@reason-machines/cli-darwin-arm64 0.2.829 → 0.2.831

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,67 +1,67 @@
1
1
  // @bun
2
- var Lb=Object.create;var{getPrototypeOf:Ub,defineProperty:xf,getOwnPropertyNames:zb}=Object;var bf=Object.prototype.hasOwnProperty;function Fb(e){return this[e]}var Mb,Vb,ja=(e,t,n)=>{var r=e!=null&&typeof e==="object";if(r){var i=t?Mb??=new WeakMap:Vb??=new WeakMap,o=i.get(e);if(o)return o}n=e!=null?Lb(Ub(e)):{};let s=t||!e||!e.__esModule||!bf.call(e,"default")?xf(n,"default",{value:e,enumerable:!0}):n;if(e&&typeof e==="object"||typeof e==="function"){for(let a of zb(e))if(!bf.call(s,a))xf(s,a,{get:Fb.bind(e,a),enumerable:!0})}if(r)i.set(e,s);return s};var le=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Ci=import.meta.require;var he=le(function(g2,_f){_f.exports={options:{usePureJavaScript:!1}}});var kf=le(function(y2,Af){var Xa={};Af.exports=Xa;var Tf={};Xa.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=Jb(e,t);else{var i=0,o=t.length,s=t.charAt(0),a=[0];for(i=0;i<e.length;++i){for(var c=0,u=e[i];c<a.length;++c)u+=a[c]<<8,a[c]=u%o,u=u/o|0;while(u>0)a.push(u%o),u=u/o|0}for(i=0;e[i]===0&&i<e.length-1;++i)r+=s;for(i=a.length-1;i>=0;--i)r+=t[a[i]]}if(n){var l=new RegExp(".{1,"+n+"}","g");r=r.match(l).join(`\r
3
- `)}return r};Xa.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=Tf[t];if(!n){n=Tf[t]=[];for(var r=0;r<t.length;++r)n[t.charCodeAt(r)]=r}e=e.replace(/\s/g,"");var i=t.length,o=t.charAt(0),s=[0];for(var r=0;r<e.length;r++){var a=n[e.charCodeAt(r)];if(a===void 0)return;for(var c=0,u=a;c<s.length;++c)u+=s[c]*i,s[c]=u&255,u>>=8;while(u>0)s.push(u&255),u>>=8}for(var l=0;e[l]===o&&l<e.length-1;++l)s.push(0);if(typeof Buffer<"u")return Buffer.from(s.reverse());return new Uint8Array(s.reverse())};function Jb(e,t){var n=0,r=t.length,i=t.charAt(0),o=[0];for(n=0;n<e.length();++n){for(var s=0,a=e.at(n);s<o.length;++s)a+=o[s]<<8,o[s]=a%r,a=a/r|0;while(a>0)o.push(a%r),a=a/r|0}var c="";for(n=0;e.at(n)===0&&n<e.length()-1;++n)c+=i;for(n=o.length-1;n>=0;--n)c+=t[o[n]];return c}});var Te=le(function(v2,Bf){var If=he(),Pf=kf(),A=Bf.exports=If.util=If.util||{};(function(){if(typeof process<"u"&&process.nextTick){if(A.nextTick=process.nextTick,typeof setImmediate==="function")A.setImmediate=setImmediate;else A.setImmediate=A.nextTick;return}if(typeof setImmediate==="function"){A.setImmediate=function(){return setImmediate.apply(void 0,arguments)},A.nextTick=function(a){return setImmediate(a)};return}if(A.setImmediate=function(a){setTimeout(a,0)},typeof window<"u"&&typeof window.postMessage==="function"){let a=function(c){if(c.source===window&&c.data===e){c.stopPropagation();var u=t.slice();t.length=0,u.forEach(function(l){l()})}};var s=a,e="forge.setImmediate",t=[];A.setImmediate=function(c){if(t.push(c),t.length===1)window.postMessage(e,"*")},window.addEventListener("message",a,!0)}if(typeof MutationObserver<"u"){var n=Date.now(),r=!0,i=document.createElement("div"),t=[];new MutationObserver(function(){var c=t.slice();t.length=0,c.forEach(function(u){u()})}).observe(i,{attributes:!0});var o=A.setImmediate;A.setImmediate=function(c){if(Date.now()-n>15)n=Date.now(),o(c);else if(t.push(c),t.length===1)i.setAttribute("a",r=!r)}}A.nextTick=A.setImmediate})();A.isNodejs=typeof process<"u"&&process.versions&&process.versions.node;A.globalScope=function(){if(A.isNodejs)return global;return typeof self>"u"?window:self}();A.isArray=Array.isArray||function(e){return Object.prototype.toString.call(e)==="[object Array]"};A.isArrayBuffer=function(e){return typeof ArrayBuffer<"u"&&e instanceof ArrayBuffer};A.isArrayBufferView=function(e){return e&&A.isArrayBuffer(e.buffer)&&e.byteLength!==void 0};function ki(e){if(!(e===8||e===16||e===24||e===32))throw Error("Only 8, 16, 24, or 32 bits supported: "+e)}A.ByteBuffer=Ja;function Ja(e){if(this.data="",this.read=0,typeof e==="string")this.data=e;else if(A.isArrayBuffer(e)||A.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 Ja||typeof e==="object"&&typeof e.data==="string"&&typeof e.read==="number")this.data=e.data,this.read=e.read;this._constructedStringLength=0}A.ByteStringBuffer=Ja;var Qb=4096;A.ByteStringBuffer.prototype._optimizeConstructedString=function(e){if(this._constructedStringLength+=e,this._constructedStringLength>Qb)this.data.substr(0,1),this._constructedStringLength=0};A.ByteStringBuffer.prototype.length=function(){return this.data.length-this.read};A.ByteStringBuffer.prototype.isEmpty=function(){return this.length()<=0};A.ByteStringBuffer.prototype.putByte=function(e){return this.putBytes(String.fromCharCode(e))};A.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};A.ByteStringBuffer.prototype.putBytes=function(e){return this.data+=e,this._optimizeConstructedString(e.length),this};A.ByteStringBuffer.prototype.putString=function(e){return this.putBytes(A.encodeUtf8(e))};A.ByteStringBuffer.prototype.putInt16=function(e){return this.putBytes(String.fromCharCode(e>>8&255)+String.fromCharCode(e&255))};A.ByteStringBuffer.prototype.putInt24=function(e){return this.putBytes(String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e&255))};A.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))};A.ByteStringBuffer.prototype.putInt16Le=function(e){return this.putBytes(String.fromCharCode(e&255)+String.fromCharCode(e>>8&255))};A.ByteStringBuffer.prototype.putInt24Le=function(e){return this.putBytes(String.fromCharCode(e&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e>>16&255))};A.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))};A.ByteStringBuffer.prototype.putInt=function(e,t){ki(t);var n="";do t-=8,n+=String.fromCharCode(e>>t&255);while(t>0);return this.putBytes(n)};A.ByteStringBuffer.prototype.putSignedInt=function(e,t){if(e<0)e+=2<<t-1;return this.putInt(e,t)};A.ByteStringBuffer.prototype.putBuffer=function(e){return this.putBytes(e.getBytes())};A.ByteStringBuffer.prototype.getByte=function(){return this.data.charCodeAt(this.read++)};A.ByteStringBuffer.prototype.getInt16=function(){var e=this.data.charCodeAt(this.read)<<8^this.data.charCodeAt(this.read+1);return this.read+=2,e};A.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};A.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};A.ByteStringBuffer.prototype.getInt16Le=function(){var e=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8;return this.read+=2,e};A.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};A.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};A.ByteStringBuffer.prototype.getInt=function(e){ki(e);var t=0;do t=(t<<8)+this.data.charCodeAt(this.read++),e-=8;while(e>0);return t};A.ByteStringBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),n=2<<e-2;if(t>=n)t-=n<<1;return t};A.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};A.ByteStringBuffer.prototype.bytes=function(e){return typeof e>"u"?this.data.slice(this.read):this.data.slice(this.read,this.read+e)};A.ByteStringBuffer.prototype.at=function(e){return this.data.charCodeAt(this.read+e)};A.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};A.ByteStringBuffer.prototype.last=function(){return this.data.charCodeAt(this.data.length-1)};A.ByteStringBuffer.prototype.copy=function(){var e=A.createBuffer(this.data);return e.read=this.read,e};A.ByteStringBuffer.prototype.compact=function(){if(this.read>0)this.data=this.data.slice(this.read),this.read=0;return this};A.ByteStringBuffer.prototype.clear=function(){return this.data="",this.read=0,this};A.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};A.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};A.ByteStringBuffer.prototype.toString=function(){return A.decodeUtf8(this.bytes())};function Yb(e,t){t=t||{},this.read=t.readOffset||0,this.growSize=t.growSize||1024;var n=A.isArrayBuffer(e),r=A.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}A.DataBuffer=Yb;A.DataBuffer.prototype.length=function(){return this.write-this.read};A.DataBuffer.prototype.isEmpty=function(){return this.length()<=0};A.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};A.DataBuffer.prototype.putByte=function(e){return this.accommodate(1),this.data.setUint8(this.write++,e),this};A.DataBuffer.prototype.fillWithByte=function(e,t){this.accommodate(t);for(var n=0;n<t;++n)this.data.setUint8(e);return this};A.DataBuffer.prototype.putBytes=function(e,t){if(A.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(A.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 A.DataBuffer||typeof e==="object"&&typeof e.read==="number"&&typeof e.write==="number"&&A.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 A.ByteStringBuffer)e=e.data,t="binary";if(t=t||"binary",typeof e==="string"){var o;if(t==="hex")return this.accommodate(Math.ceil(e.length/2)),o=new Uint8Array(this.data.buffer,this.write),this.write+=A.binary.hex.decode(e,o,this.write),this;if(t==="base64")return this.accommodate(Math.ceil(e.length/4)*3),o=new Uint8Array(this.data.buffer,this.write),this.write+=A.binary.base64.decode(e,o,this.write),this;if(t==="utf8")e=A.encodeUtf8(e),t="binary";if(t==="binary"||t==="raw")return this.accommodate(e.length),o=new Uint8Array(this.data.buffer,this.write),this.write+=A.binary.raw.decode(o),this;if(t==="utf16")return this.accommodate(e.length*2),o=new Uint16Array(this.data.buffer,this.write),this.write+=A.text.utf16.encode(o),this;throw Error("Invalid encoding: "+t)}throw Error("Invalid parameter: "+e)};A.DataBuffer.prototype.putBuffer=function(e){return this.putBytes(e),e.clear(),this};A.DataBuffer.prototype.putString=function(e){return this.putBytes(e,"utf16")};A.DataBuffer.prototype.putInt16=function(e){return this.accommodate(2),this.data.setInt16(this.write,e),this.write+=2,this};A.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};A.DataBuffer.prototype.putInt32=function(e){return this.accommodate(4),this.data.setInt32(this.write,e),this.write+=4,this};A.DataBuffer.prototype.putInt16Le=function(e){return this.accommodate(2),this.data.setInt16(this.write,e,!0),this.write+=2,this};A.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};A.DataBuffer.prototype.putInt32Le=function(e){return this.accommodate(4),this.data.setInt32(this.write,e,!0),this.write+=4,this};A.DataBuffer.prototype.putInt=function(e,t){ki(t),this.accommodate(t/8);do t-=8,this.data.setInt8(this.write++,e>>t&255);while(t>0);return this};A.DataBuffer.prototype.putSignedInt=function(e,t){if(ki(t),this.accommodate(t/8),e<0)e+=2<<t-1;return this.putInt(e,t)};A.DataBuffer.prototype.getByte=function(){return this.data.getInt8(this.read++)};A.DataBuffer.prototype.getInt16=function(){var e=this.data.getInt16(this.read);return this.read+=2,e};A.DataBuffer.prototype.getInt24=function(){var e=this.data.getInt16(this.read)<<8^this.data.getInt8(this.read+2);return this.read+=3,e};A.DataBuffer.prototype.getInt32=function(){var e=this.data.getInt32(this.read);return this.read+=4,e};A.DataBuffer.prototype.getInt16Le=function(){var e=this.data.getInt16(this.read,!0);return this.read+=2,e};A.DataBuffer.prototype.getInt24Le=function(){var e=this.data.getInt8(this.read)^this.data.getInt16(this.read+1,!0)<<8;return this.read+=3,e};A.DataBuffer.prototype.getInt32Le=function(){var e=this.data.getInt32(this.read,!0);return this.read+=4,e};A.DataBuffer.prototype.getInt=function(e){ki(e);var t=0;do t=(t<<8)+this.data.getInt8(this.read++),e-=8;while(e>0);return t};A.DataBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),n=2<<e-2;if(t>=n)t-=n<<1;return t};A.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};A.DataBuffer.prototype.bytes=function(e){return typeof e>"u"?this.data.slice(this.read):this.data.slice(this.read,this.read+e)};A.DataBuffer.prototype.at=function(e){return this.data.getUint8(this.read+e)};A.DataBuffer.prototype.setAt=function(e,t){return this.data.setUint8(e,t),this};A.DataBuffer.prototype.last=function(){return this.data.getUint8(this.write-1)};A.DataBuffer.prototype.copy=function(){return new A.DataBuffer(this)};A.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};A.DataBuffer.prototype.clear=function(){return this.data=new DataView(new ArrayBuffer(0)),this.read=this.write=0,this};A.DataBuffer.prototype.truncate=function(e){return this.write=Math.max(0,this.length()-e),this.read=Math.min(this.read,this.write),this};A.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};A.DataBuffer.prototype.toString=function(e){var t=new Uint8Array(this.data,this.read,this.length());if(e=e||"utf8",e==="binary"||e==="raw")return A.binary.raw.encode(t);if(e==="hex")return A.binary.hex.encode(t);if(e==="base64")return A.binary.base64.encode(t);if(e==="utf8")return A.text.utf8.decode(t);if(e==="utf16")return A.text.utf16.decode(t);throw Error("Invalid encoding: "+e)};A.createBuffer=function(e,t){if(t=t||"raw",e!==void 0&&t==="utf8")e=A.encodeUtf8(e);return new A.ByteBuffer(e)};A.fillString=function(e,t){var n="";while(t>0){if(t&1)n+=e;if(t>>>=1,t>0)e+=e}return n};A.xorBytes=function(e,t,n){var r="",i="",o="",s=0,a=0;for(;n>0;--n,++s){if(i=e.charCodeAt(s)^t.charCodeAt(s),a>=10)r+=o,o="",a=0;o+=String.fromCharCode(i),++a}return r+=o,r};A.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};A.bytesToHex=function(e){return A.createBuffer(e).toHex()};A.int32ToBytes=function(e){return String.fromCharCode(e>>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e&255)};var Fr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",Mr=[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],Rf="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";A.encode64=function(e,t){var n="",r="",i,o,s,a=0;while(a<e.length){if(i=e.charCodeAt(a++)&255,o=e.charCodeAt(a++),s=e.charCodeAt(a++),n+=Fr.charAt(i>>2),n+=Fr.charAt((i&3)<<4|(o&255)>>4),isNaN(o))n+="==";else n+=Fr.charAt((o&15)<<2|(s&255)>>6),n+=isNaN(s)?"=":Fr.charAt(s&63);if(t&&n.length>t)r+=n.substr(0,t)+`\r
4
- `,n=n.substr(t)}return r+=n,r};A.decode64=function(e){e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");var t="",n,r,i,o,s=0;while(s<e.length)if(n=Mr[e.charCodeAt(s++)-43],r=Mr[e.charCodeAt(s++)-43],i=Mr[e.charCodeAt(s++)-43],o=Mr[e.charCodeAt(s++)-43],t+=String.fromCharCode(n<<2|r>>4),i!==64){if(t+=String.fromCharCode((r&15)<<4|i>>2),o!==64)t+=String.fromCharCode((i&3)<<6|o)}return t};A.encodeUtf8=function(e){return unescape(encodeURIComponent(e))};A.decodeUtf8=function(e){return decodeURIComponent(escape(e))};A.binary={raw:{},hex:{},base64:{},base58:{},baseN:{encode:Pf.encode,decode:Pf.decode}};A.binary.raw.encode=function(e){return String.fromCharCode.apply(null,e)};A.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 o=0;o<e.length;++o)r[i++]=e.charCodeAt(o);return t?i-n:r};A.binary.hex.encode=A.bytesToHex;A.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,o=n;if(e.length&1)i=1,r[o++]=parseInt(e[0],16);for(;i<e.length;i+=2)r[o++]=parseInt(e.substr(i,2),16);return t?o-n:r};A.binary.base64.encode=function(e,t){var n="",r="",i,o,s,a=0;while(a<e.byteLength){if(i=e[a++],o=e[a++],s=e[a++],n+=Fr.charAt(i>>2),n+=Fr.charAt((i&3)<<4|o>>4),isNaN(o))n+="==";else n+=Fr.charAt((o&15)<<2|s>>6),n+=isNaN(s)?"=":Fr.charAt(s&63);if(t&&n.length>t)r+=n.substr(0,t)+`\r
5
- `,n=n.substr(t)}return r+=n,r};A.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,o,s,a,c=0,u=n;while(c<e.length)if(i=Mr[e.charCodeAt(c++)-43],o=Mr[e.charCodeAt(c++)-43],s=Mr[e.charCodeAt(c++)-43],a=Mr[e.charCodeAt(c++)-43],r[u++]=i<<2|o>>4,s!==64){if(r[u++]=(o&15)<<4|s>>2,a!==64)r[u++]=(s&3)<<6|a}return t?u-n:r.subarray(0,u)};A.binary.base58.encode=function(e,t){return A.binary.baseN.encode(e,Rf,t)};A.binary.base58.decode=function(e,t){return A.binary.baseN.decode(e,Rf,t)};A.text={utf8:{},utf16:{}};A.text.utf8.encode=function(e,t,n){e=A.encodeUtf8(e);var r=t;if(!r)r=new Uint8Array(e.length);n=n||0;var i=n;for(var o=0;o<e.length;++o)r[i++]=e.charCodeAt(o);return t?i-n:r};A.text.utf8.decode=function(e){return A.decodeUtf8(String.fromCharCode.apply(null,e))};A.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 o=n,s=n;for(var a=0;a<e.length;++a)i[s++]=e.charCodeAt(a),o+=2;return t?o-n:r};A.text.utf16.decode=function(e){return String.fromCharCode.apply(null,new Uint16Array(e.buffer))};A.deflate=function(e,t,n){if(t=A.decode64(e.deflate(A.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};A.inflate=function(e,t,n){var r=e.inflate(A.encode64(t)).rval;return r===null?null:A.decode64(r)};var Qa=function(e,t,n){if(!e)throw Error("WebStorage not available.");var r;if(n===null)r=e.removeItem(t);else n=A.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}},Ya=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(A.decode64(n));return n},eS=function(e,t,n,r){var i=Ya(e,t);if(i===null)i={};i[n]=r,Qa(e,t,i)},tS=function(e,t,n){var r=Ya(e,t);if(r!==null)r=n in r?r[n]:null;return r},rS=function(e,t,n){var r=Ya(e,t);if(r!==null&&n in r){delete r[n];var i=!0;for(var o in r){i=!1;break}if(i)r=null;Qa(e,t,r)}},nS=function(e,t){Qa(e,t,null)},Uo=function(e,t,n){var r=null;if(typeof n>"u")n=["web","flash"];var i,o=!1,s=null;for(var a in n){i=n[a];try{if(i==="flash"||i==="both"){if(t[0]===null)throw Error("Flash local storage not available.");r=e.apply(this,t),o=i==="flash"}if(i==="web"||i==="both")t[0]=localStorage,r=e.apply(this,t),o=!0}catch(c){s=c}if(o)break}if(!o)throw s;return r};A.setItem=function(e,t,n,r,i){Uo(eS,arguments,i)};A.getItem=function(e,t,n,r){return Uo(tS,arguments,r)};A.removeItem=function(e,t,n,r){Uo(rS,arguments,r)};A.clearItems=function(e,t,n){Uo(nS,arguments,n)};A.isEmpty=function(e){for(var t in e)if(e.hasOwnProperty(t))return!1;return!0};A.format=function(e){var t=/%./g,n,r,i=0,o=[],s=0;while(n=t.exec(e)){if(r=e.substring(s,t.lastIndex-2),r.length>0)o.push(r);s=t.lastIndex;var a=n[0][1];switch(a){case"s":case"o":if(i<arguments.length)o.push(arguments[i+++1]);else o.push("<?>");break;case"%":o.push("%");break;default:o.push("<%"+a+"?>")}}return o.push(e.substring(s)),o.join("")};A.formatNumber=function(e,t,n,r){var i=e,o=isNaN(t=Math.abs(t))?2:t,s=n===void 0?",":n,a=r===void 0?".":r,c=i<0?"-":"",u=parseInt(i=Math.abs(+i||0).toFixed(o),10)+"",l=u.length>3?u.length%3:0;return c+(l?u.substr(0,l)+a:"")+u.substr(l).replace(/(\d{3})(?=\d)/g,"$1"+a)+(o?s+Math.abs(i-u).toFixed(o).slice(2):"")};A.formatSize=function(e){if(e>=1073741824)e=A.formatNumber(e/1073741824,2,".","")+" GiB";else if(e>=1048576)e=A.formatNumber(e/1048576,2,".","")+" MiB";else if(e>=1024)e=A.formatNumber(e/1024,0)+" KiB";else e=A.formatNumber(e,0)+" bytes";return e};A.bytesFromIP=function(e){if(e.indexOf(".")!==-1)return A.bytesFromIPv4(e);if(e.indexOf(":")!==-1)return A.bytesFromIPv6(e);return null};A.bytesFromIPv4=function(e){if(e=e.split("."),e.length!==4)return null;var t=A.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()};A.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=A.createBuffer();for(var i=0;i<8;++i){if(!e[i]||e[i].length===0){r.fillWithByte(0,n),n=0;continue}var o=A.hexToBytes(e[i]);if(o.length<2)r.putByte(0);r.putBytes(o)}return r.getBytes()};A.bytesToIP=function(e){if(e.length===4)return A.bytesToIPv4(e);if(e.length===16)return A.bytesToIPv6(e);return null};A.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(".")};A.bytesToIPv6=function(e){if(e.length!==16)return null;var t=[],n=[],r=0;for(var i=0;i<e.length;i+=2){var o=A.bytesToHex(e[i]+e[i+1]);while(o[0]==="0"&&o!=="0")o=o.substr(1);if(o==="0"){var s=n[n.length-1],a=t.length;if(!s||a!==s.end+1)n.push({start:a,end:a});else if(s.end=a,s.end-s.start>n[r].end-n[r].start)r=n.length-1}t.push(o)}if(n.length>0){var c=n[r];if(c.end-c.start>0){if(t.splice(c.start,c.end-c.start+1,""),c.start===0)t.unshift("");if(c.end===7)t.push("")}}return t.join(":")};A.estimateCores=function(e,t){if(typeof e==="function")t=e,e={};if(e=e||{},"cores"in A&&!e.update)return t(null,A.cores);if(typeof navigator<"u"&&"hardwareConcurrency"in navigator&&navigator.hardwareConcurrency>0)return A.cores=navigator.hardwareConcurrency,t(null,A.cores);if(typeof Worker>"u")return A.cores=1,t(null,A.cores);if(typeof Blob>"u")return A.cores=2,t(null,A.cores);var n=URL.createObjectURL(new Blob(["(",function(){self.addEventListener("message",function(s){var a=Date.now(),c=a+4;while(Date.now()<c);self.postMessage({st:a,et:c})})}.toString(),")()"],{type:"application/javascript"}));r([],5,16);function r(s,a,c){if(a===0){var u=Math.floor(s.reduce(function(l,f){return l+f},0)/s.length);return A.cores=Math.max(1,u),URL.revokeObjectURL(n),t(null,A.cores)}i(c,function(l,f){s.push(o(c,f)),r(s,a-1,c)})}function i(s,a){var c=[],u=[];for(var l=0;l<s;++l){var f=new Worker(n);f.addEventListener("message",function(p){if(u.push(p.data),u.length===s){for(var h=0;h<s;++h)c[h].terminate();a(null,u)}}),c.push(f)}for(var l=0;l<s;++l)c[l].postMessage(l)}function o(s,a){var c=[];for(var u=0;u<s;++u){var l=a[u],f=c[u]=[];for(var p=0;p<s;++p){if(u===p)continue;var h=a[p];if(l.st>h.st&&l.st<h.et||h.st>l.st&&h.st<l.et)f.push(p)}}return c.reduce(function(d,g){return Math.max(d,g.length)},0)}}});var zo=le(function(x2,Nf){var ut=he();Te();Nf.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 ec=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)};ec.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)};ec.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()};ec.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 rc=le(function(b2,Df){var lt=he();Te();lt.cipher=lt.cipher||{};var ve=Df.exports=lt.cipher.modes=lt.cipher.modes||{};ve.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)};ve.ecb.prototype.start=function(e){};ve.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])};ve.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])};ve.ecb.prototype.pad=function(e,t){var n=e.length()===this.blockSize?this.blockSize:this.blockSize-e.length();return e.fillWithByte(n,n),!0};ve.ecb.prototype.unpad=function(e,t){if(t.overflow>0)return!1;var n=e.length();if(n===0)return!0;var r=e.at(n-1);if(r===0||r>this.blockSize||r>n)return!1;for(var i=2;i<=r;++i)if(e.at(n-i)!==r)return!1;return e.truncate(r),!0};ve.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)};ve.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=Fo(e.iv,this.blockSize),this._prev=this._iv.slice(0)};ve.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};ve.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)};ve.cbc.prototype.pad=function(e,t){var n=e.length()===this.blockSize?this.blockSize:this.blockSize-e.length();return e.fillWithByte(n,n),!0};ve.cbc.prototype.unpad=function(e,t){if(t.overflow>0)return!1;var n=e.length();if(n===0)return!0;var r=e.at(n-1);if(r===0||r>this.blockSize||r>n)return!1;for(var i=2;i<=r;++i)if(e.at(n-i)!==r)return!1;return e.truncate(r),!0};ve.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=lt.util.createBuffer(),this._partialBytes=0};ve.cfb.prototype.start=function(e){if(!("iv"in e))throw Error("Invalid IV parameter.");this._iv=Fo(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0};ve.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 o=(this.blockSize-r)%this.blockSize;if(o>0)o=this.blockSize-o;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(o>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(o>0&&!n)return t.putBytes(this._partialOutput.getBytes(o-this._partialBytes)),this._partialBytes=o,!0;t.putBytes(this._partialOutput.getBytes(r-this._partialBytes)),this._partialBytes=0};ve.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 o=(this.blockSize-r)%this.blockSize;if(o>0)o=this.blockSize-o;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(o>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(o>0&&!n)return t.putBytes(this._partialOutput.getBytes(o-this._partialBytes)),this._partialBytes=o,!0;t.putBytes(this._partialOutput.getBytes(r-this._partialBytes)),this._partialBytes=0};ve.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=lt.util.createBuffer(),this._partialBytes=0};ve.ofb.prototype.start=function(e){if(!("iv"in e))throw Error("Invalid IV parameter.");this._iv=Fo(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0};ve.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 o=(this.blockSize-r)%this.blockSize;if(o>0)o=this.blockSize-o;this._partialOutput.clear();for(var i=0;i<this._ints;++i)this._partialOutput.putInt32(e.getInt32()^this._outBlock[i]);if(o>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(o>0&&!n)return t.putBytes(this._partialOutput.getBytes(o-this._partialBytes)),this._partialBytes=o,!0;t.putBytes(this._partialOutput.getBytes(r-this._partialBytes)),this._partialBytes=0};ve.ofb.prototype.decrypt=ve.ofb.prototype.encrypt;ve.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=lt.util.createBuffer(),this._partialBytes=0};ve.ctr.prototype.start=function(e){if(!("iv"in e))throw Error("Invalid IV parameter.");this._iv=Fo(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0};ve.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 o=(this.blockSize-r)%this.blockSize;if(o>0)o=this.blockSize-o;this._partialOutput.clear();for(var i=0;i<this._ints;++i)this._partialOutput.putInt32(e.getInt32()^this._outBlock[i]);if(o>0)e.read-=this.blockSize;if(this._partialBytes>0)this._partialOutput.getBytes(this._partialBytes);if(o>0&&!n)return t.putBytes(this._partialOutput.getBytes(o-this._partialBytes)),this._partialBytes=o,!0;t.putBytes(this._partialOutput.getBytes(r-this._partialBytes)),this._partialBytes=0}Mo(this._inBlock)};ve.ctr.prototype.decrypt=ve.ctr.prototype.encrypt;ve.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=lt.util.createBuffer(),this._partialBytes=0,this._R=3774873600};ve.gcm.prototype.start=function(e){if(!("iv"in e))throw Error("Invalid IV parameter.");var t=lt.util.createBuffer(e.iv);this._cipherLength=0;var n;if("additionalData"in e)n=lt.util.createBuffer(e.additionalData);else n=lt.util.createBuffer();if(e.tagLength!==void 0&&e.tagLength!==null)this._tagLength=Number(e.tagLength);else this._tagLength=128;if([128,120,112,104,96,64,32].indexOf(this._tagLength)===-1)throw Error("Invalid tag length.");if(this._tag=null,e.decrypt){if(this._tag=lt.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(tc(r*8)))}this._inBlock=this._j0.slice(0),Mo(this._inBlock),this._partialBytes=0,n=lt.util.createBuffer(n),this._aDataLength=tc(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()])};ve.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 o=(this.blockSize-r)%this.blockSize;if(o>0)o=this.blockSize-o;this._partialOutput.clear();for(var i=0;i<this._ints;++i)this._partialOutput.putInt32(e.getInt32()^this._outBlock[i]);if(o<=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(o>0&&!n)return e.read-=this.blockSize,t.putBytes(this._partialOutput.getBytes(o-this._partialBytes)),this._partialBytes=o,!0;t.putBytes(this._partialOutput.getBytes(r-this._partialBytes)),this._partialBytes=0}this._s=this.ghash(this._hashSubkey,this._s,this._outBlock),Mo(this._inBlock)};ve.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),Mo(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};ve.gcm.prototype.afterFinish=function(e,t){var n=!0;if(t.decrypt&&t.overflow)e.truncate(this.blockSize-t.overflow);this.tag=lt.util.createBuffer();var r=this._aDataLength.concat(tc(this._cipherLength*8));this._s=this.ghash(this._hashSubkey,this._s,r);var i=[];this.cipher.encrypt(this._j0,i);for(var o=0;o<this._ints;++o)this.tag.putInt32(this._s[o]^i[o]);if(this.tag.truncate(this.tag.length()%(this._tagLength/8)),t.decrypt&&this.tag.bytes()!==this._tag)n=!1;return n};ve.gcm.prototype.multiply=function(e,t){var n=[0,0,0,0],r=t.slice(0);for(var i=0;i<128;++i){var o=e[i/32|0]&1<<31-i%32;if(o)n[0]^=r[0],n[1]^=r[1],n[2]^=r[2],n[3]^=r[3];this.pow(r,r)}return n};ve.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};ve.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,o=this._m[n][i];t[0]^=o[0],t[1]^=o[1],t[2]^=o[2],t[3]^=o[3]}return t};ve.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)};ve.gcm.prototype.generateHashTable=function(e,t){var n=8/t,r=4*n,i=16*n,o=Array(i);for(var s=0;s<i;++s){var a=[0,0,0,0],c=s/r|0,u=(r-1-s%r)*t;a[c]=1<<t-1<<u,o[s]=this.generateSubHashTable(this.multiply(a,e),t)}return o};ve.gcm.prototype.generateSubHashTable=function(e,t){var n=1<<t,r=n>>>1,i=Array(n);i[r]=e.slice(0);var o=r>>>1;while(o>0)this.pow(i[2*o],i[o]=[]),o>>=1;o=2;while(o<r){for(var s=1;s<o;++s){var a=i[o],c=i[s];i[o+s]=[a[0]^c[0],a[1]^c[1],a[2]^c[2],a[3]^c[3]]}o*=2}i[0]=[0,0,0,0];for(o=r+1;o<n;++o){var u=i[o^r];i[o]=[e[0]^u[0],e[1]^u[1],e[2]^u[2],e[3]^u[3]]}return i};function Fo(e,t){if(typeof e==="string")e=lt.util.createBuffer(e);if(lt.util.isArray(e)&&e.length>4){var n=e;e=lt.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(!lt.util.isArray(e)){var i=[],o=t/4;for(var r=0;r<o;++r)i.push(e.getInt32());e=i}return e}function Mo(e){e[e.length-1]=e[e.length-1]+1&4294967295}function tc(e){return[e/4294967296|0,e&4294967295]}});var Vr=le(function(S2,Uf){var Le=he();zo();rc();Te();Uf.exports=Le.aes=Le.aes||{};Le.aes.startEncrypting=function(e,t,n,r){var i=Vo({key:e,output:n,decrypt:!1,mode:r});return i.start(t),i};Le.aes.createEncryptionCipher=function(e,t){return Vo({key:e,output:null,decrypt:!1,mode:t})};Le.aes.startDecrypting=function(e,t,n,r){var i=Vo({key:e,output:n,decrypt:!0,mode:r});return i.start(t),i};Le.aes.createDecryptionCipher=function(e,t){return Vo({key:e,output:null,decrypt:!0,mode:t})};Le.aes.Algorithm=function(e,t){if(!oc)Of();var n=this;n.name=e,n.mode=new t({blockSize:16,cipher:{encrypt:function(r,i){return ic(n._w,r,i,!1)},decrypt:function(r,i){return ic(n._w,r,i,!0)}}}),n._init=!1};Le.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=Le.util.createBuffer(t);else if(Le.util.isArray(t)&&(t.length===16||t.length===24||t.length===32)){n=t,t=Le.util.createBuffer();for(var r=0;r<n.length;++r)t.putByte(n[r])}if(!Le.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(!Le.util.isArray(t)||!(t.length===4||t.length===6||t.length===8))throw Error("Invalid key parameter.");var o=this.mode.name,s=["CFB","OFB","CTR","GCM"].indexOf(o)!==-1;this._w=Lf(t,e.decrypt&&!s),this._init=!0};Le.aes._expandKey=function(e,t){if(!oc)Of();return Lf(e,t)};Le.aes._updateBlock=ic;$n("AES-ECB",Le.cipher.modes.ecb);$n("AES-CBC",Le.cipher.modes.cbc);$n("AES-CFB",Le.cipher.modes.cfb);$n("AES-OFB",Le.cipher.modes.ofb);$n("AES-CTR",Le.cipher.modes.ctr);$n("AES-GCM",Le.cipher.modes.gcm);function $n(e,t){var n=function(){return new Le.aes.Algorithm(e,t)};Le.cipher.registerAlgorithm(e,n)}var oc=!1,Dn=4,bt,nc,$f,ln,Jt;function Of(){oc=!0,$f=[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;bt=Array(256),nc=Array(256),ln=[,,,,],Jt=[,,,,];for(var t=0;t<4;++t)ln[t]=Array(256),Jt[t]=Array(256);var n=0,r=0,i,o,s,a,c,u,l;for(var t=0;t<256;++t){a=r^r<<1^r<<2^r<<3^r<<4,a=a>>8^a&255^99,bt[n]=a,nc[a]=n,c=e[a],i=e[n],o=e[i],s=e[o],u=c<<24^a<<16^a<<8^(a^c),l=(i^o^s)<<24^(n^s)<<16^(n^o^s)<<8^(n^i^s);for(var f=0;f<4;++f)ln[f][n]=u,Jt[f][a]=l,u=u<<24|u>>>8,l=l<<24|l>>>8;if(n===0)n=r=1;else n=i^e[e[e[i^s]]],r^=e[e[r]]}}function Lf(e,t){var n=e.slice(0),r,i=1,o=n.length,s=o+6+1,a=Dn*s;for(var c=o;c<a;++c){if(r=n[c-1],c%o===0)r=bt[r>>>16&255]<<24^bt[r>>>8&255]<<16^bt[r&255]<<8^bt[r>>>24]^$f[i]<<24,i++;else if(o>6&&c%o===4)r=bt[r>>>24]<<24^bt[r>>>16&255]<<16^bt[r>>>8&255]<<8^bt[r&255];n[c]=n[c-o]^r}if(t){var u,l=Jt[0],f=Jt[1],p=Jt[2],h=Jt[3],d=n.slice(0);a=n.length;for(var c=0,g=a-Dn;c<a;c+=Dn,g-=Dn)if(c===0||c===a-Dn)d[c]=n[g],d[c+1]=n[g+3],d[c+2]=n[g+2],d[c+3]=n[g+1];else for(var x=0;x<Dn;++x)u=n[g+x],d[c+(3&-x)]=l[bt[u>>>24]]^f[bt[u>>>16&255]]^p[bt[u>>>8&255]]^h[bt[u&255]];n=d}return n}function ic(e,t,n,r){var i=e.length/4-1,o,s,a,c,u;if(r)o=Jt[0],s=Jt[1],a=Jt[2],c=Jt[3],u=nc;else o=ln[0],s=ln[1],a=ln[2],c=ln[3],u=bt;var l,f,p,h,d,g,x;l=t[0]^e[0],f=t[r?3:1]^e[1],p=t[2]^e[2],h=t[r?1:3]^e[3];var b=3;for(var S=1;S<i;++S)d=o[l>>>24]^s[f>>>16&255]^a[p>>>8&255]^c[h&255]^e[++b],g=o[f>>>24]^s[p>>>16&255]^a[h>>>8&255]^c[l&255]^e[++b],x=o[p>>>24]^s[h>>>16&255]^a[l>>>8&255]^c[f&255]^e[++b],h=o[h>>>24]^s[l>>>16&255]^a[f>>>8&255]^c[p&255]^e[++b],l=d,f=g,p=x;n[0]=u[l>>>24]<<24^u[f>>>16&255]<<16^u[p>>>8&255]<<8^u[h&255]^e[++b],n[r?3:1]=u[f>>>24]<<24^u[p>>>16&255]<<16^u[h>>>8&255]<<8^u[l&255]^e[++b],n[2]=u[p>>>24]<<24^u[h>>>16&255]<<16^u[l>>>8&255]<<8^u[f&255]^e[++b],n[r?1:3]=u[h>>>24]<<24^u[l>>>16&255]<<16^u[f>>>8&255]<<8^u[p&255]^e[++b]}function Vo(e){e=e||{};var t=(e.mode||"CBC").toUpperCase(),n="AES-"+t,r;if(e.decrypt)r=Le.cipher.createDecipher(n,e.key);else r=Le.cipher.createCipher(n,e.key);var i=r.start;return r.start=function(o,s){var a=null;if(s instanceof Le.util.ByteBuffer)a=s,s={};s=s||{},s.output=a,s.iv=o,i.call(r,s)},r}});var Wr=le(function(C2,zf){var Ii=he();Ii.pki=Ii.pki||{};var sc=zf.exports=Ii.pki.oids=Ii.oids=Ii.oids||{};function z(e,t){sc[e]=t,sc[t]=e}function Re(e,t){sc[e]=t}z("1.2.840.113549.1.1.1","rsaEncryption");z("1.2.840.113549.1.1.4","md5WithRSAEncryption");z("1.2.840.113549.1.1.5","sha1WithRSAEncryption");z("1.2.840.113549.1.1.7","RSAES-OAEP");z("1.2.840.113549.1.1.8","mgf1");z("1.2.840.113549.1.1.9","pSpecified");z("1.2.840.113549.1.1.10","RSASSA-PSS");z("1.2.840.113549.1.1.11","sha256WithRSAEncryption");z("1.2.840.113549.1.1.12","sha384WithRSAEncryption");z("1.2.840.113549.1.1.13","sha512WithRSAEncryption");z("1.3.101.112","EdDSA25519");z("1.2.840.10040.4.3","dsa-with-sha1");z("1.3.14.3.2.7","desCBC");z("1.3.14.3.2.26","sha1");z("1.3.14.3.2.29","sha1WithRSASignature");z("2.16.840.1.101.3.4.2.1","sha256");z("2.16.840.1.101.3.4.2.2","sha384");z("2.16.840.1.101.3.4.2.3","sha512");z("2.16.840.1.101.3.4.2.4","sha224");z("2.16.840.1.101.3.4.2.5","sha512-224");z("2.16.840.1.101.3.4.2.6","sha512-256");z("1.2.840.113549.2.2","md2");z("1.2.840.113549.2.5","md5");z("1.2.840.113549.1.7.1","data");z("1.2.840.113549.1.7.2","signedData");z("1.2.840.113549.1.7.3","envelopedData");z("1.2.840.113549.1.7.4","signedAndEnvelopedData");z("1.2.840.113549.1.7.5","digestedData");z("1.2.840.113549.1.7.6","encryptedData");z("1.2.840.113549.1.9.1","emailAddress");z("1.2.840.113549.1.9.2","unstructuredName");z("1.2.840.113549.1.9.3","contentType");z("1.2.840.113549.1.9.4","messageDigest");z("1.2.840.113549.1.9.5","signingTime");z("1.2.840.113549.1.9.6","counterSignature");z("1.2.840.113549.1.9.7","challengePassword");z("1.2.840.113549.1.9.8","unstructuredAddress");z("1.2.840.113549.1.9.14","extensionRequest");z("1.2.840.113549.1.9.20","friendlyName");z("1.2.840.113549.1.9.21","localKeyId");z("1.2.840.113549.1.9.22.1","x509Certificate");z("1.2.840.113549.1.12.10.1.1","keyBag");z("1.2.840.113549.1.12.10.1.2","pkcs8ShroudedKeyBag");z("1.2.840.113549.1.12.10.1.3","certBag");z("1.2.840.113549.1.12.10.1.4","crlBag");z("1.2.840.113549.1.12.10.1.5","secretBag");z("1.2.840.113549.1.12.10.1.6","safeContentsBag");z("1.2.840.113549.1.5.13","pkcs5PBES2");z("1.2.840.113549.1.5.12","pkcs5PBKDF2");z("1.2.840.113549.1.12.1.1","pbeWithSHAAnd128BitRC4");z("1.2.840.113549.1.12.1.2","pbeWithSHAAnd40BitRC4");z("1.2.840.113549.1.12.1.3","pbeWithSHAAnd3-KeyTripleDES-CBC");z("1.2.840.113549.1.12.1.4","pbeWithSHAAnd2-KeyTripleDES-CBC");z("1.2.840.113549.1.12.1.5","pbeWithSHAAnd128BitRC2-CBC");z("1.2.840.113549.1.12.1.6","pbewithSHAAnd40BitRC2-CBC");z("1.2.840.113549.2.7","hmacWithSHA1");z("1.2.840.113549.2.8","hmacWithSHA224");z("1.2.840.113549.2.9","hmacWithSHA256");z("1.2.840.113549.2.10","hmacWithSHA384");z("1.2.840.113549.2.11","hmacWithSHA512");z("1.2.840.113549.3.7","des-EDE3-CBC");z("2.16.840.1.101.3.4.1.2","aes128-CBC");z("2.16.840.1.101.3.4.1.22","aes192-CBC");z("2.16.840.1.101.3.4.1.42","aes256-CBC");z("2.5.4.3","commonName");z("2.5.4.4","surname");z("2.5.4.5","serialNumber");z("2.5.4.6","countryName");z("2.5.4.7","localityName");z("2.5.4.8","stateOrProvinceName");z("2.5.4.9","streetAddress");z("2.5.4.10","organizationName");z("2.5.4.11","organizationalUnitName");z("2.5.4.12","title");z("2.5.4.13","description");z("2.5.4.15","businessCategory");z("2.5.4.17","postalCode");z("2.5.4.42","givenName");z("2.5.4.65","pseudonym");z("1.3.6.1.4.1.311.60.2.1.2","jurisdictionOfIncorporationStateOrProvinceName");z("1.3.6.1.4.1.311.60.2.1.3","jurisdictionOfIncorporationCountryName");z("2.16.840.1.113730.1.1","nsCertType");z("2.16.840.1.113730.1.13","nsComment");Re("2.5.29.1","authorityKeyIdentifier");Re("2.5.29.2","keyAttributes");Re("2.5.29.3","certificatePolicies");Re("2.5.29.4","keyUsageRestriction");Re("2.5.29.5","policyMapping");Re("2.5.29.6","subtreesConstraint");Re("2.5.29.7","subjectAltName");Re("2.5.29.8","issuerAltName");Re("2.5.29.9","subjectDirectoryAttributes");Re("2.5.29.10","basicConstraints");Re("2.5.29.11","nameConstraints");Re("2.5.29.12","policyConstraints");Re("2.5.29.13","basicConstraints");z("2.5.29.14","subjectKeyIdentifier");z("2.5.29.15","keyUsage");Re("2.5.29.16","privateKeyUsagePeriod");z("2.5.29.17","subjectAltName");z("2.5.29.18","issuerAltName");z("2.5.29.19","basicConstraints");Re("2.5.29.20","cRLNumber");Re("2.5.29.21","cRLReason");Re("2.5.29.22","expirationDate");Re("2.5.29.23","instructionCode");Re("2.5.29.24","invalidityDate");Re("2.5.29.25","cRLDistributionPoints");Re("2.5.29.26","issuingDistributionPoint");Re("2.5.29.27","deltaCRLIndicator");Re("2.5.29.28","issuingDistributionPoint");Re("2.5.29.29","certificateIssuer");Re("2.5.29.30","nameConstraints");z("2.5.29.31","cRLDistributionPoints");z("2.5.29.32","certificatePolicies");Re("2.5.29.33","policyMappings");Re("2.5.29.34","policyConstraints");z("2.5.29.35","authorityKeyIdentifier");Re("2.5.29.36","policyConstraints");z("2.5.29.37","extKeyUsage");Re("2.5.29.46","freshestCRL");Re("2.5.29.54","inhibitAnyPolicy");z("1.3.6.1.4.1.11129.2.4.2","timestampList");z("1.3.6.1.5.5.7.1.1","authorityInfoAccess");z("1.3.6.1.5.5.7.3.1","serverAuth");z("1.3.6.1.5.5.7.3.2","clientAuth");z("1.3.6.1.5.5.7.3.3","codeSigning");z("1.3.6.1.5.5.7.3.4","emailProtection");z("1.3.6.1.5.5.7.3.8","timeStamping")});var Qt=le(function(w2,Mf){var ze=he();Te();Wr();var j=Mf.exports=ze.asn1=ze.asn1||{};j.Class={UNIVERSAL:0,APPLICATION:64,CONTEXT_SPECIFIC:128,PRIVATE:192};j.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};j.maxDepth=256;j.create=function(e,t,n,r,i){if(ze.util.isArray(r)){var o=[];for(var s=0;s<r.length;++s)if(r[s]!==void 0)o.push(r[s]);r=o}var a={tagClass:e,type:t,constructed:n,composed:n||ze.util.isArray(r),value:r};if(i&&"bitStringContents"in i)a.bitStringContents=i.bitStringContents,a.original=j.copy(a);return a};j.copy=function(e,t){var n;if(ze.util.isArray(e)){n=[];for(var r=0;r<e.length;++r)n.push(j.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:j.copy(e.value,t)},t&&!t.excludeBitStringContents)n.bitStringContents=e.bitStringContents;return n};j.equals=function(e,t,n){if(ze.util.isArray(e)){if(!ze.util.isArray(t))return!1;if(e.length!==t.length)return!1;for(var r=0;r<e.length;++r)if(!j.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&&j.equals(e.value,t.value);if(n&&n.includeBitStringContents)i=i&&e.bitStringContents===t.bitStringContents;return i};j.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 Pi(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 iS=function(e,t){var n=e.getByte();if(t--,n===128)return;var r,i=n&128;if(!i)r=n;else{var o=n&127;Pi(e,t,o),r=e.getInt(o<<3)}if(r<0)throw Error("Negative length: "+r);return r};j.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=j.maxDepth;if(typeof e==="string")e=ze.util.createBuffer(e);var n=e.length(),r=Wo(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 Wo(e,t,n,r){if(n>=r.maxDepth)throw Error("ASN.1 parsing error: Max depth exceeded.");var i;Pi(e,t,2);var o=e.getByte();t--;var s=o&192,a=o&31;i=e.length();var c=iS(e,t);if(t-=i-e.length(),c!==void 0&&c>t){if(r.strict){var u=Error("Too few bytes to read ASN.1 value.");throw u.available=e.length(),u.remaining=t,u.requested=c,u}c=t}var l,f,p=(o&32)===32;if(p)if(l=[],c===void 0)for(;;){if(Pi(e,t,2),e.bytes(2)===String.fromCharCode(0,0)){e.getBytes(2),t-=2;break}i=e.length(),l.push(Wo(e,t,n+1,r)),t-=i-e.length()}else while(c>0)i=e.length(),l.push(Wo(e,c,n+1,r)),t-=i-e.length(),c-=i-e.length();if(l===void 0&&s===j.Class.UNIVERSAL&&a===j.Type.BITSTRING)f=e.bytes(c);if(l===void 0&&r.decodeBitStrings&&s===j.Class.UNIVERSAL&&a===j.Type.BITSTRING&&c>1){var h=e.read,d=t,g=0;if(a===j.Type.BITSTRING)Pi(e,t,1),g=e.getByte(),t--;if(g===0)try{i=e.length();var x={strict:!0,decodeBitStrings:!1,maxDepth:r.maxDepth},b=Wo(e,t,n+1,x),S=i-e.length();if(t-=S,a==j.Type.BITSTRING)S++;var C=b.tagClass;if(S===c&&(C===j.Class.UNIVERSAL||C===j.Class.CONTEXT_SPECIFIC))l=[b]}catch(I){}if(l===void 0)e.read=h,t=d}if(l===void 0){if(c===void 0){if(r.strict)throw Error("Non-constructed ASN.1 object of indefinite length.");c=t}if(a===j.Type.BMPSTRING){l="";for(;c>0;c-=2)Pi(e,t,2),l+=String.fromCharCode(e.getInt16()),t-=2}else l=e.getBytes(c),t-=c}var T=f===void 0?null:{bitStringContents:f};return j.create(s,a,p,l,T)}j.toDer=function(e){var t=ze.util.createBuffer(),n=e.tagClass|e.type,r=ze.util.createBuffer(),i=!1;if("bitStringContents"in e){if(i=!0,e.original)i=j.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 o=0;o<e.value.length;++o)if(e.value[o]!==void 0)r.putBuffer(j.toDer(e.value[o]))}else if(e.type===j.Type.BMPSTRING)for(var o=0;o<e.value.length;++o)r.putInt16(e.value.charCodeAt(o));else if(e.type===j.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(),a="";do a+=String.fromCharCode(s&255),s=s>>>8;while(s>0);t.putByte(a.length|128);for(var o=a.length-1;o>=0;--o)t.putByte(a.charCodeAt(o))}return t.putBuffer(r),t};j.oidToDer=function(e){var t=e.split("."),n=ze.util.createBuffer(),r=parseInt(t[0],10),i=parseInt(t[1],10);if(!(r>=0&&r<=2&&i>=0)||r<2&&i>39)throw Error("Invalid OID; the first two arcs are out of range.");var o,s,a,c;for(var u=1;u<t.length;++u){if(o=!0,s=[],a=u===1?40*r+i:parseInt(t[u],10),a>4294967295)throw Error("OID value too large; max is 32-bits.");do{if(c=a&127,a=a>>>7,!o)c|=128;s.push(c),o=!1}while(a>0);for(var l=s.length-1;l>=0;--l)n.putByte(s[l])}return n};j.derToOid=function(e){var t;if(typeof e==="string")e=ze.util.createBuffer(e);var n,r=0,i=!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{if(r+=n,i)t=r<80?Math.floor(r/40)+"."+r%40:"2."+(r-80),i=!1;else t+="."+r;r=0}}return t};j.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),o=parseInt(e.substr(6,2),10),s=parseInt(e.substr(8,2),10),a=0;if(e.length>11){var c=e.charAt(10),u=10;if(c!=="+"&&c!=="-")a=parseInt(e.substr(10,2),10),u+=2}if(t.setUTCFullYear(n,r,i),t.setUTCHours(o,s,a,0),u){if(c=e.charAt(u),c==="+"||c==="-"){var l=parseInt(e.substr(u+1,2),10),f=parseInt(e.substr(u+4,2),10),p=l*60+f;if(p*=60000,c==="+")t.setTime(+t-p);else t.setTime(+t+p)}}return t};j.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),o=parseInt(e.substr(8,2),10),s=parseInt(e.substr(10,2),10),a=parseInt(e.substr(12,2),10),c=0,u=0,l=!1;if(e.charAt(e.length-1)==="Z")l=!0;var f=e.length-5,p=e.charAt(f);if(p==="+"||p==="-"){var h=parseInt(e.substr(f+1,2),10),d=parseInt(e.substr(f+4,2),10);if(u=h*60+d,u*=60000,p==="+")u*=-1;l=!0}if(e.charAt(14)===".")c=parseFloat(e.substr(14),10)*1000;if(l)t.setUTCFullYear(n,r,i),t.setUTCHours(o,s,a,c),t.setTime(+t+u);else t.setFullYear(n,r,i),t.setHours(o,s,a,c);return t};j.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};j.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};j.integerToDer=function(e){var t=ze.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};j.derToInteger=function(e){if(typeof e==="string")e=ze.util.createBuffer(e);var t=e.length()*8;if(t>32)throw Error("Integer too large; max is 32-bits.");return e.getSignedInt(t)};j.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&&ze.util.isArray(t.value)){var o=0;for(var s=0;i&&s<t.value.length;++s){var a=t.value[s];i=!!a.optional;var c=e.value[o];if(!c){if(!a.optional){if(i=!1,r)r.push("["+t.name+'] Missing required element. Expected tag class "'+a.tagClass+'", type "'+a.type+'"')}continue}var u=typeof a.tagClass<"u"&&typeof a.type<"u";if(u&&(c.tagClass!==a.tagClass||c.type!==a.type))if(a.optional){i=!0;continue}else{if(i=!1,r)r.push("["+t.name+"] Tag mismatch. Expected ("+a.tagClass+","+a.type+"), got ("+c.tagClass+","+c.type+")");break}var l=j.validate(c,a,n,r);if(l)++o,i=!0;else if(a.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 f;if(e.bitStringContents.length<2)n[t.captureBitStringValue]="";else{var p=e.bitStringContents.charCodeAt(0);if(p!==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 Ff=/[^\\u0000-\\u00ff]/;j.prettyPrint=function(e,t,n){var r="";if(t=t||0,n=n||2,t>0)r+=`
2
+ var zb=Object.create;var{getPrototypeOf:Fb,defineProperty:bf,getOwnPropertyNames:Mb}=Object;var Sf=Object.prototype.hasOwnProperty;function Vb(e){return this[e]}var Wb,Hb,ja=(e,t,n)=>{var r=e!=null&&typeof e==="object";if(r){var i=t?Wb??=new WeakMap:Hb??=new WeakMap,o=i.get(e);if(o)return o}n=e!=null?zb(Fb(e)):{};let s=t||!e||!e.__esModule||!Sf.call(e,"default")?bf(n,"default",{value:e,enumerable:!0}):n;if(e&&typeof e==="object"||typeof e==="function"){for(let a of Mb(e))if(!Sf.call(s,a))bf(s,a,{get:Vb.bind(e,a),enumerable:!0})}if(r)i.set(e,s);return s};var le=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Ei=import.meta.require;var he=le(function(g2,Tf){Tf.exports={options:{usePureJavaScript:!1}}});var If=le(function(y2,kf){var Xa={};kf.exports=Xa;var Af={};Xa.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=Yb(e,t);else{var i=0,o=t.length,s=t.charAt(0),a=[0];for(i=0;i<e.length;++i){for(var c=0,u=e[i];c<a.length;++c)u+=a[c]<<8,a[c]=u%o,u=u/o|0;while(u>0)a.push(u%o),u=u/o|0}for(i=0;e[i]===0&&i<e.length-1;++i)r+=s;for(i=a.length-1;i>=0;--i)r+=t[a[i]]}if(n){var l=new RegExp(".{1,"+n+"}","g");r=r.match(l).join(`\r
3
+ `)}return r};Xa.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=Af[t];if(!n){n=Af[t]=[];for(var r=0;r<t.length;++r)n[t.charCodeAt(r)]=r}e=e.replace(/\s/g,"");var i=t.length,o=t.charAt(0),s=[0];for(var r=0;r<e.length;r++){var a=n[e.charCodeAt(r)];if(a===void 0)return;for(var c=0,u=a;c<s.length;++c)u+=s[c]*i,s[c]=u&255,u>>=8;while(u>0)s.push(u&255),u>>=8}for(var l=0;e[l]===o&&l<e.length-1;++l)s.push(0);if(typeof Buffer<"u")return Buffer.from(s.reverse());return new Uint8Array(s.reverse())};function Yb(e,t){var n=0,r=t.length,i=t.charAt(0),o=[0];for(n=0;n<e.length();++n){for(var s=0,a=e.at(n);s<o.length;++s)a+=o[s]<<8,o[s]=a%r,a=a/r|0;while(a>0)o.push(a%r),a=a/r|0}var c="";for(n=0;e.at(n)===0&&n<e.length()-1;++n)c+=i;for(n=o.length-1;n>=0;--n)c+=t[o[n]];return c}});var Te=le(function(v2,Nf){var Pf=he(),Rf=If(),A=Nf.exports=Pf.util=Pf.util||{};(function(){if(typeof process<"u"&&process.nextTick){if(A.nextTick=process.nextTick,typeof setImmediate==="function")A.setImmediate=setImmediate;else A.setImmediate=A.nextTick;return}if(typeof setImmediate==="function"){A.setImmediate=function(){return setImmediate.apply(void 0,arguments)},A.nextTick=function(a){return setImmediate(a)};return}if(A.setImmediate=function(a){setTimeout(a,0)},typeof window<"u"&&typeof window.postMessage==="function"){let a=function(c){if(c.source===window&&c.data===e){c.stopPropagation();var u=t.slice();t.length=0,u.forEach(function(l){l()})}};var s=a,e="forge.setImmediate",t=[];A.setImmediate=function(c){if(t.push(c),t.length===1)window.postMessage(e,"*")},window.addEventListener("message",a,!0)}if(typeof MutationObserver<"u"){var n=Date.now(),r=!0,i=document.createElement("div"),t=[];new MutationObserver(function(){var c=t.slice();t.length=0,c.forEach(function(u){u()})}).observe(i,{attributes:!0});var o=A.setImmediate;A.setImmediate=function(c){if(Date.now()-n>15)n=Date.now(),o(c);else if(t.push(c),t.length===1)i.setAttribute("a",r=!r)}}A.nextTick=A.setImmediate})();A.isNodejs=typeof process<"u"&&process.versions&&process.versions.node;A.globalScope=function(){if(A.isNodejs)return global;return typeof self>"u"?window:self}();A.isArray=Array.isArray||function(e){return Object.prototype.toString.call(e)==="[object Array]"};A.isArrayBuffer=function(e){return typeof ArrayBuffer<"u"&&e instanceof ArrayBuffer};A.isArrayBufferView=function(e){return e&&A.isArrayBuffer(e.buffer)&&e.byteLength!==void 0};function Pi(e){if(!(e===8||e===16||e===24||e===32))throw Error("Only 8, 16, 24, or 32 bits supported: "+e)}A.ByteBuffer=Ja;function Ja(e){if(this.data="",this.read=0,typeof e==="string")this.data=e;else if(A.isArrayBuffer(e)||A.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 Ja||typeof e==="object"&&typeof e.data==="string"&&typeof e.read==="number")this.data=e.data,this.read=e.read;this._constructedStringLength=0}A.ByteStringBuffer=Ja;var eS=4096;A.ByteStringBuffer.prototype._optimizeConstructedString=function(e){if(this._constructedStringLength+=e,this._constructedStringLength>eS)this.data.substr(0,1),this._constructedStringLength=0};A.ByteStringBuffer.prototype.length=function(){return this.data.length-this.read};A.ByteStringBuffer.prototype.isEmpty=function(){return this.length()<=0};A.ByteStringBuffer.prototype.putByte=function(e){return this.putBytes(String.fromCharCode(e))};A.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};A.ByteStringBuffer.prototype.putBytes=function(e){return this.data+=e,this._optimizeConstructedString(e.length),this};A.ByteStringBuffer.prototype.putString=function(e){return this.putBytes(A.encodeUtf8(e))};A.ByteStringBuffer.prototype.putInt16=function(e){return this.putBytes(String.fromCharCode(e>>8&255)+String.fromCharCode(e&255))};A.ByteStringBuffer.prototype.putInt24=function(e){return this.putBytes(String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e&255))};A.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))};A.ByteStringBuffer.prototype.putInt16Le=function(e){return this.putBytes(String.fromCharCode(e&255)+String.fromCharCode(e>>8&255))};A.ByteStringBuffer.prototype.putInt24Le=function(e){return this.putBytes(String.fromCharCode(e&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e>>16&255))};A.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))};A.ByteStringBuffer.prototype.putInt=function(e,t){Pi(t);var n="";do t-=8,n+=String.fromCharCode(e>>t&255);while(t>0);return this.putBytes(n)};A.ByteStringBuffer.prototype.putSignedInt=function(e,t){if(e<0)e+=2<<t-1;return this.putInt(e,t)};A.ByteStringBuffer.prototype.putBuffer=function(e){return this.putBytes(e.getBytes())};A.ByteStringBuffer.prototype.getByte=function(){return this.data.charCodeAt(this.read++)};A.ByteStringBuffer.prototype.getInt16=function(){var e=this.data.charCodeAt(this.read)<<8^this.data.charCodeAt(this.read+1);return this.read+=2,e};A.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};A.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};A.ByteStringBuffer.prototype.getInt16Le=function(){var e=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8;return this.read+=2,e};A.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};A.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};A.ByteStringBuffer.prototype.getInt=function(e){Pi(e);var t=0;do t=(t<<8)+this.data.charCodeAt(this.read++),e-=8;while(e>0);return t};A.ByteStringBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),n=2<<e-2;if(t>=n)t-=n<<1;return t};A.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};A.ByteStringBuffer.prototype.bytes=function(e){return typeof e>"u"?this.data.slice(this.read):this.data.slice(this.read,this.read+e)};A.ByteStringBuffer.prototype.at=function(e){return this.data.charCodeAt(this.read+e)};A.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};A.ByteStringBuffer.prototype.last=function(){return this.data.charCodeAt(this.data.length-1)};A.ByteStringBuffer.prototype.copy=function(){var e=A.createBuffer(this.data);return e.read=this.read,e};A.ByteStringBuffer.prototype.compact=function(){if(this.read>0)this.data=this.data.slice(this.read),this.read=0;return this};A.ByteStringBuffer.prototype.clear=function(){return this.data="",this.read=0,this};A.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};A.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};A.ByteStringBuffer.prototype.toString=function(){return A.decodeUtf8(this.bytes())};function tS(e,t){t=t||{},this.read=t.readOffset||0,this.growSize=t.growSize||1024;var n=A.isArrayBuffer(e),r=A.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}A.DataBuffer=tS;A.DataBuffer.prototype.length=function(){return this.write-this.read};A.DataBuffer.prototype.isEmpty=function(){return this.length()<=0};A.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};A.DataBuffer.prototype.putByte=function(e){return this.accommodate(1),this.data.setUint8(this.write++,e),this};A.DataBuffer.prototype.fillWithByte=function(e,t){this.accommodate(t);for(var n=0;n<t;++n)this.data.setUint8(e);return this};A.DataBuffer.prototype.putBytes=function(e,t){if(A.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(A.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 A.DataBuffer||typeof e==="object"&&typeof e.read==="number"&&typeof e.write==="number"&&A.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 A.ByteStringBuffer)e=e.data,t="binary";if(t=t||"binary",typeof e==="string"){var o;if(t==="hex")return this.accommodate(Math.ceil(e.length/2)),o=new Uint8Array(this.data.buffer,this.write),this.write+=A.binary.hex.decode(e,o,this.write),this;if(t==="base64")return this.accommodate(Math.ceil(e.length/4)*3),o=new Uint8Array(this.data.buffer,this.write),this.write+=A.binary.base64.decode(e,o,this.write),this;if(t==="utf8")e=A.encodeUtf8(e),t="binary";if(t==="binary"||t==="raw")return this.accommodate(e.length),o=new Uint8Array(this.data.buffer,this.write),this.write+=A.binary.raw.decode(o),this;if(t==="utf16")return this.accommodate(e.length*2),o=new Uint16Array(this.data.buffer,this.write),this.write+=A.text.utf16.encode(o),this;throw Error("Invalid encoding: "+t)}throw Error("Invalid parameter: "+e)};A.DataBuffer.prototype.putBuffer=function(e){return this.putBytes(e),e.clear(),this};A.DataBuffer.prototype.putString=function(e){return this.putBytes(e,"utf16")};A.DataBuffer.prototype.putInt16=function(e){return this.accommodate(2),this.data.setInt16(this.write,e),this.write+=2,this};A.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};A.DataBuffer.prototype.putInt32=function(e){return this.accommodate(4),this.data.setInt32(this.write,e),this.write+=4,this};A.DataBuffer.prototype.putInt16Le=function(e){return this.accommodate(2),this.data.setInt16(this.write,e,!0),this.write+=2,this};A.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};A.DataBuffer.prototype.putInt32Le=function(e){return this.accommodate(4),this.data.setInt32(this.write,e,!0),this.write+=4,this};A.DataBuffer.prototype.putInt=function(e,t){Pi(t),this.accommodate(t/8);do t-=8,this.data.setInt8(this.write++,e>>t&255);while(t>0);return this};A.DataBuffer.prototype.putSignedInt=function(e,t){if(Pi(t),this.accommodate(t/8),e<0)e+=2<<t-1;return this.putInt(e,t)};A.DataBuffer.prototype.getByte=function(){return this.data.getInt8(this.read++)};A.DataBuffer.prototype.getInt16=function(){var e=this.data.getInt16(this.read);return this.read+=2,e};A.DataBuffer.prototype.getInt24=function(){var e=this.data.getInt16(this.read)<<8^this.data.getInt8(this.read+2);return this.read+=3,e};A.DataBuffer.prototype.getInt32=function(){var e=this.data.getInt32(this.read);return this.read+=4,e};A.DataBuffer.prototype.getInt16Le=function(){var e=this.data.getInt16(this.read,!0);return this.read+=2,e};A.DataBuffer.prototype.getInt24Le=function(){var e=this.data.getInt8(this.read)^this.data.getInt16(this.read+1,!0)<<8;return this.read+=3,e};A.DataBuffer.prototype.getInt32Le=function(){var e=this.data.getInt32(this.read,!0);return this.read+=4,e};A.DataBuffer.prototype.getInt=function(e){Pi(e);var t=0;do t=(t<<8)+this.data.getInt8(this.read++),e-=8;while(e>0);return t};A.DataBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),n=2<<e-2;if(t>=n)t-=n<<1;return t};A.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};A.DataBuffer.prototype.bytes=function(e){return typeof e>"u"?this.data.slice(this.read):this.data.slice(this.read,this.read+e)};A.DataBuffer.prototype.at=function(e){return this.data.getUint8(this.read+e)};A.DataBuffer.prototype.setAt=function(e,t){return this.data.setUint8(e,t),this};A.DataBuffer.prototype.last=function(){return this.data.getUint8(this.write-1)};A.DataBuffer.prototype.copy=function(){return new A.DataBuffer(this)};A.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};A.DataBuffer.prototype.clear=function(){return this.data=new DataView(new ArrayBuffer(0)),this.read=this.write=0,this};A.DataBuffer.prototype.truncate=function(e){return this.write=Math.max(0,this.length()-e),this.read=Math.min(this.read,this.write),this};A.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};A.DataBuffer.prototype.toString=function(e){var t=new Uint8Array(this.data,this.read,this.length());if(e=e||"utf8",e==="binary"||e==="raw")return A.binary.raw.encode(t);if(e==="hex")return A.binary.hex.encode(t);if(e==="base64")return A.binary.base64.encode(t);if(e==="utf8")return A.text.utf8.decode(t);if(e==="utf16")return A.text.utf16.decode(t);throw Error("Invalid encoding: "+e)};A.createBuffer=function(e,t){if(t=t||"raw",e!==void 0&&t==="utf8")e=A.encodeUtf8(e);return new A.ByteBuffer(e)};A.fillString=function(e,t){var n="";while(t>0){if(t&1)n+=e;if(t>>>=1,t>0)e+=e}return n};A.xorBytes=function(e,t,n){var r="",i="",o="",s=0,a=0;for(;n>0;--n,++s){if(i=e.charCodeAt(s)^t.charCodeAt(s),a>=10)r+=o,o="",a=0;o+=String.fromCharCode(i),++a}return r+=o,r};A.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};A.bytesToHex=function(e){return A.createBuffer(e).toHex()};A.int32ToBytes=function(e){return String.fromCharCode(e>>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e&255)};var Fr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",Mr=[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],Bf="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";A.encode64=function(e,t){var n="",r="",i,o,s,a=0;while(a<e.length){if(i=e.charCodeAt(a++)&255,o=e.charCodeAt(a++),s=e.charCodeAt(a++),n+=Fr.charAt(i>>2),n+=Fr.charAt((i&3)<<4|(o&255)>>4),isNaN(o))n+="==";else n+=Fr.charAt((o&15)<<2|(s&255)>>6),n+=isNaN(s)?"=":Fr.charAt(s&63);if(t&&n.length>t)r+=n.substr(0,t)+`\r
4
+ `,n=n.substr(t)}return r+=n,r};A.decode64=function(e){e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");var t="",n,r,i,o,s=0;while(s<e.length)if(n=Mr[e.charCodeAt(s++)-43],r=Mr[e.charCodeAt(s++)-43],i=Mr[e.charCodeAt(s++)-43],o=Mr[e.charCodeAt(s++)-43],t+=String.fromCharCode(n<<2|r>>4),i!==64){if(t+=String.fromCharCode((r&15)<<4|i>>2),o!==64)t+=String.fromCharCode((i&3)<<6|o)}return t};A.encodeUtf8=function(e){return unescape(encodeURIComponent(e))};A.decodeUtf8=function(e){return decodeURIComponent(escape(e))};A.binary={raw:{},hex:{},base64:{},base58:{},baseN:{encode:Rf.encode,decode:Rf.decode}};A.binary.raw.encode=function(e){return String.fromCharCode.apply(null,e)};A.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 o=0;o<e.length;++o)r[i++]=e.charCodeAt(o);return t?i-n:r};A.binary.hex.encode=A.bytesToHex;A.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,o=n;if(e.length&1)i=1,r[o++]=parseInt(e[0],16);for(;i<e.length;i+=2)r[o++]=parseInt(e.substr(i,2),16);return t?o-n:r};A.binary.base64.encode=function(e,t){var n="",r="",i,o,s,a=0;while(a<e.byteLength){if(i=e[a++],o=e[a++],s=e[a++],n+=Fr.charAt(i>>2),n+=Fr.charAt((i&3)<<4|o>>4),isNaN(o))n+="==";else n+=Fr.charAt((o&15)<<2|s>>6),n+=isNaN(s)?"=":Fr.charAt(s&63);if(t&&n.length>t)r+=n.substr(0,t)+`\r
5
+ `,n=n.substr(t)}return r+=n,r};A.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,o,s,a,c=0,u=n;while(c<e.length)if(i=Mr[e.charCodeAt(c++)-43],o=Mr[e.charCodeAt(c++)-43],s=Mr[e.charCodeAt(c++)-43],a=Mr[e.charCodeAt(c++)-43],r[u++]=i<<2|o>>4,s!==64){if(r[u++]=(o&15)<<4|s>>2,a!==64)r[u++]=(s&3)<<6|a}return t?u-n:r.subarray(0,u)};A.binary.base58.encode=function(e,t){return A.binary.baseN.encode(e,Bf,t)};A.binary.base58.decode=function(e,t){return A.binary.baseN.decode(e,Bf,t)};A.text={utf8:{},utf16:{}};A.text.utf8.encode=function(e,t,n){e=A.encodeUtf8(e);var r=t;if(!r)r=new Uint8Array(e.length);n=n||0;var i=n;for(var o=0;o<e.length;++o)r[i++]=e.charCodeAt(o);return t?i-n:r};A.text.utf8.decode=function(e){return A.decodeUtf8(String.fromCharCode.apply(null,e))};A.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 o=n,s=n;for(var a=0;a<e.length;++a)i[s++]=e.charCodeAt(a),o+=2;return t?o-n:r};A.text.utf16.decode=function(e){return String.fromCharCode.apply(null,new Uint16Array(e.buffer))};A.deflate=function(e,t,n){if(t=A.decode64(e.deflate(A.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};A.inflate=function(e,t,n){var r=e.inflate(A.encode64(t)).rval;return r===null?null:A.decode64(r)};var Qa=function(e,t,n){if(!e)throw Error("WebStorage not available.");var r;if(n===null)r=e.removeItem(t);else n=A.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}},Ya=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(A.decode64(n));return n},rS=function(e,t,n,r){var i=Ya(e,t);if(i===null)i={};i[n]=r,Qa(e,t,i)},nS=function(e,t,n){var r=Ya(e,t);if(r!==null)r=n in r?r[n]:null;return r},iS=function(e,t,n){var r=Ya(e,t);if(r!==null&&n in r){delete r[n];var i=!0;for(var o in r){i=!1;break}if(i)r=null;Qa(e,t,r)}},oS=function(e,t){Qa(e,t,null)},Uo=function(e,t,n){var r=null;if(typeof n>"u")n=["web","flash"];var i,o=!1,s=null;for(var a in n){i=n[a];try{if(i==="flash"||i==="both"){if(t[0]===null)throw Error("Flash local storage not available.");r=e.apply(this,t),o=i==="flash"}if(i==="web"||i==="both")t[0]=localStorage,r=e.apply(this,t),o=!0}catch(c){s=c}if(o)break}if(!o)throw s;return r};A.setItem=function(e,t,n,r,i){Uo(rS,arguments,i)};A.getItem=function(e,t,n,r){return Uo(nS,arguments,r)};A.removeItem=function(e,t,n,r){Uo(iS,arguments,r)};A.clearItems=function(e,t,n){Uo(oS,arguments,n)};A.isEmpty=function(e){for(var t in e)if(e.hasOwnProperty(t))return!1;return!0};A.format=function(e){var t=/%./g,n,r,i=0,o=[],s=0;while(n=t.exec(e)){if(r=e.substring(s,t.lastIndex-2),r.length>0)o.push(r);s=t.lastIndex;var a=n[0][1];switch(a){case"s":case"o":if(i<arguments.length)o.push(arguments[i+++1]);else o.push("<?>");break;case"%":o.push("%");break;default:o.push("<%"+a+"?>")}}return o.push(e.substring(s)),o.join("")};A.formatNumber=function(e,t,n,r){var i=e,o=isNaN(t=Math.abs(t))?2:t,s=n===void 0?",":n,a=r===void 0?".":r,c=i<0?"-":"",u=parseInt(i=Math.abs(+i||0).toFixed(o),10)+"",l=u.length>3?u.length%3:0;return c+(l?u.substr(0,l)+a:"")+u.substr(l).replace(/(\d{3})(?=\d)/g,"$1"+a)+(o?s+Math.abs(i-u).toFixed(o).slice(2):"")};A.formatSize=function(e){if(e>=1073741824)e=A.formatNumber(e/1073741824,2,".","")+" GiB";else if(e>=1048576)e=A.formatNumber(e/1048576,2,".","")+" MiB";else if(e>=1024)e=A.formatNumber(e/1024,0)+" KiB";else e=A.formatNumber(e,0)+" bytes";return e};A.bytesFromIP=function(e){if(e.indexOf(".")!==-1)return A.bytesFromIPv4(e);if(e.indexOf(":")!==-1)return A.bytesFromIPv6(e);return null};A.bytesFromIPv4=function(e){if(e=e.split("."),e.length!==4)return null;var t=A.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()};A.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=A.createBuffer();for(var i=0;i<8;++i){if(!e[i]||e[i].length===0){r.fillWithByte(0,n),n=0;continue}var o=A.hexToBytes(e[i]);if(o.length<2)r.putByte(0);r.putBytes(o)}return r.getBytes()};A.bytesToIP=function(e){if(e.length===4)return A.bytesToIPv4(e);if(e.length===16)return A.bytesToIPv6(e);return null};A.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(".")};A.bytesToIPv6=function(e){if(e.length!==16)return null;var t=[],n=[],r=0;for(var i=0;i<e.length;i+=2){var o=A.bytesToHex(e[i]+e[i+1]);while(o[0]==="0"&&o!=="0")o=o.substr(1);if(o==="0"){var s=n[n.length-1],a=t.length;if(!s||a!==s.end+1)n.push({start:a,end:a});else if(s.end=a,s.end-s.start>n[r].end-n[r].start)r=n.length-1}t.push(o)}if(n.length>0){var c=n[r];if(c.end-c.start>0){if(t.splice(c.start,c.end-c.start+1,""),c.start===0)t.unshift("");if(c.end===7)t.push("")}}return t.join(":")};A.estimateCores=function(e,t){if(typeof e==="function")t=e,e={};if(e=e||{},"cores"in A&&!e.update)return t(null,A.cores);if(typeof navigator<"u"&&"hardwareConcurrency"in navigator&&navigator.hardwareConcurrency>0)return A.cores=navigator.hardwareConcurrency,t(null,A.cores);if(typeof Worker>"u")return A.cores=1,t(null,A.cores);if(typeof Blob>"u")return A.cores=2,t(null,A.cores);var n=URL.createObjectURL(new Blob(["(",function(){self.addEventListener("message",function(s){var a=Date.now(),c=a+4;while(Date.now()<c);self.postMessage({st:a,et:c})})}.toString(),")()"],{type:"application/javascript"}));r([],5,16);function r(s,a,c){if(a===0){var u=Math.floor(s.reduce(function(l,f){return l+f},0)/s.length);return A.cores=Math.max(1,u),URL.revokeObjectURL(n),t(null,A.cores)}i(c,function(l,f){s.push(o(c,f)),r(s,a-1,c)})}function i(s,a){var c=[],u=[];for(var l=0;l<s;++l){var f=new Worker(n);f.addEventListener("message",function(p){if(u.push(p.data),u.length===s){for(var h=0;h<s;++h)c[h].terminate();a(null,u)}}),c.push(f)}for(var l=0;l<s;++l)c[l].postMessage(l)}function o(s,a){var c=[];for(var u=0;u<s;++u){var l=a[u],f=c[u]=[];for(var p=0;p<s;++p){if(u===p)continue;var h=a[p];if(l.st>h.st&&l.st<h.et||h.st>l.st&&h.st<l.et)f.push(p)}}return c.reduce(function(d,g){return Math.max(d,g.length)},0)}}});var zo=le(function(x2,Df){var ut=he();Te();Df.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 ec=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)};ec.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)};ec.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()};ec.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 rc=le(function(b2,$f){var lt=he();Te();lt.cipher=lt.cipher||{};var ve=$f.exports=lt.cipher.modes=lt.cipher.modes||{};ve.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)};ve.ecb.prototype.start=function(e){};ve.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])};ve.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])};ve.ecb.prototype.pad=function(e,t){var n=e.length()===this.blockSize?this.blockSize:this.blockSize-e.length();return e.fillWithByte(n,n),!0};ve.ecb.prototype.unpad=function(e,t){if(t.overflow>0)return!1;var n=e.length();if(n===0)return!0;var r=e.at(n-1);if(r===0||r>this.blockSize||r>n)return!1;for(var i=2;i<=r;++i)if(e.at(n-i)!==r)return!1;return e.truncate(r),!0};ve.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)};ve.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=Fo(e.iv,this.blockSize),this._prev=this._iv.slice(0)};ve.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};ve.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)};ve.cbc.prototype.pad=function(e,t){var n=e.length()===this.blockSize?this.blockSize:this.blockSize-e.length();return e.fillWithByte(n,n),!0};ve.cbc.prototype.unpad=function(e,t){if(t.overflow>0)return!1;var n=e.length();if(n===0)return!0;var r=e.at(n-1);if(r===0||r>this.blockSize||r>n)return!1;for(var i=2;i<=r;++i)if(e.at(n-i)!==r)return!1;return e.truncate(r),!0};ve.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=lt.util.createBuffer(),this._partialBytes=0};ve.cfb.prototype.start=function(e){if(!("iv"in e))throw Error("Invalid IV parameter.");this._iv=Fo(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0};ve.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 o=(this.blockSize-r)%this.blockSize;if(o>0)o=this.blockSize-o;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(o>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(o>0&&!n)return t.putBytes(this._partialOutput.getBytes(o-this._partialBytes)),this._partialBytes=o,!0;t.putBytes(this._partialOutput.getBytes(r-this._partialBytes)),this._partialBytes=0};ve.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 o=(this.blockSize-r)%this.blockSize;if(o>0)o=this.blockSize-o;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(o>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(o>0&&!n)return t.putBytes(this._partialOutput.getBytes(o-this._partialBytes)),this._partialBytes=o,!0;t.putBytes(this._partialOutput.getBytes(r-this._partialBytes)),this._partialBytes=0};ve.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=lt.util.createBuffer(),this._partialBytes=0};ve.ofb.prototype.start=function(e){if(!("iv"in e))throw Error("Invalid IV parameter.");this._iv=Fo(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0};ve.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 o=(this.blockSize-r)%this.blockSize;if(o>0)o=this.blockSize-o;this._partialOutput.clear();for(var i=0;i<this._ints;++i)this._partialOutput.putInt32(e.getInt32()^this._outBlock[i]);if(o>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(o>0&&!n)return t.putBytes(this._partialOutput.getBytes(o-this._partialBytes)),this._partialBytes=o,!0;t.putBytes(this._partialOutput.getBytes(r-this._partialBytes)),this._partialBytes=0};ve.ofb.prototype.decrypt=ve.ofb.prototype.encrypt;ve.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=lt.util.createBuffer(),this._partialBytes=0};ve.ctr.prototype.start=function(e){if(!("iv"in e))throw Error("Invalid IV parameter.");this._iv=Fo(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0};ve.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 o=(this.blockSize-r)%this.blockSize;if(o>0)o=this.blockSize-o;this._partialOutput.clear();for(var i=0;i<this._ints;++i)this._partialOutput.putInt32(e.getInt32()^this._outBlock[i]);if(o>0)e.read-=this.blockSize;if(this._partialBytes>0)this._partialOutput.getBytes(this._partialBytes);if(o>0&&!n)return t.putBytes(this._partialOutput.getBytes(o-this._partialBytes)),this._partialBytes=o,!0;t.putBytes(this._partialOutput.getBytes(r-this._partialBytes)),this._partialBytes=0}Mo(this._inBlock)};ve.ctr.prototype.decrypt=ve.ctr.prototype.encrypt;ve.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=lt.util.createBuffer(),this._partialBytes=0,this._R=3774873600};ve.gcm.prototype.start=function(e){if(!("iv"in e))throw Error("Invalid IV parameter.");var t=lt.util.createBuffer(e.iv);this._cipherLength=0;var n;if("additionalData"in e)n=lt.util.createBuffer(e.additionalData);else n=lt.util.createBuffer();if(e.tagLength!==void 0&&e.tagLength!==null)this._tagLength=Number(e.tagLength);else this._tagLength=128;if([128,120,112,104,96,64,32].indexOf(this._tagLength)===-1)throw Error("Invalid tag length.");if(this._tag=null,e.decrypt){if(this._tag=lt.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(tc(r*8)))}this._inBlock=this._j0.slice(0),Mo(this._inBlock),this._partialBytes=0,n=lt.util.createBuffer(n),this._aDataLength=tc(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()])};ve.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 o=(this.blockSize-r)%this.blockSize;if(o>0)o=this.blockSize-o;this._partialOutput.clear();for(var i=0;i<this._ints;++i)this._partialOutput.putInt32(e.getInt32()^this._outBlock[i]);if(o<=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(o>0&&!n)return e.read-=this.blockSize,t.putBytes(this._partialOutput.getBytes(o-this._partialBytes)),this._partialBytes=o,!0;t.putBytes(this._partialOutput.getBytes(r-this._partialBytes)),this._partialBytes=0}this._s=this.ghash(this._hashSubkey,this._s,this._outBlock),Mo(this._inBlock)};ve.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),Mo(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};ve.gcm.prototype.afterFinish=function(e,t){var n=!0;if(t.decrypt&&t.overflow)e.truncate(this.blockSize-t.overflow);this.tag=lt.util.createBuffer();var r=this._aDataLength.concat(tc(this._cipherLength*8));this._s=this.ghash(this._hashSubkey,this._s,r);var i=[];this.cipher.encrypt(this._j0,i);for(var o=0;o<this._ints;++o)this.tag.putInt32(this._s[o]^i[o]);if(this.tag.truncate(this.tag.length()%(this._tagLength/8)),t.decrypt&&this.tag.bytes()!==this._tag)n=!1;return n};ve.gcm.prototype.multiply=function(e,t){var n=[0,0,0,0],r=t.slice(0);for(var i=0;i<128;++i){var o=e[i/32|0]&1<<31-i%32;if(o)n[0]^=r[0],n[1]^=r[1],n[2]^=r[2],n[3]^=r[3];this.pow(r,r)}return n};ve.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};ve.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,o=this._m[n][i];t[0]^=o[0],t[1]^=o[1],t[2]^=o[2],t[3]^=o[3]}return t};ve.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)};ve.gcm.prototype.generateHashTable=function(e,t){var n=8/t,r=4*n,i=16*n,o=Array(i);for(var s=0;s<i;++s){var a=[0,0,0,0],c=s/r|0,u=(r-1-s%r)*t;a[c]=1<<t-1<<u,o[s]=this.generateSubHashTable(this.multiply(a,e),t)}return o};ve.gcm.prototype.generateSubHashTable=function(e,t){var n=1<<t,r=n>>>1,i=Array(n);i[r]=e.slice(0);var o=r>>>1;while(o>0)this.pow(i[2*o],i[o]=[]),o>>=1;o=2;while(o<r){for(var s=1;s<o;++s){var a=i[o],c=i[s];i[o+s]=[a[0]^c[0],a[1]^c[1],a[2]^c[2],a[3]^c[3]]}o*=2}i[0]=[0,0,0,0];for(o=r+1;o<n;++o){var u=i[o^r];i[o]=[e[0]^u[0],e[1]^u[1],e[2]^u[2],e[3]^u[3]]}return i};function Fo(e,t){if(typeof e==="string")e=lt.util.createBuffer(e);if(lt.util.isArray(e)&&e.length>4){var n=e;e=lt.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(!lt.util.isArray(e)){var i=[],o=t/4;for(var r=0;r<o;++r)i.push(e.getInt32());e=i}return e}function Mo(e){e[e.length-1]=e[e.length-1]+1&4294967295}function tc(e){return[e/4294967296|0,e&4294967295]}});var Vr=le(function(S2,zf){var Le=he();zo();rc();Te();zf.exports=Le.aes=Le.aes||{};Le.aes.startEncrypting=function(e,t,n,r){var i=Vo({key:e,output:n,decrypt:!1,mode:r});return i.start(t),i};Le.aes.createEncryptionCipher=function(e,t){return Vo({key:e,output:null,decrypt:!1,mode:t})};Le.aes.startDecrypting=function(e,t,n,r){var i=Vo({key:e,output:n,decrypt:!0,mode:r});return i.start(t),i};Le.aes.createDecryptionCipher=function(e,t){return Vo({key:e,output:null,decrypt:!0,mode:t})};Le.aes.Algorithm=function(e,t){if(!oc)Lf();var n=this;n.name=e,n.mode=new t({blockSize:16,cipher:{encrypt:function(r,i){return ic(n._w,r,i,!1)},decrypt:function(r,i){return ic(n._w,r,i,!0)}}}),n._init=!1};Le.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=Le.util.createBuffer(t);else if(Le.util.isArray(t)&&(t.length===16||t.length===24||t.length===32)){n=t,t=Le.util.createBuffer();for(var r=0;r<n.length;++r)t.putByte(n[r])}if(!Le.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(!Le.util.isArray(t)||!(t.length===4||t.length===6||t.length===8))throw Error("Invalid key parameter.");var o=this.mode.name,s=["CFB","OFB","CTR","GCM"].indexOf(o)!==-1;this._w=Uf(t,e.decrypt&&!s),this._init=!0};Le.aes._expandKey=function(e,t){if(!oc)Lf();return Uf(e,t)};Le.aes._updateBlock=ic;On("AES-ECB",Le.cipher.modes.ecb);On("AES-CBC",Le.cipher.modes.cbc);On("AES-CFB",Le.cipher.modes.cfb);On("AES-OFB",Le.cipher.modes.ofb);On("AES-CTR",Le.cipher.modes.ctr);On("AES-GCM",Le.cipher.modes.gcm);function On(e,t){var n=function(){return new Le.aes.Algorithm(e,t)};Le.cipher.registerAlgorithm(e,n)}var oc=!1,$n=4,St,nc,Of,ln,Jt;function Lf(){oc=!0,Of=[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),nc=Array(256),ln=[,,,,],Jt=[,,,,];for(var t=0;t<4;++t)ln[t]=Array(256),Jt[t]=Array(256);var n=0,r=0,i,o,s,a,c,u,l;for(var t=0;t<256;++t){a=r^r<<1^r<<2^r<<3^r<<4,a=a>>8^a&255^99,St[n]=a,nc[a]=n,c=e[a],i=e[n],o=e[i],s=e[o],u=c<<24^a<<16^a<<8^(a^c),l=(i^o^s)<<24^(n^s)<<16^(n^o^s)<<8^(n^i^s);for(var f=0;f<4;++f)ln[f][n]=u,Jt[f][a]=l,u=u<<24|u>>>8,l=l<<24|l>>>8;if(n===0)n=r=1;else n=i^e[e[e[i^s]]],r^=e[e[r]]}}function Uf(e,t){var n=e.slice(0),r,i=1,o=n.length,s=o+6+1,a=$n*s;for(var c=o;c<a;++c){if(r=n[c-1],c%o===0)r=St[r>>>16&255]<<24^St[r>>>8&255]<<16^St[r&255]<<8^St[r>>>24]^Of[i]<<24,i++;else if(o>6&&c%o===4)r=St[r>>>24]<<24^St[r>>>16&255]<<16^St[r>>>8&255]<<8^St[r&255];n[c]=n[c-o]^r}if(t){var u,l=Jt[0],f=Jt[1],p=Jt[2],h=Jt[3],d=n.slice(0);a=n.length;for(var c=0,g=a-$n;c<a;c+=$n,g-=$n)if(c===0||c===a-$n)d[c]=n[g],d[c+1]=n[g+3],d[c+2]=n[g+2],d[c+3]=n[g+1];else for(var v=0;v<$n;++v)u=n[g+v],d[c+(3&-v)]=l[St[u>>>24]]^f[St[u>>>16&255]]^p[St[u>>>8&255]]^h[St[u&255]];n=d}return n}function ic(e,t,n,r){var i=e.length/4-1,o,s,a,c,u;if(r)o=Jt[0],s=Jt[1],a=Jt[2],c=Jt[3],u=nc;else o=ln[0],s=ln[1],a=ln[2],c=ln[3],u=St;var l,f,p,h,d,g,v;l=t[0]^e[0],f=t[r?3:1]^e[1],p=t[2]^e[2],h=t[r?1:3]^e[3];var b=3;for(var S=1;S<i;++S)d=o[l>>>24]^s[f>>>16&255]^a[p>>>8&255]^c[h&255]^e[++b],g=o[f>>>24]^s[p>>>16&255]^a[h>>>8&255]^c[l&255]^e[++b],v=o[p>>>24]^s[h>>>16&255]^a[l>>>8&255]^c[f&255]^e[++b],h=o[h>>>24]^s[l>>>16&255]^a[f>>>8&255]^c[p&255]^e[++b],l=d,f=g,p=v;n[0]=u[l>>>24]<<24^u[f>>>16&255]<<16^u[p>>>8&255]<<8^u[h&255]^e[++b],n[r?3:1]=u[f>>>24]<<24^u[p>>>16&255]<<16^u[h>>>8&255]<<8^u[l&255]^e[++b],n[2]=u[p>>>24]<<24^u[h>>>16&255]<<16^u[l>>>8&255]<<8^u[f&255]^e[++b],n[r?1:3]=u[h>>>24]<<24^u[l>>>16&255]<<16^u[f>>>8&255]<<8^u[p&255]^e[++b]}function Vo(e){e=e||{};var t=(e.mode||"CBC").toUpperCase(),n="AES-"+t,r;if(e.decrypt)r=Le.cipher.createDecipher(n,e.key);else r=Le.cipher.createCipher(n,e.key);var i=r.start;return r.start=function(o,s){var a=null;if(s instanceof Le.util.ByteBuffer)a=s,s={};s=s||{},s.output=a,s.iv=o,i.call(r,s)},r}});var Wr=le(function(C2,Ff){var Ri=he();Ri.pki=Ri.pki||{};var sc=Ff.exports=Ri.pki.oids=Ri.oids=Ri.oids||{};function z(e,t){sc[e]=t,sc[t]=e}function Re(e,t){sc[e]=t}z("1.2.840.113549.1.1.1","rsaEncryption");z("1.2.840.113549.1.1.4","md5WithRSAEncryption");z("1.2.840.113549.1.1.5","sha1WithRSAEncryption");z("1.2.840.113549.1.1.7","RSAES-OAEP");z("1.2.840.113549.1.1.8","mgf1");z("1.2.840.113549.1.1.9","pSpecified");z("1.2.840.113549.1.1.10","RSASSA-PSS");z("1.2.840.113549.1.1.11","sha256WithRSAEncryption");z("1.2.840.113549.1.1.12","sha384WithRSAEncryption");z("1.2.840.113549.1.1.13","sha512WithRSAEncryption");z("1.3.101.112","EdDSA25519");z("1.2.840.10040.4.3","dsa-with-sha1");z("1.3.14.3.2.7","desCBC");z("1.3.14.3.2.26","sha1");z("1.3.14.3.2.29","sha1WithRSASignature");z("2.16.840.1.101.3.4.2.1","sha256");z("2.16.840.1.101.3.4.2.2","sha384");z("2.16.840.1.101.3.4.2.3","sha512");z("2.16.840.1.101.3.4.2.4","sha224");z("2.16.840.1.101.3.4.2.5","sha512-224");z("2.16.840.1.101.3.4.2.6","sha512-256");z("1.2.840.113549.2.2","md2");z("1.2.840.113549.2.5","md5");z("1.2.840.113549.1.7.1","data");z("1.2.840.113549.1.7.2","signedData");z("1.2.840.113549.1.7.3","envelopedData");z("1.2.840.113549.1.7.4","signedAndEnvelopedData");z("1.2.840.113549.1.7.5","digestedData");z("1.2.840.113549.1.7.6","encryptedData");z("1.2.840.113549.1.9.1","emailAddress");z("1.2.840.113549.1.9.2","unstructuredName");z("1.2.840.113549.1.9.3","contentType");z("1.2.840.113549.1.9.4","messageDigest");z("1.2.840.113549.1.9.5","signingTime");z("1.2.840.113549.1.9.6","counterSignature");z("1.2.840.113549.1.9.7","challengePassword");z("1.2.840.113549.1.9.8","unstructuredAddress");z("1.2.840.113549.1.9.14","extensionRequest");z("1.2.840.113549.1.9.20","friendlyName");z("1.2.840.113549.1.9.21","localKeyId");z("1.2.840.113549.1.9.22.1","x509Certificate");z("1.2.840.113549.1.12.10.1.1","keyBag");z("1.2.840.113549.1.12.10.1.2","pkcs8ShroudedKeyBag");z("1.2.840.113549.1.12.10.1.3","certBag");z("1.2.840.113549.1.12.10.1.4","crlBag");z("1.2.840.113549.1.12.10.1.5","secretBag");z("1.2.840.113549.1.12.10.1.6","safeContentsBag");z("1.2.840.113549.1.5.13","pkcs5PBES2");z("1.2.840.113549.1.5.12","pkcs5PBKDF2");z("1.2.840.113549.1.12.1.1","pbeWithSHAAnd128BitRC4");z("1.2.840.113549.1.12.1.2","pbeWithSHAAnd40BitRC4");z("1.2.840.113549.1.12.1.3","pbeWithSHAAnd3-KeyTripleDES-CBC");z("1.2.840.113549.1.12.1.4","pbeWithSHAAnd2-KeyTripleDES-CBC");z("1.2.840.113549.1.12.1.5","pbeWithSHAAnd128BitRC2-CBC");z("1.2.840.113549.1.12.1.6","pbewithSHAAnd40BitRC2-CBC");z("1.2.840.113549.2.7","hmacWithSHA1");z("1.2.840.113549.2.8","hmacWithSHA224");z("1.2.840.113549.2.9","hmacWithSHA256");z("1.2.840.113549.2.10","hmacWithSHA384");z("1.2.840.113549.2.11","hmacWithSHA512");z("1.2.840.113549.3.7","des-EDE3-CBC");z("2.16.840.1.101.3.4.1.2","aes128-CBC");z("2.16.840.1.101.3.4.1.22","aes192-CBC");z("2.16.840.1.101.3.4.1.42","aes256-CBC");z("2.5.4.3","commonName");z("2.5.4.4","surname");z("2.5.4.5","serialNumber");z("2.5.4.6","countryName");z("2.5.4.7","localityName");z("2.5.4.8","stateOrProvinceName");z("2.5.4.9","streetAddress");z("2.5.4.10","organizationName");z("2.5.4.11","organizationalUnitName");z("2.5.4.12","title");z("2.5.4.13","description");z("2.5.4.15","businessCategory");z("2.5.4.17","postalCode");z("2.5.4.42","givenName");z("2.5.4.65","pseudonym");z("1.3.6.1.4.1.311.60.2.1.2","jurisdictionOfIncorporationStateOrProvinceName");z("1.3.6.1.4.1.311.60.2.1.3","jurisdictionOfIncorporationCountryName");z("2.16.840.1.113730.1.1","nsCertType");z("2.16.840.1.113730.1.13","nsComment");Re("2.5.29.1","authorityKeyIdentifier");Re("2.5.29.2","keyAttributes");Re("2.5.29.3","certificatePolicies");Re("2.5.29.4","keyUsageRestriction");Re("2.5.29.5","policyMapping");Re("2.5.29.6","subtreesConstraint");Re("2.5.29.7","subjectAltName");Re("2.5.29.8","issuerAltName");Re("2.5.29.9","subjectDirectoryAttributes");Re("2.5.29.10","basicConstraints");Re("2.5.29.11","nameConstraints");Re("2.5.29.12","policyConstraints");Re("2.5.29.13","basicConstraints");z("2.5.29.14","subjectKeyIdentifier");z("2.5.29.15","keyUsage");Re("2.5.29.16","privateKeyUsagePeriod");z("2.5.29.17","subjectAltName");z("2.5.29.18","issuerAltName");z("2.5.29.19","basicConstraints");Re("2.5.29.20","cRLNumber");Re("2.5.29.21","cRLReason");Re("2.5.29.22","expirationDate");Re("2.5.29.23","instructionCode");Re("2.5.29.24","invalidityDate");Re("2.5.29.25","cRLDistributionPoints");Re("2.5.29.26","issuingDistributionPoint");Re("2.5.29.27","deltaCRLIndicator");Re("2.5.29.28","issuingDistributionPoint");Re("2.5.29.29","certificateIssuer");Re("2.5.29.30","nameConstraints");z("2.5.29.31","cRLDistributionPoints");z("2.5.29.32","certificatePolicies");Re("2.5.29.33","policyMappings");Re("2.5.29.34","policyConstraints");z("2.5.29.35","authorityKeyIdentifier");Re("2.5.29.36","policyConstraints");z("2.5.29.37","extKeyUsage");Re("2.5.29.46","freshestCRL");Re("2.5.29.54","inhibitAnyPolicy");z("1.3.6.1.4.1.11129.2.4.2","timestampList");z("1.3.6.1.5.5.7.1.1","authorityInfoAccess");z("1.3.6.1.5.5.7.3.1","serverAuth");z("1.3.6.1.5.5.7.3.2","clientAuth");z("1.3.6.1.5.5.7.3.3","codeSigning");z("1.3.6.1.5.5.7.3.4","emailProtection");z("1.3.6.1.5.5.7.3.8","timeStamping")});var Qt=le(function(w2,Vf){var Me=he();Te();Wr();var j=Vf.exports=Me.asn1=Me.asn1||{};j.Class={UNIVERSAL:0,APPLICATION:64,CONTEXT_SPECIFIC:128,PRIVATE:192};j.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};j.maxDepth=256;j.create=function(e,t,n,r,i){if(Me.util.isArray(r)){var o=[];for(var s=0;s<r.length;++s)if(r[s]!==void 0)o.push(r[s]);r=o}var a={tagClass:e,type:t,constructed:n,composed:n||Me.util.isArray(r),value:r};if(i&&"bitStringContents"in i)a.bitStringContents=i.bitStringContents,a.original=j.copy(a);return a};j.copy=function(e,t){var n;if(Me.util.isArray(e)){n=[];for(var r=0;r<e.length;++r)n.push(j.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:j.copy(e.value,t)},t&&!t.excludeBitStringContents)n.bitStringContents=e.bitStringContents;return n};j.equals=function(e,t,n){if(Me.util.isArray(e)){if(!Me.util.isArray(t))return!1;if(e.length!==t.length)return!1;for(var r=0;r<e.length;++r)if(!j.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&&j.equals(e.value,t.value);if(n&&n.includeBitStringContents)i=i&&e.bitStringContents===t.bitStringContents;return i};j.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 Bi(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 sS=function(e,t){var n=e.getByte();if(t--,n===128)return;var r,i=n&128;if(!i)r=n;else{var o=n&127;Bi(e,t,o),r=e.getInt(o<<3)}if(r<0)throw Error("Negative length: "+r);return r};j.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=j.maxDepth;if(typeof e==="string")e=Me.util.createBuffer(e);var n=e.length(),r=Wo(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 Wo(e,t,n,r){if(n>=r.maxDepth)throw Error("ASN.1 parsing error: Max depth exceeded.");var i;Bi(e,t,2);var o=e.getByte();t--;var s=o&192,a=o&31;i=e.length();var c=sS(e,t);if(t-=i-e.length(),c!==void 0&&c>t){if(r.strict){var u=Error("Too few bytes to read ASN.1 value.");throw u.available=e.length(),u.remaining=t,u.requested=c,u}c=t}var l,f,p=(o&32)===32;if(p)if(l=[],c===void 0)for(;;){if(Bi(e,t,2),e.bytes(2)===String.fromCharCode(0,0)){e.getBytes(2),t-=2;break}i=e.length(),l.push(Wo(e,t,n+1,r)),t-=i-e.length()}else while(c>0)i=e.length(),l.push(Wo(e,c,n+1,r)),t-=i-e.length(),c-=i-e.length();if(l===void 0&&s===j.Class.UNIVERSAL&&a===j.Type.BITSTRING)f=e.bytes(c);if(l===void 0&&r.decodeBitStrings&&s===j.Class.UNIVERSAL&&a===j.Type.BITSTRING&&c>1){var h=e.read,d=t,g=0;if(a===j.Type.BITSTRING)Bi(e,t,1),g=e.getByte(),t--;if(g===0)try{i=e.length();var v={strict:!0,decodeBitStrings:!1,maxDepth:r.maxDepth},b=Wo(e,t,n+1,v),S=i-e.length();if(t-=S,a==j.Type.BITSTRING)S++;var C=b.tagClass;if(S===c&&(C===j.Class.UNIVERSAL||C===j.Class.CONTEXT_SPECIFIC))l=[b]}catch(I){}if(l===void 0)e.read=h,t=d}if(l===void 0){if(c===void 0){if(r.strict)throw Error("Non-constructed ASN.1 object of indefinite length.");c=t}if(a===j.Type.BMPSTRING){l="";for(;c>0;c-=2)Bi(e,t,2),l+=String.fromCharCode(e.getInt16()),t-=2}else l=e.getBytes(c),t-=c}var T=f===void 0?null:{bitStringContents:f};return j.create(s,a,p,l,T)}j.toDer=function(e){var t=Me.util.createBuffer(),n=e.tagClass|e.type,r=Me.util.createBuffer(),i=!1;if("bitStringContents"in e){if(i=!0,e.original)i=j.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 o=0;o<e.value.length;++o)if(e.value[o]!==void 0)r.putBuffer(j.toDer(e.value[o]))}else if(e.type===j.Type.BMPSTRING)for(var o=0;o<e.value.length;++o)r.putInt16(e.value.charCodeAt(o));else if(e.type===j.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(),a="";do a+=String.fromCharCode(s&255),s=s>>>8;while(s>0);t.putByte(a.length|128);for(var o=a.length-1;o>=0;--o)t.putByte(a.charCodeAt(o))}return t.putBuffer(r),t};j.oidToDer=function(e){var t=e.split("."),n=Me.util.createBuffer(),r=parseInt(t[0],10),i=parseInt(t[1],10);if(!(r>=0&&r<=2&&i>=0)||r<2&&i>39)throw Error("Invalid OID; the first two arcs are out of range.");var o,s,a,c;for(var u=1;u<t.length;++u){if(o=!0,s=[],a=u===1?40*r+i:parseInt(t[u],10),a>4294967295)throw Error("OID value too large; max is 32-bits.");do{if(c=a&127,a=a>>>7,!o)c|=128;s.push(c),o=!1}while(a>0);for(var l=s.length-1;l>=0;--l)n.putByte(s[l])}return n};j.derToOid=function(e){var t;if(typeof e==="string")e=Me.util.createBuffer(e);var n,r=0,i=!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{if(r+=n,i)t=r<80?Math.floor(r/40)+"."+r%40:"2."+(r-80),i=!1;else t+="."+r;r=0}}return t};j.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),o=parseInt(e.substr(6,2),10),s=parseInt(e.substr(8,2),10),a=0;if(e.length>11){var c=e.charAt(10),u=10;if(c!=="+"&&c!=="-")a=parseInt(e.substr(10,2),10),u+=2}if(t.setUTCFullYear(n,r,i),t.setUTCHours(o,s,a,0),u){if(c=e.charAt(u),c==="+"||c==="-"){var l=parseInt(e.substr(u+1,2),10),f=parseInt(e.substr(u+4,2),10),p=l*60+f;if(p*=60000,c==="+")t.setTime(+t-p);else t.setTime(+t+p)}}return t};j.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),o=parseInt(e.substr(8,2),10),s=parseInt(e.substr(10,2),10),a=parseInt(e.substr(12,2),10),c=0,u=0,l=!1;if(e.charAt(e.length-1)==="Z")l=!0;var f=e.length-5,p=e.charAt(f);if(p==="+"||p==="-"){var h=parseInt(e.substr(f+1,2),10),d=parseInt(e.substr(f+4,2),10);if(u=h*60+d,u*=60000,p==="+")u*=-1;l=!0}if(e.charAt(14)===".")c=parseFloat(e.substr(14),10)*1000;if(l)t.setUTCFullYear(n,r,i),t.setUTCHours(o,s,a,c),t.setTime(+t+u);else t.setFullYear(n,r,i),t.setHours(o,s,a,c);return t};j.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};j.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};j.integerToDer=function(e){var t=Me.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};j.derToInteger=function(e){if(typeof e==="string")e=Me.util.createBuffer(e);var t=e.length()*8;if(t>32)throw Error("Integer too large; max is 32-bits.");return e.getSignedInt(t)};j.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&&Me.util.isArray(t.value)){var o=0;for(var s=0;i&&s<t.value.length;++s){var a=t.value[s];i=!!a.optional;var c=e.value[o];if(!c){if(!a.optional){if(i=!1,r)r.push("["+t.name+'] Missing required element. Expected tag class "'+a.tagClass+'", type "'+a.type+'"')}continue}var u=typeof a.tagClass<"u"&&typeof a.type<"u";if(u&&(c.tagClass!==a.tagClass||c.type!==a.type))if(a.optional){i=!0;continue}else{if(i=!1,r)r.push("["+t.name+"] Tag mismatch. Expected ("+a.tagClass+","+a.type+"), got ("+c.tagClass+","+c.type+")");break}var l=j.validate(c,a,n,r);if(l)++o,i=!0;else if(a.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 f;if(e.bitStringContents.length<2)n[t.captureBitStringValue]="";else{var p=e.bitStringContents.charCodeAt(0);if(p!==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 Mf=/[^\\u0000-\\u00ff]/;j.prettyPrint=function(e,t,n){var r="";if(t=t||0,n=n||2,t>0)r+=`
6
6
  `;var i="";for(var o=0;o<t*n;++o)i+=" ";switch(r+=i+"Tag: ",e.tagClass){case j.Class.UNIVERSAL:r+="Universal:";break;case j.Class.APPLICATION:r+="Application:";break;case j.Class.CONTEXT_SPECIFIC:r+="Context-Specific:";break;case j.Class.PRIVATE:r+="Private:";break}if(e.tagClass===j.Class.UNIVERSAL)switch(r+=e.type,e.type){case j.Type.NONE:r+=" (None)";break;case j.Type.BOOLEAN:r+=" (Boolean)";break;case j.Type.INTEGER:r+=" (Integer)";break;case j.Type.BITSTRING:r+=" (Bit string)";break;case j.Type.OCTETSTRING:r+=" (Octet string)";break;case j.Type.NULL:r+=" (Null)";break;case j.Type.OID:r+=" (Object Identifier)";break;case j.Type.ODESC:r+=" (Object Descriptor)";break;case j.Type.EXTERNAL:r+=" (External or Instance of)";break;case j.Type.REAL:r+=" (Real)";break;case j.Type.ENUMERATED:r+=" (Enumerated)";break;case j.Type.EMBEDDED:r+=" (Embedded PDV)";break;case j.Type.UTF8:r+=" (UTF8)";break;case j.Type.ROID:r+=" (Relative Object Identifier)";break;case j.Type.SEQUENCE:r+=" (Sequence)";break;case j.Type.SET:r+=" (Set)";break;case j.Type.PRINTABLESTRING:r+=" (Printable String)";break;case j.Type.IA5String:r+=" (IA5String (ASCII))";break;case j.Type.UTCTIME:r+=" (UTC time)";break;case j.Type.GENERALIZEDTIME:r+=" (Generalized time)";break;case j.Type.BMPSTRING:r+=" (BMP String)";break}else r+=e.type;if(r+=`
7
7
  `,r+=i+"Constructed: "+e.constructed+`
8
- `,e.composed){var s=0,a="";for(var o=0;o<e.value.length;++o)if(e.value[o]!==void 0){if(s+=1,a+=j.prettyPrint(e.value[o],t+1,n),o+1<e.value.length)a+=","}r+=i+"Sub values: "+s+a}else{if(r+=i+"Value: ",e.type===j.Type.OID){var c=j.derToOid(e.value);if(r+=c,ze.pki&&ze.pki.oids){if(c in ze.pki.oids)r+=" ("+ze.pki.oids[c]+") "}}if(e.type===j.Type.INTEGER)try{r+=j.derToInteger(e.value)}catch(l){r+="0x"+ze.util.bytesToHex(e.value)}else if(e.type===j.Type.BITSTRING){if(e.value.length>1)r+="0x"+ze.util.bytesToHex(e.value.slice(1));else r+="(none)";if(e.value.length>0){var u=e.value.charCodeAt(0);if(u==1)r+=" (1 unused bit shown)";else if(u>1)r+=" ("+u+" unused bits shown)"}}else if(e.type===j.Type.OCTETSTRING){if(!Ff.test(e.value))r+="("+e.value+") ";r+="0x"+ze.util.bytesToHex(e.value)}else if(e.type===j.Type.UTF8)try{r+=ze.util.decodeUtf8(e.value)}catch(l){if(l.message==="URI malformed")r+="0x"+ze.util.bytesToHex(e.value)+" (malformed UTF8)";else throw l}else if(e.type===j.Type.PRINTABLESTRING||e.type===j.Type.IA5String)r+=e.value;else if(Ff.test(e.value))r+="0x"+ze.util.bytesToHex(e.value);else if(e.value.length===0)r+="[null]";else r+=e.value}return r}});var ur=le(function(E2,Vf){var Ho=he();Vf.exports=Ho.md=Ho.md||{};Ho.md.algorithms=Ho.md.algorithms||{}});var On=le(function(_2,Wf){var Ar=he();ur();Te();var oS=Wf.exports=Ar.hmac=Ar.hmac||{};oS.create=function(){var e=null,t=null,n=null,r=null,i={};return i.start=function(o,s){if(o!==null)if(typeof o==="string")if(o=o.toLowerCase(),o in Ar.md.algorithms)t=Ar.md.algorithms[o].create();else throw Error('Unknown hash algorithm "'+o+'"');else t=o;if(s===null)s=e;else{if(typeof s==="string")s=Ar.util.createBuffer(s);else if(Ar.util.isArray(s)){var a=s;s=Ar.util.createBuffer();for(var c=0;c<a.length;++c)s.putByte(a[c])}var u=s.length();if(u>t.blockLength)t.start(),t.update(s.bytes()),s=t.digest();n=Ar.util.createBuffer(),r=Ar.util.createBuffer(),u=s.length();for(var c=0;c<u;++c){var a=s.at(c);n.putByte(54^a),r.putByte(92^a)}if(u<t.blockLength){var a=t.blockLength-u;for(var c=0;c<a;++c)n.putByte(54),r.putByte(92)}e=s,n=n.bytes(),r=r.bytes()}t.start(),t.update(n)},i.update=function(o){t.update(o)},i.getMac=function(){var o=t.digest().bytes();return t.start(),t.update(r),t.update(o),t.digest()},i.digest=i.getMac,i}});var Zo=le(function(T2,jf){var lr=he();ur();Te();var Kf=jf.exports=lr.md5=lr.md5||{};lr.md.md5=lr.md.algorithms.md5=Kf;Kf.create=function(){if(!Zf)sS();var e=null,t=lr.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 o=0;o<i;++o)r.fullMessageLength.push(0);return t=lr.util.createBuffer(),e={h0:1732584193,h1:4023233417,h2:2562383102,h3:271733878},r},r.start(),r.update=function(i,o){if(o==="utf8")i=lr.util.encodeUtf8(i);var s=i.length;r.messageLength+=s,s=[s/4294967296>>>0,s>>>0];for(var a=r.fullMessageLength.length-1;a>=0;--a)r.fullMessageLength[a]+=s[1],s[1]=s[0]+(r.fullMessageLength[a]/4294967296>>>0),r.fullMessageLength[a]=r.fullMessageLength[a]>>>0,s[0]=s[1]/4294967296>>>0;if(t.putBytes(i),Hf(e,n,t),t.read>2048||t.length()===0)t.compact();return r},r.digest=function(){var i=lr.util.createBuffer();i.putBytes(t.bytes());var o=r.fullMessageLength[r.fullMessageLength.length-1]+r.messageLengthSize,s=o&r.blockLength-1;i.putBytes(ac.substr(0,r.blockLength-s));var a,c=0;for(var u=r.fullMessageLength.length-1;u>=0;--u)a=r.fullMessageLength[u]*8+c,c=a/4294967296>>>0,i.putInt32Le(a>>>0);var l={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3};Hf(l,n,i);var f=lr.util.createBuffer();return f.putInt32Le(l.h0),f.putInt32Le(l.h1),f.putInt32Le(l.h2),f.putInt32Le(l.h3),f},r};var ac=null,Ko=null,Ri=null,Ln=null,Zf=!1;function sS(){ac=String.fromCharCode(128),ac+=lr.util.fillString(String.fromCharCode(0),64),Ko=[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],Ri=[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],Ln=Array(64);for(var e=0;e<64;++e)Ln[e]=Math.floor(Math.abs(Math.sin(e+1))*4294967296);Zf=!0}function Hf(e,t,n){var r,i,o,s,a,c,u,l,f=n.length();while(f>=64){i=e.h0,o=e.h1,s=e.h2,a=e.h3;for(l=0;l<16;++l)t[l]=n.getInt32Le(),c=a^o&(s^a),r=i+c+Ln[l]+t[l],u=Ri[l],i=a,a=s,s=o,o+=r<<u|r>>>32-u;for(;l<32;++l)c=s^a&(o^s),r=i+c+Ln[l]+t[Ko[l]],u=Ri[l],i=a,a=s,s=o,o+=r<<u|r>>>32-u;for(;l<48;++l)c=o^s^a,r=i+c+Ln[l]+t[Ko[l]],u=Ri[l],i=a,a=s,s=o,o+=r<<u|r>>>32-u;for(;l<64;++l)c=s^(o|~a),r=i+c+Ln[l]+t[Ko[l]],u=Ri[l],i=a,a=s,s=o,o+=r<<u|r>>>32-u;e.h0=e.h0+i|0,e.h1=e.h1+o|0,e.h2=e.h2+s|0,e.h3=e.h3+a|0,f-=64}}});var fn=le(function(A2,qf){var Go=he();Te();var Gf=qf.exports=Go.pem=Go.pem||{};Gf.encode=function(e,t){t=t||{};var n="-----BEGIN "+e.type+`-----\r
8
+ `,e.composed){var s=0,a="";for(var o=0;o<e.value.length;++o)if(e.value[o]!==void 0){if(s+=1,a+=j.prettyPrint(e.value[o],t+1,n),o+1<e.value.length)a+=","}r+=i+"Sub values: "+s+a}else{if(r+=i+"Value: ",e.type===j.Type.OID){var c=j.derToOid(e.value);if(r+=c,Me.pki&&Me.pki.oids){if(c in Me.pki.oids)r+=" ("+Me.pki.oids[c]+") "}}if(e.type===j.Type.INTEGER)try{r+=j.derToInteger(e.value)}catch(l){r+="0x"+Me.util.bytesToHex(e.value)}else if(e.type===j.Type.BITSTRING){if(e.value.length>1)r+="0x"+Me.util.bytesToHex(e.value.slice(1));else r+="(none)";if(e.value.length>0){var u=e.value.charCodeAt(0);if(u==1)r+=" (1 unused bit shown)";else if(u>1)r+=" ("+u+" unused bits shown)"}}else if(e.type===j.Type.OCTETSTRING){if(!Mf.test(e.value))r+="("+e.value+") ";r+="0x"+Me.util.bytesToHex(e.value)}else if(e.type===j.Type.UTF8)try{r+=Me.util.decodeUtf8(e.value)}catch(l){if(l.message==="URI malformed")r+="0x"+Me.util.bytesToHex(e.value)+" (malformed UTF8)";else throw l}else if(e.type===j.Type.PRINTABLESTRING||e.type===j.Type.IA5String)r+=e.value;else if(Mf.test(e.value))r+="0x"+Me.util.bytesToHex(e.value);else if(e.value.length===0)r+="[null]";else r+=e.value}return r}});var ur=le(function(E2,Wf){var Ho=he();Wf.exports=Ho.md=Ho.md||{};Ho.md.algorithms=Ho.md.algorithms||{}});var Ln=le(function(_2,Hf){var Ar=he();ur();Te();var aS=Hf.exports=Ar.hmac=Ar.hmac||{};aS.create=function(){var e=null,t=null,n=null,r=null,i={};return i.start=function(o,s){if(o!==null)if(typeof o==="string")if(o=o.toLowerCase(),o in Ar.md.algorithms)t=Ar.md.algorithms[o].create();else throw Error('Unknown hash algorithm "'+o+'"');else t=o;if(s===null)s=e;else{if(typeof s==="string")s=Ar.util.createBuffer(s);else if(Ar.util.isArray(s)){var a=s;s=Ar.util.createBuffer();for(var c=0;c<a.length;++c)s.putByte(a[c])}var u=s.length();if(u>t.blockLength)t.start(),t.update(s.bytes()),s=t.digest();n=Ar.util.createBuffer(),r=Ar.util.createBuffer(),u=s.length();for(var c=0;c<u;++c){var a=s.at(c);n.putByte(54^a),r.putByte(92^a)}if(u<t.blockLength){var a=t.blockLength-u;for(var c=0;c<a;++c)n.putByte(54),r.putByte(92)}e=s,n=n.bytes(),r=r.bytes()}t.start(),t.update(n)},i.update=function(o){t.update(o)},i.getMac=function(){var o=t.digest().bytes();return t.start(),t.update(r),t.update(o),t.digest()},i.digest=i.getMac,i}});var Zo=le(function(T2,Gf){var lr=he();ur();Te();var Zf=Gf.exports=lr.md5=lr.md5||{};lr.md.md5=lr.md.algorithms.md5=Zf;Zf.create=function(){if(!jf)cS();var e=null,t=lr.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 o=0;o<i;++o)r.fullMessageLength.push(0);return t=lr.util.createBuffer(),e={h0:1732584193,h1:4023233417,h2:2562383102,h3:271733878},r},r.start(),r.update=function(i,o){if(o==="utf8")i=lr.util.encodeUtf8(i);var s=i.length;r.messageLength+=s,s=[s/4294967296>>>0,s>>>0];for(var a=r.fullMessageLength.length-1;a>=0;--a)r.fullMessageLength[a]+=s[1],s[1]=s[0]+(r.fullMessageLength[a]/4294967296>>>0),r.fullMessageLength[a]=r.fullMessageLength[a]>>>0,s[0]=s[1]/4294967296>>>0;if(t.putBytes(i),Kf(e,n,t),t.read>2048||t.length()===0)t.compact();return r},r.digest=function(){var i=lr.util.createBuffer();i.putBytes(t.bytes());var o=r.fullMessageLength[r.fullMessageLength.length-1]+r.messageLengthSize,s=o&r.blockLength-1;i.putBytes(ac.substr(0,r.blockLength-s));var a,c=0;for(var u=r.fullMessageLength.length-1;u>=0;--u)a=r.fullMessageLength[u]*8+c,c=a/4294967296>>>0,i.putInt32Le(a>>>0);var l={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3};Kf(l,n,i);var f=lr.util.createBuffer();return f.putInt32Le(l.h0),f.putInt32Le(l.h1),f.putInt32Le(l.h2),f.putInt32Le(l.h3),f},r};var ac=null,Ko=null,Ni=null,Un=null,jf=!1;function cS(){ac=String.fromCharCode(128),ac+=lr.util.fillString(String.fromCharCode(0),64),Ko=[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],Ni=[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],Un=Array(64);for(var e=0;e<64;++e)Un[e]=Math.floor(Math.abs(Math.sin(e+1))*4294967296);jf=!0}function Kf(e,t,n){var r,i,o,s,a,c,u,l,f=n.length();while(f>=64){i=e.h0,o=e.h1,s=e.h2,a=e.h3;for(l=0;l<16;++l)t[l]=n.getInt32Le(),c=a^o&(s^a),r=i+c+Un[l]+t[l],u=Ni[l],i=a,a=s,s=o,o+=r<<u|r>>>32-u;for(;l<32;++l)c=s^a&(o^s),r=i+c+Un[l]+t[Ko[l]],u=Ni[l],i=a,a=s,s=o,o+=r<<u|r>>>32-u;for(;l<48;++l)c=o^s^a,r=i+c+Un[l]+t[Ko[l]],u=Ni[l],i=a,a=s,s=o,o+=r<<u|r>>>32-u;for(;l<64;++l)c=s^(o|~a),r=i+c+Un[l]+t[Ko[l]],u=Ni[l],i=a,a=s,s=o,o+=r<<u|r>>>32-u;e.h0=e.h0+i|0,e.h1=e.h1+o|0,e.h2=e.h2+s|0,e.h3=e.h3+a|0,f-=64}}});var fn=le(function(A2,Xf){var Go=he();Te();var qf=Xf.exports=Go.pem=Go.pem||{};qf.encode=function(e,t){t=t||{};var n="-----BEGIN "+e.type+`-----\r
9
9
  `,r;if(e.procType)r={name:"Proc-Type",values:[String(e.procType.version),e.procType.type]},n+=jo(r);if(e.contentDomain)r={name:"Content-Domain",values:[e.contentDomain]},n+=jo(r);if(e.dekInfo){if(r={name:"DEK-Info",values:[e.dekInfo.algorithm]},e.dekInfo.parameters)r.values.push(e.dekInfo.parameters);n+=jo(r)}if(e.headers)for(var i=0;i<e.headers.length;++i)n+=jo(e.headers[i]);if(e.procType)n+=`\r
10
10
  `;return n+=Go.util.encode64(e.body,t.maxline||64)+`\r
11
11
  `,n+="-----END "+e.type+`-----\r
12
- `,n};Gf.decode=function(e){var t=[];e=String(e);var n=uS(e),r=/(?:^|[^\x21-\x7e])([\x21-\x7e]+):\s*([\x21-\x7e\s^:]+)/,i=/\r?\n/,o;while(!0){if(o=n.next(),!o)break;var s=o[1];if(s==="NEW CERTIFICATE REQUEST")s="CERTIFICATE REQUEST";var a={type:s,procType:null,contentDomain:null,dekInfo:null,headers:[],body:Go.util.decode64(o[3])};if(t.push(a),!o[2])continue;var c=o[2].split(i),u=0;while(o&&u<c.length){var l=cS(c[u]);for(var f=u+1;f<c.length;++f){var p=c[f];if(!/\s/.test(p[0]))break;l+=p,u=f}if(o=l.match(r),o){var h={name:o[1],values:[]},d=o[2].split(",");for(var g=0;g<d.length;++g)h.values.push(aS(d[g]));if(!a.procType){if(h.name!=="Proc-Type")throw Error('Invalid PEM formatted message. The first encapsulated header must be "Proc-Type".');else if(h.values.length!==2)throw Error('Invalid PEM formatted message. The "Proc-Type" header must have two subfields.');a.procType={version:d[0],type:d[1]}}else if(!a.contentDomain&&h.name==="Content-Domain")a.contentDomain=d[0]||"";else if(!a.dekInfo&&h.name==="DEK-Info"){if(h.values.length===0)throw Error('Invalid PEM formatted message. The "DEK-Info" header must have at least one subfield.');a.dekInfo={algorithm:d[0],parameters:d[1]||null}}else a.headers.push(h)}++u}if(a.procType==="ENCRYPTED"&&!a.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 jo(e){var t=e.name+": ",n=[],r=function(c,u){return" "+u};for(var i=0;i<e.values.length;++i)n.push(e.values[i].replace(/^(\S+\r\n)/,r));t+=n.join(",")+`\r
12
+ `,n};qf.decode=function(e){var t=[];e=String(e);var n=fS(e),r=/(?:^|[^\x21-\x7e])([\x21-\x7e]+):\s*([\x21-\x7e\s^:]+)/,i=/\r?\n/,o;while(!0){if(o=n.next(),!o)break;var s=o[1];if(s==="NEW CERTIFICATE REQUEST")s="CERTIFICATE REQUEST";var a={type:s,procType:null,contentDomain:null,dekInfo:null,headers:[],body:Go.util.decode64(o[3])};if(t.push(a),!o[2])continue;var c=o[2].split(i),u=0;while(o&&u<c.length){var l=lS(c[u]);for(var f=u+1;f<c.length;++f){var p=c[f];if(!/\s/.test(p[0]))break;l+=p,u=f}if(o=l.match(r),o){var h={name:o[1],values:[]},d=o[2].split(",");for(var g=0;g<d.length;++g)h.values.push(uS(d[g]));if(!a.procType){if(h.name!=="Proc-Type")throw Error('Invalid PEM formatted message. The first encapsulated header must be "Proc-Type".');else if(h.values.length!==2)throw Error('Invalid PEM formatted message. The "Proc-Type" header must have two subfields.');a.procType={version:d[0],type:d[1]}}else if(!a.contentDomain&&h.name==="Content-Domain")a.contentDomain=d[0]||"";else if(!a.dekInfo&&h.name==="DEK-Info"){if(h.values.length===0)throw Error('Invalid PEM formatted message. The "DEK-Info" header must have at least one subfield.');a.dekInfo={algorithm:d[0],parameters:d[1]||null}}else a.headers.push(h)}++u}if(a.procType==="ENCRYPTED"&&!a.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 jo(e){var t=e.name+": ",n=[],r=function(c,u){return" "+u};for(var i=0;i<e.values.length;++i)n.push(e.values[i].replace(/^(\S+\r\n)/,r));t+=n.join(",")+`\r
13
13
  `;var o=0,s=-1;for(var i=0;i<t.length;++i,++o)if(o>65&&s!==-1){var a=t[s];if(a===",")++s,t=t.substr(0,s)+`\r
14
14
  `+t.substr(s);else t=t.substr(0,s)+`\r
15
- `+a+t.substr(s+1);o=i-s-1,s=-1,++i}else if(t[i]===" "||t[i]==="\t"||t[i]===",")s=i;return t}function aS(e){return e.replace(/^\s+/,"")}function cS(e){var t=e.length;while(t>0&&/\s/.test(e.charAt(t-1)))--t;return e.substring(0,t)}function uS(e){var t=/[:A-Za-z0-9+\/=\s]/,n=/[^:A-Za-z0-9+\/=\s]/g,r=/[^\x21-\x7e\s]/g,i=/[A-Z0-9- ]/;function o(b,S){b.lastIndex=S;var C=b.exec(e);return C?C.index:e.length}function s(b){for(var S=b;S<e.length&&i.test(e.charAt(S));++S)if(S>b&&e.substr(S,5)==="-----")return e.substring(b,S);return null}function a(b){if(e.charAt(b)==="\r")++b;if(e.charAt(b)!==`
15
+ `+a+t.substr(s+1);o=i-s-1,s=-1,++i}else if(t[i]===" "||t[i]==="\t"||t[i]===",")s=i;return t}function uS(e){return e.replace(/^\s+/,"")}function lS(e){var t=e.length;while(t>0&&/\s/.test(e.charAt(t-1)))--t;return e.substring(0,t)}function fS(e){var t=/[:A-Za-z0-9+\/=\s]/,n=/[^:A-Za-z0-9+\/=\s]/g,r=/[^\x21-\x7e\s]/g,i=/[A-Z0-9- ]/;function o(b,S){b.lastIndex=S;var C=b.exec(e);return C?C.index:e.length}function s(b){for(var S=b;S<e.length&&i.test(e.charAt(S));++S)if(S>b&&e.substr(S,5)==="-----")return e.substring(b,S);return null}function a(b){if(e.charAt(b)==="\r")++b;if(e.charAt(b)!==`
16
16
  `)return-1;if(e.charAt(++b)==="\r")++b;return e.charAt(b)===`
17
- `?b+1:-1}function c(b,S){for(var C=b;C<S;++C){var T=a(C);if(T!==-1&&T<S)return C}return-1}var u={};for(var l=e.indexOf("-----END ");l!==-1;l=e.indexOf("-----END ",l+1)){var f=s(l+9),p=l;while(p>0&&t.test(e.charAt(p-1)))--p;var h=c(p,l);if(f!==null&&h!==-1){var d="$"+f;(u[d]=u[d]||[]).push({end:l,blank:h})}}var g=0,x=-1;return{next:function(){var b;while((b=e.indexOf("-----BEGIN ",g))!==-1){g=b+1;var S=s(b+11);if(S===null)continue;var C=b+16+S.length,T=o(n,C),I=e.substr(T,9)==="-----END "&&s(T+9)===S;if(C>x)x=o(r,C);var k=null,R=u["$"+S];if(R){var V=0,D=R.length;while(V<D){var F=V+D>>1;if(R[F].end>T)D=F;else V=F+1}k=R[V]||null}var H=[];if(e.charAt(C)==="\r"){if(e.charAt(C+1)===`
17
+ `?b+1:-1}function c(b,S){for(var C=b;C<S;++C){var T=a(C);if(T!==-1&&T<S)return C}return-1}var u={};for(var l=e.indexOf("-----END ");l!==-1;l=e.indexOf("-----END ",l+1)){var f=s(l+9),p=l;while(p>0&&t.test(e.charAt(p-1)))--p;var h=c(p,l);if(f!==null&&h!==-1){var d="$"+f;(u[d]=u[d]||[]).push({end:l,blank:h})}}var g=0,v=-1;return{next:function(){var b;while((b=e.indexOf("-----BEGIN ",g))!==-1){g=b+1;var S=s(b+11);if(S===null)continue;var C=b+16+S.length,T=o(n,C),I=e.substr(T,9)==="-----END "&&s(T+9)===S;if(C>v)v=o(r,C);var k=null,R=u["$"+S];if(R){var V=0,D=R.length;while(V<D){var F=V+D>>1;if(R[F].end>T)D=F;else V=F+1}k=R[V]||null}var H=[];if(e.charAt(C)==="\r"){if(e.charAt(C+1)===`
18
18
  `)H.push(C+2);H.push(C+1)}else if(e.charAt(C)===`
19
- `)H.push(C+1);H.push(C);for(var re=0;re<H.length;++re){var se=H[re],Pe=I?c(se+1,T):-1,ue=T;if(Pe===-1&&k)Pe=k.blank,ue=k.end;if(Pe!==-1&&Pe<=x){var de=a(Pe);return g=ue+14+S.length,[e.substring(b,g),S,e.substring(se,de),e.substring(de,ue)]}if(I&&se<T)return g=T+14+S.length,[e.substring(b,g),S,void 0,e.substring(se,T)]}}return null}}}});var Bi=le(function(k2,Jf){var Ke=he();zo();rc();Te();Jf.exports=Ke.des=Ke.des||{};Ke.des.startEncrypting=function(e,t,n,r){var i=qo({key:e,output:n,decrypt:!1,mode:r||(t===null?"ECB":"CBC")});return i.start(t),i};Ke.des.createEncryptionCipher=function(e,t){return qo({key:e,output:null,decrypt:!1,mode:t})};Ke.des.startDecrypting=function(e,t,n,r){var i=qo({key:e,output:n,decrypt:!0,mode:r||(t===null?"ECB":"CBC")});return i.start(t),i};Ke.des.createDecryptionCipher=function(e,t){return qo({key:e,output:null,decrypt:!0,mode:t})};Ke.des.Algorithm=function(e,t){var n=this;n.name=e,n.mode=new t({blockSize:8,cipher:{encrypt:function(r,i){return Xf(n._keys,r,i,!1)},decrypt:function(r,i){return Xf(n._keys,r,i,!0)}}}),n._init=!1};Ke.des.Algorithm.prototype.initialize=function(e){if(this._init)return;var t=Ke.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=vS(t),this._init=!0};fr("DES-ECB",Ke.cipher.modes.ecb);fr("DES-CBC",Ke.cipher.modes.cbc);fr("DES-CFB",Ke.cipher.modes.cfb);fr("DES-OFB",Ke.cipher.modes.ofb);fr("DES-CTR",Ke.cipher.modes.ctr);fr("3DES-ECB",Ke.cipher.modes.ecb);fr("3DES-CBC",Ke.cipher.modes.cbc);fr("3DES-CFB",Ke.cipher.modes.cfb);fr("3DES-OFB",Ke.cipher.modes.ofb);fr("3DES-CTR",Ke.cipher.modes.ctr);function fr(e,t){var n=function(){return new Ke.des.Algorithm(e,t)};Ke.cipher.registerAlgorithm(e,n)}var lS=[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],fS=[-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],dS=[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],pS=[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],hS=[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],mS=[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],gS=[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],yS=[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 vS(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],o=[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],a=[0,268435456,524288,268959744,2,268435458,524290,268959746,0,268435456,524288,268959744,2,268435458,524290,268959746],c=[0,65536,2048,67584,536870912,536936448,536872960,536938496,131072,196608,133120,198656,537001984,537067520,537004032,537069568],u=[0,262144,0,262144,2,262146,2,262146,33554432,33816576,33554432,33816576,33554434,33816578,33554434,33816578],l=[0,268435456,8,268435464,0,268435456,8,268435464,1024,268436480,1032,268436488,1024,268436480,1032,268436488],f=[0,32,0,32,1048576,1048608,1048576,1048608,8192,8224,8192,8224,1056768,1056800,1056768,1056800],p=[0,16777216,512,16777728,2097152,18874368,2097664,18874880,67108864,83886080,67109376,83886592,69206016,85983232,69206528,85983744],h=[0,4096,134217728,134221824,524288,528384,134742016,134746112,16,4112,134217744,134221840,524304,528400,134742032,134746128],d=[0,4,256,260,0,4,256,260,1,5,257,261,1,5,257,261],g=e.length()>8?3:1,x=[],b=[0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0],S=0,C;for(var T=0;T<g;T++){var I=e.getInt32(),k=e.getInt32();C=(I>>>4^k)&252645135,k^=C,I^=C<<4,C=(k>>>-16^I)&65535,I^=C,k^=C<<-16,C=(I>>>2^k)&858993459,k^=C,I^=C<<2,C=(k>>>-16^I)&65535,I^=C,k^=C<<-16,C=(I>>>1^k)&1431655765,k^=C,I^=C<<1,C=(k>>>8^I)&16711935,I^=C,k^=C<<8,C=(I>>>1^k)&1431655765,k^=C,I^=C<<1,C=I<<8|k>>>20&240,I=k<<24|k<<8&16711680|k>>>8&65280|k>>>24&240,k=C;for(var R=0;R<b.length;++R){if(b[R])I=I<<2|I>>>26,k=k<<2|k>>>26;else I=I<<1|I>>>27,k=k<<1|k>>>27;I&=-15,k&=-15;var V=t[I>>>28]|n[I>>>24&15]|r[I>>>20&15]|i[I>>>16&15]|o[I>>>12&15]|s[I>>>8&15]|a[I>>>4&15],D=c[k>>>28]|u[k>>>24&15]|l[k>>>20&15]|f[k>>>16&15]|p[k>>>12&15]|h[k>>>8&15]|d[k>>>4&15];C=(D>>>16^V)&65535,x[S++]=V^C,x[S++]=D^C<<16}}return x}function Xf(e,t,n,r){var i=e.length===32?3:9,o;if(i===3)o=r?[30,-2,-2]:[0,32,2];else o=r?[94,62,-2,32,64,2,30,-2,-2]:[0,32,2,62,30,-2,64,96,2];var s,a=t[0],c=t[1];s=(a>>>4^c)&252645135,c^=s,a^=s<<4,s=(a>>>16^c)&65535,c^=s,a^=s<<16,s=(c>>>2^a)&858993459,a^=s,c^=s<<2,s=(c>>>8^a)&16711935,a^=s,c^=s<<8,s=(a>>>1^c)&1431655765,c^=s,a^=s<<1,a=a<<1|a>>>31,c=c<<1|c>>>31;for(var u=0;u<i;u+=3){var l=o[u+1],f=o[u+2];for(var p=o[u];p!=l;p+=f){var h=c^e[p],d=(c>>>4|c<<28)^e[p+1];s=a,a=c,c=s^(fS[h>>>24&63]|pS[h>>>16&63]|mS[h>>>8&63]|yS[h&63]|lS[d>>>24&63]|dS[d>>>16&63]|hS[d>>>8&63]|gS[d&63])}s=a,a=c,c=s}a=a>>>1|a<<31,c=c>>>1|c<<31,s=(a>>>1^c)&1431655765,c^=s,a^=s<<1,s=(c>>>8^a)&16711935,a^=s,c^=s<<8,s=(c>>>2^a)&858993459,a^=s,c^=s<<2,s=(a>>>16^c)&65535,c^=s,a^=s<<16,s=(a>>>4^c)&252645135,c^=s,a^=s<<4,n[0]=a,n[1]=c}function qo(e){e=e||{};var t=(e.mode||"CBC").toUpperCase(),n="DES-"+t,r;if(e.decrypt)r=Ke.cipher.createDecipher(n,e.key);else r=Ke.cipher.createCipher(n,e.key);var i=r.start;return r.start=function(o,s){var a=null;if(s instanceof Ke.util.ByteBuffer)a=s,s={};s=s||{},s.output=a,s.iv=o,i.call(r,s)},r}});var Xo=le(function(I2,Qf){var St=he();On();ur();Te();var xS=St.pkcs5=St.pkcs5||{},kr;if(St.util.isNodejs&&!St.options.usePureJavaScript)kr=Ci("crypto");Qf.exports=St.pbkdf2=xS.pbkdf2=function(e,t,n,r,i,o){if(typeof i==="function")o=i,i=null;if(St.util.isNodejs&&!St.options.usePureJavaScript&&kr.pbkdf2&&(i===null||typeof i!=="object")&&(kr.pbkdf2Sync.length>4||(!i||i==="sha1"))){if(typeof i!=="string")i="sha1";if(e=Buffer.from(e,"binary"),t=Buffer.from(t,"binary"),!o){if(kr.pbkdf2Sync.length===4)return kr.pbkdf2Sync(e,t,n,r).toString("binary");return kr.pbkdf2Sync(e,t,n,r,i).toString("binary")}if(kr.pbkdf2Sync.length===4)return kr.pbkdf2(e,t,n,r,function(C,T){if(C)return o(C);o(null,T.toString("binary"))});return kr.pbkdf2(e,t,n,r,i,function(C,T){if(C)return o(C);o(null,T.toString("binary"))})}if(typeof i>"u"||i===null)i="sha1";if(typeof i==="string"){if(!(i in St.md.algorithms))throw Error("Unknown hash algorithm: "+i);i=St.md[i].create()}var s=i.digestLength;if(r>4294967295*s){var a=Error("Derived key is too long.");if(o)return o(a);throw a}var c=Math.ceil(r/s),u=r-(c-1)*s,l=St.hmac.create();l.start(i,e);var f="",p,h,d;if(!o){for(var g=1;g<=c;++g){l.start(null,null),l.update(t),l.update(St.util.int32ToBytes(g)),p=d=l.digest().getBytes();for(var x=2;x<=n;++x)l.start(null,null),l.update(d),h=l.digest().getBytes(),p=St.util.xorBytes(p,h,s),d=h;f+=g<c?p:p.substr(0,u)}return f}var g=1,x;function b(){if(g>c)return o(null,f);l.start(null,null),l.update(t),l.update(St.util.int32ToBytes(g)),p=d=l.digest().getBytes(),x=2,S()}function S(){if(x<=n)return l.start(null,null),l.update(d),h=l.digest().getBytes(),p=St.util.xorBytes(p,h,s),d=h,++x,St.util.setImmediate(S);f+=g<c?p:p.substr(0,u),++g,b()}b()}});var uc=le(function(P2,nd){var dr=he();ur();Te();var ed=nd.exports=dr.sha256=dr.sha256||{};dr.md.sha256=dr.md.algorithms.sha256=ed;ed.create=function(){if(!td)bS();var e=null,t=dr.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 o=0;o<i;++o)r.fullMessageLength.push(0);return t=dr.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,o){if(o==="utf8")i=dr.util.encodeUtf8(i);var s=i.length;r.messageLength+=s,s=[s/4294967296>>>0,s>>>0];for(var a=r.fullMessageLength.length-1;a>=0;--a)r.fullMessageLength[a]+=s[1],s[1]=s[0]+(r.fullMessageLength[a]/4294967296>>>0),r.fullMessageLength[a]=r.fullMessageLength[a]>>>0,s[0]=s[1]/4294967296>>>0;if(t.putBytes(i),Yf(e,n,t),t.read>2048||t.length()===0)t.compact();return r},r.digest=function(){var i=dr.util.createBuffer();i.putBytes(t.bytes());var o=r.fullMessageLength[r.fullMessageLength.length-1]+r.messageLengthSize,s=o&r.blockLength-1;i.putBytes(cc.substr(0,r.blockLength-s));var a,c,u=r.fullMessageLength[0]*8;for(var l=0;l<r.fullMessageLength.length-1;++l)a=r.fullMessageLength[l+1]*8,c=a/4294967296>>>0,u+=c,i.putInt32(u>>>0),u=a>>>0;i.putInt32(u);var f={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3,h4:e.h4,h5:e.h5,h6:e.h6,h7:e.h7};Yf(f,n,i);var p=dr.util.createBuffer();return p.putInt32(f.h0),p.putInt32(f.h1),p.putInt32(f.h2),p.putInt32(f.h3),p.putInt32(f.h4),p.putInt32(f.h5),p.putInt32(f.h6),p.putInt32(f.h7),p},r};var cc=null,td=!1,rd=null;function bS(){cc=String.fromCharCode(128),cc+=dr.util.fillString(String.fromCharCode(0),64),rd=[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],td=!0}function Yf(e,t,n){var r,i,o,s,a,c,u,l,f,p,h,d,g,x,b,S=n.length();while(S>=64){for(u=0;u<16;++u)t[u]=n.getInt32();for(;u<64;++u)r=t[u-2],r=(r>>>17|r<<15)^(r>>>19|r<<13)^r>>>10,i=t[u-15],i=(i>>>7|i<<25)^(i>>>18|i<<14)^i>>>3,t[u]=r+t[u-7]+i+t[u-16]|0;l=e.h0,f=e.h1,p=e.h2,h=e.h3,d=e.h4,g=e.h5,x=e.h6,b=e.h7;for(u=0;u<64;++u)s=(d>>>6|d<<26)^(d>>>11|d<<21)^(d>>>25|d<<7),a=x^d&(g^x),o=(l>>>2|l<<30)^(l>>>13|l<<19)^(l>>>22|l<<10),c=l&f|p&(l^f),r=b+s+a+rd[u]+t[u],i=o+c,b=x,x=g,g=d,d=h+r>>>0,h=p,p=f,f=l,l=r+i>>>0;e.h0=e.h0+l|0,e.h1=e.h1+f|0,e.h2=e.h2+p|0,e.h3=e.h3+h|0,e.h4=e.h4+d|0,e.h5=e.h5+g|0,e.h6=e.h6+x|0,e.h7=e.h7+b|0,S-=64}}});var lc=le(function(R2,id){var pr=he();Te();var Jo=null;if(pr.util.isNodejs&&!pr.options.usePureJavaScript&&!process.versions["node-webkit"])Jo=Ci("crypto");var SS=id.exports=pr.prng=pr.prng||{};SS.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(u,l){if(!l)return t.generateSync(u);var f=t.plugin.cipher,p=t.plugin.increment,h=t.plugin.formatKey,d=t.plugin.formatSeed,g=pr.util.createBuffer();t.key=null,x();function x(b){if(b)return l(b);if(g.length()>=u)return l(null,g.getBytes(u));if(t.generated>1048575)t.key=null;if(t.key===null)return pr.util.nextTick(function(){o(x)});var S=f(t.key,t.seed);t.generated+=S.length,g.putBytes(S),t.key=h(f(t.key,p(t.seed))),t.seed=d(f(t.key,t.seed)),pr.util.setImmediate(x)}},t.generateSync=function(u){var l=t.plugin.cipher,f=t.plugin.increment,p=t.plugin.formatKey,h=t.plugin.formatSeed;t.key=null;var d=pr.util.createBuffer();while(d.length()<u){if(t.generated>1048575)t.key=null;if(t.key===null)s();var g=l(t.key,t.seed);t.generated+=g.length,d.putBytes(g),t.key=p(l(t.key,f(t.seed))),t.seed=h(l(t.key,t.seed))}return d.getBytes(u)};function o(u){if(t.pools[0].messageLength>=32)return a(),u();var l=32-t.pools[0].messageLength<<5;t.seedFile(l,function(f,p){if(f)return u(f);t.collect(p),a(),u()})}function s(){if(t.pools[0].messageLength>=32)return a();var u=32-t.pools[0].messageLength<<5;t.collect(t.seedFileSync(u)),a()}function a(){t.reseeds=t.reseeds===4294967295?0:t.reseeds+1;var u=t.plugin.md.create();u.update(t.keyBytes);var l=1;for(var f=0;f<32;++f){if(t.reseeds%l===0)u.update(t.pools[f].digest().getBytes()),t.pools[f].start();l=l<<1}t.keyBytes=u.digest().getBytes(),u.start(),u.update(t.keyBytes);var p=u.digest().getBytes();t.key=t.plugin.formatKey(t.keyBytes),t.seed=t.plugin.formatSeed(p),t.generated=0}function c(u){var l=null,f=pr.util.globalScope,p=f.crypto||f.msCrypto;if(p&&p.getRandomValues)l=function(I){return p.getRandomValues(I)};var h=pr.util.createBuffer();if(l)while(h.length()<u){var d=Math.max(1,Math.min(u-h.length(),65536)/4),g=new Uint32Array(Math.floor(d));try{l(g);for(var x=0;x<g.length;++x)h.putInt32(g[x])}catch(I){if(!(typeof QuotaExceededError<"u"&&I instanceof QuotaExceededError))throw I}}if(h.length()<u){var b,S,C,T=Math.floor(Math.random()*65536);while(h.length()<u){S=16807*(T&65535),b=16807*(T>>16),S+=(b&32767)<<16,S+=b>>15,S=(S&2147483647)+(S>>31),T=S&4294967295;for(var x=0;x<3;++x)C=T>>>(x<<3),C^=Math.floor(Math.random()*256),h.putByte(C&255)}}return h.getBytes(u)}if(Jo)t.seedFile=function(u,l){Jo.randomBytes(u,function(f,p){if(f)return l(f);l(null,p.toString("binary"))})},t.seedFileSync=function(u){return Jo.randomBytes(u).toString("binary")};else t.seedFile=function(u,l){try{l(null,c(u))}catch(f){l(f)}},t.seedFileSync=c;return t.collect=function(u){var l=u.length;for(var f=0;f<l;++f)t.pools[t.pool].update(u.substr(f,1)),t.pool=t.pool===31?0:t.pool+1},t.collectInt=function(u,l){var f="";for(var p=0;p<l;p+=8)f+=String.fromCharCode(u>>p&255);t.collect(f)},t.registerWorker=function(u){if(u===self)t.seedFile=function(f,p){function h(d){var g=d.data;if(g.forge&&g.forge.prng)self.removeEventListener("message",h),p(g.forge.prng.err,g.forge.prng.bytes)}self.addEventListener("message",h),self.postMessage({forge:{prng:{needed:f}}})};else{var l=function(f){var p=f.data;if(p.forge&&p.forge.prng)t.seedFile(p.forge.prng.needed,function(h,d){u.postMessage({forge:{prng:{err:h,bytes:d}}})})};u.addEventListener("message",l)}},t}});var Ft=le(function(B2,fc){var ft=he();Vr();uc();lc();Te();(function(){if(ft.random&&ft.random.getBytes){fc.exports=ft.random;return}(function(e){var t={},n=[,,,,],r=ft.util.createBuffer();t.formatKey=function(f){var p=ft.util.createBuffer(f);return f=[,,,,],f[0]=p.getInt32(),f[1]=p.getInt32(),f[2]=p.getInt32(),f[3]=p.getInt32(),ft.aes._expandKey(f,!1)},t.formatSeed=function(f){var p=ft.util.createBuffer(f);return f=[,,,,],f[0]=p.getInt32(),f[1]=p.getInt32(),f[2]=p.getInt32(),f[3]=p.getInt32(),f},t.cipher=function(f,p){return ft.aes._updateBlock(f,p,n,!1),r.putInt32(n[0]),r.putInt32(n[1]),r.putInt32(n[2]),r.putInt32(n[3]),r.getBytes()},t.increment=function(f){return++f[3],f},t.md=ft.md.sha256;function i(){var f=ft.prng.create(t);return f.getBytes=function(p,h){return f.generate(p,h)},f.getBytesSync=function(p){return f.generate(p)},f}var o=i(),s=null,a=ft.util.globalScope,c=a.crypto||a.msCrypto;if(c&&c.getRandomValues)s=function(f){return c.getRandomValues(f)};if(ft.options.usePureJavaScript||!ft.util.isNodejs&&!s){if(typeof window>"u"||window.document===void 0);if(o.collectInt(+new Date,32),typeof navigator<"u"){var u="";for(var l in navigator)try{if(typeof navigator[l]=="string")u+=navigator[l]}catch(f){}o.collect(u),u=null}if(e)e().mousemove(function(f){o.collectInt(f.clientX,16),o.collectInt(f.clientY,16)}),e().keypress(function(f){o.collectInt(f.charCode,8)})}if(!ft.random)ft.random=o;else for(var l in o)ft.random[l]=o[l];ft.random.createInstance=i,fc.exports=ft.random})(typeof jQuery<"u"?jQuery:null)})()});var pc=le(function(N2,ad){var kt=he();Te();var dc=[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],od=[1,2,3,5],CS=function(e,t){return e<<t&65535|(e&65535)>>16-t},wS=function(e,t){return(e&65535)>>t|e<<16-t&65535};ad.exports=kt.rc2=kt.rc2||{};kt.rc2.expandKey=function(e,t){if(typeof e==="string")e=kt.util.createBuffer(e);t=t||128;var n=e,r=e.length(),i=t,o=Math.ceil(i/8),s=255>>(-i&7),a;for(a=r;a<128;a++)n.putByte(dc[n.at(a-1)+n.at(a-r)&255]);n.setAt(128-o,dc[n.at(128-o)&s]);for(a=127-o;a>=0;a--)n.setAt(a,dc[n.at(a+1)^n.at(a+o)]);return n};var sd=function(e,t,n){var r=!1,i=null,o=null,s=null,a,c,u,l,f=[];e=kt.rc2.expandKey(e,t);for(u=0;u<64;u++)f.push(e.getInt16Le());if(n)a=function(d){for(u=0;u<4;u++)d[u]+=f[l]+(d[(u+3)%4]&d[(u+2)%4])+(~d[(u+3)%4]&d[(u+1)%4]),d[u]=CS(d[u],od[u]),l++},c=function(d){for(u=0;u<4;u++)d[u]+=f[d[(u+3)%4]&63]};else a=function(d){for(u=3;u>=0;u--)d[u]=wS(d[u],od[u]),d[u]-=f[l]+(d[(u+3)%4]&d[(u+2)%4])+(~d[(u+3)%4]&d[(u+1)%4]),l--},c=function(d){for(u=3;u>=0;u--)d[u]-=f[d[(u+3)%4]&63]};var p=function(d){var g=[];for(u=0;u<4;u++){var x=i.getInt16Le();if(s!==null)if(n)x^=s.getInt16Le();else s.putInt16Le(x);g.push(x&65535)}l=n?0:63;for(var b=0;b<d.length;b++)for(var S=0;S<d[b][0];S++)d[b][1](g);for(u=0;u<4;u++){if(s!==null)if(n)s.putInt16Le(g[u]);else g[u]^=s.getInt16Le();o.putInt16Le(g[u])}},h=null;return h={start:function(d,g){if(d){if(typeof d==="string")d=kt.util.createBuffer(d)}r=!1,i=kt.util.createBuffer(),o=g||new kt.util.createBuffer,s=d,h.output=o},update:function(d){if(!r)i.putBuffer(d);while(i.length()>=8)p([[5,a],[1,c],[6,a],[1,c],[5,a]])},finish:function(d){var g=!0;if(n)if(d)g=d(8,i,!n);else{var x=i.length()===8?8:8-i.length();i.fillWithByte(x,x)}if(g)r=!0,h.update();if(!n){if(g=i.length()===0,g)if(d)g=d(8,o,!n);else{var b=o.length(),S=o.at(b-1);if(S>b)g=!1;else o.truncate(S)}}return g}},h};kt.rc2.startEncrypting=function(e,t,n){var r=kt.rc2.createEncryptionCipher(e,128);return r.start(t,n),r};kt.rc2.createEncryptionCipher=function(e,t){return sd(e,t,!0)};kt.rc2.startDecrypting=function(e,t,n){var r=kt.rc2.createDecryptionCipher(e,128);return r.start(t,n),r};kt.rc2.createDecryptionCipher=function(e,t){return sd(e,t,!1)}});var Di=le(function(D2,md){var Qo=he();Te();md.exports=Qo.jsbn=Qo.jsbn||{};var Ir,ES=244837814094590,cd=(ES&16777215)==15715070;function L(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)}Qo.jsbn.BigInteger=L;function Ae(){return new L(null)}function _S(e,t,n,r,i,o){while(--o>=0){var s=t*this.data[e++]+n.data[r]+i;i=Math.floor(s/67108864),n.data[r++]=s&67108863}return i}function TS(e,t,n,r,i,o){var s=t&32767,a=t>>15;while(--o>=0){var c=this.data[e]&32767,u=this.data[e++]>>15,l=a*c+u*s;c=s*c+((l&32767)<<15)+n.data[r]+(i&1073741823),i=(c>>>30)+(l>>>15)+a*u+(i>>>30),n.data[r++]=c&1073741823}return i}function ud(e,t,n,r,i,o){var s=t&16383,a=t>>14;while(--o>=0){var c=this.data[e]&16383,u=this.data[e++]>>14,l=a*c+u*s;c=s*c+((l&16383)<<14)+n.data[r]+i,i=(c>>28)+(l>>14)+a*u,n.data[r++]=c&268435455}return i}if(Qo.util.isNodejs)L.prototype.am=ud,Ir=28;else if(cd&&navigator.appName=="Microsoft Internet Explorer")L.prototype.am=TS,Ir=30;else if(cd&&navigator.appName!="Netscape")L.prototype.am=_S,Ir=26;else L.prototype.am=ud,Ir=28;L.prototype.DB=Ir;L.prototype.DM=(1<<Ir)-1;L.prototype.DV=1<<Ir;var hc=52;L.prototype.FV=Math.pow(2,hc);L.prototype.F1=hc-Ir;L.prototype.F2=2*Ir-hc;var AS="0123456789abcdefghijklmnopqrstuvwxyz",Yo=[],Un,Mt;Un=48;for(Mt=0;Mt<=9;++Mt)Yo[Un++]=Mt;Un=97;for(Mt=10;Mt<36;++Mt)Yo[Un++]=Mt;Un=65;for(Mt=10;Mt<36;++Mt)Yo[Un++]=Mt;function ld(e){return AS.charAt(e)}function fd(e,t){var n=Yo[e.charCodeAt(t)];return n==null?-1:n}function kS(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 IS(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 Hr(e){var t=Ae();return t.fromInt(e),t}function PS(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,o=0;while(--r>=0){var s=n==8?e[r]&255:fd(e,r);if(s<0){if(e.charAt(r)=="-")i=!0;continue}if(i=!1,o==0)this.data[this.t++]=s;else if(o+n>this.DB)this.data[this.t-1]|=(s&(1<<this.DB-o)-1)<<o,this.data[this.t++]=s>>this.DB-o;else this.data[this.t-1]|=s<<o;if(o+=n,o>=this.DB)o-=this.DB}if(n==8&&(e[0]&128)!=0){if(this.s=-1,o>0)this.data[this.t-1]|=(1<<this.DB-o)-1<<o}if(this.clamp(),i)L.ZERO.subTo(this,this)}function RS(){var e=this.s&this.DM;while(this.t>0&&this.data[this.t-1]==e)--this.t}function BS(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,o="",s=this.t,a=this.DB-s*this.DB%t;if(s-- >0){if(a<this.DB&&(r=this.data[s]>>a)>0)i=!0,o=ld(r);while(s>=0){if(a<t)r=(this.data[s]&(1<<a)-1)<<t-a,r|=this.data[--s]>>(a+=this.DB-t);else if(r=this.data[s]>>(a-=t)&n,a<=0)a+=this.DB,--s;if(r>0)i=!0;if(i)o+=ld(r)}}return i?o:"0"}function NS(){var e=Ae();return L.ZERO.subTo(this,e),e}function DS(){return this.s<0?this.negate():this}function $S(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 es(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 OS(){if(this.t<=0)return 0;return this.DB*(this.t-1)+es(this.data[this.t-1]^this.s&this.DM)}function LS(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 US(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 zS(e,t){var n=e%this.DB,r=this.DB-n,i=(1<<r)-1,o=Math.floor(e/this.DB),s=this.s<<n&this.DM,a;for(a=this.t-1;a>=0;--a)t.data[a+o+1]=this.data[a]>>r|s,s=(this.data[a]&i)<<n;for(a=o-1;a>=0;--a)t.data[a]=0;t.data[o]=s,t.t=this.t+o+1,t.s=this.s,t.clamp()}function FS(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,o=(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]&o)<<i,t.data[s-n]=this.data[s]>>r;if(r>0)t.data[this.t-n-1]|=(this.s&o)<<i;t.t=this.t-n,t.clamp()}function MS(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 VS(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)L.ZERO.subTo(t,t)}function WS(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 HS(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=Ae();var o=Ae(),s=this.s,a=e.s,c=this.DB-es(r.data[r.t-1]);if(c>0)r.lShiftTo(c,o),i.lShiftTo(c,n);else r.copyTo(o),i.copyTo(n);var u=o.t,l=o.data[u-1];if(l==0)return;var f=l*(1<<this.F1)+(u>1?o.data[u-2]>>this.F2:0),p=this.FV/f,h=(1<<this.F1)/f,d=1<<this.F2,g=n.t,x=g-u,b=t==null?Ae():t;if(o.dlShiftTo(x,b),n.compareTo(b)>=0)n.data[n.t++]=1,n.subTo(b,n);L.ONE.dlShiftTo(u,b),b.subTo(o,o);while(o.t<u)o.data[o.t++]=0;while(--x>=0){var S=n.data[--g]==l?this.DM:Math.floor(n.data[g]*p+(n.data[g-1]+d)*h);if((n.data[g]+=o.am(0,S,n,x,0,u))<S){o.dlShiftTo(x,b),n.subTo(b,n);while(n.data[g]<--S)n.subTo(b,n)}}if(t!=null){if(n.drShiftTo(u,t),s!=a)L.ZERO.subTo(t,t)}if(n.t=u,n.clamp(),c>0)n.rShiftTo(c,n);if(s<0)L.ZERO.subTo(n,n)}function KS(e){var t=Ae();if(this.abs().divRemTo(e,null,t),this.s<0&&t.compareTo(L.ZERO)>0)e.subTo(t,t);return t}function dn(e){this.m=e}function ZS(e){if(e.s<0||e.compareTo(this.m)>=0)return e.mod(this.m);else return e}function jS(e){return e}function GS(e){e.divRemTo(this.m,null,e)}function qS(e,t,n){e.multiplyTo(t,n),this.reduce(n)}function XS(e,t){e.squareTo(t),this.reduce(t)}dn.prototype.convert=ZS;dn.prototype.revert=jS;dn.prototype.reduce=GS;dn.prototype.mulTo=qS;dn.prototype.sqrTo=XS;function JS(){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 pn(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 QS(e){var t=Ae();if(e.abs().dlShiftTo(this.m.t,t),t.divRemTo(this.m,null,t),e.s<0&&t.compareTo(L.ZERO)>0)this.m.subTo(t,t);return t}function YS(e){var t=Ae();return e.copyTo(t),this.reduce(t),t}function eC(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 tC(e,t){e.squareTo(t),this.reduce(t)}function rC(e,t,n){e.multiplyTo(t,n),this.reduce(n)}pn.prototype.convert=QS;pn.prototype.revert=YS;pn.prototype.reduce=eC;pn.prototype.mulTo=rC;pn.prototype.sqrTo=tC;function nC(){return(this.t>0?this.data[0]&1:this.s)==0}function iC(e,t){if(e>4294967295||e<1)return L.ONE;var n=Ae(),r=Ae(),i=t.convert(this),o=es(e)-1;i.copyTo(n);while(--o>=0)if(t.sqrTo(n,r),(e&1<<o)>0)t.mulTo(r,i,n);else{var s=n;n=r,r=s}return t.revert(n)}function oC(e,t){var n;if(e<256||t.isEven())n=new dn(t);else n=new pn(t);return this.exp(e,n)}L.prototype.copyTo=kS;L.prototype.fromInt=IS;L.prototype.fromString=PS;L.prototype.clamp=RS;L.prototype.dlShiftTo=LS;L.prototype.drShiftTo=US;L.prototype.lShiftTo=zS;L.prototype.rShiftTo=FS;L.prototype.subTo=MS;L.prototype.multiplyTo=VS;L.prototype.squareTo=WS;L.prototype.divRemTo=HS;L.prototype.invDigit=JS;L.prototype.isEven=nC;L.prototype.exp=iC;L.prototype.toString=BS;L.prototype.negate=NS;L.prototype.abs=DS;L.prototype.compareTo=$S;L.prototype.bitLength=OS;L.prototype.mod=KS;L.prototype.modPowInt=oC;L.ZERO=Hr(0);L.ONE=Hr(1);function sC(){var e=Ae();return this.copyTo(e),e}function aC(){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 cC(){return this.t==0?this.s:this.data[0]<<24>>24}function uC(){return this.t==0?this.s:this.data[0]<<16>>16}function lC(e){return Math.floor(Math.LN2*this.DB/Math.log(e))}function fC(){if(this.s<0)return-1;else if(this.t<=0||this.t==1&&this.data[0]<=0)return 0;else return 1}function dC(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=Hr(n),i=Ae(),o=Ae(),s="";this.divRemTo(r,i,o);while(i.signum()>0)s=(n+o.intValue()).toString(e).substr(1)+s,i.divRemTo(r,i,o);return o.intValue().toString(e)+s}function pC(e,t){if(this.fromInt(0),t==null)t=10;var n=this.chunkSize(t),r=Math.pow(t,n),i=!1,o=0,s=0;for(var a=0;a<e.length;++a){var c=fd(e,a);if(c<0){if(e.charAt(a)=="-"&&this.signum()==0)i=!0;continue}if(s=t*s+c,++o>=n)this.dMultiply(r),this.dAddOffset(s,0),o=0,s=0}if(o>0)this.dMultiply(Math.pow(t,o)),this.dAddOffset(s,0);if(i)L.ZERO.subTo(this,this)}function hC(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(L.ONE.shiftLeft(e-1),mc,this);if(this.isEven())this.dAddOffset(1,0);while(!this.isProbablePrime(t))if(this.dAddOffset(2,0),this.bitLength()>e)this.subTo(L.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 mC(){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 gC(e){return this.compareTo(e)==0}function yC(e){return this.compareTo(e)<0?this:e}function vC(e){return this.compareTo(e)>0?this:e}function xC(e,t,n){var r,i,o=Math.min(e.t,this.t);for(r=0;r<o;++r)n.data[r]=t(this.data[r],e.data[r]);if(e.t<this.t){i=e.s&this.DM;for(r=o;r<this.t;++r)n.data[r]=t(this.data[r],i);n.t=this.t}else{i=this.s&this.DM;for(r=o;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 bC(e,t){return e&t}function SC(e){var t=Ae();return this.bitwiseTo(e,bC,t),t}function mc(e,t){return e|t}function CC(e){var t=Ae();return this.bitwiseTo(e,mc,t),t}function dd(e,t){return e^t}function wC(e){var t=Ae();return this.bitwiseTo(e,dd,t),t}function pd(e,t){return e&~t}function EC(e){var t=Ae();return this.bitwiseTo(e,pd,t),t}function _C(){var e=Ae();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 TC(e){var t=Ae();if(e<0)this.rShiftTo(-e,t);else this.lShiftTo(e,t);return t}function AC(e){var t=Ae();if(e<0)this.lShiftTo(-e,t);else this.rShiftTo(e,t);return t}function kC(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 IC(){for(var e=0;e<this.t;++e)if(this.data[e]!=0)return e*this.DB+kC(this.data[e]);if(this.s<0)return this.t*this.DB;return-1}function PC(e){var t=0;while(e!=0)e&=e-1,++t;return t}function RC(){var e=0,t=this.s&this.DM;for(var n=0;n<this.t;++n)e+=PC(this.data[n]^t);return e}function BC(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 NC(e,t){var n=L.ONE.shiftLeft(e);return this.bitwiseTo(n,t,n),n}function DC(e){return this.changeBit(e,mc)}function $C(e){return this.changeBit(e,pd)}function OC(e){return this.changeBit(e,dd)}function LC(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 UC(e){var t=Ae();return this.addTo(e,t),t}function zC(e){var t=Ae();return this.subTo(e,t),t}function FC(e){var t=Ae();return this.multiplyTo(e,t),t}function MC(){var e=Ae();return this.squareTo(e),e}function VC(e){var t=Ae();return this.divRemTo(e,t,null),t}function WC(e){var t=Ae();return this.divRemTo(e,null,t),t}function HC(e){var t=Ae(),n=Ae();return this.divRemTo(e,t,n),[t,n]}function KC(e){this.data[this.t]=this.am(0,e-1,this,0,0,this.t),++this.t,this.clamp()}function ZC(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 Ni(){}function hd(e){return e}function jC(e,t,n){e.multiplyTo(t,n)}function GC(e,t){e.squareTo(t)}Ni.prototype.convert=hd;Ni.prototype.revert=hd;Ni.prototype.mulTo=jC;Ni.prototype.sqrTo=GC;function qC(e){return this.exp(e,new Ni)}function XC(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 JC(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 zn(e){this.r2=Ae(),this.q3=Ae(),L.ONE.dlShiftTo(2*e.t,this.r2),this.mu=this.r2.divide(e),this.m=e}function QC(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=Ae();return e.copyTo(t),this.reduce(t),t}}function YC(e){return e}function ew(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 tw(e,t){e.squareTo(t),this.reduce(t)}function rw(e,t,n){e.multiplyTo(t,n),this.reduce(n)}zn.prototype.convert=QC;zn.prototype.revert=YC;zn.prototype.reduce=ew;zn.prototype.mulTo=rw;zn.prototype.sqrTo=tw;function nw(e,t){var n=e.bitLength(),r,i=Hr(1),o;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)o=new dn(t);else if(t.isEven())o=new zn(t);else o=new pn(t);var s=[],a=3,c=r-1,u=(1<<r)-1;if(s[1]=o.convert(this),r>1){var l=Ae();o.sqrTo(s[1],l);while(a<=u)s[a]=Ae(),o.mulTo(l,s[a-2],s[a]),a+=2}var f=e.t-1,p,h=!0,d=Ae(),g;n=es(e.data[f])-1;while(f>=0){if(n>=c)p=e.data[f]>>n-c&u;else if(p=(e.data[f]&(1<<n+1)-1)<<c-n,f>0)p|=e.data[f-1]>>this.DB+n-c;a=r;while((p&1)==0)p>>=1,--a;if((n-=a)<0)n+=this.DB,--f;if(h)s[p].copyTo(i),h=!1;else{while(a>1)o.sqrTo(i,d),o.sqrTo(d,i),a-=2;if(a>0)o.sqrTo(i,d);else g=i,i=d,d=g;o.mulTo(d,s[p],i)}while(f>=0&&(e.data[f]&1<<n)==0)if(o.sqrTo(i,d),g=i,i=d,d=g,--n<0)n=this.DB-1,--f}return o.revert(i)}function iw(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(),o=n.getLowestSetBit();if(o<0)return t;if(i<o)o=i;if(o>0)t.rShiftTo(o,t),n.rShiftTo(o,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(o>0)n.lShiftTo(o,n);return n}function ow(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 sw(e){if(this.signum()<=0||e.signum()<=0)return L.ZERO;var t=e.isEven();if(this.isEven()&&t||e.signum()==0)return L.ZERO;var n=e.clone(),r=this.clone(),i=Hr(1),o=Hr(0),s=Hr(0),a=Hr(1);while(n.signum()!=0){while(n.isEven()){if(n.rShiftTo(1,n),t){if(!i.isEven()||!o.isEven())i.addTo(this,i),o.subTo(e,o);i.rShiftTo(1,i)}else if(!o.isEven())o.subTo(e,o);o.rShiftTo(1,o)}while(r.isEven()){if(r.rShiftTo(1,r),t){if(!s.isEven()||!a.isEven())s.addTo(this,s),a.subTo(e,a);s.rShiftTo(1,s)}else if(!a.isEven())a.subTo(e,a);a.rShiftTo(1,a)}if(n.compareTo(r)>=0){if(n.subTo(r,n),t)i.subTo(s,i);o.subTo(a,o)}else{if(r.subTo(n,r),t)s.subTo(i,s);a.subTo(o,a)}}if(r.compareTo(L.ONE)!=0)return L.ZERO;if(a.compareTo(e)>=0)return a.subtract(e);if(a.signum()<0)a.addTo(e,a);else return a;if(a.signum()<0)return a.add(e);else return a}var Yt=[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],aw=67108864/Yt[Yt.length-1];function cw(e){var t,n=this.abs();if(n.t==1&&n.data[0]<=Yt[Yt.length-1]){for(t=0;t<Yt.length;++t)if(n.data[0]==Yt[t])return!0;return!1}if(n.isEven())return!1;t=1;while(t<Yt.length){var r=Yt[t],i=t+1;while(i<Yt.length&&r<aw)r*=Yt[i++];r=n.modInt(r);while(t<i)if(r%Yt[t++]==0)return!1}return n.millerRabin(e)}function uw(e){var t=this.subtract(L.ONE),n=t.getLowestSetBit();if(n<=0)return!1;var r=t.shiftRight(n),i=lw(),o;for(var s=0;s<e;++s){do o=new L(this.bitLength(),i);while(o.compareTo(L.ONE)<=0||o.compareTo(t)>=0);var a=o.modPow(r,this);if(a.compareTo(L.ONE)!=0&&a.compareTo(t)!=0){var c=1;while(c++<n&&a.compareTo(t)!=0)if(a=a.modPowInt(2,this),a.compareTo(L.ONE)==0)return!1;if(a.compareTo(t)!=0)return!1}}return!0}function lw(){return{nextBytes:function(e){for(var t=0;t<e.length;++t)e[t]=Math.floor(Math.random()*256)}}}L.prototype.chunkSize=lC;L.prototype.toRadix=dC;L.prototype.fromRadix=pC;L.prototype.fromNumber=hC;L.prototype.bitwiseTo=xC;L.prototype.changeBit=NC;L.prototype.addTo=LC;L.prototype.dMultiply=KC;L.prototype.dAddOffset=ZC;L.prototype.multiplyLowerTo=XC;L.prototype.multiplyUpperTo=JC;L.prototype.modInt=ow;L.prototype.millerRabin=uw;L.prototype.clone=sC;L.prototype.intValue=aC;L.prototype.byteValue=cC;L.prototype.shortValue=uC;L.prototype.signum=fC;L.prototype.toByteArray=mC;L.prototype.equals=gC;L.prototype.min=yC;L.prototype.max=vC;L.prototype.and=SC;L.prototype.or=CC;L.prototype.xor=wC;L.prototype.andNot=EC;L.prototype.not=_C;L.prototype.shiftLeft=TC;L.prototype.shiftRight=AC;L.prototype.getLowestSetBit=IC;L.prototype.bitCount=RC;L.prototype.testBit=BC;L.prototype.setBit=DC;L.prototype.clearBit=$C;L.prototype.flipBit=OC;L.prototype.add=UC;L.prototype.subtract=zC;L.prototype.multiply=FC;L.prototype.divide=VC;L.prototype.remainder=WC;L.prototype.divideAndRemainder=HC;L.prototype.modPow=nw;L.prototype.modInverse=sw;L.prototype.pow=qC;L.prototype.gcd=iw;L.prototype.isProbablePrime=cw;L.prototype.square=MC});var Fn=le(function($2,xd){var hr=he();ur();Te();var yd=xd.exports=hr.sha1=hr.sha1||{};hr.md.sha1=hr.md.algorithms.sha1=yd;yd.create=function(){if(!vd)fw();var e=null,t=hr.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 o=0;o<i;++o)r.fullMessageLength.push(0);return t=hr.util.createBuffer(),e={h0:1732584193,h1:4023233417,h2:2562383102,h3:271733878,h4:3285377520},r},r.start(),r.update=function(i,o){if(o==="utf8")i=hr.util.encodeUtf8(i);var s=i.length;r.messageLength+=s,s=[s/4294967296>>>0,s>>>0];for(var a=r.fullMessageLength.length-1;a>=0;--a)r.fullMessageLength[a]+=s[1],s[1]=s[0]+(r.fullMessageLength[a]/4294967296>>>0),r.fullMessageLength[a]=r.fullMessageLength[a]>>>0,s[0]=s[1]/4294967296>>>0;if(t.putBytes(i),gd(e,n,t),t.read>2048||t.length()===0)t.compact();return r},r.digest=function(){var i=hr.util.createBuffer();i.putBytes(t.bytes());var o=r.fullMessageLength[r.fullMessageLength.length-1]+r.messageLengthSize,s=o&r.blockLength-1;i.putBytes(gc.substr(0,r.blockLength-s));var a,c,u=r.fullMessageLength[0]*8;for(var l=0;l<r.fullMessageLength.length-1;++l)a=r.fullMessageLength[l+1]*8,c=a/4294967296>>>0,u+=c,i.putInt32(u>>>0),u=a>>>0;i.putInt32(u);var f={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3,h4:e.h4};gd(f,n,i);var p=hr.util.createBuffer();return p.putInt32(f.h0),p.putInt32(f.h1),p.putInt32(f.h2),p.putInt32(f.h3),p.putInt32(f.h4),p},r};var gc=null,vd=!1;function fw(){gc=String.fromCharCode(128),gc+=hr.util.fillString(String.fromCharCode(0),64),vd=!0}function gd(e,t,n){var r,i,o,s,a,c,u,l,f=n.length();while(f>=64){i=e.h0,o=e.h1,s=e.h2,a=e.h3,c=e.h4;for(l=0;l<16;++l)r=n.getInt32(),t[l]=r,u=a^o&(s^a),r=(i<<5|i>>>27)+u+c+1518500249+r,c=a,a=s,s=(o<<30|o>>>2)>>>0,o=i,i=r;for(;l<20;++l)r=t[l-3]^t[l-8]^t[l-14]^t[l-16],r=r<<1|r>>>31,t[l]=r,u=a^o&(s^a),r=(i<<5|i>>>27)+u+c+1518500249+r,c=a,a=s,s=(o<<30|o>>>2)>>>0,o=i,i=r;for(;l<32;++l)r=t[l-3]^t[l-8]^t[l-14]^t[l-16],r=r<<1|r>>>31,t[l]=r,u=o^s^a,r=(i<<5|i>>>27)+u+c+1859775393+r,c=a,a=s,s=(o<<30|o>>>2)>>>0,o=i,i=r;for(;l<40;++l)r=t[l-6]^t[l-16]^t[l-28]^t[l-32],r=r<<2|r>>>30,t[l]=r,u=o^s^a,r=(i<<5|i>>>27)+u+c+1859775393+r,c=a,a=s,s=(o<<30|o>>>2)>>>0,o=i,i=r;for(;l<60;++l)r=t[l-6]^t[l-16]^t[l-28]^t[l-32],r=r<<2|r>>>30,t[l]=r,u=o&s|a&(o^s),r=(i<<5|i>>>27)+u+c+2400959708+r,c=a,a=s,s=(o<<30|o>>>2)>>>0,o=i,i=r;for(;l<80;++l)r=t[l-6]^t[l-16]^t[l-28]^t[l-32],r=r<<2|r>>>30,t[l]=r,u=o^s^a,r=(i<<5|i>>>27)+u+c+3395469782+r,c=a,a=s,s=(o<<30|o>>>2)>>>0,o=i,i=r;e.h0=e.h0+i|0,e.h1=e.h1+o|0,e.h2=e.h2+s|0,e.h3=e.h3+a|0,e.h4=e.h4+c|0,f-=64}}});var yc=le(function(O2,Sd){var mr=he();Te();Ft();Fn();var bd=Sd.exports=mr.pkcs1=mr.pkcs1||{};bd.encode_rsa_oaep=function(e,t,n){var r,i,o,s;if(typeof n==="string")r=n,i=arguments[3]||void 0,o=arguments[4]||void 0;else if(n){if(r=n.label||void 0,i=n.seed||void 0,o=n.md||void 0,n.mgf1&&n.mgf1.md)s=n.mgf1.md}if(!o)o=mr.md.sha1.create();else o.start();if(!s)s=o;var a=Math.ceil(e.n.bitLength()/8),c=a-2*o.digestLength-2;if(t.length>c){var u=Error("RSAES-OAEP input message length is too long.");throw u.length=t.length,u.maxLength=c,u}if(!r)r="";o.update(r,"raw");var l=o.digest(),f="",p=c-t.length;for(var h=0;h<p;h++)f+="\x00";var d=l.getBytes()+f+"\x01"+t;if(!i)i=mr.random.getBytes(o.digestLength);else if(i.length!==o.digestLength){var u=Error("Invalid RSAES-OAEP seed. The seed length must match the digest length.");throw u.seedLength=i.length,u.digestLength=o.digestLength,u}var g=ts(i,a-o.digestLength-1,s),x=mr.util.xorBytes(d,g,d.length),b=ts(x,o.digestLength,s),S=mr.util.xorBytes(i,b,i.length);return"\x00"+S+x};bd.decode_rsa_oaep=function(e,t,n){var r,i,o;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)o=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=mr.md.sha1.create();else i.start();if(!o)o=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 a=i.digest().getBytes(),c=t.charAt(0),u=t.substring(1,i.digestLength+1),l=t.substring(1+i.digestLength),f=ts(l,i.digestLength,o),p=mr.util.xorBytes(u,f,u.length),h=ts(p,s-i.digestLength-1,o),d=mr.util.xorBytes(l,h,l.length),g=d.substring(0,i.digestLength),x=c!=="\x00";for(var b=0;b<i.digestLength;++b)x|=a.charAt(b)!==g.charAt(b);var S=1,C=i.digestLength;for(var T=i.digestLength;T<d.length;T++){var I=d.charCodeAt(T),k=I&1^1,R=S?65534:0;x|=I&R,S=S&k,C+=S}if(x||d.charCodeAt(C)!==1)throw Error("Invalid RSAES-OAEP padding.");return d.substring(C+1)};function ts(e,t,n){if(!n)n=mr.md.sha1.create();var r="",i=Math.ceil(t/n.digestLength);for(var o=0;o<i;++o){var s=String.fromCharCode(o>>24&255,o>>16&255,o>>8&255,o&255);n.start(),n.update(e+s),r+=n.digest().getBytes()}return r.substring(0,t)}});var xc=le(function(L2,vc){var Kr=he();Te();Di();Ft();(function(){if(Kr.prime){vc.exports=Kr.prime;return}var e=vc.exports=Kr.prime=Kr.prime||{},t=Kr.jsbn.BigInteger,n=[6,4,2,4,2,4,6,2],r=new t(null);r.fromInt(30);var i=function(f,p){return f|p};e.generateProbablePrime=function(f,p,h){if(typeof p==="function")h=p,p={};p=p||{};var d=p.algorithm||"PRIMEINC";if(typeof d==="string")d={name:d};d.options=d.options||{};var g=p.prng||Kr.random,x={nextBytes:function(b){var S=g.getBytesSync(b.length);for(var C=0;C<b.length;++C)b[C]=S.charCodeAt(C)}};if(d.name==="PRIMEINC")return o(f,x,d.options,h);throw Error("Invalid prime generation algorithm: "+d.name)};function o(f,p,h,d){if("workers"in h)return c(f,p,h,d);return s(f,p,h,d)}function s(f,p,h,d){var g=u(f,p),x=0,b=l(g.bitLength());if("millerRabinTests"in h)b=h.millerRabinTests;var S=10;if("maxBlockTime"in h)S=h.maxBlockTime;a(g,f,p,x,b,S,d)}function a(f,p,h,d,g,x,b){var S=+new Date;do{if(f.bitLength()>p)f=u(p,h);if(f.isProbablePrime(g))return b(null,f);f.dAddOffset(n[d++%8],0)}while(x<0||+new Date-S<x);Kr.util.setImmediate(function(){a(f,p,h,d,g,x,b)})}function c(f,p,h,d){if(typeof Worker>"u")return s(f,p,h,d);var g=u(f,p),x=h.workers,b=h.workLoad||100,S=b*30/8,C=h.workerScript||"forge/prime.worker.js";if(x===-1)return Kr.util.estimateCores(function(I,k){if(I)k=2;x=k-1,T()});T();function T(){x=Math.max(1,x);var I=[];for(var k=0;k<x;++k)I[k]=new Worker(C);var R=x;for(var k=0;k<x;++k)I[k].addEventListener("message",D);var V=!1;function D(F){if(V)return;--R;var H=F.data;if(H.found){for(var re=0;re<I.length;++re)I[re].terminate();return V=!0,d(null,new t(H.prime,16))}if(g.bitLength()>f)g=u(f,p);var se=g.toString(16);F.target.postMessage({hex:se,workLoad:b}),g.dAddOffset(S,0)}}}function u(f,p){var h=new t(f,p),d=f-1;if(!h.testBit(d))h.bitwiseTo(t.ONE.shiftLeft(d),i,h);return h.dAddOffset(31-h.mod(r).byteValue(),0),h}function l(f){if(f<=100)return 27;if(f<=150)return 18;if(f<=200)return 15;if(f<=250)return 12;if(f<=300)return 9;if(f<=350)return 8;if(f<=400)return 7;if(f<=500)return 6;if(f<=600)return 5;if(f<=800)return 4;if(f<=1250)return 3;return 2}})()});var $i=le(function(U2,Id){var ne=he();Qt();Di();Wr();yc();xc();Ft();Te();if(typeof we>"u")we=ne.jsbn.BigInteger;var we,bc=ne.util.isNodejs?Ci("crypto"):null,{asn1:P,util:Vt}=ne;ne.pki=ne.pki||{};Id.exports=ne.pki.rsa=ne.rsa=ne.rsa||{};var fe=ne.pki,dw=[6,4,2,4,2,4,6,2],pw={name:"PrivateKeyInfo",tagClass:P.Class.UNIVERSAL,type:P.Type.SEQUENCE,constructed:!0,value:[{name:"PrivateKeyInfo.version",tagClass:P.Class.UNIVERSAL,type:P.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:P.Class.UNIVERSAL,type:P.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:P.Class.UNIVERSAL,type:P.Type.OID,constructed:!1,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:P.Class.UNIVERSAL,type:P.Type.OCTETSTRING,constructed:!1,capture:"privateKey"}]},hw={name:"RSAPrivateKey",tagClass:P.Class.UNIVERSAL,type:P.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPrivateKey.version",tagClass:P.Class.UNIVERSAL,type:P.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"RSAPrivateKey.modulus",tagClass:P.Class.UNIVERSAL,type:P.Type.INTEGER,constructed:!1,capture:"privateKeyModulus"},{name:"RSAPrivateKey.publicExponent",tagClass:P.Class.UNIVERSAL,type:P.Type.INTEGER,constructed:!1,capture:"privateKeyPublicExponent"},{name:"RSAPrivateKey.privateExponent",tagClass:P.Class.UNIVERSAL,type:P.Type.INTEGER,constructed:!1,capture:"privateKeyPrivateExponent"},{name:"RSAPrivateKey.prime1",tagClass:P.Class.UNIVERSAL,type:P.Type.INTEGER,constructed:!1,capture:"privateKeyPrime1"},{name:"RSAPrivateKey.prime2",tagClass:P.Class.UNIVERSAL,type:P.Type.INTEGER,constructed:!1,capture:"privateKeyPrime2"},{name:"RSAPrivateKey.exponent1",tagClass:P.Class.UNIVERSAL,type:P.Type.INTEGER,constructed:!1,capture:"privateKeyExponent1"},{name:"RSAPrivateKey.exponent2",tagClass:P.Class.UNIVERSAL,type:P.Type.INTEGER,constructed:!1,capture:"privateKeyExponent2"},{name:"RSAPrivateKey.coefficient",tagClass:P.Class.UNIVERSAL,type:P.Type.INTEGER,constructed:!1,capture:"privateKeyCoefficient"}]},mw={name:"RSAPublicKey",tagClass:P.Class.UNIVERSAL,type:P.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPublicKey.modulus",tagClass:P.Class.UNIVERSAL,type:P.Type.INTEGER,constructed:!1,capture:"publicKeyModulus"},{name:"RSAPublicKey.exponent",tagClass:P.Class.UNIVERSAL,type:P.Type.INTEGER,constructed:!1,capture:"publicKeyExponent"}]},gw=ne.pki.rsa.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:P.Class.UNIVERSAL,type:P.Type.SEQUENCE,constructed:!0,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:P.Class.UNIVERSAL,type:P.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:P.Class.UNIVERSAL,type:P.Type.OID,constructed:!1,capture:"publicKeyOid"}]},{name:"SubjectPublicKeyInfo.subjectPublicKey",tagClass:P.Class.UNIVERSAL,type:P.Type.BITSTRING,constructed:!1,value:[{name:"SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey",tagClass:P.Class.UNIVERSAL,type:P.Type.SEQUENCE,constructed:!0,optional:!0,captureAsn1:"rsaPublicKey"}]}]},yw={name:"DigestInfo",tagClass:P.Class.UNIVERSAL,type:P.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm",tagClass:P.Class.UNIVERSAL,type:P.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm.algorithmIdentifier",tagClass:P.Class.UNIVERSAL,type:P.Type.OID,constructed:!1,capture:"algorithmIdentifier"},{name:"DigestInfo.DigestAlgorithm.parameters",tagClass:P.Class.UNIVERSAL,type:P.Type.NULL,capture:"parameters",optional:!0,constructed:!1}]},{name:"DigestInfo.digest",tagClass:P.Class.UNIVERSAL,type:P.Type.OCTETSTRING,constructed:!1,capture:"digest"}]},Cd=function(e,t,n){var r=[P.create(P.Class.UNIVERSAL,P.Type.OID,!1,P.oidToDer(e).getBytes())];if(n)r.push(P.create(P.Class.UNIVERSAL,P.Type.NULL,!1,""));return P.toDer(P.create(P.Class.UNIVERSAL,P.Type.SEQUENCE,!0,[P.create(P.Class.UNIVERSAL,P.Type.SEQUENCE,!0,r),P.create(P.Class.UNIVERSAL,P.Type.OCTETSTRING,!1,t)])).getBytes()},vw=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=P.oidToDer(t).getBytes(),i=P.create(P.Class.UNIVERSAL,P.Type.SEQUENCE,!0,[]),o=P.create(P.Class.UNIVERSAL,P.Type.SEQUENCE,!0,[]);o.value.push(P.create(P.Class.UNIVERSAL,P.Type.OID,!1,r)),o.value.push(P.create(P.Class.UNIVERSAL,P.Type.NULL,!1,""));var s=P.create(P.Class.UNIVERSAL,P.Type.OCTETSTRING,!1,e.digest().getBytes());return i.value.push(o),i.value.push(s),P.toDer(i).getBytes()},Ad=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(we.ONE));if(!t.dQ)t.dQ=t.d.mod(t.q.subtract(we.ONE));if(!t.qInv)t.qInv=t.q.modInverse(t.p);var r;do r=new we(ne.util.bytesToHex(ne.random.getBytes(t.n.bitLength()/8)),16);while(r.compareTo(t.n)>=0||!r.gcd(t.n).equals(we.ONE));e=e.multiply(r.modPow(t.e,t.n)).mod(t.n);var i=e.mod(t.p).modPow(t.dP,t.p),o=e.mod(t.q).modPow(t.dQ,t.q);while(i.compareTo(o)<0)i=i.add(t.p);var s=i.subtract(o).multiply(t.qInv).mod(t.p).multiply(t.q).add(o);return s=s.multiply(r.modInverse(t.n)).mod(t.n),s};fe.rsa.encrypt=function(e,t,n){var r=n,i,o=Math.ceil(t.n.bitLength()/8);if(n!==!1&&n!==!0)r=n===2,i=kd(e,t,n);else i=ne.util.createBuffer(),i.putBytes(e);var s=new we(i.toHex(),16),a=Ad(s,t,r),c=a.toString(16),u=ne.util.createBuffer(),l=o-Math.ceil(c.length/2);while(l>0)u.putByte(0),--l;return u.putBytes(ne.util.hexToBytes(c)),u.getBytes()};fe.rsa.decrypt=function(e,t,n,r){var i=Math.ceil(t.n.bitLength()/8);if(e.length!==i){var o=Error("Encrypted message length is invalid.");throw o.length=e.length,o.expected=i,o}var s=new we(ne.util.createBuffer(e).toHex(),16);if(s.compareTo(t.n)>=0)throw Error("Encrypted message is invalid.");var a=Ad(s,t,n),c=a.toString(16),u=ne.util.createBuffer(),l=i-Math.ceil(c.length/2);while(l>0)u.putByte(0),--l;if(u.putBytes(ne.util.hexToBytes(c)),r!==!1)return rs(u.getBytes(),t,n);return u.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||ne.random,i={nextBytes:function(a){var c=r.getBytesSync(a.length);for(var u=0;u<a.length;++u)a[u]=c.charCodeAt(u)}},o=n.algorithm||"PRIMEINC",s;if(o==="PRIMEINC")s={algorithm:o,state:0,bits:e,rng:i,eInt:t||65537,e:new we(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: "+o);return s};fe.rsa.stepKeyPairGenerationState=function(e,t){if(!("algorithm"in e))e.algorithm="PRIMEINC";var n=new we(null);n.fromInt(30);var r=0,i=function(f,p){return f|p},o=+new Date,s,a=0;while(e.keys===null&&(t<=0||a<t)){if(e.state===0){var c=e.p===null?e.pBits:e.qBits,u=c-1;if(e.pqState===0){if(e.num=new we(c,e.rng),!e.num.testBit(u))e.num.bitwiseTo(we.ONE.shiftLeft(u),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()>c)e.pqState=0;else if(e.num.isProbablePrime(bw(e.num.bitLength())))++e.pqState;else e.num.dAddOffset(dw[r++%8],0);else if(e.pqState===2)e.pqState=e.num.subtract(we.ONE).gcd(e.e).compareTo(we.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(we.ONE),e.q1=e.q.subtract(we.ONE),e.phi=e.p1.multiply(e.q1),++e.state;else if(e.state===3)if(e.phi.gcd(e.e).compareTo(we.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 l=e.e.modInverse(e.phi);e.keys={privateKey:fe.rsa.setPrivateKey(e.n,e.e,l,e.p,e.q,l.mod(e.p1),l.mod(e.q1),e.q.modInverse(e.p)),publicKey:fe.rsa.setPublicKey(e.n,e.e)}}s=+new Date,a+=s-o,o=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(!ne.options.usePureJavaScript&&!n.prng&&e>=256&&e<=16384&&(t===65537||t===3)){if(r){if(wd("generateKeyPair"))return bc.generateKeyPair("rsa",{modulusLength:e,publicExponent:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}},function(a,c,u){if(a)return r(a);r(null,{privateKey:fe.privateKeyFromPem(u),publicKey:fe.publicKeyFromPem(c)})});if(Ed("generateKey")&&Ed("exportKey"))return Vt.globalScope.crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:Td(t),hash:{name:"SHA-256"}},!0,["sign","verify"]).then(function(a){return Vt.globalScope.crypto.subtle.exportKey("pkcs8",a.privateKey)}).then(void 0,function(a){r(a)}).then(function(a){if(a){var c=fe.privateKeyFromAsn1(P.fromDer(ne.util.createBuffer(a)));r(null,{privateKey:c,publicKey:fe.setRsaPublicKey(c.n,c.e)})}});if(_d("generateKey")&&_d("exportKey")){var i=Vt.globalScope.msCrypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:Td(t),hash:{name:"SHA-256"}},!0,["sign","verify"]);i.oncomplete=function(a){var c=a.target.result,u=Vt.globalScope.msCrypto.subtle.exportKey("pkcs8",c.privateKey);u.oncomplete=function(l){var f=l.target.result,p=fe.privateKeyFromAsn1(P.fromDer(ne.util.createBuffer(f)));r(null,{privateKey:p,publicKey:fe.setRsaPublicKey(p.n,p.e)})},u.onerror=function(l){r(l)}},i.onerror=function(a){r(a)};return}}else if(wd("generateKeyPairSync")){var o=bc.generateKeyPairSync("rsa",{modulusLength:e,publicExponent:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{privateKey:fe.privateKeyFromPem(o.privateKey),publicKey:fe.publicKeyFromPem(o.publicKey)}}}var s=fe.rsa.createKeyPairGenerationState(e,t,n);if(!r)return fe.rsa.stepKeyPairGenerationState(s,0),s.keys;xw(s,n,r)};fe.setRsaPublicKey=fe.rsa.setPublicKey=function(e,t){var n={n:e,e:t};return n.encrypt=function(r,i,o){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(a,c,u){return kd(a,c,2).getBytes()}};else if(i==="RSA-OAEP"||i==="RSAES-OAEP")i={encode:function(a,c){return ne.pkcs1.encode_rsa_oaep(c,a,o)}};else if(["RAW","NONE","NULL",null].indexOf(i)!==-1)i={encode:function(a){return a}};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,o,s){if(typeof o==="string")o=o.toUpperCase();else if(o===void 0)o="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(o==="RSASSA-PKCS1-V1_5")o={verify:function(c,u){u=rs(u,n,!0,void 0,s);var l=P.fromDer(u,{parseAllBytes:s._parseAllDigestBytes}),f={},p=[];if(!P.validate(l,yw,f,p)||l.value.length!==2){var h=Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value.");throw h.errors=p,h}var d=P.derToOid(f.algorithmIdentifier);if(!(d===ne.oids.md2||d===ne.oids.md5||d===ne.oids.sha1||d===ne.oids.sha224||d===ne.oids.sha256||d===ne.oids.sha384||d===ne.oids.sha512||d===ne.oids["sha512-224"]||d===ne.oids["sha512-256"])){var h=Error("Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.");throw h.oid=d,h}if(d===ne.oids.md2||d===ne.oids.md5){if(!("parameters"in f))throw Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value. Missing algorithm identifier NULL parameters.")}var g=Cd(d,f.digest,!0),x=Cd(d,f.digest,!1);if(u.substring(0,g.length)!==g&&u.substring(0,x.length)!==x)throw Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value.");return c===f.digest}};else if(o==="NONE"||o==="NULL"||o===null)o={verify:function(c,u){return u=rs(u,n,!0,void 0,s),c===u}};var a=fe.rsa.decrypt(i,n,!0,!1);return o.verify(r,a,n.n.bitLength())},n};fe.setRsaPrivateKey=fe.rsa.setPrivateKey=function(e,t,n,r,i,o,s,a){var c={n:e,e:t,d:n,p:r,q:i,dP:o,dQ:s,qInv:a};return c.decrypt=function(u,l,f){if(typeof l==="string")l=l.toUpperCase();else if(l===void 0)l="RSAES-PKCS1-V1_5";var p=fe.rsa.decrypt(u,c,!1,!1);if(l==="RSAES-PKCS1-V1_5")l={decode:rs};else if(l==="RSA-OAEP"||l==="RSAES-OAEP")l={decode:function(h,d){return ne.pkcs1.decode_rsa_oaep(d,h,f)}};else if(["RAW","NONE","NULL",null].indexOf(l)!==-1)l={decode:function(h){return h}};else throw Error('Unsupported encryption scheme: "'+l+'".');return l.decode(p,c,!1)},c.sign=function(u,l){var f=!1;if(typeof l==="string")l=l.toUpperCase();if(l===void 0||l==="RSASSA-PKCS1-V1_5")l={encode:vw},f=1;else if(l==="NONE"||l==="NULL"||l===null)l={encode:function(){return u}},f=1;var p=l.encode(u,c.n.bitLength());return fe.rsa.encrypt(p,c,f)},c};fe.wrapRsaPrivateKey=function(e){return P.create(P.Class.UNIVERSAL,P.Type.SEQUENCE,!0,[P.create(P.Class.UNIVERSAL,P.Type.INTEGER,!1,P.integerToDer(0).getBytes()),P.create(P.Class.UNIVERSAL,P.Type.SEQUENCE,!0,[P.create(P.Class.UNIVERSAL,P.Type.OID,!1,P.oidToDer(fe.oids.rsaEncryption).getBytes()),P.create(P.Class.UNIVERSAL,P.Type.NULL,!1,"")]),P.create(P.Class.UNIVERSAL,P.Type.OCTETSTRING,!1,P.toDer(e).getBytes())])};fe.privateKeyFromAsn1=function(e){var t={},n=[];if(P.validate(e,pw,t,n))e=P.fromDer(ne.util.createBuffer(t.privateKey));if(t={},n=[],!P.validate(e,hw,t,n)){var r=Error("Cannot read private key. ASN.1 object does not contain an RSAPrivateKey.");throw r.errors=n,r}if(t.privateKeyVersion!=="\x00"||e.value.length!==9)throw Error("Cannot read private key. Only two-prime RSAPrivateKey version 0 is supported.");var i,o,s,a,c,u,l,f;return i=ne.util.createBuffer(t.privateKeyModulus).toHex(),o=ne.util.createBuffer(t.privateKeyPublicExponent).toHex(),s=ne.util.createBuffer(t.privateKeyPrivateExponent).toHex(),a=ne.util.createBuffer(t.privateKeyPrime1).toHex(),c=ne.util.createBuffer(t.privateKeyPrime2).toHex(),u=ne.util.createBuffer(t.privateKeyExponent1).toHex(),l=ne.util.createBuffer(t.privateKeyExponent2).toHex(),f=ne.util.createBuffer(t.privateKeyCoefficient).toHex(),fe.setRsaPrivateKey(new we(i,16),new we(o,16),new we(s,16),new we(a,16),new we(c,16),new we(u,16),new we(l,16),new we(f,16))};fe.privateKeyToAsn1=fe.privateKeyToRSAPrivateKey=function(e){return P.create(P.Class.UNIVERSAL,P.Type.SEQUENCE,!0,[P.create(P.Class.UNIVERSAL,P.Type.INTEGER,!1,P.integerToDer(0).getBytes()),P.create(P.Class.UNIVERSAL,P.Type.INTEGER,!1,gr(e.n)),P.create(P.Class.UNIVERSAL,P.Type.INTEGER,!1,gr(e.e)),P.create(P.Class.UNIVERSAL,P.Type.INTEGER,!1,gr(e.d)),P.create(P.Class.UNIVERSAL,P.Type.INTEGER,!1,gr(e.p)),P.create(P.Class.UNIVERSAL,P.Type.INTEGER,!1,gr(e.q)),P.create(P.Class.UNIVERSAL,P.Type.INTEGER,!1,gr(e.dP)),P.create(P.Class.UNIVERSAL,P.Type.INTEGER,!1,gr(e.dQ)),P.create(P.Class.UNIVERSAL,P.Type.INTEGER,!1,gr(e.qInv))])};fe.publicKeyFromAsn1=function(e){var t={},n=[];if(P.validate(e,gw,t,n)){var r=P.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=[],!P.validate(e,mw,t,n)){var i=Error("Cannot read public key. ASN.1 object does not contain an RSAPublicKey.");throw i.errors=n,i}var o=ne.util.createBuffer(t.publicKeyModulus).toHex(),s=ne.util.createBuffer(t.publicKeyExponent).toHex();return fe.setRsaPublicKey(new we(o,16),new we(s,16))};fe.publicKeyToAsn1=fe.publicKeyToSubjectPublicKeyInfo=function(e){return P.create(P.Class.UNIVERSAL,P.Type.SEQUENCE,!0,[P.create(P.Class.UNIVERSAL,P.Type.SEQUENCE,!0,[P.create(P.Class.UNIVERSAL,P.Type.OID,!1,P.oidToDer(fe.oids.rsaEncryption).getBytes()),P.create(P.Class.UNIVERSAL,P.Type.NULL,!1,"")]),P.create(P.Class.UNIVERSAL,P.Type.BITSTRING,!1,[fe.publicKeyToRSAPublicKey(e)])])};fe.publicKeyToRSAPublicKey=function(e){return P.create(P.Class.UNIVERSAL,P.Type.SEQUENCE,!0,[P.create(P.Class.UNIVERSAL,P.Type.INTEGER,!1,gr(e.n)),P.create(P.Class.UNIVERSAL,P.Type.INTEGER,!1,gr(e.e))])};function kd(e,t,n){var r=ne.util.createBuffer(),i=Math.ceil(t.n.bitLength()/8);if(e.length>i-11){var o=Error("Message is too long for PKCS#1 v1.5 padding.");throw o.length=e.length,o.max=i-11,o}r.putByte(0),r.putByte(n);var s=i-3-e.length,a;if(n===0||n===1){a=n===0?0:255;for(var c=0;c<s;++c)r.putByte(a)}else while(s>0){var u=0,l=ne.random.getBytes(s);for(var c=0;c<s;++c)if(a=l.charCodeAt(c),a===0)++u;else r.putByte(a);s=u}return r.putByte(0),r.putBytes(e),r}function rs(e,t,n,r,i){var o=Math.ceil(t.n.bitLength()/8),s=ne.util.createBuffer(e),a=s.getByte(),c=s.getByte();if(a!==0||n&&c!==0&&c!==1||!n&&c!==2||n&&c===0&&typeof r>"u")throw Error("Encryption block is invalid.");var u=0;if(c===0){u=o-3-r;for(var l=0;l<u;++l)if(s.getByte()!==0)throw Error("Encryption block is invalid.")}else if(c===1){u=0;while(s.length()>1){if(s.getByte()!==255){--s.read;break}++u}if(u<8&&!(i?i._skipPaddingChecks:!1))throw Error("Encryption block is invalid.")}else if(c===2){u=0;while(s.length()>1){if(s.getByte()===0){--s.read;break}++u}if(u<8&&!(i?i._skipPaddingChecks:!1))throw Error("Encryption block is invalid.")}var f=s.getByte();if(f!==0||u!==o-3-s.length())throw Error("Encryption block is invalid.");return s.getBytes()}function xw(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(){o(e.pBits,function(a,c){if(a)return n(a);if(e.p=c,e.q!==null)return s(a,e.q);o(e.qBits,s)})}function o(a,c){ne.prime.generateProbablePrime(a,r,c)}function s(a,c){if(a)return n(a);if(e.q=c,e.p.compareTo(e.q)<0){var u=e.p;e.p=e.q,e.q=u}if(e.p.subtract(we.ONE).gcd(e.e).compareTo(we.ONE)!==0){e.p=null,i();return}if(e.q.subtract(we.ONE).gcd(e.e).compareTo(we.ONE)!==0){e.q=null,o(e.qBits,s);return}if(e.p1=e.p.subtract(we.ONE),e.q1=e.q.subtract(we.ONE),e.phi=e.p1.multiply(e.q1),e.phi.gcd(e.e).compareTo(we.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,o(e.qBits,s);return}var l=e.e.modInverse(e.phi);e.keys={privateKey:fe.rsa.setPrivateKey(e.n,e.e,l,e.p,e.q,l.mod(e.p1),l.mod(e.q1),e.q.modInverse(e.p)),publicKey:fe.rsa.setPublicKey(e.n,e.e)},n(null,e.keys)}}function gr(e){var t=e.toString(16);if(t[0]>="8")t="00"+t;var n=ne.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 bw(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 wd(e){return ne.util.isNodejs&&typeof bc[e]==="function"}function Ed(e){return typeof Vt.globalScope<"u"&&typeof Vt.globalScope.crypto==="object"&&typeof Vt.globalScope.crypto.subtle==="object"&&typeof Vt.globalScope.crypto.subtle[e]==="function"}function _d(e){return typeof Vt.globalScope<"u"&&typeof Vt.globalScope.msCrypto==="object"&&typeof Vt.globalScope.msCrypto.subtle==="object"&&typeof Vt.globalScope.msCrypto.subtle[e]==="function"}function Td(e){var t=ne.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 Cc=le(function(z2,Nd){var q=he();Vr();Qt();Bi();ur();Wr();Xo();fn();Ft();pc();$i();Te();if(typeof Sc>"u")Sc=q.jsbn.BigInteger;var Sc,B=q.asn1,pe=q.pki=q.pki||{};Nd.exports=pe.pbe=q.pbe=q.pbe||{};var hn=pe.oids,Sw={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"}]},Cw={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"}]}]},ww={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"}]};pe.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=q.random.getBytesSync(n.saltSize),i=n.count,o=B.integerToDer(i),s,a,c;if(n.algorithm.indexOf("aes")===0||n.algorithm==="des"){var u,l,f;switch(n.algorithm){case"aes128":s=16,u=16,l=hn["aes128-CBC"],f=q.aes.createEncryptionCipher;break;case"aes192":s=24,u=16,l=hn["aes192-CBC"],f=q.aes.createEncryptionCipher;break;case"aes256":s=32,u=16,l=hn["aes256-CBC"],f=q.aes.createEncryptionCipher;break;case"des":s=8,u=8,l=hn.desCBC,f=q.des.createEncryptionCipher;break;default:var p=Error("Cannot encrypt private key. Unknown encryption algorithm.");throw p.algorithm=n.algorithm,p}var h="hmacWith"+n.prfAlgorithm.toUpperCase(),d=Bd(h),g=q.pkcs5.pbkdf2(t,r,i,s,d),x=q.random.getBytesSync(u),b=f(g);b.start(x),b.update(B.toDer(e)),b.finish(),c=b.output.getBytes();var S=Ew(r,o,s,h);a=B.create(B.Class.UNIVERSAL,B.Type.SEQUENCE,!0,[B.create(B.Class.UNIVERSAL,B.Type.OID,!1,B.oidToDer(hn.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(hn.pkcs5PBKDF2).getBytes()),S]),B.create(B.Class.UNIVERSAL,B.Type.SEQUENCE,!0,[B.create(B.Class.UNIVERSAL,B.Type.OID,!1,B.oidToDer(l).getBytes()),B.create(B.Class.UNIVERSAL,B.Type.OCTETSTRING,!1,x)])])])}else if(n.algorithm==="3des"){s=24;var C=new q.util.ByteBuffer(r),g=pe.pbe.generatePkcs12Key(t,C,1,i,s),x=pe.pbe.generatePkcs12Key(t,C,2,i,s),b=q.des.createEncryptionCipher(g);b.start(x),b.update(B.toDer(e)),b.finish(),c=b.output.getBytes(),a=B.create(B.Class.UNIVERSAL,B.Type.SEQUENCE,!0,[B.create(B.Class.UNIVERSAL,B.Type.OID,!1,B.oidToDer(hn["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,o.getBytes())])])}else{var p=Error("Cannot encrypt private key. Unknown encryption algorithm.");throw p.algorithm=n.algorithm,p}var T=B.create(B.Class.UNIVERSAL,B.Type.SEQUENCE,!0,[a,B.create(B.Class.UNIVERSAL,B.Type.OCTETSTRING,!1,c)]);return T};pe.decryptPrivateKeyInfo=function(e,t){var n=null,r={},i=[];if(!B.validate(e,Sw,r,i)){var o=Error("Cannot read encrypted private key. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw o.errors=i,o}var s=B.derToOid(r.encryptionOid),a=pe.pbe.getCipher(s,r.encryptionParams,t),c=q.util.createBuffer(r.encryptedData);if(a.update(c),a.finish())n=B.fromDer(a.output);return n};pe.encryptedPrivateKeyToPem=function(e,t){var n={type:"ENCRYPTED PRIVATE KEY",body:B.toDer(e).getBytes()};return q.pem.encode(n,{maxline:t})};pe.encryptedPrivateKeyFromPem=function(e){var t=q.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)};pe.encryptRsaPrivateKey=function(e,t,n){if(n=n||{},!n.legacy){var r=pe.wrapRsaPrivateKey(pe.privateKeyToAsn1(e));return r=pe.encryptPrivateKeyInfo(r,t,n),pe.encryptedPrivateKeyToPem(r)}var i,o,s,a;switch(n.algorithm){case"aes128":i="AES-128-CBC",s=16,o=q.random.getBytesSync(16),a=q.aes.createEncryptionCipher;break;case"aes192":i="AES-192-CBC",s=24,o=q.random.getBytesSync(16),a=q.aes.createEncryptionCipher;break;case"aes256":i="AES-256-CBC",s=32,o=q.random.getBytesSync(16),a=q.aes.createEncryptionCipher;break;case"3des":i="DES-EDE3-CBC",s=24,o=q.random.getBytesSync(8),a=q.des.createEncryptionCipher;break;case"des":i="DES-CBC",s=8,o=q.random.getBytesSync(8),a=q.des.createEncryptionCipher;break;default:var c=Error('Could not encrypt RSA private key; unsupported encryption algorithm "'+n.algorithm+'".');throw c.algorithm=n.algorithm,c}var u=q.pbe.opensslDeriveBytes(t,o.substr(0,8),s),l=a(u);l.start(o),l.update(B.toDer(pe.privateKeyToAsn1(e))),l.finish();var f={type:"RSA PRIVATE KEY",procType:{version:"4",type:"ENCRYPTED"},dekInfo:{algorithm:i,parameters:q.util.bytesToHex(o).toUpperCase()},body:l.output.getBytes()};return q.pem.encode(f)};pe.decryptRsaPrivateKey=function(e,t){var n=null,r=q.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 o,s;switch(r.dekInfo.algorithm){case"DES-CBC":o=8,s=q.des.createDecryptionCipher;break;case"DES-EDE3-CBC":o=24,s=q.des.createDecryptionCipher;break;case"AES-128-CBC":o=16,s=q.aes.createDecryptionCipher;break;case"AES-192-CBC":o=24,s=q.aes.createDecryptionCipher;break;case"AES-256-CBC":o=32,s=q.aes.createDecryptionCipher;break;case"RC2-40-CBC":o=5,s=function(f){return q.rc2.createDecryptionCipher(f,40)};break;case"RC2-64-CBC":o=8,s=function(f){return q.rc2.createDecryptionCipher(f,64)};break;case"RC2-128-CBC":o=16,s=function(f){return q.rc2.createDecryptionCipher(f,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 a=q.util.hexToBytes(r.dekInfo.parameters),c=q.pbe.opensslDeriveBytes(t,a.substr(0,8),o),u=s(c);if(u.start(a),u.update(q.util.createBuffer(r.body)),u.finish())n=u.output.getBytes();else return n}else n=r.body;if(r.type==="ENCRYPTED PRIVATE KEY")n=pe.decryptPrivateKeyInfo(B.fromDer(n),t);else n=B.fromDer(n);if(n!==null)n=pe.privateKeyFromAsn1(n);return n};pe.pbe.generatePkcs12Key=function(e,t,n,r,i,o){var s,a;if(!(r>=1))throw Error("PKCS#12 key derivation iteration count must be >= 1.");if(typeof o>"u"||o===null){if(!("sha1"in q.md))throw Error('"sha1" hash algorithm unavailable.');o=q.md.sha1.create()}var c=o.digestLength,u=o.blockLength,l=new q.util.ByteBuffer,f=new q.util.ByteBuffer;if(e!==null&&e!==void 0){for(a=0;a<e.length;a++)f.putInt16(e.charCodeAt(a));f.putInt16(0)}var p=f.length(),h=t.length(),d=new q.util.ByteBuffer;d.fillWithByte(n,u);var g=u*Math.ceil(h/u),x=new q.util.ByteBuffer;for(a=0;a<g;a++)x.putByte(t.at(a%h));var b=u*Math.ceil(p/u),S=new q.util.ByteBuffer;for(a=0;a<b;a++)S.putByte(f.at(a%p));var C=x;C.putBuffer(S);var T=Math.ceil(i/c);for(var I=1;I<=T;I++){var k=new q.util.ByteBuffer;k.putBytes(d.bytes()),k.putBytes(C.bytes());for(var R=0;R<r;R++)o.start(),o.update(k.getBytes()),k=o.digest();var V=new q.util.ByteBuffer;for(a=0;a<u;a++)V.putByte(k.at(a%c));var D=Math.ceil(h/u)+Math.ceil(p/u),F=new q.util.ByteBuffer;for(s=0;s<D;s++){var H=new q.util.ByteBuffer(C.getBytes(u)),re=511;for(a=V.length()-1;a>=0;a--)re=re>>8,re+=V.at(a)+H.at(a),H.setAt(a,re&255);F.putBuffer(H)}C=F,l.putBuffer(k)}return l.truncate(l.length()-i),l};pe.pbe.getCipher=function(e,t,n){switch(e){case pe.oids.pkcs5PBES2:return pe.pbe.getCipherForPBES2(e,t,n);case pe.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:case pe.oids["pbewithSHAAnd40BitRC2-CBC"]:return pe.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}};pe.pbe.getCipherForPBES2=function(e,t,n){var r={},i=[];if(!B.validate(t,Cw,r,i)){var o=Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw o.errors=i,o}if(e=B.derToOid(r.kdfOid),e!==pe.oids.pkcs5PBKDF2){var o=Error("Cannot read encrypted private key. Unsupported key derivation function OID.");throw o.oid=e,o.supportedOids=["pkcs5PBKDF2"],o}if(e=B.derToOid(r.encOid),e!==pe.oids["aes128-CBC"]&&e!==pe.oids["aes192-CBC"]&&e!==pe.oids["aes256-CBC"]&&e!==pe.oids["des-EDE3-CBC"]&&e!==pe.oids.desCBC){var o=Error("Cannot read encrypted private key. Unsupported encryption scheme OID.");throw o.oid=e,o.supportedOids=["aes128-CBC","aes192-CBC","aes256-CBC","des-EDE3-CBC","desCBC"],o}var s=r.kdfSalt,a=q.util.createBuffer(r.kdfIterationCount);a=a.getInt(a.length()<<3);var c,u;switch(pe.oids[e]){case"aes128-CBC":c=16,u=q.aes.createDecryptionCipher;break;case"aes192-CBC":c=24,u=q.aes.createDecryptionCipher;break;case"aes256-CBC":c=32,u=q.aes.createDecryptionCipher;break;case"des-EDE3-CBC":c=24,u=q.des.createDecryptionCipher;break;case"desCBC":c=8,u=q.des.createDecryptionCipher;break}var l=Rd(r.prfOid),f=q.pkcs5.pbkdf2(n,s,a,c,l),p=r.encIv,h=u(f);return h.start(p),h};pe.pbe.getCipherForPKCS12PBE=function(e,t,n){var r={},i=[];if(!B.validate(t,ww,r,i)){var o=Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw o.errors=i,o}var s=q.util.createBuffer(r.salt),a=q.util.createBuffer(r.iterations);a=a.getInt(a.length()<<3);var c,u,l;switch(e){case pe.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:c=24,u=8,l=q.des.startDecrypting;break;case pe.oids["pbewithSHAAnd40BitRC2-CBC"]:c=5,u=8,l=function(g,x){var b=q.rc2.createDecryptionCipher(g,40);return b.start(x,null),b};break;default:var o=Error("Cannot read PKCS #12 PBE data block. Unsupported OID.");throw o.oid=e,o}var f=Rd(r.prfOid),p=pe.pbe.generatePkcs12Key(n,s,1,a,c,f);f.start();var h=pe.pbe.generatePkcs12Key(n,s,2,a,u,f);return l(p,h)};pe.pbe.opensslDeriveBytes=function(e,t,n,r){if(typeof r>"u"||r===null){if(!("md5"in q.md))throw Error('"md5" hash algorithm unavailable.');r=q.md.md5.create()}if(t===null)t="";var i=[Pd(r,e+t)];for(var o=16,s=1;o<n;++s,o+=16)i.push(Pd(r,i[s-1]+e+t));return i.join("").substr(0,n)};function Pd(e,t){return e.start().update(t).digest().getBytes()}function Rd(e){var t;if(!e)t="hmacWithSHA1";else if(t=pe.oids[B.derToOid(e)],!t){var n=Error("Unsupported PRF OID.");throw n.oid=e,n.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"],n}return Bd(t)}function Bd(e){var t=q.md;switch(e){case"hmacWithSHA224":t=q.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 Ew(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,q.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(pe.oids[r]).getBytes()),B.create(B.Class.UNIVERSAL,B.Type.NULL,!1,"")]));return i}});var wc=le(function(F2,Od){var Mn=he();Qt();Te();var G=Mn.asn1,Vn=Od.exports=Mn.pkcs7asn1=Mn.pkcs7asn1||{};Mn.pkcs7=Mn.pkcs7||{};Mn.pkcs7.asn1=Vn;var Dd={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"}]};Vn.contentInfoValidator=Dd;var $d={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"}]};Vn.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($d)};Vn.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($d)};var _w={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"}]};Vn.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"},Dd,{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:[_w]}]};Vn.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 Ec=le(function(M2,Ld){var mn=he();Te();mn.mgf=mn.mgf||{};var Tw=Ld.exports=mn.mgf.mgf1=mn.mgf1=mn.mgf1||{};Tw.create=function(e){var t={generate:function(n,r){var i=new mn.util.ByteBuffer,o=Math.ceil(r/e.digestLength);for(var s=0;s<o;s++){var a=new mn.util.ByteBuffer;a.putInt32(s),e.start(),e.update(n+a.getBytes()),i.putBuffer(e.digest())}return i.truncate(i.length()-r),i.getBytes()}};return t}});var zd=le(function(V2,Ud){var ns=he();Ec();Ud.exports=ns.mgf=ns.mgf||{};ns.mgf.mgf1=ns.mgf1});var is=le(function(W2,Fd){var gn=he();Ft();Te();var Aw=Fd.exports=gn.pss=gn.pss||{};Aw.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=gn.util.createBuffer(i);var o;if("saltLength"in e)o=e.saltLength;else if(i!==null)o=i.length();else throw Error("Salt length not specified or specific salt not given.");if(i!==null&&i.length()!==o)throw Error("Given salt length does not match length of given salt.");var s=e.prng||gn.random,a={};return a.encode=function(c,u){var l,f=u-1,p=Math.ceil(f/8),h=c.digest().getBytes();if(p<r+o+2)throw Error("Message is too long to encrypt.");var d;if(i===null)d=s.getBytesSync(o);else d=i.bytes();var g=new gn.util.ByteBuffer;g.fillWithByte(0,8),g.putBytes(h),g.putBytes(d),t.start(),t.update(g.getBytes());var x=t.digest().getBytes(),b=new gn.util.ByteBuffer;b.fillWithByte(0,p-o-r-2),b.putByte(1),b.putBytes(d);var S=b.getBytes(),C=p-r-1,T=n.generate(x,C),I="";for(l=0;l<C;l++)I+=String.fromCharCode(S.charCodeAt(l)^T.charCodeAt(l));var k=65280>>8*p-f&255;return I=String.fromCharCode(I.charCodeAt(0)&~k)+I.substr(1),I+x+String.fromCharCode(188)},a.verify=function(c,u,l){var f,p=l-1,h=Math.ceil(p/8);if(u=u.substr(-h),h<r+o+2)throw Error("Inconsistent parameters to PSS signature verification.");if(u.charCodeAt(h-1)!==188)throw Error("Encoded message does not end in 0xBC.");var d=h-r-1,g=u.substr(0,d),x=u.substr(d,r),b=65280>>8*h-p&255;if((g.charCodeAt(0)&b)!==0)throw Error("Bits beyond keysize not zero as expected.");var S=n.generate(x,d),C="";for(f=0;f<d;f++)C+=String.fromCharCode(g.charCodeAt(f)^S.charCodeAt(f));C=String.fromCharCode(C.charCodeAt(0)&~b)+C.substr(1);var T=h-r-o-2;for(f=0;f<T;f++)if(C.charCodeAt(f)!==0)throw Error("Leftmost octets not zero as expected");if(C.charCodeAt(T)!==1)throw Error("Inconsistent PSS signature, 0x01 marker not found");var I=C.substr(-o),k=new gn.util.ByteBuffer;k.fillWithByte(0,8),k.putBytes(c),k.putBytes(I),t.start(),t.update(k.getBytes());var R=t.digest().getBytes();return x===R},a}});var cs=le(function(H2,Yd){var X=he();Vr();Qt();Bi();ur();zd();Wr();fn();is();$i();Te();var m=X.asn1,M=Yd.exports=X.pki=X.pki||{},Se=M.oids,Je={};Je.CN=Se.commonName;Je.commonName="CN";Je.C=Se.countryName;Je.countryName="C";Je.L=Se.localityName;Je.localityName="L";Je.ST=Se.stateOrProvinceName;Je.stateOrProvinceName="ST";Je.O=Se.organizationName;Je.organizationName="O";Je.OU=Se.organizationalUnitName;Je.organizationalUnitName="OU";Je.E=Se.emailAddress;Je.emailAddress="E";var Gd=X.pki.rsa.publicKeyValidator,kw={name:"Certificate",tagClass:m.Class.UNIVERSAL,type:m.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate",tagClass:m.Class.UNIVERSAL,type:m.Type.SEQUENCE,constructed:!0,captureAsn1:"tbsCertificate",value:[{name:"Certificate.TBSCertificate.version",tagClass:m.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.version.integer",tagClass:m.Class.UNIVERSAL,type:m.Type.INTEGER,constructed:!1,capture:"certVersion"}]},{name:"Certificate.TBSCertificate.serialNumber",tagClass:m.Class.UNIVERSAL,type:m.Type.INTEGER,constructed:!1,capture:"certSerialNumber"},{name:"Certificate.TBSCertificate.signature",tagClass:m.Class.UNIVERSAL,type:m.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate.signature.algorithm",tagClass:m.Class.UNIVERSAL,type:m.Type.OID,constructed:!1,capture:"certinfoSignatureOid"},{name:"Certificate.TBSCertificate.signature.parameters",tagClass:m.Class.UNIVERSAL,optional:!0,captureAsn1:"certinfoSignatureParams"}]},{name:"Certificate.TBSCertificate.issuer",tagClass:m.Class.UNIVERSAL,type:m.Type.SEQUENCE,constructed:!0,captureAsn1:"certIssuer"},{name:"Certificate.TBSCertificate.validity",tagClass:m.Class.UNIVERSAL,type:m.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate.validity.notBefore (utc)",tagClass:m.Class.UNIVERSAL,type:m.Type.UTCTIME,constructed:!1,optional:!0,capture:"certValidity1UTCTime"},{name:"Certificate.TBSCertificate.validity.notBefore (generalized)",tagClass:m.Class.UNIVERSAL,type:m.Type.GENERALIZEDTIME,constructed:!1,optional:!0,capture:"certValidity2GeneralizedTime"},{name:"Certificate.TBSCertificate.validity.notAfter (utc)",tagClass:m.Class.UNIVERSAL,type:m.Type.UTCTIME,constructed:!1,optional:!0,capture:"certValidity3UTCTime"},{name:"Certificate.TBSCertificate.validity.notAfter (generalized)",tagClass:m.Class.UNIVERSAL,type:m.Type.GENERALIZEDTIME,constructed:!1,optional:!0,capture:"certValidity4GeneralizedTime"}]},{name:"Certificate.TBSCertificate.subject",tagClass:m.Class.UNIVERSAL,type:m.Type.SEQUENCE,constructed:!0,captureAsn1:"certSubject"},Gd,{name:"Certificate.TBSCertificate.issuerUniqueID",tagClass:m.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.issuerUniqueID.id",tagClass:m.Class.UNIVERSAL,type:m.Type.BITSTRING,constructed:!1,captureBitStringValue:"certIssuerUniqueId"}]},{name:"Certificate.TBSCertificate.subjectUniqueID",tagClass:m.Class.CONTEXT_SPECIFIC,type:2,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.subjectUniqueID.id",tagClass:m.Class.UNIVERSAL,type:m.Type.BITSTRING,constructed:!1,captureBitStringValue:"certSubjectUniqueId"}]},{name:"Certificate.TBSCertificate.extensions",tagClass:m.Class.CONTEXT_SPECIFIC,type:3,constructed:!0,captureAsn1:"certExtensions",optional:!0}]},{name:"Certificate.signatureAlgorithm",tagClass:m.Class.UNIVERSAL,type:m.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.signatureAlgorithm.algorithm",tagClass:m.Class.UNIVERSAL,type:m.Type.OID,constructed:!1,capture:"certSignatureOid"},{name:"Certificate.TBSCertificate.signature.parameters",tagClass:m.Class.UNIVERSAL,optional:!0,captureAsn1:"certSignatureParams"}]},{name:"Certificate.signatureValue",tagClass:m.Class.UNIVERSAL,type:m.Type.BITSTRING,constructed:!1,captureBitStringValue:"certSignature"}]},Iw={name:"rsapss",tagClass:m.Class.UNIVERSAL,type:m.Type.SEQUENCE,constructed:!0,value:[{name:"rsapss.hashAlgorithm",tagClass:m.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,value:[{name:"rsapss.hashAlgorithm.AlgorithmIdentifier",tagClass:m.Class.UNIVERSAL,type:m.Class.SEQUENCE,constructed:!0,optional:!0,value:[{name:"rsapss.hashAlgorithm.AlgorithmIdentifier.algorithm",tagClass:m.Class.UNIVERSAL,type:m.Type.OID,constructed:!1,capture:"hashOid"}]}]},{name:"rsapss.maskGenAlgorithm",tagClass:m.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier",tagClass:m.Class.UNIVERSAL,type:m.Class.SEQUENCE,constructed:!0,optional:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.algorithm",tagClass:m.Class.UNIVERSAL,type:m.Type.OID,constructed:!1,capture:"maskGenOid"},{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.params",tagClass:m.Class.UNIVERSAL,type:m.Type.SEQUENCE,constructed:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.params.algorithm",tagClass:m.Class.UNIVERSAL,type:m.Type.OID,constructed:!1,capture:"maskGenHashOid"}]}]}]},{name:"rsapss.saltLength",tagClass:m.Class.CONTEXT_SPECIFIC,type:2,optional:!0,value:[{name:"rsapss.saltLength.saltLength",tagClass:m.Class.UNIVERSAL,type:m.Class.INTEGER,constructed:!1,capture:"saltLength"}]},{name:"rsapss.trailerField",tagClass:m.Class.CONTEXT_SPECIFIC,type:3,optional:!0,value:[{name:"rsapss.trailer.trailer",tagClass:m.Class.UNIVERSAL,type:m.Class.INTEGER,constructed:!1,capture:"trailer"}]}]},Pw={name:"CertificationRequestInfo",tagClass:m.Class.UNIVERSAL,type:m.Type.SEQUENCE,constructed:!0,captureAsn1:"certificationRequestInfo",value:[{name:"CertificationRequestInfo.integer",tagClass:m.Class.UNIVERSAL,type:m.Type.INTEGER,constructed:!1,capture:"certificationRequestInfoVersion"},{name:"CertificationRequestInfo.subject",tagClass:m.Class.UNIVERSAL,type:m.Type.SEQUENCE,constructed:!0,captureAsn1:"certificationRequestInfoSubject"},Gd,{name:"CertificationRequestInfo.attributes",tagClass:m.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,capture:"certificationRequestInfoAttributes",value:[{name:"CertificationRequestInfo.attributes",tagClass:m.Class.UNIVERSAL,type:m.Type.SEQUENCE,constructed:!0,value:[{name:"CertificationRequestInfo.attributes.type",tagClass:m.Class.UNIVERSAL,type:m.Type.OID,constructed:!1},{name:"CertificationRequestInfo.attributes.value",tagClass:m.Class.UNIVERSAL,type:m.Type.SET,constructed:!0}]}]}]},Rw={name:"CertificationRequest",tagClass:m.Class.UNIVERSAL,type:m.Type.SEQUENCE,constructed:!0,captureAsn1:"csr",value:[Pw,{name:"CertificationRequest.signatureAlgorithm",tagClass:m.Class.UNIVERSAL,type:m.Type.SEQUENCE,constructed:!0,value:[{name:"CertificationRequest.signatureAlgorithm.algorithm",tagClass:m.Class.UNIVERSAL,type:m.Type.OID,constructed:!1,capture:"csrSignatureOid"},{name:"CertificationRequest.signatureAlgorithm.parameters",tagClass:m.Class.UNIVERSAL,optional:!0,captureAsn1:"csrSignatureParams"}]},{name:"CertificationRequest.signature",tagClass:m.Class.UNIVERSAL,type:m.Type.BITSTRING,constructed:!1,captureBitStringValue:"csrSignature"}]};M.RDNAttributesAsArray=function(e,t){var n=[],r,i,o;for(var s=0;s<e.value.length;++s){r=e.value[s];for(var a=0;a<r.value.length;++a){if(o={},i=r.value[a],o.type=m.derToOid(i.value[0].value),o.value=i.value[1].value,o.valueTagClass=i.value[1].type,o.type in Se){if(o.name=Se[o.type],o.name in Je)o.shortName=Je[o.name]}if(t)t.update(o.type),t.update(o.value);n.push(o)}}return n};M.CRIAttributesAsArray=function(e){var t=[];for(var n=0;n<e.length;++n){var r=e[n],i=m.derToOid(r.value[0].value),o=r.value[1].value;for(var s=0;s<o.length;++s){var a={};if(a.type=i,a.value=o[s].value,a.valueTagClass=o[s].type,a.type in Se){if(a.name=Se[a.type],a.name in Je)a.shortName=Je[a.name]}if(a.type===Se.extensionRequest){a.extensions=[];for(var c=0;c<a.value.length;++c)a.extensions.push(M.certificateExtensionFromAsn1(a.value[c]))}t.push(a)}}return t};function Zr(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 ss=function(e,t,n){var r={};if(e!==Se["RSASSA-PSS"])return r;if(n)r={hash:{algorithmOid:Se.sha1},mgf:{algorithmOid:Se.mgf1,hash:{algorithmOid:Se.sha1}},saltLength:20};var i={},o=[];if(!m.validate(t,Iw,i,o)){var s=Error("Cannot read RSASSA-PSS parameter block.");throw s.errors=o,s}if(i.hashOid!==void 0)r.hash=r.hash||{},r.hash.algorithmOid=m.derToOid(i.hashOid);if(i.maskGenOid!==void 0)r.mgf=r.mgf||{},r.mgf.algorithmOid=m.derToOid(i.maskGenOid),r.mgf.hash=r.mgf.hash||{},r.mgf.hash.algorithmOid=m.derToOid(i.maskGenHashOid);if(i.saltLength!==void 0)r.saltLength=i.saltLength.charCodeAt(0);return r},as=function(e){switch(Se[e.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 t=Error("Could not compute "+e.type+" digest. Unknown signature OID.");throw t.signatureOid=e.signatureOid,t}},qd=function(e){var t=e.certificate,n=e.publicKey||t.publicKey,r;switch(t.signatureOid){case Se.sha1WithRSAEncryption:case Se.sha1WithRSASignature:break;case Se["RSASSA-PSS"]:var i,o;if(i=Se[t.signatureParameters.mgf.hash.algorithmOid],i===void 0||X.md[i]===void 0){var s=Error("Unsupported MGF hash function.");throw s.oid=t.signatureParameters.mgf.hash.algorithmOid,s.name=i,s}if(o=Se[t.signatureParameters.mgf.algorithmOid],o===void 0||X.mgf[o]===void 0){var s=Error("Unsupported MGF function.");throw s.oid=t.signatureParameters.mgf.algorithmOid,s.name=o,s}if(o=X.mgf[o].create(X.md[i].create()),i=Se[t.signatureParameters.hash.algorithmOid],i===void 0||X.md[i]===void 0){var s=Error("Unsupported RSASSA-PSS hash function.");throw s.oid=t.signatureParameters.hash.algorithmOid,s.name=i,s}r=X.pss.create(X.md[i].create(),o,t.signatureParameters.saltLength);break}return n.verify(e.md.digest().getBytes(),e.signature,r)};M.certificateFromPem=function(e,t,n){var r=X.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 o=m.fromDer(r.body,n);return M.certificateFromAsn1(o,t)};M.certificateToPem=function(e,t){var n={type:"CERTIFICATE",body:m.toDer(M.certificateToAsn1(e)).getBytes()};return X.pem.encode(n,{maxline:t})};M.publicKeyFromPem=function(e){var t=X.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=m.fromDer(t.body);return M.publicKeyFromAsn1(r)};M.publicKeyToPem=function(e,t){var n={type:"PUBLIC KEY",body:m.toDer(M.publicKeyToAsn1(e)).getBytes()};return X.pem.encode(n,{maxline:t})};M.publicKeyToRSAPublicKeyPem=function(e,t){var n={type:"RSA PUBLIC KEY",body:m.toDer(M.publicKeyToRSAPublicKey(e)).getBytes()};return X.pem.encode(n,{maxline:t})};M.getPublicKeyFingerprint=function(e,t){t=t||{};var n=t.md||X.md.sha1.create(),r=t.type||"RSAPublicKey",i;switch(r){case"RSAPublicKey":i=m.toDer(M.publicKeyToRSAPublicKey(e)).getBytes();break;case"SubjectPublicKeyInfo":i=m.toDer(M.publicKeyToAsn1(e)).getBytes();break;default:throw Error('Unknown fingerprint type "'+t.type+'".')}n.start(),n.update(i);var o=n.digest();if(t.encoding==="hex"){var s=o.toHex();if(t.delimiter)return s.match(/.{2}/g).join(t.delimiter);return s}else if(t.encoding==="binary")return o.getBytes();else if(t.encoding)throw Error('Unknown encoding "'+t.encoding+'".');return o};M.certificationRequestFromPem=function(e,t,n){var r=X.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 o=m.fromDer(r.body,n);return M.certificationRequestFromAsn1(o,t)};M.certificationRequestToPem=function(e,t){var n={type:"CERTIFICATE REQUEST",body:m.toDer(M.certificationRequestToAsn1(e)).getBytes()};return X.pem.encode(n,{maxline:t})};M.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 Zr(e.issuer,t)},e.issuer.addField=function(t){Wt([t]),e.issuer.attributes.push(t)},e.issuer.attributes=[],e.issuer.hash=null,e.subject={},e.subject.getField=function(t){return Zr(e.subject,t)},e.subject.addField=function(t){Wt([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(Wt(t),e.subject.attributes=t,delete e.subject.uniqueId,n)e.subject.uniqueId=n;e.subject.hash=null},e.setIssuer=function(t,n){if(Wt(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)Jd(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||X.md.sha1.create();var r=Se[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=M.getTBSCertificate(e);var o=m.toDer(e.tbsCertificate);e.md.update(o.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,o=Error("The parent certificate did not issue the given child certificate; the child certificate's issuer does not match the parent's subject.");throw o.expectedIssuer=i.attributes,o.actualIssuer=r.attributes,o}var s=t.md;if(s===null){s=as({signatureOid:t.signatureOid,type:"certificate"});var a=t.tbsCertificate||M.getTBSCertificate(t),c=m.toDer(a);s.update(c.getBytes())}if(s!==null)n=qd({certificate:t,publicKey:e.publicKey,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 o,s;for(var a=0;n&&a<r.attributes.length;++a)if(o=r.attributes[a],s=i.attributes[a],o.type!==s.type||o.value!==s.value)n=!1}return n},e.issued=function(t){return t.isIssuer(e)},e.generateSubjectKeyIdentifier=function(){return M.getPublicKeyFingerprint(e.publicKey,{type:"RSAPublicKey"})},e.verifySubjectKeyIdentifier=function(){var t=Se.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 X.util.hexToBytes(r.subjectKeyIdentifier)===i}}return!1},e};M.certificateFromAsn1=function(e,t){var n={},r=[];if(!m.validate(e,kw,n,r)){var i=Error("Cannot read X.509 certificate. ASN.1 object is not an X509v3 Certificate.");throw i.errors=r,i}var o=m.derToOid(n.publicKeyOid);if(o!==M.oids.rsaEncryption)throw Error("Cannot read public key. OID is not RSA.");var s=M.createCertificate();s.version=n.certVersion?n.certVersion.charCodeAt(0):0;var a=X.util.createBuffer(n.certSerialNumber);s.serialNumber=a.toHex(),s.signatureOid=X.asn1.derToOid(n.certSignatureOid),s.signatureParameters=ss(s.signatureOid,n.certSignatureParams,!0),s.siginfo.algorithmOid=X.asn1.derToOid(n.certinfoSignatureOid),s.siginfo.parameters=ss(s.siginfo.algorithmOid,n.certinfoSignatureParams,!1),s.signature=n.certSignature;var c=[];if(n.certValidity1UTCTime!==void 0)c.push(m.utcTimeToDate(n.certValidity1UTCTime));if(n.certValidity2GeneralizedTime!==void 0)c.push(m.generalizedTimeToDate(n.certValidity2GeneralizedTime));if(n.certValidity3UTCTime!==void 0)c.push(m.utcTimeToDate(n.certValidity3UTCTime));if(n.certValidity4GeneralizedTime!==void 0)c.push(m.generalizedTimeToDate(n.certValidity4GeneralizedTime));if(c.length>2)throw Error("Cannot read notBefore/notAfter validity times; more than two times were provided in the certificate.");if(c.length<2)throw Error("Cannot read notBefore/notAfter validity times; they were not provided as either UTCTime or GeneralizedTime.");if(s.validity.notBefore=c[0],s.validity.notAfter=c[1],s.tbsCertificate=n.tbsCertificate,t){s.md=as({signatureOid:s.signatureOid,type:"certificate"});var u=m.toDer(s.tbsCertificate);s.md.update(u.getBytes())}var l=X.md.sha1.create(),f=m.toDer(n.certIssuer);if(l.update(f.getBytes()),s.issuer.getField=function(d){return Zr(s.issuer,d)},s.issuer.addField=function(d){Wt([d]),s.issuer.attributes.push(d)},s.issuer.attributes=M.RDNAttributesAsArray(n.certIssuer),n.certIssuerUniqueId)s.issuer.uniqueId=n.certIssuerUniqueId;s.issuer.hash=l.digest().toHex();var p=X.md.sha1.create(),h=m.toDer(n.certSubject);if(p.update(h.getBytes()),s.subject.getField=function(d){return Zr(s.subject,d)},s.subject.addField=function(d){Wt([d]),s.subject.attributes.push(d)},s.subject.attributes=M.RDNAttributesAsArray(n.certSubject),n.certSubjectUniqueId)s.subject.uniqueId=n.certSubjectUniqueId;if(s.subject.hash=p.digest().toHex(),n.certExtensions)s.extensions=M.certificateExtensionsFromAsn1(n.certExtensions);else s.extensions=[];return s.publicKey=M.publicKeyFromAsn1(n.subjectPublicKeyInfo),s};M.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(M.certificateExtensionFromAsn1(r.value[i]))}return t};M.certificateExtensionFromAsn1=function(e){var t={};if(t.id=m.derToOid(e.value[0].value),t.critical=!1,e.value[1].type===m.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 Se){if(t.name=Se[t.id],t.name==="keyUsage"){var n=m.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=m.fromDer(t.value);if(n.value.length>0&&n.value[0].type===m.Type.BOOLEAN)t.cA=n.value[0].value.charCodeAt(0)!==0;else t.cA=!1;var o=null;if(n.value.length>0&&n.value[0].type===m.Type.INTEGER)o=n.value[0].value;else if(n.value.length>1)o=n.value[1].value;if(o!==null)t.pathLenConstraint=m.derToInteger(o)}else if(t.name==="extKeyUsage"){var n=m.fromDer(t.value);for(var s=0;s<n.value.length;++s){var a=m.derToOid(n.value[s].value);if(a in Se)t[Se[a]]=!0;else t[a]=!0}}else if(t.name==="nsCertType"){var n=m.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 c,n=m.fromDer(t.value);for(var u=0;u<n.value.length;++u){c=n.value[u];var l={type:c.type,value:c.value};switch(t.altNames.push(l),c.type){case 1:case 2:case 6:break;case 7:l.ip=X.util.bytesToIP(c.value);break;case 8:l.oid=m.derToOid(c.value);break;default:}}}else if(t.name==="nameConstraints"&&t.id==="2.5.29.30")try{var f=Xd(m.fromDer(t.value));t.permittedSubtrees=f.permittedSubtrees,t.excludedSubtrees=f.excludedSubtrees,t.unsupportedSubtreeRange=f.unsupportedSubtreeRange}catch(p){}else if(t.name==="subjectKeyIdentifier"){var n=m.fromDer(t.value);t.subjectKeyIdentifier=X.util.bytesToHex(n.value)}}return t};function Xd(e){var t={permittedSubtrees:[],excludedSubtrees:[],unsupportedSubtreeRange:!1};if(e.tagClass!==m.Class.UNIVERSAL||e.type!==m.Type.SEQUENCE||!X.util.isArray(e.value))throw Error("Invalid nameConstraints extension.");for(var n=0;n<e.value.length;++n){var r=e.value[n],i;if(r.tagClass===m.Class.CONTEXT_SPECIFIC&&r.type===0)i=t.permittedSubtrees;else if(r.tagClass===m.Class.CONTEXT_SPECIFIC&&r.type===1)i=t.excludedSubtrees;else throw Error("Invalid nameConstraints extension.");if(!X.util.isArray(r.value))throw Error("Invalid nameConstraints extension.");for(var o=0;o<r.value.length;++o){var s=r.value[o];if(s.type!==m.Type.SEQUENCE||!X.util.isArray(s.value)||s.value.length===0||s.value[0].tagClass!==m.Class.CONTEXT_SPECIFIC)throw Error("Invalid nameConstraints extension.");var a=s.value[0],c={type:a.type,value:a.value};if(a.type===4&&X.util.isArray(a.value)&&a.value.length===1&&a.value[0].type===m.Type.SEQUENCE&&X.util.isArray(a.value[0].value))c.attributes=M.RDNAttributesAsArray(a.value[0]);for(var u=1;u<s.value.length;++u){var l=s.value[u];if(l.tagClass===m.Class.CONTEXT_SPECIFIC&&l.type===0){if(c.minimum=m.derToInteger(l.value),c.minimum!==0)t.unsupportedSubtreeRange=!0}else if(l.tagClass===m.Class.CONTEXT_SPECIFIC&&l.type===1)c.maximum=m.derToInteger(l.value),t.unsupportedSubtreeRange=!0;else throw Error("Invalid nameConstraints extension.")}i.push(c)}}return t}M.certificationRequestFromAsn1=function(e,t){var n={},r=[];if(!m.validate(e,Rw,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 o=m.derToOid(n.publicKeyOid);if(o!==M.oids.rsaEncryption)throw Error("Cannot read public key. OID is not RSA.");var s=M.createCertificationRequest();if(s.version=n.csrVersion?n.csrVersion.charCodeAt(0):0,s.signatureOid=X.asn1.derToOid(n.csrSignatureOid),s.signatureParameters=ss(s.signatureOid,n.csrSignatureParams,!0),s.siginfo.algorithmOid=X.asn1.derToOid(n.csrSignatureOid),s.siginfo.parameters=ss(s.siginfo.algorithmOid,n.csrSignatureParams,!1),s.signature=n.csrSignature,s.certificationRequestInfo=n.certificationRequestInfo,t){s.md=as({signatureOid:s.signatureOid,type:"certification request"});var a=m.toDer(s.certificationRequestInfo);s.md.update(a.getBytes())}var c=X.md.sha1.create();return s.subject.getField=function(u){return Zr(s.subject,u)},s.subject.addField=function(u){Wt([u]),s.subject.attributes.push(u)},s.subject.attributes=M.RDNAttributesAsArray(n.certificationRequestInfoSubject,c),s.subject.hash=c.digest().toHex(),s.publicKey=M.publicKeyFromAsn1(n.subjectPublicKeyInfo),s.getAttribute=function(u){return Zr(s,u)},s.addAttribute=function(u){Wt([u]),s.attributes.push(u)},s.attributes=M.CRIAttributesAsArray(n.certificationRequestInfoAttributes||[]),s};M.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 Zr(e.subject,t)},e.subject.addField=function(t){Wt([t]),e.subject.attributes.push(t)},e.subject.attributes=[],e.subject.hash=null,e.publicKey=null,e.attributes=[],e.getAttribute=function(t){return Zr(e,t)},e.addAttribute=function(t){Wt([t]),e.attributes.push(t)},e.md=null,e.setSubject=function(t){Wt(t),e.subject.attributes=t,e.subject.hash=null},e.setAttributes=function(t){Wt(t),e.attributes=t},e.sign=function(t,n){e.md=n||X.md.sha1.create();var r=Se[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=M.getCertificationRequestInfo(e);var o=m.toDer(e.certificationRequestInfo);e.md.update(o.getBytes()),e.signature=t.sign(e.md)},e.verify=function(){var t=!1,n=e.md;if(n===null){n=as({signatureOid:e.signatureOid,type:"certification request"});var r=e.certificationRequestInfo||M.getCertificationRequestInfo(e),i=m.toDer(r);n.update(i.getBytes())}if(n!==null)t=qd({certificate:e,md:n,signature:e.signature});return t},e};function Wn(e){var t=m.create(m.Class.UNIVERSAL,m.Type.SEQUENCE,!0,[]),n,r,i=e.attributes;for(var o=0;o<i.length;++o){n=i[o];var s=n.value,a=m.Type.PRINTABLESTRING;if("valueTagClass"in n){if(a=n.valueTagClass,a===m.Type.UTF8)s=X.util.encodeUtf8(s)}r=m.create(m.Class.UNIVERSAL,m.Type.SET,!0,[m.create(m.Class.UNIVERSAL,m.Type.SEQUENCE,!0,[m.create(m.Class.UNIVERSAL,m.Type.OID,!1,m.oidToDer(n.type).getBytes()),m.create(m.Class.UNIVERSAL,a,!1,s)])]),t.value.push(r)}return t}function Wt(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 M.oids)t.name=M.oids[t.type];else if(t.shortName&&t.shortName in Je)t.name=M.oids[Je[t.shortName]]}if(typeof t.type>"u")if(t.name&&t.name in M.oids)t.type=M.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 Je)t.shortName=Je[t.name]}if(t.type===Se.extensionRequest){if(t.valueConstructed=!0,t.valueTagClass=m.Type.SEQUENCE,!t.value&&t.extensions){t.value=[];for(var i=0;i<t.extensions.length;++i)t.value.push(M.certificateExtensionToAsn1(Jd(t.extensions[i])))}}if(typeof t.value>"u"){var r=Error("Attribute value not specified.");throw r.attribute=t,r}}}function Jd(e,t){if(t=t||{},typeof e.name>"u"){if(e.id&&e.id in M.oids)e.name=M.oids[e.id]}if(typeof e.id>"u")if(e.name&&e.name in M.oids)e.id=M.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,o=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)o|=128,r=7;var s=String.fromCharCode(r);if(o!==0)s+=String.fromCharCode(i)+String.fromCharCode(o);else if(i!==0)s+=String.fromCharCode(i);e.value=m.create(m.Class.UNIVERSAL,m.Type.BITSTRING,!1,s)}else if(e.name==="basicConstraints"){if(e.value=m.create(m.Class.UNIVERSAL,m.Type.SEQUENCE,!0,[]),e.cA)e.value.value.push(m.create(m.Class.UNIVERSAL,m.Type.BOOLEAN,!1,String.fromCharCode(255)));if("pathLenConstraint"in e)e.value.value.push(m.create(m.Class.UNIVERSAL,m.Type.INTEGER,!1,m.integerToDer(e.pathLenConstraint).getBytes()))}else if(e.name==="extKeyUsage"){e.value=m.create(m.Class.UNIVERSAL,m.Type.SEQUENCE,!0,[]);var a=e.value.value;for(var c in e){if(e[c]!==!0)continue;if(c in Se)a.push(m.create(m.Class.UNIVERSAL,m.Type.OID,!1,m.oidToDer(Se[c]).getBytes()));else if(c.indexOf(".")!==-1)a.push(m.create(m.Class.UNIVERSAL,m.Type.OID,!1,m.oidToDer(c).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=m.create(m.Class.UNIVERSAL,m.Type.BITSTRING,!1,s)}else if(e.name==="subjectAltName"||e.name==="issuerAltName"){e.value=m.create(m.Class.UNIVERSAL,m.Type.SEQUENCE,!0,[]);var u;for(var l=0;l<e.altNames.length;++l){u=e.altNames[l];var s=u.value;if(u.type===7&&u.ip){if(s=X.util.bytesFromIP(u.ip),s===null){var n=Error('Extension "ip" value is not a valid IPv4 or IPv6 address.');throw n.extension=e,n}}else if(u.type===8)if(u.oid)s=m.oidToDer(m.oidToDer(u.oid));else s=m.oidToDer(s);e.value.value.push(m.create(m.Class.CONTEXT_SPECIFIC,u.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=m.create(m.Class.UNIVERSAL,m.Type.IA5STRING,!1,e.comment)}else if(e.name==="subjectKeyIdentifier"&&t.cert){var f=t.cert.generateSubjectKeyIdentifier();e.subjectKeyIdentifier=f.toHex(),e.value=m.create(m.Class.UNIVERSAL,m.Type.OCTETSTRING,!1,f.getBytes())}else if(e.name==="authorityKeyIdentifier"&&t.cert){e.value=m.create(m.Class.UNIVERSAL,m.Type.SEQUENCE,!0,[]);var a=e.value.value;if(e.keyIdentifier){var p=e.keyIdentifier===!0?t.cert.generateSubjectKeyIdentifier().getBytes():e.keyIdentifier;a.push(m.create(m.Class.CONTEXT_SPECIFIC,0,!1,p))}if(e.authorityCertIssuer){var h=[m.create(m.Class.CONTEXT_SPECIFIC,4,!0,[Wn(e.authorityCertIssuer===!0?t.cert.issuer:e.authorityCertIssuer)])];a.push(m.create(m.Class.CONTEXT_SPECIFIC,1,!0,h))}if(e.serialNumber){var d=X.util.hexToBytes(e.serialNumber===!0?t.cert.serialNumber:e.serialNumber);a.push(m.create(m.Class.CONTEXT_SPECIFIC,2,!1,d))}}else if(e.name==="cRLDistributionPoints"){e.value=m.create(m.Class.UNIVERSAL,m.Type.SEQUENCE,!0,[]);var a=e.value.value,g=m.create(m.Class.UNIVERSAL,m.Type.SEQUENCE,!0,[]),x=m.create(m.Class.CONTEXT_SPECIFIC,0,!0,[]),u;for(var l=0;l<e.altNames.length;++l){u=e.altNames[l];var s=u.value;if(u.type===7&&u.ip){if(s=X.util.bytesFromIP(u.ip),s===null){var n=Error('Extension "ip" value is not a valid IPv4 or IPv6 address.');throw n.extension=e,n}}else if(u.type===8)if(u.oid)s=m.oidToDer(m.oidToDer(u.oid));else s=m.oidToDer(s);x.value.push(m.create(m.Class.CONTEXT_SPECIFIC,u.type,!1,s))}g.value.push(m.create(m.Class.CONTEXT_SPECIFIC,0,!0,[x])),a.push(g)}if(typeof e.value>"u"){var n=Error("Extension value not specified.");throw n.extension=e,n}return e}function Tc(e,t){switch(e){case Se["RSASSA-PSS"]:var n=[];if(t.hash.algorithmOid!==void 0)n.push(m.create(m.Class.CONTEXT_SPECIFIC,0,!0,[m.create(m.Class.UNIVERSAL,m.Type.SEQUENCE,!0,[m.create(m.Class.UNIVERSAL,m.Type.OID,!1,m.oidToDer(t.hash.algorithmOid).getBytes()),m.create(m.Class.UNIVERSAL,m.Type.NULL,!1,"")])]));if(t.mgf.algorithmOid!==void 0)n.push(m.create(m.Class.CONTEXT_SPECIFIC,1,!0,[m.create(m.Class.UNIVERSAL,m.Type.SEQUENCE,!0,[m.create(m.Class.UNIVERSAL,m.Type.OID,!1,m.oidToDer(t.mgf.algorithmOid).getBytes()),m.create(m.Class.UNIVERSAL,m.Type.SEQUENCE,!0,[m.create(m.Class.UNIVERSAL,m.Type.OID,!1,m.oidToDer(t.mgf.hash.algorithmOid).getBytes()),m.create(m.Class.UNIVERSAL,m.Type.NULL,!1,"")])])]));if(t.saltLength!==void 0)n.push(m.create(m.Class.CONTEXT_SPECIFIC,2,!0,[m.create(m.Class.UNIVERSAL,m.Type.INTEGER,!1,m.integerToDer(t.saltLength).getBytes())]));return m.create(m.Class.UNIVERSAL,m.Type.SEQUENCE,!0,n);default:return m.create(m.Class.UNIVERSAL,m.Type.NULL,!1,"")}}function Bw(e){var t=m.create(m.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],o=i.value,s=m.Type.UTF8;if("valueTagClass"in i)s=i.valueTagClass;if(s===m.Type.UTF8)o=X.util.encodeUtf8(o);var a=!1;if("valueConstructed"in i)a=i.valueConstructed;var c=m.create(m.Class.UNIVERSAL,m.Type.SEQUENCE,!0,[m.create(m.Class.UNIVERSAL,m.Type.OID,!1,m.oidToDer(i.type).getBytes()),m.create(m.Class.UNIVERSAL,m.Type.SET,!0,[m.create(m.Class.UNIVERSAL,s,a,o)])]);t.value.push(c)}return t}var Nw=new Date("1950-01-01T00:00:00Z"),Dw=new Date("2050-01-01T00:00:00Z");function Md(e){if(e>=Nw&&e<Dw)return m.create(m.Class.UNIVERSAL,m.Type.UTCTIME,!1,m.dateToUtcTime(e));else return m.create(m.Class.UNIVERSAL,m.Type.GENERALIZEDTIME,!1,m.dateToGeneralizedTime(e))}M.getTBSCertificate=function(e){var t=Md(e.validity.notBefore),n=Md(e.validity.notAfter),r=m.create(m.Class.UNIVERSAL,m.Type.SEQUENCE,!0,[m.create(m.Class.CONTEXT_SPECIFIC,0,!0,[m.create(m.Class.UNIVERSAL,m.Type.INTEGER,!1,m.integerToDer(e.version).getBytes())]),m.create(m.Class.UNIVERSAL,m.Type.INTEGER,!1,X.util.hexToBytes(e.serialNumber)),m.create(m.Class.UNIVERSAL,m.Type.SEQUENCE,!0,[m.create(m.Class.UNIVERSAL,m.Type.OID,!1,m.oidToDer(e.siginfo.algorithmOid).getBytes()),Tc(e.siginfo.algorithmOid,e.siginfo.parameters)]),Wn(e.issuer),m.create(m.Class.UNIVERSAL,m.Type.SEQUENCE,!0,[t,n]),Wn(e.subject),M.publicKeyToAsn1(e.publicKey)]);if(e.issuer.uniqueId)r.value.push(m.create(m.Class.CONTEXT_SPECIFIC,1,!0,[m.create(m.Class.UNIVERSAL,m.Type.BITSTRING,!1,String.fromCharCode(0)+e.issuer.uniqueId)]));if(e.subject.uniqueId)r.value.push(m.create(m.Class.CONTEXT_SPECIFIC,2,!0,[m.create(m.Class.UNIVERSAL,m.Type.BITSTRING,!1,String.fromCharCode(0)+e.subject.uniqueId)]));if(e.extensions.length>0)r.value.push(M.certificateExtensionsToAsn1(e.extensions));return r};M.getCertificationRequestInfo=function(e){var t=m.create(m.Class.UNIVERSAL,m.Type.SEQUENCE,!0,[m.create(m.Class.UNIVERSAL,m.Type.INTEGER,!1,m.integerToDer(e.version).getBytes()),Wn(e.subject),M.publicKeyToAsn1(e.publicKey),Bw(e)]);return t};M.distinguishedNameToAsn1=function(e){return Wn(e)};M.certificateToAsn1=function(e){var t=e.tbsCertificate||M.getTBSCertificate(e);return m.create(m.Class.UNIVERSAL,m.Type.SEQUENCE,!0,[t,m.create(m.Class.UNIVERSAL,m.Type.SEQUENCE,!0,[m.create(m.Class.UNIVERSAL,m.Type.OID,!1,m.oidToDer(e.signatureOid).getBytes()),Tc(e.signatureOid,e.signatureParameters)]),m.create(m.Class.UNIVERSAL,m.Type.BITSTRING,!1,String.fromCharCode(0)+e.signature)])};M.certificateExtensionsToAsn1=function(e){var t=m.create(m.Class.CONTEXT_SPECIFIC,3,!0,[]),n=m.create(m.Class.UNIVERSAL,m.Type.SEQUENCE,!0,[]);t.value.push(n);for(var r=0;r<e.length;++r)n.value.push(M.certificateExtensionToAsn1(e[r]));return t};M.certificateExtensionToAsn1=function(e){var t=m.create(m.Class.UNIVERSAL,m.Type.SEQUENCE,!0,[]);if(t.value.push(m.create(m.Class.UNIVERSAL,m.Type.OID,!1,m.oidToDer(e.id).getBytes())),e.critical)t.value.push(m.create(m.Class.UNIVERSAL,m.Type.BOOLEAN,!1,String.fromCharCode(255)));var n=e.value;if(typeof e.value!=="string")n=m.toDer(n).getBytes();return t.value.push(m.create(m.Class.UNIVERSAL,m.Type.OCTETSTRING,!1,n)),t};M.certificationRequestToAsn1=function(e){var t=e.certificationRequestInfo||M.getCertificationRequestInfo(e);return m.create(m.Class.UNIVERSAL,m.Type.SEQUENCE,!0,[t,m.create(m.Class.UNIVERSAL,m.Type.SEQUENCE,!0,[m.create(m.Class.UNIVERSAL,m.Type.OID,!1,m.oidToDer(e.signatureOid).getBytes()),Tc(e.signatureOid,e.signatureParameters)]),m.create(m.Class.UNIVERSAL,m.Type.BITSTRING,!1,String.fromCharCode(0)+e.signature)])};M.createCaStore=function(e){var t={certs:{}};t.getIssuer=function(s){var a=n(s.issuer);return a},t.addCertificate=function(s){if(typeof s==="string")s=X.pki.certificateFromPem(s);if(r(s.subject),!t.hasCertificate(s))if(s.subject.hash in t.certs){var a=t.certs[s.subject.hash];if(!X.util.isArray(a))a=[a];a.push(s),t.certs[s.subject.hash]=a}else t.certs[s.subject.hash]=s},t.hasCertificate=function(s){if(typeof s==="string")s=X.pki.certificateFromPem(s);var a=n(s.subject);if(!a)return!1;if(!X.util.isArray(a))a=[a];var c=m.toDer(M.certificateToAsn1(s)).getBytes();for(var u=0;u<a.length;++u){var l=m.toDer(M.certificateToAsn1(a[u])).getBytes();if(c===l)return!0}return!1},t.listAllCertificates=function(){var s=[];for(var a in t.certs)if(t.certs.hasOwnProperty(a)){var c=t.certs[a];if(!X.util.isArray(c))s.push(c);else for(var u=0;u<c.length;++u)s.push(c[u])}return s},t.removeCertificate=function(s){var a;if(typeof s==="string")s=X.pki.certificateFromPem(s);if(r(s.subject),!t.hasCertificate(s))return null;var c=n(s.subject);if(!X.util.isArray(c))return a=t.certs[s.subject.hash],delete t.certs[s.subject.hash],a;var u=m.toDer(M.certificateToAsn1(s)).getBytes();for(var l=0;l<c.length;++l){var f=m.toDer(M.certificateToAsn1(c[l])).getBytes();if(u===f)a=c[l],c.splice(l,1)}if(c.length===0)delete t.certs[s.subject.hash];return a};function n(s){return r(s),t.certs[s.hash]||null}function r(s){if(!s.hash){var a=X.md.sha1.create();s.attributes=M.RDNAttributesAsArray(Wn(s),a),s.hash=a.digest().toHex()}}if(e)for(var i=0;i<e.length;++i){var o=e[i];t.addCertificate(o)}return t};M.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"};var _c={0:"otherName",1:"rfc822Name",2:"dNSName",3:"x400Address",4:"directoryName",5:"ediPartyName",6:"uniformResourceIdentifier",7:"iPAddress",8:"registeredID"},Vd=1048576;function Wd(e){var t=[];for(var n=0;n<e.extensions.length;++n){var r=e.extensions[n];if(r.id!=="2.5.29.30")continue;var i;try{var o=r.value;if(typeof o==="string")o=m.fromDer(o);i=Xd(o)}catch(s){t.push({invalid:!0});continue}t.push({permitted:Hd(i.permittedSubtrees),excluded:Hd(i.excludedSubtrees)})}return t}function Hd(e){var t=[];for(var n=0;n<e.length;++n){var r=e[n],i={type:r.type,supported:$w(r)};if(i.supported)switch(i.type){case 1:var o=r.value.lastIndexOf("@");i.local=o===-1?null:r.value.substr(0,o),i.host=r.value.substr(o+1).toLowerCase();break;case 2:case 6:i.host=r.value.toLowerCase();break;case 4:i.attributes=Qd(r.attributes);break;case 7:i.value=r.value;break}t.push(i)}return t}function $w(e){if(e.minimum&&e.minimum!==0||"maximum"in e)return!1;switch(e.type){case 1:case 2:case 6:return typeof e.value==="string";case 4:return X.util.isArray(e.attributes);case 7:return typeof e.value==="string"&&(e.value.length===8||e.value.length===32)}return!1}function Qd(e){var t=[];for(var n=0;n<e.length;++n){var r=e[n].value;if(typeof r==="string"){if(r=r.replace(/[ \t\n\v\f\r]+/g," "),r.charAt(0)===" ")r=r.substr(1);if(r.charAt(r.length-1)===" ")r=r.substr(0,r.length-1);r=r.replace(/[A-Z]+/g,function(i){return i.toLowerCase()})}t.push({type:e[n].type,value:r})}return t}function Ow(e){if(typeof e!=="string")return!1;var t=!1;for(var n=0;n<e.length;++n){var r=e.charAt(n);if(/[a-zA-Z0-9_]/.test(r))continue;if(n>0&&n<e.length-1){if(r==="-")continue;var i=e.charAt(n+1);if(r==="."&&i!=="."&&i!=="-"&&e.charAt(n-1)!=="-"){t=!0;continue}}return!1}return t}function Lw(e,t){var n={names:[],unsupported:{},types:{}},r=e.subject.attributes,i;if(r.length>0)os(n,4,r);for(i=0;i<r.length;++i)if(r[i].type===Se.emailAddress)os(n,1,r[i].value);var o=!1;for(i=0;i<e.extensions.length;++i){var s=e.extensions[i];if(s.id!=="2.5.29.17")continue;var a=s.altNames||[];for(var c=0;c<a.length;++c){var u=a[c],l=u.value;if(u.type===2)o=!0;switch(u.type){case 4:if(l=null,X.util.isArray(u.value)&&u.value.length===1&&u.value[0].type===m.Type.SEQUENCE&&X.util.isArray(u.value[0].value))l=M.RDNAttributesAsArray(u.value[0]);break;case 7:if(u.ip)l=X.util.bytesFromIP(u.ip);break}os(n,u.type,l)}}if(t&&!o){for(i=0;i<r.length;++i)if(r[i].type===Se.commonName&&Ow(r[i].value))os(n,2,r[i].value)}return n}function os(e,t,n){var r={type:t,value:n},i=!1;switch(e.types[t]=!0,t){case 1:if(i=typeof n==="string"&&n.lastIndexOf("@")!==-1,i){var o=n.lastIndexOf("@");r.local=n.substr(0,o),r.host=n.substr(o+1).toLowerCase()}break;case 2:if(i=typeof n==="string",i)r.host=n.toLowerCase();break;case 4:if(i=X.util.isArray(n),i)r.attributes=Qd(n);break;case 6:var s=typeof n==="string"&&/^[a-zA-Z][a-zA-Z0-9+.\-]*:\/\/([^\/?#]*)/.exec(n);if(s){var a=s[1].substr(s[1].lastIndexOf("@")+1);if(a.charAt(0)==="[")r.host=null;else{var c=a.indexOf(":");if(c!==-1)a=a.substr(0,c);r.host=a.toLowerCase()}i=a.length>0}break;case 7:i=typeof n==="string"&&(n.length===4||n.length===16);break}if(i)e.names.push(r);else e.unsupported[t]=!0}function Kd(e,t){if(t.length===0)return!0;if(t.charAt(0)===".")return e.length>t.length&&e.substr(e.length-t.length)===t;return e===t}function Zd(e,t){var n=e.host,r=t.host,i;switch(e.type){case 1:if(t.local!==null)return(t.local===""||e.local===t.local)&&n===r;return Kd(n,r);case 2:if(r.length===0)return!0;if(r.charAt(0)===".")return n.length>r.length&&n.substr(n.length-r.length)===r;return n===r||n.length>r.length&&n.substr(n.length-r.length-1)==="."+r;case 6:return n!==null&&Kd(n,r);case 4:var o=t.attributes,s=e.attributes;if(o.length>s.length)return!1;for(i=0;i<o.length;++i)if(o[i].type!==s[i].type||o[i].value!==s[i].value)return!1;return!0;case 7:if(n=e.value,r=t.value,r.length!==n.length*2)return!1;for(i=0;i<n.length;++i){var a=r.charCodeAt(n.length+i);if((n.charCodeAt(i)&a)!==(r.charCodeAt(i)&a))return!1}return!0}return!1}function jd(e){if(e.type===4){var t=[];for(var n=0;n<e.value.length;++n){var r=e.value[n];t.push((r.shortName||r.name||r.type)+"="+r.value)}return t.join(", ")}if(e.type===7)return X.util.bytesToIP(e.value);return e.value}function Uw(e,t,n,r,i){if(n===0)return null;var o=Lw(e,r),s=o.names,a,c,u,l,f,p;for(a=0;a<n&&i.checks<=Vd;++a)l=t[a],i.checks+=(s.length+1)*(l.invalid?1:l.permitted.length+l.excluded.length+1);if(i.checks>Vd)return{message:"Certificate name constraints require too many checks.",error:M.certificateError.unsupported_certificate};for(a=0;a<n;++a){if(l=t[a],l.invalid)return{message:"Certificate name constraint could not be parsed.",error:M.certificateError.unsupported_certificate};var h=l.permitted.concat(l.excluded);for(c=0;c<h.length;++c)if(f=h[c],f.type in o.unsupported||!f.supported&&f.type in o.types)return p=_c[f.type]||String(f.type),{message:"Certificate name constraint of type "+p+" is not supported.",error:M.certificateError.unsupported_certificate,nameType:p}}for(u=0;u<s.length;++u){var d=s[u];for(a=0;a<n;++a){l=t[a];var g=!1,x=!1;for(c=0;!x&&c<l.permitted.length;++c)if(f=l.permitted[c],f.type===d.type)g=!0,x=Zd(d,f);if(g&&!x)return{message:"Certificate subject name is not permitted by a name constraint.",error:M.certificateError.bad_certificate,nameValue:jd(d),nameType:_c[d.type]};for(c=0;c<l.excluded.length;++c)if(f=l.excluded[c],f.type===d.type&&Zd(d,f))return{message:"Certificate subject name is excluded by a name constraint.",error:M.certificateError.bad_certificate,nameValue:jd(d),nameType:_c[d.type]}}}return null}M.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 o=[],s=[],a={checks:0},c=r[r.length-1];if(c&&!c.isIssuer(c)){var u=e.getIssuer(c);u=u?X.util.isArray(u)?u.slice():[u]:[];for(var l=0;l<u.length;++l){var f=Wd(u[l]);if(f.length>0){var p=!1;try{p=u[l].verify(c)}catch(W){}for(var h=0;p&&h<f.length;++h)o.push(f[h])}}}for(var d=r.length-1;d>=0;--d){s[d]=o.length;var g=d>0?Wd(r[d]):[];for(var x=0;x<g.length;++x)o.push(g[x])}var b=!0,S=null,C=0;do{var T=t.shift(),I=null,k=!1;if(i){if(i<T.validity.notBefore||i>T.validity.notAfter)S={message:"Certificate is not valid yet or has expired.",error:M.certificateError.certificate_expired,notBefore:T.validity.notBefore,notAfter:T.validity.notAfter,now:i}}if(S===null){if(I=t[0]||e.getIssuer(T),I===null){if(T.isIssuer(T))k=!0,I=T}if(I){var R=X.util.isArray(I)?I.slice():[I],V=!1;while(!V&&R.length>0){I=R.shift();try{V=I.verify(T)}catch(W){}}if(!V)S={message:"Certificate signature is invalid.",error:M.certificateError.bad_certificate}}if(S===null&&(!I||k)&&!e.hasCertificate(T))S={message:"Certificate is not trusted.",error:M.certificateError.unknown_ca}}if(S===null&&I&&!T.isIssuer(I))S={message:"Certificate issuer is invalid.",error:M.certificateError.bad_certificate};if(S===null&&(b||!T.isIssuer(T)))S=Uw(T,o,s[C],b,a);if(S===null){var D={keyUsage:!0,basicConstraints:!0,nameConstraints:!0};for(var F=0;S===null&&F<T.extensions.length;++F){var H=T.extensions[F];if(H.critical&&(!(H.name in D)||H.name==="nameConstraints"&&H.id!=="2.5.29.30"))S={message:"Certificate has an unsupported critical extension.",error:M.certificateError.unsupported_certificate}}}if(S===null&&(!b||t.length===0&&(!I||k))){var re=T.getExtension({id:"2.5.29.19"}),se=T.getExtension("keyUsage");if(se!==null){if(!se.keyCertSign||re===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:M.certificateError.bad_certificate}}if(S===null&&re===null)S={message:"Certificate is missing basicConstraints extension and cannot be used as a CA.",error:M.certificateError.bad_certificate};if(S===null&&re!==null&&!re.cA)S={message:"Certificate basicConstraints indicates the certificate is not a CA.",error:M.certificateError.bad_certificate};if(S===null&&re!==null&&"pathLenConstraint"in re){var Pe=C-1;if(Pe>re.pathLenConstraint)S={message:"Certificate basicConstraints pathLenConstraint violated.",error:M.certificateError.bad_certificate}}}var ue=S===null?!0:S.error,de=n.verify?n.verify(ue,C,r):ue;if(de===!0)S=null;else{if(ue===!0)S={message:"The application rejected the certificate.",error:M.certificateError.bad_certificate};if(de||de===0){if(typeof de==="object"&&!X.util.isArray(de)){if(de.message)S.message=de.message;if(de.error)S.error=de.error}else if(typeof de==="string")S.error=de}throw S}b=!1,++C}while(t.length>0);return!0}});var kc=le(function(K2,tp){var Ue=he();Qt();On();Wr();wc();Cc();Ft();$i();Fn();Te();cs();var{asn1:E,pki:xe}=Ue,Li=tp.exports=Ue.pkcs12=Ue.pkcs12||{},ep={name:"ContentInfo",tagClass:E.Class.UNIVERSAL,type:E.Type.SEQUENCE,constructed:!0,value:[{name:"ContentInfo.contentType",tagClass:E.Class.UNIVERSAL,type:E.Type.OID,constructed:!1,capture:"contentType"},{name:"ContentInfo.content",tagClass:E.Class.CONTEXT_SPECIFIC,constructed:!0,captureAsn1:"content"}]},zw={name:"PFX",tagClass:E.Class.UNIVERSAL,type:E.Type.SEQUENCE,constructed:!0,value:[{name:"PFX.version",tagClass:E.Class.UNIVERSAL,type:E.Type.INTEGER,constructed:!1,capture:"version"},ep,{name:"PFX.macData",tagClass:E.Class.UNIVERSAL,type:E.Type.SEQUENCE,constructed:!0,optional:!0,captureAsn1:"mac",value:[{name:"PFX.macData.mac",tagClass:E.Class.UNIVERSAL,type:E.Type.SEQUENCE,constructed:!0,value:[{name:"PFX.macData.mac.digestAlgorithm",tagClass:E.Class.UNIVERSAL,type:E.Type.SEQUENCE,constructed:!0,value:[{name:"PFX.macData.mac.digestAlgorithm.algorithm",tagClass:E.Class.UNIVERSAL,type:E.Type.OID,constructed:!1,capture:"macAlgorithm"},{name:"PFX.macData.mac.digestAlgorithm.parameters",optional:!0,tagClass:E.Class.UNIVERSAL,captureAsn1:"macAlgorithmParameters"}]},{name:"PFX.macData.mac.digest",tagClass:E.Class.UNIVERSAL,type:E.Type.OCTETSTRING,constructed:!1,capture:"macDigest"}]},{name:"PFX.macData.macSalt",tagClass:E.Class.UNIVERSAL,type:E.Type.OCTETSTRING,constructed:!1,capture:"macSalt"},{name:"PFX.macData.iterations",tagClass:E.Class.UNIVERSAL,type:E.Type.INTEGER,constructed:!1,optional:!0,capture:"macIterations"}]}]},Fw={name:"SafeBag",tagClass:E.Class.UNIVERSAL,type:E.Type.SEQUENCE,constructed:!0,value:[{name:"SafeBag.bagId",tagClass:E.Class.UNIVERSAL,type:E.Type.OID,constructed:!1,capture:"bagId"},{name:"SafeBag.bagValue",tagClass:E.Class.CONTEXT_SPECIFIC,constructed:!0,captureAsn1:"bagValue"},{name:"SafeBag.bagAttributes",tagClass:E.Class.UNIVERSAL,type:E.Type.SET,constructed:!0,optional:!0,capture:"bagAttributes"}]},Mw={name:"Attribute",tagClass:E.Class.UNIVERSAL,type:E.Type.SEQUENCE,constructed:!0,value:[{name:"Attribute.attrId",tagClass:E.Class.UNIVERSAL,type:E.Type.OID,constructed:!1,capture:"oid"},{name:"Attribute.attrValues",tagClass:E.Class.UNIVERSAL,type:E.Type.SET,constructed:!0,capture:"values"}]},Vw={name:"CertBag",tagClass:E.Class.UNIVERSAL,type:E.Type.SEQUENCE,constructed:!0,value:[{name:"CertBag.certId",tagClass:E.Class.UNIVERSAL,type:E.Type.OID,constructed:!1,capture:"certId"},{name:"CertBag.certValue",tagClass:E.Class.CONTEXT_SPECIFIC,constructed:!0,value:[{name:"CertBag.certValue[0]",tagClass:E.Class.UNIVERSAL,type:E.Class.OCTETSTRING,constructed:!1,capture:"cert"}]}]};function Oi(e,t,n,r){var i=[];for(var o=0;o<e.length;o++)for(var s=0;s<e[o].safeBags.length;s++){var a=e[o].safeBags[s];if(r!==void 0&&a.type!==r)continue;if(t===null){i.push(a);continue}if(a.attributes[t]!==void 0&&a.attributes[t].indexOf(n)>=0)i.push(a)}return i}Li.pkcs12FromAsn1=function(e,t,n){if(typeof t==="string")n=t,t=!0;else if(t===void 0)t=!0;var r={},i=[];if(!E.validate(e,zw,r,i)){var o=Error("Cannot read PKCS#12 PFX. ASN.1 object is not an PKCS#12 PFX.");throw o.errors=o,o}var s={version:r.version.charCodeAt(0),safeContents:[],getBags:function(x){var b={},S;if("localKeyId"in x)S=x.localKeyId;else if("localKeyIdHex"in x)S=Ue.util.hexToBytes(x.localKeyIdHex);if(S===void 0&&!("friendlyName"in x)&&"bagType"in x)b[x.bagType]=Oi(s.safeContents,null,null,x.bagType);if(S!==void 0)b.localKeyId=Oi(s.safeContents,"localKeyId",S,x.bagType);if("friendlyName"in x)b.friendlyName=Oi(s.safeContents,"friendlyName",x.friendlyName,x.bagType);return b},getBagsByFriendlyName:function(x,b){return Oi(s.safeContents,"friendlyName",x,b)},getBagsByLocalKeyId:function(x,b){return Oi(s.safeContents,"localKeyId",x,b)}};if(r.version.charCodeAt(0)!==3){var o=Error("PKCS#12 PFX of version other than 3 not supported.");throw o.version=r.version.charCodeAt(0),o}if(E.derToOid(r.contentType)!==xe.oids.data){var o=Error("Only PKCS#12 PFX in password integrity mode supported.");throw o.oid=E.derToOid(r.contentType),o}var a=r.content.value[0];if(a.tagClass!==E.Class.UNIVERSAL||a.type!==E.Type.OCTETSTRING)throw Error("PKCS#12 authSafe content data is not an OCTET STRING.");if(a=Ac(a),r.mac){var c=null,u=0,l=E.derToOid(r.macAlgorithm);switch(l){case xe.oids.sha1:c=Ue.md.sha1.create(),u=20;break;case xe.oids.sha256:c=Ue.md.sha256.create(),u=32;break;case xe.oids.sha384:c=Ue.md.sha384.create(),u=48;break;case xe.oids.sha512:c=Ue.md.sha512.create(),u=64;break;case xe.oids.md5:c=Ue.md.md5.create(),u=16;break}if(c===null)throw Error("PKCS#12 uses unsupported MAC algorithm: "+l);var f=new Ue.util.ByteBuffer(r.macSalt),p="macIterations"in r?parseInt(Ue.util.bytesToHex(r.macIterations),16):1;if(!(p>=1))throw Error("PKCS#12 MAC iteration count must be >= 1.");var h=Li.generateKey(n,f,3,p,u,c),d=Ue.hmac.create();d.start(c,h),d.update(a.value);var g=d.getMac();if(g.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 Ww(s,a.value,t,n),s};function Ac(e){if(e.composed||e.constructed){var t=Ue.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 Ww(e,t,n,r){if(t=E.fromDer(t,n),t.tagClass!==E.Class.UNIVERSAL||t.type!==E.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 o=t.value[i],s={},a=[];if(!E.validate(o,ep,s,a)){var c=Error("Cannot read ContentInfo.");throw c.errors=a,c}var u={encrypted:!1},l=null,f=s.content.value[0];switch(E.derToOid(s.contentType)){case xe.oids.data:if(f.tagClass!==E.Class.UNIVERSAL||f.type!==E.Type.OCTETSTRING)throw Error("PKCS#12 SafeContents Data is not an OCTET STRING.");l=Ac(f).value;break;case xe.oids.encryptedData:l=Hw(f,r),u.encrypted=!0;break;default:var c=Error("Unsupported PKCS#12 contentType.");throw c.contentType=E.derToOid(s.contentType),c}u.safeBags=Kw(l,n,r),e.safeContents.push(u)}}function Hw(e,t){var n={},r=[];if(!E.validate(e,Ue.pkcs7.asn1.encryptedDataValidator,n,r)){var i=Error("Cannot read EncryptedContentInfo.");throw i.errors=r,i}var o=E.derToOid(n.contentType);if(o!==xe.oids.data){var i=Error("PKCS#12 EncryptedContentInfo ContentType is not Data.");throw i.oid=o,i}o=E.derToOid(n.encAlgorithm);var s=xe.pbe.getCipher(o,n.encParameter,t),a=Ac(n.encryptedContentAsn1),c=Ue.util.createBuffer(a.value);if(s.update(c),!s.finish())throw Error("Failed to decrypt PKCS#12 SafeContents.");return s.output.getBytes()}function Kw(e,t,n){if(!t&&e.length===0)return[];if(e=E.fromDer(e,t),e.tagClass!==E.Class.UNIVERSAL||e.type!==E.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 o=e.value[i],s={},a=[];if(!E.validate(o,Fw,s,a)){var c=Error("Cannot read SafeBag.");throw c.errors=a,c}var u={type:E.derToOid(s.bagId),attributes:Zw(s.bagAttributes)};r.push(u);var l,f,p=s.bagValue.value[0];switch(u.type){case xe.oids.pkcs8ShroudedKeyBag:if(p=xe.decryptPrivateKeyInfo(p,n),p===null)throw Error("Unable to decrypt PKCS#8 ShroudedKeyBag, wrong password?");case xe.oids.keyBag:try{u.key=xe.privateKeyFromAsn1(p)}catch(d){u.key=null,u.asn1=p}continue;case xe.oids.certBag:l=Vw,f=function(){if(E.derToOid(s.certId)!==xe.oids.x509Certificate){var d=Error("Unsupported certificate type, only X.509 supported.");throw d.oid=E.derToOid(s.certId),d}var g=E.fromDer(s.cert,t);try{u.cert=xe.certificateFromAsn1(g,!0)}catch(x){u.cert=null,u.asn1=g}};break;default:var c=Error("Unsupported PKCS#12 SafeBag type.");throw c.oid=u.type,c}if(l!==void 0&&!E.validate(p,l,s,a)){var c=Error("Cannot read PKCS#12 "+l.name);throw c.errors=a,c}f()}return r}function Zw(e){var t={};if(e!==void 0)for(var n=0;n<e.length;++n){var r={},i=[];if(!E.validate(e[n],Mw,r,i)){var o=Error("Cannot read PKCS#12 BagAttribute.");throw o.errors=i,o}var s=E.derToOid(r.oid);if(xe.oids[s]===void 0)continue;t[xe.oids[s]]=[];for(var a=0;a<r.values.length;++a)t[xe.oids[s]].push(r.values[a].value)}return t}Li.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,o;if(i!==null)i=Ue.util.hexToBytes(i);else if(r.generateLocalKeyId)if(t){var s=Ue.util.isArray(t)?t[0]:t;if(typeof s==="string")s=xe.certificateFromPem(s);var a=Ue.md.sha1.create();a.update(E.toDer(xe.certificateToAsn1(s)).getBytes()),i=a.digest().getBytes()}else i=Ue.random.getBytes(20);var c=[];if(i!==null)c.push(E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.OID,!1,E.oidToDer(xe.oids.localKeyId).getBytes()),E.create(E.Class.UNIVERSAL,E.Type.SET,!0,[E.create(E.Class.UNIVERSAL,E.Type.OCTETSTRING,!1,i)])]));if("friendlyName"in r)c.push(E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.OID,!1,E.oidToDer(xe.oids.friendlyName).getBytes()),E.create(E.Class.UNIVERSAL,E.Type.SET,!0,[E.create(E.Class.UNIVERSAL,E.Type.BMPSTRING,!1,r.friendlyName)])]));if(c.length>0)o=E.create(E.Class.UNIVERSAL,E.Type.SET,!0,c);var u=[],l=[];if(t!==null)if(Ue.util.isArray(t))l=t;else l=[t];var f=[];for(var p=0;p<l.length;++p){if(t=l[p],typeof t==="string")t=xe.certificateFromPem(t);var h=p===0?o:void 0,d=xe.certificateToAsn1(t),g=E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.OID,!1,E.oidToDer(xe.oids.certBag).getBytes()),E.create(E.Class.CONTEXT_SPECIFIC,0,!0,[E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.OID,!1,E.oidToDer(xe.oids.x509Certificate).getBytes()),E.create(E.Class.CONTEXT_SPECIFIC,0,!0,[E.create(E.Class.UNIVERSAL,E.Type.OCTETSTRING,!1,E.toDer(d).getBytes())])])]),h]);f.push(g)}if(f.length>0){var x=E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,f),b=E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.OID,!1,E.oidToDer(xe.oids.data).getBytes()),E.create(E.Class.CONTEXT_SPECIFIC,0,!0,[E.create(E.Class.UNIVERSAL,E.Type.OCTETSTRING,!1,E.toDer(x).getBytes())])]);u.push(b)}var S=null;if(e!==null){var C=xe.wrapRsaPrivateKey(xe.privateKeyToAsn1(e));if(n===null)S=E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.OID,!1,E.oidToDer(xe.oids.keyBag).getBytes()),E.create(E.Class.CONTEXT_SPECIFIC,0,!0,[C]),o]);else S=E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.OID,!1,E.oidToDer(xe.oids.pkcs8ShroudedKeyBag).getBytes()),E.create(E.Class.CONTEXT_SPECIFIC,0,!0,[xe.encryptPrivateKeyInfo(C,n,r)]),o]);var T=E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[S]),I=E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.OID,!1,E.oidToDer(xe.oids.data).getBytes()),E.create(E.Class.CONTEXT_SPECIFIC,0,!0,[E.create(E.Class.UNIVERSAL,E.Type.OCTETSTRING,!1,E.toDer(T).getBytes())])]);u.push(I)}var k=E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,u),R;if(r.useMac){var a=Ue.md.sha1.create(),V=new Ue.util.ByteBuffer(Ue.random.getBytes(r.saltSize)),D=r.count,e=Li.generateKey(n,V,3,D,20),F=Ue.hmac.create();F.start(a,e),F.update(E.toDer(k).getBytes());var H=F.getMac();R=E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.OID,!1,E.oidToDer(xe.oids.sha1).getBytes()),E.create(E.Class.UNIVERSAL,E.Type.NULL,!1,"")]),E.create(E.Class.UNIVERSAL,E.Type.OCTETSTRING,!1,H.getBytes())]),E.create(E.Class.UNIVERSAL,E.Type.OCTETSTRING,!1,V.getBytes()),E.create(E.Class.UNIVERSAL,E.Type.INTEGER,!1,E.integerToDer(D).getBytes())])}return E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.INTEGER,!1,E.integerToDer(3).getBytes()),E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.OID,!1,E.oidToDer(xe.oids.data).getBytes()),E.create(E.Class.CONTEXT_SPECIFIC,0,!0,[E.create(E.Class.UNIVERSAL,E.Type.OCTETSTRING,!1,E.toDer(k).getBytes())])]),R])};Li.generateKey=Ue.pbe.generatePkcs12Key});var Pc=le(function(Z2,rp){var jr=he();Qt();Wr();Cc();fn();Xo();kc();is();$i();Te();cs();var Ic=jr.asn1,Hn=rp.exports=jr.pki=jr.pki||{};Hn.pemToDer=function(e){var t=jr.pem.decode(e)[0];if(t.procType&&t.procType.type==="ENCRYPTED")throw Error("Could not convert PEM to DER; PEM is encrypted.");return jr.util.createBuffer(t.body)};Hn.privateKeyFromPem=function(e){var t=jr.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=Ic.fromDer(t.body);return Hn.privateKeyFromAsn1(r)};Hn.privateKeyToPem=function(e,t){var n={type:"RSA PRIVATE KEY",body:Ic.toDer(Hn.privateKeyToAsn1(e)).getBytes()};return jr.pem.encode(n,{maxline:t})};Hn.privateKeyInfoToPem=function(e,t){var n={type:"PRIVATE KEY",body:Ic.toDer(e).getBytes()};return jr.pem.encode(n,{maxline:t})}});var Oc=le(function(j2,lp){var U=he();Qt();On();Zo();fn();Pc();Ft();Fn();Te();var fs=function(e,t,n,r){var i=U.util.createBuffer(),o=e.length>>1,s=o+(e.length&1),a=e.substr(0,s),c=e.substr(o,s),u=U.util.createBuffer(),l=U.hmac.create();n=t+n;var f=Math.ceil(r/16),p=Math.ceil(r/20);l.start("MD5",a);var h=U.util.createBuffer();u.putBytes(n);for(var d=0;d<f;++d)l.start(null,null),l.update(u.getBytes()),u.putBuffer(l.digest()),l.start(null,null),l.update(u.bytes()+n),h.putBuffer(l.digest());l.start("SHA1",c);var g=U.util.createBuffer();u.clear(),u.putBytes(n);for(var d=0;d<p;++d)l.start(null,null),l.update(u.getBytes()),u.putBuffer(l.digest()),l.start(null,null),l.update(u.bytes()+n),g.putBuffer(l.digest());return i.putBytes(U.util.xorBytes(h.getBytes(),g.getBytes(),r)),i},jw=function(e,t,n){var r=U.hmac.create();r.start("SHA1",e);var i=U.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()},Gw=function(e,t,n){var r=!1;try{var i=e.deflate(t.fragment.getBytes());t.fragment=U.util.createBuffer(i),t.length=i.length,r=!0}catch(o){}return r},qw=function(e,t,n){var r=!1;try{var i=e.inflate(t.fragment.getBytes());t.fragment=U.util.createBuffer(i),t.length=i.length,r=!0}catch(o){}return r},Rt=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 U.util.createBuffer(e.getBytes(n))},Ht=function(e,t,n){e.putInt(n.length(),t<<3),e.putBuffer(n)},v={};v.Versions={TLS_1_0:{major:3,minor:1},TLS_1_1:{major:3,minor:2},TLS_1_2:{major:3,minor:3}};v.SupportedVersions=[v.Versions.TLS_1_1,v.Versions.TLS_1_0];v.Version=v.SupportedVersions[0];v.MaxFragment=15360;v.ConnectionEnd={server:0,client:1};v.PRFAlgorithm={tls_prf_sha256:0};v.BulkCipherAlgorithm={none:null,rc4:0,des3:1,aes:2};v.CipherType={stream:0,block:1,aead:2};v.MACAlgorithm={none:null,hmac_md5:0,hmac_sha1:1,hmac_sha256:2,hmac_sha384:3,hmac_sha512:4};v.CompressionMethod={none:0,deflate:1};v.ContentType={change_cipher_spec:20,alert:21,handshake:22,application_data:23,heartbeat:24};v.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};v.Alert={};v.Alert.Level={warning:1,fatal:2};v.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};v.HeartbeatMessageType={heartbeat_request:1,heartbeat_response:2};v.CipherSuites={};v.getCipherSuite=function(e){var t=null;for(var n in v.CipherSuites){var r=v.CipherSuites[n];if(r.id[0]===e.charCodeAt(0)&&r.id[1]===e.charCodeAt(1)){t=r;break}}return t};v.handleUnexpected=function(e,t){var n=!e.open&&e.entity===v.ConnectionEnd.client;if(!n)e.error(e,{message:"Unexpected message. Received TLS record out of order.",send:!0,alert:{level:v.Alert.Level.fatal,description:v.Alert.Description.unexpected_message}})};v.handleHelloRequest=function(e,t,n){if(!e.handshaking&&e.handshakes>0)v.queue(e,v.createAlert(e,{level:v.Alert.Level.warning,description:v.Alert.Description.no_renegotiation})),v.flush(e);e.process()};v.parseHelloMessage=function(e,t,n){var r=null,i=e.entity===v.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:v.Alert.Level.fatal,description:v.Alert.Description.illegal_parameter}});else{var o=t.fragment,s=o.length();if(r={version:{major:o.getByte(),minor:o.getByte()},random:U.util.createBuffer(o.getBytes(32)),session_id:Rt(o,1),extensions:[]},i)r.cipher_suite=o.getBytes(2),r.compression_method=o.getByte();else r.cipher_suites=Rt(o,2),r.compression_methods=Rt(o,1);if(s=n-(s-o.length()),s>0){var a=Rt(o,2);while(a.length()>0)r.extensions.push({type:[a.getByte(),a.getByte()],data:Rt(a,2)});if(!i)for(var c=0;c<r.extensions.length;++c){var u=r.extensions[c];if(u.type[0]===0&&u.type[1]===0){var l=Rt(u.data,2);while(l.length()>0){var f=l.getByte();if(f!==0)break;e.session.extensions.server_name.serverNameList.push(Rt(l,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:v.Alert.Level.fatal,description:v.Alert.Description.protocol_version}})}if(i)e.session.cipherSuite=v.getCipherSuite(r.cipher_suite);else{var p=U.util.createBuffer(r.cipher_suites.bytes());while(p.length()>0)if(e.session.cipherSuite=v.getCipherSuite(p.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:v.Alert.Level.fatal,description:v.Alert.Description.handshake_failure},cipherSuite:U.util.bytesToHex(r.cipher_suite)});if(i){if(r.compression_method!==v.CompressionMethod.none)return e.error(e,{message:"Unsupported compression method.",send:!0,alert:{level:v.Alert.Level.fatal,description:v.Alert.Description.illegal_parameter}});e.session.compressionMethod=r.compression_method}else e.session.compressionMethod=v.CompressionMethod.none}return r};v.createSecurityParameters=function(e,t){var n=e.entity===v.ConnectionEnd.client,r=t.random.bytes(),i=n?e.session.sp.client_random:r,o=n?r:v.createRandom().getBytes();e.session.sp={entity:e.entity,prf_algorithm:v.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:o}};v.handleServerHello=function(e,t,n){var r=v.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:v.Alert.Level.fatal,description:v.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=op,e.session.resuming=!0,e.session.sp.server_random=r.random.bytes();else e.expect=Jw,e.session.resuming=!1,v.createSecurityParameters(e,r);e.session.id=i,e.process()};v.handleClientHello=function(e,t,n){var r=v.parseHelloMessage(e,t,n);if(e.fail)return;var i=r.session_id.bytes(),o=null;if(e.sessionCache){if(o=e.sessionCache.getSession(i),o===null)i="";else if(o.version.major!==r.version.major||o.version.minor>r.version.minor)o=null,i=""}if(i.length===0)i=U.random.getBytes(32);if(e.session.id=i,e.session.clientHelloVersion=r.version,e.session.sp={},o)e.version=e.session.version=o.version,e.session.sp=o.sp;else{var s;for(var a=1;a<v.SupportedVersions.length;++a)if(s=v.SupportedVersions[a],s.minor<=r.version.minor)break;e.version={major:s.major,minor:s.minor},e.session.version=e.version}if(o!==null)e.expect=Dc,e.session.resuming=!0,e.session.sp.client_random=r.random.bytes();else e.expect=e.verifyClient!==!1?i1:Nc,e.session.resuming=!1,v.createSecurityParameters(e,r);if(e.open=!0,v.queue(e,v.createRecord(e,{type:v.ContentType.handshake,data:v.createServerHello(e)})),e.session.resuming)v.queue(e,v.createRecord(e,{type:v.ContentType.change_cipher_spec,data:v.createChangeCipherSpec()})),e.state.pending=v.createConnectionState(e),e.state.current.write=e.state.pending.write,v.queue(e,v.createRecord(e,{type:v.ContentType.handshake,data:v.createFinished(e)}));else if(v.queue(e,v.createRecord(e,{type:v.ContentType.handshake,data:v.createCertificate(e)})),!e.fail){if(v.queue(e,v.createRecord(e,{type:v.ContentType.handshake,data:v.createServerKeyExchange(e)})),e.verifyClient!==!1)v.queue(e,v.createRecord(e,{type:v.ContentType.handshake,data:v.createCertificateRequest(e)}));v.queue(e,v.createRecord(e,{type:v.ContentType.handshake,data:v.createServerHelloDone(e)}))}v.flush(e),e.process()};v.handleCertificate=function(e,t,n){if(n<3)return e.error(e,{message:"Invalid Certificate message. Message too short.",send:!0,alert:{level:v.Alert.Level.fatal,description:v.Alert.Description.illegal_parameter}});var r=t.fragment,i={certificate_list:Rt(r,3)},o,s,a=[];try{while(i.certificate_list.length()>0)o=Rt(i.certificate_list,3),s=U.asn1.fromDer(o),o=U.pki.certificateFromAsn1(s,!0),a.push(o)}catch(u){return e.error(e,{message:"Could not parse certificate list.",cause:u,send:!0,alert:{level:v.Alert.Level.fatal,description:v.Alert.Description.bad_certificate}})}var c=e.entity===v.ConnectionEnd.client;if((c||e.verifyClient===!0)&&a.length===0)e.error(e,{message:c?"No server certificate provided.":"No client certificate provided.",send:!0,alert:{level:v.Alert.Level.fatal,description:v.Alert.Description.illegal_parameter}});else if(a.length===0)e.expect=c?np:Nc;else{if(c)e.session.serverCertificate=a[0];else e.session.clientCertificate=a[0];if(v.verifyCertificateChain(e,a))e.expect=c?np:Nc}e.process()};v.handleServerKeyExchange=function(e,t,n){if(n>0)return e.error(e,{message:"Invalid key parameters. Only RSA is supported.",send:!0,alert:{level:v.Alert.Level.fatal,description:v.Alert.Description.unsupported_certificate}});e.expect=Qw,e.process()};v.handleClientKeyExchange=function(e,t,n){if(n<48)return e.error(e,{message:"Invalid key parameters. Only RSA is supported.",send:!0,alert:{level:v.Alert.Level.fatal,description:v.Alert.Description.unsupported_certificate}});var r=t.fragment,i={enc_pre_master_secret:Rt(r,2).getBytes()},o=null;if(e.getPrivateKey)try{o=e.getPrivateKey(e,e.session.serverCertificate),o=U.pki.privateKeyFromPem(o)}catch(c){e.error(e,{message:"Could not get private key.",cause:c,send:!0,alert:{level:v.Alert.Level.fatal,description:v.Alert.Description.internal_error}})}if(o===null)return e.error(e,{message:"No private key set.",send:!0,alert:{level:v.Alert.Level.fatal,description:v.Alert.Description.internal_error}});try{var s=e.session.sp;s.pre_master_secret=o.decrypt(i.enc_pre_master_secret);var a=e.session.clientHelloVersion;if(a.major!==s.pre_master_secret.charCodeAt(0)||a.minor!==s.pre_master_secret.charCodeAt(1))throw Error("TLS version rollback attack detected.")}catch(c){s.pre_master_secret=U.random.getBytes(48)}if(e.expect=Dc,e.session.clientCertificate!==null)e.expect=o1;e.process()};v.handleCertificateRequest=function(e,t,n){if(n<3)return e.error(e,{message:"Invalid CertificateRequest. Message too short.",send:!0,alert:{level:v.Alert.Level.fatal,description:v.Alert.Description.illegal_parameter}});var r=t.fragment,i={certificate_types:Rt(r,1),certificate_authorities:Rt(r,2)};e.session.certificateRequest=i,e.expect=Yw,e.process()};v.handleCertificateVerify=function(e,t,n){if(n<2)return e.error(e,{message:"Invalid CertificateVerify. Message too short.",send:!0,alert:{level:v.Alert.Level.fatal,description:v.Alert.Description.illegal_parameter}});var r=t.fragment;r.read-=4;var i=r.bytes();r.read+=4;var o={signature:Rt(r,2).getBytes()},s=U.util.createBuffer();s.putBuffer(e.session.md5.digest()),s.putBuffer(e.session.sha1.digest()),s=s.getBytes();try{var a=e.session.clientCertificate;if(!a.publicKey.verify(s,o.signature,"NONE"))throw Error("CertificateVerify signature does not match.");e.session.md5.update(i),e.session.sha1.update(i)}catch(c){return e.error(e,{message:"Bad signature in CertificateVerify.",send:!0,alert:{level:v.Alert.Level.fatal,description:v.Alert.Description.handshake_failure}})}e.expect=Dc,e.process()};v.handleServerHelloDone=function(e,t,n){if(n>0)return e.error(e,{message:"Invalid ServerHelloDone message. Invalid length.",send:!0,alert:{level:v.Alert.Level.fatal,description:v.Alert.Description.record_overflow}});if(e.session.serverCertificate===null){var r={message:"No server certificate provided. Not enough security.",send:!0,alert:{level:v.Alert.Level.fatal,description:v.Alert.Description.insufficient_security}},i=0,o=e.verify(e,r.alert.description,i,[]);if(o!==!0){if(o||o===0){if(typeof o==="object"&&!U.util.isArray(o)){if(o.message)r.message=o.message;if(o.alert)r.alert.description=o.alert}else if(typeof o==="number")r.alert.description=o}}return e.error(e,r)}if(e.session.certificateRequest!==null)t=v.createRecord(e,{type:v.ContentType.handshake,data:v.createCertificate(e)}),v.queue(e,t);t=v.createRecord(e,{type:v.ContentType.handshake,data:v.createClientKeyExchange(e)}),v.queue(e,t),e.expect=r1;var s=function(a,c){if(a.session.certificateRequest!==null&&a.session.clientCertificate!==null)v.queue(a,v.createRecord(a,{type:v.ContentType.handshake,data:v.createCertificateVerify(a,c)}));v.queue(a,v.createRecord(a,{type:v.ContentType.change_cipher_spec,data:v.createChangeCipherSpec()})),a.state.pending=v.createConnectionState(a),a.state.current.write=a.state.pending.write,v.queue(a,v.createRecord(a,{type:v.ContentType.handshake,data:v.createFinished(a)})),a.expect=op,v.flush(a),a.process()};if(e.session.certificateRequest===null||e.session.clientCertificate===null)return s(e,null);v.getClientSignature(e,s)};v.handleChangeCipherSpec=function(e,t){if(t.fragment.getByte()!==1)return e.error(e,{message:"Invalid ChangeCipherSpec message received.",send:!0,alert:{level:v.Alert.Level.fatal,description:v.Alert.Description.illegal_parameter}});var n=e.entity===v.ConnectionEnd.client;if(e.session.resuming&&n||!e.session.resuming&&!n)e.state.pending=v.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?e1:s1,e.process()};v.handleFinished=function(e,t,n){var r=t.fragment;r.read-=4;var i=r.bytes();r.read+=4;var o=t.fragment.getBytes();r=U.util.createBuffer(),r.putBuffer(e.session.md5.digest()),r.putBuffer(e.session.sha1.digest());var s=e.entity===v.ConnectionEnd.client,a=s?"server finished":"client finished",c=e.session.sp,u=12,l=fs;if(r=l(c.master_secret,a,r.getBytes(),u),r.getBytes()!==o)return e.error(e,{message:"Invalid verify_data in Finished message.",send:!0,alert:{level:v.Alert.Level.fatal,description:v.Alert.Description.decrypt_error}});if(e.session.md5.update(i),e.session.sha1.update(i),e.session.resuming&&s||!e.session.resuming&&!s)v.queue(e,v.createRecord(e,{type:v.ContentType.change_cipher_spec,data:v.createChangeCipherSpec()})),e.state.current.write=e.state.pending.write,e.state.pending=null,v.queue(e,v.createRecord(e,{type:v.ContentType.handshake,data:v.createFinished(e)}));e.expect=s?t1:a1,e.handshaking=!1,++e.handshakes,e.peerCertificate=s?e.session.serverCertificate:e.session.clientCertificate,v.flush(e),e.isConnected=!0,e.connected(e),e.process()};v.handleAlert=function(e,t){var n=t.fragment,r={level:n.getByte(),description:n.getByte()},i;switch(r.description){case v.Alert.Description.close_notify:i="Connection closed.";break;case v.Alert.Description.unexpected_message:i="Unexpected message.";break;case v.Alert.Description.bad_record_mac:i="Bad record MAC.";break;case v.Alert.Description.decryption_failed:i="Decryption failed.";break;case v.Alert.Description.record_overflow:i="Record overflow.";break;case v.Alert.Description.decompression_failure:i="Decompression failed.";break;case v.Alert.Description.handshake_failure:i="Handshake failure.";break;case v.Alert.Description.bad_certificate:i="Bad certificate.";break;case v.Alert.Description.unsupported_certificate:i="Unsupported certificate.";break;case v.Alert.Description.certificate_revoked:i="Certificate revoked.";break;case v.Alert.Description.certificate_expired:i="Certificate expired.";break;case v.Alert.Description.certificate_unknown:i="Certificate unknown.";break;case v.Alert.Description.illegal_parameter:i="Illegal parameter.";break;case v.Alert.Description.unknown_ca:i="Unknown certificate authority.";break;case v.Alert.Description.access_denied:i="Access denied.";break;case v.Alert.Description.decode_error:i="Decode error.";break;case v.Alert.Description.decrypt_error:i="Decrypt error.";break;case v.Alert.Description.export_restriction:i="Export restriction.";break;case v.Alert.Description.protocol_version:i="Unsupported protocol version.";break;case v.Alert.Description.insufficient_security:i="Insufficient security.";break;case v.Alert.Description.internal_error:i="Internal error.";break;case v.Alert.Description.user_canceled:i="User canceled.";break;case v.Alert.Description.no_renegotiation:i="Renegotiation not supported.";break;default:i="Unknown error.";break}if(r.description===v.Alert.Description.close_notify)return e.close();e.error(e,{message:i,send:!1,origin:e.entity===v.ConnectionEnd.client?"server":"client",alert:r}),e.process()};v.handleHandshake=function(e,t){var n=t.fragment,r=n.getByte(),i=n.getInt24();if(i>n.length())return e.fragmented=t,t.fragment=U.util.createBuffer(),n.read-=4,e.process();e.fragmented=null,n.read-=4;var o=n.bytes(i+4);if(n.read+=4,r in ls[e.entity][e.expect]&&(e.session||e.entity===v.ConnectionEnd.server)){if(e.entity===v.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:U.md.md5.create(),sha1:U.md.sha1.create()};if(r!==v.HandshakeType.hello_request&&r!==v.HandshakeType.certificate_verify&&r!==v.HandshakeType.finished)e.session.md5.update(o),e.session.sha1.update(o);ls[e.entity][e.expect][r](e,t,i)}else v.handleUnexpected(e,t)};v.handleApplicationData=function(e,t){e.data.putBuffer(t.fragment),e.dataReady(e),e.process()};v.handleHeartbeat=function(e,t){var n=t.fragment,r=n.getByte(),i=n.getInt16(),o=n.getBytes(i);if(r===v.HeartbeatMessageType.heartbeat_request){if(e.handshakes===0||e.handshaking||i>o.length)return e.process();v.queue(e,v.createRecord(e,{type:v.ContentType.heartbeat,data:v.createHeartbeat(v.HeartbeatMessageType.heartbeat_response,o)})),v.flush(e)}else if(r===v.HeartbeatMessageType.heartbeat_response){if(o!==e.expectedHeartbeatPayload)return e.process();if(e.heartbeatReceived)e.heartbeatReceived(e,U.util.createBuffer(o))}e.process()};var Xw=0,Jw=1,np=2,Qw=3,Yw=4,op=5,e1=6,t1=7,r1=8,n1=0,i1=1,Nc=2,o1=3,Dc=4,s1=5,a1=6,{handleUnexpected:y,handleChangeCipherSpec:sp,handleAlert:ht,handleHandshake:Ct,handleApplicationData:ap,handleHeartbeat:mt}=v,$c=[];$c[v.ConnectionEnd.client]=[[y,ht,Ct,y,mt],[y,ht,Ct,y,mt],[y,ht,Ct,y,mt],[y,ht,Ct,y,mt],[y,ht,Ct,y,mt],[sp,ht,y,y,mt],[y,ht,Ct,y,mt],[y,ht,Ct,ap,mt],[y,ht,Ct,y,mt]];$c[v.ConnectionEnd.server]=[[y,ht,Ct,y,mt],[y,ht,Ct,y,mt],[y,ht,Ct,y,mt],[y,ht,Ct,y,mt],[sp,ht,y,y,mt],[y,ht,Ct,y,mt],[y,ht,Ct,ap,mt],[y,ht,Ct,y,mt]];var{handleHelloRequest:Gr,handleServerHello:c1,handleCertificate:cp,handleServerKeyExchange:ip,handleCertificateRequest:Rc,handleServerHelloDone:us,handleFinished:up}=v,ls=[];ls[v.ConnectionEnd.client]=[[y,y,c1,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y],[Gr,y,y,y,y,y,y,y,y,y,y,cp,ip,Rc,us,y,y,y,y,y,y],[Gr,y,y,y,y,y,y,y,y,y,y,y,ip,Rc,us,y,y,y,y,y,y],[Gr,y,y,y,y,y,y,y,y,y,y,y,y,Rc,us,y,y,y,y,y,y],[Gr,y,y,y,y,y,y,y,y,y,y,y,y,y,us,y,y,y,y,y,y],[Gr,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y],[Gr,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,up],[Gr,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y],[Gr,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y]];var{handleClientHello:u1,handleClientKeyExchange:l1,handleCertificateVerify:f1}=v;ls[v.ConnectionEnd.server]=[[y,u1,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y],[y,y,y,y,y,y,y,y,y,y,y,cp,y,y,y,y,y,y,y,y,y],[y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,l1,y,y,y,y],[y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,f1,y,y,y,y,y],[y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y],[y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,up],[y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y],[y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y]];v.generateKeys=function(e,t){var n=fs,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,o=e.version.major===v.Versions.TLS_1_0.major&&e.version.minor===v.Versions.TLS_1_0.minor;if(o)i+=2*t.fixed_iv_length;var s=n(t.master_secret,"key expansion",r,i),a={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(o)a.client_write_IV=s.getBytes(t.fixed_iv_length),a.server_write_IV=s.getBytes(t.fixed_iv_length);return a};v.createConnectionState=function(e){var t=e.entity===v.ConnectionEnd.client,n=function(){var o={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(o.sequenceNumber[1]===4294967295)o.sequenceNumber[1]=0,++o.sequenceNumber[0];else++o.sequenceNumber[1]}};return o},r={read:n(),write:n()};if(r.read.update=function(o,s){if(!r.read.cipherFunction(s,r.read))o.error(o,{message:"Could not decrypt record or bad MAC.",send:!0,alert:{level:v.Alert.Level.fatal,description:v.Alert.Description.bad_record_mac}});else if(!r.read.compressFunction(o,s,r.read))o.error(o,{message:"Could not decompress record.",send:!0,alert:{level:v.Alert.Level.fatal,description:v.Alert.Description.decompression_failure}});return!o.fail},r.write.update=function(o,s){if(!r.write.compressFunction(o,s,r.write))o.error(o,{message:"Could not compress record.",send:!1,alert:{level:v.Alert.Level.fatal,description:v.Alert.Description.internal_error}});else if(!r.write.cipherFunction(s,r.write))o.error(o,{message:"Could not encrypt record.",send:!1,alert:{level:v.Alert.Level.fatal,description:v.Alert.Description.internal_error}});return!o.fail},e.session){var i=e.session.sp;switch(e.session.cipherSuite.initSecurityParameters(i),i.keys=v.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 v.CompressionMethod.none:break;case v.CompressionMethod.deflate:r.read.compressFunction=qw,r.write.compressFunction=Gw;break;default:throw Error("Unsupported compression algorithm.")}}return r};v.createRandom=function(){var e=new Date,t=+e+e.getTimezoneOffset()*60000,n=U.util.createBuffer();return n.putInt32(t),n.putBytes(U.random.getBytes(28)),n};v.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};v.createAlert=function(e,t){var n=U.util.createBuffer();return n.putByte(t.level),n.putByte(t.description),v.createRecord(e,{type:v.ContentType.alert,data:n})};v.createClientHello=function(e){e.session.clientHelloVersion={major:e.version.major,minor:e.version.minor};var t=U.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(),o=U.util.createBuffer();o.putByte(v.CompressionMethod.none);var s=o.length(),a=U.util.createBuffer();if(e.virtualHost){var c=U.util.createBuffer();c.putByte(0),c.putByte(0);var u=U.util.createBuffer();u.putByte(0),Ht(u,2,U.util.createBuffer(e.virtualHost));var l=U.util.createBuffer();Ht(l,2,u),Ht(c,2,l),a.putBuffer(c)}var f=a.length();if(f>0)f+=2;var p=e.session.id,h=p.length+1+2+4+28+2+i+1+s+f,d=U.util.createBuffer();if(d.putByte(v.HandshakeType.client_hello),d.putInt24(h),d.putByte(e.version.major),d.putByte(e.version.minor),d.putBytes(e.session.sp.client_random),Ht(d,1,U.util.createBuffer(p)),Ht(d,2,t),Ht(d,1,o),f>0)Ht(d,2,a);return d};v.createServerHello=function(e){var t=e.session.id,n=t.length+1+2+4+28+2+1,r=U.util.createBuffer();return r.putByte(v.HandshakeType.server_hello),r.putInt24(n),r.putByte(e.version.major),r.putByte(e.version.minor),r.putBytes(e.session.sp.server_random),Ht(r,1,U.util.createBuffer(t)),r.putByte(e.session.cipherSuite.id[0]),r.putByte(e.session.cipherSuite.id[1]),r.putByte(e.session.compressionMethod),r};v.createCertificate=function(e){var t=e.entity===v.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=U.util.createBuffer();if(n!==null)try{if(!U.util.isArray(n))n=[n];var o=null;for(var s=0;s<n.length;++s){var a=U.pem.decode(n[s])[0];if(a.type!=="CERTIFICATE"&&a.type!=="X509 CERTIFICATE"&&a.type!=="TRUSTED CERTIFICATE"){var c=Error('Could not convert certificate from PEM; PEM header type is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".');throw c.headerType=a.type,c}if(a.procType&&a.procType.type==="ENCRYPTED")throw Error("Could not convert certificate from PEM; PEM is encrypted.");var u=U.util.createBuffer(a.body);if(o===null)o=U.asn1.fromDer(u.bytes(),!1);var l=U.util.createBuffer();Ht(l,3,u),i.putBuffer(l)}if(n=U.pki.certificateFromAsn1(o),t)e.session.clientCertificate=n;else e.session.serverCertificate=n}catch(h){return e.error(e,{message:"Could not send certificate list.",cause:h,send:!0,alert:{level:v.Alert.Level.fatal,description:v.Alert.Description.bad_certificate}})}var f=3+i.length(),p=U.util.createBuffer();return p.putByte(v.HandshakeType.certificate),p.putInt24(f),Ht(p,3,i),p};v.createClientKeyExchange=function(e){var t=U.util.createBuffer();t.putByte(e.session.clientHelloVersion.major),t.putByte(e.session.clientHelloVersion.minor),t.putBytes(U.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,o=U.util.createBuffer();return o.putByte(v.HandshakeType.client_key_exchange),o.putInt24(i),o.putInt16(t.length),o.putBytes(t),o};v.createServerKeyExchange=function(e){var t=0,n=U.util.createBuffer();if(t>0)n.putByte(v.HandshakeType.server_key_exchange),n.putInt24(t);return n};v.getClientSignature=function(e,t){var n=U.util.createBuffer();n.putBuffer(e.session.md5.digest()),n.putBuffer(e.session.sha1.digest()),n=n.getBytes(),e.getSignature=e.getSignature||function(r,i,o){var s=null;if(r.getPrivateKey)try{s=r.getPrivateKey(r,r.session.clientCertificate),s=U.pki.privateKeyFromPem(s)}catch(a){r.error(r,{message:"Could not get private key.",cause:a,send:!0,alert:{level:v.Alert.Level.fatal,description:v.Alert.Description.internal_error}})}if(s===null)r.error(r,{message:"No private key set.",send:!0,alert:{level:v.Alert.Level.fatal,description:v.Alert.Description.internal_error}});else i=s.sign(i,null);o(r,i)},e.getSignature(e,n,t)};v.createCertificateVerify=function(e,t){var n=t.length+2,r=U.util.createBuffer();return r.putByte(v.HandshakeType.certificate_verify),r.putInt24(n),r.putInt16(t.length),r.putBytes(t),r};v.createCertificateRequest=function(e){var t=U.util.createBuffer();t.putByte(1);var n=U.util.createBuffer();for(var r in e.caStore.certs){var i=e.caStore.certs[r],o=U.pki.distinguishedNameToAsn1(i.subject),s=U.asn1.toDer(o);n.putInt16(s.length()),n.putBuffer(s)}var a=1+t.length()+2+n.length(),c=U.util.createBuffer();return c.putByte(v.HandshakeType.certificate_request),c.putInt24(a),Ht(c,1,t),Ht(c,2,n),c};v.createServerHelloDone=function(e){var t=U.util.createBuffer();return t.putByte(v.HandshakeType.server_hello_done),t.putInt24(0),t};v.createChangeCipherSpec=function(){var e=U.util.createBuffer();return e.putByte(1),e};v.createFinished=function(e){var t=U.util.createBuffer();t.putBuffer(e.session.md5.digest()),t.putBuffer(e.session.sha1.digest());var n=e.entity===v.ConnectionEnd.client,r=e.session.sp,i=12,o=fs,s=n?"client finished":"server finished";t=o(r.master_secret,s,t.getBytes(),i);var a=U.util.createBuffer();return a.putByte(v.HandshakeType.finished),a.putInt24(t.length()),a.putBuffer(t),a};v.createHeartbeat=function(e,t,n){if(typeof n>"u")n=t.length;var r=U.util.createBuffer();r.putByte(e),r.putInt16(n),r.putBytes(t);var i=r.length(),o=Math.max(16,i-n-3);return r.putBytes(U.random.getBytes(o)),r};v.queue=function(e,t){if(!t)return;if(t.fragment.length()===0){if(t.type===v.ContentType.handshake||t.type===v.ContentType.alert||t.type===v.ContentType.change_cipher_spec)return}if(t.type===v.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()<=v.MaxFragment)r=[t];else{r=[];var i=t.fragment.bytes();while(i.length>v.MaxFragment)r.push(v.createRecord(e,{type:t.type,data:U.util.createBuffer(i.slice(0,v.MaxFragment))})),i=i.slice(v.MaxFragment);if(i.length>0)r.push(v.createRecord(e,{type:t.type,data:U.util.createBuffer(i)}))}for(var o=0;o<r.length&&!e.fail;++o){var s=r[o],a=e.state.current.write;if(a.update(e,s))e.records.push(s)}};v.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 Bc=function(e){switch(e){case!0:return!0;case U.pki.certificateError.bad_certificate:return v.Alert.Description.bad_certificate;case U.pki.certificateError.unsupported_certificate:return v.Alert.Description.unsupported_certificate;case U.pki.certificateError.certificate_revoked:return v.Alert.Description.certificate_revoked;case U.pki.certificateError.certificate_expired:return v.Alert.Description.certificate_expired;case U.pki.certificateError.certificate_unknown:return v.Alert.Description.certificate_unknown;case U.pki.certificateError.unknown_ca:return v.Alert.Description.unknown_ca;default:return v.Alert.Description.bad_certificate}},d1=function(e){switch(e){case!0:return!0;case v.Alert.Description.bad_certificate:return U.pki.certificateError.bad_certificate;case v.Alert.Description.unsupported_certificate:return U.pki.certificateError.unsupported_certificate;case v.Alert.Description.certificate_revoked:return U.pki.certificateError.certificate_revoked;case v.Alert.Description.certificate_expired:return U.pki.certificateError.certificate_expired;case v.Alert.Description.certificate_unknown:return U.pki.certificateError.certificate_unknown;case v.Alert.Description.unknown_ca:return U.pki.certificateError.unknown_ca;default:return U.pki.certificateError.bad_certificate}};v.verifyCertificateChain=function(e,t){try{var n={};for(var r in e.verifyOptions)n[r]=e.verifyOptions[r];n.verify=function(o,s,a){var c=Bc(o),u=e.verify(e,o,s,a);if(u!==!0){if(typeof u==="object"&&!U.util.isArray(u)){var l=Error("The application rejected the certificate.");if(l.send=!0,l.alert={level:v.Alert.Level.fatal,description:v.Alert.Description.bad_certificate},u.message)l.message=u.message;if(u.alert)l.alert.description=u.alert;throw l}if(u!==o)u=d1(u)}return u},U.pki.verifyCertificateChain(e.caStore,t,n)}catch(o){var i=o;if(typeof i!=="object"||U.util.isArray(i))i={send:!0,alert:{level:v.Alert.Level.fatal,description:Bc(o)}};if(!("send"in i))i.send=!0;if(!("alert"in i))i.alert={level:v.Alert.Level.fatal,description:Bc(i.error)};e.error(e,i)}return!e.fail};v.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 o=null,s=null;if(i)s=U.util.bytesToHex(i);else if(n.order.length>0)s=n.order[0];if(s!==null&&s in n.cache){o=n.cache[s],delete n.cache[s];for(var a in n.order)if(n.order[a]===s){n.order.splice(a,1);break}}return o},n.setSession=function(i,o){if(n.order.length===n.capacity){var s=n.order.shift();delete n.cache[s]}var s=U.util.bytesToHex(i);n.order.push(s),n.cache[s]=o}}return n};v.createConnection=function(e){var t=null;if(e.caStore)if(U.util.isArray(e.caStore))t=U.pki.createCaStore(e.caStore);else t=e.caStore;else t=U.pki.createCaStore();var n=e.cipherSuites||null;if(n===null){n=[];for(var r in v.CipherSuites)n.push(v.CipherSuites[r])}var i=e.server?v.ConnectionEnd.server:v.ConnectionEnd.client,o=e.sessionCache?v.createSessionCache(e.sessionCache):null,s={version:{major:v.Version.major,minor:v.Version.minor},entity:i,sessionId:e.sessionId,caStore:t,sessionCache:o,cipherSuites:n,connected:e.connected,virtualHost:e.virtualHost||null,verifyClient:e.verifyClient||!1,verify:e.verify||function(h,d,g,x){return d},verifyOptions:e.verifyOptions||{},getCertificate:e.getCertificate||null,getPrivateKey:e.getPrivateKey||null,getSignature:e.getSignature||null,input:U.util.createBuffer(),tlsData:U.util.createBuffer(),data:U.util.createBuffer(),tlsDataReady:e.tlsDataReady,dataReady:e.dataReady,heartbeatReceived:e.heartbeatReceived,closed:e.closed,error:function(h,d){if(d.origin=d.origin||(h.entity===v.ConnectionEnd.client?"client":"server"),d.send)v.queue(h,v.createAlert(h,d.alert)),v.flush(h);var g=d.fatal!==!1;if(g)h.fail=!0;if(e.error(h,d),g)h.close(!1)},deflate:e.deflate||null,inflate:e.inflate||null};s.reset=function(h){s.version={major:v.Version.major,minor:v.Version.minor},s.record=null,s.session=null,s.peerCertificate=null,s.state={pending:null,current:null},s.expect=s.entity===v.ConnectionEnd.client?Xw:n1,s.fragmented=null,s.records=[],s.open=!1,s.handshakes=0,s.handshaking=!1,s.isConnected=!1,s.fail=!(h||typeof h>"u"),s.input.clear(),s.tlsData.clear(),s.data.clear(),s.state.current=v.createConnectionState(s)},s.reset();var a=function(h,d){var g=d.type-v.ContentType.change_cipher_spec,x=$c[h.entity][h.expect];if(g in x)x[g](h,d);else v.handleUnexpected(h,d)},c=function(h){var d=0,g=h.input,x=g.length();if(x<5)d=5-x;else{h.record={type:g.getByte(),version:{major:g.getByte(),minor:g.getByte()},length:g.getInt16(),fragment:U.util.createBuffer(),ready:!1};var b=h.record.version.major===h.version.major;if(b&&h.session&&h.session.version)b=h.record.version.minor===h.version.minor;if(!b)h.error(h,{message:"Incompatible TLS version.",send:!0,alert:{level:v.Alert.Level.fatal,description:v.Alert.Description.protocol_version}})}return d},u=function(h){var d=0,g=h.input,x=g.length();if(x<h.record.length)d=h.record.length-x;else{h.record.fragment.putBytes(g.getBytes(h.record.length)),g.compact();var b=h.state.current.read;if(b.update(h,h.record)){if(h.fragmented!==null)if(h.fragmented.type===h.record.type)h.fragmented.fragment.putBuffer(h.record.fragment),h.record=h.fragmented;else return h.error(h,{message:"Invalid fragmented record.",send:!0,alert:{level:v.Alert.Level.fatal,description:v.Alert.Description.unexpected_message}}),d;h.record.ready=!0}}return d};s.handshake=function(h){if(s.entity!==v.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,h=h||"";var d=null;if(h.length>0){if(s.sessionCache)d=s.sessionCache.getSession(h);if(d===null)h=""}if(h.length===0&&s.sessionCache){if(d=s.sessionCache.getSession(),d!==null)h=d.id}if(s.session={id:h,version:null,cipherSuite:null,compressionMethod:null,serverCertificate:null,certificateRequest:null,clientCertificate:null,sp:{},md5:U.md.md5.create(),sha1:U.md.sha1.create()},d)s.version=d.version,s.session.sp=d.sp;s.session.sp.client_random=v.createRandom().getBytes(),s.open=!0,v.queue(s,v.createRecord(s,{type:v.ContentType.handshake,data:v.createClientHello(s)})),v.flush(s)}};var l=!1,f=!1,p=function(h){var d=0;if(!h.fail){if(h.record!==null&&h.record.ready&&h.record.fragment.isEmpty())h.record=null;if(h.record===null)d=c(h);if(!h.fail&&h.record!==null&&!h.record.ready)d=u(h);if(!h.fail&&h.record!==null&&h.record.ready)a(h,h.record)}return d};return s.process=function(h){var d=0;if(h)s.input.putBytes(h);if(l&&typeof h>"u")return f=!0,d;var g=l,x=f;l=!0,f=!1;try{d=p(s);while(f)f=!1,p(s)}finally{l=g,f=x}return d},s.prepare=function(h){return v.queue(s,v.createRecord(s,{type:v.ContentType.application_data,data:U.util.createBuffer(h)})),v.flush(s)},s.prepareHeartbeatRequest=function(h,d){if(h instanceof U.util.ByteBuffer)h=h.bytes();if(typeof d>"u")d=h.length;return s.expectedHeartbeatPayload=h,v.queue(s,v.createRecord(s,{type:v.ContentType.heartbeat,data:v.createHeartbeat(v.HeartbeatMessageType.heartbeat_request,h,d)})),v.flush(s)},s.close=function(h){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,v.queue(s,v.createAlert(s,{level:v.Alert.Level.warning,description:v.Alert.Description.close_notify})),v.flush(s);s.closed(s)}s.reset(h)},s};lp.exports=U.tls=U.tls||{};for(Ui in v)if(typeof v[Ui]!=="function")U.tls[Ui]=v[Ui];var Ui;U.tls.prf_tls1=fs;U.tls.hmac_sha1=jw;U.tls.createSessionCache=v.createSessionCache;U.tls.createConnection=v.createConnection});var pp=le(function(G2,dp){var qr=he();Vr();Oc();var Kt=dp.exports=qr.tls;Kt.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=Kt.BulkCipherAlgorithm.aes,e.cipher_type=Kt.CipherType.block,e.enc_key_length=16,e.block_length=16,e.fixed_iv_length=16,e.record_iv_length=16,e.mac_algorithm=Kt.MACAlgorithm.hmac_sha1,e.mac_length=20,e.mac_key_length=20},initConnectionState:fp};Kt.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=Kt.BulkCipherAlgorithm.aes,e.cipher_type=Kt.CipherType.block,e.enc_key_length=32,e.block_length=16,e.fixed_iv_length=16,e.record_iv_length=16,e.mac_algorithm=Kt.MACAlgorithm.hmac_sha1,e.mac_length=20,e.mac_key_length=20},initConnectionState:fp};function fp(e,t,n){var r=t.entity===qr.tls.ConnectionEnd.client;e.read.cipherState={init:!1,cipher:qr.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:qr.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=g1,e.write.cipherFunction=p1,e.read.macLength=e.write.macLength=n.mac_length,e.read.macFunction=e.write.macFunction=Kt.hmac_sha1}function p1(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===Kt.Versions.TLS_1_0.minor)i=t.cipherState.init?null:t.cipherState.iv;else i=qr.random.getBytesSync(16);t.cipherState.init=!0;var o=t.cipherState.cipher;if(o.start({iv:i}),e.version.minor>=Kt.Versions.TLS_1_1.minor)o.output.putBytes(i);if(o.update(e.fragment),o.finish(h1))e.fragment=o.output,e.length=e.fragment.length(),n=!0;return n}function h1(e,t,n){if(!n){var r=e-t.length()%e;t.fillWithByte(r-1,r)}return!0}function m1(e,t,n){var r=!0;if(n){var i=t.length(),o=t.last();for(var s=i-1-o;s<i-1;++s)r=r&&t.at(s)==o;if(r)t.truncate(o+1)}return r}function g1(e,t){var n=!1,r;if(e.version.minor===Kt.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(m1);var o=t.macLength,s=qr.random.getBytesSync(o),a=i.output.length();if(a>=o)e.fragment=i.output.getBytes(a-o),s=i.output.getBytes(o);else e.fragment=i.output.getBytes();e.fragment=qr.util.createBuffer(e.fragment),e.length=e.fragment.length();var c=t.macFunction(t.macKey,t.sequenceNumber,e);return t.updateSequenceNumber(),n=y1(t.macKey,s,c)&&n,n}function y1(e,t,n){var r=qr.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 zc=le(function(q2,yp){var Fe=he();ur();Te();var zi=yp.exports=Fe.sha512=Fe.sha512||{};Fe.md.sha512=Fe.md.algorithms.sha512=zi;var mp=Fe.sha384=Fe.sha512.sha384=Fe.sha512.sha384||{};mp.create=function(){return zi.create("SHA-384")};Fe.md.sha384=Fe.md.algorithms.sha384=mp;Fe.sha512.sha256=Fe.sha512.sha256||{create:function(){return zi.create("SHA-512/256")}};Fe.md["sha512/256"]=Fe.md.algorithms["sha512/256"]=Fe.sha512.sha256;Fe.sha512.sha224=Fe.sha512.sha224||{create:function(){return zi.create("SHA-512/224")}};Fe.md["sha512/224"]=Fe.md.algorithms["sha512/224"]=Fe.sha512.sha224;zi.create=function(e){if(!gp)v1();if(typeof e>"u")e="SHA-512";if(!(e in yn))throw Error("Invalid SHA-512 algorithm: "+e);var t=yn[e],n=null,r=Fe.util.createBuffer(),i=Array(80);for(var o=0;o<80;++o)i[o]=[,,];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 a={algorithm:e.replace("-","").toLowerCase(),blockLength:128,digestLength:s,messageLength:0,fullMessageLength:null,messageLengthSize:16};return a.start=function(){a.messageLength=0,a.fullMessageLength=a.messageLength128=[];var c=a.messageLengthSize/4;for(var u=0;u<c;++u)a.fullMessageLength.push(0);r=Fe.util.createBuffer(),n=Array(t.length);for(var u=0;u<t.length;++u)n[u]=t[u].slice(0);return a},a.start(),a.update=function(c,u){if(u==="utf8")c=Fe.util.encodeUtf8(c);var l=c.length;a.messageLength+=l,l=[l/4294967296>>>0,l>>>0];for(var f=a.fullMessageLength.length-1;f>=0;--f)a.fullMessageLength[f]+=l[1],l[1]=l[0]+(a.fullMessageLength[f]/4294967296>>>0),a.fullMessageLength[f]=a.fullMessageLength[f]>>>0,l[0]=l[1]/4294967296>>>0;if(r.putBytes(c),hp(n,i,r),r.read>2048||r.length()===0)r.compact();return a},a.digest=function(){var c=Fe.util.createBuffer();c.putBytes(r.bytes());var u=a.fullMessageLength[a.fullMessageLength.length-1]+a.messageLengthSize,l=u&a.blockLength-1;c.putBytes(Lc.substr(0,a.blockLength-l));var f,p,h=a.fullMessageLength[0]*8;for(var d=0;d<a.fullMessageLength.length-1;++d)f=a.fullMessageLength[d+1]*8,p=f/4294967296>>>0,h+=p,c.putInt32(h>>>0),h=f>>>0;c.putInt32(h);var g=Array(n.length);for(var d=0;d<n.length;++d)g[d]=n[d].slice(0);hp(g,i,c);var x=Fe.util.createBuffer(),b;if(e==="SHA-512")b=g.length;else if(e==="SHA-384")b=g.length-2;else b=g.length-4;for(var d=0;d<b;++d)if(x.putInt32(g[d][0]),d!==b-1||e!=="SHA-512/224")x.putInt32(g[d][1]);return x},a};var Lc=null,gp=!1,Uc=null,yn=null;function v1(){Lc=String.fromCharCode(128),Lc+=Fe.util.fillString(String.fromCharCode(0),128),Uc=[[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]],yn={},yn["SHA-512"]=[[1779033703,4089235720],[3144134277,2227873595],[1013904242,4271175723],[2773480762,1595750129],[1359893119,2917565137],[2600822924,725511199],[528734635,4215389547],[1541459225,327033209]],yn["SHA-384"]=[[3418070365,3238371032],[1654270250,914150663],[2438529370,812702999],[355462360,4144912697],[1731405415,4290775857],[2394180231,1750603025],[3675008525,1694076839],[1203062813,3204075428]],yn["SHA-512/256"]=[[573645204,4230739756],[2673172387,3360449730],[596883563,1867755857],[2520282905,1497426621],[2519219938,2827943907],[3193839141,1401305490],[721525244,746961066],[246885852,2177182882]],yn["SHA-512/224"]=[[2352822216,424955298],[1944164710,2312950998],[502970286,855612546],[1738396948,1479516111],[258812777,2077511080],[2011393907,79989058],[1067287976,1780299464],[286451373,2446758561]],gp=!0}function hp(e,t,n){var r,i,o,s,a,c,u,l,f,p,h,d,g,x,b,S,C,T,I,k,R,V,D,F,H,re,se,Pe,ue,de,W,te,J,ce,ae,ee=n.length();while(ee>=128){for(ue=0;ue<16;++ue)t[ue][0]=n.getInt32()>>>0,t[ue][1]=n.getInt32()>>>0;for(;ue<80;++ue)te=t[ue-2],de=te[0],W=te[1],r=((de>>>19|W<<13)^(W>>>29|de<<3)^de>>>6)>>>0,i=((de<<13|W>>>19)^(W<<3|de>>>29)^(de<<26|W>>>6))>>>0,ce=t[ue-15],de=ce[0],W=ce[1],o=((de>>>1|W<<31)^(de>>>8|W<<24)^de>>>7)>>>0,s=((de<<31|W>>>1)^(de<<24|W>>>8)^(de<<25|W>>>7))>>>0,J=t[ue-7],ae=t[ue-16],W=i+J[1]+s+ae[1],t[ue][0]=r+J[0]+o+ae[0]+(W/4294967296>>>0)>>>0,t[ue][1]=W>>>0;g=e[0][0],x=e[0][1],b=e[1][0],S=e[1][1],C=e[2][0],T=e[2][1],I=e[3][0],k=e[3][1],R=e[4][0],V=e[4][1],D=e[5][0],F=e[5][1],H=e[6][0],re=e[6][1],se=e[7][0],Pe=e[7][1];for(ue=0;ue<80;++ue)u=((R>>>14|V<<18)^(R>>>18|V<<14)^(V>>>9|R<<23))>>>0,l=((R<<18|V>>>14)^(R<<14|V>>>18)^(V<<23|R>>>9))>>>0,f=(H^R&(D^H))>>>0,p=(re^V&(F^re))>>>0,a=((g>>>28|x<<4)^(x>>>2|g<<30)^(x>>>7|g<<25))>>>0,c=((g<<4|x>>>28)^(x<<30|g>>>2)^(x<<25|g>>>7))>>>0,h=(g&b|C&(g^b))>>>0,d=(x&S|T&(x^S))>>>0,W=Pe+l+p+Uc[ue][1]+t[ue][1],r=se+u+f+Uc[ue][0]+t[ue][0]+(W/4294967296>>>0)>>>0,i=W>>>0,W=c+d,o=a+h+(W/4294967296>>>0)>>>0,s=W>>>0,se=H,Pe=re,H=D,re=F,D=R,F=V,W=k+i,R=I+r+(W/4294967296>>>0)>>>0,V=W>>>0,I=C,k=T,C=b,T=S,b=g,S=x,W=i+s,g=r+o+(W/4294967296>>>0)>>>0,x=W>>>0;W=e[0][1]+x,e[0][0]=e[0][0]+g+(W/4294967296>>>0)>>>0,e[0][1]=W>>>0,W=e[1][1]+S,e[1][0]=e[1][0]+b+(W/4294967296>>>0)>>>0,e[1][1]=W>>>0,W=e[2][1]+T,e[2][0]=e[2][0]+C+(W/4294967296>>>0)>>>0,e[2][1]=W>>>0,W=e[3][1]+k,e[3][0]=e[3][0]+I+(W/4294967296>>>0)>>>0,e[3][1]=W>>>0,W=e[4][1]+V,e[4][0]=e[4][0]+R+(W/4294967296>>>0)>>>0,e[4][1]=W>>>0,W=e[5][1]+F,e[5][0]=e[5][0]+D+(W/4294967296>>>0)>>>0,e[5][1]=W>>>0,W=e[6][1]+re,e[6][0]=e[6][0]+H+(W/4294967296>>>0)>>>0,e[6][1]=W>>>0,W=e[7][1]+Pe,e[7][0]=e[7][0]+se+(W/4294967296>>>0)>>>0,e[7][1]=W>>>0,ee-=128}}});var vp=le(function(b1){var x1=he();Qt();var dt=x1.asn1;b1.privateKeyValidator={name:"PrivateKeyInfo",tagClass:dt.Class.UNIVERSAL,type:dt.Type.SEQUENCE,constructed:!0,value:[{name:"PrivateKeyInfo.version",tagClass:dt.Class.UNIVERSAL,type:dt.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:dt.Class.UNIVERSAL,type:dt.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:dt.Class.UNIVERSAL,type:dt.Type.OID,constructed:!1,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:dt.Class.UNIVERSAL,type:dt.Type.OCTETSTRING,constructed:!1,capture:"privateKey"}]};b1.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:dt.Class.UNIVERSAL,type:dt.Type.SEQUENCE,constructed:!0,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:dt.Class.UNIVERSAL,type:dt.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:dt.Class.UNIVERSAL,type:dt.Type.OID,constructed:!1,capture:"publicKeyOid"}]},{tagClass:dt.Class.UNIVERSAL,type:dt.Type.BITSTRING,constructed:!1,composed:!0,captureBitStringValue:"ed25519PublicKey"}]}});var Pp=le(function(J2,Ip){var gt=he();Di();Ft();zc();Te();var wp=vp(),{publicKeyValidator:w1,privateKeyValidator:E1}=wp;if(typeof Mc>"u")Mc=gt.jsbn.BigInteger;var Mc,Vc=gt.util.ByteBuffer,wt=typeof Buffer>"u"?Uint8Array:Buffer;gt.pki=gt.pki||{};Ip.exports=gt.pki.ed25519=gt.ed25519=gt.ed25519||{};var be=gt.ed25519;be.constants={};be.constants.PUBLIC_KEY_BYTE_LENGTH=32;be.constants.PRIVATE_KEY_BYTE_LENGTH=64;be.constants.SEED_BYTE_LENGTH=32;be.constants.SIGN_BYTE_LENGTH=64;be.constants.HASH_BYTE_LENGTH=64;be.generateKeyPair=function(e){e=e||{};var t=e.seed;if(t===void 0)t=gt.random.getBytesSync(be.constants.SEED_BYTE_LENGTH);else if(typeof t==="string"){if(t.length!==be.constants.SEED_BYTE_LENGTH)throw TypeError('"seed" must be '+be.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=Pr({message:t,encoding:"binary"});var n=new wt(be.constants.PUBLIC_KEY_BYTE_LENGTH),r=new wt(be.constants.PRIVATE_KEY_BYTE_LENGTH);for(var i=0;i<32;++i)r[i]=t[i];return k1(n,r),{publicKey:n,privateKey:r}};be.privateKeyFromAsn1=function(e){var t={},n=[],r=gt.asn1.validate(e,E1,t,n);if(!r){var i=Error("Invalid Key.");throw i.errors=n,i}var o=gt.asn1.derToOid(t.privateKeyOid),s=gt.oids.EdDSA25519;if(o!==s)throw Error('Invalid OID "'+o+'"; OID must be "'+s+'".');var a=t.privateKey,c=Pr({message:gt.asn1.fromDer(a).value,encoding:"binary"});return{privateKeyBytes:c}};be.publicKeyFromAsn1=function(e){var t={},n=[],r=gt.asn1.validate(e,w1,t,n);if(!r){var i=Error("Invalid Key.");throw i.errors=n,i}var o=gt.asn1.derToOid(t.publicKeyOid),s=gt.oids.EdDSA25519;if(o!==s)throw Error('Invalid OID "'+o+'"; OID must be "'+s+'".');var a=t.ed25519PublicKey;if(a.length!==be.constants.PUBLIC_KEY_BYTE_LENGTH)throw Error("Key length is invalid.");return Pr({message:a,encoding:"binary"})};be.publicKeyFromPrivateKey=function(e){e=e||{};var t=Pr({message:e.privateKey,encoding:"binary"});if(t.length!==be.constants.PRIVATE_KEY_BYTE_LENGTH)throw TypeError('"options.privateKey" must have a byte length of '+be.constants.PRIVATE_KEY_BYTE_LENGTH);var n=new wt(be.constants.PUBLIC_KEY_BYTE_LENGTH);for(var r=0;r<n.length;++r)n[r]=t[32+r];return n};be.sign=function(e){e=e||{};var t=Pr(e),n=Pr({message:e.privateKey,encoding:"binary"});if(n.length===be.constants.SEED_BYTE_LENGTH){var r=be.generateKeyPair({seed:n});n=r.privateKey}else if(n.length!==be.constants.PRIVATE_KEY_BYTE_LENGTH)throw TypeError('"options.privateKey" must have a byte length of '+be.constants.SEED_BYTE_LENGTH+" or "+be.constants.PRIVATE_KEY_BYTE_LENGTH);var i=new wt(be.constants.SIGN_BYTE_LENGTH+t.length);I1(i,t,t.length,n);var o=new wt(be.constants.SIGN_BYTE_LENGTH);for(var s=0;s<o.length;++s)o[s]=i[s];return o};be.verify=function(e){e=e||{};var t=Pr(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=Pr({message:e.signature,encoding:"binary"});if(n.length!==be.constants.SIGN_BYTE_LENGTH)throw TypeError('"options.signature" must have a byte length of '+be.constants.SIGN_BYTE_LENGTH);var r=Pr({message:e.publicKey,encoding:"binary"});if(r.length!==be.constants.PUBLIC_KEY_BYTE_LENGTH)throw TypeError('"options.publicKey" must have a byte length of '+be.constants.PUBLIC_KEY_BYTE_LENGTH);var i=new wt(be.constants.SIGN_BYTE_LENGTH+t.length),o=new wt(be.constants.SIGN_BYTE_LENGTH+t.length),s;for(s=0;s<be.constants.SIGN_BYTE_LENGTH;++s)i[s]=n[s];for(s=0;s<t.length;++s)i[s+be.constants.SIGN_BYTE_LENGTH]=t[s];return P1(o,i,i.length,r)>=0};function Pr(e){var t=e.message;if(t instanceof Uint8Array||t instanceof wt)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 Vc(t,n)}else if(!(t instanceof Vc))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 wt(t.length());for(var i=0;i<r.length;++i)r[i]=t.at(i);return r}var Wc=ie(),ds=ie([1]),_1=ie([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),T1=ie([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),xp=ie([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),bp=ie([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),Fi=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]),A1=ie([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function Mi(e,t){var n=gt.md.sha512.create(),r=new Vc(e);n.update(r.getBytes(t),"binary");var i=n.digest().getBytes();if(typeof Buffer<"u")return Buffer.from(i,"binary");var o=new wt(be.constants.HASH_BYTE_LENGTH);for(var s=0;s<64;++s)o[s]=i.charCodeAt(s);return o}function k1(e,t){var n=[ie(),ie(),ie(),ie()],r,i=Mi(t,32);i[0]&=248,i[31]&=127,i[31]|=64,Kc(n,i),ms(e,n);for(r=0;r<32;++r)t[r+32]=e[r];return 0}function I1(e,t,n,r){var i,o,s=new Float64Array(64),a=[ie(),ie(),ie(),ie()],c=Mi(r,32);c[0]&=248,c[31]&=127,c[31]|=64;var u=n+64;for(i=0;i<n;++i)e[64+i]=t[i];for(i=0;i<32;++i)e[32+i]=c[32+i];var l=Mi(e.subarray(32),n+32);Hc(l),Kc(a,l),ms(e,a);for(i=32;i<64;++i)e[i]=r[i];var f=Mi(e,n+64);Hc(f);for(i=32;i<64;++i)s[i]=0;for(i=0;i<32;++i)s[i]=l[i];for(i=0;i<32;++i)for(o=0;o<32;o++)s[i+o]+=f[i]*c[o];return Ep(e.subarray(32),s),u}function P1(e,t,n,r){var i,o,s=new wt(32),a=[ie(),ie(),ie(),ie()],c=[ie(),ie(),ie(),ie()];if(o=-1,n<64)return-1;if(N1(c,r))return-1;if(B1(c))return-1;if(!R1(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 u=Mi(e,n);if(Hc(u),Ap(a,c,u),Kc(c,t.subarray(32)),ps(a,c),ms(s,a),n-=64,_p(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 o=n,o}function R1(e,t){var n;for(n=31;n>=0;--n){if(e[t+n]<Fi[n])return!0;if(e[t+n]>Fi[n])return!1}return!1}function B1(e){var t,n=new wt(32),r=[ie(e[0]),ie(e[1]),ie(e[2]),ie(e[3])];for(t=0;t<3;++t)ps(r,r);if(ms(n,r),n[0]!==1)return!1;for(t=1;t<32;++t)if(n[t]!==0)return!1;return!0}function Ep(e,t){var n,r,i,o;for(r=63;r>=32;--r){n=0;for(i=r-32,o=r-12;i<o;++i)t[i]+=n-16*t[r]*Fi[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)*Fi[i],n=t[i]>>8,t[i]&=255;for(i=0;i<32;++i)t[i]-=n*Fi[i];for(r=0;r<32;++r)t[r+1]+=t[r]>>8,e[r]=t[r]&255}function Hc(e){var t=new Float64Array(64);for(var n=0;n<64;++n)t[n]=e[n],e[n]=0;Ep(e,t)}function ps(e,t){var n=ie(),r=ie(),i=ie(),o=ie(),s=ie(),a=ie(),c=ie(),u=ie(),l=ie();Zn(n,e[1],e[0]),Zn(l,t[1],t[0]),Ne(n,n,l),Kn(r,e[0],e[1]),Kn(l,t[0],t[1]),Ne(r,r,l),Ne(i,e[3],t[3]),Ne(i,i,T1),Ne(o,e[2],t[2]),Kn(o,o,o),Zn(s,r,n),Zn(a,o,i),Kn(c,o,i),Kn(u,r,n),Ne(e[0],s,a),Ne(e[1],u,c),Ne(e[2],c,a),Ne(e[3],s,u)}function Sp(e,t,n){for(var r=0;r<4;++r)kp(e[r],t[r],n)}function ms(e,t){var n=ie(),r=ie(),i=ie();L1(i,t[2]),Ne(n,t[0],i),Ne(r,t[1],i),hs(e,r),e[31]^=Tp(n)<<7}function hs(e,t){var n,r,i,o=ie(),s=ie();for(n=0;n<16;++n)s[n]=t[n];Fc(s),Fc(s),Fc(s);for(r=0;r<2;++r){o[0]=s[0]-65517;for(n=1;n<15;++n)o[n]=s[n]-65535-(o[n-1]>>16&1),o[n-1]&=65535;o[15]=s[15]-32767-(o[14]>>16&1),i=o[15]>>16&1,o[14]&=65535,kp(s,o,1-i)}for(n=0;n<16;n++)e[2*n]=s[n]&255,e[2*n+1]=s[n]>>8}function N1(e,t){var n=ie(),r=ie(),i=ie(),o=ie(),s=ie(),a=ie(),c=ie();if(Xr(e[2],ds),D1(e[1],t),vn(i,e[1]),Ne(o,i,_1),Zn(i,i,e[2]),Kn(o,e[2],o),vn(s,o),vn(a,s),Ne(c,a,s),Ne(n,c,i),Ne(n,n,o),$1(n,n),Ne(n,n,i),Ne(n,n,o),Ne(n,n,o),Ne(e[0],n,o),vn(r,e[0]),Ne(r,r,o),Cp(r,i))Ne(e[0],e[0],A1);if(vn(r,e[0]),Ne(r,r,o),Cp(r,i))return-1;if(Tp(e[0])===t[31]>>7)Zn(e[0],Wc,e[0]);return Ne(e[3],e[0],e[1]),0}function D1(e,t){var n;for(n=0;n<16;++n)e[n]=t[2*n]+(t[2*n+1]<<8);e[15]&=32767}function $1(e,t){var n=ie(),r;for(r=0;r<16;++r)n[r]=t[r];for(r=250;r>=0;--r)if(vn(n,n),r!==1)Ne(n,n,t);for(r=0;r<16;++r)e[r]=n[r]}function Cp(e,t){var n=new wt(32),r=new wt(32);return hs(n,e),hs(r,t),_p(n,0,r,0)}function _p(e,t,n,r){return O1(e,t,n,r,32)}function O1(e,t,n,r,i){var o,s=0;for(o=0;o<i;++o)s|=e[t+o]^n[r+o];return(1&s-1>>>8)-1}function Tp(e){var t=new wt(32);return hs(t,e),t[0]&1}function Ap(e,t,n){var r,i;Xr(e[0],Wc),Xr(e[1],ds),Xr(e[2],ds),Xr(e[3],Wc);for(i=255;i>=0;--i)r=n[i/8|0]>>(i&7)&1,Sp(e,t,r),ps(t,e),ps(e,e),Sp(e,t,r)}function Kc(e,t){var n=[ie(),ie(),ie(),ie()];Xr(n[0],xp),Xr(n[1],bp),Xr(n[2],ds),Ne(n[3],xp,bp),Ap(e,n,t)}function Xr(e,t){var n;for(n=0;n<16;n++)e[n]=t[n]|0}function L1(e,t){var n=ie(),r;for(r=0;r<16;++r)n[r]=t[r];for(r=253;r>=0;--r)if(vn(n,n),r!==2&&r!==4)Ne(n,n,t);for(r=0;r<16;++r)e[r]=n[r]}function Fc(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 kp(e,t,n){var r,i=~(n-1);for(var o=0;o<16;++o)r=i&(e[o]^t[o]),e[o]^=r,t[o]^=r}function ie(e){var t,n=new Float64Array(16);if(e)for(t=0;t<e.length;++t)n[t]=e[t];return n}function Kn(e,t,n){for(var r=0;r<16;++r)e[r]=t[r]+n[r]}function Zn(e,t,n){for(var r=0;r<16;++r)e[r]=t[r]-n[r]}function vn(e,t){Ne(e,t,t)}function Ne(e,t,n){var r,i,o=0,s=0,a=0,c=0,u=0,l=0,f=0,p=0,h=0,d=0,g=0,x=0,b=0,S=0,C=0,T=0,I=0,k=0,R=0,V=0,D=0,F=0,H=0,re=0,se=0,Pe=0,ue=0,de=0,W=0,te=0,J=0,ce=n[0],ae=n[1],ee=n[2],Ee=n[3],$e=n[4],qe=n[5],ye=n[6],oe=n[7],Oe=n[8],_e=n[9],it=n[10],rt=n[11],ot=n[12],st=n[13],Xe=n[14],at=n[15];r=t[0],o+=r*ce,s+=r*ae,a+=r*ee,c+=r*Ee,u+=r*$e,l+=r*qe,f+=r*ye,p+=r*oe,h+=r*Oe,d+=r*_e,g+=r*it,x+=r*rt,b+=r*ot,S+=r*st,C+=r*Xe,T+=r*at,r=t[1],s+=r*ce,a+=r*ae,c+=r*ee,u+=r*Ee,l+=r*$e,f+=r*qe,p+=r*ye,h+=r*oe,d+=r*Oe,g+=r*_e,x+=r*it,b+=r*rt,S+=r*ot,C+=r*st,T+=r*Xe,I+=r*at,r=t[2],a+=r*ce,c+=r*ae,u+=r*ee,l+=r*Ee,f+=r*$e,p+=r*qe,h+=r*ye,d+=r*oe,g+=r*Oe,x+=r*_e,b+=r*it,S+=r*rt,C+=r*ot,T+=r*st,I+=r*Xe,k+=r*at,r=t[3],c+=r*ce,u+=r*ae,l+=r*ee,f+=r*Ee,p+=r*$e,h+=r*qe,d+=r*ye,g+=r*oe,x+=r*Oe,b+=r*_e,S+=r*it,C+=r*rt,T+=r*ot,I+=r*st,k+=r*Xe,R+=r*at,r=t[4],u+=r*ce,l+=r*ae,f+=r*ee,p+=r*Ee,h+=r*$e,d+=r*qe,g+=r*ye,x+=r*oe,b+=r*Oe,S+=r*_e,C+=r*it,T+=r*rt,I+=r*ot,k+=r*st,R+=r*Xe,V+=r*at,r=t[5],l+=r*ce,f+=r*ae,p+=r*ee,h+=r*Ee,d+=r*$e,g+=r*qe,x+=r*ye,b+=r*oe,S+=r*Oe,C+=r*_e,T+=r*it,I+=r*rt,k+=r*ot,R+=r*st,V+=r*Xe,D+=r*at,r=t[6],f+=r*ce,p+=r*ae,h+=r*ee,d+=r*Ee,g+=r*$e,x+=r*qe,b+=r*ye,S+=r*oe,C+=r*Oe,T+=r*_e,I+=r*it,k+=r*rt,R+=r*ot,V+=r*st,D+=r*Xe,F+=r*at,r=t[7],p+=r*ce,h+=r*ae,d+=r*ee,g+=r*Ee,x+=r*$e,b+=r*qe,S+=r*ye,C+=r*oe,T+=r*Oe,I+=r*_e,k+=r*it,R+=r*rt,V+=r*ot,D+=r*st,F+=r*Xe,H+=r*at,r=t[8],h+=r*ce,d+=r*ae,g+=r*ee,x+=r*Ee,b+=r*$e,S+=r*qe,C+=r*ye,T+=r*oe,I+=r*Oe,k+=r*_e,R+=r*it,V+=r*rt,D+=r*ot,F+=r*st,H+=r*Xe,re+=r*at,r=t[9],d+=r*ce,g+=r*ae,x+=r*ee,b+=r*Ee,S+=r*$e,C+=r*qe,T+=r*ye,I+=r*oe,k+=r*Oe,R+=r*_e,V+=r*it,D+=r*rt,F+=r*ot,H+=r*st,re+=r*Xe,se+=r*at,r=t[10],g+=r*ce,x+=r*ae,b+=r*ee,S+=r*Ee,C+=r*$e,T+=r*qe,I+=r*ye,k+=r*oe,R+=r*Oe,V+=r*_e,D+=r*it,F+=r*rt,H+=r*ot,re+=r*st,se+=r*Xe,Pe+=r*at,r=t[11],x+=r*ce,b+=r*ae,S+=r*ee,C+=r*Ee,T+=r*$e,I+=r*qe,k+=r*ye,R+=r*oe,V+=r*Oe,D+=r*_e,F+=r*it,H+=r*rt,re+=r*ot,se+=r*st,Pe+=r*Xe,ue+=r*at,r=t[12],b+=r*ce,S+=r*ae,C+=r*ee,T+=r*Ee,I+=r*$e,k+=r*qe,R+=r*ye,V+=r*oe,D+=r*Oe,F+=r*_e,H+=r*it,re+=r*rt,se+=r*ot,Pe+=r*st,ue+=r*Xe,de+=r*at,r=t[13],S+=r*ce,C+=r*ae,T+=r*ee,I+=r*Ee,k+=r*$e,R+=r*qe,V+=r*ye,D+=r*oe,F+=r*Oe,H+=r*_e,re+=r*it,se+=r*rt,Pe+=r*ot,ue+=r*st,de+=r*Xe,W+=r*at,r=t[14],C+=r*ce,T+=r*ae,I+=r*ee,k+=r*Ee,R+=r*$e,V+=r*qe,D+=r*ye,F+=r*oe,H+=r*Oe,re+=r*_e,se+=r*it,Pe+=r*rt,ue+=r*ot,de+=r*st,W+=r*Xe,te+=r*at,r=t[15],T+=r*ce,I+=r*ae,k+=r*ee,R+=r*Ee,V+=r*$e,D+=r*qe,F+=r*ye,H+=r*oe,re+=r*Oe,se+=r*_e,Pe+=r*it,ue+=r*rt,de+=r*ot,W+=r*st,te+=r*Xe,J+=r*at,o+=38*I,s+=38*k,a+=38*R,c+=38*V,u+=38*D,l+=38*F,f+=38*H,p+=38*re,h+=38*se,d+=38*Pe,g+=38*ue,x+=38*de,b+=38*W,S+=38*te,C+=38*J,i=1,r=o+i+65535,i=Math.floor(r/65536),o=r-i*65536,r=s+i+65535,i=Math.floor(r/65536),s=r-i*65536,r=a+i+65535,i=Math.floor(r/65536),a=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=l+i+65535,i=Math.floor(r/65536),l=r-i*65536,r=f+i+65535,i=Math.floor(r/65536),f=r-i*65536,r=p+i+65535,i=Math.floor(r/65536),p=r-i*65536,r=h+i+65535,i=Math.floor(r/65536),h=r-i*65536,r=d+i+65535,i=Math.floor(r/65536),d=r-i*65536,r=g+i+65535,i=Math.floor(r/65536),g=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=S+i+65535,i=Math.floor(r/65536),S=r-i*65536,r=C+i+65535,i=Math.floor(r/65536),C=r-i*65536,r=T+i+65535,i=Math.floor(r/65536),T=r-i*65536,o+=i-1+37*(i-1),i=1,r=o+i+65535,i=Math.floor(r/65536),o=r-i*65536,r=s+i+65535,i=Math.floor(r/65536),s=r-i*65536,r=a+i+65535,i=Math.floor(r/65536),a=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=l+i+65535,i=Math.floor(r/65536),l=r-i*65536,r=f+i+65535,i=Math.floor(r/65536),f=r-i*65536,r=p+i+65535,i=Math.floor(r/65536),p=r-i*65536,r=h+i+65535,i=Math.floor(r/65536),h=r-i*65536,r=d+i+65535,i=Math.floor(r/65536),d=r-i*65536,r=g+i+65535,i=Math.floor(r/65536),g=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=S+i+65535,i=Math.floor(r/65536),S=r-i*65536,r=C+i+65535,i=Math.floor(r/65536),C=r-i*65536,r=T+i+65535,i=Math.floor(r/65536),T=r-i*65536,o+=i-1+37*(i-1),e[0]=o,e[1]=s,e[2]=a,e[3]=c,e[4]=u,e[5]=l,e[6]=f,e[7]=p,e[8]=h,e[9]=d,e[10]=g,e[11]=x,e[12]=b,e[13]=S,e[14]=C,e[15]=T}});var Dp=le(function(Q2,Np){var Bt=he();Te();Ft();Di();Np.exports=Bt.kem=Bt.kem||{};var Rp=Bt.jsbn.BigInteger;Bt.kem.rsa={};Bt.kem.rsa.create=function(e,t){t=t||{};var n=t.prng||Bt.random,r={};return r.encrypt=function(i,o){var s=Math.ceil(i.n.bitLength()/8),a;do a=new Rp(Bt.util.bytesToHex(n.getBytesSync(s)),16).mod(i.n);while(a.compareTo(Rp.ONE)<=0);a=Bt.util.hexToBytes(a.toString(16));var c=s-a.length;if(c>0)a=Bt.util.fillString(String.fromCharCode(0),c)+a;var u=i.encrypt(a,"NONE"),l=e.generate(a,o);return{encapsulation:u,key:l}},r.decrypt=function(i,o,s){var a=i.decrypt(o,"NONE");return e.generate(a,s)},r};Bt.kem.kdf1=function(e,t){Bp(this,e,0,t||e.digestLength)};Bt.kem.kdf2=function(e,t){Bp(this,e,1,t||e.digestLength)};function Bp(e,t,n,r){e.generate=function(i,o){var s=new Bt.util.ByteBuffer,a=Math.ceil(o/r)+n,c=new Bt.util.ByteBuffer;for(var u=n;u<a;++u){c.putInt32(u),t.start(),t.update(i+c.getBytes());var l=t.digest();s.putBytes(l.getBytes(r))}return s.truncate(s.length()-o),s.getBytes()}}});var Op=le(function(Y2,$p){var Ce=he();Te();$p.exports=Ce.log=Ce.log||{};Ce.log.levels=["none","error","warning","info","debug","verbose","max"];var vs={},Zc=[],Vi=null;Ce.log.LEVEL_LOCKED=2;Ce.log.NO_LEVEL_CHECK=4;Ce.log.INTERPOLATE=8;for(Zt=0;Zt<Ce.log.levels.length;++Zt)gs=Ce.log.levels[Zt],vs[gs]={index:Zt,name:gs.toUpperCase()};var gs,Zt;Ce.log.logMessage=function(e){var t=vs[e.level].index;for(var n=0;n<Zc.length;++n){var r=Zc[n];if(r.flags&Ce.log.NO_LEVEL_CHECK)r.f(e);else{var i=vs[r.level].index;if(t<=i)r.f(r,e)}}};Ce.log.prepareStandard=function(e){if(!("standard"in e))e.standard=vs[e.level].name+" ["+e.category+"] "+e.message};Ce.log.prepareFull=function(e){if(!("full"in e)){var t=[e.message];t=t.concat([]),e.full=Ce.util.format.apply(this,t)}};Ce.log.prepareStandardFull=function(e){if(!("standardFull"in e))Ce.log.prepareStandard(e),e.standardFull=e.standard};ys=["error","warning","info","debug","verbose"];for(Zt=0;Zt<ys.length;++Zt)(function(t){Ce.log[t]=function(n,r){var i=Array.prototype.slice.call(arguments).slice(2),o={timestamp:new Date,level:t,category:n,message:r,arguments:i};Ce.log.logMessage(o)}})(ys[Zt]);var ys,Zt;Ce.log.makeLogger=function(e){var t={flags:0,f:e};return Ce.log.setLevel(t,"none"),t};Ce.log.setLevel=function(e,t){var n=!1;if(e&&!(e.flags&Ce.log.LEVEL_LOCKED))for(var r=0;r<Ce.log.levels.length;++r){var i=Ce.log.levels[r];if(t==i){e.level=t,n=!0;break}}return n};Ce.log.lock=function(e,t){if(typeof t>"u"||t)e.flags|=Ce.log.LEVEL_LOCKED;else e.flags&=~Ce.log.LEVEL_LOCKED};Ce.log.addLogger=function(e){Zc.push(e)};if(typeof console<"u"&&"log"in console){if(console.error&&console.warn&&console.info&&console.debug)jc={error:console.error,warning:console.warn,info:console.info,debug:console.debug,verbose:console.debug},Gn=function(e,t){Ce.log.prepareStandard(t);var n=jc[t.level],r=[t.standard];r=r.concat(t.arguments.slice()),n.apply(console,r)},xn=Ce.log.makeLogger(Gn);else Gn=function(t,n){Ce.log.prepareStandardFull(n),console.log(n.standardFull)},xn=Ce.log.makeLogger(Gn);Ce.log.setLevel(xn,"debug"),Ce.log.addLogger(xn),Vi=xn}else console={log:function(){}};var xn,jc,Gn;if(Vi!==null&&typeof window<"u"&&window.location&&window.location.href&&typeof URL==="function"){if(jn=new URL(window.location.href).searchParams,jn.has("console.level"))Ce.log.setLevel(Vi,jn.get("console.level").slice(-1)[0]);if(jn.has("console.lock")){if(Gc=jn.get("console.lock").slice(-1)[0],Gc=="true")Ce.log.lock(Vi)}}var jn,Gc;Ce.log.consoleLogger=Vi});var Up=le(function(eP,Lp){Lp.exports=ur();Zo();Fn();uc();zc()});var Mp=le(function(tP,Fp){var Z=he();Vr();Qt();Bi();Wr();fn();wc();Ft();Te();cs();var _=Z.asn1,Et=Fp.exports=Z.pkcs7=Z.pkcs7||{};Et.messageFromPem=function(e){var t=Z.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=_.fromDer(t.body);return Et.messageFromAsn1(r)};Et.messageToPem=function(e,t){var n={type:"PKCS7",body:_.toDer(e.toAsn1()).getBytes()};return Z.pem.encode(n,{maxline:t})};Et.messageFromAsn1=function(e){var t={},n=[];if(!_.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=_.derToOid(t.contentType),o;switch(i){case Z.pki.oids.envelopedData:o=Et.createEnvelopedData();break;case Z.pki.oids.encryptedData:o=Et.createEncryptedData();break;case Z.pki.oids.signedData:o=Et.createSignedData();break;default:throw Error("Cannot read PKCS#7 message. ContentType with OID "+i+" is not (yet) supported.")}return o.fromAsn1(t.content.value[0]),o};Et.createSignedData=function(){var e=null;return e={type:Z.pki.oids.signedData,version:1,certificates:[],crls:[],signers:[],digestAlgorithmIdentifiers:[],contentInfo:null,signerInfos:[],fromAsn1:function(r){if(Xc(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 o=0;o<i.length;++o)e.certificates.push(Z.pki.certificateFromAsn1(i[o]))}},toAsn1:function(){if(!e.contentInfo)e.sign();var r=[];for(var i=0;i<e.certificates.length;++i)r.push(Z.pki.certificateToAsn1(e.certificates[i]));var o=[],s=_.create(_.Class.CONTEXT_SPECIFIC,0,!0,[_.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[_.create(_.Class.UNIVERSAL,_.Type.INTEGER,!1,_.integerToDer(e.version).getBytes()),_.create(_.Class.UNIVERSAL,_.Type.SET,!0,e.digestAlgorithmIdentifiers),e.contentInfo])]);if(r.length>0)s.value[0].value.push(_.create(_.Class.CONTEXT_SPECIFIC,0,!0,r));if(o.length>0)s.value[0].value.push(_.create(_.Class.CONTEXT_SPECIFIC,1,!0,o));return s.value[0].value.push(_.create(_.Class.UNIVERSAL,_.Type.SET,!0,e.signerInfos)),_.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[_.create(_.Class.UNIVERSAL,_.Type.OID,!1,_.oidToDer(e.type).getBytes()),s])},addSigner:function(r){var{issuer:i,serialNumber:o}=r;if(r.certificate){var s=r.certificate;if(typeof s==="string")s=Z.pki.certificateFromPem(s);i=s.issuer.attributes,o=s.serialNumber}var a=r.key;if(!a)throw Error("Could not add PKCS#7 signer; no private key specified.");if(typeof a==="string")a=Z.pki.privateKeyFromPem(a);var c=r.digestAlgorithm||Z.pki.oids.sha1;switch(c){case Z.pki.oids.sha1:case Z.pki.oids.sha256:case Z.pki.oids.sha384:case Z.pki.oids.sha512:case Z.pki.oids.md5:break;default:throw Error("Could not add PKCS#7 signer; unknown message digest algorithm: "+c)}var u=r.authenticatedAttributes||[];if(u.length>0){var l=!1,f=!1;for(var p=0;p<u.length;++p){var h=u[p];if(!l&&h.type===Z.pki.oids.contentType){if(l=!0,f)break;continue}if(!f&&h.type===Z.pki.oids.messageDigest){if(f=!0,l)break;continue}}if(!l||!f)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:a,version:1,issuer:i,serialNumber:o,digestAlgorithm:c,signatureAlgorithm:Z.pki.oids.rsaEncryption,signature:null,authenticatedAttributes:u,unauthenticatedAttributes:[]})},sign:function(r){if(r=r||{},typeof e.content!=="object"||e.contentInfo===null){if(e.contentInfo=_.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[_.create(_.Class.UNIVERSAL,_.Type.OID,!1,_.oidToDer(Z.pki.oids.data).getBytes())]),"content"in e){var i;if(e.content instanceof Z.util.ByteBuffer)i=e.content.bytes();else if(typeof e.content==="string")i=Z.util.encodeUtf8(e.content);if(r.detached)e.detachedContent=_.create(_.Class.UNIVERSAL,_.Type.OCTETSTRING,!1,i);else e.contentInfo.value.push(_.create(_.Class.CONTEXT_SPECIFIC,0,!0,[_.create(_.Class.UNIVERSAL,_.Type.OCTETSTRING,!1,i)]))}}if(e.signers.length===0)return;var o=t();n(o)},verify:function(){throw Error("PKCS#7 signature verification not yet implemented.")},addCertificate:function(r){if(typeof r==="string")r=Z.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 o=e.signers[i],s=o.digestAlgorithm;if(!(s in r))r[s]=Z.md[Z.pki.oids[s]].create();if(o.authenticatedAttributes.length===0)o.md=r[s];else o.md=Z.md[Z.pki.oids[s]].create()}e.digestAlgorithmIdentifiers=[];for(var s in r)e.digestAlgorithmIdentifiers.push(_.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[_.create(_.Class.UNIVERSAL,_.Type.OID,!1,_.oidToDer(s).getBytes()),_.create(_.Class.UNIVERSAL,_.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 o=_.derToOid(e.contentInfo.value[0].value),s=_.toDer(i);s.getByte(),_.getBerValueLength(s),s=s.getBytes();for(var a in r)r[a].start().update(s);var c=new Date;for(var u=0;u<e.signers.length;++u){var l=e.signers[u];if(l.authenticatedAttributes.length===0){if(o!==Z.pki.oids.data)throw Error("Invalid signer; authenticatedAttributes must be present when the ContentInfo content type is not PKCS#7 Data.")}else{l.authenticatedAttributesAsn1=_.create(_.Class.CONTEXT_SPECIFIC,0,!0,[]);var f=_.create(_.Class.UNIVERSAL,_.Type.SET,!0,[]);for(var p=0;p<l.authenticatedAttributes.length;++p){var h=l.authenticatedAttributes[p];if(h.type===Z.pki.oids.messageDigest)h.value=r[l.digestAlgorithm].digest();else if(h.type===Z.pki.oids.signingTime){if(!h.value)h.value=c}f.value.push(qc(h)),l.authenticatedAttributesAsn1.value.push(qc(h))}s=_.toDer(f).getBytes(),l.md.start().update(s)}l.signature=l.key.sign(l.md,"RSASSA-PKCS1-V1_5")}e.signerInfos=W1(e.signers)}};Et.createEncryptedData=function(){var e=null;return e={type:Z.pki.oids.encryptedData,version:0,encryptedContent:{algorithm:Z.pki.oids["aes256-CBC"]},fromAsn1:function(t){Xc(e,t,Et.asn1.encryptedDataValidator)},decrypt:function(t){if(t!==void 0)e.encryptedContent.key=t;zp(e)}},e};Et.createEnvelopedData=function(){var e=null;return e={type:Z.pki.oids.envelopedData,version:0,recipients:[],encryptedContent:{algorithm:Z.pki.oids["aes256-CBC"]},fromAsn1:function(t){var n=Xc(e,t,Et.asn1.envelopedDataValidator);e.recipients=F1(n.recipientInfos.value)},toAsn1:function(){return _.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[_.create(_.Class.UNIVERSAL,_.Type.OID,!1,_.oidToDer(e.type).getBytes()),_.create(_.Class.CONTEXT_SPECIFIC,0,!0,[_.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[_.create(_.Class.UNIVERSAL,_.Type.INTEGER,!1,_.integerToDer(e.version).getBytes()),_.create(_.Class.UNIVERSAL,_.Type.SET,!0,M1(e.recipients)),_.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,H1(e.encryptedContent))])])])},findRecipient:function(t){var n=t.issuer.attributes;for(var r=0;r<e.recipients.length;++r){var i=e.recipients[r],o=i.issuer;if(i.serialNumber!==t.serialNumber)continue;if(o.length!==n.length)continue;var s=!0;for(var a=0;a<n.length;++a)if(o[a].type!==n[a].type||o[a].value!==n[a].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 Z.pki.oids.rsaEncryption:case Z.pki.oids.desCBC:var r=n.decrypt(t.encryptedContent.content);e.encryptedContent.key=Z.util.createBuffer(r);break;default:throw Error("Unsupported asymmetric cipher, OID "+t.encryptedContent.algorithm)}zp(e)},addRecipient:function(t){e.recipients.push({version:0,issuer:t.issuer.attributes,serialNumber:t.serialNumber,encryptedContent:{algorithm:Z.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,o;switch(n){case Z.pki.oids["aes128-CBC"]:r=16,i=16,o=Z.aes.createEncryptionCipher;break;case Z.pki.oids["aes192-CBC"]:r=24,i=16,o=Z.aes.createEncryptionCipher;break;case Z.pki.oids["aes256-CBC"]:r=32,i=16,o=Z.aes.createEncryptionCipher;break;case Z.pki.oids["des-EDE3-CBC"]:r=24,i=8,o=Z.des.createEncryptionCipher;break;default:throw Error("Unsupported symmetric cipher, OID "+n)}if(t===void 0)t=Z.util.createBuffer(Z.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=Z.util.createBuffer(Z.random.getBytes(i));var s=o(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 a=0;a<e.recipients.length;++a){var c=e.recipients[a];if(c.encryptedContent.content!==void 0)continue;switch(c.encryptedContent.algorithm){case Z.pki.oids.rsaEncryption:c.encryptedContent.content=c.encryptedContent.key.encrypt(e.encryptedContent.key.data);break;default:throw Error("Unsupported asymmetric cipher, OID "+c.encryptedContent.algorithm)}}}},e};function U1(e){var t={},n=[];if(!_.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:Z.pki.RDNAttributesAsArray(t.issuer),serialNumber:Z.util.createBuffer(t.serial).toHex(),encryptedContent:{algorithm:_.derToOid(t.encAlgorithm),parameter:t.encParameter?t.encParameter.value:void 0,content:t.encKey}}}function z1(e){return _.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[_.create(_.Class.UNIVERSAL,_.Type.INTEGER,!1,_.integerToDer(e.version).getBytes()),_.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[Z.pki.distinguishedNameToAsn1({attributes:e.issuer}),_.create(_.Class.UNIVERSAL,_.Type.INTEGER,!1,Z.util.hexToBytes(e.serialNumber))]),_.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[_.create(_.Class.UNIVERSAL,_.Type.OID,!1,_.oidToDer(e.encryptedContent.algorithm).getBytes()),_.create(_.Class.UNIVERSAL,_.Type.NULL,!1,"")]),_.create(_.Class.UNIVERSAL,_.Type.OCTETSTRING,!1,e.encryptedContent.content)])}function F1(e){var t=[];for(var n=0;n<e.length;++n)t.push(U1(e[n]));return t}function M1(e){var t=[];for(var n=0;n<e.length;++n)t.push(z1(e[n]));return t}function V1(e){var t=_.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[_.create(_.Class.UNIVERSAL,_.Type.INTEGER,!1,_.integerToDer(e.version).getBytes()),_.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[Z.pki.distinguishedNameToAsn1({attributes:e.issuer}),_.create(_.Class.UNIVERSAL,_.Type.INTEGER,!1,Z.util.hexToBytes(e.serialNumber))]),_.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[_.create(_.Class.UNIVERSAL,_.Type.OID,!1,_.oidToDer(e.digestAlgorithm).getBytes()),_.create(_.Class.UNIVERSAL,_.Type.NULL,!1,"")])]);if(e.authenticatedAttributesAsn1)t.value.push(e.authenticatedAttributesAsn1);if(t.value.push(_.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[_.create(_.Class.UNIVERSAL,_.Type.OID,!1,_.oidToDer(e.signatureAlgorithm).getBytes()),_.create(_.Class.UNIVERSAL,_.Type.NULL,!1,"")])),t.value.push(_.create(_.Class.UNIVERSAL,_.Type.OCTETSTRING,!1,e.signature)),e.unauthenticatedAttributes.length>0){var n=_.create(_.Class.CONTEXT_SPECIFIC,1,!0,[]);for(var r=0;r<e.unauthenticatedAttributes.length;++r){var i=e.unauthenticatedAttributes[r];n.values.push(qc(i))}t.value.push(n)}return t}function W1(e){var t=[];for(var n=0;n<e.length;++n)t.push(V1(e[n]));return t}function qc(e){var t;if(e.type===Z.pki.oids.contentType)t=_.create(_.Class.UNIVERSAL,_.Type.OID,!1,_.oidToDer(e.value).getBytes());else if(e.type===Z.pki.oids.messageDigest)t=_.create(_.Class.UNIVERSAL,_.Type.OCTETSTRING,!1,e.value.bytes());else if(e.type===Z.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 o=Date.parse(i);if(!isNaN(o))i=new Date(o);else if(i.length===13)i=_.utcTimeToDate(i);else i=_.generalizedTimeToDate(i)}if(i>=n&&i<r)t=_.create(_.Class.UNIVERSAL,_.Type.UTCTIME,!1,_.dateToUtcTime(i));else t=_.create(_.Class.UNIVERSAL,_.Type.GENERALIZEDTIME,!1,_.dateToGeneralizedTime(i))}return _.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[_.create(_.Class.UNIVERSAL,_.Type.OID,!1,_.oidToDer(e.type).getBytes()),_.create(_.Class.UNIVERSAL,_.Type.SET,!0,[t])])}function H1(e){return[_.create(_.Class.UNIVERSAL,_.Type.OID,!1,_.oidToDer(Z.pki.oids.data).getBytes()),_.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[_.create(_.Class.UNIVERSAL,_.Type.OID,!1,_.oidToDer(e.algorithm).getBytes()),!e.parameter?void 0:_.create(_.Class.UNIVERSAL,_.Type.OCTETSTRING,!1,e.parameter.getBytes())]),_.create(_.Class.CONTEXT_SPECIFIC,0,!0,[_.create(_.Class.UNIVERSAL,_.Type.OCTETSTRING,!1,e.content.getBytes())])]}function Xc(e,t,n){var r={},i=[];if(!_.validate(t,n,r,i)){var o=Error("Cannot read PKCS#7 message. ASN.1 object is not a supported PKCS#7 message.");throw o.errors=o,o}var s=_.derToOid(r.contentType);if(s!==Z.pki.oids.data)throw Error("Unsupported PKCS#7 message. Only wrapped ContentType Data supported.");if(r.encryptedContent){var a="";if(Z.util.isArray(r.encryptedContent))for(var c=0;c<r.encryptedContent.length;++c){if(r.encryptedContent[c].type!==_.Type.OCTETSTRING)throw Error("Malformed PKCS#7 message, expecting encrypted content constructed of only OCTET STRING objects.");a+=r.encryptedContent[c].value}else a=r.encryptedContent;e.encryptedContent={algorithm:_.derToOid(r.encAlgorithm),parameter:Z.util.createBuffer(r.encParameter.value),content:Z.util.createBuffer(a)}}if(r.content){var a="";if(Z.util.isArray(r.content))for(var c=0;c<r.content.length;++c){if(r.content[c].type!==_.Type.OCTETSTRING)throw Error("Malformed PKCS#7 message, expecting content constructed of only OCTET STRING objects.");a+=r.content[c].value}else a=r.content;e.content=Z.util.createBuffer(a)}return e.version=r.version.charCodeAt(0),e.rawCapture=r,r}function zp(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 Z.pki.oids["aes128-CBC"]:case Z.pki.oids["aes192-CBC"]:case Z.pki.oids["aes256-CBC"]:t=Z.aes.createDecryptionCipher(e.encryptedContent.key);break;case Z.pki.oids.desCBC:case Z.pki.oids["des-EDE3-CBC"]:t=Z.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 Wp=le(function(rP,Vp){var nt=he();Vr();On();Zo();Fn();Te();var bs=Vp.exports=nt.ssh=nt.ssh||{};bs.privateKeyToPutty=function(e,t,n){n=n||"",t=t||"";var r="ssh-rsa",i=t===""?"none":"aes256-cbc",o="PuTTY-User-Key-File-2: "+r+`\r
19
+ `)H.push(C+1);H.push(C);for(var re=0;re<H.length;++re){var se=H[re],Pe=I?c(se+1,T):-1,ue=T;if(Pe===-1&&k)Pe=k.blank,ue=k.end;if(Pe!==-1&&Pe<=v){var de=a(Pe);return g=ue+14+S.length,[e.substring(b,g),S,e.substring(se,de),e.substring(de,ue)]}if(I&&se<T)return g=T+14+S.length,[e.substring(b,g),S,void 0,e.substring(se,T)]}}return null}}}});var Di=le(function(k2,Qf){var Ke=he();zo();rc();Te();Qf.exports=Ke.des=Ke.des||{};Ke.des.startEncrypting=function(e,t,n,r){var i=qo({key:e,output:n,decrypt:!1,mode:r||(t===null?"ECB":"CBC")});return i.start(t),i};Ke.des.createEncryptionCipher=function(e,t){return qo({key:e,output:null,decrypt:!1,mode:t})};Ke.des.startDecrypting=function(e,t,n,r){var i=qo({key:e,output:n,decrypt:!0,mode:r||(t===null?"ECB":"CBC")});return i.start(t),i};Ke.des.createDecryptionCipher=function(e,t){return qo({key:e,output:null,decrypt:!0,mode:t})};Ke.des.Algorithm=function(e,t){var n=this;n.name=e,n.mode=new t({blockSize:8,cipher:{encrypt:function(r,i){return Jf(n._keys,r,i,!1)},decrypt:function(r,i){return Jf(n._keys,r,i,!0)}}}),n._init=!1};Ke.des.Algorithm.prototype.initialize=function(e){if(this._init)return;var t=Ke.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=bS(t),this._init=!0};fr("DES-ECB",Ke.cipher.modes.ecb);fr("DES-CBC",Ke.cipher.modes.cbc);fr("DES-CFB",Ke.cipher.modes.cfb);fr("DES-OFB",Ke.cipher.modes.ofb);fr("DES-CTR",Ke.cipher.modes.ctr);fr("3DES-ECB",Ke.cipher.modes.ecb);fr("3DES-CBC",Ke.cipher.modes.cbc);fr("3DES-CFB",Ke.cipher.modes.cfb);fr("3DES-OFB",Ke.cipher.modes.ofb);fr("3DES-CTR",Ke.cipher.modes.ctr);function fr(e,t){var n=function(){return new Ke.des.Algorithm(e,t)};Ke.cipher.registerAlgorithm(e,n)}var dS=[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],pS=[-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],hS=[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],mS=[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],gS=[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],yS=[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],vS=[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],xS=[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 bS(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],o=[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],a=[0,268435456,524288,268959744,2,268435458,524290,268959746,0,268435456,524288,268959744,2,268435458,524290,268959746],c=[0,65536,2048,67584,536870912,536936448,536872960,536938496,131072,196608,133120,198656,537001984,537067520,537004032,537069568],u=[0,262144,0,262144,2,262146,2,262146,33554432,33816576,33554432,33816576,33554434,33816578,33554434,33816578],l=[0,268435456,8,268435464,0,268435456,8,268435464,1024,268436480,1032,268436488,1024,268436480,1032,268436488],f=[0,32,0,32,1048576,1048608,1048576,1048608,8192,8224,8192,8224,1056768,1056800,1056768,1056800],p=[0,16777216,512,16777728,2097152,18874368,2097664,18874880,67108864,83886080,67109376,83886592,69206016,85983232,69206528,85983744],h=[0,4096,134217728,134221824,524288,528384,134742016,134746112,16,4112,134217744,134221840,524304,528400,134742032,134746128],d=[0,4,256,260,0,4,256,260,1,5,257,261,1,5,257,261],g=e.length()>8?3:1,v=[],b=[0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0],S=0,C;for(var T=0;T<g;T++){var I=e.getInt32(),k=e.getInt32();C=(I>>>4^k)&252645135,k^=C,I^=C<<4,C=(k>>>-16^I)&65535,I^=C,k^=C<<-16,C=(I>>>2^k)&858993459,k^=C,I^=C<<2,C=(k>>>-16^I)&65535,I^=C,k^=C<<-16,C=(I>>>1^k)&1431655765,k^=C,I^=C<<1,C=(k>>>8^I)&16711935,I^=C,k^=C<<8,C=(I>>>1^k)&1431655765,k^=C,I^=C<<1,C=I<<8|k>>>20&240,I=k<<24|k<<8&16711680|k>>>8&65280|k>>>24&240,k=C;for(var R=0;R<b.length;++R){if(b[R])I=I<<2|I>>>26,k=k<<2|k>>>26;else I=I<<1|I>>>27,k=k<<1|k>>>27;I&=-15,k&=-15;var V=t[I>>>28]|n[I>>>24&15]|r[I>>>20&15]|i[I>>>16&15]|o[I>>>12&15]|s[I>>>8&15]|a[I>>>4&15],D=c[k>>>28]|u[k>>>24&15]|l[k>>>20&15]|f[k>>>16&15]|p[k>>>12&15]|h[k>>>8&15]|d[k>>>4&15];C=(D>>>16^V)&65535,v[S++]=V^C,v[S++]=D^C<<16}}return v}function Jf(e,t,n,r){var i=e.length===32?3:9,o;if(i===3)o=r?[30,-2,-2]:[0,32,2];else o=r?[94,62,-2,32,64,2,30,-2,-2]:[0,32,2,62,30,-2,64,96,2];var s,a=t[0],c=t[1];s=(a>>>4^c)&252645135,c^=s,a^=s<<4,s=(a>>>16^c)&65535,c^=s,a^=s<<16,s=(c>>>2^a)&858993459,a^=s,c^=s<<2,s=(c>>>8^a)&16711935,a^=s,c^=s<<8,s=(a>>>1^c)&1431655765,c^=s,a^=s<<1,a=a<<1|a>>>31,c=c<<1|c>>>31;for(var u=0;u<i;u+=3){var l=o[u+1],f=o[u+2];for(var p=o[u];p!=l;p+=f){var h=c^e[p],d=(c>>>4|c<<28)^e[p+1];s=a,a=c,c=s^(pS[h>>>24&63]|mS[h>>>16&63]|yS[h>>>8&63]|xS[h&63]|dS[d>>>24&63]|hS[d>>>16&63]|gS[d>>>8&63]|vS[d&63])}s=a,a=c,c=s}a=a>>>1|a<<31,c=c>>>1|c<<31,s=(a>>>1^c)&1431655765,c^=s,a^=s<<1,s=(c>>>8^a)&16711935,a^=s,c^=s<<8,s=(c>>>2^a)&858993459,a^=s,c^=s<<2,s=(a>>>16^c)&65535,c^=s,a^=s<<16,s=(a>>>4^c)&252645135,c^=s,a^=s<<4,n[0]=a,n[1]=c}function qo(e){e=e||{};var t=(e.mode||"CBC").toUpperCase(),n="DES-"+t,r;if(e.decrypt)r=Ke.cipher.createDecipher(n,e.key);else r=Ke.cipher.createCipher(n,e.key);var i=r.start;return r.start=function(o,s){var a=null;if(s instanceof Ke.util.ByteBuffer)a=s,s={};s=s||{},s.output=a,s.iv=o,i.call(r,s)},r}});var Xo=le(function(I2,Yf){var Ct=he();Ln();ur();Te();var SS=Ct.pkcs5=Ct.pkcs5||{},kr;if(Ct.util.isNodejs&&!Ct.options.usePureJavaScript)kr=Ei("crypto");Yf.exports=Ct.pbkdf2=SS.pbkdf2=function(e,t,n,r,i,o){if(typeof i==="function")o=i,i=null;if(Ct.util.isNodejs&&!Ct.options.usePureJavaScript&&kr.pbkdf2&&(i===null||typeof i!=="object")&&(kr.pbkdf2Sync.length>4||(!i||i==="sha1"))){if(typeof i!=="string")i="sha1";if(e=Buffer.from(e,"binary"),t=Buffer.from(t,"binary"),!o){if(kr.pbkdf2Sync.length===4)return kr.pbkdf2Sync(e,t,n,r).toString("binary");return kr.pbkdf2Sync(e,t,n,r,i).toString("binary")}if(kr.pbkdf2Sync.length===4)return kr.pbkdf2(e,t,n,r,function(C,T){if(C)return o(C);o(null,T.toString("binary"))});return kr.pbkdf2(e,t,n,r,i,function(C,T){if(C)return o(C);o(null,T.toString("binary"))})}if(typeof i>"u"||i===null)i="sha1";if(typeof i==="string"){if(!(i in Ct.md.algorithms))throw Error("Unknown hash algorithm: "+i);i=Ct.md[i].create()}var s=i.digestLength;if(r>4294967295*s){var a=Error("Derived key is too long.");if(o)return o(a);throw a}var c=Math.ceil(r/s),u=r-(c-1)*s,l=Ct.hmac.create();l.start(i,e);var f="",p,h,d;if(!o){for(var g=1;g<=c;++g){l.start(null,null),l.update(t),l.update(Ct.util.int32ToBytes(g)),p=d=l.digest().getBytes();for(var v=2;v<=n;++v)l.start(null,null),l.update(d),h=l.digest().getBytes(),p=Ct.util.xorBytes(p,h,s),d=h;f+=g<c?p:p.substr(0,u)}return f}var g=1,v;function b(){if(g>c)return o(null,f);l.start(null,null),l.update(t),l.update(Ct.util.int32ToBytes(g)),p=d=l.digest().getBytes(),v=2,S()}function S(){if(v<=n)return l.start(null,null),l.update(d),h=l.digest().getBytes(),p=Ct.util.xorBytes(p,h,s),d=h,++v,Ct.util.setImmediate(S);f+=g<c?p:p.substr(0,u),++g,b()}b()}});var uc=le(function(P2,id){var dr=he();ur();Te();var td=id.exports=dr.sha256=dr.sha256||{};dr.md.sha256=dr.md.algorithms.sha256=td;td.create=function(){if(!rd)CS();var e=null,t=dr.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 o=0;o<i;++o)r.fullMessageLength.push(0);return t=dr.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,o){if(o==="utf8")i=dr.util.encodeUtf8(i);var s=i.length;r.messageLength+=s,s=[s/4294967296>>>0,s>>>0];for(var a=r.fullMessageLength.length-1;a>=0;--a)r.fullMessageLength[a]+=s[1],s[1]=s[0]+(r.fullMessageLength[a]/4294967296>>>0),r.fullMessageLength[a]=r.fullMessageLength[a]>>>0,s[0]=s[1]/4294967296>>>0;if(t.putBytes(i),ed(e,n,t),t.read>2048||t.length()===0)t.compact();return r},r.digest=function(){var i=dr.util.createBuffer();i.putBytes(t.bytes());var o=r.fullMessageLength[r.fullMessageLength.length-1]+r.messageLengthSize,s=o&r.blockLength-1;i.putBytes(cc.substr(0,r.blockLength-s));var a,c,u=r.fullMessageLength[0]*8;for(var l=0;l<r.fullMessageLength.length-1;++l)a=r.fullMessageLength[l+1]*8,c=a/4294967296>>>0,u+=c,i.putInt32(u>>>0),u=a>>>0;i.putInt32(u);var f={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3,h4:e.h4,h5:e.h5,h6:e.h6,h7:e.h7};ed(f,n,i);var p=dr.util.createBuffer();return p.putInt32(f.h0),p.putInt32(f.h1),p.putInt32(f.h2),p.putInt32(f.h3),p.putInt32(f.h4),p.putInt32(f.h5),p.putInt32(f.h6),p.putInt32(f.h7),p},r};var cc=null,rd=!1,nd=null;function CS(){cc=String.fromCharCode(128),cc+=dr.util.fillString(String.fromCharCode(0),64),nd=[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],rd=!0}function ed(e,t,n){var r,i,o,s,a,c,u,l,f,p,h,d,g,v,b,S=n.length();while(S>=64){for(u=0;u<16;++u)t[u]=n.getInt32();for(;u<64;++u)r=t[u-2],r=(r>>>17|r<<15)^(r>>>19|r<<13)^r>>>10,i=t[u-15],i=(i>>>7|i<<25)^(i>>>18|i<<14)^i>>>3,t[u]=r+t[u-7]+i+t[u-16]|0;l=e.h0,f=e.h1,p=e.h2,h=e.h3,d=e.h4,g=e.h5,v=e.h6,b=e.h7;for(u=0;u<64;++u)s=(d>>>6|d<<26)^(d>>>11|d<<21)^(d>>>25|d<<7),a=v^d&(g^v),o=(l>>>2|l<<30)^(l>>>13|l<<19)^(l>>>22|l<<10),c=l&f|p&(l^f),r=b+s+a+nd[u]+t[u],i=o+c,b=v,v=g,g=d,d=h+r>>>0,h=p,p=f,f=l,l=r+i>>>0;e.h0=e.h0+l|0,e.h1=e.h1+f|0,e.h2=e.h2+p|0,e.h3=e.h3+h|0,e.h4=e.h4+d|0,e.h5=e.h5+g|0,e.h6=e.h6+v|0,e.h7=e.h7+b|0,S-=64}}});var lc=le(function(R2,od){var pr=he();Te();var Jo=null;if(pr.util.isNodejs&&!pr.options.usePureJavaScript&&!process.versions["node-webkit"])Jo=Ei("crypto");var wS=od.exports=pr.prng=pr.prng||{};wS.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(u,l){if(!l)return t.generateSync(u);var f=t.plugin.cipher,p=t.plugin.increment,h=t.plugin.formatKey,d=t.plugin.formatSeed,g=pr.util.createBuffer();t.key=null,v();function v(b){if(b)return l(b);if(g.length()>=u)return l(null,g.getBytes(u));if(t.generated>1048575)t.key=null;if(t.key===null)return pr.util.nextTick(function(){o(v)});var S=f(t.key,t.seed);t.generated+=S.length,g.putBytes(S),t.key=h(f(t.key,p(t.seed))),t.seed=d(f(t.key,t.seed)),pr.util.setImmediate(v)}},t.generateSync=function(u){var l=t.plugin.cipher,f=t.plugin.increment,p=t.plugin.formatKey,h=t.plugin.formatSeed;t.key=null;var d=pr.util.createBuffer();while(d.length()<u){if(t.generated>1048575)t.key=null;if(t.key===null)s();var g=l(t.key,t.seed);t.generated+=g.length,d.putBytes(g),t.key=p(l(t.key,f(t.seed))),t.seed=h(l(t.key,t.seed))}return d.getBytes(u)};function o(u){if(t.pools[0].messageLength>=32)return a(),u();var l=32-t.pools[0].messageLength<<5;t.seedFile(l,function(f,p){if(f)return u(f);t.collect(p),a(),u()})}function s(){if(t.pools[0].messageLength>=32)return a();var u=32-t.pools[0].messageLength<<5;t.collect(t.seedFileSync(u)),a()}function a(){t.reseeds=t.reseeds===4294967295?0:t.reseeds+1;var u=t.plugin.md.create();u.update(t.keyBytes);var l=1;for(var f=0;f<32;++f){if(t.reseeds%l===0)u.update(t.pools[f].digest().getBytes()),t.pools[f].start();l=l<<1}t.keyBytes=u.digest().getBytes(),u.start(),u.update(t.keyBytes);var p=u.digest().getBytes();t.key=t.plugin.formatKey(t.keyBytes),t.seed=t.plugin.formatSeed(p),t.generated=0}function c(u){var l=null,f=pr.util.globalScope,p=f.crypto||f.msCrypto;if(p&&p.getRandomValues)l=function(I){return p.getRandomValues(I)};var h=pr.util.createBuffer();if(l)while(h.length()<u){var d=Math.max(1,Math.min(u-h.length(),65536)/4),g=new Uint32Array(Math.floor(d));try{l(g);for(var v=0;v<g.length;++v)h.putInt32(g[v])}catch(I){if(!(typeof QuotaExceededError<"u"&&I instanceof QuotaExceededError))throw I}}if(h.length()<u){var b,S,C,T=Math.floor(Math.random()*65536);while(h.length()<u){S=16807*(T&65535),b=16807*(T>>16),S+=(b&32767)<<16,S+=b>>15,S=(S&2147483647)+(S>>31),T=S&4294967295;for(var v=0;v<3;++v)C=T>>>(v<<3),C^=Math.floor(Math.random()*256),h.putByte(C&255)}}return h.getBytes(u)}if(Jo)t.seedFile=function(u,l){Jo.randomBytes(u,function(f,p){if(f)return l(f);l(null,p.toString("binary"))})},t.seedFileSync=function(u){return Jo.randomBytes(u).toString("binary")};else t.seedFile=function(u,l){try{l(null,c(u))}catch(f){l(f)}},t.seedFileSync=c;return t.collect=function(u){var l=u.length;for(var f=0;f<l;++f)t.pools[t.pool].update(u.substr(f,1)),t.pool=t.pool===31?0:t.pool+1},t.collectInt=function(u,l){var f="";for(var p=0;p<l;p+=8)f+=String.fromCharCode(u>>p&255);t.collect(f)},t.registerWorker=function(u){if(u===self)t.seedFile=function(f,p){function h(d){var g=d.data;if(g.forge&&g.forge.prng)self.removeEventListener("message",h),p(g.forge.prng.err,g.forge.prng.bytes)}self.addEventListener("message",h),self.postMessage({forge:{prng:{needed:f}}})};else{var l=function(f){var p=f.data;if(p.forge&&p.forge.prng)t.seedFile(p.forge.prng.needed,function(h,d){u.postMessage({forge:{prng:{err:h,bytes:d}}})})};u.addEventListener("message",l)}},t}});var Ft=le(function(B2,fc){var ft=he();Vr();uc();lc();Te();(function(){if(ft.random&&ft.random.getBytes){fc.exports=ft.random;return}(function(e){var t={},n=[,,,,],r=ft.util.createBuffer();t.formatKey=function(f){var p=ft.util.createBuffer(f);return f=[,,,,],f[0]=p.getInt32(),f[1]=p.getInt32(),f[2]=p.getInt32(),f[3]=p.getInt32(),ft.aes._expandKey(f,!1)},t.formatSeed=function(f){var p=ft.util.createBuffer(f);return f=[,,,,],f[0]=p.getInt32(),f[1]=p.getInt32(),f[2]=p.getInt32(),f[3]=p.getInt32(),f},t.cipher=function(f,p){return ft.aes._updateBlock(f,p,n,!1),r.putInt32(n[0]),r.putInt32(n[1]),r.putInt32(n[2]),r.putInt32(n[3]),r.getBytes()},t.increment=function(f){return++f[3],f},t.md=ft.md.sha256;function i(){var f=ft.prng.create(t);return f.getBytes=function(p,h){return f.generate(p,h)},f.getBytesSync=function(p){return f.generate(p)},f}var o=i(),s=null,a=ft.util.globalScope,c=a.crypto||a.msCrypto;if(c&&c.getRandomValues)s=function(f){return c.getRandomValues(f)};if(ft.options.usePureJavaScript||!ft.util.isNodejs&&!s){if(typeof window>"u"||window.document===void 0);if(o.collectInt(+new Date,32),typeof navigator<"u"){var u="";for(var l in navigator)try{if(typeof navigator[l]=="string")u+=navigator[l]}catch(f){}o.collect(u),u=null}if(e)e().mousemove(function(f){o.collectInt(f.clientX,16),o.collectInt(f.clientY,16)}),e().keypress(function(f){o.collectInt(f.charCode,8)})}if(!ft.random)ft.random=o;else for(var l in o)ft.random[l]=o[l];ft.random.createInstance=i,fc.exports=ft.random})(typeof jQuery<"u"?jQuery:null)})()});var pc=le(function(N2,cd){var kt=he();Te();var dc=[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],sd=[1,2,3,5],ES=function(e,t){return e<<t&65535|(e&65535)>>16-t},_S=function(e,t){return(e&65535)>>t|e<<16-t&65535};cd.exports=kt.rc2=kt.rc2||{};kt.rc2.expandKey=function(e,t){if(typeof e==="string")e=kt.util.createBuffer(e);t=t||128;var n=e,r=e.length(),i=t,o=Math.ceil(i/8),s=255>>(-i&7),a;for(a=r;a<128;a++)n.putByte(dc[n.at(a-1)+n.at(a-r)&255]);n.setAt(128-o,dc[n.at(128-o)&s]);for(a=127-o;a>=0;a--)n.setAt(a,dc[n.at(a+1)^n.at(a+o)]);return n};var ad=function(e,t,n){var r=!1,i=null,o=null,s=null,a,c,u,l,f=[];e=kt.rc2.expandKey(e,t);for(u=0;u<64;u++)f.push(e.getInt16Le());if(n)a=function(d){for(u=0;u<4;u++)d[u]+=f[l]+(d[(u+3)%4]&d[(u+2)%4])+(~d[(u+3)%4]&d[(u+1)%4]),d[u]=ES(d[u],sd[u]),l++},c=function(d){for(u=0;u<4;u++)d[u]+=f[d[(u+3)%4]&63]};else a=function(d){for(u=3;u>=0;u--)d[u]=_S(d[u],sd[u]),d[u]-=f[l]+(d[(u+3)%4]&d[(u+2)%4])+(~d[(u+3)%4]&d[(u+1)%4]),l--},c=function(d){for(u=3;u>=0;u--)d[u]-=f[d[(u+3)%4]&63]};var p=function(d){var g=[];for(u=0;u<4;u++){var v=i.getInt16Le();if(s!==null)if(n)v^=s.getInt16Le();else s.putInt16Le(v);g.push(v&65535)}l=n?0:63;for(var b=0;b<d.length;b++)for(var S=0;S<d[b][0];S++)d[b][1](g);for(u=0;u<4;u++){if(s!==null)if(n)s.putInt16Le(g[u]);else g[u]^=s.getInt16Le();o.putInt16Le(g[u])}},h=null;return h={start:function(d,g){if(d){if(typeof d==="string")d=kt.util.createBuffer(d)}r=!1,i=kt.util.createBuffer(),o=g||new kt.util.createBuffer,s=d,h.output=o},update:function(d){if(!r)i.putBuffer(d);while(i.length()>=8)p([[5,a],[1,c],[6,a],[1,c],[5,a]])},finish:function(d){var g=!0;if(n)if(d)g=d(8,i,!n);else{var v=i.length()===8?8:8-i.length();i.fillWithByte(v,v)}if(g)r=!0,h.update();if(!n){if(g=i.length()===0,g)if(d)g=d(8,o,!n);else{var b=o.length(),S=o.at(b-1);if(S>b)g=!1;else o.truncate(S)}}return g}},h};kt.rc2.startEncrypting=function(e,t,n){var r=kt.rc2.createEncryptionCipher(e,128);return r.start(t,n),r};kt.rc2.createEncryptionCipher=function(e,t){return ad(e,t,!0)};kt.rc2.startDecrypting=function(e,t,n){var r=kt.rc2.createDecryptionCipher(e,128);return r.start(t,n),r};kt.rc2.createDecryptionCipher=function(e,t){return ad(e,t,!1)}});var Oi=le(function(D2,gd){var Qo=he();Te();gd.exports=Qo.jsbn=Qo.jsbn||{};var Ir,TS=244837814094590,ud=(TS&16777215)==15715070;function L(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)}Qo.jsbn.BigInteger=L;function Ae(){return new L(null)}function AS(e,t,n,r,i,o){while(--o>=0){var s=t*this.data[e++]+n.data[r]+i;i=Math.floor(s/67108864),n.data[r++]=s&67108863}return i}function kS(e,t,n,r,i,o){var s=t&32767,a=t>>15;while(--o>=0){var c=this.data[e]&32767,u=this.data[e++]>>15,l=a*c+u*s;c=s*c+((l&32767)<<15)+n.data[r]+(i&1073741823),i=(c>>>30)+(l>>>15)+a*u+(i>>>30),n.data[r++]=c&1073741823}return i}function ld(e,t,n,r,i,o){var s=t&16383,a=t>>14;while(--o>=0){var c=this.data[e]&16383,u=this.data[e++]>>14,l=a*c+u*s;c=s*c+((l&16383)<<14)+n.data[r]+i,i=(c>>28)+(l>>14)+a*u,n.data[r++]=c&268435455}return i}if(Qo.util.isNodejs)L.prototype.am=ld,Ir=28;else if(ud&&navigator.appName=="Microsoft Internet Explorer")L.prototype.am=kS,Ir=30;else if(ud&&navigator.appName!="Netscape")L.prototype.am=AS,Ir=26;else L.prototype.am=ld,Ir=28;L.prototype.DB=Ir;L.prototype.DM=(1<<Ir)-1;L.prototype.DV=1<<Ir;var hc=52;L.prototype.FV=Math.pow(2,hc);L.prototype.F1=hc-Ir;L.prototype.F2=2*Ir-hc;var IS="0123456789abcdefghijklmnopqrstuvwxyz",Yo=[],zn,Mt;zn=48;for(Mt=0;Mt<=9;++Mt)Yo[zn++]=Mt;zn=97;for(Mt=10;Mt<36;++Mt)Yo[zn++]=Mt;zn=65;for(Mt=10;Mt<36;++Mt)Yo[zn++]=Mt;function fd(e){return IS.charAt(e)}function dd(e,t){var n=Yo[e.charCodeAt(t)];return n==null?-1:n}function PS(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 RS(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 Hr(e){var t=Ae();return t.fromInt(e),t}function BS(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,o=0;while(--r>=0){var s=n==8?e[r]&255:dd(e,r);if(s<0){if(e.charAt(r)=="-")i=!0;continue}if(i=!1,o==0)this.data[this.t++]=s;else if(o+n>this.DB)this.data[this.t-1]|=(s&(1<<this.DB-o)-1)<<o,this.data[this.t++]=s>>this.DB-o;else this.data[this.t-1]|=s<<o;if(o+=n,o>=this.DB)o-=this.DB}if(n==8&&(e[0]&128)!=0){if(this.s=-1,o>0)this.data[this.t-1]|=(1<<this.DB-o)-1<<o}if(this.clamp(),i)L.ZERO.subTo(this,this)}function NS(){var e=this.s&this.DM;while(this.t>0&&this.data[this.t-1]==e)--this.t}function DS(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,o="",s=this.t,a=this.DB-s*this.DB%t;if(s-- >0){if(a<this.DB&&(r=this.data[s]>>a)>0)i=!0,o=fd(r);while(s>=0){if(a<t)r=(this.data[s]&(1<<a)-1)<<t-a,r|=this.data[--s]>>(a+=this.DB-t);else if(r=this.data[s]>>(a-=t)&n,a<=0)a+=this.DB,--s;if(r>0)i=!0;if(i)o+=fd(r)}}return i?o:"0"}function $S(){var e=Ae();return L.ZERO.subTo(this,e),e}function OS(){return this.s<0?this.negate():this}function LS(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 es(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 US(){if(this.t<=0)return 0;return this.DB*(this.t-1)+es(this.data[this.t-1]^this.s&this.DM)}function zS(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 FS(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 MS(e,t){var n=e%this.DB,r=this.DB-n,i=(1<<r)-1,o=Math.floor(e/this.DB),s=this.s<<n&this.DM,a;for(a=this.t-1;a>=0;--a)t.data[a+o+1]=this.data[a]>>r|s,s=(this.data[a]&i)<<n;for(a=o-1;a>=0;--a)t.data[a]=0;t.data[o]=s,t.t=this.t+o+1,t.s=this.s,t.clamp()}function VS(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,o=(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]&o)<<i,t.data[s-n]=this.data[s]>>r;if(r>0)t.data[this.t-n-1]|=(this.s&o)<<i;t.t=this.t-n,t.clamp()}function WS(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 HS(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)L.ZERO.subTo(t,t)}function KS(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 ZS(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=Ae();var o=Ae(),s=this.s,a=e.s,c=this.DB-es(r.data[r.t-1]);if(c>0)r.lShiftTo(c,o),i.lShiftTo(c,n);else r.copyTo(o),i.copyTo(n);var u=o.t,l=o.data[u-1];if(l==0)return;var f=l*(1<<this.F1)+(u>1?o.data[u-2]>>this.F2:0),p=this.FV/f,h=(1<<this.F1)/f,d=1<<this.F2,g=n.t,v=g-u,b=t==null?Ae():t;if(o.dlShiftTo(v,b),n.compareTo(b)>=0)n.data[n.t++]=1,n.subTo(b,n);L.ONE.dlShiftTo(u,b),b.subTo(o,o);while(o.t<u)o.data[o.t++]=0;while(--v>=0){var S=n.data[--g]==l?this.DM:Math.floor(n.data[g]*p+(n.data[g-1]+d)*h);if((n.data[g]+=o.am(0,S,n,v,0,u))<S){o.dlShiftTo(v,b),n.subTo(b,n);while(n.data[g]<--S)n.subTo(b,n)}}if(t!=null){if(n.drShiftTo(u,t),s!=a)L.ZERO.subTo(t,t)}if(n.t=u,n.clamp(),c>0)n.rShiftTo(c,n);if(s<0)L.ZERO.subTo(n,n)}function jS(e){var t=Ae();if(this.abs().divRemTo(e,null,t),this.s<0&&t.compareTo(L.ZERO)>0)e.subTo(t,t);return t}function dn(e){this.m=e}function GS(e){if(e.s<0||e.compareTo(this.m)>=0)return e.mod(this.m);else return e}function qS(e){return e}function XS(e){e.divRemTo(this.m,null,e)}function JS(e,t,n){e.multiplyTo(t,n),this.reduce(n)}function QS(e,t){e.squareTo(t),this.reduce(t)}dn.prototype.convert=GS;dn.prototype.revert=qS;dn.prototype.reduce=XS;dn.prototype.mulTo=JS;dn.prototype.sqrTo=QS;function YS(){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 pn(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 eC(e){var t=Ae();if(e.abs().dlShiftTo(this.m.t,t),t.divRemTo(this.m,null,t),e.s<0&&t.compareTo(L.ZERO)>0)this.m.subTo(t,t);return t}function tC(e){var t=Ae();return e.copyTo(t),this.reduce(t),t}function rC(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 nC(e,t){e.squareTo(t),this.reduce(t)}function iC(e,t,n){e.multiplyTo(t,n),this.reduce(n)}pn.prototype.convert=eC;pn.prototype.revert=tC;pn.prototype.reduce=rC;pn.prototype.mulTo=iC;pn.prototype.sqrTo=nC;function oC(){return(this.t>0?this.data[0]&1:this.s)==0}function sC(e,t){if(e>4294967295||e<1)return L.ONE;var n=Ae(),r=Ae(),i=t.convert(this),o=es(e)-1;i.copyTo(n);while(--o>=0)if(t.sqrTo(n,r),(e&1<<o)>0)t.mulTo(r,i,n);else{var s=n;n=r,r=s}return t.revert(n)}function aC(e,t){var n;if(e<256||t.isEven())n=new dn(t);else n=new pn(t);return this.exp(e,n)}L.prototype.copyTo=PS;L.prototype.fromInt=RS;L.prototype.fromString=BS;L.prototype.clamp=NS;L.prototype.dlShiftTo=zS;L.prototype.drShiftTo=FS;L.prototype.lShiftTo=MS;L.prototype.rShiftTo=VS;L.prototype.subTo=WS;L.prototype.multiplyTo=HS;L.prototype.squareTo=KS;L.prototype.divRemTo=ZS;L.prototype.invDigit=YS;L.prototype.isEven=oC;L.prototype.exp=sC;L.prototype.toString=DS;L.prototype.negate=$S;L.prototype.abs=OS;L.prototype.compareTo=LS;L.prototype.bitLength=US;L.prototype.mod=jS;L.prototype.modPowInt=aC;L.ZERO=Hr(0);L.ONE=Hr(1);function cC(){var e=Ae();return this.copyTo(e),e}function uC(){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 lC(){return this.t==0?this.s:this.data[0]<<24>>24}function fC(){return this.t==0?this.s:this.data[0]<<16>>16}function dC(e){return Math.floor(Math.LN2*this.DB/Math.log(e))}function pC(){if(this.s<0)return-1;else if(this.t<=0||this.t==1&&this.data[0]<=0)return 0;else return 1}function hC(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=Hr(n),i=Ae(),o=Ae(),s="";this.divRemTo(r,i,o);while(i.signum()>0)s=(n+o.intValue()).toString(e).substr(1)+s,i.divRemTo(r,i,o);return o.intValue().toString(e)+s}function mC(e,t){if(this.fromInt(0),t==null)t=10;var n=this.chunkSize(t),r=Math.pow(t,n),i=!1,o=0,s=0;for(var a=0;a<e.length;++a){var c=dd(e,a);if(c<0){if(e.charAt(a)=="-"&&this.signum()==0)i=!0;continue}if(s=t*s+c,++o>=n)this.dMultiply(r),this.dAddOffset(s,0),o=0,s=0}if(o>0)this.dMultiply(Math.pow(t,o)),this.dAddOffset(s,0);if(i)L.ZERO.subTo(this,this)}function gC(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(L.ONE.shiftLeft(e-1),mc,this);if(this.isEven())this.dAddOffset(1,0);while(!this.isProbablePrime(t))if(this.dAddOffset(2,0),this.bitLength()>e)this.subTo(L.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 yC(){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 vC(e){return this.compareTo(e)==0}function xC(e){return this.compareTo(e)<0?this:e}function bC(e){return this.compareTo(e)>0?this:e}function SC(e,t,n){var r,i,o=Math.min(e.t,this.t);for(r=0;r<o;++r)n.data[r]=t(this.data[r],e.data[r]);if(e.t<this.t){i=e.s&this.DM;for(r=o;r<this.t;++r)n.data[r]=t(this.data[r],i);n.t=this.t}else{i=this.s&this.DM;for(r=o;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 CC(e,t){return e&t}function wC(e){var t=Ae();return this.bitwiseTo(e,CC,t),t}function mc(e,t){return e|t}function EC(e){var t=Ae();return this.bitwiseTo(e,mc,t),t}function pd(e,t){return e^t}function _C(e){var t=Ae();return this.bitwiseTo(e,pd,t),t}function hd(e,t){return e&~t}function TC(e){var t=Ae();return this.bitwiseTo(e,hd,t),t}function AC(){var e=Ae();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 kC(e){var t=Ae();if(e<0)this.rShiftTo(-e,t);else this.lShiftTo(e,t);return t}function IC(e){var t=Ae();if(e<0)this.lShiftTo(-e,t);else this.rShiftTo(e,t);return t}function PC(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 RC(){for(var e=0;e<this.t;++e)if(this.data[e]!=0)return e*this.DB+PC(this.data[e]);if(this.s<0)return this.t*this.DB;return-1}function BC(e){var t=0;while(e!=0)e&=e-1,++t;return t}function NC(){var e=0,t=this.s&this.DM;for(var n=0;n<this.t;++n)e+=BC(this.data[n]^t);return e}function DC(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 $C(e,t){var n=L.ONE.shiftLeft(e);return this.bitwiseTo(n,t,n),n}function OC(e){return this.changeBit(e,mc)}function LC(e){return this.changeBit(e,hd)}function UC(e){return this.changeBit(e,pd)}function zC(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 FC(e){var t=Ae();return this.addTo(e,t),t}function MC(e){var t=Ae();return this.subTo(e,t),t}function VC(e){var t=Ae();return this.multiplyTo(e,t),t}function WC(){var e=Ae();return this.squareTo(e),e}function HC(e){var t=Ae();return this.divRemTo(e,t,null),t}function KC(e){var t=Ae();return this.divRemTo(e,null,t),t}function ZC(e){var t=Ae(),n=Ae();return this.divRemTo(e,t,n),[t,n]}function jC(e){this.data[this.t]=this.am(0,e-1,this,0,0,this.t),++this.t,this.clamp()}function GC(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 $i(){}function md(e){return e}function qC(e,t,n){e.multiplyTo(t,n)}function XC(e,t){e.squareTo(t)}$i.prototype.convert=md;$i.prototype.revert=md;$i.prototype.mulTo=qC;$i.prototype.sqrTo=XC;function JC(e){return this.exp(e,new $i)}function QC(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 YC(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 Fn(e){this.r2=Ae(),this.q3=Ae(),L.ONE.dlShiftTo(2*e.t,this.r2),this.mu=this.r2.divide(e),this.m=e}function ew(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=Ae();return e.copyTo(t),this.reduce(t),t}}function tw(e){return e}function rw(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 nw(e,t){e.squareTo(t),this.reduce(t)}function iw(e,t,n){e.multiplyTo(t,n),this.reduce(n)}Fn.prototype.convert=ew;Fn.prototype.revert=tw;Fn.prototype.reduce=rw;Fn.prototype.mulTo=iw;Fn.prototype.sqrTo=nw;function ow(e,t){var n=e.bitLength(),r,i=Hr(1),o;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)o=new dn(t);else if(t.isEven())o=new Fn(t);else o=new pn(t);var s=[],a=3,c=r-1,u=(1<<r)-1;if(s[1]=o.convert(this),r>1){var l=Ae();o.sqrTo(s[1],l);while(a<=u)s[a]=Ae(),o.mulTo(l,s[a-2],s[a]),a+=2}var f=e.t-1,p,h=!0,d=Ae(),g;n=es(e.data[f])-1;while(f>=0){if(n>=c)p=e.data[f]>>n-c&u;else if(p=(e.data[f]&(1<<n+1)-1)<<c-n,f>0)p|=e.data[f-1]>>this.DB+n-c;a=r;while((p&1)==0)p>>=1,--a;if((n-=a)<0)n+=this.DB,--f;if(h)s[p].copyTo(i),h=!1;else{while(a>1)o.sqrTo(i,d),o.sqrTo(d,i),a-=2;if(a>0)o.sqrTo(i,d);else g=i,i=d,d=g;o.mulTo(d,s[p],i)}while(f>=0&&(e.data[f]&1<<n)==0)if(o.sqrTo(i,d),g=i,i=d,d=g,--n<0)n=this.DB-1,--f}return o.revert(i)}function sw(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(),o=n.getLowestSetBit();if(o<0)return t;if(i<o)o=i;if(o>0)t.rShiftTo(o,t),n.rShiftTo(o,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(o>0)n.lShiftTo(o,n);return n}function aw(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 cw(e){if(this.signum()<=0||e.signum()<=0)return L.ZERO;var t=e.isEven();if(this.isEven()&&t||e.signum()==0)return L.ZERO;var n=e.clone(),r=this.clone(),i=Hr(1),o=Hr(0),s=Hr(0),a=Hr(1);while(n.signum()!=0){while(n.isEven()){if(n.rShiftTo(1,n),t){if(!i.isEven()||!o.isEven())i.addTo(this,i),o.subTo(e,o);i.rShiftTo(1,i)}else if(!o.isEven())o.subTo(e,o);o.rShiftTo(1,o)}while(r.isEven()){if(r.rShiftTo(1,r),t){if(!s.isEven()||!a.isEven())s.addTo(this,s),a.subTo(e,a);s.rShiftTo(1,s)}else if(!a.isEven())a.subTo(e,a);a.rShiftTo(1,a)}if(n.compareTo(r)>=0){if(n.subTo(r,n),t)i.subTo(s,i);o.subTo(a,o)}else{if(r.subTo(n,r),t)s.subTo(i,s);a.subTo(o,a)}}if(r.compareTo(L.ONE)!=0)return L.ZERO;if(a.compareTo(e)>=0)return a.subtract(e);if(a.signum()<0)a.addTo(e,a);else return a;if(a.signum()<0)return a.add(e);else return a}var Yt=[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],uw=67108864/Yt[Yt.length-1];function lw(e){var t,n=this.abs();if(n.t==1&&n.data[0]<=Yt[Yt.length-1]){for(t=0;t<Yt.length;++t)if(n.data[0]==Yt[t])return!0;return!1}if(n.isEven())return!1;t=1;while(t<Yt.length){var r=Yt[t],i=t+1;while(i<Yt.length&&r<uw)r*=Yt[i++];r=n.modInt(r);while(t<i)if(r%Yt[t++]==0)return!1}return n.millerRabin(e)}function fw(e){var t=this.subtract(L.ONE),n=t.getLowestSetBit();if(n<=0)return!1;var r=t.shiftRight(n),i=dw(),o;for(var s=0;s<e;++s){do o=new L(this.bitLength(),i);while(o.compareTo(L.ONE)<=0||o.compareTo(t)>=0);var a=o.modPow(r,this);if(a.compareTo(L.ONE)!=0&&a.compareTo(t)!=0){var c=1;while(c++<n&&a.compareTo(t)!=0)if(a=a.modPowInt(2,this),a.compareTo(L.ONE)==0)return!1;if(a.compareTo(t)!=0)return!1}}return!0}function dw(){return{nextBytes:function(e){for(var t=0;t<e.length;++t)e[t]=Math.floor(Math.random()*256)}}}L.prototype.chunkSize=dC;L.prototype.toRadix=hC;L.prototype.fromRadix=mC;L.prototype.fromNumber=gC;L.prototype.bitwiseTo=SC;L.prototype.changeBit=$C;L.prototype.addTo=zC;L.prototype.dMultiply=jC;L.prototype.dAddOffset=GC;L.prototype.multiplyLowerTo=QC;L.prototype.multiplyUpperTo=YC;L.prototype.modInt=aw;L.prototype.millerRabin=fw;L.prototype.clone=cC;L.prototype.intValue=uC;L.prototype.byteValue=lC;L.prototype.shortValue=fC;L.prototype.signum=pC;L.prototype.toByteArray=yC;L.prototype.equals=vC;L.prototype.min=xC;L.prototype.max=bC;L.prototype.and=wC;L.prototype.or=EC;L.prototype.xor=_C;L.prototype.andNot=TC;L.prototype.not=AC;L.prototype.shiftLeft=kC;L.prototype.shiftRight=IC;L.prototype.getLowestSetBit=RC;L.prototype.bitCount=NC;L.prototype.testBit=DC;L.prototype.setBit=OC;L.prototype.clearBit=LC;L.prototype.flipBit=UC;L.prototype.add=FC;L.prototype.subtract=MC;L.prototype.multiply=VC;L.prototype.divide=HC;L.prototype.remainder=KC;L.prototype.divideAndRemainder=ZC;L.prototype.modPow=ow;L.prototype.modInverse=cw;L.prototype.pow=JC;L.prototype.gcd=sw;L.prototype.isProbablePrime=lw;L.prototype.square=WC});var Mn=le(function($2,bd){var hr=he();ur();Te();var vd=bd.exports=hr.sha1=hr.sha1||{};hr.md.sha1=hr.md.algorithms.sha1=vd;vd.create=function(){if(!xd)pw();var e=null,t=hr.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 o=0;o<i;++o)r.fullMessageLength.push(0);return t=hr.util.createBuffer(),e={h0:1732584193,h1:4023233417,h2:2562383102,h3:271733878,h4:3285377520},r},r.start(),r.update=function(i,o){if(o==="utf8")i=hr.util.encodeUtf8(i);var s=i.length;r.messageLength+=s,s=[s/4294967296>>>0,s>>>0];for(var a=r.fullMessageLength.length-1;a>=0;--a)r.fullMessageLength[a]+=s[1],s[1]=s[0]+(r.fullMessageLength[a]/4294967296>>>0),r.fullMessageLength[a]=r.fullMessageLength[a]>>>0,s[0]=s[1]/4294967296>>>0;if(t.putBytes(i),yd(e,n,t),t.read>2048||t.length()===0)t.compact();return r},r.digest=function(){var i=hr.util.createBuffer();i.putBytes(t.bytes());var o=r.fullMessageLength[r.fullMessageLength.length-1]+r.messageLengthSize,s=o&r.blockLength-1;i.putBytes(gc.substr(0,r.blockLength-s));var a,c,u=r.fullMessageLength[0]*8;for(var l=0;l<r.fullMessageLength.length-1;++l)a=r.fullMessageLength[l+1]*8,c=a/4294967296>>>0,u+=c,i.putInt32(u>>>0),u=a>>>0;i.putInt32(u);var f={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3,h4:e.h4};yd(f,n,i);var p=hr.util.createBuffer();return p.putInt32(f.h0),p.putInt32(f.h1),p.putInt32(f.h2),p.putInt32(f.h3),p.putInt32(f.h4),p},r};var gc=null,xd=!1;function pw(){gc=String.fromCharCode(128),gc+=hr.util.fillString(String.fromCharCode(0),64),xd=!0}function yd(e,t,n){var r,i,o,s,a,c,u,l,f=n.length();while(f>=64){i=e.h0,o=e.h1,s=e.h2,a=e.h3,c=e.h4;for(l=0;l<16;++l)r=n.getInt32(),t[l]=r,u=a^o&(s^a),r=(i<<5|i>>>27)+u+c+1518500249+r,c=a,a=s,s=(o<<30|o>>>2)>>>0,o=i,i=r;for(;l<20;++l)r=t[l-3]^t[l-8]^t[l-14]^t[l-16],r=r<<1|r>>>31,t[l]=r,u=a^o&(s^a),r=(i<<5|i>>>27)+u+c+1518500249+r,c=a,a=s,s=(o<<30|o>>>2)>>>0,o=i,i=r;for(;l<32;++l)r=t[l-3]^t[l-8]^t[l-14]^t[l-16],r=r<<1|r>>>31,t[l]=r,u=o^s^a,r=(i<<5|i>>>27)+u+c+1859775393+r,c=a,a=s,s=(o<<30|o>>>2)>>>0,o=i,i=r;for(;l<40;++l)r=t[l-6]^t[l-16]^t[l-28]^t[l-32],r=r<<2|r>>>30,t[l]=r,u=o^s^a,r=(i<<5|i>>>27)+u+c+1859775393+r,c=a,a=s,s=(o<<30|o>>>2)>>>0,o=i,i=r;for(;l<60;++l)r=t[l-6]^t[l-16]^t[l-28]^t[l-32],r=r<<2|r>>>30,t[l]=r,u=o&s|a&(o^s),r=(i<<5|i>>>27)+u+c+2400959708+r,c=a,a=s,s=(o<<30|o>>>2)>>>0,o=i,i=r;for(;l<80;++l)r=t[l-6]^t[l-16]^t[l-28]^t[l-32],r=r<<2|r>>>30,t[l]=r,u=o^s^a,r=(i<<5|i>>>27)+u+c+3395469782+r,c=a,a=s,s=(o<<30|o>>>2)>>>0,o=i,i=r;e.h0=e.h0+i|0,e.h1=e.h1+o|0,e.h2=e.h2+s|0,e.h3=e.h3+a|0,e.h4=e.h4+c|0,f-=64}}});var yc=le(function(O2,Cd){var mr=he();Te();Ft();Mn();var Sd=Cd.exports=mr.pkcs1=mr.pkcs1||{};Sd.encode_rsa_oaep=function(e,t,n){var r,i,o,s;if(typeof n==="string")r=n,i=arguments[3]||void 0,o=arguments[4]||void 0;else if(n){if(r=n.label||void 0,i=n.seed||void 0,o=n.md||void 0,n.mgf1&&n.mgf1.md)s=n.mgf1.md}if(!o)o=mr.md.sha1.create();else o.start();if(!s)s=o;var a=Math.ceil(e.n.bitLength()/8),c=a-2*o.digestLength-2;if(t.length>c){var u=Error("RSAES-OAEP input message length is too long.");throw u.length=t.length,u.maxLength=c,u}if(!r)r="";o.update(r,"raw");var l=o.digest(),f="",p=c-t.length;for(var h=0;h<p;h++)f+="\x00";var d=l.getBytes()+f+"\x01"+t;if(!i)i=mr.random.getBytes(o.digestLength);else if(i.length!==o.digestLength){var u=Error("Invalid RSAES-OAEP seed. The seed length must match the digest length.");throw u.seedLength=i.length,u.digestLength=o.digestLength,u}var g=ts(i,a-o.digestLength-1,s),v=mr.util.xorBytes(d,g,d.length),b=ts(v,o.digestLength,s),S=mr.util.xorBytes(i,b,i.length);return"\x00"+S+v};Sd.decode_rsa_oaep=function(e,t,n){var r,i,o;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)o=n.mgf1.md}var s=Math.ceil(e.n.bitLength()/8);if(t.length!==s){var v=Error("RSAES-OAEP encoded message length is invalid.");throw v.length=t.length,v.expectedLength=s,v}if(i===void 0)i=mr.md.sha1.create();else i.start();if(!o)o=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 a=i.digest().getBytes(),c=t.charAt(0),u=t.substring(1,i.digestLength+1),l=t.substring(1+i.digestLength),f=ts(l,i.digestLength,o),p=mr.util.xorBytes(u,f,u.length),h=ts(p,s-i.digestLength-1,o),d=mr.util.xorBytes(l,h,l.length),g=d.substring(0,i.digestLength),v=c!=="\x00";for(var b=0;b<i.digestLength;++b)v|=a.charAt(b)!==g.charAt(b);var S=1,C=i.digestLength;for(var T=i.digestLength;T<d.length;T++){var I=d.charCodeAt(T),k=I&1^1,R=S?65534:0;v|=I&R,S=S&k,C+=S}if(v||d.charCodeAt(C)!==1)throw Error("Invalid RSAES-OAEP padding.");return d.substring(C+1)};function ts(e,t,n){if(!n)n=mr.md.sha1.create();var r="",i=Math.ceil(t/n.digestLength);for(var o=0;o<i;++o){var s=String.fromCharCode(o>>24&255,o>>16&255,o>>8&255,o&255);n.start(),n.update(e+s),r+=n.digest().getBytes()}return r.substring(0,t)}});var xc=le(function(L2,vc){var Kr=he();Te();Oi();Ft();(function(){if(Kr.prime){vc.exports=Kr.prime;return}var e=vc.exports=Kr.prime=Kr.prime||{},t=Kr.jsbn.BigInteger,n=[6,4,2,4,2,4,6,2],r=new t(null);r.fromInt(30);var i=function(f,p){return f|p};e.generateProbablePrime=function(f,p,h){if(typeof p==="function")h=p,p={};p=p||{};var d=p.algorithm||"PRIMEINC";if(typeof d==="string")d={name:d};d.options=d.options||{};var g=p.prng||Kr.random,v={nextBytes:function(b){var S=g.getBytesSync(b.length);for(var C=0;C<b.length;++C)b[C]=S.charCodeAt(C)}};if(d.name==="PRIMEINC")return o(f,v,d.options,h);throw Error("Invalid prime generation algorithm: "+d.name)};function o(f,p,h,d){if("workers"in h)return c(f,p,h,d);return s(f,p,h,d)}function s(f,p,h,d){var g=u(f,p),v=0,b=l(g.bitLength());if("millerRabinTests"in h)b=h.millerRabinTests;var S=10;if("maxBlockTime"in h)S=h.maxBlockTime;a(g,f,p,v,b,S,d)}function a(f,p,h,d,g,v,b){var S=+new Date;do{if(f.bitLength()>p)f=u(p,h);if(f.isProbablePrime(g))return b(null,f);f.dAddOffset(n[d++%8],0)}while(v<0||+new Date-S<v);Kr.util.setImmediate(function(){a(f,p,h,d,g,v,b)})}function c(f,p,h,d){if(typeof Worker>"u")return s(f,p,h,d);var g=u(f,p),v=h.workers,b=h.workLoad||100,S=b*30/8,C=h.workerScript||"forge/prime.worker.js";if(v===-1)return Kr.util.estimateCores(function(I,k){if(I)k=2;v=k-1,T()});T();function T(){v=Math.max(1,v);var I=[];for(var k=0;k<v;++k)I[k]=new Worker(C);var R=v;for(var k=0;k<v;++k)I[k].addEventListener("message",D);var V=!1;function D(F){if(V)return;--R;var H=F.data;if(H.found){for(var re=0;re<I.length;++re)I[re].terminate();return V=!0,d(null,new t(H.prime,16))}if(g.bitLength()>f)g=u(f,p);var se=g.toString(16);F.target.postMessage({hex:se,workLoad:b}),g.dAddOffset(S,0)}}}function u(f,p){var h=new t(f,p),d=f-1;if(!h.testBit(d))h.bitwiseTo(t.ONE.shiftLeft(d),i,h);return h.dAddOffset(31-h.mod(r).byteValue(),0),h}function l(f){if(f<=100)return 27;if(f<=150)return 18;if(f<=200)return 15;if(f<=250)return 12;if(f<=300)return 9;if(f<=350)return 8;if(f<=400)return 7;if(f<=500)return 6;if(f<=600)return 5;if(f<=800)return 4;if(f<=1250)return 3;return 2}})()});var Li=le(function(U2,Pd){var ne=he();Qt();Oi();Wr();yc();xc();Ft();Te();if(typeof we>"u")we=ne.jsbn.BigInteger;var we,bc=ne.util.isNodejs?Ei("crypto"):null,{asn1:P,util:Vt}=ne;ne.pki=ne.pki||{};Pd.exports=ne.pki.rsa=ne.rsa=ne.rsa||{};var fe=ne.pki,hw=[6,4,2,4,2,4,6,2],mw={name:"PrivateKeyInfo",tagClass:P.Class.UNIVERSAL,type:P.Type.SEQUENCE,constructed:!0,value:[{name:"PrivateKeyInfo.version",tagClass:P.Class.UNIVERSAL,type:P.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:P.Class.UNIVERSAL,type:P.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:P.Class.UNIVERSAL,type:P.Type.OID,constructed:!1,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:P.Class.UNIVERSAL,type:P.Type.OCTETSTRING,constructed:!1,capture:"privateKey"}]},gw={name:"RSAPrivateKey",tagClass:P.Class.UNIVERSAL,type:P.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPrivateKey.version",tagClass:P.Class.UNIVERSAL,type:P.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"RSAPrivateKey.modulus",tagClass:P.Class.UNIVERSAL,type:P.Type.INTEGER,constructed:!1,capture:"privateKeyModulus"},{name:"RSAPrivateKey.publicExponent",tagClass:P.Class.UNIVERSAL,type:P.Type.INTEGER,constructed:!1,capture:"privateKeyPublicExponent"},{name:"RSAPrivateKey.privateExponent",tagClass:P.Class.UNIVERSAL,type:P.Type.INTEGER,constructed:!1,capture:"privateKeyPrivateExponent"},{name:"RSAPrivateKey.prime1",tagClass:P.Class.UNIVERSAL,type:P.Type.INTEGER,constructed:!1,capture:"privateKeyPrime1"},{name:"RSAPrivateKey.prime2",tagClass:P.Class.UNIVERSAL,type:P.Type.INTEGER,constructed:!1,capture:"privateKeyPrime2"},{name:"RSAPrivateKey.exponent1",tagClass:P.Class.UNIVERSAL,type:P.Type.INTEGER,constructed:!1,capture:"privateKeyExponent1"},{name:"RSAPrivateKey.exponent2",tagClass:P.Class.UNIVERSAL,type:P.Type.INTEGER,constructed:!1,capture:"privateKeyExponent2"},{name:"RSAPrivateKey.coefficient",tagClass:P.Class.UNIVERSAL,type:P.Type.INTEGER,constructed:!1,capture:"privateKeyCoefficient"}]},yw={name:"RSAPublicKey",tagClass:P.Class.UNIVERSAL,type:P.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPublicKey.modulus",tagClass:P.Class.UNIVERSAL,type:P.Type.INTEGER,constructed:!1,capture:"publicKeyModulus"},{name:"RSAPublicKey.exponent",tagClass:P.Class.UNIVERSAL,type:P.Type.INTEGER,constructed:!1,capture:"publicKeyExponent"}]},vw=ne.pki.rsa.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:P.Class.UNIVERSAL,type:P.Type.SEQUENCE,constructed:!0,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:P.Class.UNIVERSAL,type:P.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:P.Class.UNIVERSAL,type:P.Type.OID,constructed:!1,capture:"publicKeyOid"}]},{name:"SubjectPublicKeyInfo.subjectPublicKey",tagClass:P.Class.UNIVERSAL,type:P.Type.BITSTRING,constructed:!1,value:[{name:"SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey",tagClass:P.Class.UNIVERSAL,type:P.Type.SEQUENCE,constructed:!0,optional:!0,captureAsn1:"rsaPublicKey"}]}]},xw={name:"DigestInfo",tagClass:P.Class.UNIVERSAL,type:P.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm",tagClass:P.Class.UNIVERSAL,type:P.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm.algorithmIdentifier",tagClass:P.Class.UNIVERSAL,type:P.Type.OID,constructed:!1,capture:"algorithmIdentifier"},{name:"DigestInfo.DigestAlgorithm.parameters",tagClass:P.Class.UNIVERSAL,type:P.Type.NULL,capture:"parameters",optional:!0,constructed:!1}]},{name:"DigestInfo.digest",tagClass:P.Class.UNIVERSAL,type:P.Type.OCTETSTRING,constructed:!1,capture:"digest"}]},wd=function(e,t,n){var r=[P.create(P.Class.UNIVERSAL,P.Type.OID,!1,P.oidToDer(e).getBytes())];if(n)r.push(P.create(P.Class.UNIVERSAL,P.Type.NULL,!1,""));return P.toDer(P.create(P.Class.UNIVERSAL,P.Type.SEQUENCE,!0,[P.create(P.Class.UNIVERSAL,P.Type.SEQUENCE,!0,r),P.create(P.Class.UNIVERSAL,P.Type.OCTETSTRING,!1,t)])).getBytes()},bw=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=P.oidToDer(t).getBytes(),i=P.create(P.Class.UNIVERSAL,P.Type.SEQUENCE,!0,[]),o=P.create(P.Class.UNIVERSAL,P.Type.SEQUENCE,!0,[]);o.value.push(P.create(P.Class.UNIVERSAL,P.Type.OID,!1,r)),o.value.push(P.create(P.Class.UNIVERSAL,P.Type.NULL,!1,""));var s=P.create(P.Class.UNIVERSAL,P.Type.OCTETSTRING,!1,e.digest().getBytes());return i.value.push(o),i.value.push(s),P.toDer(i).getBytes()},kd=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(we.ONE));if(!t.dQ)t.dQ=t.d.mod(t.q.subtract(we.ONE));if(!t.qInv)t.qInv=t.q.modInverse(t.p);var r;do r=new we(ne.util.bytesToHex(ne.random.getBytes(t.n.bitLength()/8)),16);while(r.compareTo(t.n)>=0||!r.gcd(t.n).equals(we.ONE));e=e.multiply(r.modPow(t.e,t.n)).mod(t.n);var i=e.mod(t.p).modPow(t.dP,t.p),o=e.mod(t.q).modPow(t.dQ,t.q);while(i.compareTo(o)<0)i=i.add(t.p);var s=i.subtract(o).multiply(t.qInv).mod(t.p).multiply(t.q).add(o);return s=s.multiply(r.modInverse(t.n)).mod(t.n),s};fe.rsa.encrypt=function(e,t,n){var r=n,i,o=Math.ceil(t.n.bitLength()/8);if(n!==!1&&n!==!0)r=n===2,i=Id(e,t,n);else i=ne.util.createBuffer(),i.putBytes(e);var s=new we(i.toHex(),16),a=kd(s,t,r),c=a.toString(16),u=ne.util.createBuffer(),l=o-Math.ceil(c.length/2);while(l>0)u.putByte(0),--l;return u.putBytes(ne.util.hexToBytes(c)),u.getBytes()};fe.rsa.decrypt=function(e,t,n,r){var i=Math.ceil(t.n.bitLength()/8);if(e.length!==i){var o=Error("Encrypted message length is invalid.");throw o.length=e.length,o.expected=i,o}var s=new we(ne.util.createBuffer(e).toHex(),16);if(s.compareTo(t.n)>=0)throw Error("Encrypted message is invalid.");var a=kd(s,t,n),c=a.toString(16),u=ne.util.createBuffer(),l=i-Math.ceil(c.length/2);while(l>0)u.putByte(0),--l;if(u.putBytes(ne.util.hexToBytes(c)),r!==!1)return rs(u.getBytes(),t,n);return u.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||ne.random,i={nextBytes:function(a){var c=r.getBytesSync(a.length);for(var u=0;u<a.length;++u)a[u]=c.charCodeAt(u)}},o=n.algorithm||"PRIMEINC",s;if(o==="PRIMEINC")s={algorithm:o,state:0,bits:e,rng:i,eInt:t||65537,e:new we(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: "+o);return s};fe.rsa.stepKeyPairGenerationState=function(e,t){if(!("algorithm"in e))e.algorithm="PRIMEINC";var n=new we(null);n.fromInt(30);var r=0,i=function(f,p){return f|p},o=+new Date,s,a=0;while(e.keys===null&&(t<=0||a<t)){if(e.state===0){var c=e.p===null?e.pBits:e.qBits,u=c-1;if(e.pqState===0){if(e.num=new we(c,e.rng),!e.num.testBit(u))e.num.bitwiseTo(we.ONE.shiftLeft(u),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()>c)e.pqState=0;else if(e.num.isProbablePrime(Cw(e.num.bitLength())))++e.pqState;else e.num.dAddOffset(hw[r++%8],0);else if(e.pqState===2)e.pqState=e.num.subtract(we.ONE).gcd(e.e).compareTo(we.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(we.ONE),e.q1=e.q.subtract(we.ONE),e.phi=e.p1.multiply(e.q1),++e.state;else if(e.state===3)if(e.phi.gcd(e.e).compareTo(we.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 l=e.e.modInverse(e.phi);e.keys={privateKey:fe.rsa.setPrivateKey(e.n,e.e,l,e.p,e.q,l.mod(e.p1),l.mod(e.q1),e.q.modInverse(e.p)),publicKey:fe.rsa.setPublicKey(e.n,e.e)}}s=+new Date,a+=s-o,o=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(!ne.options.usePureJavaScript&&!n.prng&&e>=256&&e<=16384&&(t===65537||t===3)){if(r){if(Ed("generateKeyPair"))return bc.generateKeyPair("rsa",{modulusLength:e,publicExponent:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}},function(a,c,u){if(a)return r(a);r(null,{privateKey:fe.privateKeyFromPem(u),publicKey:fe.publicKeyFromPem(c)})});if(_d("generateKey")&&_d("exportKey"))return Vt.globalScope.crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:Ad(t),hash:{name:"SHA-256"}},!0,["sign","verify"]).then(function(a){return Vt.globalScope.crypto.subtle.exportKey("pkcs8",a.privateKey)}).then(void 0,function(a){r(a)}).then(function(a){if(a){var c=fe.privateKeyFromAsn1(P.fromDer(ne.util.createBuffer(a)));r(null,{privateKey:c,publicKey:fe.setRsaPublicKey(c.n,c.e)})}});if(Td("generateKey")&&Td("exportKey")){var i=Vt.globalScope.msCrypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:Ad(t),hash:{name:"SHA-256"}},!0,["sign","verify"]);i.oncomplete=function(a){var c=a.target.result,u=Vt.globalScope.msCrypto.subtle.exportKey("pkcs8",c.privateKey);u.oncomplete=function(l){var f=l.target.result,p=fe.privateKeyFromAsn1(P.fromDer(ne.util.createBuffer(f)));r(null,{privateKey:p,publicKey:fe.setRsaPublicKey(p.n,p.e)})},u.onerror=function(l){r(l)}},i.onerror=function(a){r(a)};return}}else if(Ed("generateKeyPairSync")){var o=bc.generateKeyPairSync("rsa",{modulusLength:e,publicExponent:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{privateKey:fe.privateKeyFromPem(o.privateKey),publicKey:fe.publicKeyFromPem(o.publicKey)}}}var s=fe.rsa.createKeyPairGenerationState(e,t,n);if(!r)return fe.rsa.stepKeyPairGenerationState(s,0),s.keys;Sw(s,n,r)};fe.setRsaPublicKey=fe.rsa.setPublicKey=function(e,t){var n={n:e,e:t};return n.encrypt=function(r,i,o){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(a,c,u){return Id(a,c,2).getBytes()}};else if(i==="RSA-OAEP"||i==="RSAES-OAEP")i={encode:function(a,c){return ne.pkcs1.encode_rsa_oaep(c,a,o)}};else if(["RAW","NONE","NULL",null].indexOf(i)!==-1)i={encode:function(a){return a}};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,o,s){if(typeof o==="string")o=o.toUpperCase();else if(o===void 0)o="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(o==="RSASSA-PKCS1-V1_5")o={verify:function(c,u){u=rs(u,n,!0,void 0,s);var l=P.fromDer(u,{parseAllBytes:s._parseAllDigestBytes}),f={},p=[];if(!P.validate(l,xw,f,p)||l.value.length!==2){var h=Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value.");throw h.errors=p,h}var d=P.derToOid(f.algorithmIdentifier);if(!(d===ne.oids.md2||d===ne.oids.md5||d===ne.oids.sha1||d===ne.oids.sha224||d===ne.oids.sha256||d===ne.oids.sha384||d===ne.oids.sha512||d===ne.oids["sha512-224"]||d===ne.oids["sha512-256"])){var h=Error("Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.");throw h.oid=d,h}if(d===ne.oids.md2||d===ne.oids.md5){if(!("parameters"in f))throw Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value. Missing algorithm identifier NULL parameters.")}var g=wd(d,f.digest,!0),v=wd(d,f.digest,!1);if(u.substring(0,g.length)!==g&&u.substring(0,v.length)!==v)throw Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value.");return c===f.digest}};else if(o==="NONE"||o==="NULL"||o===null)o={verify:function(c,u){return u=rs(u,n,!0,void 0,s),c===u}};var a=fe.rsa.decrypt(i,n,!0,!1);return o.verify(r,a,n.n.bitLength())},n};fe.setRsaPrivateKey=fe.rsa.setPrivateKey=function(e,t,n,r,i,o,s,a){var c={n:e,e:t,d:n,p:r,q:i,dP:o,dQ:s,qInv:a};return c.decrypt=function(u,l,f){if(typeof l==="string")l=l.toUpperCase();else if(l===void 0)l="RSAES-PKCS1-V1_5";var p=fe.rsa.decrypt(u,c,!1,!1);if(l==="RSAES-PKCS1-V1_5")l={decode:rs};else if(l==="RSA-OAEP"||l==="RSAES-OAEP")l={decode:function(h,d){return ne.pkcs1.decode_rsa_oaep(d,h,f)}};else if(["RAW","NONE","NULL",null].indexOf(l)!==-1)l={decode:function(h){return h}};else throw Error('Unsupported encryption scheme: "'+l+'".');return l.decode(p,c,!1)},c.sign=function(u,l){var f=!1;if(typeof l==="string")l=l.toUpperCase();if(l===void 0||l==="RSASSA-PKCS1-V1_5")l={encode:bw},f=1;else if(l==="NONE"||l==="NULL"||l===null)l={encode:function(){return u}},f=1;var p=l.encode(u,c.n.bitLength());return fe.rsa.encrypt(p,c,f)},c};fe.wrapRsaPrivateKey=function(e){return P.create(P.Class.UNIVERSAL,P.Type.SEQUENCE,!0,[P.create(P.Class.UNIVERSAL,P.Type.INTEGER,!1,P.integerToDer(0).getBytes()),P.create(P.Class.UNIVERSAL,P.Type.SEQUENCE,!0,[P.create(P.Class.UNIVERSAL,P.Type.OID,!1,P.oidToDer(fe.oids.rsaEncryption).getBytes()),P.create(P.Class.UNIVERSAL,P.Type.NULL,!1,"")]),P.create(P.Class.UNIVERSAL,P.Type.OCTETSTRING,!1,P.toDer(e).getBytes())])};fe.privateKeyFromAsn1=function(e){var t={},n=[];if(P.validate(e,mw,t,n))e=P.fromDer(ne.util.createBuffer(t.privateKey));if(t={},n=[],!P.validate(e,gw,t,n)){var r=Error("Cannot read private key. ASN.1 object does not contain an RSAPrivateKey.");throw r.errors=n,r}if(t.privateKeyVersion!=="\x00"||e.value.length!==9)throw Error("Cannot read private key. Only two-prime RSAPrivateKey version 0 is supported.");var i,o,s,a,c,u,l,f;return i=ne.util.createBuffer(t.privateKeyModulus).toHex(),o=ne.util.createBuffer(t.privateKeyPublicExponent).toHex(),s=ne.util.createBuffer(t.privateKeyPrivateExponent).toHex(),a=ne.util.createBuffer(t.privateKeyPrime1).toHex(),c=ne.util.createBuffer(t.privateKeyPrime2).toHex(),u=ne.util.createBuffer(t.privateKeyExponent1).toHex(),l=ne.util.createBuffer(t.privateKeyExponent2).toHex(),f=ne.util.createBuffer(t.privateKeyCoefficient).toHex(),fe.setRsaPrivateKey(new we(i,16),new we(o,16),new we(s,16),new we(a,16),new we(c,16),new we(u,16),new we(l,16),new we(f,16))};fe.privateKeyToAsn1=fe.privateKeyToRSAPrivateKey=function(e){return P.create(P.Class.UNIVERSAL,P.Type.SEQUENCE,!0,[P.create(P.Class.UNIVERSAL,P.Type.INTEGER,!1,P.integerToDer(0).getBytes()),P.create(P.Class.UNIVERSAL,P.Type.INTEGER,!1,gr(e.n)),P.create(P.Class.UNIVERSAL,P.Type.INTEGER,!1,gr(e.e)),P.create(P.Class.UNIVERSAL,P.Type.INTEGER,!1,gr(e.d)),P.create(P.Class.UNIVERSAL,P.Type.INTEGER,!1,gr(e.p)),P.create(P.Class.UNIVERSAL,P.Type.INTEGER,!1,gr(e.q)),P.create(P.Class.UNIVERSAL,P.Type.INTEGER,!1,gr(e.dP)),P.create(P.Class.UNIVERSAL,P.Type.INTEGER,!1,gr(e.dQ)),P.create(P.Class.UNIVERSAL,P.Type.INTEGER,!1,gr(e.qInv))])};fe.publicKeyFromAsn1=function(e){var t={},n=[];if(P.validate(e,vw,t,n)){var r=P.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=[],!P.validate(e,yw,t,n)){var i=Error("Cannot read public key. ASN.1 object does not contain an RSAPublicKey.");throw i.errors=n,i}var o=ne.util.createBuffer(t.publicKeyModulus).toHex(),s=ne.util.createBuffer(t.publicKeyExponent).toHex();return fe.setRsaPublicKey(new we(o,16),new we(s,16))};fe.publicKeyToAsn1=fe.publicKeyToSubjectPublicKeyInfo=function(e){return P.create(P.Class.UNIVERSAL,P.Type.SEQUENCE,!0,[P.create(P.Class.UNIVERSAL,P.Type.SEQUENCE,!0,[P.create(P.Class.UNIVERSAL,P.Type.OID,!1,P.oidToDer(fe.oids.rsaEncryption).getBytes()),P.create(P.Class.UNIVERSAL,P.Type.NULL,!1,"")]),P.create(P.Class.UNIVERSAL,P.Type.BITSTRING,!1,[fe.publicKeyToRSAPublicKey(e)])])};fe.publicKeyToRSAPublicKey=function(e){return P.create(P.Class.UNIVERSAL,P.Type.SEQUENCE,!0,[P.create(P.Class.UNIVERSAL,P.Type.INTEGER,!1,gr(e.n)),P.create(P.Class.UNIVERSAL,P.Type.INTEGER,!1,gr(e.e))])};function Id(e,t,n){var r=ne.util.createBuffer(),i=Math.ceil(t.n.bitLength()/8);if(e.length>i-11){var o=Error("Message is too long for PKCS#1 v1.5 padding.");throw o.length=e.length,o.max=i-11,o}r.putByte(0),r.putByte(n);var s=i-3-e.length,a;if(n===0||n===1){a=n===0?0:255;for(var c=0;c<s;++c)r.putByte(a)}else while(s>0){var u=0,l=ne.random.getBytes(s);for(var c=0;c<s;++c)if(a=l.charCodeAt(c),a===0)++u;else r.putByte(a);s=u}return r.putByte(0),r.putBytes(e),r}function rs(e,t,n,r,i){var o=Math.ceil(t.n.bitLength()/8),s=ne.util.createBuffer(e),a=s.getByte(),c=s.getByte();if(a!==0||n&&c!==0&&c!==1||!n&&c!==2||n&&c===0&&typeof r>"u")throw Error("Encryption block is invalid.");var u=0;if(c===0){u=o-3-r;for(var l=0;l<u;++l)if(s.getByte()!==0)throw Error("Encryption block is invalid.")}else if(c===1){u=0;while(s.length()>1){if(s.getByte()!==255){--s.read;break}++u}if(u<8&&!(i?i._skipPaddingChecks:!1))throw Error("Encryption block is invalid.")}else if(c===2){u=0;while(s.length()>1){if(s.getByte()===0){--s.read;break}++u}if(u<8&&!(i?i._skipPaddingChecks:!1))throw Error("Encryption block is invalid.")}var f=s.getByte();if(f!==0||u!==o-3-s.length())throw Error("Encryption block is invalid.");return s.getBytes()}function Sw(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(){o(e.pBits,function(a,c){if(a)return n(a);if(e.p=c,e.q!==null)return s(a,e.q);o(e.qBits,s)})}function o(a,c){ne.prime.generateProbablePrime(a,r,c)}function s(a,c){if(a)return n(a);if(e.q=c,e.p.compareTo(e.q)<0){var u=e.p;e.p=e.q,e.q=u}if(e.p.subtract(we.ONE).gcd(e.e).compareTo(we.ONE)!==0){e.p=null,i();return}if(e.q.subtract(we.ONE).gcd(e.e).compareTo(we.ONE)!==0){e.q=null,o(e.qBits,s);return}if(e.p1=e.p.subtract(we.ONE),e.q1=e.q.subtract(we.ONE),e.phi=e.p1.multiply(e.q1),e.phi.gcd(e.e).compareTo(we.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,o(e.qBits,s);return}var l=e.e.modInverse(e.phi);e.keys={privateKey:fe.rsa.setPrivateKey(e.n,e.e,l,e.p,e.q,l.mod(e.p1),l.mod(e.q1),e.q.modInverse(e.p)),publicKey:fe.rsa.setPublicKey(e.n,e.e)},n(null,e.keys)}}function gr(e){var t=e.toString(16);if(t[0]>="8")t="00"+t;var n=ne.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 Cw(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 Ed(e){return ne.util.isNodejs&&typeof bc[e]==="function"}function _d(e){return typeof Vt.globalScope<"u"&&typeof Vt.globalScope.crypto==="object"&&typeof Vt.globalScope.crypto.subtle==="object"&&typeof Vt.globalScope.crypto.subtle[e]==="function"}function Td(e){return typeof Vt.globalScope<"u"&&typeof Vt.globalScope.msCrypto==="object"&&typeof Vt.globalScope.msCrypto.subtle==="object"&&typeof Vt.globalScope.msCrypto.subtle[e]==="function"}function Ad(e){var t=ne.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 Cc=le(function(z2,Dd){var q=he();Vr();Qt();Di();ur();Wr();Xo();fn();Ft();pc();Li();Te();if(typeof Sc>"u")Sc=q.jsbn.BigInteger;var Sc,B=q.asn1,pe=q.pki=q.pki||{};Dd.exports=pe.pbe=q.pbe=q.pbe||{};var hn=pe.oids,ww={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"}]},Ew={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"}]}]},_w={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"}]};pe.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=q.random.getBytesSync(n.saltSize),i=n.count,o=B.integerToDer(i),s,a,c;if(n.algorithm.indexOf("aes")===0||n.algorithm==="des"){var u,l,f;switch(n.algorithm){case"aes128":s=16,u=16,l=hn["aes128-CBC"],f=q.aes.createEncryptionCipher;break;case"aes192":s=24,u=16,l=hn["aes192-CBC"],f=q.aes.createEncryptionCipher;break;case"aes256":s=32,u=16,l=hn["aes256-CBC"],f=q.aes.createEncryptionCipher;break;case"des":s=8,u=8,l=hn.desCBC,f=q.des.createEncryptionCipher;break;default:var p=Error("Cannot encrypt private key. Unknown encryption algorithm.");throw p.algorithm=n.algorithm,p}var h="hmacWith"+n.prfAlgorithm.toUpperCase(),d=Nd(h),g=q.pkcs5.pbkdf2(t,r,i,s,d),v=q.random.getBytesSync(u),b=f(g);b.start(v),b.update(B.toDer(e)),b.finish(),c=b.output.getBytes();var S=Tw(r,o,s,h);a=B.create(B.Class.UNIVERSAL,B.Type.SEQUENCE,!0,[B.create(B.Class.UNIVERSAL,B.Type.OID,!1,B.oidToDer(hn.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(hn.pkcs5PBKDF2).getBytes()),S]),B.create(B.Class.UNIVERSAL,B.Type.SEQUENCE,!0,[B.create(B.Class.UNIVERSAL,B.Type.OID,!1,B.oidToDer(l).getBytes()),B.create(B.Class.UNIVERSAL,B.Type.OCTETSTRING,!1,v)])])])}else if(n.algorithm==="3des"){s=24;var C=new q.util.ByteBuffer(r),g=pe.pbe.generatePkcs12Key(t,C,1,i,s),v=pe.pbe.generatePkcs12Key(t,C,2,i,s),b=q.des.createEncryptionCipher(g);b.start(v),b.update(B.toDer(e)),b.finish(),c=b.output.getBytes(),a=B.create(B.Class.UNIVERSAL,B.Type.SEQUENCE,!0,[B.create(B.Class.UNIVERSAL,B.Type.OID,!1,B.oidToDer(hn["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,o.getBytes())])])}else{var p=Error("Cannot encrypt private key. Unknown encryption algorithm.");throw p.algorithm=n.algorithm,p}var T=B.create(B.Class.UNIVERSAL,B.Type.SEQUENCE,!0,[a,B.create(B.Class.UNIVERSAL,B.Type.OCTETSTRING,!1,c)]);return T};pe.decryptPrivateKeyInfo=function(e,t){var n=null,r={},i=[];if(!B.validate(e,ww,r,i)){var o=Error("Cannot read encrypted private key. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw o.errors=i,o}var s=B.derToOid(r.encryptionOid),a=pe.pbe.getCipher(s,r.encryptionParams,t),c=q.util.createBuffer(r.encryptedData);if(a.update(c),a.finish())n=B.fromDer(a.output);return n};pe.encryptedPrivateKeyToPem=function(e,t){var n={type:"ENCRYPTED PRIVATE KEY",body:B.toDer(e).getBytes()};return q.pem.encode(n,{maxline:t})};pe.encryptedPrivateKeyFromPem=function(e){var t=q.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)};pe.encryptRsaPrivateKey=function(e,t,n){if(n=n||{},!n.legacy){var r=pe.wrapRsaPrivateKey(pe.privateKeyToAsn1(e));return r=pe.encryptPrivateKeyInfo(r,t,n),pe.encryptedPrivateKeyToPem(r)}var i,o,s,a;switch(n.algorithm){case"aes128":i="AES-128-CBC",s=16,o=q.random.getBytesSync(16),a=q.aes.createEncryptionCipher;break;case"aes192":i="AES-192-CBC",s=24,o=q.random.getBytesSync(16),a=q.aes.createEncryptionCipher;break;case"aes256":i="AES-256-CBC",s=32,o=q.random.getBytesSync(16),a=q.aes.createEncryptionCipher;break;case"3des":i="DES-EDE3-CBC",s=24,o=q.random.getBytesSync(8),a=q.des.createEncryptionCipher;break;case"des":i="DES-CBC",s=8,o=q.random.getBytesSync(8),a=q.des.createEncryptionCipher;break;default:var c=Error('Could not encrypt RSA private key; unsupported encryption algorithm "'+n.algorithm+'".');throw c.algorithm=n.algorithm,c}var u=q.pbe.opensslDeriveBytes(t,o.substr(0,8),s),l=a(u);l.start(o),l.update(B.toDer(pe.privateKeyToAsn1(e))),l.finish();var f={type:"RSA PRIVATE KEY",procType:{version:"4",type:"ENCRYPTED"},dekInfo:{algorithm:i,parameters:q.util.bytesToHex(o).toUpperCase()},body:l.output.getBytes()};return q.pem.encode(f)};pe.decryptRsaPrivateKey=function(e,t){var n=null,r=q.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 o,s;switch(r.dekInfo.algorithm){case"DES-CBC":o=8,s=q.des.createDecryptionCipher;break;case"DES-EDE3-CBC":o=24,s=q.des.createDecryptionCipher;break;case"AES-128-CBC":o=16,s=q.aes.createDecryptionCipher;break;case"AES-192-CBC":o=24,s=q.aes.createDecryptionCipher;break;case"AES-256-CBC":o=32,s=q.aes.createDecryptionCipher;break;case"RC2-40-CBC":o=5,s=function(f){return q.rc2.createDecryptionCipher(f,40)};break;case"RC2-64-CBC":o=8,s=function(f){return q.rc2.createDecryptionCipher(f,64)};break;case"RC2-128-CBC":o=16,s=function(f){return q.rc2.createDecryptionCipher(f,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 a=q.util.hexToBytes(r.dekInfo.parameters),c=q.pbe.opensslDeriveBytes(t,a.substr(0,8),o),u=s(c);if(u.start(a),u.update(q.util.createBuffer(r.body)),u.finish())n=u.output.getBytes();else return n}else n=r.body;if(r.type==="ENCRYPTED PRIVATE KEY")n=pe.decryptPrivateKeyInfo(B.fromDer(n),t);else n=B.fromDer(n);if(n!==null)n=pe.privateKeyFromAsn1(n);return n};pe.pbe.generatePkcs12Key=function(e,t,n,r,i,o){var s,a;if(!(r>=1))throw Error("PKCS#12 key derivation iteration count must be >= 1.");if(typeof o>"u"||o===null){if(!("sha1"in q.md))throw Error('"sha1" hash algorithm unavailable.');o=q.md.sha1.create()}var c=o.digestLength,u=o.blockLength,l=new q.util.ByteBuffer,f=new q.util.ByteBuffer;if(e!==null&&e!==void 0){for(a=0;a<e.length;a++)f.putInt16(e.charCodeAt(a));f.putInt16(0)}var p=f.length(),h=t.length(),d=new q.util.ByteBuffer;d.fillWithByte(n,u);var g=u*Math.ceil(h/u),v=new q.util.ByteBuffer;for(a=0;a<g;a++)v.putByte(t.at(a%h));var b=u*Math.ceil(p/u),S=new q.util.ByteBuffer;for(a=0;a<b;a++)S.putByte(f.at(a%p));var C=v;C.putBuffer(S);var T=Math.ceil(i/c);for(var I=1;I<=T;I++){var k=new q.util.ByteBuffer;k.putBytes(d.bytes()),k.putBytes(C.bytes());for(var R=0;R<r;R++)o.start(),o.update(k.getBytes()),k=o.digest();var V=new q.util.ByteBuffer;for(a=0;a<u;a++)V.putByte(k.at(a%c));var D=Math.ceil(h/u)+Math.ceil(p/u),F=new q.util.ByteBuffer;for(s=0;s<D;s++){var H=new q.util.ByteBuffer(C.getBytes(u)),re=511;for(a=V.length()-1;a>=0;a--)re=re>>8,re+=V.at(a)+H.at(a),H.setAt(a,re&255);F.putBuffer(H)}C=F,l.putBuffer(k)}return l.truncate(l.length()-i),l};pe.pbe.getCipher=function(e,t,n){switch(e){case pe.oids.pkcs5PBES2:return pe.pbe.getCipherForPBES2(e,t,n);case pe.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:case pe.oids["pbewithSHAAnd40BitRC2-CBC"]:return pe.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}};pe.pbe.getCipherForPBES2=function(e,t,n){var r={},i=[];if(!B.validate(t,Ew,r,i)){var o=Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw o.errors=i,o}if(e=B.derToOid(r.kdfOid),e!==pe.oids.pkcs5PBKDF2){var o=Error("Cannot read encrypted private key. Unsupported key derivation function OID.");throw o.oid=e,o.supportedOids=["pkcs5PBKDF2"],o}if(e=B.derToOid(r.encOid),e!==pe.oids["aes128-CBC"]&&e!==pe.oids["aes192-CBC"]&&e!==pe.oids["aes256-CBC"]&&e!==pe.oids["des-EDE3-CBC"]&&e!==pe.oids.desCBC){var o=Error("Cannot read encrypted private key. Unsupported encryption scheme OID.");throw o.oid=e,o.supportedOids=["aes128-CBC","aes192-CBC","aes256-CBC","des-EDE3-CBC","desCBC"],o}var s=r.kdfSalt,a=q.util.createBuffer(r.kdfIterationCount);a=a.getInt(a.length()<<3);var c,u;switch(pe.oids[e]){case"aes128-CBC":c=16,u=q.aes.createDecryptionCipher;break;case"aes192-CBC":c=24,u=q.aes.createDecryptionCipher;break;case"aes256-CBC":c=32,u=q.aes.createDecryptionCipher;break;case"des-EDE3-CBC":c=24,u=q.des.createDecryptionCipher;break;case"desCBC":c=8,u=q.des.createDecryptionCipher;break}var l=Bd(r.prfOid),f=q.pkcs5.pbkdf2(n,s,a,c,l),p=r.encIv,h=u(f);return h.start(p),h};pe.pbe.getCipherForPKCS12PBE=function(e,t,n){var r={},i=[];if(!B.validate(t,_w,r,i)){var o=Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw o.errors=i,o}var s=q.util.createBuffer(r.salt),a=q.util.createBuffer(r.iterations);a=a.getInt(a.length()<<3);var c,u,l;switch(e){case pe.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:c=24,u=8,l=q.des.startDecrypting;break;case pe.oids["pbewithSHAAnd40BitRC2-CBC"]:c=5,u=8,l=function(g,v){var b=q.rc2.createDecryptionCipher(g,40);return b.start(v,null),b};break;default:var o=Error("Cannot read PKCS #12 PBE data block. Unsupported OID.");throw o.oid=e,o}var f=Bd(r.prfOid),p=pe.pbe.generatePkcs12Key(n,s,1,a,c,f);f.start();var h=pe.pbe.generatePkcs12Key(n,s,2,a,u,f);return l(p,h)};pe.pbe.opensslDeriveBytes=function(e,t,n,r){if(typeof r>"u"||r===null){if(!("md5"in q.md))throw Error('"md5" hash algorithm unavailable.');r=q.md.md5.create()}if(t===null)t="";var i=[Rd(r,e+t)];for(var o=16,s=1;o<n;++s,o+=16)i.push(Rd(r,i[s-1]+e+t));return i.join("").substr(0,n)};function Rd(e,t){return e.start().update(t).digest().getBytes()}function Bd(e){var t;if(!e)t="hmacWithSHA1";else if(t=pe.oids[B.derToOid(e)],!t){var n=Error("Unsupported PRF OID.");throw n.oid=e,n.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"],n}return Nd(t)}function Nd(e){var t=q.md;switch(e){case"hmacWithSHA224":t=q.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 Tw(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,q.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(pe.oids[r]).getBytes()),B.create(B.Class.UNIVERSAL,B.Type.NULL,!1,"")]));return i}});var wc=le(function(F2,Ld){var Vn=he();Qt();Te();var G=Vn.asn1,Wn=Ld.exports=Vn.pkcs7asn1=Vn.pkcs7asn1||{};Vn.pkcs7=Vn.pkcs7||{};Vn.pkcs7.asn1=Wn;var $d={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"}]};Wn.contentInfoValidator=$d;var Od={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"}]};Wn.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(Od)};Wn.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(Od)};var Aw={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"}]};Wn.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"},$d,{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:[Aw]}]};Wn.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 Ec=le(function(M2,Ud){var mn=he();Te();mn.mgf=mn.mgf||{};var kw=Ud.exports=mn.mgf.mgf1=mn.mgf1=mn.mgf1||{};kw.create=function(e){var t={generate:function(n,r){var i=new mn.util.ByteBuffer,o=Math.ceil(r/e.digestLength);for(var s=0;s<o;s++){var a=new mn.util.ByteBuffer;a.putInt32(s),e.start(),e.update(n+a.getBytes()),i.putBuffer(e.digest())}return i.truncate(i.length()-r),i.getBytes()}};return t}});var Fd=le(function(V2,zd){var ns=he();Ec();zd.exports=ns.mgf=ns.mgf||{};ns.mgf.mgf1=ns.mgf1});var is=le(function(W2,Md){var gn=he();Ft();Te();var Iw=Md.exports=gn.pss=gn.pss||{};Iw.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=gn.util.createBuffer(i);var o;if("saltLength"in e)o=e.saltLength;else if(i!==null)o=i.length();else throw Error("Salt length not specified or specific salt not given.");if(i!==null&&i.length()!==o)throw Error("Given salt length does not match length of given salt.");var s=e.prng||gn.random,a={};return a.encode=function(c,u){var l,f=u-1,p=Math.ceil(f/8),h=c.digest().getBytes();if(p<r+o+2)throw Error("Message is too long to encrypt.");var d;if(i===null)d=s.getBytesSync(o);else d=i.bytes();var g=new gn.util.ByteBuffer;g.fillWithByte(0,8),g.putBytes(h),g.putBytes(d),t.start(),t.update(g.getBytes());var v=t.digest().getBytes(),b=new gn.util.ByteBuffer;b.fillWithByte(0,p-o-r-2),b.putByte(1),b.putBytes(d);var S=b.getBytes(),C=p-r-1,T=n.generate(v,C),I="";for(l=0;l<C;l++)I+=String.fromCharCode(S.charCodeAt(l)^T.charCodeAt(l));var k=65280>>8*p-f&255;return I=String.fromCharCode(I.charCodeAt(0)&~k)+I.substr(1),I+v+String.fromCharCode(188)},a.verify=function(c,u,l){var f,p=l-1,h=Math.ceil(p/8);if(u=u.substr(-h),h<r+o+2)throw Error("Inconsistent parameters to PSS signature verification.");if(u.charCodeAt(h-1)!==188)throw Error("Encoded message does not end in 0xBC.");var d=h-r-1,g=u.substr(0,d),v=u.substr(d,r),b=65280>>8*h-p&255;if((g.charCodeAt(0)&b)!==0)throw Error("Bits beyond keysize not zero as expected.");var S=n.generate(v,d),C="";for(f=0;f<d;f++)C+=String.fromCharCode(g.charCodeAt(f)^S.charCodeAt(f));C=String.fromCharCode(C.charCodeAt(0)&~b)+C.substr(1);var T=h-r-o-2;for(f=0;f<T;f++)if(C.charCodeAt(f)!==0)throw Error("Leftmost octets not zero as expected");if(C.charCodeAt(T)!==1)throw Error("Inconsistent PSS signature, 0x01 marker not found");var I=C.substr(-o),k=new gn.util.ByteBuffer;k.fillWithByte(0,8),k.putBytes(c),k.putBytes(I),t.start(),t.update(k.getBytes());var R=t.digest().getBytes();return v===R},a}});var cs=le(function(H2,ep){var X=he();Vr();Qt();Di();ur();Fd();Wr();fn();is();Li();Te();var m=X.asn1,M=ep.exports=X.pki=X.pki||{},Se=M.oids,Je={};Je.CN=Se.commonName;Je.commonName="CN";Je.C=Se.countryName;Je.countryName="C";Je.L=Se.localityName;Je.localityName="L";Je.ST=Se.stateOrProvinceName;Je.stateOrProvinceName="ST";Je.O=Se.organizationName;Je.organizationName="O";Je.OU=Se.organizationalUnitName;Je.organizationalUnitName="OU";Je.E=Se.emailAddress;Je.emailAddress="E";var qd=X.pki.rsa.publicKeyValidator,Pw={name:"Certificate",tagClass:m.Class.UNIVERSAL,type:m.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate",tagClass:m.Class.UNIVERSAL,type:m.Type.SEQUENCE,constructed:!0,captureAsn1:"tbsCertificate",value:[{name:"Certificate.TBSCertificate.version",tagClass:m.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.version.integer",tagClass:m.Class.UNIVERSAL,type:m.Type.INTEGER,constructed:!1,capture:"certVersion"}]},{name:"Certificate.TBSCertificate.serialNumber",tagClass:m.Class.UNIVERSAL,type:m.Type.INTEGER,constructed:!1,capture:"certSerialNumber"},{name:"Certificate.TBSCertificate.signature",tagClass:m.Class.UNIVERSAL,type:m.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate.signature.algorithm",tagClass:m.Class.UNIVERSAL,type:m.Type.OID,constructed:!1,capture:"certinfoSignatureOid"},{name:"Certificate.TBSCertificate.signature.parameters",tagClass:m.Class.UNIVERSAL,optional:!0,captureAsn1:"certinfoSignatureParams"}]},{name:"Certificate.TBSCertificate.issuer",tagClass:m.Class.UNIVERSAL,type:m.Type.SEQUENCE,constructed:!0,captureAsn1:"certIssuer"},{name:"Certificate.TBSCertificate.validity",tagClass:m.Class.UNIVERSAL,type:m.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate.validity.notBefore (utc)",tagClass:m.Class.UNIVERSAL,type:m.Type.UTCTIME,constructed:!1,optional:!0,capture:"certValidity1UTCTime"},{name:"Certificate.TBSCertificate.validity.notBefore (generalized)",tagClass:m.Class.UNIVERSAL,type:m.Type.GENERALIZEDTIME,constructed:!1,optional:!0,capture:"certValidity2GeneralizedTime"},{name:"Certificate.TBSCertificate.validity.notAfter (utc)",tagClass:m.Class.UNIVERSAL,type:m.Type.UTCTIME,constructed:!1,optional:!0,capture:"certValidity3UTCTime"},{name:"Certificate.TBSCertificate.validity.notAfter (generalized)",tagClass:m.Class.UNIVERSAL,type:m.Type.GENERALIZEDTIME,constructed:!1,optional:!0,capture:"certValidity4GeneralizedTime"}]},{name:"Certificate.TBSCertificate.subject",tagClass:m.Class.UNIVERSAL,type:m.Type.SEQUENCE,constructed:!0,captureAsn1:"certSubject"},qd,{name:"Certificate.TBSCertificate.issuerUniqueID",tagClass:m.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.issuerUniqueID.id",tagClass:m.Class.UNIVERSAL,type:m.Type.BITSTRING,constructed:!1,captureBitStringValue:"certIssuerUniqueId"}]},{name:"Certificate.TBSCertificate.subjectUniqueID",tagClass:m.Class.CONTEXT_SPECIFIC,type:2,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.subjectUniqueID.id",tagClass:m.Class.UNIVERSAL,type:m.Type.BITSTRING,constructed:!1,captureBitStringValue:"certSubjectUniqueId"}]},{name:"Certificate.TBSCertificate.extensions",tagClass:m.Class.CONTEXT_SPECIFIC,type:3,constructed:!0,captureAsn1:"certExtensions",optional:!0}]},{name:"Certificate.signatureAlgorithm",tagClass:m.Class.UNIVERSAL,type:m.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.signatureAlgorithm.algorithm",tagClass:m.Class.UNIVERSAL,type:m.Type.OID,constructed:!1,capture:"certSignatureOid"},{name:"Certificate.TBSCertificate.signature.parameters",tagClass:m.Class.UNIVERSAL,optional:!0,captureAsn1:"certSignatureParams"}]},{name:"Certificate.signatureValue",tagClass:m.Class.UNIVERSAL,type:m.Type.BITSTRING,constructed:!1,captureBitStringValue:"certSignature"}]},Rw={name:"rsapss",tagClass:m.Class.UNIVERSAL,type:m.Type.SEQUENCE,constructed:!0,value:[{name:"rsapss.hashAlgorithm",tagClass:m.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,value:[{name:"rsapss.hashAlgorithm.AlgorithmIdentifier",tagClass:m.Class.UNIVERSAL,type:m.Class.SEQUENCE,constructed:!0,optional:!0,value:[{name:"rsapss.hashAlgorithm.AlgorithmIdentifier.algorithm",tagClass:m.Class.UNIVERSAL,type:m.Type.OID,constructed:!1,capture:"hashOid"}]}]},{name:"rsapss.maskGenAlgorithm",tagClass:m.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier",tagClass:m.Class.UNIVERSAL,type:m.Class.SEQUENCE,constructed:!0,optional:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.algorithm",tagClass:m.Class.UNIVERSAL,type:m.Type.OID,constructed:!1,capture:"maskGenOid"},{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.params",tagClass:m.Class.UNIVERSAL,type:m.Type.SEQUENCE,constructed:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.params.algorithm",tagClass:m.Class.UNIVERSAL,type:m.Type.OID,constructed:!1,capture:"maskGenHashOid"}]}]}]},{name:"rsapss.saltLength",tagClass:m.Class.CONTEXT_SPECIFIC,type:2,optional:!0,value:[{name:"rsapss.saltLength.saltLength",tagClass:m.Class.UNIVERSAL,type:m.Class.INTEGER,constructed:!1,capture:"saltLength"}]},{name:"rsapss.trailerField",tagClass:m.Class.CONTEXT_SPECIFIC,type:3,optional:!0,value:[{name:"rsapss.trailer.trailer",tagClass:m.Class.UNIVERSAL,type:m.Class.INTEGER,constructed:!1,capture:"trailer"}]}]},Bw={name:"CertificationRequestInfo",tagClass:m.Class.UNIVERSAL,type:m.Type.SEQUENCE,constructed:!0,captureAsn1:"certificationRequestInfo",value:[{name:"CertificationRequestInfo.integer",tagClass:m.Class.UNIVERSAL,type:m.Type.INTEGER,constructed:!1,capture:"certificationRequestInfoVersion"},{name:"CertificationRequestInfo.subject",tagClass:m.Class.UNIVERSAL,type:m.Type.SEQUENCE,constructed:!0,captureAsn1:"certificationRequestInfoSubject"},qd,{name:"CertificationRequestInfo.attributes",tagClass:m.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,capture:"certificationRequestInfoAttributes",value:[{name:"CertificationRequestInfo.attributes",tagClass:m.Class.UNIVERSAL,type:m.Type.SEQUENCE,constructed:!0,value:[{name:"CertificationRequestInfo.attributes.type",tagClass:m.Class.UNIVERSAL,type:m.Type.OID,constructed:!1},{name:"CertificationRequestInfo.attributes.value",tagClass:m.Class.UNIVERSAL,type:m.Type.SET,constructed:!0}]}]}]},Nw={name:"CertificationRequest",tagClass:m.Class.UNIVERSAL,type:m.Type.SEQUENCE,constructed:!0,captureAsn1:"csr",value:[Bw,{name:"CertificationRequest.signatureAlgorithm",tagClass:m.Class.UNIVERSAL,type:m.Type.SEQUENCE,constructed:!0,value:[{name:"CertificationRequest.signatureAlgorithm.algorithm",tagClass:m.Class.UNIVERSAL,type:m.Type.OID,constructed:!1,capture:"csrSignatureOid"},{name:"CertificationRequest.signatureAlgorithm.parameters",tagClass:m.Class.UNIVERSAL,optional:!0,captureAsn1:"csrSignatureParams"}]},{name:"CertificationRequest.signature",tagClass:m.Class.UNIVERSAL,type:m.Type.BITSTRING,constructed:!1,captureBitStringValue:"csrSignature"}]};M.RDNAttributesAsArray=function(e,t){var n=[],r,i,o;for(var s=0;s<e.value.length;++s){r=e.value[s];for(var a=0;a<r.value.length;++a){if(o={},i=r.value[a],o.type=m.derToOid(i.value[0].value),o.value=i.value[1].value,o.valueTagClass=i.value[1].type,o.type in Se){if(o.name=Se[o.type],o.name in Je)o.shortName=Je[o.name]}if(t)t.update(o.type),t.update(o.value);n.push(o)}}return n};M.CRIAttributesAsArray=function(e){var t=[];for(var n=0;n<e.length;++n){var r=e[n],i=m.derToOid(r.value[0].value),o=r.value[1].value;for(var s=0;s<o.length;++s){var a={};if(a.type=i,a.value=o[s].value,a.valueTagClass=o[s].type,a.type in Se){if(a.name=Se[a.type],a.name in Je)a.shortName=Je[a.name]}if(a.type===Se.extensionRequest){a.extensions=[];for(var c=0;c<a.value.length;++c)a.extensions.push(M.certificateExtensionFromAsn1(a.value[c]))}t.push(a)}}return t};function Zr(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 ss=function(e,t,n){var r={};if(e!==Se["RSASSA-PSS"])return r;if(n)r={hash:{algorithmOid:Se.sha1},mgf:{algorithmOid:Se.mgf1,hash:{algorithmOid:Se.sha1}},saltLength:20};var i={},o=[];if(!m.validate(t,Rw,i,o)){var s=Error("Cannot read RSASSA-PSS parameter block.");throw s.errors=o,s}if(i.hashOid!==void 0)r.hash=r.hash||{},r.hash.algorithmOid=m.derToOid(i.hashOid);if(i.maskGenOid!==void 0)r.mgf=r.mgf||{},r.mgf.algorithmOid=m.derToOid(i.maskGenOid),r.mgf.hash=r.mgf.hash||{},r.mgf.hash.algorithmOid=m.derToOid(i.maskGenHashOid);if(i.saltLength!==void 0)r.saltLength=i.saltLength.charCodeAt(0);return r},as=function(e){switch(Se[e.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 t=Error("Could not compute "+e.type+" digest. Unknown signature OID.");throw t.signatureOid=e.signatureOid,t}},Xd=function(e){var t=e.certificate,n=e.publicKey||t.publicKey,r;switch(t.signatureOid){case Se.sha1WithRSAEncryption:case Se.sha1WithRSASignature:break;case Se["RSASSA-PSS"]:var i,o;if(i=Se[t.signatureParameters.mgf.hash.algorithmOid],i===void 0||X.md[i]===void 0){var s=Error("Unsupported MGF hash function.");throw s.oid=t.signatureParameters.mgf.hash.algorithmOid,s.name=i,s}if(o=Se[t.signatureParameters.mgf.algorithmOid],o===void 0||X.mgf[o]===void 0){var s=Error("Unsupported MGF function.");throw s.oid=t.signatureParameters.mgf.algorithmOid,s.name=o,s}if(o=X.mgf[o].create(X.md[i].create()),i=Se[t.signatureParameters.hash.algorithmOid],i===void 0||X.md[i]===void 0){var s=Error("Unsupported RSASSA-PSS hash function.");throw s.oid=t.signatureParameters.hash.algorithmOid,s.name=i,s}r=X.pss.create(X.md[i].create(),o,t.signatureParameters.saltLength);break}return n.verify(e.md.digest().getBytes(),e.signature,r)};M.certificateFromPem=function(e,t,n){var r=X.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 o=m.fromDer(r.body,n);return M.certificateFromAsn1(o,t)};M.certificateToPem=function(e,t){var n={type:"CERTIFICATE",body:m.toDer(M.certificateToAsn1(e)).getBytes()};return X.pem.encode(n,{maxline:t})};M.publicKeyFromPem=function(e){var t=X.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=m.fromDer(t.body);return M.publicKeyFromAsn1(r)};M.publicKeyToPem=function(e,t){var n={type:"PUBLIC KEY",body:m.toDer(M.publicKeyToAsn1(e)).getBytes()};return X.pem.encode(n,{maxline:t})};M.publicKeyToRSAPublicKeyPem=function(e,t){var n={type:"RSA PUBLIC KEY",body:m.toDer(M.publicKeyToRSAPublicKey(e)).getBytes()};return X.pem.encode(n,{maxline:t})};M.getPublicKeyFingerprint=function(e,t){t=t||{};var n=t.md||X.md.sha1.create(),r=t.type||"RSAPublicKey",i;switch(r){case"RSAPublicKey":i=m.toDer(M.publicKeyToRSAPublicKey(e)).getBytes();break;case"SubjectPublicKeyInfo":i=m.toDer(M.publicKeyToAsn1(e)).getBytes();break;default:throw Error('Unknown fingerprint type "'+t.type+'".')}n.start(),n.update(i);var o=n.digest();if(t.encoding==="hex"){var s=o.toHex();if(t.delimiter)return s.match(/.{2}/g).join(t.delimiter);return s}else if(t.encoding==="binary")return o.getBytes();else if(t.encoding)throw Error('Unknown encoding "'+t.encoding+'".');return o};M.certificationRequestFromPem=function(e,t,n){var r=X.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 o=m.fromDer(r.body,n);return M.certificationRequestFromAsn1(o,t)};M.certificationRequestToPem=function(e,t){var n={type:"CERTIFICATE REQUEST",body:m.toDer(M.certificationRequestToAsn1(e)).getBytes()};return X.pem.encode(n,{maxline:t})};M.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 Zr(e.issuer,t)},e.issuer.addField=function(t){Wt([t]),e.issuer.attributes.push(t)},e.issuer.attributes=[],e.issuer.hash=null,e.subject={},e.subject.getField=function(t){return Zr(e.subject,t)},e.subject.addField=function(t){Wt([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(Wt(t),e.subject.attributes=t,delete e.subject.uniqueId,n)e.subject.uniqueId=n;e.subject.hash=null},e.setIssuer=function(t,n){if(Wt(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)Qd(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||X.md.sha1.create();var r=Se[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=M.getTBSCertificate(e);var o=m.toDer(e.tbsCertificate);e.md.update(o.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,o=Error("The parent certificate did not issue the given child certificate; the child certificate's issuer does not match the parent's subject.");throw o.expectedIssuer=i.attributes,o.actualIssuer=r.attributes,o}var s=t.md;if(s===null){s=as({signatureOid:t.signatureOid,type:"certificate"});var a=t.tbsCertificate||M.getTBSCertificate(t),c=m.toDer(a);s.update(c.getBytes())}if(s!==null)n=Xd({certificate:t,publicKey:e.publicKey,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 o,s;for(var a=0;n&&a<r.attributes.length;++a)if(o=r.attributes[a],s=i.attributes[a],o.type!==s.type||o.value!==s.value)n=!1}return n},e.issued=function(t){return t.isIssuer(e)},e.generateSubjectKeyIdentifier=function(){return M.getPublicKeyFingerprint(e.publicKey,{type:"RSAPublicKey"})},e.verifySubjectKeyIdentifier=function(){var t=Se.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 X.util.hexToBytes(r.subjectKeyIdentifier)===i}}return!1},e};M.certificateFromAsn1=function(e,t){var n={},r=[];if(!m.validate(e,Pw,n,r)){var i=Error("Cannot read X.509 certificate. ASN.1 object is not an X509v3 Certificate.");throw i.errors=r,i}var o=m.derToOid(n.publicKeyOid);if(o!==M.oids.rsaEncryption)throw Error("Cannot read public key. OID is not RSA.");var s=M.createCertificate();s.version=n.certVersion?n.certVersion.charCodeAt(0):0;var a=X.util.createBuffer(n.certSerialNumber);s.serialNumber=a.toHex(),s.signatureOid=X.asn1.derToOid(n.certSignatureOid),s.signatureParameters=ss(s.signatureOid,n.certSignatureParams,!0),s.siginfo.algorithmOid=X.asn1.derToOid(n.certinfoSignatureOid),s.siginfo.parameters=ss(s.siginfo.algorithmOid,n.certinfoSignatureParams,!1),s.signature=n.certSignature;var c=[];if(n.certValidity1UTCTime!==void 0)c.push(m.utcTimeToDate(n.certValidity1UTCTime));if(n.certValidity2GeneralizedTime!==void 0)c.push(m.generalizedTimeToDate(n.certValidity2GeneralizedTime));if(n.certValidity3UTCTime!==void 0)c.push(m.utcTimeToDate(n.certValidity3UTCTime));if(n.certValidity4GeneralizedTime!==void 0)c.push(m.generalizedTimeToDate(n.certValidity4GeneralizedTime));if(c.length>2)throw Error("Cannot read notBefore/notAfter validity times; more than two times were provided in the certificate.");if(c.length<2)throw Error("Cannot read notBefore/notAfter validity times; they were not provided as either UTCTime or GeneralizedTime.");if(s.validity.notBefore=c[0],s.validity.notAfter=c[1],s.tbsCertificate=n.tbsCertificate,t){s.md=as({signatureOid:s.signatureOid,type:"certificate"});var u=m.toDer(s.tbsCertificate);s.md.update(u.getBytes())}var l=X.md.sha1.create(),f=m.toDer(n.certIssuer);if(l.update(f.getBytes()),s.issuer.getField=function(d){return Zr(s.issuer,d)},s.issuer.addField=function(d){Wt([d]),s.issuer.attributes.push(d)},s.issuer.attributes=M.RDNAttributesAsArray(n.certIssuer),n.certIssuerUniqueId)s.issuer.uniqueId=n.certIssuerUniqueId;s.issuer.hash=l.digest().toHex();var p=X.md.sha1.create(),h=m.toDer(n.certSubject);if(p.update(h.getBytes()),s.subject.getField=function(d){return Zr(s.subject,d)},s.subject.addField=function(d){Wt([d]),s.subject.attributes.push(d)},s.subject.attributes=M.RDNAttributesAsArray(n.certSubject),n.certSubjectUniqueId)s.subject.uniqueId=n.certSubjectUniqueId;if(s.subject.hash=p.digest().toHex(),n.certExtensions)s.extensions=M.certificateExtensionsFromAsn1(n.certExtensions);else s.extensions=[];return s.publicKey=M.publicKeyFromAsn1(n.subjectPublicKeyInfo),s};M.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(M.certificateExtensionFromAsn1(r.value[i]))}return t};M.certificateExtensionFromAsn1=function(e){var t={};if(t.id=m.derToOid(e.value[0].value),t.critical=!1,e.value[1].type===m.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 Se){if(t.name=Se[t.id],t.name==="keyUsage"){var n=m.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=m.fromDer(t.value);if(n.value.length>0&&n.value[0].type===m.Type.BOOLEAN)t.cA=n.value[0].value.charCodeAt(0)!==0;else t.cA=!1;var o=null;if(n.value.length>0&&n.value[0].type===m.Type.INTEGER)o=n.value[0].value;else if(n.value.length>1)o=n.value[1].value;if(o!==null)t.pathLenConstraint=m.derToInteger(o)}else if(t.name==="extKeyUsage"){var n=m.fromDer(t.value);for(var s=0;s<n.value.length;++s){var a=m.derToOid(n.value[s].value);if(a in Se)t[Se[a]]=!0;else t[a]=!0}}else if(t.name==="nsCertType"){var n=m.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 c,n=m.fromDer(t.value);for(var u=0;u<n.value.length;++u){c=n.value[u];var l={type:c.type,value:c.value};switch(t.altNames.push(l),c.type){case 1:case 2:case 6:break;case 7:l.ip=X.util.bytesToIP(c.value);break;case 8:l.oid=m.derToOid(c.value);break;default:}}}else if(t.name==="nameConstraints"&&t.id==="2.5.29.30")try{var f=Jd(m.fromDer(t.value));t.permittedSubtrees=f.permittedSubtrees,t.excludedSubtrees=f.excludedSubtrees,t.unsupportedSubtreeRange=f.unsupportedSubtreeRange}catch(p){}else if(t.name==="subjectKeyIdentifier"){var n=m.fromDer(t.value);t.subjectKeyIdentifier=X.util.bytesToHex(n.value)}}return t};function Jd(e){var t={permittedSubtrees:[],excludedSubtrees:[],unsupportedSubtreeRange:!1};if(e.tagClass!==m.Class.UNIVERSAL||e.type!==m.Type.SEQUENCE||!X.util.isArray(e.value))throw Error("Invalid nameConstraints extension.");for(var n=0;n<e.value.length;++n){var r=e.value[n],i;if(r.tagClass===m.Class.CONTEXT_SPECIFIC&&r.type===0)i=t.permittedSubtrees;else if(r.tagClass===m.Class.CONTEXT_SPECIFIC&&r.type===1)i=t.excludedSubtrees;else throw Error("Invalid nameConstraints extension.");if(!X.util.isArray(r.value))throw Error("Invalid nameConstraints extension.");for(var o=0;o<r.value.length;++o){var s=r.value[o];if(s.type!==m.Type.SEQUENCE||!X.util.isArray(s.value)||s.value.length===0||s.value[0].tagClass!==m.Class.CONTEXT_SPECIFIC)throw Error("Invalid nameConstraints extension.");var a=s.value[0],c={type:a.type,value:a.value};if(a.type===4&&X.util.isArray(a.value)&&a.value.length===1&&a.value[0].type===m.Type.SEQUENCE&&X.util.isArray(a.value[0].value))c.attributes=M.RDNAttributesAsArray(a.value[0]);for(var u=1;u<s.value.length;++u){var l=s.value[u];if(l.tagClass===m.Class.CONTEXT_SPECIFIC&&l.type===0){if(c.minimum=m.derToInteger(l.value),c.minimum!==0)t.unsupportedSubtreeRange=!0}else if(l.tagClass===m.Class.CONTEXT_SPECIFIC&&l.type===1)c.maximum=m.derToInteger(l.value),t.unsupportedSubtreeRange=!0;else throw Error("Invalid nameConstraints extension.")}i.push(c)}}return t}M.certificationRequestFromAsn1=function(e,t){var n={},r=[];if(!m.validate(e,Nw,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 o=m.derToOid(n.publicKeyOid);if(o!==M.oids.rsaEncryption)throw Error("Cannot read public key. OID is not RSA.");var s=M.createCertificationRequest();if(s.version=n.csrVersion?n.csrVersion.charCodeAt(0):0,s.signatureOid=X.asn1.derToOid(n.csrSignatureOid),s.signatureParameters=ss(s.signatureOid,n.csrSignatureParams,!0),s.siginfo.algorithmOid=X.asn1.derToOid(n.csrSignatureOid),s.siginfo.parameters=ss(s.siginfo.algorithmOid,n.csrSignatureParams,!1),s.signature=n.csrSignature,s.certificationRequestInfo=n.certificationRequestInfo,t){s.md=as({signatureOid:s.signatureOid,type:"certification request"});var a=m.toDer(s.certificationRequestInfo);s.md.update(a.getBytes())}var c=X.md.sha1.create();return s.subject.getField=function(u){return Zr(s.subject,u)},s.subject.addField=function(u){Wt([u]),s.subject.attributes.push(u)},s.subject.attributes=M.RDNAttributesAsArray(n.certificationRequestInfoSubject,c),s.subject.hash=c.digest().toHex(),s.publicKey=M.publicKeyFromAsn1(n.subjectPublicKeyInfo),s.getAttribute=function(u){return Zr(s,u)},s.addAttribute=function(u){Wt([u]),s.attributes.push(u)},s.attributes=M.CRIAttributesAsArray(n.certificationRequestInfoAttributes||[]),s};M.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 Zr(e.subject,t)},e.subject.addField=function(t){Wt([t]),e.subject.attributes.push(t)},e.subject.attributes=[],e.subject.hash=null,e.publicKey=null,e.attributes=[],e.getAttribute=function(t){return Zr(e,t)},e.addAttribute=function(t){Wt([t]),e.attributes.push(t)},e.md=null,e.setSubject=function(t){Wt(t),e.subject.attributes=t,e.subject.hash=null},e.setAttributes=function(t){Wt(t),e.attributes=t},e.sign=function(t,n){e.md=n||X.md.sha1.create();var r=Se[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=M.getCertificationRequestInfo(e);var o=m.toDer(e.certificationRequestInfo);e.md.update(o.getBytes()),e.signature=t.sign(e.md)},e.verify=function(){var t=!1,n=e.md;if(n===null){n=as({signatureOid:e.signatureOid,type:"certification request"});var r=e.certificationRequestInfo||M.getCertificationRequestInfo(e),i=m.toDer(r);n.update(i.getBytes())}if(n!==null)t=Xd({certificate:e,md:n,signature:e.signature});return t},e};function Hn(e){var t=m.create(m.Class.UNIVERSAL,m.Type.SEQUENCE,!0,[]),n,r,i=e.attributes;for(var o=0;o<i.length;++o){n=i[o];var s=n.value,a=m.Type.PRINTABLESTRING;if("valueTagClass"in n){if(a=n.valueTagClass,a===m.Type.UTF8)s=X.util.encodeUtf8(s)}r=m.create(m.Class.UNIVERSAL,m.Type.SET,!0,[m.create(m.Class.UNIVERSAL,m.Type.SEQUENCE,!0,[m.create(m.Class.UNIVERSAL,m.Type.OID,!1,m.oidToDer(n.type).getBytes()),m.create(m.Class.UNIVERSAL,a,!1,s)])]),t.value.push(r)}return t}function Wt(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 M.oids)t.name=M.oids[t.type];else if(t.shortName&&t.shortName in Je)t.name=M.oids[Je[t.shortName]]}if(typeof t.type>"u")if(t.name&&t.name in M.oids)t.type=M.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 Je)t.shortName=Je[t.name]}if(t.type===Se.extensionRequest){if(t.valueConstructed=!0,t.valueTagClass=m.Type.SEQUENCE,!t.value&&t.extensions){t.value=[];for(var i=0;i<t.extensions.length;++i)t.value.push(M.certificateExtensionToAsn1(Qd(t.extensions[i])))}}if(typeof t.value>"u"){var r=Error("Attribute value not specified.");throw r.attribute=t,r}}}function Qd(e,t){if(t=t||{},typeof e.name>"u"){if(e.id&&e.id in M.oids)e.name=M.oids[e.id]}if(typeof e.id>"u")if(e.name&&e.name in M.oids)e.id=M.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,o=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)o|=128,r=7;var s=String.fromCharCode(r);if(o!==0)s+=String.fromCharCode(i)+String.fromCharCode(o);else if(i!==0)s+=String.fromCharCode(i);e.value=m.create(m.Class.UNIVERSAL,m.Type.BITSTRING,!1,s)}else if(e.name==="basicConstraints"){if(e.value=m.create(m.Class.UNIVERSAL,m.Type.SEQUENCE,!0,[]),e.cA)e.value.value.push(m.create(m.Class.UNIVERSAL,m.Type.BOOLEAN,!1,String.fromCharCode(255)));if("pathLenConstraint"in e)e.value.value.push(m.create(m.Class.UNIVERSAL,m.Type.INTEGER,!1,m.integerToDer(e.pathLenConstraint).getBytes()))}else if(e.name==="extKeyUsage"){e.value=m.create(m.Class.UNIVERSAL,m.Type.SEQUENCE,!0,[]);var a=e.value.value;for(var c in e){if(e[c]!==!0)continue;if(c in Se)a.push(m.create(m.Class.UNIVERSAL,m.Type.OID,!1,m.oidToDer(Se[c]).getBytes()));else if(c.indexOf(".")!==-1)a.push(m.create(m.Class.UNIVERSAL,m.Type.OID,!1,m.oidToDer(c).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=m.create(m.Class.UNIVERSAL,m.Type.BITSTRING,!1,s)}else if(e.name==="subjectAltName"||e.name==="issuerAltName"){e.value=m.create(m.Class.UNIVERSAL,m.Type.SEQUENCE,!0,[]);var u;for(var l=0;l<e.altNames.length;++l){u=e.altNames[l];var s=u.value;if(u.type===7&&u.ip){if(s=X.util.bytesFromIP(u.ip),s===null){var n=Error('Extension "ip" value is not a valid IPv4 or IPv6 address.');throw n.extension=e,n}}else if(u.type===8)if(u.oid)s=m.oidToDer(m.oidToDer(u.oid));else s=m.oidToDer(s);e.value.value.push(m.create(m.Class.CONTEXT_SPECIFIC,u.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=m.create(m.Class.UNIVERSAL,m.Type.IA5STRING,!1,e.comment)}else if(e.name==="subjectKeyIdentifier"&&t.cert){var f=t.cert.generateSubjectKeyIdentifier();e.subjectKeyIdentifier=f.toHex(),e.value=m.create(m.Class.UNIVERSAL,m.Type.OCTETSTRING,!1,f.getBytes())}else if(e.name==="authorityKeyIdentifier"&&t.cert){e.value=m.create(m.Class.UNIVERSAL,m.Type.SEQUENCE,!0,[]);var a=e.value.value;if(e.keyIdentifier){var p=e.keyIdentifier===!0?t.cert.generateSubjectKeyIdentifier().getBytes():e.keyIdentifier;a.push(m.create(m.Class.CONTEXT_SPECIFIC,0,!1,p))}if(e.authorityCertIssuer){var h=[m.create(m.Class.CONTEXT_SPECIFIC,4,!0,[Hn(e.authorityCertIssuer===!0?t.cert.issuer:e.authorityCertIssuer)])];a.push(m.create(m.Class.CONTEXT_SPECIFIC,1,!0,h))}if(e.serialNumber){var d=X.util.hexToBytes(e.serialNumber===!0?t.cert.serialNumber:e.serialNumber);a.push(m.create(m.Class.CONTEXT_SPECIFIC,2,!1,d))}}else if(e.name==="cRLDistributionPoints"){e.value=m.create(m.Class.UNIVERSAL,m.Type.SEQUENCE,!0,[]);var a=e.value.value,g=m.create(m.Class.UNIVERSAL,m.Type.SEQUENCE,!0,[]),v=m.create(m.Class.CONTEXT_SPECIFIC,0,!0,[]),u;for(var l=0;l<e.altNames.length;++l){u=e.altNames[l];var s=u.value;if(u.type===7&&u.ip){if(s=X.util.bytesFromIP(u.ip),s===null){var n=Error('Extension "ip" value is not a valid IPv4 or IPv6 address.');throw n.extension=e,n}}else if(u.type===8)if(u.oid)s=m.oidToDer(m.oidToDer(u.oid));else s=m.oidToDer(s);v.value.push(m.create(m.Class.CONTEXT_SPECIFIC,u.type,!1,s))}g.value.push(m.create(m.Class.CONTEXT_SPECIFIC,0,!0,[v])),a.push(g)}if(typeof e.value>"u"){var n=Error("Extension value not specified.");throw n.extension=e,n}return e}function Tc(e,t){switch(e){case Se["RSASSA-PSS"]:var n=[];if(t.hash.algorithmOid!==void 0)n.push(m.create(m.Class.CONTEXT_SPECIFIC,0,!0,[m.create(m.Class.UNIVERSAL,m.Type.SEQUENCE,!0,[m.create(m.Class.UNIVERSAL,m.Type.OID,!1,m.oidToDer(t.hash.algorithmOid).getBytes()),m.create(m.Class.UNIVERSAL,m.Type.NULL,!1,"")])]));if(t.mgf.algorithmOid!==void 0)n.push(m.create(m.Class.CONTEXT_SPECIFIC,1,!0,[m.create(m.Class.UNIVERSAL,m.Type.SEQUENCE,!0,[m.create(m.Class.UNIVERSAL,m.Type.OID,!1,m.oidToDer(t.mgf.algorithmOid).getBytes()),m.create(m.Class.UNIVERSAL,m.Type.SEQUENCE,!0,[m.create(m.Class.UNIVERSAL,m.Type.OID,!1,m.oidToDer(t.mgf.hash.algorithmOid).getBytes()),m.create(m.Class.UNIVERSAL,m.Type.NULL,!1,"")])])]));if(t.saltLength!==void 0)n.push(m.create(m.Class.CONTEXT_SPECIFIC,2,!0,[m.create(m.Class.UNIVERSAL,m.Type.INTEGER,!1,m.integerToDer(t.saltLength).getBytes())]));return m.create(m.Class.UNIVERSAL,m.Type.SEQUENCE,!0,n);default:return m.create(m.Class.UNIVERSAL,m.Type.NULL,!1,"")}}function Dw(e){var t=m.create(m.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],o=i.value,s=m.Type.UTF8;if("valueTagClass"in i)s=i.valueTagClass;if(s===m.Type.UTF8)o=X.util.encodeUtf8(o);var a=!1;if("valueConstructed"in i)a=i.valueConstructed;var c=m.create(m.Class.UNIVERSAL,m.Type.SEQUENCE,!0,[m.create(m.Class.UNIVERSAL,m.Type.OID,!1,m.oidToDer(i.type).getBytes()),m.create(m.Class.UNIVERSAL,m.Type.SET,!0,[m.create(m.Class.UNIVERSAL,s,a,o)])]);t.value.push(c)}return t}var $w=new Date("1950-01-01T00:00:00Z"),Ow=new Date("2050-01-01T00:00:00Z");function Vd(e){if(e>=$w&&e<Ow)return m.create(m.Class.UNIVERSAL,m.Type.UTCTIME,!1,m.dateToUtcTime(e));else return m.create(m.Class.UNIVERSAL,m.Type.GENERALIZEDTIME,!1,m.dateToGeneralizedTime(e))}M.getTBSCertificate=function(e){var t=Vd(e.validity.notBefore),n=Vd(e.validity.notAfter),r=m.create(m.Class.UNIVERSAL,m.Type.SEQUENCE,!0,[m.create(m.Class.CONTEXT_SPECIFIC,0,!0,[m.create(m.Class.UNIVERSAL,m.Type.INTEGER,!1,m.integerToDer(e.version).getBytes())]),m.create(m.Class.UNIVERSAL,m.Type.INTEGER,!1,X.util.hexToBytes(e.serialNumber)),m.create(m.Class.UNIVERSAL,m.Type.SEQUENCE,!0,[m.create(m.Class.UNIVERSAL,m.Type.OID,!1,m.oidToDer(e.siginfo.algorithmOid).getBytes()),Tc(e.siginfo.algorithmOid,e.siginfo.parameters)]),Hn(e.issuer),m.create(m.Class.UNIVERSAL,m.Type.SEQUENCE,!0,[t,n]),Hn(e.subject),M.publicKeyToAsn1(e.publicKey)]);if(e.issuer.uniqueId)r.value.push(m.create(m.Class.CONTEXT_SPECIFIC,1,!0,[m.create(m.Class.UNIVERSAL,m.Type.BITSTRING,!1,String.fromCharCode(0)+e.issuer.uniqueId)]));if(e.subject.uniqueId)r.value.push(m.create(m.Class.CONTEXT_SPECIFIC,2,!0,[m.create(m.Class.UNIVERSAL,m.Type.BITSTRING,!1,String.fromCharCode(0)+e.subject.uniqueId)]));if(e.extensions.length>0)r.value.push(M.certificateExtensionsToAsn1(e.extensions));return r};M.getCertificationRequestInfo=function(e){var t=m.create(m.Class.UNIVERSAL,m.Type.SEQUENCE,!0,[m.create(m.Class.UNIVERSAL,m.Type.INTEGER,!1,m.integerToDer(e.version).getBytes()),Hn(e.subject),M.publicKeyToAsn1(e.publicKey),Dw(e)]);return t};M.distinguishedNameToAsn1=function(e){return Hn(e)};M.certificateToAsn1=function(e){var t=e.tbsCertificate||M.getTBSCertificate(e);return m.create(m.Class.UNIVERSAL,m.Type.SEQUENCE,!0,[t,m.create(m.Class.UNIVERSAL,m.Type.SEQUENCE,!0,[m.create(m.Class.UNIVERSAL,m.Type.OID,!1,m.oidToDer(e.signatureOid).getBytes()),Tc(e.signatureOid,e.signatureParameters)]),m.create(m.Class.UNIVERSAL,m.Type.BITSTRING,!1,String.fromCharCode(0)+e.signature)])};M.certificateExtensionsToAsn1=function(e){var t=m.create(m.Class.CONTEXT_SPECIFIC,3,!0,[]),n=m.create(m.Class.UNIVERSAL,m.Type.SEQUENCE,!0,[]);t.value.push(n);for(var r=0;r<e.length;++r)n.value.push(M.certificateExtensionToAsn1(e[r]));return t};M.certificateExtensionToAsn1=function(e){var t=m.create(m.Class.UNIVERSAL,m.Type.SEQUENCE,!0,[]);if(t.value.push(m.create(m.Class.UNIVERSAL,m.Type.OID,!1,m.oidToDer(e.id).getBytes())),e.critical)t.value.push(m.create(m.Class.UNIVERSAL,m.Type.BOOLEAN,!1,String.fromCharCode(255)));var n=e.value;if(typeof e.value!=="string")n=m.toDer(n).getBytes();return t.value.push(m.create(m.Class.UNIVERSAL,m.Type.OCTETSTRING,!1,n)),t};M.certificationRequestToAsn1=function(e){var t=e.certificationRequestInfo||M.getCertificationRequestInfo(e);return m.create(m.Class.UNIVERSAL,m.Type.SEQUENCE,!0,[t,m.create(m.Class.UNIVERSAL,m.Type.SEQUENCE,!0,[m.create(m.Class.UNIVERSAL,m.Type.OID,!1,m.oidToDer(e.signatureOid).getBytes()),Tc(e.signatureOid,e.signatureParameters)]),m.create(m.Class.UNIVERSAL,m.Type.BITSTRING,!1,String.fromCharCode(0)+e.signature)])};M.createCaStore=function(e){var t={certs:{}};t.getIssuer=function(s){var a=n(s.issuer);return a},t.addCertificate=function(s){if(typeof s==="string")s=X.pki.certificateFromPem(s);if(r(s.subject),!t.hasCertificate(s))if(s.subject.hash in t.certs){var a=t.certs[s.subject.hash];if(!X.util.isArray(a))a=[a];a.push(s),t.certs[s.subject.hash]=a}else t.certs[s.subject.hash]=s},t.hasCertificate=function(s){if(typeof s==="string")s=X.pki.certificateFromPem(s);var a=n(s.subject);if(!a)return!1;if(!X.util.isArray(a))a=[a];var c=m.toDer(M.certificateToAsn1(s)).getBytes();for(var u=0;u<a.length;++u){var l=m.toDer(M.certificateToAsn1(a[u])).getBytes();if(c===l)return!0}return!1},t.listAllCertificates=function(){var s=[];for(var a in t.certs)if(t.certs.hasOwnProperty(a)){var c=t.certs[a];if(!X.util.isArray(c))s.push(c);else for(var u=0;u<c.length;++u)s.push(c[u])}return s},t.removeCertificate=function(s){var a;if(typeof s==="string")s=X.pki.certificateFromPem(s);if(r(s.subject),!t.hasCertificate(s))return null;var c=n(s.subject);if(!X.util.isArray(c))return a=t.certs[s.subject.hash],delete t.certs[s.subject.hash],a;var u=m.toDer(M.certificateToAsn1(s)).getBytes();for(var l=0;l<c.length;++l){var f=m.toDer(M.certificateToAsn1(c[l])).getBytes();if(u===f)a=c[l],c.splice(l,1)}if(c.length===0)delete t.certs[s.subject.hash];return a};function n(s){return r(s),t.certs[s.hash]||null}function r(s){if(!s.hash){var a=X.md.sha1.create();s.attributes=M.RDNAttributesAsArray(Hn(s),a),s.hash=a.digest().toHex()}}if(e)for(var i=0;i<e.length;++i){var o=e[i];t.addCertificate(o)}return t};M.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"};var _c={0:"otherName",1:"rfc822Name",2:"dNSName",3:"x400Address",4:"directoryName",5:"ediPartyName",6:"uniformResourceIdentifier",7:"iPAddress",8:"registeredID"},Wd=1048576;function Hd(e){var t=[];for(var n=0;n<e.extensions.length;++n){var r=e.extensions[n];if(r.id!=="2.5.29.30")continue;var i;try{var o=r.value;if(typeof o==="string")o=m.fromDer(o);i=Jd(o)}catch(s){t.push({invalid:!0});continue}t.push({permitted:Kd(i.permittedSubtrees),excluded:Kd(i.excludedSubtrees)})}return t}function Kd(e){var t=[];for(var n=0;n<e.length;++n){var r=e[n],i={type:r.type,supported:Lw(r)};if(i.supported)switch(i.type){case 1:var o=r.value.lastIndexOf("@");i.local=o===-1?null:r.value.substr(0,o),i.host=r.value.substr(o+1).toLowerCase();break;case 2:case 6:i.host=r.value.toLowerCase();break;case 4:i.attributes=Yd(r.attributes);break;case 7:i.value=r.value;break}t.push(i)}return t}function Lw(e){if(e.minimum&&e.minimum!==0||"maximum"in e)return!1;switch(e.type){case 1:case 2:case 6:return typeof e.value==="string";case 4:return X.util.isArray(e.attributes);case 7:return typeof e.value==="string"&&(e.value.length===8||e.value.length===32)}return!1}function Yd(e){var t=[];for(var n=0;n<e.length;++n){var r=e[n].value;if(typeof r==="string"){if(r=r.replace(/[ \t\n\v\f\r]+/g," "),r.charAt(0)===" ")r=r.substr(1);if(r.charAt(r.length-1)===" ")r=r.substr(0,r.length-1);r=r.replace(/[A-Z]+/g,function(i){return i.toLowerCase()})}t.push({type:e[n].type,value:r})}return t}function Uw(e){if(typeof e!=="string")return!1;var t=!1;for(var n=0;n<e.length;++n){var r=e.charAt(n);if(/[a-zA-Z0-9_]/.test(r))continue;if(n>0&&n<e.length-1){if(r==="-")continue;var i=e.charAt(n+1);if(r==="."&&i!=="."&&i!=="-"&&e.charAt(n-1)!=="-"){t=!0;continue}}return!1}return t}function zw(e,t){var n={names:[],unsupported:{},types:{}},r=e.subject.attributes,i;if(r.length>0)os(n,4,r);for(i=0;i<r.length;++i)if(r[i].type===Se.emailAddress)os(n,1,r[i].value);var o=!1;for(i=0;i<e.extensions.length;++i){var s=e.extensions[i];if(s.id!=="2.5.29.17")continue;var a=s.altNames||[];for(var c=0;c<a.length;++c){var u=a[c],l=u.value;if(u.type===2)o=!0;switch(u.type){case 4:if(l=null,X.util.isArray(u.value)&&u.value.length===1&&u.value[0].type===m.Type.SEQUENCE&&X.util.isArray(u.value[0].value))l=M.RDNAttributesAsArray(u.value[0]);break;case 7:if(u.ip)l=X.util.bytesFromIP(u.ip);break}os(n,u.type,l)}}if(t&&!o){for(i=0;i<r.length;++i)if(r[i].type===Se.commonName&&Uw(r[i].value))os(n,2,r[i].value)}return n}function os(e,t,n){var r={type:t,value:n},i=!1;switch(e.types[t]=!0,t){case 1:if(i=typeof n==="string"&&n.lastIndexOf("@")!==-1,i){var o=n.lastIndexOf("@");r.local=n.substr(0,o),r.host=n.substr(o+1).toLowerCase()}break;case 2:if(i=typeof n==="string",i)r.host=n.toLowerCase();break;case 4:if(i=X.util.isArray(n),i)r.attributes=Yd(n);break;case 6:var s=typeof n==="string"&&/^[a-zA-Z][a-zA-Z0-9+.\-]*:\/\/([^\/?#]*)/.exec(n);if(s){var a=s[1].substr(s[1].lastIndexOf("@")+1);if(a.charAt(0)==="[")r.host=null;else{var c=a.indexOf(":");if(c!==-1)a=a.substr(0,c);r.host=a.toLowerCase()}i=a.length>0}break;case 7:i=typeof n==="string"&&(n.length===4||n.length===16);break}if(i)e.names.push(r);else e.unsupported[t]=!0}function Zd(e,t){if(t.length===0)return!0;if(t.charAt(0)===".")return e.length>t.length&&e.substr(e.length-t.length)===t;return e===t}function jd(e,t){var n=e.host,r=t.host,i;switch(e.type){case 1:if(t.local!==null)return(t.local===""||e.local===t.local)&&n===r;return Zd(n,r);case 2:if(r.length===0)return!0;if(r.charAt(0)===".")return n.length>r.length&&n.substr(n.length-r.length)===r;return n===r||n.length>r.length&&n.substr(n.length-r.length-1)==="."+r;case 6:return n!==null&&Zd(n,r);case 4:var o=t.attributes,s=e.attributes;if(o.length>s.length)return!1;for(i=0;i<o.length;++i)if(o[i].type!==s[i].type||o[i].value!==s[i].value)return!1;return!0;case 7:if(n=e.value,r=t.value,r.length!==n.length*2)return!1;for(i=0;i<n.length;++i){var a=r.charCodeAt(n.length+i);if((n.charCodeAt(i)&a)!==(r.charCodeAt(i)&a))return!1}return!0}return!1}function Gd(e){if(e.type===4){var t=[];for(var n=0;n<e.value.length;++n){var r=e.value[n];t.push((r.shortName||r.name||r.type)+"="+r.value)}return t.join(", ")}if(e.type===7)return X.util.bytesToIP(e.value);return e.value}function Fw(e,t,n,r,i){if(n===0)return null;var o=zw(e,r),s=o.names,a,c,u,l,f,p;for(a=0;a<n&&i.checks<=Wd;++a)l=t[a],i.checks+=(s.length+1)*(l.invalid?1:l.permitted.length+l.excluded.length+1);if(i.checks>Wd)return{message:"Certificate name constraints require too many checks.",error:M.certificateError.unsupported_certificate};for(a=0;a<n;++a){if(l=t[a],l.invalid)return{message:"Certificate name constraint could not be parsed.",error:M.certificateError.unsupported_certificate};var h=l.permitted.concat(l.excluded);for(c=0;c<h.length;++c)if(f=h[c],f.type in o.unsupported||!f.supported&&f.type in o.types)return p=_c[f.type]||String(f.type),{message:"Certificate name constraint of type "+p+" is not supported.",error:M.certificateError.unsupported_certificate,nameType:p}}for(u=0;u<s.length;++u){var d=s[u];for(a=0;a<n;++a){l=t[a];var g=!1,v=!1;for(c=0;!v&&c<l.permitted.length;++c)if(f=l.permitted[c],f.type===d.type)g=!0,v=jd(d,f);if(g&&!v)return{message:"Certificate subject name is not permitted by a name constraint.",error:M.certificateError.bad_certificate,nameValue:Gd(d),nameType:_c[d.type]};for(c=0;c<l.excluded.length;++c)if(f=l.excluded[c],f.type===d.type&&jd(d,f))return{message:"Certificate subject name is excluded by a name constraint.",error:M.certificateError.bad_certificate,nameValue:Gd(d),nameType:_c[d.type]}}}return null}M.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 o=[],s=[],a={checks:0},c=r[r.length-1];if(c&&!c.isIssuer(c)){var u=e.getIssuer(c);u=u?X.util.isArray(u)?u.slice():[u]:[];for(var l=0;l<u.length;++l){var f=Hd(u[l]);if(f.length>0){var p=!1;try{p=u[l].verify(c)}catch(W){}for(var h=0;p&&h<f.length;++h)o.push(f[h])}}}for(var d=r.length-1;d>=0;--d){s[d]=o.length;var g=d>0?Hd(r[d]):[];for(var v=0;v<g.length;++v)o.push(g[v])}var b=!0,S=null,C=0;do{var T=t.shift(),I=null,k=!1;if(i){if(i<T.validity.notBefore||i>T.validity.notAfter)S={message:"Certificate is not valid yet or has expired.",error:M.certificateError.certificate_expired,notBefore:T.validity.notBefore,notAfter:T.validity.notAfter,now:i}}if(S===null){if(I=t[0]||e.getIssuer(T),I===null){if(T.isIssuer(T))k=!0,I=T}if(I){var R=X.util.isArray(I)?I.slice():[I],V=!1;while(!V&&R.length>0){I=R.shift();try{V=I.verify(T)}catch(W){}}if(!V)S={message:"Certificate signature is invalid.",error:M.certificateError.bad_certificate}}if(S===null&&(!I||k)&&!e.hasCertificate(T))S={message:"Certificate is not trusted.",error:M.certificateError.unknown_ca}}if(S===null&&I&&!T.isIssuer(I))S={message:"Certificate issuer is invalid.",error:M.certificateError.bad_certificate};if(S===null&&(b||!T.isIssuer(T)))S=Fw(T,o,s[C],b,a);if(S===null){var D={keyUsage:!0,basicConstraints:!0,nameConstraints:!0};for(var F=0;S===null&&F<T.extensions.length;++F){var H=T.extensions[F];if(H.critical&&(!(H.name in D)||H.name==="nameConstraints"&&H.id!=="2.5.29.30"))S={message:"Certificate has an unsupported critical extension.",error:M.certificateError.unsupported_certificate}}}if(S===null&&(!b||t.length===0&&(!I||k))){var re=T.getExtension({id:"2.5.29.19"}),se=T.getExtension("keyUsage");if(se!==null){if(!se.keyCertSign||re===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:M.certificateError.bad_certificate}}if(S===null&&re===null)S={message:"Certificate is missing basicConstraints extension and cannot be used as a CA.",error:M.certificateError.bad_certificate};if(S===null&&re!==null&&!re.cA)S={message:"Certificate basicConstraints indicates the certificate is not a CA.",error:M.certificateError.bad_certificate};if(S===null&&re!==null&&"pathLenConstraint"in re){var Pe=C-1;if(Pe>re.pathLenConstraint)S={message:"Certificate basicConstraints pathLenConstraint violated.",error:M.certificateError.bad_certificate}}}var ue=S===null?!0:S.error,de=n.verify?n.verify(ue,C,r):ue;if(de===!0)S=null;else{if(ue===!0)S={message:"The application rejected the certificate.",error:M.certificateError.bad_certificate};if(de||de===0){if(typeof de==="object"&&!X.util.isArray(de)){if(de.message)S.message=de.message;if(de.error)S.error=de.error}else if(typeof de==="string")S.error=de}throw S}b=!1,++C}while(t.length>0);return!0}});var kc=le(function(K2,rp){var Ue=he();Qt();Ln();Wr();wc();Cc();Ft();Li();Mn();Te();cs();var{asn1:E,pki:xe}=Ue,zi=rp.exports=Ue.pkcs12=Ue.pkcs12||{},tp={name:"ContentInfo",tagClass:E.Class.UNIVERSAL,type:E.Type.SEQUENCE,constructed:!0,value:[{name:"ContentInfo.contentType",tagClass:E.Class.UNIVERSAL,type:E.Type.OID,constructed:!1,capture:"contentType"},{name:"ContentInfo.content",tagClass:E.Class.CONTEXT_SPECIFIC,constructed:!0,captureAsn1:"content"}]},Mw={name:"PFX",tagClass:E.Class.UNIVERSAL,type:E.Type.SEQUENCE,constructed:!0,value:[{name:"PFX.version",tagClass:E.Class.UNIVERSAL,type:E.Type.INTEGER,constructed:!1,capture:"version"},tp,{name:"PFX.macData",tagClass:E.Class.UNIVERSAL,type:E.Type.SEQUENCE,constructed:!0,optional:!0,captureAsn1:"mac",value:[{name:"PFX.macData.mac",tagClass:E.Class.UNIVERSAL,type:E.Type.SEQUENCE,constructed:!0,value:[{name:"PFX.macData.mac.digestAlgorithm",tagClass:E.Class.UNIVERSAL,type:E.Type.SEQUENCE,constructed:!0,value:[{name:"PFX.macData.mac.digestAlgorithm.algorithm",tagClass:E.Class.UNIVERSAL,type:E.Type.OID,constructed:!1,capture:"macAlgorithm"},{name:"PFX.macData.mac.digestAlgorithm.parameters",optional:!0,tagClass:E.Class.UNIVERSAL,captureAsn1:"macAlgorithmParameters"}]},{name:"PFX.macData.mac.digest",tagClass:E.Class.UNIVERSAL,type:E.Type.OCTETSTRING,constructed:!1,capture:"macDigest"}]},{name:"PFX.macData.macSalt",tagClass:E.Class.UNIVERSAL,type:E.Type.OCTETSTRING,constructed:!1,capture:"macSalt"},{name:"PFX.macData.iterations",tagClass:E.Class.UNIVERSAL,type:E.Type.INTEGER,constructed:!1,optional:!0,capture:"macIterations"}]}]},Vw={name:"SafeBag",tagClass:E.Class.UNIVERSAL,type:E.Type.SEQUENCE,constructed:!0,value:[{name:"SafeBag.bagId",tagClass:E.Class.UNIVERSAL,type:E.Type.OID,constructed:!1,capture:"bagId"},{name:"SafeBag.bagValue",tagClass:E.Class.CONTEXT_SPECIFIC,constructed:!0,captureAsn1:"bagValue"},{name:"SafeBag.bagAttributes",tagClass:E.Class.UNIVERSAL,type:E.Type.SET,constructed:!0,optional:!0,capture:"bagAttributes"}]},Ww={name:"Attribute",tagClass:E.Class.UNIVERSAL,type:E.Type.SEQUENCE,constructed:!0,value:[{name:"Attribute.attrId",tagClass:E.Class.UNIVERSAL,type:E.Type.OID,constructed:!1,capture:"oid"},{name:"Attribute.attrValues",tagClass:E.Class.UNIVERSAL,type:E.Type.SET,constructed:!0,capture:"values"}]},Hw={name:"CertBag",tagClass:E.Class.UNIVERSAL,type:E.Type.SEQUENCE,constructed:!0,value:[{name:"CertBag.certId",tagClass:E.Class.UNIVERSAL,type:E.Type.OID,constructed:!1,capture:"certId"},{name:"CertBag.certValue",tagClass:E.Class.CONTEXT_SPECIFIC,constructed:!0,value:[{name:"CertBag.certValue[0]",tagClass:E.Class.UNIVERSAL,type:E.Class.OCTETSTRING,constructed:!1,capture:"cert"}]}]};function Ui(e,t,n,r){var i=[];for(var o=0;o<e.length;o++)for(var s=0;s<e[o].safeBags.length;s++){var a=e[o].safeBags[s];if(r!==void 0&&a.type!==r)continue;if(t===null){i.push(a);continue}if(a.attributes[t]!==void 0&&a.attributes[t].indexOf(n)>=0)i.push(a)}return i}zi.pkcs12FromAsn1=function(e,t,n){if(typeof t==="string")n=t,t=!0;else if(t===void 0)t=!0;var r={},i=[];if(!E.validate(e,Mw,r,i)){var o=Error("Cannot read PKCS#12 PFX. ASN.1 object is not an PKCS#12 PFX.");throw o.errors=o,o}var s={version:r.version.charCodeAt(0),safeContents:[],getBags:function(v){var b={},S;if("localKeyId"in v)S=v.localKeyId;else if("localKeyIdHex"in v)S=Ue.util.hexToBytes(v.localKeyIdHex);if(S===void 0&&!("friendlyName"in v)&&"bagType"in v)b[v.bagType]=Ui(s.safeContents,null,null,v.bagType);if(S!==void 0)b.localKeyId=Ui(s.safeContents,"localKeyId",S,v.bagType);if("friendlyName"in v)b.friendlyName=Ui(s.safeContents,"friendlyName",v.friendlyName,v.bagType);return b},getBagsByFriendlyName:function(v,b){return Ui(s.safeContents,"friendlyName",v,b)},getBagsByLocalKeyId:function(v,b){return Ui(s.safeContents,"localKeyId",v,b)}};if(r.version.charCodeAt(0)!==3){var o=Error("PKCS#12 PFX of version other than 3 not supported.");throw o.version=r.version.charCodeAt(0),o}if(E.derToOid(r.contentType)!==xe.oids.data){var o=Error("Only PKCS#12 PFX in password integrity mode supported.");throw o.oid=E.derToOid(r.contentType),o}var a=r.content.value[0];if(a.tagClass!==E.Class.UNIVERSAL||a.type!==E.Type.OCTETSTRING)throw Error("PKCS#12 authSafe content data is not an OCTET STRING.");if(a=Ac(a),r.mac){var c=null,u=0,l=E.derToOid(r.macAlgorithm);switch(l){case xe.oids.sha1:c=Ue.md.sha1.create(),u=20;break;case xe.oids.sha256:c=Ue.md.sha256.create(),u=32;break;case xe.oids.sha384:c=Ue.md.sha384.create(),u=48;break;case xe.oids.sha512:c=Ue.md.sha512.create(),u=64;break;case xe.oids.md5:c=Ue.md.md5.create(),u=16;break}if(c===null)throw Error("PKCS#12 uses unsupported MAC algorithm: "+l);var f=new Ue.util.ByteBuffer(r.macSalt),p="macIterations"in r?parseInt(Ue.util.bytesToHex(r.macIterations),16):1;if(!(p>=1))throw Error("PKCS#12 MAC iteration count must be >= 1.");var h=zi.generateKey(n,f,3,p,u,c),d=Ue.hmac.create();d.start(c,h),d.update(a.value);var g=d.getMac();if(g.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 Kw(s,a.value,t,n),s};function Ac(e){if(e.composed||e.constructed){var t=Ue.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 Kw(e,t,n,r){if(t=E.fromDer(t,n),t.tagClass!==E.Class.UNIVERSAL||t.type!==E.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 o=t.value[i],s={},a=[];if(!E.validate(o,tp,s,a)){var c=Error("Cannot read ContentInfo.");throw c.errors=a,c}var u={encrypted:!1},l=null,f=s.content.value[0];switch(E.derToOid(s.contentType)){case xe.oids.data:if(f.tagClass!==E.Class.UNIVERSAL||f.type!==E.Type.OCTETSTRING)throw Error("PKCS#12 SafeContents Data is not an OCTET STRING.");l=Ac(f).value;break;case xe.oids.encryptedData:l=Zw(f,r),u.encrypted=!0;break;default:var c=Error("Unsupported PKCS#12 contentType.");throw c.contentType=E.derToOid(s.contentType),c}u.safeBags=jw(l,n,r),e.safeContents.push(u)}}function Zw(e,t){var n={},r=[];if(!E.validate(e,Ue.pkcs7.asn1.encryptedDataValidator,n,r)){var i=Error("Cannot read EncryptedContentInfo.");throw i.errors=r,i}var o=E.derToOid(n.contentType);if(o!==xe.oids.data){var i=Error("PKCS#12 EncryptedContentInfo ContentType is not Data.");throw i.oid=o,i}o=E.derToOid(n.encAlgorithm);var s=xe.pbe.getCipher(o,n.encParameter,t),a=Ac(n.encryptedContentAsn1),c=Ue.util.createBuffer(a.value);if(s.update(c),!s.finish())throw Error("Failed to decrypt PKCS#12 SafeContents.");return s.output.getBytes()}function jw(e,t,n){if(!t&&e.length===0)return[];if(e=E.fromDer(e,t),e.tagClass!==E.Class.UNIVERSAL||e.type!==E.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 o=e.value[i],s={},a=[];if(!E.validate(o,Vw,s,a)){var c=Error("Cannot read SafeBag.");throw c.errors=a,c}var u={type:E.derToOid(s.bagId),attributes:Gw(s.bagAttributes)};r.push(u);var l,f,p=s.bagValue.value[0];switch(u.type){case xe.oids.pkcs8ShroudedKeyBag:if(p=xe.decryptPrivateKeyInfo(p,n),p===null)throw Error("Unable to decrypt PKCS#8 ShroudedKeyBag, wrong password?");case xe.oids.keyBag:try{u.key=xe.privateKeyFromAsn1(p)}catch(d){u.key=null,u.asn1=p}continue;case xe.oids.certBag:l=Hw,f=function(){if(E.derToOid(s.certId)!==xe.oids.x509Certificate){var d=Error("Unsupported certificate type, only X.509 supported.");throw d.oid=E.derToOid(s.certId),d}var g=E.fromDer(s.cert,t);try{u.cert=xe.certificateFromAsn1(g,!0)}catch(v){u.cert=null,u.asn1=g}};break;default:var c=Error("Unsupported PKCS#12 SafeBag type.");throw c.oid=u.type,c}if(l!==void 0&&!E.validate(p,l,s,a)){var c=Error("Cannot read PKCS#12 "+l.name);throw c.errors=a,c}f()}return r}function Gw(e){var t={};if(e!==void 0)for(var n=0;n<e.length;++n){var r={},i=[];if(!E.validate(e[n],Ww,r,i)){var o=Error("Cannot read PKCS#12 BagAttribute.");throw o.errors=i,o}var s=E.derToOid(r.oid);if(xe.oids[s]===void 0)continue;t[xe.oids[s]]=[];for(var a=0;a<r.values.length;++a)t[xe.oids[s]].push(r.values[a].value)}return t}zi.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,o;if(i!==null)i=Ue.util.hexToBytes(i);else if(r.generateLocalKeyId)if(t){var s=Ue.util.isArray(t)?t[0]:t;if(typeof s==="string")s=xe.certificateFromPem(s);var a=Ue.md.sha1.create();a.update(E.toDer(xe.certificateToAsn1(s)).getBytes()),i=a.digest().getBytes()}else i=Ue.random.getBytes(20);var c=[];if(i!==null)c.push(E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.OID,!1,E.oidToDer(xe.oids.localKeyId).getBytes()),E.create(E.Class.UNIVERSAL,E.Type.SET,!0,[E.create(E.Class.UNIVERSAL,E.Type.OCTETSTRING,!1,i)])]));if("friendlyName"in r)c.push(E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.OID,!1,E.oidToDer(xe.oids.friendlyName).getBytes()),E.create(E.Class.UNIVERSAL,E.Type.SET,!0,[E.create(E.Class.UNIVERSAL,E.Type.BMPSTRING,!1,r.friendlyName)])]));if(c.length>0)o=E.create(E.Class.UNIVERSAL,E.Type.SET,!0,c);var u=[],l=[];if(t!==null)if(Ue.util.isArray(t))l=t;else l=[t];var f=[];for(var p=0;p<l.length;++p){if(t=l[p],typeof t==="string")t=xe.certificateFromPem(t);var h=p===0?o:void 0,d=xe.certificateToAsn1(t),g=E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.OID,!1,E.oidToDer(xe.oids.certBag).getBytes()),E.create(E.Class.CONTEXT_SPECIFIC,0,!0,[E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.OID,!1,E.oidToDer(xe.oids.x509Certificate).getBytes()),E.create(E.Class.CONTEXT_SPECIFIC,0,!0,[E.create(E.Class.UNIVERSAL,E.Type.OCTETSTRING,!1,E.toDer(d).getBytes())])])]),h]);f.push(g)}if(f.length>0){var v=E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,f),b=E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.OID,!1,E.oidToDer(xe.oids.data).getBytes()),E.create(E.Class.CONTEXT_SPECIFIC,0,!0,[E.create(E.Class.UNIVERSAL,E.Type.OCTETSTRING,!1,E.toDer(v).getBytes())])]);u.push(b)}var S=null;if(e!==null){var C=xe.wrapRsaPrivateKey(xe.privateKeyToAsn1(e));if(n===null)S=E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.OID,!1,E.oidToDer(xe.oids.keyBag).getBytes()),E.create(E.Class.CONTEXT_SPECIFIC,0,!0,[C]),o]);else S=E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.OID,!1,E.oidToDer(xe.oids.pkcs8ShroudedKeyBag).getBytes()),E.create(E.Class.CONTEXT_SPECIFIC,0,!0,[xe.encryptPrivateKeyInfo(C,n,r)]),o]);var T=E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[S]),I=E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.OID,!1,E.oidToDer(xe.oids.data).getBytes()),E.create(E.Class.CONTEXT_SPECIFIC,0,!0,[E.create(E.Class.UNIVERSAL,E.Type.OCTETSTRING,!1,E.toDer(T).getBytes())])]);u.push(I)}var k=E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,u),R;if(r.useMac){var a=Ue.md.sha1.create(),V=new Ue.util.ByteBuffer(Ue.random.getBytes(r.saltSize)),D=r.count,e=zi.generateKey(n,V,3,D,20),F=Ue.hmac.create();F.start(a,e),F.update(E.toDer(k).getBytes());var H=F.getMac();R=E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.OID,!1,E.oidToDer(xe.oids.sha1).getBytes()),E.create(E.Class.UNIVERSAL,E.Type.NULL,!1,"")]),E.create(E.Class.UNIVERSAL,E.Type.OCTETSTRING,!1,H.getBytes())]),E.create(E.Class.UNIVERSAL,E.Type.OCTETSTRING,!1,V.getBytes()),E.create(E.Class.UNIVERSAL,E.Type.INTEGER,!1,E.integerToDer(D).getBytes())])}return E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.INTEGER,!1,E.integerToDer(3).getBytes()),E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.OID,!1,E.oidToDer(xe.oids.data).getBytes()),E.create(E.Class.CONTEXT_SPECIFIC,0,!0,[E.create(E.Class.UNIVERSAL,E.Type.OCTETSTRING,!1,E.toDer(k).getBytes())])]),R])};zi.generateKey=Ue.pbe.generatePkcs12Key});var Pc=le(function(Z2,np){var jr=he();Qt();Wr();Cc();fn();Xo();kc();is();Li();Te();cs();var Ic=jr.asn1,Kn=np.exports=jr.pki=jr.pki||{};Kn.pemToDer=function(e){var t=jr.pem.decode(e)[0];if(t.procType&&t.procType.type==="ENCRYPTED")throw Error("Could not convert PEM to DER; PEM is encrypted.");return jr.util.createBuffer(t.body)};Kn.privateKeyFromPem=function(e){var t=jr.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=Ic.fromDer(t.body);return Kn.privateKeyFromAsn1(r)};Kn.privateKeyToPem=function(e,t){var n={type:"RSA PRIVATE KEY",body:Ic.toDer(Kn.privateKeyToAsn1(e)).getBytes()};return jr.pem.encode(n,{maxline:t})};Kn.privateKeyInfoToPem=function(e,t){var n={type:"PRIVATE KEY",body:Ic.toDer(e).getBytes()};return jr.pem.encode(n,{maxline:t})}});var Oc=le(function(j2,fp){var U=he();Qt();Ln();Zo();fn();Pc();Ft();Mn();Te();var fs=function(e,t,n,r){var i=U.util.createBuffer(),o=e.length>>1,s=o+(e.length&1),a=e.substr(0,s),c=e.substr(o,s),u=U.util.createBuffer(),l=U.hmac.create();n=t+n;var f=Math.ceil(r/16),p=Math.ceil(r/20);l.start("MD5",a);var h=U.util.createBuffer();u.putBytes(n);for(var d=0;d<f;++d)l.start(null,null),l.update(u.getBytes()),u.putBuffer(l.digest()),l.start(null,null),l.update(u.bytes()+n),h.putBuffer(l.digest());l.start("SHA1",c);var g=U.util.createBuffer();u.clear(),u.putBytes(n);for(var d=0;d<p;++d)l.start(null,null),l.update(u.getBytes()),u.putBuffer(l.digest()),l.start(null,null),l.update(u.bytes()+n),g.putBuffer(l.digest());return i.putBytes(U.util.xorBytes(h.getBytes(),g.getBytes(),r)),i},qw=function(e,t,n){var r=U.hmac.create();r.start("SHA1",e);var i=U.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()},Xw=function(e,t,n){var r=!1;try{var i=e.deflate(t.fragment.getBytes());t.fragment=U.util.createBuffer(i),t.length=i.length,r=!0}catch(o){}return r},Jw=function(e,t,n){var r=!1;try{var i=e.inflate(t.fragment.getBytes());t.fragment=U.util.createBuffer(i),t.length=i.length,r=!0}catch(o){}return r},Rt=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 U.util.createBuffer(e.getBytes(n))},Ht=function(e,t,n){e.putInt(n.length(),t<<3),e.putBuffer(n)},x={};x.Versions={TLS_1_0:{major:3,minor:1},TLS_1_1:{major:3,minor:2},TLS_1_2:{major:3,minor:3}};x.SupportedVersions=[x.Versions.TLS_1_1,x.Versions.TLS_1_0];x.Version=x.SupportedVersions[0];x.MaxFragment=15360;x.ConnectionEnd={server:0,client:1};x.PRFAlgorithm={tls_prf_sha256:0};x.BulkCipherAlgorithm={none:null,rc4:0,des3:1,aes:2};x.CipherType={stream:0,block:1,aead:2};x.MACAlgorithm={none:null,hmac_md5:0,hmac_sha1:1,hmac_sha256:2,hmac_sha384:3,hmac_sha512:4};x.CompressionMethod={none:0,deflate:1};x.ContentType={change_cipher_spec:20,alert:21,handshake:22,application_data:23,heartbeat:24};x.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};x.Alert={};x.Alert.Level={warning:1,fatal:2};x.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};x.HeartbeatMessageType={heartbeat_request:1,heartbeat_response:2};x.CipherSuites={};x.getCipherSuite=function(e){var t=null;for(var n in x.CipherSuites){var r=x.CipherSuites[n];if(r.id[0]===e.charCodeAt(0)&&r.id[1]===e.charCodeAt(1)){t=r;break}}return t};x.handleUnexpected=function(e,t){var n=!e.open&&e.entity===x.ConnectionEnd.client;if(!n)e.error(e,{message:"Unexpected message. Received TLS record out of order.",send:!0,alert:{level:x.Alert.Level.fatal,description:x.Alert.Description.unexpected_message}})};x.handleHelloRequest=function(e,t,n){if(!e.handshaking&&e.handshakes>0)x.queue(e,x.createAlert(e,{level:x.Alert.Level.warning,description:x.Alert.Description.no_renegotiation})),x.flush(e);e.process()};x.parseHelloMessage=function(e,t,n){var r=null,i=e.entity===x.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:x.Alert.Level.fatal,description:x.Alert.Description.illegal_parameter}});else{var o=t.fragment,s=o.length();if(r={version:{major:o.getByte(),minor:o.getByte()},random:U.util.createBuffer(o.getBytes(32)),session_id:Rt(o,1),extensions:[]},i)r.cipher_suite=o.getBytes(2),r.compression_method=o.getByte();else r.cipher_suites=Rt(o,2),r.compression_methods=Rt(o,1);if(s=n-(s-o.length()),s>0){var a=Rt(o,2);while(a.length()>0)r.extensions.push({type:[a.getByte(),a.getByte()],data:Rt(a,2)});if(!i)for(var c=0;c<r.extensions.length;++c){var u=r.extensions[c];if(u.type[0]===0&&u.type[1]===0){var l=Rt(u.data,2);while(l.length()>0){var f=l.getByte();if(f!==0)break;e.session.extensions.server_name.serverNameList.push(Rt(l,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:x.Alert.Level.fatal,description:x.Alert.Description.protocol_version}})}if(i)e.session.cipherSuite=x.getCipherSuite(r.cipher_suite);else{var p=U.util.createBuffer(r.cipher_suites.bytes());while(p.length()>0)if(e.session.cipherSuite=x.getCipherSuite(p.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:x.Alert.Level.fatal,description:x.Alert.Description.handshake_failure},cipherSuite:U.util.bytesToHex(r.cipher_suite)});if(i){if(r.compression_method!==x.CompressionMethod.none)return e.error(e,{message:"Unsupported compression method.",send:!0,alert:{level:x.Alert.Level.fatal,description:x.Alert.Description.illegal_parameter}});e.session.compressionMethod=r.compression_method}else e.session.compressionMethod=x.CompressionMethod.none}return r};x.createSecurityParameters=function(e,t){var n=e.entity===x.ConnectionEnd.client,r=t.random.bytes(),i=n?e.session.sp.client_random:r,o=n?r:x.createRandom().getBytes();e.session.sp={entity:e.entity,prf_algorithm:x.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:o}};x.handleServerHello=function(e,t,n){var r=x.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:x.Alert.Level.fatal,description:x.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=sp,e.session.resuming=!0,e.session.sp.server_random=r.random.bytes();else e.expect=Yw,e.session.resuming=!1,x.createSecurityParameters(e,r);e.session.id=i,e.process()};x.handleClientHello=function(e,t,n){var r=x.parseHelloMessage(e,t,n);if(e.fail)return;var i=r.session_id.bytes(),o=null;if(e.sessionCache){if(o=e.sessionCache.getSession(i),o===null)i="";else if(o.version.major!==r.version.major||o.version.minor>r.version.minor)o=null,i=""}if(i.length===0)i=U.random.getBytes(32);if(e.session.id=i,e.session.clientHelloVersion=r.version,e.session.sp={},o)e.version=e.session.version=o.version,e.session.sp=o.sp;else{var s;for(var a=1;a<x.SupportedVersions.length;++a)if(s=x.SupportedVersions[a],s.minor<=r.version.minor)break;e.version={major:s.major,minor:s.minor},e.session.version=e.version}if(o!==null)e.expect=Dc,e.session.resuming=!0,e.session.sp.client_random=r.random.bytes();else e.expect=e.verifyClient!==!1?s1:Nc,e.session.resuming=!1,x.createSecurityParameters(e,r);if(e.open=!0,x.queue(e,x.createRecord(e,{type:x.ContentType.handshake,data:x.createServerHello(e)})),e.session.resuming)x.queue(e,x.createRecord(e,{type:x.ContentType.change_cipher_spec,data:x.createChangeCipherSpec()})),e.state.pending=x.createConnectionState(e),e.state.current.write=e.state.pending.write,x.queue(e,x.createRecord(e,{type:x.ContentType.handshake,data:x.createFinished(e)}));else if(x.queue(e,x.createRecord(e,{type:x.ContentType.handshake,data:x.createCertificate(e)})),!e.fail){if(x.queue(e,x.createRecord(e,{type:x.ContentType.handshake,data:x.createServerKeyExchange(e)})),e.verifyClient!==!1)x.queue(e,x.createRecord(e,{type:x.ContentType.handshake,data:x.createCertificateRequest(e)}));x.queue(e,x.createRecord(e,{type:x.ContentType.handshake,data:x.createServerHelloDone(e)}))}x.flush(e),e.process()};x.handleCertificate=function(e,t,n){if(n<3)return e.error(e,{message:"Invalid Certificate message. Message too short.",send:!0,alert:{level:x.Alert.Level.fatal,description:x.Alert.Description.illegal_parameter}});var r=t.fragment,i={certificate_list:Rt(r,3)},o,s,a=[];try{while(i.certificate_list.length()>0)o=Rt(i.certificate_list,3),s=U.asn1.fromDer(o),o=U.pki.certificateFromAsn1(s,!0),a.push(o)}catch(u){return e.error(e,{message:"Could not parse certificate list.",cause:u,send:!0,alert:{level:x.Alert.Level.fatal,description:x.Alert.Description.bad_certificate}})}var c=e.entity===x.ConnectionEnd.client;if((c||e.verifyClient===!0)&&a.length===0)e.error(e,{message:c?"No server certificate provided.":"No client certificate provided.",send:!0,alert:{level:x.Alert.Level.fatal,description:x.Alert.Description.illegal_parameter}});else if(a.length===0)e.expect=c?ip:Nc;else{if(c)e.session.serverCertificate=a[0];else e.session.clientCertificate=a[0];if(x.verifyCertificateChain(e,a))e.expect=c?ip:Nc}e.process()};x.handleServerKeyExchange=function(e,t,n){if(n>0)return e.error(e,{message:"Invalid key parameters. Only RSA is supported.",send:!0,alert:{level:x.Alert.Level.fatal,description:x.Alert.Description.unsupported_certificate}});e.expect=e1,e.process()};x.handleClientKeyExchange=function(e,t,n){if(n<48)return e.error(e,{message:"Invalid key parameters. Only RSA is supported.",send:!0,alert:{level:x.Alert.Level.fatal,description:x.Alert.Description.unsupported_certificate}});var r=t.fragment,i={enc_pre_master_secret:Rt(r,2).getBytes()},o=null;if(e.getPrivateKey)try{o=e.getPrivateKey(e,e.session.serverCertificate),o=U.pki.privateKeyFromPem(o)}catch(c){e.error(e,{message:"Could not get private key.",cause:c,send:!0,alert:{level:x.Alert.Level.fatal,description:x.Alert.Description.internal_error}})}if(o===null)return e.error(e,{message:"No private key set.",send:!0,alert:{level:x.Alert.Level.fatal,description:x.Alert.Description.internal_error}});try{var s=e.session.sp;s.pre_master_secret=o.decrypt(i.enc_pre_master_secret);var a=e.session.clientHelloVersion;if(a.major!==s.pre_master_secret.charCodeAt(0)||a.minor!==s.pre_master_secret.charCodeAt(1))throw Error("TLS version rollback attack detected.")}catch(c){s.pre_master_secret=U.random.getBytes(48)}if(e.expect=Dc,e.session.clientCertificate!==null)e.expect=a1;e.process()};x.handleCertificateRequest=function(e,t,n){if(n<3)return e.error(e,{message:"Invalid CertificateRequest. Message too short.",send:!0,alert:{level:x.Alert.Level.fatal,description:x.Alert.Description.illegal_parameter}});var r=t.fragment,i={certificate_types:Rt(r,1),certificate_authorities:Rt(r,2)};e.session.certificateRequest=i,e.expect=t1,e.process()};x.handleCertificateVerify=function(e,t,n){if(n<2)return e.error(e,{message:"Invalid CertificateVerify. Message too short.",send:!0,alert:{level:x.Alert.Level.fatal,description:x.Alert.Description.illegal_parameter}});var r=t.fragment;r.read-=4;var i=r.bytes();r.read+=4;var o={signature:Rt(r,2).getBytes()},s=U.util.createBuffer();s.putBuffer(e.session.md5.digest()),s.putBuffer(e.session.sha1.digest()),s=s.getBytes();try{var a=e.session.clientCertificate;if(!a.publicKey.verify(s,o.signature,"NONE"))throw Error("CertificateVerify signature does not match.");e.session.md5.update(i),e.session.sha1.update(i)}catch(c){return e.error(e,{message:"Bad signature in CertificateVerify.",send:!0,alert:{level:x.Alert.Level.fatal,description:x.Alert.Description.handshake_failure}})}e.expect=Dc,e.process()};x.handleServerHelloDone=function(e,t,n){if(n>0)return e.error(e,{message:"Invalid ServerHelloDone message. Invalid length.",send:!0,alert:{level:x.Alert.Level.fatal,description:x.Alert.Description.record_overflow}});if(e.session.serverCertificate===null){var r={message:"No server certificate provided. Not enough security.",send:!0,alert:{level:x.Alert.Level.fatal,description:x.Alert.Description.insufficient_security}},i=0,o=e.verify(e,r.alert.description,i,[]);if(o!==!0){if(o||o===0){if(typeof o==="object"&&!U.util.isArray(o)){if(o.message)r.message=o.message;if(o.alert)r.alert.description=o.alert}else if(typeof o==="number")r.alert.description=o}}return e.error(e,r)}if(e.session.certificateRequest!==null)t=x.createRecord(e,{type:x.ContentType.handshake,data:x.createCertificate(e)}),x.queue(e,t);t=x.createRecord(e,{type:x.ContentType.handshake,data:x.createClientKeyExchange(e)}),x.queue(e,t),e.expect=i1;var s=function(a,c){if(a.session.certificateRequest!==null&&a.session.clientCertificate!==null)x.queue(a,x.createRecord(a,{type:x.ContentType.handshake,data:x.createCertificateVerify(a,c)}));x.queue(a,x.createRecord(a,{type:x.ContentType.change_cipher_spec,data:x.createChangeCipherSpec()})),a.state.pending=x.createConnectionState(a),a.state.current.write=a.state.pending.write,x.queue(a,x.createRecord(a,{type:x.ContentType.handshake,data:x.createFinished(a)})),a.expect=sp,x.flush(a),a.process()};if(e.session.certificateRequest===null||e.session.clientCertificate===null)return s(e,null);x.getClientSignature(e,s)};x.handleChangeCipherSpec=function(e,t){if(t.fragment.getByte()!==1)return e.error(e,{message:"Invalid ChangeCipherSpec message received.",send:!0,alert:{level:x.Alert.Level.fatal,description:x.Alert.Description.illegal_parameter}});var n=e.entity===x.ConnectionEnd.client;if(e.session.resuming&&n||!e.session.resuming&&!n)e.state.pending=x.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?r1:c1,e.process()};x.handleFinished=function(e,t,n){var r=t.fragment;r.read-=4;var i=r.bytes();r.read+=4;var o=t.fragment.getBytes();r=U.util.createBuffer(),r.putBuffer(e.session.md5.digest()),r.putBuffer(e.session.sha1.digest());var s=e.entity===x.ConnectionEnd.client,a=s?"server finished":"client finished",c=e.session.sp,u=12,l=fs;if(r=l(c.master_secret,a,r.getBytes(),u),r.getBytes()!==o)return e.error(e,{message:"Invalid verify_data in Finished message.",send:!0,alert:{level:x.Alert.Level.fatal,description:x.Alert.Description.decrypt_error}});if(e.session.md5.update(i),e.session.sha1.update(i),e.session.resuming&&s||!e.session.resuming&&!s)x.queue(e,x.createRecord(e,{type:x.ContentType.change_cipher_spec,data:x.createChangeCipherSpec()})),e.state.current.write=e.state.pending.write,e.state.pending=null,x.queue(e,x.createRecord(e,{type:x.ContentType.handshake,data:x.createFinished(e)}));e.expect=s?n1:u1,e.handshaking=!1,++e.handshakes,e.peerCertificate=s?e.session.serverCertificate:e.session.clientCertificate,x.flush(e),e.isConnected=!0,e.connected(e),e.process()};x.handleAlert=function(e,t){var n=t.fragment,r={level:n.getByte(),description:n.getByte()},i;switch(r.description){case x.Alert.Description.close_notify:i="Connection closed.";break;case x.Alert.Description.unexpected_message:i="Unexpected message.";break;case x.Alert.Description.bad_record_mac:i="Bad record MAC.";break;case x.Alert.Description.decryption_failed:i="Decryption failed.";break;case x.Alert.Description.record_overflow:i="Record overflow.";break;case x.Alert.Description.decompression_failure:i="Decompression failed.";break;case x.Alert.Description.handshake_failure:i="Handshake failure.";break;case x.Alert.Description.bad_certificate:i="Bad certificate.";break;case x.Alert.Description.unsupported_certificate:i="Unsupported certificate.";break;case x.Alert.Description.certificate_revoked:i="Certificate revoked.";break;case x.Alert.Description.certificate_expired:i="Certificate expired.";break;case x.Alert.Description.certificate_unknown:i="Certificate unknown.";break;case x.Alert.Description.illegal_parameter:i="Illegal parameter.";break;case x.Alert.Description.unknown_ca:i="Unknown certificate authority.";break;case x.Alert.Description.access_denied:i="Access denied.";break;case x.Alert.Description.decode_error:i="Decode error.";break;case x.Alert.Description.decrypt_error:i="Decrypt error.";break;case x.Alert.Description.export_restriction:i="Export restriction.";break;case x.Alert.Description.protocol_version:i="Unsupported protocol version.";break;case x.Alert.Description.insufficient_security:i="Insufficient security.";break;case x.Alert.Description.internal_error:i="Internal error.";break;case x.Alert.Description.user_canceled:i="User canceled.";break;case x.Alert.Description.no_renegotiation:i="Renegotiation not supported.";break;default:i="Unknown error.";break}if(r.description===x.Alert.Description.close_notify)return e.close();e.error(e,{message:i,send:!1,origin:e.entity===x.ConnectionEnd.client?"server":"client",alert:r}),e.process()};x.handleHandshake=function(e,t){var n=t.fragment,r=n.getByte(),i=n.getInt24();if(i>n.length())return e.fragmented=t,t.fragment=U.util.createBuffer(),n.read-=4,e.process();e.fragmented=null,n.read-=4;var o=n.bytes(i+4);if(n.read+=4,r in ls[e.entity][e.expect]&&(e.session||e.entity===x.ConnectionEnd.server)){if(e.entity===x.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:U.md.md5.create(),sha1:U.md.sha1.create()};if(r!==x.HandshakeType.hello_request&&r!==x.HandshakeType.certificate_verify&&r!==x.HandshakeType.finished)e.session.md5.update(o),e.session.sha1.update(o);ls[e.entity][e.expect][r](e,t,i)}else x.handleUnexpected(e,t)};x.handleApplicationData=function(e,t){e.data.putBuffer(t.fragment),e.dataReady(e),e.process()};x.handleHeartbeat=function(e,t){var n=t.fragment,r=n.getByte(),i=n.getInt16(),o=n.getBytes(i);if(r===x.HeartbeatMessageType.heartbeat_request){if(e.handshakes===0||e.handshaking||i>o.length)return e.process();x.queue(e,x.createRecord(e,{type:x.ContentType.heartbeat,data:x.createHeartbeat(x.HeartbeatMessageType.heartbeat_response,o)})),x.flush(e)}else if(r===x.HeartbeatMessageType.heartbeat_response){if(o!==e.expectedHeartbeatPayload)return e.process();if(e.heartbeatReceived)e.heartbeatReceived(e,U.util.createBuffer(o))}e.process()};var Qw=0,Yw=1,ip=2,e1=3,t1=4,sp=5,r1=6,n1=7,i1=8,o1=0,s1=1,Nc=2,a1=3,Dc=4,c1=5,u1=6,{handleUnexpected:y,handleChangeCipherSpec:ap,handleAlert:ht,handleHandshake:wt,handleApplicationData:cp,handleHeartbeat:mt}=x,$c=[];$c[x.ConnectionEnd.client]=[[y,ht,wt,y,mt],[y,ht,wt,y,mt],[y,ht,wt,y,mt],[y,ht,wt,y,mt],[y,ht,wt,y,mt],[ap,ht,y,y,mt],[y,ht,wt,y,mt],[y,ht,wt,cp,mt],[y,ht,wt,y,mt]];$c[x.ConnectionEnd.server]=[[y,ht,wt,y,mt],[y,ht,wt,y,mt],[y,ht,wt,y,mt],[y,ht,wt,y,mt],[ap,ht,y,y,mt],[y,ht,wt,y,mt],[y,ht,wt,cp,mt],[y,ht,wt,y,mt]];var{handleHelloRequest:Gr,handleServerHello:l1,handleCertificate:up,handleServerKeyExchange:op,handleCertificateRequest:Rc,handleServerHelloDone:us,handleFinished:lp}=x,ls=[];ls[x.ConnectionEnd.client]=[[y,y,l1,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y],[Gr,y,y,y,y,y,y,y,y,y,y,up,op,Rc,us,y,y,y,y,y,y],[Gr,y,y,y,y,y,y,y,y,y,y,y,op,Rc,us,y,y,y,y,y,y],[Gr,y,y,y,y,y,y,y,y,y,y,y,y,Rc,us,y,y,y,y,y,y],[Gr,y,y,y,y,y,y,y,y,y,y,y,y,y,us,y,y,y,y,y,y],[Gr,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y],[Gr,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,lp],[Gr,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y],[Gr,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y]];var{handleClientHello:f1,handleClientKeyExchange:d1,handleCertificateVerify:p1}=x;ls[x.ConnectionEnd.server]=[[y,f1,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y],[y,y,y,y,y,y,y,y,y,y,y,up,y,y,y,y,y,y,y,y,y],[y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,d1,y,y,y,y],[y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,p1,y,y,y,y,y],[y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y],[y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,lp],[y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y],[y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y,y]];x.generateKeys=function(e,t){var n=fs,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,o=e.version.major===x.Versions.TLS_1_0.major&&e.version.minor===x.Versions.TLS_1_0.minor;if(o)i+=2*t.fixed_iv_length;var s=n(t.master_secret,"key expansion",r,i),a={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(o)a.client_write_IV=s.getBytes(t.fixed_iv_length),a.server_write_IV=s.getBytes(t.fixed_iv_length);return a};x.createConnectionState=function(e){var t=e.entity===x.ConnectionEnd.client,n=function(){var o={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(o.sequenceNumber[1]===4294967295)o.sequenceNumber[1]=0,++o.sequenceNumber[0];else++o.sequenceNumber[1]}};return o},r={read:n(),write:n()};if(r.read.update=function(o,s){if(!r.read.cipherFunction(s,r.read))o.error(o,{message:"Could not decrypt record or bad MAC.",send:!0,alert:{level:x.Alert.Level.fatal,description:x.Alert.Description.bad_record_mac}});else if(!r.read.compressFunction(o,s,r.read))o.error(o,{message:"Could not decompress record.",send:!0,alert:{level:x.Alert.Level.fatal,description:x.Alert.Description.decompression_failure}});return!o.fail},r.write.update=function(o,s){if(!r.write.compressFunction(o,s,r.write))o.error(o,{message:"Could not compress record.",send:!1,alert:{level:x.Alert.Level.fatal,description:x.Alert.Description.internal_error}});else if(!r.write.cipherFunction(s,r.write))o.error(o,{message:"Could not encrypt record.",send:!1,alert:{level:x.Alert.Level.fatal,description:x.Alert.Description.internal_error}});return!o.fail},e.session){var i=e.session.sp;switch(e.session.cipherSuite.initSecurityParameters(i),i.keys=x.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 x.CompressionMethod.none:break;case x.CompressionMethod.deflate:r.read.compressFunction=Jw,r.write.compressFunction=Xw;break;default:throw Error("Unsupported compression algorithm.")}}return r};x.createRandom=function(){var e=new Date,t=+e+e.getTimezoneOffset()*60000,n=U.util.createBuffer();return n.putInt32(t),n.putBytes(U.random.getBytes(28)),n};x.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};x.createAlert=function(e,t){var n=U.util.createBuffer();return n.putByte(t.level),n.putByte(t.description),x.createRecord(e,{type:x.ContentType.alert,data:n})};x.createClientHello=function(e){e.session.clientHelloVersion={major:e.version.major,minor:e.version.minor};var t=U.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(),o=U.util.createBuffer();o.putByte(x.CompressionMethod.none);var s=o.length(),a=U.util.createBuffer();if(e.virtualHost){var c=U.util.createBuffer();c.putByte(0),c.putByte(0);var u=U.util.createBuffer();u.putByte(0),Ht(u,2,U.util.createBuffer(e.virtualHost));var l=U.util.createBuffer();Ht(l,2,u),Ht(c,2,l),a.putBuffer(c)}var f=a.length();if(f>0)f+=2;var p=e.session.id,h=p.length+1+2+4+28+2+i+1+s+f,d=U.util.createBuffer();if(d.putByte(x.HandshakeType.client_hello),d.putInt24(h),d.putByte(e.version.major),d.putByte(e.version.minor),d.putBytes(e.session.sp.client_random),Ht(d,1,U.util.createBuffer(p)),Ht(d,2,t),Ht(d,1,o),f>0)Ht(d,2,a);return d};x.createServerHello=function(e){var t=e.session.id,n=t.length+1+2+4+28+2+1,r=U.util.createBuffer();return r.putByte(x.HandshakeType.server_hello),r.putInt24(n),r.putByte(e.version.major),r.putByte(e.version.minor),r.putBytes(e.session.sp.server_random),Ht(r,1,U.util.createBuffer(t)),r.putByte(e.session.cipherSuite.id[0]),r.putByte(e.session.cipherSuite.id[1]),r.putByte(e.session.compressionMethod),r};x.createCertificate=function(e){var t=e.entity===x.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=U.util.createBuffer();if(n!==null)try{if(!U.util.isArray(n))n=[n];var o=null;for(var s=0;s<n.length;++s){var a=U.pem.decode(n[s])[0];if(a.type!=="CERTIFICATE"&&a.type!=="X509 CERTIFICATE"&&a.type!=="TRUSTED CERTIFICATE"){var c=Error('Could not convert certificate from PEM; PEM header type is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".');throw c.headerType=a.type,c}if(a.procType&&a.procType.type==="ENCRYPTED")throw Error("Could not convert certificate from PEM; PEM is encrypted.");var u=U.util.createBuffer(a.body);if(o===null)o=U.asn1.fromDer(u.bytes(),!1);var l=U.util.createBuffer();Ht(l,3,u),i.putBuffer(l)}if(n=U.pki.certificateFromAsn1(o),t)e.session.clientCertificate=n;else e.session.serverCertificate=n}catch(h){return e.error(e,{message:"Could not send certificate list.",cause:h,send:!0,alert:{level:x.Alert.Level.fatal,description:x.Alert.Description.bad_certificate}})}var f=3+i.length(),p=U.util.createBuffer();return p.putByte(x.HandshakeType.certificate),p.putInt24(f),Ht(p,3,i),p};x.createClientKeyExchange=function(e){var t=U.util.createBuffer();t.putByte(e.session.clientHelloVersion.major),t.putByte(e.session.clientHelloVersion.minor),t.putBytes(U.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,o=U.util.createBuffer();return o.putByte(x.HandshakeType.client_key_exchange),o.putInt24(i),o.putInt16(t.length),o.putBytes(t),o};x.createServerKeyExchange=function(e){var t=0,n=U.util.createBuffer();if(t>0)n.putByte(x.HandshakeType.server_key_exchange),n.putInt24(t);return n};x.getClientSignature=function(e,t){var n=U.util.createBuffer();n.putBuffer(e.session.md5.digest()),n.putBuffer(e.session.sha1.digest()),n=n.getBytes(),e.getSignature=e.getSignature||function(r,i,o){var s=null;if(r.getPrivateKey)try{s=r.getPrivateKey(r,r.session.clientCertificate),s=U.pki.privateKeyFromPem(s)}catch(a){r.error(r,{message:"Could not get private key.",cause:a,send:!0,alert:{level:x.Alert.Level.fatal,description:x.Alert.Description.internal_error}})}if(s===null)r.error(r,{message:"No private key set.",send:!0,alert:{level:x.Alert.Level.fatal,description:x.Alert.Description.internal_error}});else i=s.sign(i,null);o(r,i)},e.getSignature(e,n,t)};x.createCertificateVerify=function(e,t){var n=t.length+2,r=U.util.createBuffer();return r.putByte(x.HandshakeType.certificate_verify),r.putInt24(n),r.putInt16(t.length),r.putBytes(t),r};x.createCertificateRequest=function(e){var t=U.util.createBuffer();t.putByte(1);var n=U.util.createBuffer();for(var r in e.caStore.certs){var i=e.caStore.certs[r],o=U.pki.distinguishedNameToAsn1(i.subject),s=U.asn1.toDer(o);n.putInt16(s.length()),n.putBuffer(s)}var a=1+t.length()+2+n.length(),c=U.util.createBuffer();return c.putByte(x.HandshakeType.certificate_request),c.putInt24(a),Ht(c,1,t),Ht(c,2,n),c};x.createServerHelloDone=function(e){var t=U.util.createBuffer();return t.putByte(x.HandshakeType.server_hello_done),t.putInt24(0),t};x.createChangeCipherSpec=function(){var e=U.util.createBuffer();return e.putByte(1),e};x.createFinished=function(e){var t=U.util.createBuffer();t.putBuffer(e.session.md5.digest()),t.putBuffer(e.session.sha1.digest());var n=e.entity===x.ConnectionEnd.client,r=e.session.sp,i=12,o=fs,s=n?"client finished":"server finished";t=o(r.master_secret,s,t.getBytes(),i);var a=U.util.createBuffer();return a.putByte(x.HandshakeType.finished),a.putInt24(t.length()),a.putBuffer(t),a};x.createHeartbeat=function(e,t,n){if(typeof n>"u")n=t.length;var r=U.util.createBuffer();r.putByte(e),r.putInt16(n),r.putBytes(t);var i=r.length(),o=Math.max(16,i-n-3);return r.putBytes(U.random.getBytes(o)),r};x.queue=function(e,t){if(!t)return;if(t.fragment.length()===0){if(t.type===x.ContentType.handshake||t.type===x.ContentType.alert||t.type===x.ContentType.change_cipher_spec)return}if(t.type===x.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()<=x.MaxFragment)r=[t];else{r=[];var i=t.fragment.bytes();while(i.length>x.MaxFragment)r.push(x.createRecord(e,{type:t.type,data:U.util.createBuffer(i.slice(0,x.MaxFragment))})),i=i.slice(x.MaxFragment);if(i.length>0)r.push(x.createRecord(e,{type:t.type,data:U.util.createBuffer(i)}))}for(var o=0;o<r.length&&!e.fail;++o){var s=r[o],a=e.state.current.write;if(a.update(e,s))e.records.push(s)}};x.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 Bc=function(e){switch(e){case!0:return!0;case U.pki.certificateError.bad_certificate:return x.Alert.Description.bad_certificate;case U.pki.certificateError.unsupported_certificate:return x.Alert.Description.unsupported_certificate;case U.pki.certificateError.certificate_revoked:return x.Alert.Description.certificate_revoked;case U.pki.certificateError.certificate_expired:return x.Alert.Description.certificate_expired;case U.pki.certificateError.certificate_unknown:return x.Alert.Description.certificate_unknown;case U.pki.certificateError.unknown_ca:return x.Alert.Description.unknown_ca;default:return x.Alert.Description.bad_certificate}},h1=function(e){switch(e){case!0:return!0;case x.Alert.Description.bad_certificate:return U.pki.certificateError.bad_certificate;case x.Alert.Description.unsupported_certificate:return U.pki.certificateError.unsupported_certificate;case x.Alert.Description.certificate_revoked:return U.pki.certificateError.certificate_revoked;case x.Alert.Description.certificate_expired:return U.pki.certificateError.certificate_expired;case x.Alert.Description.certificate_unknown:return U.pki.certificateError.certificate_unknown;case x.Alert.Description.unknown_ca:return U.pki.certificateError.unknown_ca;default:return U.pki.certificateError.bad_certificate}};x.verifyCertificateChain=function(e,t){try{var n={};for(var r in e.verifyOptions)n[r]=e.verifyOptions[r];n.verify=function(o,s,a){var c=Bc(o),u=e.verify(e,o,s,a);if(u!==!0){if(typeof u==="object"&&!U.util.isArray(u)){var l=Error("The application rejected the certificate.");if(l.send=!0,l.alert={level:x.Alert.Level.fatal,description:x.Alert.Description.bad_certificate},u.message)l.message=u.message;if(u.alert)l.alert.description=u.alert;throw l}if(u!==o)u=h1(u)}return u},U.pki.verifyCertificateChain(e.caStore,t,n)}catch(o){var i=o;if(typeof i!=="object"||U.util.isArray(i))i={send:!0,alert:{level:x.Alert.Level.fatal,description:Bc(o)}};if(!("send"in i))i.send=!0;if(!("alert"in i))i.alert={level:x.Alert.Level.fatal,description:Bc(i.error)};e.error(e,i)}return!e.fail};x.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 o=null,s=null;if(i)s=U.util.bytesToHex(i);else if(n.order.length>0)s=n.order[0];if(s!==null&&s in n.cache){o=n.cache[s],delete n.cache[s];for(var a in n.order)if(n.order[a]===s){n.order.splice(a,1);break}}return o},n.setSession=function(i,o){if(n.order.length===n.capacity){var s=n.order.shift();delete n.cache[s]}var s=U.util.bytesToHex(i);n.order.push(s),n.cache[s]=o}}return n};x.createConnection=function(e){var t=null;if(e.caStore)if(U.util.isArray(e.caStore))t=U.pki.createCaStore(e.caStore);else t=e.caStore;else t=U.pki.createCaStore();var n=e.cipherSuites||null;if(n===null){n=[];for(var r in x.CipherSuites)n.push(x.CipherSuites[r])}var i=e.server?x.ConnectionEnd.server:x.ConnectionEnd.client,o=e.sessionCache?x.createSessionCache(e.sessionCache):null,s={version:{major:x.Version.major,minor:x.Version.minor},entity:i,sessionId:e.sessionId,caStore:t,sessionCache:o,cipherSuites:n,connected:e.connected,virtualHost:e.virtualHost||null,verifyClient:e.verifyClient||!1,verify:e.verify||function(h,d,g,v){return d},verifyOptions:e.verifyOptions||{},getCertificate:e.getCertificate||null,getPrivateKey:e.getPrivateKey||null,getSignature:e.getSignature||null,input:U.util.createBuffer(),tlsData:U.util.createBuffer(),data:U.util.createBuffer(),tlsDataReady:e.tlsDataReady,dataReady:e.dataReady,heartbeatReceived:e.heartbeatReceived,closed:e.closed,error:function(h,d){if(d.origin=d.origin||(h.entity===x.ConnectionEnd.client?"client":"server"),d.send)x.queue(h,x.createAlert(h,d.alert)),x.flush(h);var g=d.fatal!==!1;if(g)h.fail=!0;if(e.error(h,d),g)h.close(!1)},deflate:e.deflate||null,inflate:e.inflate||null};s.reset=function(h){s.version={major:x.Version.major,minor:x.Version.minor},s.record=null,s.session=null,s.peerCertificate=null,s.state={pending:null,current:null},s.expect=s.entity===x.ConnectionEnd.client?Qw:o1,s.fragmented=null,s.records=[],s.open=!1,s.handshakes=0,s.handshaking=!1,s.isConnected=!1,s.fail=!(h||typeof h>"u"),s.input.clear(),s.tlsData.clear(),s.data.clear(),s.state.current=x.createConnectionState(s)},s.reset();var a=function(h,d){var g=d.type-x.ContentType.change_cipher_spec,v=$c[h.entity][h.expect];if(g in v)v[g](h,d);else x.handleUnexpected(h,d)},c=function(h){var d=0,g=h.input,v=g.length();if(v<5)d=5-v;else{h.record={type:g.getByte(),version:{major:g.getByte(),minor:g.getByte()},length:g.getInt16(),fragment:U.util.createBuffer(),ready:!1};var b=h.record.version.major===h.version.major;if(b&&h.session&&h.session.version)b=h.record.version.minor===h.version.minor;if(!b)h.error(h,{message:"Incompatible TLS version.",send:!0,alert:{level:x.Alert.Level.fatal,description:x.Alert.Description.protocol_version}})}return d},u=function(h){var d=0,g=h.input,v=g.length();if(v<h.record.length)d=h.record.length-v;else{h.record.fragment.putBytes(g.getBytes(h.record.length)),g.compact();var b=h.state.current.read;if(b.update(h,h.record)){if(h.fragmented!==null)if(h.fragmented.type===h.record.type)h.fragmented.fragment.putBuffer(h.record.fragment),h.record=h.fragmented;else return h.error(h,{message:"Invalid fragmented record.",send:!0,alert:{level:x.Alert.Level.fatal,description:x.Alert.Description.unexpected_message}}),d;h.record.ready=!0}}return d};s.handshake=function(h){if(s.entity!==x.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,h=h||"";var d=null;if(h.length>0){if(s.sessionCache)d=s.sessionCache.getSession(h);if(d===null)h=""}if(h.length===0&&s.sessionCache){if(d=s.sessionCache.getSession(),d!==null)h=d.id}if(s.session={id:h,version:null,cipherSuite:null,compressionMethod:null,serverCertificate:null,certificateRequest:null,clientCertificate:null,sp:{},md5:U.md.md5.create(),sha1:U.md.sha1.create()},d)s.version=d.version,s.session.sp=d.sp;s.session.sp.client_random=x.createRandom().getBytes(),s.open=!0,x.queue(s,x.createRecord(s,{type:x.ContentType.handshake,data:x.createClientHello(s)})),x.flush(s)}};var l=!1,f=!1,p=function(h){var d=0;if(!h.fail){if(h.record!==null&&h.record.ready&&h.record.fragment.isEmpty())h.record=null;if(h.record===null)d=c(h);if(!h.fail&&h.record!==null&&!h.record.ready)d=u(h);if(!h.fail&&h.record!==null&&h.record.ready)a(h,h.record)}return d};return s.process=function(h){var d=0;if(h)s.input.putBytes(h);if(l&&typeof h>"u")return f=!0,d;var g=l,v=f;l=!0,f=!1;try{d=p(s);while(f)f=!1,p(s)}finally{l=g,f=v}return d},s.prepare=function(h){return x.queue(s,x.createRecord(s,{type:x.ContentType.application_data,data:U.util.createBuffer(h)})),x.flush(s)},s.prepareHeartbeatRequest=function(h,d){if(h instanceof U.util.ByteBuffer)h=h.bytes();if(typeof d>"u")d=h.length;return s.expectedHeartbeatPayload=h,x.queue(s,x.createRecord(s,{type:x.ContentType.heartbeat,data:x.createHeartbeat(x.HeartbeatMessageType.heartbeat_request,h,d)})),x.flush(s)},s.close=function(h){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,x.queue(s,x.createAlert(s,{level:x.Alert.Level.warning,description:x.Alert.Description.close_notify})),x.flush(s);s.closed(s)}s.reset(h)},s};fp.exports=U.tls=U.tls||{};for(Fi in x)if(typeof x[Fi]!=="function")U.tls[Fi]=x[Fi];var Fi;U.tls.prf_tls1=fs;U.tls.hmac_sha1=qw;U.tls.createSessionCache=x.createSessionCache;U.tls.createConnection=x.createConnection});var hp=le(function(G2,pp){var qr=he();Vr();Oc();var Kt=pp.exports=qr.tls;Kt.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=Kt.BulkCipherAlgorithm.aes,e.cipher_type=Kt.CipherType.block,e.enc_key_length=16,e.block_length=16,e.fixed_iv_length=16,e.record_iv_length=16,e.mac_algorithm=Kt.MACAlgorithm.hmac_sha1,e.mac_length=20,e.mac_key_length=20},initConnectionState:dp};Kt.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=Kt.BulkCipherAlgorithm.aes,e.cipher_type=Kt.CipherType.block,e.enc_key_length=32,e.block_length=16,e.fixed_iv_length=16,e.record_iv_length=16,e.mac_algorithm=Kt.MACAlgorithm.hmac_sha1,e.mac_length=20,e.mac_key_length=20},initConnectionState:dp};function dp(e,t,n){var r=t.entity===qr.tls.ConnectionEnd.client;e.read.cipherState={init:!1,cipher:qr.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:qr.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=v1,e.write.cipherFunction=m1,e.read.macLength=e.write.macLength=n.mac_length,e.read.macFunction=e.write.macFunction=Kt.hmac_sha1}function m1(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===Kt.Versions.TLS_1_0.minor)i=t.cipherState.init?null:t.cipherState.iv;else i=qr.random.getBytesSync(16);t.cipherState.init=!0;var o=t.cipherState.cipher;if(o.start({iv:i}),e.version.minor>=Kt.Versions.TLS_1_1.minor)o.output.putBytes(i);if(o.update(e.fragment),o.finish(g1))e.fragment=o.output,e.length=e.fragment.length(),n=!0;return n}function g1(e,t,n){if(!n){var r=e-t.length()%e;t.fillWithByte(r-1,r)}return!0}function y1(e,t,n){var r=!0;if(n){var i=t.length(),o=t.last();for(var s=i-1-o;s<i-1;++s)r=r&&t.at(s)==o;if(r)t.truncate(o+1)}return r}function v1(e,t){var n=!1,r;if(e.version.minor===Kt.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(y1);var o=t.macLength,s=qr.random.getBytesSync(o),a=i.output.length();if(a>=o)e.fragment=i.output.getBytes(a-o),s=i.output.getBytes(o);else e.fragment=i.output.getBytes();e.fragment=qr.util.createBuffer(e.fragment),e.length=e.fragment.length();var c=t.macFunction(t.macKey,t.sequenceNumber,e);return t.updateSequenceNumber(),n=x1(t.macKey,s,c)&&n,n}function x1(e,t,n){var r=qr.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 zc=le(function(q2,vp){var Ve=he();ur();Te();var Mi=vp.exports=Ve.sha512=Ve.sha512||{};Ve.md.sha512=Ve.md.algorithms.sha512=Mi;var gp=Ve.sha384=Ve.sha512.sha384=Ve.sha512.sha384||{};gp.create=function(){return Mi.create("SHA-384")};Ve.md.sha384=Ve.md.algorithms.sha384=gp;Ve.sha512.sha256=Ve.sha512.sha256||{create:function(){return Mi.create("SHA-512/256")}};Ve.md["sha512/256"]=Ve.md.algorithms["sha512/256"]=Ve.sha512.sha256;Ve.sha512.sha224=Ve.sha512.sha224||{create:function(){return Mi.create("SHA-512/224")}};Ve.md["sha512/224"]=Ve.md.algorithms["sha512/224"]=Ve.sha512.sha224;Mi.create=function(e){if(!yp)b1();if(typeof e>"u")e="SHA-512";if(!(e in yn))throw Error("Invalid SHA-512 algorithm: "+e);var t=yn[e],n=null,r=Ve.util.createBuffer(),i=Array(80);for(var o=0;o<80;++o)i[o]=[,,];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 a={algorithm:e.replace("-","").toLowerCase(),blockLength:128,digestLength:s,messageLength:0,fullMessageLength:null,messageLengthSize:16};return a.start=function(){a.messageLength=0,a.fullMessageLength=a.messageLength128=[];var c=a.messageLengthSize/4;for(var u=0;u<c;++u)a.fullMessageLength.push(0);r=Ve.util.createBuffer(),n=Array(t.length);for(var u=0;u<t.length;++u)n[u]=t[u].slice(0);return a},a.start(),a.update=function(c,u){if(u==="utf8")c=Ve.util.encodeUtf8(c);var l=c.length;a.messageLength+=l,l=[l/4294967296>>>0,l>>>0];for(var f=a.fullMessageLength.length-1;f>=0;--f)a.fullMessageLength[f]+=l[1],l[1]=l[0]+(a.fullMessageLength[f]/4294967296>>>0),a.fullMessageLength[f]=a.fullMessageLength[f]>>>0,l[0]=l[1]/4294967296>>>0;if(r.putBytes(c),mp(n,i,r),r.read>2048||r.length()===0)r.compact();return a},a.digest=function(){var c=Ve.util.createBuffer();c.putBytes(r.bytes());var u=a.fullMessageLength[a.fullMessageLength.length-1]+a.messageLengthSize,l=u&a.blockLength-1;c.putBytes(Lc.substr(0,a.blockLength-l));var f,p,h=a.fullMessageLength[0]*8;for(var d=0;d<a.fullMessageLength.length-1;++d)f=a.fullMessageLength[d+1]*8,p=f/4294967296>>>0,h+=p,c.putInt32(h>>>0),h=f>>>0;c.putInt32(h);var g=Array(n.length);for(var d=0;d<n.length;++d)g[d]=n[d].slice(0);mp(g,i,c);var v=Ve.util.createBuffer(),b;if(e==="SHA-512")b=g.length;else if(e==="SHA-384")b=g.length-2;else b=g.length-4;for(var d=0;d<b;++d)if(v.putInt32(g[d][0]),d!==b-1||e!=="SHA-512/224")v.putInt32(g[d][1]);return v},a};var Lc=null,yp=!1,Uc=null,yn=null;function b1(){Lc=String.fromCharCode(128),Lc+=Ve.util.fillString(String.fromCharCode(0),128),Uc=[[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]],yn={},yn["SHA-512"]=[[1779033703,4089235720],[3144134277,2227873595],[1013904242,4271175723],[2773480762,1595750129],[1359893119,2917565137],[2600822924,725511199],[528734635,4215389547],[1541459225,327033209]],yn["SHA-384"]=[[3418070365,3238371032],[1654270250,914150663],[2438529370,812702999],[355462360,4144912697],[1731405415,4290775857],[2394180231,1750603025],[3675008525,1694076839],[1203062813,3204075428]],yn["SHA-512/256"]=[[573645204,4230739756],[2673172387,3360449730],[596883563,1867755857],[2520282905,1497426621],[2519219938,2827943907],[3193839141,1401305490],[721525244,746961066],[246885852,2177182882]],yn["SHA-512/224"]=[[2352822216,424955298],[1944164710,2312950998],[502970286,855612546],[1738396948,1479516111],[258812777,2077511080],[2011393907,79989058],[1067287976,1780299464],[286451373,2446758561]],yp=!0}function mp(e,t,n){var r,i,o,s,a,c,u,l,f,p,h,d,g,v,b,S,C,T,I,k,R,V,D,F,H,re,se,Pe,ue,de,W,te,J,ce,ae,ee=n.length();while(ee>=128){for(ue=0;ue<16;++ue)t[ue][0]=n.getInt32()>>>0,t[ue][1]=n.getInt32()>>>0;for(;ue<80;++ue)te=t[ue-2],de=te[0],W=te[1],r=((de>>>19|W<<13)^(W>>>29|de<<3)^de>>>6)>>>0,i=((de<<13|W>>>19)^(W<<3|de>>>29)^(de<<26|W>>>6))>>>0,ce=t[ue-15],de=ce[0],W=ce[1],o=((de>>>1|W<<31)^(de>>>8|W<<24)^de>>>7)>>>0,s=((de<<31|W>>>1)^(de<<24|W>>>8)^(de<<25|W>>>7))>>>0,J=t[ue-7],ae=t[ue-16],W=i+J[1]+s+ae[1],t[ue][0]=r+J[0]+o+ae[0]+(W/4294967296>>>0)>>>0,t[ue][1]=W>>>0;g=e[0][0],v=e[0][1],b=e[1][0],S=e[1][1],C=e[2][0],T=e[2][1],I=e[3][0],k=e[3][1],R=e[4][0],V=e[4][1],D=e[5][0],F=e[5][1],H=e[6][0],re=e[6][1],se=e[7][0],Pe=e[7][1];for(ue=0;ue<80;++ue)u=((R>>>14|V<<18)^(R>>>18|V<<14)^(V>>>9|R<<23))>>>0,l=((R<<18|V>>>14)^(R<<14|V>>>18)^(V<<23|R>>>9))>>>0,f=(H^R&(D^H))>>>0,p=(re^V&(F^re))>>>0,a=((g>>>28|v<<4)^(v>>>2|g<<30)^(v>>>7|g<<25))>>>0,c=((g<<4|v>>>28)^(v<<30|g>>>2)^(v<<25|g>>>7))>>>0,h=(g&b|C&(g^b))>>>0,d=(v&S|T&(v^S))>>>0,W=Pe+l+p+Uc[ue][1]+t[ue][1],r=se+u+f+Uc[ue][0]+t[ue][0]+(W/4294967296>>>0)>>>0,i=W>>>0,W=c+d,o=a+h+(W/4294967296>>>0)>>>0,s=W>>>0,se=H,Pe=re,H=D,re=F,D=R,F=V,W=k+i,R=I+r+(W/4294967296>>>0)>>>0,V=W>>>0,I=C,k=T,C=b,T=S,b=g,S=v,W=i+s,g=r+o+(W/4294967296>>>0)>>>0,v=W>>>0;W=e[0][1]+v,e[0][0]=e[0][0]+g+(W/4294967296>>>0)>>>0,e[0][1]=W>>>0,W=e[1][1]+S,e[1][0]=e[1][0]+b+(W/4294967296>>>0)>>>0,e[1][1]=W>>>0,W=e[2][1]+T,e[2][0]=e[2][0]+C+(W/4294967296>>>0)>>>0,e[2][1]=W>>>0,W=e[3][1]+k,e[3][0]=e[3][0]+I+(W/4294967296>>>0)>>>0,e[3][1]=W>>>0,W=e[4][1]+V,e[4][0]=e[4][0]+R+(W/4294967296>>>0)>>>0,e[4][1]=W>>>0,W=e[5][1]+F,e[5][0]=e[5][0]+D+(W/4294967296>>>0)>>>0,e[5][1]=W>>>0,W=e[6][1]+re,e[6][0]=e[6][0]+H+(W/4294967296>>>0)>>>0,e[6][1]=W>>>0,W=e[7][1]+Pe,e[7][0]=e[7][0]+se+(W/4294967296>>>0)>>>0,e[7][1]=W>>>0,ee-=128}}});var xp=le(function(C1){var S1=he();Qt();var dt=S1.asn1;C1.privateKeyValidator={name:"PrivateKeyInfo",tagClass:dt.Class.UNIVERSAL,type:dt.Type.SEQUENCE,constructed:!0,value:[{name:"PrivateKeyInfo.version",tagClass:dt.Class.UNIVERSAL,type:dt.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:dt.Class.UNIVERSAL,type:dt.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:dt.Class.UNIVERSAL,type:dt.Type.OID,constructed:!1,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:dt.Class.UNIVERSAL,type:dt.Type.OCTETSTRING,constructed:!1,capture:"privateKey"}]};C1.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:dt.Class.UNIVERSAL,type:dt.Type.SEQUENCE,constructed:!0,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:dt.Class.UNIVERSAL,type:dt.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:dt.Class.UNIVERSAL,type:dt.Type.OID,constructed:!1,capture:"publicKeyOid"}]},{tagClass:dt.Class.UNIVERSAL,type:dt.Type.BITSTRING,constructed:!1,composed:!0,captureBitStringValue:"ed25519PublicKey"}]}});var Rp=le(function(J2,Pp){var gt=he();Oi();Ft();zc();Te();var Ep=xp(),{publicKeyValidator:_1,privateKeyValidator:T1}=Ep;if(typeof Mc>"u")Mc=gt.jsbn.BigInteger;var Mc,Vc=gt.util.ByteBuffer,Et=typeof Buffer>"u"?Uint8Array:Buffer;gt.pki=gt.pki||{};Pp.exports=gt.pki.ed25519=gt.ed25519=gt.ed25519||{};var be=gt.ed25519;be.constants={};be.constants.PUBLIC_KEY_BYTE_LENGTH=32;be.constants.PRIVATE_KEY_BYTE_LENGTH=64;be.constants.SEED_BYTE_LENGTH=32;be.constants.SIGN_BYTE_LENGTH=64;be.constants.HASH_BYTE_LENGTH=64;be.generateKeyPair=function(e){e=e||{};var t=e.seed;if(t===void 0)t=gt.random.getBytesSync(be.constants.SEED_BYTE_LENGTH);else if(typeof t==="string"){if(t.length!==be.constants.SEED_BYTE_LENGTH)throw TypeError('"seed" must be '+be.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=Pr({message:t,encoding:"binary"});var n=new Et(be.constants.PUBLIC_KEY_BYTE_LENGTH),r=new Et(be.constants.PRIVATE_KEY_BYTE_LENGTH);for(var i=0;i<32;++i)r[i]=t[i];return P1(n,r),{publicKey:n,privateKey:r}};be.privateKeyFromAsn1=function(e){var t={},n=[],r=gt.asn1.validate(e,T1,t,n);if(!r){var i=Error("Invalid Key.");throw i.errors=n,i}var o=gt.asn1.derToOid(t.privateKeyOid),s=gt.oids.EdDSA25519;if(o!==s)throw Error('Invalid OID "'+o+'"; OID must be "'+s+'".');var a=t.privateKey,c=Pr({message:gt.asn1.fromDer(a).value,encoding:"binary"});return{privateKeyBytes:c}};be.publicKeyFromAsn1=function(e){var t={},n=[],r=gt.asn1.validate(e,_1,t,n);if(!r){var i=Error("Invalid Key.");throw i.errors=n,i}var o=gt.asn1.derToOid(t.publicKeyOid),s=gt.oids.EdDSA25519;if(o!==s)throw Error('Invalid OID "'+o+'"; OID must be "'+s+'".');var a=t.ed25519PublicKey;if(a.length!==be.constants.PUBLIC_KEY_BYTE_LENGTH)throw Error("Key length is invalid.");return Pr({message:a,encoding:"binary"})};be.publicKeyFromPrivateKey=function(e){e=e||{};var t=Pr({message:e.privateKey,encoding:"binary"});if(t.length!==be.constants.PRIVATE_KEY_BYTE_LENGTH)throw TypeError('"options.privateKey" must have a byte length of '+be.constants.PRIVATE_KEY_BYTE_LENGTH);var n=new Et(be.constants.PUBLIC_KEY_BYTE_LENGTH);for(var r=0;r<n.length;++r)n[r]=t[32+r];return n};be.sign=function(e){e=e||{};var t=Pr(e),n=Pr({message:e.privateKey,encoding:"binary"});if(n.length===be.constants.SEED_BYTE_LENGTH){var r=be.generateKeyPair({seed:n});n=r.privateKey}else if(n.length!==be.constants.PRIVATE_KEY_BYTE_LENGTH)throw TypeError('"options.privateKey" must have a byte length of '+be.constants.SEED_BYTE_LENGTH+" or "+be.constants.PRIVATE_KEY_BYTE_LENGTH);var i=new Et(be.constants.SIGN_BYTE_LENGTH+t.length);R1(i,t,t.length,n);var o=new Et(be.constants.SIGN_BYTE_LENGTH);for(var s=0;s<o.length;++s)o[s]=i[s];return o};be.verify=function(e){e=e||{};var t=Pr(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=Pr({message:e.signature,encoding:"binary"});if(n.length!==be.constants.SIGN_BYTE_LENGTH)throw TypeError('"options.signature" must have a byte length of '+be.constants.SIGN_BYTE_LENGTH);var r=Pr({message:e.publicKey,encoding:"binary"});if(r.length!==be.constants.PUBLIC_KEY_BYTE_LENGTH)throw TypeError('"options.publicKey" must have a byte length of '+be.constants.PUBLIC_KEY_BYTE_LENGTH);var i=new Et(be.constants.SIGN_BYTE_LENGTH+t.length),o=new Et(be.constants.SIGN_BYTE_LENGTH+t.length),s;for(s=0;s<be.constants.SIGN_BYTE_LENGTH;++s)i[s]=n[s];for(s=0;s<t.length;++s)i[s+be.constants.SIGN_BYTE_LENGTH]=t[s];return B1(o,i,i.length,r)>=0};function Pr(e){var t=e.message;if(t instanceof Uint8Array||t instanceof Et)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 Vc(t,n)}else if(!(t instanceof Vc))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 Et(t.length());for(var i=0;i<r.length;++i)r[i]=t.at(i);return r}var Wc=ie(),ds=ie([1]),A1=ie([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),k1=ie([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),bp=ie([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),Sp=ie([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),Vi=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]),I1=ie([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function Wi(e,t){var n=gt.md.sha512.create(),r=new Vc(e);n.update(r.getBytes(t),"binary");var i=n.digest().getBytes();if(typeof Buffer<"u")return Buffer.from(i,"binary");var o=new Et(be.constants.HASH_BYTE_LENGTH);for(var s=0;s<64;++s)o[s]=i.charCodeAt(s);return o}function P1(e,t){var n=[ie(),ie(),ie(),ie()],r,i=Wi(t,32);i[0]&=248,i[31]&=127,i[31]|=64,Kc(n,i),ms(e,n);for(r=0;r<32;++r)t[r+32]=e[r];return 0}function R1(e,t,n,r){var i,o,s=new Float64Array(64),a=[ie(),ie(),ie(),ie()],c=Wi(r,32);c[0]&=248,c[31]&=127,c[31]|=64;var u=n+64;for(i=0;i<n;++i)e[64+i]=t[i];for(i=0;i<32;++i)e[32+i]=c[32+i];var l=Wi(e.subarray(32),n+32);Hc(l),Kc(a,l),ms(e,a);for(i=32;i<64;++i)e[i]=r[i];var f=Wi(e,n+64);Hc(f);for(i=32;i<64;++i)s[i]=0;for(i=0;i<32;++i)s[i]=l[i];for(i=0;i<32;++i)for(o=0;o<32;o++)s[i+o]+=f[i]*c[o];return _p(e.subarray(32),s),u}function B1(e,t,n,r){var i,o,s=new Et(32),a=[ie(),ie(),ie(),ie()],c=[ie(),ie(),ie(),ie()];if(o=-1,n<64)return-1;if($1(c,r))return-1;if(D1(c))return-1;if(!N1(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 u=Wi(e,n);if(Hc(u),kp(a,c,u),Kc(c,t.subarray(32)),ps(a,c),ms(s,a),n-=64,Tp(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 o=n,o}function N1(e,t){var n;for(n=31;n>=0;--n){if(e[t+n]<Vi[n])return!0;if(e[t+n]>Vi[n])return!1}return!1}function D1(e){var t,n=new Et(32),r=[ie(e[0]),ie(e[1]),ie(e[2]),ie(e[3])];for(t=0;t<3;++t)ps(r,r);if(ms(n,r),n[0]!==1)return!1;for(t=1;t<32;++t)if(n[t]!==0)return!1;return!0}function _p(e,t){var n,r,i,o;for(r=63;r>=32;--r){n=0;for(i=r-32,o=r-12;i<o;++i)t[i]+=n-16*t[r]*Vi[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)*Vi[i],n=t[i]>>8,t[i]&=255;for(i=0;i<32;++i)t[i]-=n*Vi[i];for(r=0;r<32;++r)t[r+1]+=t[r]>>8,e[r]=t[r]&255}function Hc(e){var t=new Float64Array(64);for(var n=0;n<64;++n)t[n]=e[n],e[n]=0;_p(e,t)}function ps(e,t){var n=ie(),r=ie(),i=ie(),o=ie(),s=ie(),a=ie(),c=ie(),u=ie(),l=ie();jn(n,e[1],e[0]),jn(l,t[1],t[0]),Ne(n,n,l),Zn(r,e[0],e[1]),Zn(l,t[0],t[1]),Ne(r,r,l),Ne(i,e[3],t[3]),Ne(i,i,k1),Ne(o,e[2],t[2]),Zn(o,o,o),jn(s,r,n),jn(a,o,i),Zn(c,o,i),Zn(u,r,n),Ne(e[0],s,a),Ne(e[1],u,c),Ne(e[2],c,a),Ne(e[3],s,u)}function Cp(e,t,n){for(var r=0;r<4;++r)Ip(e[r],t[r],n)}function ms(e,t){var n=ie(),r=ie(),i=ie();z1(i,t[2]),Ne(n,t[0],i),Ne(r,t[1],i),hs(e,r),e[31]^=Ap(n)<<7}function hs(e,t){var n,r,i,o=ie(),s=ie();for(n=0;n<16;++n)s[n]=t[n];Fc(s),Fc(s),Fc(s);for(r=0;r<2;++r){o[0]=s[0]-65517;for(n=1;n<15;++n)o[n]=s[n]-65535-(o[n-1]>>16&1),o[n-1]&=65535;o[15]=s[15]-32767-(o[14]>>16&1),i=o[15]>>16&1,o[14]&=65535,Ip(s,o,1-i)}for(n=0;n<16;n++)e[2*n]=s[n]&255,e[2*n+1]=s[n]>>8}function $1(e,t){var n=ie(),r=ie(),i=ie(),o=ie(),s=ie(),a=ie(),c=ie();if(Xr(e[2],ds),O1(e[1],t),vn(i,e[1]),Ne(o,i,A1),jn(i,i,e[2]),Zn(o,e[2],o),vn(s,o),vn(a,s),Ne(c,a,s),Ne(n,c,i),Ne(n,n,o),L1(n,n),Ne(n,n,i),Ne(n,n,o),Ne(n,n,o),Ne(e[0],n,o),vn(r,e[0]),Ne(r,r,o),wp(r,i))Ne(e[0],e[0],I1);if(vn(r,e[0]),Ne(r,r,o),wp(r,i))return-1;if(Ap(e[0])===t[31]>>7)jn(e[0],Wc,e[0]);return Ne(e[3],e[0],e[1]),0}function O1(e,t){var n;for(n=0;n<16;++n)e[n]=t[2*n]+(t[2*n+1]<<8);e[15]&=32767}function L1(e,t){var n=ie(),r;for(r=0;r<16;++r)n[r]=t[r];for(r=250;r>=0;--r)if(vn(n,n),r!==1)Ne(n,n,t);for(r=0;r<16;++r)e[r]=n[r]}function wp(e,t){var n=new Et(32),r=new Et(32);return hs(n,e),hs(r,t),Tp(n,0,r,0)}function Tp(e,t,n,r){return U1(e,t,n,r,32)}function U1(e,t,n,r,i){var o,s=0;for(o=0;o<i;++o)s|=e[t+o]^n[r+o];return(1&s-1>>>8)-1}function Ap(e){var t=new Et(32);return hs(t,e),t[0]&1}function kp(e,t,n){var r,i;Xr(e[0],Wc),Xr(e[1],ds),Xr(e[2],ds),Xr(e[3],Wc);for(i=255;i>=0;--i)r=n[i/8|0]>>(i&7)&1,Cp(e,t,r),ps(t,e),ps(e,e),Cp(e,t,r)}function Kc(e,t){var n=[ie(),ie(),ie(),ie()];Xr(n[0],bp),Xr(n[1],Sp),Xr(n[2],ds),Ne(n[3],bp,Sp),kp(e,n,t)}function Xr(e,t){var n;for(n=0;n<16;n++)e[n]=t[n]|0}function z1(e,t){var n=ie(),r;for(r=0;r<16;++r)n[r]=t[r];for(r=253;r>=0;--r)if(vn(n,n),r!==2&&r!==4)Ne(n,n,t);for(r=0;r<16;++r)e[r]=n[r]}function Fc(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 Ip(e,t,n){var r,i=~(n-1);for(var o=0;o<16;++o)r=i&(e[o]^t[o]),e[o]^=r,t[o]^=r}function ie(e){var t,n=new Float64Array(16);if(e)for(t=0;t<e.length;++t)n[t]=e[t];return n}function Zn(e,t,n){for(var r=0;r<16;++r)e[r]=t[r]+n[r]}function jn(e,t,n){for(var r=0;r<16;++r)e[r]=t[r]-n[r]}function vn(e,t){Ne(e,t,t)}function Ne(e,t,n){var r,i,o=0,s=0,a=0,c=0,u=0,l=0,f=0,p=0,h=0,d=0,g=0,v=0,b=0,S=0,C=0,T=0,I=0,k=0,R=0,V=0,D=0,F=0,H=0,re=0,se=0,Pe=0,ue=0,de=0,W=0,te=0,J=0,ce=n[0],ae=n[1],ee=n[2],Ee=n[3],$e=n[4],qe=n[5],ye=n[6],oe=n[7],Oe=n[8],_e=n[9],it=n[10],rt=n[11],ot=n[12],st=n[13],Xe=n[14],at=n[15];r=t[0],o+=r*ce,s+=r*ae,a+=r*ee,c+=r*Ee,u+=r*$e,l+=r*qe,f+=r*ye,p+=r*oe,h+=r*Oe,d+=r*_e,g+=r*it,v+=r*rt,b+=r*ot,S+=r*st,C+=r*Xe,T+=r*at,r=t[1],s+=r*ce,a+=r*ae,c+=r*ee,u+=r*Ee,l+=r*$e,f+=r*qe,p+=r*ye,h+=r*oe,d+=r*Oe,g+=r*_e,v+=r*it,b+=r*rt,S+=r*ot,C+=r*st,T+=r*Xe,I+=r*at,r=t[2],a+=r*ce,c+=r*ae,u+=r*ee,l+=r*Ee,f+=r*$e,p+=r*qe,h+=r*ye,d+=r*oe,g+=r*Oe,v+=r*_e,b+=r*it,S+=r*rt,C+=r*ot,T+=r*st,I+=r*Xe,k+=r*at,r=t[3],c+=r*ce,u+=r*ae,l+=r*ee,f+=r*Ee,p+=r*$e,h+=r*qe,d+=r*ye,g+=r*oe,v+=r*Oe,b+=r*_e,S+=r*it,C+=r*rt,T+=r*ot,I+=r*st,k+=r*Xe,R+=r*at,r=t[4],u+=r*ce,l+=r*ae,f+=r*ee,p+=r*Ee,h+=r*$e,d+=r*qe,g+=r*ye,v+=r*oe,b+=r*Oe,S+=r*_e,C+=r*it,T+=r*rt,I+=r*ot,k+=r*st,R+=r*Xe,V+=r*at,r=t[5],l+=r*ce,f+=r*ae,p+=r*ee,h+=r*Ee,d+=r*$e,g+=r*qe,v+=r*ye,b+=r*oe,S+=r*Oe,C+=r*_e,T+=r*it,I+=r*rt,k+=r*ot,R+=r*st,V+=r*Xe,D+=r*at,r=t[6],f+=r*ce,p+=r*ae,h+=r*ee,d+=r*Ee,g+=r*$e,v+=r*qe,b+=r*ye,S+=r*oe,C+=r*Oe,T+=r*_e,I+=r*it,k+=r*rt,R+=r*ot,V+=r*st,D+=r*Xe,F+=r*at,r=t[7],p+=r*ce,h+=r*ae,d+=r*ee,g+=r*Ee,v+=r*$e,b+=r*qe,S+=r*ye,C+=r*oe,T+=r*Oe,I+=r*_e,k+=r*it,R+=r*rt,V+=r*ot,D+=r*st,F+=r*Xe,H+=r*at,r=t[8],h+=r*ce,d+=r*ae,g+=r*ee,v+=r*Ee,b+=r*$e,S+=r*qe,C+=r*ye,T+=r*oe,I+=r*Oe,k+=r*_e,R+=r*it,V+=r*rt,D+=r*ot,F+=r*st,H+=r*Xe,re+=r*at,r=t[9],d+=r*ce,g+=r*ae,v+=r*ee,b+=r*Ee,S+=r*$e,C+=r*qe,T+=r*ye,I+=r*oe,k+=r*Oe,R+=r*_e,V+=r*it,D+=r*rt,F+=r*ot,H+=r*st,re+=r*Xe,se+=r*at,r=t[10],g+=r*ce,v+=r*ae,b+=r*ee,S+=r*Ee,C+=r*$e,T+=r*qe,I+=r*ye,k+=r*oe,R+=r*Oe,V+=r*_e,D+=r*it,F+=r*rt,H+=r*ot,re+=r*st,se+=r*Xe,Pe+=r*at,r=t[11],v+=r*ce,b+=r*ae,S+=r*ee,C+=r*Ee,T+=r*$e,I+=r*qe,k+=r*ye,R+=r*oe,V+=r*Oe,D+=r*_e,F+=r*it,H+=r*rt,re+=r*ot,se+=r*st,Pe+=r*Xe,ue+=r*at,r=t[12],b+=r*ce,S+=r*ae,C+=r*ee,T+=r*Ee,I+=r*$e,k+=r*qe,R+=r*ye,V+=r*oe,D+=r*Oe,F+=r*_e,H+=r*it,re+=r*rt,se+=r*ot,Pe+=r*st,ue+=r*Xe,de+=r*at,r=t[13],S+=r*ce,C+=r*ae,T+=r*ee,I+=r*Ee,k+=r*$e,R+=r*qe,V+=r*ye,D+=r*oe,F+=r*Oe,H+=r*_e,re+=r*it,se+=r*rt,Pe+=r*ot,ue+=r*st,de+=r*Xe,W+=r*at,r=t[14],C+=r*ce,T+=r*ae,I+=r*ee,k+=r*Ee,R+=r*$e,V+=r*qe,D+=r*ye,F+=r*oe,H+=r*Oe,re+=r*_e,se+=r*it,Pe+=r*rt,ue+=r*ot,de+=r*st,W+=r*Xe,te+=r*at,r=t[15],T+=r*ce,I+=r*ae,k+=r*ee,R+=r*Ee,V+=r*$e,D+=r*qe,F+=r*ye,H+=r*oe,re+=r*Oe,se+=r*_e,Pe+=r*it,ue+=r*rt,de+=r*ot,W+=r*st,te+=r*Xe,J+=r*at,o+=38*I,s+=38*k,a+=38*R,c+=38*V,u+=38*D,l+=38*F,f+=38*H,p+=38*re,h+=38*se,d+=38*Pe,g+=38*ue,v+=38*de,b+=38*W,S+=38*te,C+=38*J,i=1,r=o+i+65535,i=Math.floor(r/65536),o=r-i*65536,r=s+i+65535,i=Math.floor(r/65536),s=r-i*65536,r=a+i+65535,i=Math.floor(r/65536),a=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=l+i+65535,i=Math.floor(r/65536),l=r-i*65536,r=f+i+65535,i=Math.floor(r/65536),f=r-i*65536,r=p+i+65535,i=Math.floor(r/65536),p=r-i*65536,r=h+i+65535,i=Math.floor(r/65536),h=r-i*65536,r=d+i+65535,i=Math.floor(r/65536),d=r-i*65536,r=g+i+65535,i=Math.floor(r/65536),g=r-i*65536,r=v+i+65535,i=Math.floor(r/65536),v=r-i*65536,r=b+i+65535,i=Math.floor(r/65536),b=r-i*65536,r=S+i+65535,i=Math.floor(r/65536),S=r-i*65536,r=C+i+65535,i=Math.floor(r/65536),C=r-i*65536,r=T+i+65535,i=Math.floor(r/65536),T=r-i*65536,o+=i-1+37*(i-1),i=1,r=o+i+65535,i=Math.floor(r/65536),o=r-i*65536,r=s+i+65535,i=Math.floor(r/65536),s=r-i*65536,r=a+i+65535,i=Math.floor(r/65536),a=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=l+i+65535,i=Math.floor(r/65536),l=r-i*65536,r=f+i+65535,i=Math.floor(r/65536),f=r-i*65536,r=p+i+65535,i=Math.floor(r/65536),p=r-i*65536,r=h+i+65535,i=Math.floor(r/65536),h=r-i*65536,r=d+i+65535,i=Math.floor(r/65536),d=r-i*65536,r=g+i+65535,i=Math.floor(r/65536),g=r-i*65536,r=v+i+65535,i=Math.floor(r/65536),v=r-i*65536,r=b+i+65535,i=Math.floor(r/65536),b=r-i*65536,r=S+i+65535,i=Math.floor(r/65536),S=r-i*65536,r=C+i+65535,i=Math.floor(r/65536),C=r-i*65536,r=T+i+65535,i=Math.floor(r/65536),T=r-i*65536,o+=i-1+37*(i-1),e[0]=o,e[1]=s,e[2]=a,e[3]=c,e[4]=u,e[5]=l,e[6]=f,e[7]=p,e[8]=h,e[9]=d,e[10]=g,e[11]=v,e[12]=b,e[13]=S,e[14]=C,e[15]=T}});var $p=le(function(Q2,Dp){var Bt=he();Te();Ft();Oi();Dp.exports=Bt.kem=Bt.kem||{};var Bp=Bt.jsbn.BigInteger;Bt.kem.rsa={};Bt.kem.rsa.create=function(e,t){t=t||{};var n=t.prng||Bt.random,r={};return r.encrypt=function(i,o){var s=Math.ceil(i.n.bitLength()/8),a;do a=new Bp(Bt.util.bytesToHex(n.getBytesSync(s)),16).mod(i.n);while(a.compareTo(Bp.ONE)<=0);a=Bt.util.hexToBytes(a.toString(16));var c=s-a.length;if(c>0)a=Bt.util.fillString(String.fromCharCode(0),c)+a;var u=i.encrypt(a,"NONE"),l=e.generate(a,o);return{encapsulation:u,key:l}},r.decrypt=function(i,o,s){var a=i.decrypt(o,"NONE");return e.generate(a,s)},r};Bt.kem.kdf1=function(e,t){Np(this,e,0,t||e.digestLength)};Bt.kem.kdf2=function(e,t){Np(this,e,1,t||e.digestLength)};function Np(e,t,n,r){e.generate=function(i,o){var s=new Bt.util.ByteBuffer,a=Math.ceil(o/r)+n,c=new Bt.util.ByteBuffer;for(var u=n;u<a;++u){c.putInt32(u),t.start(),t.update(i+c.getBytes());var l=t.digest();s.putBytes(l.getBytes(r))}return s.truncate(s.length()-o),s.getBytes()}}});var Lp=le(function(Y2,Op){var Ce=he();Te();Op.exports=Ce.log=Ce.log||{};Ce.log.levels=["none","error","warning","info","debug","verbose","max"];var vs={},Zc=[],Hi=null;Ce.log.LEVEL_LOCKED=2;Ce.log.NO_LEVEL_CHECK=4;Ce.log.INTERPOLATE=8;for(Zt=0;Zt<Ce.log.levels.length;++Zt)gs=Ce.log.levels[Zt],vs[gs]={index:Zt,name:gs.toUpperCase()};var gs,Zt;Ce.log.logMessage=function(e){var t=vs[e.level].index;for(var n=0;n<Zc.length;++n){var r=Zc[n];if(r.flags&Ce.log.NO_LEVEL_CHECK)r.f(e);else{var i=vs[r.level].index;if(t<=i)r.f(r,e)}}};Ce.log.prepareStandard=function(e){if(!("standard"in e))e.standard=vs[e.level].name+" ["+e.category+"] "+e.message};Ce.log.prepareFull=function(e){if(!("full"in e)){var t=[e.message];t=t.concat([]),e.full=Ce.util.format.apply(this,t)}};Ce.log.prepareStandardFull=function(e){if(!("standardFull"in e))Ce.log.prepareStandard(e),e.standardFull=e.standard};ys=["error","warning","info","debug","verbose"];for(Zt=0;Zt<ys.length;++Zt)(function(t){Ce.log[t]=function(n,r){var i=Array.prototype.slice.call(arguments).slice(2),o={timestamp:new Date,level:t,category:n,message:r,arguments:i};Ce.log.logMessage(o)}})(ys[Zt]);var ys,Zt;Ce.log.makeLogger=function(e){var t={flags:0,f:e};return Ce.log.setLevel(t,"none"),t};Ce.log.setLevel=function(e,t){var n=!1;if(e&&!(e.flags&Ce.log.LEVEL_LOCKED))for(var r=0;r<Ce.log.levels.length;++r){var i=Ce.log.levels[r];if(t==i){e.level=t,n=!0;break}}return n};Ce.log.lock=function(e,t){if(typeof t>"u"||t)e.flags|=Ce.log.LEVEL_LOCKED;else e.flags&=~Ce.log.LEVEL_LOCKED};Ce.log.addLogger=function(e){Zc.push(e)};if(typeof console<"u"&&"log"in console){if(console.error&&console.warn&&console.info&&console.debug)jc={error:console.error,warning:console.warn,info:console.info,debug:console.debug,verbose:console.debug},qn=function(e,t){Ce.log.prepareStandard(t);var n=jc[t.level],r=[t.standard];r=r.concat(t.arguments.slice()),n.apply(console,r)},xn=Ce.log.makeLogger(qn);else qn=function(t,n){Ce.log.prepareStandardFull(n),console.log(n.standardFull)},xn=Ce.log.makeLogger(qn);Ce.log.setLevel(xn,"debug"),Ce.log.addLogger(xn),Hi=xn}else console={log:function(){}};var xn,jc,qn;if(Hi!==null&&typeof window<"u"&&window.location&&window.location.href&&typeof URL==="function"){if(Gn=new URL(window.location.href).searchParams,Gn.has("console.level"))Ce.log.setLevel(Hi,Gn.get("console.level").slice(-1)[0]);if(Gn.has("console.lock")){if(Gc=Gn.get("console.lock").slice(-1)[0],Gc=="true")Ce.log.lock(Hi)}}var Gn,Gc;Ce.log.consoleLogger=Hi});var zp=le(function(eP,Up){Up.exports=ur();Zo();Mn();uc();zc()});var Vp=le(function(tP,Mp){var Z=he();Vr();Qt();Di();Wr();fn();wc();Ft();Te();cs();var _=Z.asn1,_t=Mp.exports=Z.pkcs7=Z.pkcs7||{};_t.messageFromPem=function(e){var t=Z.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=_.fromDer(t.body);return _t.messageFromAsn1(r)};_t.messageToPem=function(e,t){var n={type:"PKCS7",body:_.toDer(e.toAsn1()).getBytes()};return Z.pem.encode(n,{maxline:t})};_t.messageFromAsn1=function(e){var t={},n=[];if(!_.validate(e,_t.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=_.derToOid(t.contentType),o;switch(i){case Z.pki.oids.envelopedData:o=_t.createEnvelopedData();break;case Z.pki.oids.encryptedData:o=_t.createEncryptedData();break;case Z.pki.oids.signedData:o=_t.createSignedData();break;default:throw Error("Cannot read PKCS#7 message. ContentType with OID "+i+" is not (yet) supported.")}return o.fromAsn1(t.content.value[0]),o};_t.createSignedData=function(){var e=null;return e={type:Z.pki.oids.signedData,version:1,certificates:[],crls:[],signers:[],digestAlgorithmIdentifiers:[],contentInfo:null,signerInfos:[],fromAsn1:function(r){if(Xc(e,r,_t.asn1.signedDataValidator),e.certificates=[],e.crls=[],e.digestAlgorithmIdentifiers=[],e.contentInfo=null,e.signerInfos=[],e.rawCapture.certificates){var i=e.rawCapture.certificates.value;for(var o=0;o<i.length;++o)e.certificates.push(Z.pki.certificateFromAsn1(i[o]))}},toAsn1:function(){if(!e.contentInfo)e.sign();var r=[];for(var i=0;i<e.certificates.length;++i)r.push(Z.pki.certificateToAsn1(e.certificates[i]));var o=[],s=_.create(_.Class.CONTEXT_SPECIFIC,0,!0,[_.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[_.create(_.Class.UNIVERSAL,_.Type.INTEGER,!1,_.integerToDer(e.version).getBytes()),_.create(_.Class.UNIVERSAL,_.Type.SET,!0,e.digestAlgorithmIdentifiers),e.contentInfo])]);if(r.length>0)s.value[0].value.push(_.create(_.Class.CONTEXT_SPECIFIC,0,!0,r));if(o.length>0)s.value[0].value.push(_.create(_.Class.CONTEXT_SPECIFIC,1,!0,o));return s.value[0].value.push(_.create(_.Class.UNIVERSAL,_.Type.SET,!0,e.signerInfos)),_.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[_.create(_.Class.UNIVERSAL,_.Type.OID,!1,_.oidToDer(e.type).getBytes()),s])},addSigner:function(r){var{issuer:i,serialNumber:o}=r;if(r.certificate){var s=r.certificate;if(typeof s==="string")s=Z.pki.certificateFromPem(s);i=s.issuer.attributes,o=s.serialNumber}var a=r.key;if(!a)throw Error("Could not add PKCS#7 signer; no private key specified.");if(typeof a==="string")a=Z.pki.privateKeyFromPem(a);var c=r.digestAlgorithm||Z.pki.oids.sha1;switch(c){case Z.pki.oids.sha1:case Z.pki.oids.sha256:case Z.pki.oids.sha384:case Z.pki.oids.sha512:case Z.pki.oids.md5:break;default:throw Error("Could not add PKCS#7 signer; unknown message digest algorithm: "+c)}var u=r.authenticatedAttributes||[];if(u.length>0){var l=!1,f=!1;for(var p=0;p<u.length;++p){var h=u[p];if(!l&&h.type===Z.pki.oids.contentType){if(l=!0,f)break;continue}if(!f&&h.type===Z.pki.oids.messageDigest){if(f=!0,l)break;continue}}if(!l||!f)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:a,version:1,issuer:i,serialNumber:o,digestAlgorithm:c,signatureAlgorithm:Z.pki.oids.rsaEncryption,signature:null,authenticatedAttributes:u,unauthenticatedAttributes:[]})},sign:function(r){if(r=r||{},typeof e.content!=="object"||e.contentInfo===null){if(e.contentInfo=_.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[_.create(_.Class.UNIVERSAL,_.Type.OID,!1,_.oidToDer(Z.pki.oids.data).getBytes())]),"content"in e){var i;if(e.content instanceof Z.util.ByteBuffer)i=e.content.bytes();else if(typeof e.content==="string")i=Z.util.encodeUtf8(e.content);if(r.detached)e.detachedContent=_.create(_.Class.UNIVERSAL,_.Type.OCTETSTRING,!1,i);else e.contentInfo.value.push(_.create(_.Class.CONTEXT_SPECIFIC,0,!0,[_.create(_.Class.UNIVERSAL,_.Type.OCTETSTRING,!1,i)]))}}if(e.signers.length===0)return;var o=t();n(o)},verify:function(){throw Error("PKCS#7 signature verification not yet implemented.")},addCertificate:function(r){if(typeof r==="string")r=Z.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 o=e.signers[i],s=o.digestAlgorithm;if(!(s in r))r[s]=Z.md[Z.pki.oids[s]].create();if(o.authenticatedAttributes.length===0)o.md=r[s];else o.md=Z.md[Z.pki.oids[s]].create()}e.digestAlgorithmIdentifiers=[];for(var s in r)e.digestAlgorithmIdentifiers.push(_.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[_.create(_.Class.UNIVERSAL,_.Type.OID,!1,_.oidToDer(s).getBytes()),_.create(_.Class.UNIVERSAL,_.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 o=_.derToOid(e.contentInfo.value[0].value),s=_.toDer(i);s.getByte(),_.getBerValueLength(s),s=s.getBytes();for(var a in r)r[a].start().update(s);var c=new Date;for(var u=0;u<e.signers.length;++u){var l=e.signers[u];if(l.authenticatedAttributes.length===0){if(o!==Z.pki.oids.data)throw Error("Invalid signer; authenticatedAttributes must be present when the ContentInfo content type is not PKCS#7 Data.")}else{l.authenticatedAttributesAsn1=_.create(_.Class.CONTEXT_SPECIFIC,0,!0,[]);var f=_.create(_.Class.UNIVERSAL,_.Type.SET,!0,[]);for(var p=0;p<l.authenticatedAttributes.length;++p){var h=l.authenticatedAttributes[p];if(h.type===Z.pki.oids.messageDigest)h.value=r[l.digestAlgorithm].digest();else if(h.type===Z.pki.oids.signingTime){if(!h.value)h.value=c}f.value.push(qc(h)),l.authenticatedAttributesAsn1.value.push(qc(h))}s=_.toDer(f).getBytes(),l.md.start().update(s)}l.signature=l.key.sign(l.md,"RSASSA-PKCS1-V1_5")}e.signerInfos=K1(e.signers)}};_t.createEncryptedData=function(){var e=null;return e={type:Z.pki.oids.encryptedData,version:0,encryptedContent:{algorithm:Z.pki.oids["aes256-CBC"]},fromAsn1:function(t){Xc(e,t,_t.asn1.encryptedDataValidator)},decrypt:function(t){if(t!==void 0)e.encryptedContent.key=t;Fp(e)}},e};_t.createEnvelopedData=function(){var e=null;return e={type:Z.pki.oids.envelopedData,version:0,recipients:[],encryptedContent:{algorithm:Z.pki.oids["aes256-CBC"]},fromAsn1:function(t){var n=Xc(e,t,_t.asn1.envelopedDataValidator);e.recipients=V1(n.recipientInfos.value)},toAsn1:function(){return _.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[_.create(_.Class.UNIVERSAL,_.Type.OID,!1,_.oidToDer(e.type).getBytes()),_.create(_.Class.CONTEXT_SPECIFIC,0,!0,[_.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[_.create(_.Class.UNIVERSAL,_.Type.INTEGER,!1,_.integerToDer(e.version).getBytes()),_.create(_.Class.UNIVERSAL,_.Type.SET,!0,W1(e.recipients)),_.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,Z1(e.encryptedContent))])])])},findRecipient:function(t){var n=t.issuer.attributes;for(var r=0;r<e.recipients.length;++r){var i=e.recipients[r],o=i.issuer;if(i.serialNumber!==t.serialNumber)continue;if(o.length!==n.length)continue;var s=!0;for(var a=0;a<n.length;++a)if(o[a].type!==n[a].type||o[a].value!==n[a].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 Z.pki.oids.rsaEncryption:case Z.pki.oids.desCBC:var r=n.decrypt(t.encryptedContent.content);e.encryptedContent.key=Z.util.createBuffer(r);break;default:throw Error("Unsupported asymmetric cipher, OID "+t.encryptedContent.algorithm)}Fp(e)},addRecipient:function(t){e.recipients.push({version:0,issuer:t.issuer.attributes,serialNumber:t.serialNumber,encryptedContent:{algorithm:Z.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,o;switch(n){case Z.pki.oids["aes128-CBC"]:r=16,i=16,o=Z.aes.createEncryptionCipher;break;case Z.pki.oids["aes192-CBC"]:r=24,i=16,o=Z.aes.createEncryptionCipher;break;case Z.pki.oids["aes256-CBC"]:r=32,i=16,o=Z.aes.createEncryptionCipher;break;case Z.pki.oids["des-EDE3-CBC"]:r=24,i=8,o=Z.des.createEncryptionCipher;break;default:throw Error("Unsupported symmetric cipher, OID "+n)}if(t===void 0)t=Z.util.createBuffer(Z.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=Z.util.createBuffer(Z.random.getBytes(i));var s=o(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 a=0;a<e.recipients.length;++a){var c=e.recipients[a];if(c.encryptedContent.content!==void 0)continue;switch(c.encryptedContent.algorithm){case Z.pki.oids.rsaEncryption:c.encryptedContent.content=c.encryptedContent.key.encrypt(e.encryptedContent.key.data);break;default:throw Error("Unsupported asymmetric cipher, OID "+c.encryptedContent.algorithm)}}}},e};function F1(e){var t={},n=[];if(!_.validate(e,_t.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:Z.pki.RDNAttributesAsArray(t.issuer),serialNumber:Z.util.createBuffer(t.serial).toHex(),encryptedContent:{algorithm:_.derToOid(t.encAlgorithm),parameter:t.encParameter?t.encParameter.value:void 0,content:t.encKey}}}function M1(e){return _.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[_.create(_.Class.UNIVERSAL,_.Type.INTEGER,!1,_.integerToDer(e.version).getBytes()),_.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[Z.pki.distinguishedNameToAsn1({attributes:e.issuer}),_.create(_.Class.UNIVERSAL,_.Type.INTEGER,!1,Z.util.hexToBytes(e.serialNumber))]),_.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[_.create(_.Class.UNIVERSAL,_.Type.OID,!1,_.oidToDer(e.encryptedContent.algorithm).getBytes()),_.create(_.Class.UNIVERSAL,_.Type.NULL,!1,"")]),_.create(_.Class.UNIVERSAL,_.Type.OCTETSTRING,!1,e.encryptedContent.content)])}function V1(e){var t=[];for(var n=0;n<e.length;++n)t.push(F1(e[n]));return t}function W1(e){var t=[];for(var n=0;n<e.length;++n)t.push(M1(e[n]));return t}function H1(e){var t=_.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[_.create(_.Class.UNIVERSAL,_.Type.INTEGER,!1,_.integerToDer(e.version).getBytes()),_.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[Z.pki.distinguishedNameToAsn1({attributes:e.issuer}),_.create(_.Class.UNIVERSAL,_.Type.INTEGER,!1,Z.util.hexToBytes(e.serialNumber))]),_.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[_.create(_.Class.UNIVERSAL,_.Type.OID,!1,_.oidToDer(e.digestAlgorithm).getBytes()),_.create(_.Class.UNIVERSAL,_.Type.NULL,!1,"")])]);if(e.authenticatedAttributesAsn1)t.value.push(e.authenticatedAttributesAsn1);if(t.value.push(_.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[_.create(_.Class.UNIVERSAL,_.Type.OID,!1,_.oidToDer(e.signatureAlgorithm).getBytes()),_.create(_.Class.UNIVERSAL,_.Type.NULL,!1,"")])),t.value.push(_.create(_.Class.UNIVERSAL,_.Type.OCTETSTRING,!1,e.signature)),e.unauthenticatedAttributes.length>0){var n=_.create(_.Class.CONTEXT_SPECIFIC,1,!0,[]);for(var r=0;r<e.unauthenticatedAttributes.length;++r){var i=e.unauthenticatedAttributes[r];n.values.push(qc(i))}t.value.push(n)}return t}function K1(e){var t=[];for(var n=0;n<e.length;++n)t.push(H1(e[n]));return t}function qc(e){var t;if(e.type===Z.pki.oids.contentType)t=_.create(_.Class.UNIVERSAL,_.Type.OID,!1,_.oidToDer(e.value).getBytes());else if(e.type===Z.pki.oids.messageDigest)t=_.create(_.Class.UNIVERSAL,_.Type.OCTETSTRING,!1,e.value.bytes());else if(e.type===Z.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 o=Date.parse(i);if(!isNaN(o))i=new Date(o);else if(i.length===13)i=_.utcTimeToDate(i);else i=_.generalizedTimeToDate(i)}if(i>=n&&i<r)t=_.create(_.Class.UNIVERSAL,_.Type.UTCTIME,!1,_.dateToUtcTime(i));else t=_.create(_.Class.UNIVERSAL,_.Type.GENERALIZEDTIME,!1,_.dateToGeneralizedTime(i))}return _.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[_.create(_.Class.UNIVERSAL,_.Type.OID,!1,_.oidToDer(e.type).getBytes()),_.create(_.Class.UNIVERSAL,_.Type.SET,!0,[t])])}function Z1(e){return[_.create(_.Class.UNIVERSAL,_.Type.OID,!1,_.oidToDer(Z.pki.oids.data).getBytes()),_.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[_.create(_.Class.UNIVERSAL,_.Type.OID,!1,_.oidToDer(e.algorithm).getBytes()),!e.parameter?void 0:_.create(_.Class.UNIVERSAL,_.Type.OCTETSTRING,!1,e.parameter.getBytes())]),_.create(_.Class.CONTEXT_SPECIFIC,0,!0,[_.create(_.Class.UNIVERSAL,_.Type.OCTETSTRING,!1,e.content.getBytes())])]}function Xc(e,t,n){var r={},i=[];if(!_.validate(t,n,r,i)){var o=Error("Cannot read PKCS#7 message. ASN.1 object is not a supported PKCS#7 message.");throw o.errors=o,o}var s=_.derToOid(r.contentType);if(s!==Z.pki.oids.data)throw Error("Unsupported PKCS#7 message. Only wrapped ContentType Data supported.");if(r.encryptedContent){var a="";if(Z.util.isArray(r.encryptedContent))for(var c=0;c<r.encryptedContent.length;++c){if(r.encryptedContent[c].type!==_.Type.OCTETSTRING)throw Error("Malformed PKCS#7 message, expecting encrypted content constructed of only OCTET STRING objects.");a+=r.encryptedContent[c].value}else a=r.encryptedContent;e.encryptedContent={algorithm:_.derToOid(r.encAlgorithm),parameter:Z.util.createBuffer(r.encParameter.value),content:Z.util.createBuffer(a)}}if(r.content){var a="";if(Z.util.isArray(r.content))for(var c=0;c<r.content.length;++c){if(r.content[c].type!==_.Type.OCTETSTRING)throw Error("Malformed PKCS#7 message, expecting content constructed of only OCTET STRING objects.");a+=r.content[c].value}else a=r.content;e.content=Z.util.createBuffer(a)}return e.version=r.version.charCodeAt(0),e.rawCapture=r,r}function Fp(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 Z.pki.oids["aes128-CBC"]:case Z.pki.oids["aes192-CBC"]:case Z.pki.oids["aes256-CBC"]:t=Z.aes.createDecryptionCipher(e.encryptedContent.key);break;case Z.pki.oids.desCBC:case Z.pki.oids["des-EDE3-CBC"]:t=Z.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 Hp=le(function(rP,Wp){var nt=he();Vr();Ln();Zo();Mn();Te();var bs=Wp.exports=nt.ssh=nt.ssh||{};bs.privateKeyToPutty=function(e,t,n){n=n||"",t=t||"";var r="ssh-rsa",i=t===""?"none":"aes256-cbc",o="PuTTY-User-Key-File-2: "+r+`\r
20
20
  `;o+="Encryption: "+i+`\r
21
21
  `,o+="Comment: "+n+`\r
22
- `;var s=nt.util.createBuffer();qn(s,r),yr(s,e.e),yr(s,e.n);var a=nt.util.encode64(s.bytes(),64),c=Math.floor(a.length/66)+1;o+="Public-Lines: "+c+`\r
22
+ `;var s=nt.util.createBuffer();Xn(s,r),yr(s,e.e),yr(s,e.n);var a=nt.util.encode64(s.bytes(),64),c=Math.floor(a.length/66)+1;o+="Public-Lines: "+c+`\r
23
23
  `,o+=a;var u=nt.util.createBuffer();yr(u,e.d),yr(u,e.p),yr(u,e.q),yr(u,e.qInv);var l;if(!t)l=nt.util.encode64(u.bytes(),64);else{var f=u.length()+16-1;f-=f%16;var p=xs(u.bytes());p.truncate(p.length()-f+u.length()),u.putBuffer(p);var h=nt.util.createBuffer();h.putBuffer(xs("\x00\x00\x00\x00",t)),h.putBuffer(xs("\x00\x00\x00\x01",t));var d=nt.aes.createEncryptionCipher(h.truncate(8),"CBC");d.start(nt.util.createBuffer().fillWithByte(0,16)),d.update(u.copy()),d.finish();var g=d.output;g.truncate(16),l=nt.util.encode64(g.bytes(),64)}c=Math.floor(l.length/66)+1,o+=`\r
24
24
  Private-Lines: `+c+`\r
25
- `,o+=l;var x=xs("putty-private-key-file-mac-key",t),b=nt.util.createBuffer();qn(b,r),qn(b,i),qn(b,n),b.putInt32(s.length()),b.putBuffer(s),b.putInt32(u.length()),b.putBuffer(u);var S=nt.hmac.create();return S.start("sha1",x),S.update(b.bytes()),o+=`\r
25
+ `,o+=l;var v=xs("putty-private-key-file-mac-key",t),b=nt.util.createBuffer();Xn(b,r),Xn(b,i),Xn(b,n),b.putInt32(s.length()),b.putBuffer(s),b.putInt32(u.length()),b.putBuffer(u);var S=nt.hmac.create();return S.start("sha1",v),S.update(b.bytes()),o+=`\r
26
26
  Private-MAC: `+S.digest().toHex()+`\r
27
- `,o};bs.publicKeyToOpenSSH=function(e,t){var n="ssh-rsa";t=t||"";var r=nt.util.createBuffer();return qn(r,n),yr(r,e.e),yr(r,e.n),n+" "+nt.util.encode64(r.bytes())+" "+t};bs.privateKeyToOpenSSH=function(e,t){if(!t)return nt.pki.privateKeyToPem(e);return nt.pki.encryptRsaPrivateKey(e,t,{legacy:!0,algorithm:"aes128"})};bs.getPublicKeyFingerprint=function(e,t){t=t||{};var n=t.md||nt.md.md5.create(),r="ssh-rsa",i=nt.util.createBuffer();qn(i,r),yr(i,e.e),yr(i,e.n),n.start(),n.update(i.getBytes());var o=n.digest();if(t.encoding==="hex"){var s=o.toHex();if(t.delimiter)return s.match(/.{2}/g).join(t.delimiter);return s}else if(t.encoding==="binary")return o.getBytes();else if(t.encoding)throw Error('Unknown encoding "'+t.encoding+'".');return o};function yr(e,t){var n=t.toString(16);if(n[0]>="8"&&n.length%2===0)n="00"+n;var r=nt.util.hexToBytes(n);e.putInt32(r.length),e.putBytes(r)}function qn(e,t){e.putInt32(t.length),e.putString(t)}function xs(){var e=nt.md.sha1.create(),t=arguments.length;for(var n=0;n<t;++n)e.update(arguments[n]);return e.digest()}});var Jc=le(function(nP,Hp){Hp.exports=he();Vr();pp();Qt();zo();Bi();Pp();On();Dp();Op();Up();Ec();Xo();fn();yc();kc();Mp();Pc();xc();lc();is();Ft();pc();Wp();Oc();Te()});var Vh=le(function(dR,Mh){var{create:GE,defineProperty:Os,getOwnPropertyDescriptor:qE,getOwnPropertyNames:XE,getPrototypeOf:JE}=Object,QE=Object.prototype.hasOwnProperty,YE=(e,t)=>{for(var n in t)Os(e,n,{get:t[n],enumerable:!0})},Oh=(e,t,n,r)=>{if(t&&typeof t==="object"||typeof t==="function"){for(let i of XE(t))if(!QE.call(e,i)&&i!==n)Os(e,i,{get:()=>t[i],enumerable:!(r=qE(t,i))||r.enumerable})}return e},Lh=(e,t,n)=>(n=e!=null?GE(JE(e)):{},Oh(t||!e||!e.__esModule?Os(n,"default",{value:e,enumerable:!0}):n,e)),e_=(e)=>Oh(Os({},"__esModule",{value:!0}),e),Uh={};YE(Uh,{Socks5Server:()=>Fh,createServer:()=>i_,defaultConnectionHandler:()=>Cu});Mh.exports=e_(Uh);var t_=Lh(Ci("net")),zh=((e)=>(e[e.connect=1]="connect",e[e.bind=2]="bind",e[e.udp=3]="udp",e))(zh||{}),Su=((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))(Su||{}),r_=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=(o)=>{let s=Math.min(o.length,e-r);if(o.copy(n,r,0,s),r+=s,r<e)return;this.socket.removeListener("data",i),this.socket.push(o.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,o=()=>{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()},a=await this.server.authHandler(this,o,s);if(a===!0)o();else if(a===!1)s()}async handleConnectionRequest(){await this.readBytes(1);let e=(await this.readBytes(1))[0],t=zh[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 u=(await this.readBytes(1)).readUInt8();r=(await this.readBytes(u)).toString();break;case 4:let l=await this.readBytes(16);for(let f=0;f<16;f++){if(f%2===0&&f>0)r+=":";r+=`${l[f]<16?"0":""}${l[f].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 o=!1,s=()=>{if(o)return;o=!0,this.connect()};if(!this.server.rulesetValidator)return s();let a=()=>{if(o)return;o=!0,this.socket.write(Buffer.from([5,2,0,1,0,0,0,0,0,0])),this.socket.destroy()},c=await this.server.rulesetValidator(this,s,a);if(c===!0)s();else if(c===!1)a()}connect(){this.socket.removeListener("error",this.errorHandler),this.server.connectionHandler(this,(e)=>{if(Su[e]===void 0)throw Error(`"${e}" is not a valid status.`);if(this.socket.write(Buffer.from([5,Su[e],0,1,0,0,0,0,0,0])),e!=="REQUEST_GRANTED")this.socket.destroy()}),this.socket.resume()}},n_=Lh(Ci("net"));function Cu(e,t){if(e.command!=="connect")return t("COMMAND_NOT_SUPPORTED");e.socket.on("error",()=>{});let n=n_.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 Fh=class{constructor(){this.supportedCommands=new Set(["connect"]),this.connectionHandler=Cu,this.server=t_.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=Cu,this}_handleConnection(e){return new r_(this,e),this}};function i_(e){let t=new Fh;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 WE,createServer as HE}from"http";import{request as bu}from"http";import{request as Bh}from"https";import{connect as KE,isIP as Nh}from"net";import{URL as Dh}from"url";function w(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 Wb}from"crypto";function Bo(e,t){let n=Buffer.from(e),r=Buffer.from(t);if(n.length!==r.length)return!1;return Wb(n,r)}import{homedir as No}from"os";import*as ct from"path";import*as an from"fs";import*as Sf from"fs";function Ga(){if(process.platform!=="linux")return;try{let e=Sf.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 Ie(){switch(process.platform){case"darwin":return"macos";case"linux":return"linux";case"win32":return"windows";default:return"unknown"}}var wi=[".gitconfig",".gitmodules",".bashrc",".bash_profile",".zshrc",".zprofile",".profile",".ripgreprc",".mcp.json"],Hb=[".git",".vscode",".idea"];function $o(){return[...Hb.filter((e)=>e!==".git"),".claude/commands",".claude/agents"]}function qa(e){return e.toLowerCase()}function xt(e){return e.includes("*")||e.includes("?")||e.includes("[")||e.includes("]")}function Ei(e){return e.includes("*")||e.includes("?")}function Cf(e){return Ie()==="windows"?Ei(e):xt(e)}function wf(e){if(/^\\\\\?\\unc\\/i.test(e))return"\\\\"+e.slice(8);if(e.startsWith("\\\\?\\"))return e.slice(4);return e}function _i(e){let t=ct.win32.toNamespacedPath(e);return/^[\\/]{2}[?.][\\/]unc[\\/]/i.test(t)}function Tr(e){return e.replace(/\/\*\*$/,"")||"/"}function Do(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 o=n;if(n.startsWith("/tmp/"))o="/private"+n;else if(n.startsWith("/var/"))o="/private"+n;if(o!==n&&o.startsWith(r+"/"))return!0;let s=r.startsWith(n+"/"),a=o!==n&&r.startsWith(o+"/");if(r!==n&&!(o!==n&&r===o)&&!s&&!a)return!0;return!1}function Kb(e){if(e==="~")return No();if(e.startsWith("~/")||process.platform==="win32"&&e.startsWith("~\\"))return No()+e.slice(1);return e}function Zb(e){let t=No(),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 Ef(e){let t=e.length;while(t>0&&e.charCodeAt(t-1)===47)t--;return e.slice(0,t)}function Ye(e){let t=process.cwd();if(Ie()==="windows"){if(e=wf(Zb(e)),/^[a-z]:/.test(e))e=e[0].toUpperCase()+e.slice(1);if(_i(e)&&!Ei(e))return ct.win32.normalize(e)}if(Ie()!=="windows"&&e.endsWith("/")&&e!=="/"&&!Cf(e))e=Ef(e)||"/";let n=Kb(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(Cf(n)){let r=Ie()==="windows"?/[*?]/:/[*?[\]]/,i=n.split(r)[0];if(i&&i!=="/"){let o=i.endsWith("/")?i.slice(0,-1):ct.dirname(i);try{let s=an.realpathSync(o);if(!Do(o,s)){let a=n.slice(o.length);return s+a}}catch{}}return n}try{let r=an.realpathSync(n);if(Do(n,r));else n=r}catch{}return n}function Bn(e){let t=e??No();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 jb=["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 Nn(e,t,n,r,i,o){let s=qb(o),a=s===_r?s:encodeURIComponent(s),c=r?`${a}:${r}@`:"",u=Ie()==="linux"?"127.0.0.1":"localhost",l=["SANDBOX_RUNTIME=1"];if(!i){let h=process.env.CLAUDE_CODE_TMPDIR||process.env.CLAUDE_TMPDIR||"/tmp/claude";l.push(`TMPDIR=${h}`)}if(n)for(let h of jb)l.push(`${h}=${n}`);if(!e&&!t)return l;let f=["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(l.push(`NO_PROXY=${f}`),l.push(`no_proxy=${f}`),e){if(l.push(`HTTP_PROXY=http://${c}${u}:${e}`),l.push(`HTTPS_PROXY=http://${c}${u}:${e}`),l.push(`http_proxy=http://${c}${u}:${e}`),l.push(`https_proxy=http://${c}${u}:${e}`),r)l.push("GIT_CONFIG_PARAMETERS='http.proxyAuthMethod=basic'")}let p=e?`http://${c}${u}:${e}`:`socks5h://${c}${u}:${t}`;if(l.push(`ALL_PROXY=${p}`),l.push(`all_proxy=${p}`),l.push(`GRPC_PROXY=${p}`),l.push(`grpc_proxy=${p}`),t){let d=Ie();if(d==="macos")l.push(`GIT_SSH_COMMAND=ssh -o ControlMaster=no -o ControlPath=none -o ProxyCommand='nc -X 5 -x localhost:${t} %h %p'`);else if(d==="linux"&&e){let g=r?`,proxyauth=${s}:${r}`:"";if(l.push(`GIT_SSH_COMMAND=ssh -o ControlMaster=no -o ControlPath=none -o ProxyCommand='socat - PROXY:${u}:%h:%p,proxyport=${e}${g}'`),r)l.push(`SRT_SSH_PROXY_AUTH=${s}:${r}`)}if(l.push(`FTP_PROXY=socks5h://${c}${u}:${t}`),l.push(`ftp_proxy=socks5h://${c}${u}:${t}`),l.push(`RSYNC_PROXY=${u}:${t}`),l.push(`DOCKER_HTTP_PROXY=http://${c}${u}:${e||t}`),l.push(`DOCKER_HTTPS_PROXY=http://${c}${u}:${e||t}`),e){if(l.push("CLOUDSDK_PROXY_TYPE=http"),l.push(`CLOUDSDK_PROXY_ADDRESS=${u}`),l.push(`CLOUDSDK_PROXY_PORT=${e}`),r)l.push(`CLOUDSDK_PROXY_USERNAME=${s}`),l.push(`CLOUDSDK_PROXY_PASSWORD=${r}`)}}return l}var Gb=8;function Ti(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={},o=(a,c)=>{i[`GIT_CONFIG_KEY_${r}`]=a,i[`GIT_CONFIG_VALUE_${r}`]=c,r++},s=[...new Set(e.safeDirs.filter((a)=>!!a).map((a)=>{let c=a.replace(/\\/g,"/"),u=Ef(c);if(u===""||/^[A-Za-z]:$/.test(u))return`${u}/`;return u}))];if(s.length>Gb)o("safe.directory","*");else for(let a of s)o("safe.directory",a),o("safe.directory",a.endsWith("/")?`${a}*`:`${a}/*`);if(e.schannelCa)o("http.schannelUseSSLCAInfo","true"),o("http.schannelCheckRevoke","false");if(r===n)return{};return i.GIT_CONFIG_COUNT=String(r),i}function Oo(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??{}),Ti({safeDirs:e.safeDirs,baseEnv:t})}function zt(e){let t=e.slice(0,100);return Buffer.from(t).toString("base64")}function cn(e){return Buffer.from(e,"base64").toString("utf8")}var _r="srt";function qb(e){if(!e)return _r;let t=`${_r}.${e}`;return Buffer.byteLength(t)<=255?t:_r}function Lo(e){if(!e||!e.startsWith(`${_r}.`))return;return e.slice(_r.length+1)||void 0}function Xb(e){let t=e.indexOf("[",e.lastIndexOf("]")+1);return t<0?e:`${e.slice(0,t)}\\${e.slice(t)}`}function Ai(e){return"^"+Xb(e.replace(/[.^$+{}()|\\]/g,"\\$&")).replace(/\*\*\//g,"__GLOBSTAR_SLASH__").replace(/\*\*/g,"__GLOBSTAR__").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").replace(/__GLOBSTAR_SLASH__/g,"(.*/)?").replace(/__GLOBSTAR__/g,".*")+"$"}function un(e,t={}){let n=(c)=>process.platform==="win32"?c.replace(/\\/g,"/"):c,r=n(Ye(e)),i=r.split(/[*?[\]]/)[0];if(!i||i==="/")return w(`[Sandbox] Glob pattern too broad, skipping: ${e}`),[];let o=i.endsWith("/")?i.slice(0,-1):ct.dirname(i);if(!an.existsSync(o))return w(`[Sandbox] Base directory for glob does not exist: ${o}`),[];let s=new RegExp(Ai(r),t.caseInsensitive?"i":""),a=[];try{let c=an.readdirSync(o,{recursive:!0,withFileTypes:!0});for(let u of c){let l=u.parentPath??u.path??o,f=ct.join(l,u.name);if(s.test(n(f)))a.push(f)}}catch(c){w(`[Sandbox] Error expanding glob pattern ${e}: ${c}`)}return a}var jp=ja(Jc(),1);import{sign as K1,X509Certificate as Z1}from"crypto";import{mkdtempSync as Yc,readFileSync as eu,writeFileSync as tu}from"fs";import{rm as j1}from"fs/promises";import{tmpdir as ru}from"os";import{join as Jn,dirname as Qc}from"path";import{rootCertificates as G1}from"tls";var{asn1:Qe,pki:er,md:q1,random:X1,util:Gp}=jp.default,J1=er.getTBSCertificate,Q1=/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g,Ss="/srt.crl";function nu(e){let t=e.getExtension("subjectKeyIdentifier");return t?.subjectKeyIdentifier?Gp.hexToBytes(t.subjectKeyIdentifier):e.generateSubjectKeyIdentifier().getBytes()}function iu(e,t){let n=er.oids.sha256WithRSAEncryption;e.siginfo.algorithmOid=n,e.signatureOid=n,e.tbsCertificate=J1(e);let r=Qe.toDer(e.tbsCertificate).getBytes();e.signature=qp(r,t),e.md=q1.sha256.create(),e.md.update(r)}function qp(e,t){return K1("sha256",Buffer.from(e,"binary"),t).toString("binary")}function ou(e){if(e.caCertPem&&e.caKeyPem){let t=Hi(e.caCertPem,e.caKeyPem);if(!t.ok)throw Error(`tlsTerminate: CA PEM pair: ${t.reason}`);return su(e.caCertPem,e.caKeyPem,t.cert,t.key,{certPath:e.caCertPath??"",keyPath:e.caKeyPath??"",extraCaCertPaths:e.extraCaCertPaths})}if(e.caCertPath&&e.caKeyPath)return tE(e.caCertPath,e.caKeyPath,e.extraCaCertPaths);if(e.caCertPath||e.caKeyPath)throw Error("tlsTerminate: caCertPath and caKeyPath must be provided together");return rE(e.extraCaCertPaths)}async function Xp(e){let t=new Set([Qc(e.trustBundlePath)]);if(e.ephemeral){if(t.add(Qc(e.certPath)),e.keyPath)t.add(Qc(e.keyPath))}for(let n of t)try{await j1(n,{recursive:!0,force:!0})}catch(r){w(`[mitm-ca] cleanup failed: ${r.message}`,{level:"warn"})}}function Y1(e,t,n){let r=[t.trim(),...G1],i=process.env.NODE_EXTRA_CA_CERTS;if(i)try{r.push(eu(i,"utf8").trim())}catch{}for(let s of n??[]){let a;try{a=eu(s,"utf8")}catch(u){let l=u.code??String(u);w(`[mitm-ca] extraCaCertPaths: cannot read ${s} (${l}); skipping`,{level:"warn"});continue}let c=a.match(Q1);if(!c){w(`[mitm-ca] extraCaCertPaths: ${s} has no PEM CERTIFICATE block; skipping`,{level:"warn"});continue}r.push(...c)}let o=Jn(e,"trust-bundle.crt");return tu(o,r.join(`
27
+ `,o};bs.publicKeyToOpenSSH=function(e,t){var n="ssh-rsa";t=t||"";var r=nt.util.createBuffer();return Xn(r,n),yr(r,e.e),yr(r,e.n),n+" "+nt.util.encode64(r.bytes())+" "+t};bs.privateKeyToOpenSSH=function(e,t){if(!t)return nt.pki.privateKeyToPem(e);return nt.pki.encryptRsaPrivateKey(e,t,{legacy:!0,algorithm:"aes128"})};bs.getPublicKeyFingerprint=function(e,t){t=t||{};var n=t.md||nt.md.md5.create(),r="ssh-rsa",i=nt.util.createBuffer();Xn(i,r),yr(i,e.e),yr(i,e.n),n.start(),n.update(i.getBytes());var o=n.digest();if(t.encoding==="hex"){var s=o.toHex();if(t.delimiter)return s.match(/.{2}/g).join(t.delimiter);return s}else if(t.encoding==="binary")return o.getBytes();else if(t.encoding)throw Error('Unknown encoding "'+t.encoding+'".');return o};function yr(e,t){var n=t.toString(16);if(n[0]>="8"&&n.length%2===0)n="00"+n;var r=nt.util.hexToBytes(n);e.putInt32(r.length),e.putBytes(r)}function Xn(e,t){e.putInt32(t.length),e.putString(t)}function xs(){var e=nt.md.sha1.create(),t=arguments.length;for(var n=0;n<t;++n)e.update(arguments[n]);return e.digest()}});var Jc=le(function(nP,Kp){Kp.exports=he();Vr();hp();Qt();zo();Di();Rp();Ln();$p();Lp();zp();Ec();Xo();fn();yc();kc();Vp();Pc();xc();lc();is();Ft();pc();Hp();Oc();Te()});var Wh=le(function(dR,Vh){var{create:qE,defineProperty:Os,getOwnPropertyDescriptor:XE,getOwnPropertyNames:JE,getPrototypeOf:QE}=Object,YE=Object.prototype.hasOwnProperty,e_=(e,t)=>{for(var n in t)Os(e,n,{get:t[n],enumerable:!0})},Lh=(e,t,n,r)=>{if(t&&typeof t==="object"||typeof t==="function"){for(let i of JE(t))if(!YE.call(e,i)&&i!==n)Os(e,i,{get:()=>t[i],enumerable:!(r=XE(t,i))||r.enumerable})}return e},Uh=(e,t,n)=>(n=e!=null?qE(QE(e)):{},Lh(t||!e||!e.__esModule?Os(n,"default",{value:e,enumerable:!0}):n,e)),t_=(e)=>Lh(Os({},"__esModule",{value:!0}),e),zh={};e_(zh,{Socks5Server:()=>Mh,createServer:()=>o_,defaultConnectionHandler:()=>wu});Vh.exports=t_(zh);var r_=Uh(Ei("net")),Fh=((e)=>(e[e.connect=1]="connect",e[e.bind=2]="bind",e[e.udp=3]="udp",e))(Fh||{}),Cu=((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))(Cu||{}),n_=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=(o)=>{let s=Math.min(o.length,e-r);if(o.copy(n,r,0,s),r+=s,r<e)return;this.socket.removeListener("data",i),this.socket.push(o.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,o=()=>{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()},a=await this.server.authHandler(this,o,s);if(a===!0)o();else if(a===!1)s()}async handleConnectionRequest(){await this.readBytes(1);let e=(await this.readBytes(1))[0],t=Fh[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 u=(await this.readBytes(1)).readUInt8();r=(await this.readBytes(u)).toString();break;case 4:let l=await this.readBytes(16);for(let f=0;f<16;f++){if(f%2===0&&f>0)r+=":";r+=`${l[f]<16?"0":""}${l[f].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 o=!1,s=()=>{if(o)return;o=!0,this.connect()};if(!this.server.rulesetValidator)return s();let a=()=>{if(o)return;o=!0,this.socket.write(Buffer.from([5,2,0,1,0,0,0,0,0,0])),this.socket.destroy()},c=await this.server.rulesetValidator(this,s,a);if(c===!0)s();else if(c===!1)a()}connect(){this.socket.removeListener("error",this.errorHandler),this.server.connectionHandler(this,(e)=>{if(Cu[e]===void 0)throw Error(`"${e}" is not a valid status.`);if(this.socket.write(Buffer.from([5,Cu[e],0,1,0,0,0,0,0,0])),e!=="REQUEST_GRANTED")this.socket.destroy()}),this.socket.resume()}},i_=Uh(Ei("net"));function wu(e,t){if(e.command!=="connect")return t("COMMAND_NOT_SUPPORTED");e.socket.on("error",()=>{});let n=i_.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 Mh=class{constructor(){this.supportedCommands=new Set(["connect"]),this.connectionHandler=wu,this.server=r_.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=wu,this}_handleConnection(e){return new n_(this,e),this}};function o_(e){let t=new Mh;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 HE,createServer as KE}from"http";import{request as Su}from"http";import{request as Nh}from"https";import{connect as ZE,isIP as Dh}from"net";import{URL as $h}from"url";function w(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 Kb}from"crypto";function Bo(e,t){let n=Buffer.from(e),r=Buffer.from(t);if(n.length!==r.length)return!1;return Kb(n,r)}import{homedir as No}from"os";import*as ct from"path";import*as an from"fs";import*as Cf from"fs";function Ga(){if(process.platform!=="linux")return;try{let e=Cf.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 Ie(){switch(process.platform){case"darwin":return"macos";case"linux":return"linux";case"win32":return"windows";default:return"unknown"}}var _i=[".gitconfig",".gitmodules",".bashrc",".bash_profile",".zshrc",".zprofile",".profile",".ripgreprc",".mcp.json"],Zb=[".git",".vscode",".idea"];function $o(){return[...Zb.filter((e)=>e!==".git"),".claude/commands",".claude/agents"]}function qa(e){return e.toLowerCase()}function bt(e){return e.includes("*")||e.includes("?")||e.includes("[")||e.includes("]")}function Ti(e){return e.includes("*")||e.includes("?")}function wf(e){return Ie()==="windows"?Ti(e):bt(e)}function Ef(e){if(/^\\\\\?\\unc\\/i.test(e))return"\\\\"+e.slice(8);if(e.startsWith("\\\\?\\"))return e.slice(4);return e}function Ai(e){let t=ct.win32.toNamespacedPath(e);return/^[\\/]{2}[?.][\\/]unc[\\/]/i.test(t)}function Tr(e){return e.replace(/\/\*\*$/,"")||"/"}function Do(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 o=n;if(n.startsWith("/tmp/"))o="/private"+n;else if(n.startsWith("/var/"))o="/private"+n;if(o!==n&&o.startsWith(r+"/"))return!0;let s=r.startsWith(n+"/"),a=o!==n&&r.startsWith(o+"/");if(r!==n&&!(o!==n&&r===o)&&!s&&!a)return!0;return!1}function jb(e){if(e==="~")return No();if(e.startsWith("~/")||process.platform==="win32"&&e.startsWith("~\\"))return No()+e.slice(1);return e}function Gb(e){let t=No(),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 _f(e){let t=e.length;while(t>0&&e.charCodeAt(t-1)===47)t--;return e.slice(0,t)}function Ye(e){let t=process.cwd();if(Ie()==="windows"){if(e=Ef(Gb(e)),/^[a-z]:/.test(e))e=e[0].toUpperCase()+e.slice(1);if(Ai(e)&&!Ti(e))return ct.win32.normalize(e)}if(Ie()!=="windows"&&e.endsWith("/")&&e!=="/"&&!wf(e))e=_f(e)||"/";let n=jb(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(wf(n)){let r=Ie()==="windows"?/[*?]/:/[*?[\]]/,i=n.split(r)[0];if(i&&i!=="/"){let o=i.endsWith("/")?i.slice(0,-1):ct.dirname(i);try{let s=an.realpathSync(o);if(!Do(o,s)){let a=n.slice(o.length);return s+a}}catch{}}return n}try{let r=an.realpathSync(n);if(Do(n,r));else n=r}catch{}return n}function Nn(e){let t=e??No();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 qb=["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 Dn(e,t,n,r,i,o){let s=Jb(o),a=s===_r?s:encodeURIComponent(s),c=r?`${a}:${r}@`:"",u=Ie()==="linux"?"127.0.0.1":"localhost",l=["SANDBOX_RUNTIME=1"];if(!i){let h=process.env.CLAUDE_CODE_TMPDIR||process.env.CLAUDE_TMPDIR||"/tmp/claude";l.push(`TMPDIR=${h}`)}if(n)for(let h of qb)l.push(`${h}=${n}`);if(!e&&!t)return l;let f=["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(l.push(`NO_PROXY=${f}`),l.push(`no_proxy=${f}`),e){if(l.push(`HTTP_PROXY=http://${c}${u}:${e}`),l.push(`HTTPS_PROXY=http://${c}${u}:${e}`),l.push(`http_proxy=http://${c}${u}:${e}`),l.push(`https_proxy=http://${c}${u}:${e}`),r)l.push("GIT_CONFIG_PARAMETERS='http.proxyAuthMethod=basic'")}let p=e?`http://${c}${u}:${e}`:`socks5h://${c}${u}:${t}`;if(l.push(`ALL_PROXY=${p}`),l.push(`all_proxy=${p}`),l.push(`GRPC_PROXY=${p}`),l.push(`grpc_proxy=${p}`),t){let d=Ie();if(d==="macos")l.push(`GIT_SSH_COMMAND=ssh -o ControlMaster=no -o ControlPath=none -o ProxyCommand='nc -X 5 -x localhost:${t} %h %p'`);else if(d==="linux"&&e){let g=r?`,proxyauth=${s}:${r}`:"";if(l.push(`GIT_SSH_COMMAND=ssh -o ControlMaster=no -o ControlPath=none -o ProxyCommand='socat - PROXY:${u}:%h:%p,proxyport=${e}${g}'`),r)l.push(`SRT_SSH_PROXY_AUTH=${s}:${r}`)}if(l.push(`FTP_PROXY=socks5h://${c}${u}:${t}`),l.push(`ftp_proxy=socks5h://${c}${u}:${t}`),l.push(`RSYNC_PROXY=${u}:${t}`),l.push(`DOCKER_HTTP_PROXY=http://${c}${u}:${e||t}`),l.push(`DOCKER_HTTPS_PROXY=http://${c}${u}:${e||t}`),e){if(l.push("CLOUDSDK_PROXY_TYPE=http"),l.push(`CLOUDSDK_PROXY_ADDRESS=${u}`),l.push(`CLOUDSDK_PROXY_PORT=${e}`),r)l.push(`CLOUDSDK_PROXY_USERNAME=${s}`),l.push(`CLOUDSDK_PROXY_PASSWORD=${r}`)}}return l}var Xb=8;function ki(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={},o=(a,c)=>{i[`GIT_CONFIG_KEY_${r}`]=a,i[`GIT_CONFIG_VALUE_${r}`]=c,r++},s=[...new Set(e.safeDirs.filter((a)=>!!a).map((a)=>{let c=a.replace(/\\/g,"/"),u=_f(c);if(u===""||/^[A-Za-z]:$/.test(u))return`${u}/`;return u}))];if(s.length>Xb)o("safe.directory","*");else for(let a of s)o("safe.directory",a),o("safe.directory",a.endsWith("/")?`${a}*`:`${a}/*`);if(e.schannelCa)o("http.schannelUseSSLCAInfo","true"),o("http.schannelCheckRevoke","false");if(r===n)return{};return i.GIT_CONFIG_COUNT=String(r),i}function Oo(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??{}),ki({safeDirs:e.safeDirs,baseEnv:t})}function zt(e){let t=e.slice(0,100);return Buffer.from(t).toString("base64")}function cn(e){return Buffer.from(e,"base64").toString("utf8")}var _r="srt";function Jb(e){if(!e)return _r;let t=`${_r}.${e}`;return Buffer.byteLength(t)<=255?t:_r}function Lo(e){if(!e||!e.startsWith(`${_r}.`))return;return e.slice(_r.length+1)||void 0}function Qb(e){let t=e.indexOf("[",e.lastIndexOf("]")+1);return t<0?e:`${e.slice(0,t)}\\${e.slice(t)}`}function Ii(e){return"^"+Qb(e.replace(/[.^$+{}()|\\]/g,"\\$&")).replace(/\*\*\//g,"__GLOBSTAR_SLASH__").replace(/\*\*/g,"__GLOBSTAR__").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").replace(/__GLOBSTAR_SLASH__/g,"(.*/)?").replace(/__GLOBSTAR__/g,".*")+"$"}function un(e,t={}){let n=(c)=>process.platform==="win32"?c.replace(/\\/g,"/"):c,r=n(Ye(e)),i=r.split(/[*?[\]]/)[0];if(!i||i==="/")return w(`[Sandbox] Glob pattern too broad, skipping: ${e}`),[];let o=i.endsWith("/")?i.slice(0,-1):ct.dirname(i);if(!an.existsSync(o))return w(`[Sandbox] Base directory for glob does not exist: ${o}`),[];let s=new RegExp(Ii(r),t.caseInsensitive?"i":""),a=[];try{let c=an.readdirSync(o,{recursive:!0,withFileTypes:!0});for(let u of c){let l=u.parentPath??u.path??o,f=ct.join(l,u.name);if(s.test(n(f)))a.push(f)}}catch(c){w(`[Sandbox] Error expanding glob pattern ${e}: ${c}`)}return a}var Gp=ja(Jc(),1);import{sign as j1,X509Certificate as G1}from"crypto";import{mkdtempSync as Yc,readFileSync as eu,writeFileSync as tu}from"fs";import{rm as q1}from"fs/promises";import{tmpdir as ru}from"os";import{join as Qn,dirname as Qc}from"path";import{rootCertificates as X1}from"tls";var{asn1:Qe,pki:er,md:J1,random:Q1,util:qp}=Gp.default,Y1=er.getTBSCertificate,eE=/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g,Ss="/srt.crl";function nu(e){let t=e.getExtension("subjectKeyIdentifier");return t?.subjectKeyIdentifier?qp.hexToBytes(t.subjectKeyIdentifier):e.generateSubjectKeyIdentifier().getBytes()}function iu(e,t){let n=er.oids.sha256WithRSAEncryption;e.siginfo.algorithmOid=n,e.signatureOid=n,e.tbsCertificate=Y1(e);let r=Qe.toDer(e.tbsCertificate).getBytes();e.signature=Xp(r,t),e.md=J1.sha256.create(),e.md.update(r)}function Xp(e,t){return j1("sha256",Buffer.from(e,"binary"),t).toString("binary")}function ou(e){if(e.caCertPem&&e.caKeyPem){let t=Zi(e.caCertPem,e.caKeyPem);if(!t.ok)throw Error(`tlsTerminate: CA PEM pair: ${t.reason}`);return su(e.caCertPem,e.caKeyPem,t.cert,t.key,{certPath:e.caCertPath??"",keyPath:e.caKeyPath??"",extraCaCertPaths:e.extraCaCertPaths})}if(e.caCertPath&&e.caKeyPath)return nE(e.caCertPath,e.caKeyPath,e.extraCaCertPaths);if(e.caCertPath||e.caKeyPath)throw Error("tlsTerminate: caCertPath and caKeyPath must be provided together");return iE(e.extraCaCertPaths)}async function Jp(e){let t=new Set([Qc(e.trustBundlePath)]);if(e.ephemeral){if(t.add(Qc(e.certPath)),e.keyPath)t.add(Qc(e.keyPath))}for(let n of t)try{await q1(n,{recursive:!0,force:!0})}catch(r){w(`[mitm-ca] cleanup failed: ${r.message}`,{level:"warn"})}}function tE(e,t,n){let r=[t.trim(),...X1],i=process.env.NODE_EXTRA_CA_CERTS;if(i)try{r.push(eu(i,"utf8").trim())}catch{}for(let s of n??[]){let a;try{a=eu(s,"utf8")}catch(u){let l=u.code??String(u);w(`[mitm-ca] extraCaCertPaths: cannot read ${s} (${l}); skipping`,{level:"warn"});continue}let c=a.match(eE);if(!c){w(`[mitm-ca] extraCaCertPaths: ${s} has no PEM CERTIFICATE block; skipping`,{level:"warn"});continue}r.push(...c)}let o=Qn(e,"trust-bundle.crt");return tu(o,r.join(`
28
28
  `)+`
29
- `,{mode:420}),o}function eE(e,t){let n=er.oids.sha256WithRSAEncryption,r=()=>Xn([Qe.create(jt.UNIVERSAL,vr.OID,!1,Qe.oidToDer(n).getBytes()),Qe.create(jt.UNIVERSAL,vr.NULL,!1,"")]),i=(p,h)=>Xn([Qe.create(jt.UNIVERSAL,vr.OID,!1,Qe.oidToDer(p).getBytes()),Qe.create(jt.UNIVERSAL,vr.OCTETSTRING,!1,Qe.toDer(h).getBytes())]),o=Qe.create(jt.CONTEXT_SPECIFIC,0,!0,[Xn([i(er.oids.authorityKeyIdentifier,Xn([Qe.create(jt.CONTEXT_SPECIFIC,0,!1,nu(e))])),i("2.5.29.20",Qe.create(jt.UNIVERSAL,vr.INTEGER,!1,"\x01"))])]),s=new Date,a=e.validity.notAfter,c=a>s?a:Wi(1),u=Xn([Qe.create(jt.UNIVERSAL,vr.INTEGER,!1,"\x01"),r(),er.distinguishedNameToAsn1(e.subject),Kp(s),Kp(c),o]),l=qp(Qe.toDer(u).getBytes(),t),f=Xn([u,r(),Qe.create(jt.UNIVERSAL,vr.BITSTRING,!1,"\x00"+l)]);return Buffer.from(Qe.toDer(f).getBytes(),"binary")}var{Class:jt,Type:vr}=Qe;function Xn(e){return Qe.create(jt.UNIVERSAL,vr.SEQUENCE,!0,e)}function Kp(e){return e.getUTCFullYear()<2050?Qe.create(jt.UNIVERSAL,vr.UTCTIME,!1,Qe.dateToUtcTime(e)):Qe.create(jt.UNIVERSAL,vr.GENERALIZEDTIME,!1,Qe.dateToGeneralizedTime(e))}function tE(e,t,n){let r=Zp(e,"CERTIFICATE","tlsTerminate.caCertPath"),i=Zp(t,"PRIVATE KEY","tlsTerminate.caKeyPath"),o=Hi(r,i);if(!o.ok)throw Error(`tlsTerminate: CA at ${e}: ${o.reason}`);return w(`[mitm-ca] loaded CA from ${e}`),su(r,i,o.cert,o.key,{certPath:e,keyPath:t,extraCaCertPaths:n})}function su(e,t,n,r,i){let o=Yc(Jn(ru(),"srt-ca-"));return{certPath:i.certPath,keyPath:i.keyPath,trustBundlePath:Y1(o,e,i.extraCaCertPaths),certPem:e,keyPem:t,cert:n,key:r,leafCerts:new Map,secureContexts:new Map,crlDer:eE(n,t),ephemeral:i.ephemeral??!1}}function Cs(e={}){let t=er.rsa.generateKeyPair(2048),n=er.createCertificate();n.publicKey=t.publicKey,n.serialNumber=au(),n.validity.notBefore=Wi(-1),n.validity.notAfter=Wi(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=er.privateKeyToPem(t.privateKey);return iu(n,i),{certPem:er.certificateToPem(n),keyPem:i,cert:n,key:t.privateKey}}function Qn(e){return new Z1(e).fingerprint.replace(/:/g,"").toUpperCase()}function Hi(e,t){let n,r;try{n=er.certificateFromPem(e),r=er.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 o;try{o=Qn(e)}catch(s){return{ok:!1,reason:`thumbprint: ${s.message}`}}return{ok:!0,thumbprint:o,notAfter:n.validity.notAfter,cert:n,key:r}}function rE(e){let{certPem:t,keyPem:n,cert:r,key:i}=Cs(),o=Yc(Jn(ru(),"srt-ca-")),s=Jn(o,"ca.crt"),a=Jn(Yc(Jn(ru(),"srt-ca-key-")),"ca.key");return tu(s,t,{mode:420}),tu(a,n,{mode:384}),w(`[mitm-ca] generated ephemeral CA at ${s}`),su(t,n,r,i,{certPath:s,keyPath:a,extraCaCertPaths:e,ephemeral:!0})}function Zp(e,t,n){let r;try{r=eu(e,"utf8")}catch(i){let o=i.code??String(i);throw Error(`${n}: cannot read ${e} (${o})`)}if(!new RegExp(`-----BEGIN [A-Z ]*${t}-----`).test(r))throw Error(`${n}: ${e} is not a PEM ${t}`);return r}function au(){let e=X1.getBytesSync(16),t=Gp.bytesToHex(e);return(parseInt(t[0],16)&7).toString(16)+t.slice(1)}function Wi(e){let t=new Date;return t.setDate(t.getDate()+e),t}import{BlockList as Qp,isIP as Yn}from"net";import{lookup as nE}from"dns/promises";import{networkInterfaces as iE}from"os";var Ki=new Qp;for(let[e,t]of[["0.0.0.0",8],["10.0.0.0",8],["100.64.0.0",10],["127.0.0.0",8],["169.254.0.0",16],["172.16.0.0",12],["192.0.0.0",24],["192.0.2.0",24],["192.168.0.0",16],["198.18.0.0",15],["198.51.100.0",24],["203.0.113.0",24],["224.0.0.0",4],["240.0.0.0",4]])Ki.addSubnet(e,t,"ipv4");for(let[e,t]of[["::",128],["::1",128],["64:ff9b:1::",48],["100::",64],["2001:db8::",32],["fc00::",7],["fe80::",10],["fec0::",10],["ff00::",8]])Ki.addSubnet(e,t,"ipv6");function Jp(e){let t=e.toLowerCase(),n=t.indexOf("%");if(n>=0)t=t.slice(0,n);if(Yn(t)!==6)return;let r=/^(.*:)(\d+)\.(\d+)\.(\d+)\.(\d+)$/.exec(t);if(r){let[u,l,f,p]=r.slice(2).map(Number);t=`${r[1]}${(u<<8|l).toString(16)}:${(f<<8|p).toString(16)}`}let[i,o]=t.split("::"),s=(u)=>u===""?[]:u.split(":").map((l)=>parseInt(l,16)),a=s(i);if(o===void 0)return a.length===8?a:void 0;let c=s(o);if(a.length+c.length>7)return;return[...a,...Array(8-a.length-c.length).fill(0),...c]}function ws(e,t){return`${e>>8}.${e&255}.${t>>8}.${t&255}`}function oE(e){let t=/^::(?:ffff:(?:0:)?)?(\d+\.\d+\.\d+\.\d+)$/i.exec(e);if(t)return t[1];let n=/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i.exec(e);if(!n)return;let r=parseInt(n[1],16),i=parseInt(n[2],16);return`${r>>8}.${r&255}.${i>>8}.${i&255}`}function _s(e){let t=e.replace(/^\[|\]$/g,""),n=Yn(t);if(n===0)return!1;if(n===4)return!Ki.check(t,"ipv4");let r=oE(t);if(r!==void 0)return Yn(r)===4&&!Ki.check(r,"ipv4");return!Ki.check(t,"ipv6")}function Ts(e){let t=e.toLowerCase().replace(/\.$/,"");return t==="localhost"||t.endsWith(".localhost")||t==="localhost.localdomain"}class Rr extends Error{}class Es extends Rr{constructor(e,t){super(t===void 0?`${e} is not on the public internet`:`${e} resolves to ${t}, which is not on the public internet`);this.name="NonPublicDestinationError"}}class Yp extends Rr{constructor(e,t){super(`${e} resolves to ${t}, an address of this machine or its link-local network; the allowlist admits the name, not services on this machine`);this.name="LocalDestinationError"}}var eh=(e)=>nE(e,{all:!0,verbatim:!0});async function th(e,t=eh){let n=e.replace(/^\[|\]$/g,"");if(Yn(n)){if(!_s(n))throw new Es(e);return n}if(Ts(n))throw new Es(e);let r=await t(n);if(r.length===0)throw Error(`${e} did not resolve`);for(let{address:i}of r)if(!_s(i))throw new Es(e,i);return(r.find((i)=>i.family===4)??r[0]).address}var Zi=new Qp;Zi.addSubnet("0.0.0.0",8,"ipv4");Zi.addSubnet("127.0.0.0",8,"ipv4");Zi.addSubnet("169.254.0.0",16,"ipv4");function sE(){return Object.values(iE()).flatMap((e)=>(e??[]).map((t)=>t.address))}function aE(e){let[t,n,r,i,o,s,a,c]=e,u=ws(a,c);if(t===0&&n===0&&r===0&&i===0){if(o===0&&(s===0||s===65535)||o===65535&&s===0)return[u];return[]}if(t===100&&n===65435)return[u];if(t===8194)return[ws(n,r)];if(t===8193&&n===0)return[ws(r,i),ws(a^65535,c^65535)];return[]}function cE(e,t=sE()){let n=e.replace(/^\[|\]$/g,"");if(Yn(n)===4)return Zi.check(n,"ipv4")||t.includes(n);let r=Jp(n);if(r===void 0)return!0;if(r.slice(0,7).every((o)=>o===0)&&r[7]<=1)return!0;if((r[0]&65472)===65152)return!0;if(aE(r).some((o)=>Zi.check(o,"ipv4")||t.includes(o)))return!0;let i=r.join(":");return t.some((o)=>Jp(o)?.join(":")===i)}async function rh(e,t=eh,n){let r=e.replace(/^\[|\]$/g,"");if(Yn(r)||Ts(r))return r;let i=await t(r);if(i.length===0)throw Error(`${e} did not resolve`);for(let{address:o}of i)if(cE(o,n))throw new Yp(e,o);return(i.find((o)=>o.family===4)??i[0]).address}import{PassThrough as uE,Readable as nh}from"stream";var cu=new Set(["GET","HEAD","OPTIONS"]),As="denied by sandbox policy";function ih(e,t){if(t.writableFinished||t.destroyed){e.destroy();return}t.once("finish",()=>e.destroy()),t.once("close",()=>e.destroy())}async function ks(e,t,n,r,i,o){let s=t.method??"GET",a,c=t,u=Boolean(t.headers["content-length"]||t.headers["transfer-encoding"]),l=cu.has(s);if(!l||u){let h=new uE;h.on("error",()=>{}),t.pipe(h);let d=nh.toWeb(h),[g,x]=d.tee();a=g,c=nh.fromWeb(x);let b=c;b.on("error",()=>{}),t.on("error",(S)=>{h.end(),b.destroy(S)})}let f;try{if(a&&!(a instanceof ReadableStream))throw TypeError("Unexpected request body stream");let h=a&&!l?{body:a,duplex:"half"}:{};f=new Request(r,{method:s,headers:ah(t),signal:i,...h})}catch(h){let d=`malformed request: ${h.message}`;if(o?.(s,r,d),oh(n,{action:"deny",reason:d}),a?.cancel().catch(()=>{}),c.destroy(),c!==t)ih(t,n);return null}let p;try{p=await e(f)}catch(h){p={action:"deny",reason:`sandbox policy check failed: ${h.message}`}}if(a&&!f.bodyUsed)a.cancel().catch(()=>{});if(p.action==="allow")return w(`[request-filter] allow ${s} ${r}`),c;if(o?.(s,r,p.reason??As),oh(n,p),c.destroy(),c!==t)ih(t,n);return null}async function sh(e,t,n,r){let i=t.method??"GET",o;try{o=new Request(n,{method:i,headers:ah(t),signal:r})}catch(s){return{action:"deny",reason:`malformed request: ${s.message}`}}try{let s=await e(o);if(s.action==="allow")w(`[request-filter] allow upgrade ${i} ${n}`);return s}catch(s){return{action:"deny",reason:`sandbox policy check failed: ${s.message}`}}}function oh(e,t){ei(e,t.reason??As)}function ei(e,t){if(w(`[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+`
30
- `)}function ah(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 RE,request as _h}from"https";import{STATUS_CODES as Th}from"http";import{connect as BE,isIP as ni}from"net";import{unlink as NE}from"fs";import{tmpdir as DE}from"os";import{join as $E}from"path";import{Transform as lE}from"stream";function fE(e){return e.every((t)=>t.sentinel.length===t.realValue.length)}function Is(e,t,n,r){if(e===void 0)return;let i=t.headers["content-length"]!==void 0||t.headers["transfer-encoding"]!==void 0;if(cu.has(t.method??"GET")&&!i)return;let o=e(r);if(!o?.length)return;if(t.headers["content-encoding"]!==void 0){w(`[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(!fE(o))delete n["content-length"];return dE(o)}function dE(e){let t=Math.max(...e.map((r)=>r.sentinel.length)),n;return new lE({transform(r,i,o){let s=Buffer.isBuffer(r)?r:Buffer.from(r,i),a=n?.length?Buffer.concat([n,s]):s,{out:c,tail:u}=pE(a,e,t);n=u,o(null,c)},flush(r){r(null,n?.length?n:void 0)}})}function pE(e,t,n){let r=[],i=0;for(;;){let s=-1,a;for(let c of t){let u=e.indexOf(c.sentinel,i);if(u!==-1&&(s===-1||u<s))s=u,a=c}if(a===void 0)break;r.push(e.subarray(i,s),a.realValue),i=s+a.sentinel.length}let o=Math.max(i,e.length-(n-1));return r.push(e.subarray(i,o)),{out:Buffer.concat(r),tail:Buffer.from(e.subarray(o))}}var ch=ja(Jc(),1);import{isIP as hE}from"net";import{createSecureContext as mE}from"tls";var{pki:Ps}=ch.default;function uu(e,t){let n=e.leafCerts.get(t);if(n)return n;let r=Ps.rsa.generateKeyPair(2048),i=Ps.createCertificate();i.publicKey=r.publicKey,i.serialNumber=au();let o=Wi(-1);i.validity.notBefore=o,i.validity.notAfter=yE(e.cert,o),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:[gE(t)]},{name:"subjectKeyIdentifier"},{name:"authorityKeyIdentifier",keyIdentifier:nu(e.cert)},...e.crlUrl?[{name:"cRLDistributionPoints",altNames:[{type:6,value:e.crlUrl}]}]:[]]),iu(i,e.keyPem);let s={certPem:Ps.certificateToPem(i)+e.certPem,keyPem:Ps.privateKeyToPem(r.privateKey)};return e.leafCerts.set(t,s),w(`[mitm-leaf] minted RSA leaf for ${t}`),s}function uh(e,t){let n=e.secureContexts.get(t);if(n)return n;let{certPem:r,keyPem:i}=uu(e,t),o=mE({cert:r,key:i});return e.secureContexts.set(t,o),o}function gE(e){return hE(e)!==0?{type:7,ip:e}:{type:2,value:e}}function yE(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 lh,connect as fh,isIP as bn}from"net";import{connect as vE}from"tls";import{URL as lu}from"url";var dh=30000,xE=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","proxy-connection","te","trailer","transfer-encoding","upgrade"]);function fu(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=(a)=>{if(!a)return;let u=/^[a-z][a-z0-9+.-]*:\/\//i.test(a)?a:`http://${a}`;try{let l=new lu(u);if(l.protocol!=="http:"&&l.protocol!=="https:"||!l.hostname)throw Error("unsupported scheme or empty host");return l}catch{w(`Invalid parent proxy URL, ignoring: ${CE(a)}`,{level:"error"});return}},o=i(t),s=i(n);if(!o&&!s)return;return{httpUrl:o,httpsUrl:s,noProxy:bE(r)}}function bE(e){let t={all:!1,suffixes:[],cidr:new lh};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 a=n.slice(0,r),c=n.slice(r+1),u=bn(a);if(u&&c!==""&&/^\d+$/.test(c)){let l=Number(c),f=u===6?128:32;if(l>=0&&l<=f){try{t.cidr.addSubnet(a,l,u===6?"ipv6":"ipv4")}catch{}continue}}continue}let i=n.toLowerCase(),o=/^\[([^\]]+)\](?::\d+)?$/.exec(i);if(o)i=o[1];if(i.startsWith("*."))i=i.slice(1);let s=bn(i);if(!s){let a=i.lastIndexOf(":");if(a!==-1&&/^\d+$/.test(i.slice(a+1)))i=i.slice(0,a)}else try{t.cidr.addAddress(i,s===6?"ipv6":"ipv4");continue}catch{}t.suffixes.push(i)}return t}function ji(e,t){let n=tr(t.toLowerCase().replace(/\.$/,""));if(n==="localhost")return!0;let r=bn(n);if(r){if(SE.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 SE=(()=>{let e=new lh;return e.addSubnet("127.0.0.0",8,"ipv4"),e.addAddress("::1","ipv6"),e.addSubnet("::ffff:127.0.0.0",104,"ipv6"),e})();function Gi(e,t){if(t.isHttps)return e.httpsUrl??e.httpUrl;return e.httpUrl}function du(e){let{destHost:t,destPort:n}=e,r=tr(t);if(!ti(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=bn(r)===6?`[${r}]:${n}`:`${r}:${n}`;return new Promise((o,s)=>{let a=e.dial(),c=!1,u=(f)=>{if(c)return;c=!0,a.destroy(),s(f)},l=()=>u(Error("Proxy closed during CONNECT handshake"));a.setTimeout(e.timeoutMs??dh,()=>u(Error("CONNECT handshake timed out"))),a.once("error",u),a.once("close",l),a.once(e.readyEvent,()=>{a.write(`CONNECT ${i} HTTP/1.1\r
29
+ `,{mode:420}),o}function rE(e,t){let n=er.oids.sha256WithRSAEncryption,r=()=>Jn([Qe.create(jt.UNIVERSAL,vr.OID,!1,Qe.oidToDer(n).getBytes()),Qe.create(jt.UNIVERSAL,vr.NULL,!1,"")]),i=(p,h)=>Jn([Qe.create(jt.UNIVERSAL,vr.OID,!1,Qe.oidToDer(p).getBytes()),Qe.create(jt.UNIVERSAL,vr.OCTETSTRING,!1,Qe.toDer(h).getBytes())]),o=Qe.create(jt.CONTEXT_SPECIFIC,0,!0,[Jn([i(er.oids.authorityKeyIdentifier,Jn([Qe.create(jt.CONTEXT_SPECIFIC,0,!1,nu(e))])),i("2.5.29.20",Qe.create(jt.UNIVERSAL,vr.INTEGER,!1,"\x01"))])]),s=new Date,a=e.validity.notAfter,c=a>s?a:Ki(1),u=Jn([Qe.create(jt.UNIVERSAL,vr.INTEGER,!1,"\x01"),r(),er.distinguishedNameToAsn1(e.subject),Zp(s),Zp(c),o]),l=Xp(Qe.toDer(u).getBytes(),t),f=Jn([u,r(),Qe.create(jt.UNIVERSAL,vr.BITSTRING,!1,"\x00"+l)]);return Buffer.from(Qe.toDer(f).getBytes(),"binary")}var{Class:jt,Type:vr}=Qe;function Jn(e){return Qe.create(jt.UNIVERSAL,vr.SEQUENCE,!0,e)}function Zp(e){return e.getUTCFullYear()<2050?Qe.create(jt.UNIVERSAL,vr.UTCTIME,!1,Qe.dateToUtcTime(e)):Qe.create(jt.UNIVERSAL,vr.GENERALIZEDTIME,!1,Qe.dateToGeneralizedTime(e))}function nE(e,t,n){let r=jp(e,"CERTIFICATE","tlsTerminate.caCertPath"),i=jp(t,"PRIVATE KEY","tlsTerminate.caKeyPath"),o=Zi(r,i);if(!o.ok)throw Error(`tlsTerminate: CA at ${e}: ${o.reason}`);return w(`[mitm-ca] loaded CA from ${e}`),su(r,i,o.cert,o.key,{certPath:e,keyPath:t,extraCaCertPaths:n})}function su(e,t,n,r,i){let o=Yc(Qn(ru(),"srt-ca-"));return{certPath:i.certPath,keyPath:i.keyPath,trustBundlePath:tE(o,e,i.extraCaCertPaths),certPem:e,keyPem:t,cert:n,key:r,leafCerts:new Map,secureContexts:new Map,crlDer:rE(n,t),ephemeral:i.ephemeral??!1}}function Cs(e={}){let t=er.rsa.generateKeyPair(2048),n=er.createCertificate();n.publicKey=t.publicKey,n.serialNumber=au(),n.validity.notBefore=Ki(-1),n.validity.notAfter=Ki(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=er.privateKeyToPem(t.privateKey);return iu(n,i),{certPem:er.certificateToPem(n),keyPem:i,cert:n,key:t.privateKey}}function Yn(e){return new G1(e).fingerprint.replace(/:/g,"").toUpperCase()}function Zi(e,t){let n,r;try{n=er.certificateFromPem(e),r=er.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 o;try{o=Yn(e)}catch(s){return{ok:!1,reason:`thumbprint: ${s.message}`}}return{ok:!0,thumbprint:o,notAfter:n.validity.notAfter,cert:n,key:r}}function iE(e){let{certPem:t,keyPem:n,cert:r,key:i}=Cs(),o=Yc(Qn(ru(),"srt-ca-")),s=Qn(o,"ca.crt"),a=Qn(Yc(Qn(ru(),"srt-ca-key-")),"ca.key");return tu(s,t,{mode:420}),tu(a,n,{mode:384}),w(`[mitm-ca] generated ephemeral CA at ${s}`),su(t,n,r,i,{certPath:s,keyPath:a,extraCaCertPaths:e,ephemeral:!0})}function jp(e,t,n){let r;try{r=eu(e,"utf8")}catch(i){let o=i.code??String(i);throw Error(`${n}: cannot read ${e} (${o})`)}if(!new RegExp(`-----BEGIN [A-Z ]*${t}-----`).test(r))throw Error(`${n}: ${e} is not a PEM ${t}`);return r}function au(){let e=Q1.getBytesSync(16),t=qp.bytesToHex(e);return(parseInt(t[0],16)&7).toString(16)+t.slice(1)}function Ki(e){let t=new Date;return t.setDate(t.getDate()+e),t}import{BlockList as Qp,isIP as ti}from"net";import{lookup as oE}from"dns/promises";import{networkInterfaces as sE}from"os";var ei=new Qp;for(let[e,t]of[["0.0.0.0",8],["10.0.0.0",8],["100.64.0.0",10],["127.0.0.0",8],["169.254.0.0",16],["172.16.0.0",12],["192.0.0.0",24],["192.0.2.0",24],["192.168.0.0",16],["198.18.0.0",15],["198.51.100.0",24],["203.0.113.0",24],["224.0.0.0",4],["240.0.0.0",4]])ei.addSubnet(e,t,"ipv4");for(let[e,t]of[["::",128],["::1",128],["64:ff9b:1::",48],["100::",64],["2001:db8::",32],["fc00::",7],["fe80::",10],["fec0::",10],["ff00::",8]])ei.addSubnet(e,t,"ipv6");function cu(e){let t=e.toLowerCase(),n=t.indexOf("%");if(n>=0)t=t.slice(0,n);if(ti(t)!==6)return;let r=/^(.*:)(\d+)\.(\d+)\.(\d+)\.(\d+)$/.exec(t);if(r){let[u,l,f,p]=r.slice(2).map(Number);t=`${r[1]}${(u<<8|l).toString(16)}:${(f<<8|p).toString(16)}`}let[i,o]=t.split("::"),s=(u)=>u===""?[]:u.split(":").map((l)=>parseInt(l,16)),a=s(i);if(o===void 0)return a.length===8?a:void 0;let c=s(o);if(a.length+c.length>7)return;return[...a,...Array(8-a.length-c.length).fill(0),...c]}function ws(e,t){return`${e>>8}.${e&255}.${t>>8}.${t&255}`}function aE(e){let t=/^::(?:ffff:(?:0:)?)?(\d+\.\d+\.\d+\.\d+)$/i.exec(e);if(t)return t[1];let n=/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i.exec(e);if(!n)return;let r=parseInt(n[1],16),i=parseInt(n[2],16);return`${r>>8}.${r&255}.${i>>8}.${i&255}`}function _s(e){let t=e.replace(/^\[|\]$/g,""),n=ti(t);if(n===0)return!1;if(n===4)return!ei.check(t,"ipv4");let r=aE(t);if(r!==void 0)return ti(r)===4&&!ei.check(r,"ipv4");let i=cu(t);if(i===void 0)return!1;if(rh(i).some((o)=>ei.check(o,"ipv4")))return!1;return!ei.check(t,"ipv6")}function Ts(e){let t=e.toLowerCase().replace(/\.$/,"");return t==="localhost"||t.endsWith(".localhost")||t==="localhost.localdomain"}class Rr extends Error{}class Es extends Rr{constructor(e,t){super(t===void 0?`${e} is not on the public internet`:`${e} resolves to ${t}, which is not on the public internet`);this.name="NonPublicDestinationError"}}class Yp extends Rr{constructor(e,t){super(`${e} resolves to ${t}, an address of this machine or its link-local network; the allowlist admits the name, not services on this machine`);this.name="LocalDestinationError"}}var eh=(e)=>oE(e,{all:!0,verbatim:!0});async function th(e,t=eh){let n=e.replace(/^\[|\]$/g,"");if(ti(n)){if(!_s(n))throw new Es(e);return n}if(Ts(n))throw new Es(e);let r=await t(n);if(r.length===0)throw Error(`${e} did not resolve`);for(let{address:i}of r)if(!_s(i))throw new Es(e,i);return(r.find((i)=>i.family===4)??r[0]).address}var ji=new Qp;ji.addSubnet("0.0.0.0",8,"ipv4");ji.addSubnet("127.0.0.0",8,"ipv4");ji.addSubnet("169.254.0.0",16,"ipv4");function cE(){return Object.values(sE()).flatMap((e)=>(e??[]).map((t)=>t.address))}function rh(e){let[t,n,r,i,o,s,a,c]=e,u=ws(a,c);if(t===0&&n===0&&r===0&&i===0){if(o===0&&(s===0||s===65535)||o===65535&&s===0)return[u];return[]}if(t===100&&n===65435)return[u];if(t===8194)return[ws(n,r)];if(t===8193&&n===0)return[ws(r,i),ws(a^65535,c^65535)];return[]}function uE(e,t=cE()){let n=e.replace(/^\[|\]$/g,"");if(ti(n)===4)return ji.check(n,"ipv4")||t.includes(n);let r=cu(n);if(r===void 0)return!0;if(r.slice(0,7).every((o)=>o===0)&&r[7]<=1)return!0;if((r[0]&65472)===65152)return!0;if(rh(r).some((o)=>ji.check(o,"ipv4")||t.includes(o)))return!0;let i=r.join(":");return t.some((o)=>cu(o)?.join(":")===i)}async function nh(e,t=eh,n){let r=e.replace(/^\[|\]$/g,"");if(ti(r)||Ts(r))return r;let i=await t(r);if(i.length===0)throw Error(`${e} did not resolve`);for(let{address:o}of i)if(uE(o,n))throw new Yp(e,o);return(i.find((o)=>o.family===4)??i[0]).address}import{PassThrough as lE,Readable as ih}from"stream";var uu=new Set(["GET","HEAD","OPTIONS"]),As="denied by sandbox policy";function oh(e,t){if(t.writableFinished||t.destroyed){e.destroy();return}t.once("finish",()=>e.destroy()),t.once("close",()=>e.destroy())}async function ks(e,t,n,r,i,o){let s=t.method??"GET",a,c=t,u=Boolean(t.headers["content-length"]||t.headers["transfer-encoding"]),l=uu.has(s);if(!l||u){let h=new lE;h.on("error",()=>{}),t.pipe(h);let d=ih.toWeb(h),[g,v]=d.tee();a=g,c=ih.fromWeb(v);let b=c;b.on("error",()=>{}),t.on("error",(S)=>{h.end(),b.destroy(S)})}let f;try{if(a&&!(a instanceof ReadableStream))throw TypeError("Unexpected request body stream");let h=a&&!l?{body:a,duplex:"half"}:{};f=new Request(r,{method:s,headers:ch(t),signal:i,...h})}catch(h){let d=`malformed request: ${h.message}`;if(o?.(s,r,d),sh(n,{action:"deny",reason:d}),a?.cancel().catch(()=>{}),c.destroy(),c!==t)oh(t,n);return null}let p;try{p=await e(f)}catch(h){p={action:"deny",reason:`sandbox policy check failed: ${h.message}`}}if(a&&!f.bodyUsed)a.cancel().catch(()=>{});if(p.action==="allow")return w(`[request-filter] allow ${s} ${r}`),c;if(o?.(s,r,p.reason??As),sh(n,p),c.destroy(),c!==t)oh(t,n);return null}async function ah(e,t,n,r){let i=t.method??"GET",o;try{o=new Request(n,{method:i,headers:ch(t),signal:r})}catch(s){return{action:"deny",reason:`malformed request: ${s.message}`}}try{let s=await e(o);if(s.action==="allow")w(`[request-filter] allow upgrade ${i} ${n}`);return s}catch(s){return{action:"deny",reason:`sandbox policy check failed: ${s.message}`}}}function sh(e,t){ri(e,t.reason??As)}function ri(e,t){if(w(`[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+`
30
+ `)}function ch(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 BE,request as Th}from"https";import{STATUS_CODES as Ah}from"http";import{connect as NE,isIP as oi}from"net";import{unlink as DE}from"fs";import{tmpdir as $E}from"os";import{join as OE}from"path";import{Transform as fE}from"stream";function dE(e){return e.every((t)=>t.sentinel.length===t.realValue.length)}function Is(e,t,n,r){if(e===void 0)return;let i=t.headers["content-length"]!==void 0||t.headers["transfer-encoding"]!==void 0;if(uu.has(t.method??"GET")&&!i)return;let o=e(r);if(!o?.length)return;if(t.headers["content-encoding"]!==void 0){w(`[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(!dE(o))delete n["content-length"];return pE(o)}function pE(e){let t=Math.max(...e.map((r)=>r.sentinel.length)),n;return new fE({transform(r,i,o){let s=Buffer.isBuffer(r)?r:Buffer.from(r,i),a=n?.length?Buffer.concat([n,s]):s,{out:c,tail:u}=hE(a,e,t);n=u,o(null,c)},flush(r){r(null,n?.length?n:void 0)}})}function hE(e,t,n){let r=[],i=0;for(;;){let s=-1,a;for(let c of t){let u=e.indexOf(c.sentinel,i);if(u!==-1&&(s===-1||u<s))s=u,a=c}if(a===void 0)break;r.push(e.subarray(i,s),a.realValue),i=s+a.sentinel.length}let o=Math.max(i,e.length-(n-1));return r.push(e.subarray(i,o)),{out:Buffer.concat(r),tail:Buffer.from(e.subarray(o))}}var uh=ja(Jc(),1);import{isIP as mE}from"net";import{createSecureContext as gE}from"tls";var{pki:Ps}=uh.default;function lu(e,t){let n=e.leafCerts.get(t);if(n)return n;let r=Ps.rsa.generateKeyPair(2048),i=Ps.createCertificate();i.publicKey=r.publicKey,i.serialNumber=au();let o=Ki(-1);i.validity.notBefore=o,i.validity.notAfter=vE(e.cert,o),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:[yE(t)]},{name:"subjectKeyIdentifier"},{name:"authorityKeyIdentifier",keyIdentifier:nu(e.cert)},...e.crlUrl?[{name:"cRLDistributionPoints",altNames:[{type:6,value:e.crlUrl}]}]:[]]),iu(i,e.keyPem);let s={certPem:Ps.certificateToPem(i)+e.certPem,keyPem:Ps.privateKeyToPem(r.privateKey)};return e.leafCerts.set(t,s),w(`[mitm-leaf] minted RSA leaf for ${t}`),s}function lh(e,t){let n=e.secureContexts.get(t);if(n)return n;let{certPem:r,keyPem:i}=lu(e,t),o=gE({cert:r,key:i});return e.secureContexts.set(t,o),o}function yE(e){return mE(e)!==0?{type:7,ip:e}:{type:2,value:e}}function vE(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 fh,connect as dh,isIP as bn}from"net";import{connect as xE}from"tls";import{URL as fu}from"url";var ph=30000,bE=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","proxy-connection","te","trailer","transfer-encoding","upgrade"]);function du(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=(a)=>{if(!a)return;let u=/^[a-z][a-z0-9+.-]*:\/\//i.test(a)?a:`http://${a}`;try{let l=new fu(u);if(l.protocol!=="http:"&&l.protocol!=="https:"||!l.hostname)throw Error("unsupported scheme or empty host");return l}catch{w(`Invalid parent proxy URL, ignoring: ${wE(a)}`,{level:"error"});return}},o=i(t),s=i(n);if(!o&&!s)return;return{httpUrl:o,httpsUrl:s,noProxy:SE(r)}}function SE(e){let t={all:!1,suffixes:[],cidr:new fh};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 a=n.slice(0,r),c=n.slice(r+1),u=bn(a);if(u&&c!==""&&/^\d+$/.test(c)){let l=Number(c),f=u===6?128:32;if(l>=0&&l<=f){try{t.cidr.addSubnet(a,l,u===6?"ipv6":"ipv4")}catch{}continue}}continue}let i=n.toLowerCase(),o=/^\[([^\]]+)\](?::\d+)?$/.exec(i);if(o)i=o[1];if(i.startsWith("*."))i=i.slice(1);let s=bn(i);if(!s){let a=i.lastIndexOf(":");if(a!==-1&&/^\d+$/.test(i.slice(a+1)))i=i.slice(0,a)}else try{t.cidr.addAddress(i,s===6?"ipv6":"ipv4");continue}catch{}t.suffixes.push(i)}return t}function Gi(e,t){let n=tr(t.toLowerCase().replace(/\.$/,""));if(n==="localhost")return!0;let r=bn(n);if(r){if(CE.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 CE=(()=>{let e=new fh;return e.addSubnet("127.0.0.0",8,"ipv4"),e.addAddress("::1","ipv6"),e.addSubnet("::ffff:127.0.0.0",104,"ipv6"),e})();function qi(e,t){if(t.isHttps)return e.httpsUrl??e.httpUrl;return e.httpUrl}function pu(e){let{destHost:t,destPort:n}=e,r=tr(t);if(!ni(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=bn(r)===6?`[${r}]:${n}`:`${r}:${n}`;return new Promise((o,s)=>{let a=e.dial(),c=!1,u=(f)=>{if(c)return;c=!0,a.destroy(),s(f)},l=()=>u(Error("Proxy closed during CONNECT handshake"));a.setTimeout(e.timeoutMs??ph,()=>u(Error("CONNECT handshake timed out"))),a.once("error",u),a.once("close",l),a.once(e.readyEvent,()=>{a.write(`CONNECT ${i} HTTP/1.1\r
31
31
  Host: ${i}\r
32
32
  `+(e.authHeader?`Proxy-Authorization: ${e.authHeader}\r
33
33
  `:"")+`\r
34
34
  `);let f="",p=(h)=>{f+=h.toString("latin1");let d=f.indexOf(`\r
35
35
  \r
36
36
  `);if(d===-1){if(f.length>16384)u(Error("CONNECT response header too large"));return}a.pause(),a.removeListener("data",p);let g=f.slice(0,f.indexOf(`\r
37
- `));if(!/^HTTP\/1\.[01] 2\d\d(?:\s|$)/.test(g))return u(Error(`Proxy refused CONNECT: ${g.trim()}`));let x=f.slice(d+4);if(x.length)a.unshift(Buffer.from(x,"latin1"));c=!0,a.setTimeout(0),a.removeListener("error",u),a.removeListener("close",l),o(a)};a.on("data",p)})})}function Rs(e,t,n){let r=tr(e.hostname),i=Number(e.port)||(e.protocol==="https:"?443:80),o=e.protocol==="https:";return du({destHost:t,destPort:n,authHeader:pu(e),readyEvent:o?"secureConnect":"connect",dial:()=>o?vE({host:r,port:i,...bn(r)?{}:{servername:r}}):fh(i,r)})}function pu(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 xr(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,o]of Object.entries(e)){let s=i.toLowerCase();if(!xE.has(s)&&!t.has(s))r[i]=o}return r}function tr(e){return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}function hu(e){if(!e)return"-";if(!e.username&&!e.password)return e.href;let t=new lu(e.href);return t.username="***",t.password="***",t.href}function CE(e){return e.replace(/\/\/[^@/]*@/,"//***:***@")}function ti(e){if(!e||e.length>255)return!1;let t=tr(e);if(t.includes("%"))return!1;if(bn(t))return!0;return/^[A-Za-z0-9._-]+$/.test(t)}function vt(e){try{let t=tr(e),n=bn(t)===6?`[${t}]`:t,r=new lu(`http://${n}/`).hostname;return tr(r).replace(/\.$/,"")}catch{return}}async function Bs(e,t,n=dh){return new Promise((r,i)=>{let o=fh(t,e),s=!1,a=(c)=>{if(s)return;if(s=!0,o.setTimeout(0),c)o.destroy(),i(c);else r(o)};o.setTimeout(n,()=>a(Error("connect timed out"))),o.once("connect",()=>a()),o.once("error",a),o.once("close",()=>a(Error("socket closed before connect")))})}import{createHash as wE,createHmac as gh}from"crypto";var qi="AWS4-HMAC-SHA256",EE="AWS4-ECDSA-P256-SHA256",Ds="UNSIGNED-PAYLOAD";function yh(e,t){let n=ri(e.authorization);if(n!==void 0&&n.startsWith(EE)){let a=ph(n);if(a!==void 0)return{kind:"sigv4a",accessKeyId:a}}else if(n!==void 0&&n.startsWith(qi)){let a=ph(n);if(a!==void 0)return{kind:ri(e["x-amz-content-sha256"])?.startsWith("STREAMING-")?"streaming":"header-sigv4",accessKeyId:a}}let r=t.indexOf("?");if(r===-1)return null;let i=new URLSearchParams(t.slice(r+1));if(i.get("X-Amz-Algorithm")!==qi)return null;if(!i.has("X-Amz-Signature"))return null;let o=i.get("X-Amz-Credential");if(!o)return null;let s=o.split("/")[0];return s?{kind:"presigned",accessKeyId:s}:null}function ph(e){return/Credential=([^/,\s]+)\//.exec(e)?.[1]}function vh(e){if(!e.startsWith(qi))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[o,s,a,c]=i;if(!o||!s||!a||!c)return null;return{accessKeyId:o,date:s,region:a,service:c,signedHeaders:n.split(";").map((u)=>u.toLowerCase()),signature:r}}function mu(e){return encodeURIComponent(e).replace(/[!'()*]/g,(t)=>"%"+t.charCodeAt(0).toString(16).toUpperCase())}function _E(e,t){if(e==="")return"/";if(t==="s3")return e;let n=[];for(let o of e.split("/")){if(o===""||o===".")continue;if(o==="..")n.pop();else n.push(o)}let r=n.length>0&&e.endsWith("/")?"/":"",i=`/${n.join("/")}${r}`;return mu(i).replace(/%2F/gi,"/")}function TE(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),o=r===-1?"":n.slice(r+1);t.push([mu(hh(i)),mu(hh(o))])}return t.sort(([n,r],[i,o])=>n<i?-1:n>i?1:r<o?-1:r>o?1:0),t.map(([n,r])=>`${n}=${r}`).join("&")}function hh(e){try{return decodeURIComponent(e)}catch{return e}}function mh(e){return e.trim().replace(/[ \t]+/g," ")}function AE(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(),o=[];for(let s of i){let a=s==="host"?e.hostHeader:e.headers[s];if(a===void 0)throw Error(`signed header "${s}" is missing from the request`);let c=Array.isArray(a)?a.map(mh).join(","):mh(String(a));o.push(`${s}:${c}`)}return[e.method.toUpperCase(),_E(n,e.scope.service),TE(r),o.join(`
37
+ `));if(!/^HTTP\/1\.[01] 2\d\d(?:\s|$)/.test(g))return u(Error(`Proxy refused CONNECT: ${g.trim()}`));let v=f.slice(d+4);if(v.length)a.unshift(Buffer.from(v,"latin1"));c=!0,a.setTimeout(0),a.removeListener("error",u),a.removeListener("close",l),o(a)};a.on("data",p)})})}function Rs(e,t,n){let r=tr(e.hostname),i=Number(e.port)||(e.protocol==="https:"?443:80),o=e.protocol==="https:";return pu({destHost:t,destPort:n,authHeader:hu(e),readyEvent:o?"secureConnect":"connect",dial:()=>o?xE({host:r,port:i,...bn(r)?{}:{servername:r}}):dh(i,r)})}function hu(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 xr(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,o]of Object.entries(e)){let s=i.toLowerCase();if(!bE.has(s)&&!t.has(s))r[i]=o}return r}function tr(e){return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}function mu(e){if(!e)return"-";if(!e.username&&!e.password)return e.href;let t=new fu(e.href);return t.username="***",t.password="***",t.href}function wE(e){return e.replace(/\/\/[^@/]*@/,"//***:***@")}function ni(e){if(!e||e.length>255)return!1;let t=tr(e);if(t.includes("%"))return!1;if(bn(t))return!0;return/^[A-Za-z0-9._-]+$/.test(t)}function xt(e){try{let t=tr(e),n=bn(t)===6?`[${t}]`:t,r=new fu(`http://${n}/`).hostname;return tr(r).replace(/\.$/,"")}catch{return}}async function Bs(e,t,n=ph){return new Promise((r,i)=>{let o=dh(t,e),s=!1,a=(c)=>{if(s)return;if(s=!0,o.setTimeout(0),c)o.destroy(),i(c);else r(o)};o.setTimeout(n,()=>a(Error("connect timed out"))),o.once("connect",()=>a()),o.once("error",a),o.once("close",()=>a(Error("socket closed before connect")))})}import{createHash as EE,createHmac as yh}from"crypto";var Xi="AWS4-HMAC-SHA256",_E="AWS4-ECDSA-P256-SHA256",Ds="UNSIGNED-PAYLOAD";function vh(e,t){let n=ii(e.authorization);if(n!==void 0&&n.startsWith(_E)){let a=hh(n);if(a!==void 0)return{kind:"sigv4a",accessKeyId:a}}else if(n!==void 0&&n.startsWith(Xi)){let a=hh(n);if(a!==void 0)return{kind:ii(e["x-amz-content-sha256"])?.startsWith("STREAMING-")?"streaming":"header-sigv4",accessKeyId:a}}let r=t.indexOf("?");if(r===-1)return null;let i=new URLSearchParams(t.slice(r+1));if(i.get("X-Amz-Algorithm")!==Xi)return null;if(!i.has("X-Amz-Signature"))return null;let o=i.get("X-Amz-Credential");if(!o)return null;let s=o.split("/")[0];return s?{kind:"presigned",accessKeyId:s}:null}function hh(e){return/Credential=([^/,\s]+)\//.exec(e)?.[1]}function xh(e){if(!e.startsWith(Xi))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[o,s,a,c]=i;if(!o||!s||!a||!c)return null;return{accessKeyId:o,date:s,region:a,service:c,signedHeaders:n.split(";").map((u)=>u.toLowerCase()),signature:r}}function gu(e){return encodeURIComponent(e).replace(/[!'()*]/g,(t)=>"%"+t.charCodeAt(0).toString(16).toUpperCase())}function TE(e,t){if(e==="")return"/";if(t==="s3")return e;let n=[];for(let o of e.split("/")){if(o===""||o===".")continue;if(o==="..")n.pop();else n.push(o)}let r=n.length>0&&e.endsWith("/")?"/":"",i=`/${n.join("/")}${r}`;return gu(i).replace(/%2F/gi,"/")}function AE(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),o=r===-1?"":n.slice(r+1);t.push([gu(mh(i)),gu(mh(o))])}return t.sort(([n,r],[i,o])=>n<i?-1:n>i?1:r<o?-1:r>o?1:0),t.map(([n,r])=>`${n}=${r}`).join("&")}function mh(e){try{return decodeURIComponent(e)}catch{return e}}function gh(e){return e.trim().replace(/[ \t]+/g," ")}function kE(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(),o=[];for(let s of i){let a=s==="host"?e.hostHeader:e.headers[s];if(a===void 0)throw Error(`signed header "${s}" is missing from the request`);let c=Array.isArray(a)?a.map(gh).join(","):gh(String(a));o.push(`${s}:${c}`)}return[e.method.toUpperCase(),TE(n,e.scope.service),AE(r),o.join(`
38
38
  `)+`
39
39
  `,i.join(";"),e.payloadHash].join(`
40
- `)}function kE(e,t,n){return[qi,t,`${n.date}/${n.region}/${n.service}/aws4_request`,$s(e)].join(`
41
- `)}function IE(e,t){let n=Ns(`AWS4${e}`,t.date),r=Ns(n,t.region),i=Ns(r,t.service);return Ns(i,"aws4_request")}function xh(e){let t=AE(e),n=kE(t,e.amzDate,e.scope),r=gh("sha256",IE(e.secretAccessKey,e.scope)).update(n,"utf8").digest("hex"),i=[...e.signedHeaders].map((s)=>s.toLowerCase()).sort(),o=`${e.scope.date}/${e.scope.region}/${e.scope.service}/aws4_request`;return{authorization:`${qi} Credential=${e.accessKeyId}/${o}, SignedHeaders=${i.join(";")}, Signature=${r}`,signature:r,canonicalRequest:t,stringToSign:n}}function $s(e){return wE("sha256").update(e).digest("hex")}function Ns(e,t){return gh("sha256",e).update(t,"utf8").digest()}function ri(e){return Array.isArray(e)?e[0]:e}var bh="reason-egress-target",Sh="reason-egress-token";class gu{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((o)=>o.includes(n.placeholder)||PE(o,n.placeholder)))return{url:new URL(n.url),token:n.token}}return}}function PE(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 Ah=67108864;class xu extends Error{}function Ch(e){return e.length>=3&&e[0]===22&&e[1]===3&&e[2]<=3}function kh(e,t){if(t.length>=3)return Promise.resolve({isTLS:Ch(t),head:t});return new Promise((n)=>{let r=t,i=()=>{e.removeListener("data",o),e.removeListener("close",i),n({isTLS:Ch(r),head:r})},o=(s)=>{if(e.pause(),r=r.length?Buffer.concat([r,s]):s,r.length>=3)return i();e.resume()};e.on("data",o),e.once("close",i)})}function vu(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 Ih(e,t,n,r,i,o,s,a,c=Ah,u){let l=uu(e,s.hostname),f=RE({ALPNProtocols:["http/1.1"],cert:l.certPem,key:l.keyPem,SNICallback:(d,g)=>{try{g(null,uh(e,d||s.hostname))}catch(x){g(x)}}});f.on("request",(d,g)=>{d.on("error",(x)=>{w(`[tls-terminate] client request error: ${x.message}`,{level:"error"})}),g.on("error",(x)=>{w(`[tls-terminate] client response error: ${x.message}`,{level:"error"})}),OE(t,n,r,d,g,s,a,c,u)}),f.on("clientError",(d,g)=>{w(`[tls-terminate] client connection error for ${s.hostname}: ${d.message}`,{level:"error"}),g.destroy()}),f.on("tlsClientError",(d,g)=>{w(`[tls-terminate] client TLS error for ${s.hostname}: ${d.message}`,{level:"error"}),g.destroy()}),f.on("upgrade",(d,g,x)=>{g.on("error",(b)=>{w(`[tls-terminate] upgraded client error: ${b.message}`,{level:"error"})}),zE(t,n,d,g,x,s,a,u).catch((b)=>{w(`[tls-terminate] forwardUpgrade failed: ${b.message}`,{level:"error"}),g.destroy()})});let p=VE(),h=()=>{f.close(),NE(p,()=>{})};f.on("error",(d)=>{w(`[tls-terminate] inner server listen failed: ${d.message}`,{level:"error"}),i.destroy(),h()}),f.listen(p,()=>{let d=BE({path:p});d.on("error",(g)=>{w(`[tls-terminate] inner loopback failed: ${g.message}`,{level:"error"}),i.destroy(),h()}),d.once("connect",()=>{if(o.length)d.write(o);vu(i,d),d.pipe(i)}),i.on("error",()=>d.destroy()),i.once("close",()=>{d.destroy(),h()}),d.once("close",()=>i.destroy())}),f.unref()}function yu(e,t){if(t.writableFinished||t.destroyed){e.destroy();return}t.once("finish",()=>e.destroy()),t.once("close",()=>e.destroy())}function OE(...e){LE(...e).catch((t)=>{w(`[tls-terminate] forwardUpstream failed: ${t.message}`,{level:"error"})})}async function LE(e,t,n,r,i,o,s,a=Ah,c){let u=Rh(r.url),l=r;if(e){let T=new AbortController;i.once("close",()=>T.abort());let I=o.port===443?o.hostname:`${o.hostname}:${o.port}`,k=await ks(e,r,i,`https://${I}${u}`,T.signal,o.onFilterRequestDeny);if(k===null)return;if(l=k,r.destroyed&&!r.readableEnded||i.destroyed||r.socket.destroyed||l.destroyed){l.destroy();return}}let f=xr(r.headers);delete f.host;let p=c?.(f,o.hostname),h=s?.(r.method??"GET",u,f,o.hostname);t?.(f,o.hostname);let d=Is(n,r,f,o.hostname),g;if(h?.action==="deny"){if(ei(i,h.reason),l.destroy(),l!==r)yu(r,i);return}if(h?.action==="resign"){let T=h.payloadHash;if(T===void 0){let R=d?l.pipe(d):l;if(d)l.on("error",(V)=>d.destroy(V));try{g=await FE(R,a)}catch(V){if(V instanceof xu){ei(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 ${a}-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}w(`[tls-terminate] failed to buffer body for SigV4 re-sign: ${V.message}`,{level:"error"}),i.destroy();return}T=$s(g),f["content-length"]=String(g.length)}let I=ni(o.hostname)===6?`[${o.hostname}]`:o.hostname,k=o.port===443?I:`${I}:${o.port}`;try{h.apply(f,k,T)}catch(R){if(ei(i,`AWS SigV4 re-signing failed: ${R.message}`),l.destroy(),l!==r)yu(r,i);return}}if(Boolean(r.headers["content-length"]||r.headers["transfer-encoding"])&&g===void 0&&f["content-length"]===void 0&&f["transfer-encoding"]===void 0)f["transfer-encoding"]="chunked";if(p){let T=ni(o.hostname)===6?`[${o.hostname}]`:o.hostname;f[bh]=`https://${o.port===443?T:`${T}:${o.port}`}${u}`,f[Sh]=p.token}let b=p?p.url.hostname:o.hostname,S;if(!p&&o.resolveAddress){try{S=await o.resolveAddress()}catch(T){if(T instanceof Rr)ei(i,`Connection blocked: ${T.message}`);else if(!i.headersSent)i.writeHead(502,{"Content-Type":"text/plain"}),i.end("Bad Gateway");else i.destroy();if(l.destroy(),l!==r)yu(r,i);return}if(i.destroyed||r.socket.destroyed){l.destroy();return}}let C=_h({host:b,port:p?Number(p.url.port||443):o.port,path:p?`${p.url.pathname}${p.url.search}`:u,method:r.method,headers:f,...ni(b)?{}:{servername:b},...S!==void 0&&S!==b?{lookup:Ph(S)}:{},...o.upstreamCA?{ca:o.upstreamCA}:{},agent:!1},(T)=>{T.on("error",(I)=>{w(`[tls-terminate] upstream response error: ${I.message}`,{level:"error"}),i.destroy()}),i.writeHead(T.statusCode??502,xr(T.headers)),T.pipe(i)});if(C.on("error",(T)=>{if(w(`[tls-terminate] upstream ${o.hostname}:${o.port} failed: ${T.message}`,{level:"error"}),!i.headersSent)i.writeHead(502,{"Content-Type":"text/plain"}),i.end("Bad Gateway");else i.destroy()}),i.on("close",()=>C.destroy()),g!==void 0)C.end(g);else if(d)d.on("error",(T)=>C.destroy(T)),l.on("error",(T)=>d.destroy(T)),i.on("close",()=>d.destroy()),l.pipe(d).pipe(C);else l.on("error",(T)=>C.destroy(T)),l.pipe(C)}function Br(e,t,n,r){let i=`${n.replace(/[\r\n]+/g," ")}
42
- `;e.end(`HTTP/1.1 ${t} ${Th[t]??""}\r
40
+ `)}function IE(e,t,n){return[Xi,t,`${n.date}/${n.region}/${n.service}/aws4_request`,$s(e)].join(`
41
+ `)}function PE(e,t){let n=Ns(`AWS4${e}`,t.date),r=Ns(n,t.region),i=Ns(r,t.service);return Ns(i,"aws4_request")}function bh(e){let t=kE(e),n=IE(t,e.amzDate,e.scope),r=yh("sha256",PE(e.secretAccessKey,e.scope)).update(n,"utf8").digest("hex"),i=[...e.signedHeaders].map((s)=>s.toLowerCase()).sort(),o=`${e.scope.date}/${e.scope.region}/${e.scope.service}/aws4_request`;return{authorization:`${Xi} Credential=${e.accessKeyId}/${o}, SignedHeaders=${i.join(";")}, Signature=${r}`,signature:r,canonicalRequest:t,stringToSign:n}}function $s(e){return EE("sha256").update(e).digest("hex")}function Ns(e,t){return yh("sha256",e).update(t,"utf8").digest()}function ii(e){return Array.isArray(e)?e[0]:e}var Sh="reason-egress-target",Ch="reason-egress-token";class yu{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((o)=>o.includes(n.placeholder)||RE(o,n.placeholder)))return{url:new URL(n.url),token:n.token}}return}}function RE(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 kh=67108864;class bu extends Error{}function wh(e){return e.length>=3&&e[0]===22&&e[1]===3&&e[2]<=3}function Ih(e,t){if(t.length>=3)return Promise.resolve({isTLS:wh(t),head:t});return new Promise((n)=>{let r=t,i=()=>{e.removeListener("data",o),e.removeListener("close",i),n({isTLS:wh(r),head:r})},o=(s)=>{if(e.pause(),r=r.length?Buffer.concat([r,s]):s,r.length>=3)return i();e.resume()};e.on("data",o),e.once("close",i)})}function xu(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 Ph(e,t,n,r,i,o,s,a,c=kh,u){let l=lu(e,s.hostname),f=BE({ALPNProtocols:["http/1.1"],cert:l.certPem,key:l.keyPem,SNICallback:(d,g)=>{try{g(null,lh(e,d||s.hostname))}catch(v){g(v)}}});f.on("request",(d,g)=>{d.on("error",(v)=>{w(`[tls-terminate] client request error: ${v.message}`,{level:"error"})}),g.on("error",(v)=>{w(`[tls-terminate] client response error: ${v.message}`,{level:"error"})}),LE(t,n,r,d,g,s,a,c,u)}),f.on("clientError",(d,g)=>{w(`[tls-terminate] client connection error for ${s.hostname}: ${d.message}`,{level:"error"}),g.destroy()}),f.on("tlsClientError",(d,g)=>{w(`[tls-terminate] client TLS error for ${s.hostname}: ${d.message}`,{level:"error"}),g.destroy()}),f.on("upgrade",(d,g,v)=>{g.on("error",(b)=>{w(`[tls-terminate] upgraded client error: ${b.message}`,{level:"error"})}),FE(t,n,d,g,v,s,a,u).catch((b)=>{w(`[tls-terminate] forwardUpgrade failed: ${b.message}`,{level:"error"}),g.destroy()})});let p=WE(),h=()=>{f.close(),DE(p,()=>{})};f.on("error",(d)=>{w(`[tls-terminate] inner server listen failed: ${d.message}`,{level:"error"}),i.destroy(),h()}),f.listen(p,()=>{let d=NE({path:p});d.on("error",(g)=>{w(`[tls-terminate] inner loopback failed: ${g.message}`,{level:"error"}),i.destroy(),h()}),d.once("connect",()=>{if(o.length)d.write(o);xu(i,d),d.pipe(i)}),i.on("error",()=>d.destroy()),i.once("close",()=>{d.destroy(),h()}),d.once("close",()=>i.destroy())}),f.unref()}function vu(e,t){if(t.writableFinished||t.destroyed){e.destroy();return}t.once("finish",()=>e.destroy()),t.once("close",()=>e.destroy())}function LE(...e){UE(...e).catch((t)=>{w(`[tls-terminate] forwardUpstream failed: ${t.message}`,{level:"error"})})}async function UE(e,t,n,r,i,o,s,a=kh,c){let u=Bh(r.url),l=r;if(e){let T=new AbortController;i.once("close",()=>T.abort());let I=o.port===443?o.hostname:`${o.hostname}:${o.port}`,k=await ks(e,r,i,`https://${I}${u}`,T.signal,o.onFilterRequestDeny);if(k===null)return;if(l=k,r.destroyed&&!r.readableEnded||i.destroyed||r.socket.destroyed||l.destroyed){l.destroy();return}}let f=xr(r.headers);delete f.host;let p=c?.(f,o.hostname),h=s?.(r.method??"GET",u,f,o.hostname);t?.(f,o.hostname);let d=Is(n,r,f,o.hostname),g;if(h?.action==="deny"){if(ri(i,h.reason),l.destroy(),l!==r)vu(r,i);return}if(h?.action==="resign"){let T=h.payloadHash;if(T===void 0){let R=d?l.pipe(d):l;if(d)l.on("error",(V)=>d.destroy(V));try{g=await ME(R,a)}catch(V){if(V instanceof bu){ri(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 ${a}-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}w(`[tls-terminate] failed to buffer body for SigV4 re-sign: ${V.message}`,{level:"error"}),i.destroy();return}T=$s(g),f["content-length"]=String(g.length)}let I=oi(o.hostname)===6?`[${o.hostname}]`:o.hostname,k=o.port===443?I:`${I}:${o.port}`;try{h.apply(f,k,T)}catch(R){if(ri(i,`AWS SigV4 re-signing failed: ${R.message}`),l.destroy(),l!==r)vu(r,i);return}}if(Boolean(r.headers["content-length"]||r.headers["transfer-encoding"])&&g===void 0&&f["content-length"]===void 0&&f["transfer-encoding"]===void 0)f["transfer-encoding"]="chunked";if(p){let T=oi(o.hostname)===6?`[${o.hostname}]`:o.hostname;f[Sh]=`https://${o.port===443?T:`${T}:${o.port}`}${u}`,f[Ch]=p.token}let b=p?p.url.hostname:o.hostname,S;if(!p&&o.resolveAddress){try{S=await o.resolveAddress()}catch(T){if(T instanceof Rr)ri(i,`Connection blocked: ${T.message}`);else if(!i.headersSent)i.writeHead(502,{"Content-Type":"text/plain"}),i.end("Bad Gateway");else i.destroy();if(l.destroy(),l!==r)vu(r,i);return}if(i.destroyed||r.socket.destroyed){l.destroy();return}}let C=Th({host:b,port:p?Number(p.url.port||443):o.port,path:p?`${p.url.pathname}${p.url.search}`:u,method:r.method,headers:f,...oi(b)?{}:{servername:b},...S!==void 0&&S!==b?{lookup:Rh(S)}:{},...o.upstreamCA?{ca:o.upstreamCA}:{},agent:!1},(T)=>{T.on("error",(I)=>{w(`[tls-terminate] upstream response error: ${I.message}`,{level:"error"}),i.destroy()}),i.writeHead(T.statusCode??502,xr(T.headers)),T.pipe(i)});if(C.on("error",(T)=>{if(w(`[tls-terminate] upstream ${o.hostname}:${o.port} failed: ${T.message}`,{level:"error"}),!i.headersSent)i.writeHead(502,{"Content-Type":"text/plain"}),i.end("Bad Gateway");else i.destroy()}),i.on("close",()=>C.destroy()),g!==void 0)C.end(g);else if(d)d.on("error",(T)=>C.destroy(T)),l.on("error",(T)=>d.destroy(T)),i.on("close",()=>d.destroy()),l.pipe(d).pipe(C);else l.on("error",(T)=>C.destroy(T)),l.pipe(C)}function Br(e,t,n,r){let i=`${n.replace(/[\r\n]+/g," ")}
42
+ `;e.end(`HTTP/1.1 ${t} ${Ah[t]??""}\r
43
43
  Content-Type: text/plain\r
44
44
  X-Proxy-Error: ${r}\r
45
45
  Content-Length: ${Buffer.byteLength(i)}\r
46
46
  Connection: close\r
47
47
  \r
48
- `+i)}var UE=1048576;function wh(e){if(e.destroyed)return;if(e.writableFinished||e.errored){e.destroy();return}let t=setTimeout(()=>e.destroy(),1e4);if(t.unref?.(),e.once("finish",()=>{clearTimeout(t),e.destroy()}),!e.writableEnded)e.end()}function Eh(e,t,n){let r=`HTTP/1.1 ${e} ${t||Th[e]||""}\r
48
+ `+i)}var zE=1048576;function Eh(e){if(e.destroyed)return;if(e.writableFinished||e.errored){e.destroy();return}let t=setTimeout(()=>e.destroy(),1e4);if(t.unref?.(),e.once("finish",()=>{clearTimeout(t),e.destroy()}),!e.writableEnded)e.end()}function _h(e,t,n){let r=`HTTP/1.1 ${e} ${t||Ah[e]||""}\r
49
49
  `;for(let i=0;i+1<n.length;i+=2)r+=`${n[i]}: ${n[i+1]}\r
50
50
  `;return`${r}\r
51
- `}async function zE(e,t,n,r,i,o,s,a){let c=[i],u=i.length,l=()=>{let R;while((R=r.read())!==null){if(u+=R.length,u>UE){r.destroy();return}c.push(R)}},f=()=>{r.destroy()};r.on("readable",l),r.once("end",f),l();let p=n.method??"GET",h=Rh(n.url),d=o.port===443?o.hostname:`${o.hostname}:${o.port}`,g=`https://${d}${h}`,x=String(n.headers.upgrade??"").trim().toLowerCase();if(p!=="GET"||x!=="websocket"){Br(r,501,`The sandbox proxy carries WebSocket upgrades (GET with Upgrade: websocket) only; ${p} with Upgrade: ${String(n.headers.upgrade??"").slice(0,40)} is not carried.`,"upgrade-not-carried");return}let b=n.headers["content-length"];if(b!==void 0&&b.trim()!=="0"||n.headers["transfer-encoding"]!==void 0){Br(r,400,"An upgrade request with a body is not carried by the sandbox proxy.","upgrade-with-body");return}if(e){let R=new AbortController;r.once("close",()=>R.abort());let V=await sh(e,n,g,R.signal);if(V.action!=="allow"){let D=V.reason??As;w(`[request-filter] deny: ${D}`),o.onFilterRequestDeny?.(p,g,D),Br(r,403,D,"blocked-by-sandbox-runtime");return}if(r.destroyed)return}let S=xr(n.headers);if(delete S.host,a?.(S,o.hostname)){Br(r,501,`This upgrade (WebSocket) request to ${o.hostname} carries a brokered credential placeholder, and the credential broker carries requests, not upgraded connections. Use a WebSocket without that credential, or an ordinary HTTPS request.`,"upgrade-not-carried");return}let C=s?.(p,h,S,o.hostname);if(t?.(S,o.hostname),C?.action==="deny"){Br(r,403,C.reason,"blocked-by-sandbox-runtime");return}if(C?.action==="resign"){let R=ni(o.hostname)===6?`[${o.hostname}]`:o.hostname,V=o.port===443?R:`${R}:${o.port}`;try{C.apply(S,V,C.payloadHash??$s(Buffer.alloc(0)))}catch(D){Br(r,403,`AWS SigV4 re-signing failed: ${D.message}`,"blocked-by-sandbox-runtime");return}}S.connection="Upgrade",S.upgrade=n.headers.upgrade;let T;if(o.resolveAddress){try{T=await o.resolveAddress()}catch(R){if(R instanceof Rr)Br(r,403,`Connection blocked: ${R.message}`,"blocked-by-allowlist");else Br(r,502,`${d} could not be reached: ${R.message}`,"upstream-unreachable");return}if(r.destroyed)return}let I=!1,k=_h({host:o.hostname,port:o.port,path:h,method:p,headers:S,...ni(o.hostname)?{}:{servername:o.hostname},...T!==void 0&&T!==o.hostname?{lookup:Ph(T)}:{},...o.upstreamCA?{ca:o.upstreamCA}:{},agent:!1});k.on("upgrade",(R,V,D)=>{if(I=!0,V.on("error",(H)=>{w(`[tls-terminate] upgraded upstream ${o.hostname}:${o.port} error: ${H.message}`,{level:"error"}),r.destroy()}),r.write(Eh(R.statusCode??101,R.statusMessage,R.rawHeaders),"latin1"),D.length)r.write(D);r.removeListener("readable",l),r.removeListener("end",f),l();let F=Buffer.concat(c);if(F.length)V.write(F);r.once("close",()=>wh(V)),V.once("close",()=>wh(r)),vu(r,V),vu(V,r)}),k.on("response",(R)=>{I=!0,r.once("close",()=>k.destroy()),R.on("error",()=>r.destroy());let V=xr(R.headers),D=[];for(let[F,H]of Object.entries(V))for(let re of Array.isArray(H)?H:H===void 0?[]:[H])D.push(F,String(re));D.push("connection","close"),r.write(Eh(R.statusCode??502,R.statusMessage,D),"latin1"),R.pipe(r)}),k.on("error",(R)=>{if(w(`[tls-terminate] upstream upgrade ${o.hostname}:${o.port} failed: ${R.message}`,{level:"error"}),!I)Br(r,502,`${d} could not be reached: ${R.message}`,"upstream-unreachable");else r.destroy()}),r.once("close",()=>{if(!I)k.destroy()}),k.end()}function Ph(e){let t=ni(e);return(n,r,i)=>{if(r.all)i(null,[{address:e,family:t}]);else i(null,e,t)}}function FE(e,t){return new Promise((n,r)=>{let i=[],o=0,s=(a)=>{if(o+=a.length,o>t){i.length=0,e.removeListener("data",s),r(new xu(`request body exceeds ${t} bytes`));return}i.push(a)};e.on("data",s),e.once("end",()=>n(Buffer.concat(i))),e.once("error",r)})}function Rh(e){let t=e??"/";if(t.startsWith("/"))return t;try{let n=new URL(t);return`${n.pathname}${n.search}`||"/"}catch{return t}}var ME=0;function VE(){return $E(DE(),`srt-tt-${process.pid}-${(ME++).toString(36)}.sock`)}function ZE(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||!Bo(r.slice(i+1),t))return{ok:!1};return{ok:!0,encodedCommand:Lo(r.slice(0,i))}}function $h(e){let t=HE();t.on("clientError",(r,i)=>{if(w(`Client connection error: ${r.message}`,{level:"error"}),i.on("error",()=>{}),r.code!=="ECONNRESET"&&i.writable){let o=r.code==="HPE_HEADER_OVERFLOW"?"431 Request Header Fields Too Large":"400 Bad Request";i.end(`HTTP/1.1 ${o}\r
51
+ `}async function FE(e,t,n,r,i,o,s,a){let c=[i],u=i.length,l=()=>{let R;while((R=r.read())!==null){if(u+=R.length,u>zE){r.destroy();return}c.push(R)}},f=()=>{r.destroy()};r.on("readable",l),r.once("end",f),l();let p=n.method??"GET",h=Bh(n.url),d=o.port===443?o.hostname:`${o.hostname}:${o.port}`,g=`https://${d}${h}`,v=String(n.headers.upgrade??"").trim().toLowerCase();if(p!=="GET"||v!=="websocket"){Br(r,501,`The sandbox proxy carries WebSocket upgrades (GET with Upgrade: websocket) only; ${p} with Upgrade: ${String(n.headers.upgrade??"").slice(0,40)} is not carried.`,"upgrade-not-carried");return}let b=n.headers["content-length"];if(b!==void 0&&b.trim()!=="0"||n.headers["transfer-encoding"]!==void 0){Br(r,400,"An upgrade request with a body is not carried by the sandbox proxy.","upgrade-with-body");return}if(e){let R=new AbortController;r.once("close",()=>R.abort());let V=await ah(e,n,g,R.signal);if(V.action!=="allow"){let D=V.reason??As;w(`[request-filter] deny: ${D}`),o.onFilterRequestDeny?.(p,g,D),Br(r,403,D,"blocked-by-sandbox-runtime");return}if(r.destroyed)return}let S=xr(n.headers);if(delete S.host,a?.(S,o.hostname)){Br(r,501,`This upgrade (WebSocket) request to ${o.hostname} carries a brokered credential placeholder, and the credential broker carries requests, not upgraded connections. Use a WebSocket without that credential, or an ordinary HTTPS request.`,"upgrade-not-carried");return}let C=s?.(p,h,S,o.hostname);if(t?.(S,o.hostname),C?.action==="deny"){Br(r,403,C.reason,"blocked-by-sandbox-runtime");return}if(C?.action==="resign"){let R=oi(o.hostname)===6?`[${o.hostname}]`:o.hostname,V=o.port===443?R:`${R}:${o.port}`;try{C.apply(S,V,C.payloadHash??$s(Buffer.alloc(0)))}catch(D){Br(r,403,`AWS SigV4 re-signing failed: ${D.message}`,"blocked-by-sandbox-runtime");return}}S.connection="Upgrade",S.upgrade=n.headers.upgrade;let T;if(o.resolveAddress){try{T=await o.resolveAddress()}catch(R){if(R instanceof Rr)Br(r,403,`Connection blocked: ${R.message}`,"blocked-by-allowlist");else Br(r,502,`${d} could not be reached: ${R.message}`,"upstream-unreachable");return}if(r.destroyed)return}let I=!1,k=Th({host:o.hostname,port:o.port,path:h,method:p,headers:S,...oi(o.hostname)?{}:{servername:o.hostname},...T!==void 0&&T!==o.hostname?{lookup:Rh(T)}:{},...o.upstreamCA?{ca:o.upstreamCA}:{},agent:!1});k.on("upgrade",(R,V,D)=>{if(I=!0,V.on("error",(H)=>{w(`[tls-terminate] upgraded upstream ${o.hostname}:${o.port} error: ${H.message}`,{level:"error"}),r.destroy()}),r.write(_h(R.statusCode??101,R.statusMessage,R.rawHeaders),"latin1"),D.length)r.write(D);r.removeListener("readable",l),r.removeListener("end",f),l();let F=Buffer.concat(c);if(F.length)V.write(F);r.once("close",()=>Eh(V)),V.once("close",()=>Eh(r)),xu(r,V),xu(V,r)}),k.on("response",(R)=>{I=!0,r.once("close",()=>k.destroy()),R.on("error",()=>r.destroy());let V=xr(R.headers),D=[];for(let[F,H]of Object.entries(V))for(let re of Array.isArray(H)?H:H===void 0?[]:[H])D.push(F,String(re));D.push("connection","close"),r.write(_h(R.statusCode??502,R.statusMessage,D),"latin1"),R.pipe(r)}),k.on("error",(R)=>{if(w(`[tls-terminate] upstream upgrade ${o.hostname}:${o.port} failed: ${R.message}`,{level:"error"}),!I)Br(r,502,`${d} could not be reached: ${R.message}`,"upstream-unreachable");else r.destroy()}),r.once("close",()=>{if(!I)k.destroy()}),k.end()}function Rh(e){let t=oi(e);return(n,r,i)=>{if(r.all)i(null,[{address:e,family:t}]);else i(null,e,t)}}function ME(e,t){return new Promise((n,r)=>{let i=[],o=0,s=(a)=>{if(o+=a.length,o>t){i.length=0,e.removeListener("data",s),r(new bu(`request body exceeds ${t} bytes`));return}i.push(a)};e.on("data",s),e.once("end",()=>n(Buffer.concat(i))),e.once("error",r)})}function Bh(e){let t=e??"/";if(t.startsWith("/"))return t;try{let n=new URL(t);return`${n.pathname}${n.search}`||"/"}catch{return t}}var VE=0;function WE(){return OE($E(),`srt-tt-${process.pid}-${(VE++).toString(36)}.sock`)}function jE(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||!Bo(r.slice(i+1),t))return{ok:!1};return{ok:!0,encodedCommand:Lo(r.slice(0,i))}}function Oh(e){let t=KE();t.on("clientError",(r,i)=>{if(w(`Client connection error: ${r.message}`,{level:"error"}),i.on("error",()=>{}),r.code!=="ECONNRESET"&&i.writable){let o=r.code==="HPE_HEADER_OVERFLOW"?"431 Request Header Fields Too Large":"400 Bad Request";i.end(`HTTP/1.1 ${o}\r
52
52
  \r
53
- `,()=>i.destroy()),setTimeout(()=>i.destroy(),1000).unref?.();return}i.destroy()});let n=(r)=>ZE(r,e.proxyAuthToken);return t.on("connect",async(r,i,o)=>{i.on("error",(b)=>{w(`Client socket error: ${b.message}`,{level:"error"}),i.destroy()});let s=!1;i.once("close",()=>{s=!0});let a=()=>{s=!0,i.destroy()},c=65536,u=0,l=!1,f=[],p=(b)=>{if(!l)return;if(u+=b.length,u>c){w("CONNECT client exceeded pre-establishment capture cap; destroying",{level:"error"}),a();return}f.push(b)};if(!e.mitmCA)l=!0,i.on("data",p);if(i.readableEnded)a();else i.once("end",a);let h=()=>{if(l=!1,f.length)o=Buffer.concat([o,...f]),f.length=0},d=()=>{i.removeListener("end",a),h()},g=(b)=>{if(s||i.destroyed||i.readableEnded||!i.writable){w("CONNECT client gone before status write; dropping verdict and destroying socket"),i.destroy();return}d(),i.end(b)};if(s||i.destroyed)return;let x=!1;try{let b=n(r.headers["proxy-authorization"]);if(!b.ok){g(`HTTP/1.1 407 Proxy Authentication Required\r
53
+ `,()=>i.destroy()),setTimeout(()=>i.destroy(),1000).unref?.();return}i.destroy()});let n=(r)=>jE(r,e.proxyAuthToken);return t.on("connect",async(r,i,o)=>{i.on("error",(b)=>{w(`Client socket error: ${b.message}`,{level:"error"}),i.destroy()});let s=!1;i.once("close",()=>{s=!0});let a=()=>{s=!0,i.destroy()},c=65536,u=0,l=!1,f=[],p=(b)=>{if(!l)return;if(u+=b.length,u>c){w("CONNECT client exceeded pre-establishment capture cap; destroying",{level:"error"}),a();return}f.push(b)};if(!e.mitmCA)l=!0,i.on("data",p);if(i.readableEnded)a();else i.once("end",a);let h=()=>{if(l=!1,f.length)o=Buffer.concat([o,...f]),f.length=0},d=()=>{i.removeListener("end",a),h()},g=(b)=>{if(s||i.destroyed||i.readableEnded||!i.writable){w("CONNECT client gone before status write; dropping verdict and destroying socket"),i.destroy();return}d(),i.end(b)};if(s||i.destroyed)return;let v=!1;try{let b=n(r.headers["proxy-authorization"]);if(!b.ok){g(`HTTP/1.1 407 Proxy Authentication Required\r
54
54
  Proxy-Authenticate: Basic realm="srt"\r
55
55
  \r
56
- `);return}let S=jE(r.url);if(!S){w(`Invalid CONNECT request: ${r.url}`,{level:"error"}),g(`HTTP/1.1 400 Bad Request\r
56
+ `);return}let S=GE(r.url);if(!S){w(`Invalid CONNECT request: ${r.url}`,{level:"error"}),g(`HTTP/1.1 400 Bad Request\r
57
57
  \r
58
58
  `);return}let{hostname:C,port:T}=S;if(!await e.filter(T,C,i,b.encodedCommand)){w(`Connection blocked to ${C}:${T}`,{level:"error"}),g(`HTTP/1.1 403 Forbidden\r
59
59
  Content-Type: text/plain\r
60
60
  X-Proxy-Error: blocked-by-allowlist\r
61
61
  \r
62
- Connection blocked by network allowlist`);return}if(s||i.destroyed){i.destroy();return}let k=vt(C)??C,R;if(e.mitmCA&&(e.shouldTerminateTLS?.(k,T)??!0)){i.write(`HTTP/1.1 200 Connection Established\r
62
+ Connection blocked by network allowlist`);return}if(s||i.destroyed){i.destroy();return}let k=xt(C)??C,R;if(e.mitmCA&&(e.shouldTerminateTLS?.(k,T)??!0)){i.write(`HTTP/1.1 200 Connection Established\r
63
63
  \r
64
- `),x=!0;let H=await kh(i,o);if(s||i.destroyed){i.destroy();return}if(H.isTLS){d(),Ih(e.mitmCA,e.filterRequest,e.mutateHeaders,e.getBodySubstitutions,i,H.head,{hostname:k,port:T,resolveAddress:e.resolveDestination&&(()=>R??=e.resolveDestination(k,T)),upstreamCA:e.tlsTerminateUpstreamCA,onFilterRequestDeny:e.onFilterRequestDenied?(re,se,Pe)=>e.onFilterRequestDenied({method:re,url:se,reason:Pe,encodedCommand:b.encodedCommand}):void 0},e.planSigv4,e.maxSigv4ResignBodyBytes,e.getBrokerForward);return}w(`[tls-terminate] non-TLS bytes on CONNECT ${k}:${T}; opaque-tunnelling`),o=H.head}else if(e.mitmCA)w(`[tls-terminate] policy exempts ${k}:${T}; opaque-tunnelling`);let V=e.getMitmSocketPath?.(k),D=!V&&e.parentProxy&&!ji(e.parentProxy,k)?Gi(e.parentProxy,{isHttps:!0}):void 0,F;try{if(V)w(`Routing CONNECT ${k}:${T} through MITM proxy at ${V}`),F=await du({dial:()=>KE({path:V}),readyEvent:"connect",destHost:k,destPort:T});else if(D)F=await Rs(D,k,T);else F=await Bs(await e.resolveDestination?.(k,T)??k,T)}catch(H){if(w(`CONNECT tunnel failed: ${H.message}`,{level:"error"}),x)i.destroy();else if(H instanceof Rr)g(`HTTP/1.1 403 Forbidden\r
64
+ `),v=!0;let H=await Ih(i,o);if(s||i.destroyed){i.destroy();return}if(H.isTLS){d(),Ph(e.mitmCA,e.filterRequest,e.mutateHeaders,e.getBodySubstitutions,i,H.head,{hostname:k,port:T,resolveAddress:e.resolveDestination&&(()=>R??=e.resolveDestination(k,T)),upstreamCA:e.tlsTerminateUpstreamCA,onFilterRequestDeny:e.onFilterRequestDenied?(re,se,Pe)=>e.onFilterRequestDenied({method:re,url:se,reason:Pe,encodedCommand:b.encodedCommand}):void 0},e.planSigv4,e.maxSigv4ResignBodyBytes,e.getBrokerForward);return}w(`[tls-terminate] non-TLS bytes on CONNECT ${k}:${T}; opaque-tunnelling`),o=H.head}else if(e.mitmCA)w(`[tls-terminate] policy exempts ${k}:${T}; opaque-tunnelling`);let V=e.getMitmSocketPath?.(k),D=!V&&e.parentProxy&&!Gi(e.parentProxy,k)?qi(e.parentProxy,{isHttps:!0}):void 0,F;try{if(V)w(`Routing CONNECT ${k}:${T} through MITM proxy at ${V}`),F=await pu({dial:()=>ZE({path:V}),readyEvent:"connect",destHost:k,destPort:T});else if(D)F=await Rs(D,k,T);else F=await Bs(await e.resolveDestination?.(k,T)??k,T)}catch(H){if(w(`CONNECT tunnel failed: ${H.message}`,{level:"error"}),v)i.destroy();else if(H instanceof Rr)g(`HTTP/1.1 403 Forbidden\r
65
65
  Content-Type: text/plain\r
66
66
  X-Proxy-Error: blocked-by-allowlist\r
67
67
  \r
@@ -69,35 +69,35 @@ Connection blocked: ${H.message}`);else{let re=H.message.replace(/[\r\n]+/g," ")
69
69
  Content-Type: text/plain\r
70
70
  X-Proxy-Error: upstream-unreachable\r
71
71
  \r
72
- ${k}:${T} could not be reached (the network allowlist allowed it): ${re}`)}return}if(s||i.destroyed){F.on("error",()=>{}),F.destroy(),i.destroy();return}if(!x)i.write(`HTTP/1.1 200 Connection Established\r
72
+ ${k}:${T} could not be reached (the network allowlist allowed it): ${re}`)}return}if(s||i.destroyed){F.on("error",()=>{}),F.destroy(),i.destroy();return}if(!v)i.write(`HTTP/1.1 200 Connection Established\r
73
73
  \r
74
- `);if(d(),i.allowHalfOpen=!0,o.length)F.write(o);F.pipe(i),i.pipe(F),F.on("error",(H)=>{w(`CONNECT tunnel failed: ${H.message}`,{level:"error"}),i.destroy()}),i.on("close",()=>F.destroy()),F.on("close",()=>i.destroy())}catch(b){if(w(`Error handling CONNECT: ${b}`,{level:"error"}),x)i.destroy();else g(`HTTP/1.1 500 Internal Server Error\r
74
+ `);if(d(),i.allowHalfOpen=!0,o.length)F.write(o);F.pipe(i),i.pipe(F),F.on("error",(H)=>{w(`CONNECT tunnel failed: ${H.message}`,{level:"error"}),i.destroy()}),i.on("close",()=>F.destroy()),F.on("close",()=>i.destroy())}catch(b){if(w(`Error handling CONNECT: ${b}`,{level:"error"}),v)i.destroy();else g(`HTTP/1.1 500 Internal Server Error\r
75
75
  \r
76
- `)}}),t.on("request",async(r,i)=>{r.on("error",(o)=>{w(`Client request error: ${o.message}`,{level:"error"})}),i.on("error",(o)=>{w(`Client response error: ${o.message}`,{level:"error"}),i.socket?.destroy()});try{if(e.mitmCA&&r.method==="GET"&&new Dh(r.url??"","http://x").pathname===Ss){i.writeHead(200,{"Content-Type":"application/pkix-crl","Content-Length":e.mitmCA.crlDer.length}),i.end(e.mitmCA.crlDer);return}let o=n(r.headers["proxy-authorization"]);if(!o.ok){i.writeHead(407,{"Proxy-Authenticate":'Basic realm="srt"'}),i.end();return}let s=new Dh(r.url),a=tr(s.hostname),c=s.port?parseInt(s.port,10):s.protocol==="https:"?443:80;if(!await e.filter(c,a,r.socket,o.encodedCommand)){if(w(`HTTP request blocked to ${a}:${c}`,{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 l=vt(a)??a,f=(Nh(l)===6?`[${l}]`:l)+(s.port?`:${s.port}`:""),p={...xr(r.headers),host:f};e.mutateHeadersPlaintext?.(p,l);let h=Is(e.getBodySubstitutionsPlaintext,r,p,l),d=e.getMitmSocketPath?.(l),g=!d&&e.parentProxy&&!ji(e.parentProxy,l)?Gi(e.parentProxy,{isHttps:s.protocol==="https:"}):void 0,x=`${s.protocol}//${f}${s.pathname}${s.search}`,b=r;if(e.filterRequest){let T=new AbortController;i.once("close",()=>T.abort());let I=await ks(e.filterRequest,r,i,x,T.signal,e.onFilterRequestDenied?(k,R,V)=>e.onFilterRequestDenied({method:k,url:R,reason:V,encodedCommand:o.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"])&&p["content-length"]===void 0&&p["transfer-encoding"]===void 0)p["transfer-encoding"]="chunked";let C;if(d){w(`Routing HTTP ${r.method} ${l}:${c} through MITM proxy at ${d}`);let T=new WE({socketPath:d});C=bu({agent:T,path:x,method:r.method,headers:p},(I)=>{I.on("error",(k)=>{w(`Upstream response error: ${k.message}`,{level:"error"}),i.destroy()}),i.writeHead(I.statusCode,xr(I.headers)),I.pipe(i)})}else if(g){let T=tr(g.hostname),I=Number(g.port)||(g.protocol==="https:"?443:80),k=pu(g);C=(g.protocol==="https:"?Bh:bu)({hostname:T,port:I,path:x,method:r.method,headers:k?{...p,"proxy-authorization":k}:p},(V)=>{V.on("error",(D)=>{w(`Upstream response error: ${D.message}`,{level:"error"}),i.destroy()}),i.writeHead(V.statusCode,xr(V.headers)),V.pipe(i)})}else{let T=s.protocol==="https:"?Bh:bu,I=l;if(e.resolveDestination)try{I=await e.resolveDestination(l,c)}catch(k){if(w(`Refused ${l}:${c}: ${k.message}`,{level:"error"}),k instanceof Rr)i.writeHead(403,{"Content-Type":"text/plain","X-Proxy-Error":"blocked-by-allowlist"}),i.end(`Connection blocked: ${k.message}`);else i.writeHead(502,{"Content-Type":"text/plain"}),i.end("Bad Gateway");return}C=T({hostname:I,...I!==l&&s.protocol==="https:"&&!Nh(l)?{servername:l}:{},port:c,path:s.pathname+s.search,method:r.method,headers:p},(k)=>{k.on("error",(R)=>{w(`Upstream response error: ${R.message}`,{level:"error"}),i.destroy()}),i.writeHead(k.statusCode,xr(k.headers)),k.pipe(i)})}if(C.on("error",(T)=>{if(w(`Proxy request failed: ${T.message}`,{level:"error"}),!i.headersSent)i.writeHead(502,{"Content-Type":"text/plain"}),i.end("Bad Gateway");else i.destroy()}),i.on("close",()=>C.destroy()),h)h.on("error",(T)=>C.destroy(T)),b.on("error",(T)=>h.destroy(T)),i.on("close",()=>h.destroy()),b.pipe(h).pipe(C);else b.on("error",(T)=>C.destroy(T)),b.pipe(C)}catch(o){if(w(`Error handling HTTP request: ${o}`,{level:"error"}),!i.headersSent)i.writeHead(500,{"Content-Type":"text/plain"}),i.end("Internal Server Error");else i.destroy()}}),t}function jE(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 Wh=ja(Vh(),1);function o_(e,t,n){if(!n||t===void 0)return!1;return e!==void 0&&(e===_r||e.startsWith(`${_r}.`))&&Bo(t,n)}function Hh(e){let t=Wh.createServer();if(e.proxyAuthToken)t.setAuthHandler((r,i,o)=>{if(o_(r.username,r.password,e.proxyAuthToken))i();else w("SOCKS auth rejected",{level:"error"}),o()});t.setRulesetValidator(async(r)=>{try{let{destAddress:i,destPort:o}=r;if(!ti(i))return w(`Rejecting malformed SOCKS host: ${JSON.stringify(i)}`,{level:"error"}),!1;if(w(`Connection request to ${i}:${o}`),!await e.filter(o,i,Lo(r.username)))return w(`Connection blocked to ${i}:${o}`,{level:"error"}),!1;return w(`Connection allowed to ${i}:${o}`),!0}catch(i){return w(`Error validating connection: ${i}`,{level:"error"}),!1}}),t.setConnectionHandler((r,i)=>{let o=vt(r.destAddress)??r.destAddress,s=r.destPort,a=!1,c;r.socket.once("close",()=>{a=!0,c?.destroy()}),r.socket.on("error",()=>c?.destroy());let u=e.parentProxy&&!ji(e.parentProxy,o)?Gi(e.parentProxy,{isHttps:!0}):void 0;(u?Rs(u,o,s):(e.resolveDestination?.(o,s)??Promise.resolve(o)).then((f)=>Bs(f,s))).then((f)=>{if(c=f,f.on("error",()=>r.socket.destroy()),a){f.destroy();return}i("REQUEST_GRANTED"),f.pipe(r.socket),r.socket.pipe(f),f.on("close",()=>r.socket.destroy())}).catch((f)=>{if(w(`SOCKS connect to ${o}:${s} failed: ${f.message}`,{level:"error"}),!a)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}c_(r,(i)=>{if(i){t._handleConnection(r);return}u_(r,e).catch(()=>r.destroy())})},async close(){for(let r of n)r.destroy();n.clear()}}}var s_=0,a_=2;function c_(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 o=n[1];if(n.length<2+o)return;e.off("data",r),e.pause();let a=n.subarray(2,2+o).includes(a_),c=a?n:n.subarray(2+o);if(c.length>0)e.unshift(c);t(a)};e.on("data",r),e.once("error",()=>e.off("data",r))}async function u_(e,t){e.write(Buffer.from([5,s_]));let n=await l_(e);if(n===void 0){e.destroy();return}let{host:r,port:i}=n;if(!ti(r)){e.end(wu(2));return}let o=t.probeUnauthenticated?await t.probeUnauthenticated(i,r):{};if(w(`SOCKS unauthenticated client refused for ${r}:${i}`+(o.deniedReason!==void 0?" (denied by policy)":"")),i!==22){e.end(wu(2));return}let s=o.deniedReason??"This proxy requires authentication, and this client did not offer an authentication method, so the connection was refused.";e.write(wu(0)),e.write(Buffer.from(`SSH-2.0-policy_refusal\r
77
- `)),e.end(f_(s))}function wu(e){return Buffer.from([5,e,0,1,0,0,0,0,0,0])}function l_(e){return new Promise((t)=>{let n=Buffer.alloc(0),r=(s)=>{e.off("data",o),clearTimeout(i),t(s)},i=setTimeout(()=>r(void 0),5000),o=(s)=>{if(n=Buffer.concat([n,s]),n.length<4)return;if(n[0]!==5||n[1]!==1){r(void 0);return}let a=n[3];if(a===1){if(n.length<10)return;let c=Array.from(n.subarray(4,8)).join(".");r({host:c,port:n.readUInt16BE(8)})}else if(a===3){if(n.length<5)return;let c=n[4];if(n.length<5+c+2)return;r({host:n.subarray(5,5+c).toString("utf8"),port:n.readUInt16BE(5+c)})}else if(a===4){if(n.length<22)return;let c=[];for(let u=0;u<16;u+=2)c.push(n.readUInt16BE(4+u).toString(16));r({host:c.join(":"),port:n.readUInt16BE(20)})}else r(void 0)};e.on("data",o),e.resume(),e.once("error",()=>r(void 0)),e.once("close",()=>r(void 0))})}function f_(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]),Ls(1),Ls(n.length),n,Ls(r.length),r]),o=8-(5+i.length)%8;if(o<4)o+=8;return Buffer.concat([Ls(1+i.length+o),Buffer.from([o]),i,Buffer.alloc(o)])}function Ls(e){let t=Buffer.alloc(4);return t.writeUInt32BE(e,0),t}import{createServer as d_,connect as Kh}from"net";import{join as p_}from"path";import{tmpdir as h_}from"os";import{unlink as Zh}from"fs/promises";function Us(e,t,n,r){return new Promise((i,o)=>{let[s,a]=n??[0,0],c=s,u=()=>{while(r.has(c)&&c<=a)c++;if(c>a){o(Error(`No free port in range ${s}-${a} (excluding ${[...r].join(",")})`));return}let l=()=>{e.removeListener("error",f),i()},f=(p)=>{if(e.removeListener("listening",l),n&&p?.code==="EADDRINUSE"&&c<a){c++,u();return}o(p??Error("listen error"))};e.once("error",f),e.once("listening",l),t(n?c:0)};u()})}var m_=new Set([4,5]),g_=1e4,y_=0;function v_(){return p_(h_(),`srt-mux-${process.pid}-${(y_++).toString(36)}.sock`)}function jh(e){let t=e.firstByteTimeoutMs??g_,n=Ie()==="windows",r,i,o=new Set;function s(c){if(r===void 0&&i===void 0){w("mux: HTTP dispatch before backend bound; dropping",{level:"error"}),c.destroy();return}let u=r?Kh(r):Kh(i,"127.0.0.1");u.on("error",(l)=>{let f=l.code??"ERR";if(w(`mux: HTTP backend dial failed: ${l.message}`,{level:"error"}),!c.destroyed)c.end(`HTTP/1.1 502 Bad Gateway\r
76
+ `)}}),t.on("request",async(r,i)=>{r.on("error",(o)=>{w(`Client request error: ${o.message}`,{level:"error"})}),i.on("error",(o)=>{w(`Client response error: ${o.message}`,{level:"error"}),i.socket?.destroy()});try{if(e.mitmCA&&r.method==="GET"&&new $h(r.url??"","http://x").pathname===Ss){i.writeHead(200,{"Content-Type":"application/pkix-crl","Content-Length":e.mitmCA.crlDer.length}),i.end(e.mitmCA.crlDer);return}let o=n(r.headers["proxy-authorization"]);if(!o.ok){i.writeHead(407,{"Proxy-Authenticate":'Basic realm="srt"'}),i.end();return}let s=new $h(r.url),a=tr(s.hostname),c=s.port?parseInt(s.port,10):s.protocol==="https:"?443:80;if(!await e.filter(c,a,r.socket,o.encodedCommand)){if(w(`HTTP request blocked to ${a}:${c}`,{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 l=xt(a)??a,f=(Dh(l)===6?`[${l}]`:l)+(s.port?`:${s.port}`:""),p={...xr(r.headers),host:f};e.mutateHeadersPlaintext?.(p,l);let h=Is(e.getBodySubstitutionsPlaintext,r,p,l),d=e.getMitmSocketPath?.(l),g=!d&&e.parentProxy&&!Gi(e.parentProxy,l)?qi(e.parentProxy,{isHttps:s.protocol==="https:"}):void 0,v=`${s.protocol}//${f}${s.pathname}${s.search}`,b=r;if(e.filterRequest){let T=new AbortController;i.once("close",()=>T.abort());let I=await ks(e.filterRequest,r,i,v,T.signal,e.onFilterRequestDenied?(k,R,V)=>e.onFilterRequestDenied({method:k,url:R,reason:V,encodedCommand:o.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"])&&p["content-length"]===void 0&&p["transfer-encoding"]===void 0)p["transfer-encoding"]="chunked";let C;if(d){w(`Routing HTTP ${r.method} ${l}:${c} through MITM proxy at ${d}`);let T=new HE({socketPath:d});C=Su({agent:T,path:v,method:r.method,headers:p},(I)=>{I.on("error",(k)=>{w(`Upstream response error: ${k.message}`,{level:"error"}),i.destroy()}),i.writeHead(I.statusCode,xr(I.headers)),I.pipe(i)})}else if(g){let T=tr(g.hostname),I=Number(g.port)||(g.protocol==="https:"?443:80),k=hu(g);C=(g.protocol==="https:"?Nh:Su)({hostname:T,port:I,path:v,method:r.method,headers:k?{...p,"proxy-authorization":k}:p},(V)=>{V.on("error",(D)=>{w(`Upstream response error: ${D.message}`,{level:"error"}),i.destroy()}),i.writeHead(V.statusCode,xr(V.headers)),V.pipe(i)})}else{let T=s.protocol==="https:"?Nh:Su,I=l;if(e.resolveDestination)try{I=await e.resolveDestination(l,c)}catch(k){if(w(`Refused ${l}:${c}: ${k.message}`,{level:"error"}),k instanceof Rr)i.writeHead(403,{"Content-Type":"text/plain","X-Proxy-Error":"blocked-by-allowlist"}),i.end(`Connection blocked: ${k.message}`);else i.writeHead(502,{"Content-Type":"text/plain"}),i.end("Bad Gateway");return}C=T({hostname:I,...I!==l&&s.protocol==="https:"&&!Dh(l)?{servername:l}:{},port:c,path:s.pathname+s.search,method:r.method,headers:p},(k)=>{k.on("error",(R)=>{w(`Upstream response error: ${R.message}`,{level:"error"}),i.destroy()}),i.writeHead(k.statusCode,xr(k.headers)),k.pipe(i)})}if(C.on("error",(T)=>{if(w(`Proxy request failed: ${T.message}`,{level:"error"}),!i.headersSent)i.writeHead(502,{"Content-Type":"text/plain"}),i.end("Bad Gateway");else i.destroy()}),i.on("close",()=>C.destroy()),h)h.on("error",(T)=>C.destroy(T)),b.on("error",(T)=>h.destroy(T)),i.on("close",()=>h.destroy()),b.pipe(h).pipe(C);else b.on("error",(T)=>C.destroy(T)),b.pipe(C)}catch(o){if(w(`Error handling HTTP request: ${o}`,{level:"error"}),!i.headersSent)i.writeHead(500,{"Content-Type":"text/plain"}),i.end("Internal Server Error");else i.destroy()}}),t}function GE(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 Hh=ja(Wh(),1);function s_(e,t,n){if(!n||t===void 0)return!1;return e!==void 0&&(e===_r||e.startsWith(`${_r}.`))&&Bo(t,n)}function Kh(e){let t=Hh.createServer();if(e.proxyAuthToken)t.setAuthHandler((r,i,o)=>{if(s_(r.username,r.password,e.proxyAuthToken))i();else w("SOCKS auth rejected",{level:"error"}),o()});t.setRulesetValidator(async(r)=>{try{let{destAddress:i,destPort:o}=r;if(!ni(i))return w(`Rejecting malformed SOCKS host: ${JSON.stringify(i)}`,{level:"error"}),!1;if(w(`Connection request to ${i}:${o}`),!await e.filter(o,i,Lo(r.username)))return w(`Connection blocked to ${i}:${o}`,{level:"error"}),!1;return w(`Connection allowed to ${i}:${o}`),!0}catch(i){return w(`Error validating connection: ${i}`,{level:"error"}),!1}}),t.setConnectionHandler((r,i)=>{let o=xt(r.destAddress)??r.destAddress,s=r.destPort,a=!1,c;r.socket.once("close",()=>{a=!0,c?.destroy()}),r.socket.on("error",()=>c?.destroy());let u=e.parentProxy&&!Gi(e.parentProxy,o)?qi(e.parentProxy,{isHttps:!0}):void 0;(u?Rs(u,o,s):(e.resolveDestination?.(o,s)??Promise.resolve(o)).then((f)=>Bs(f,s))).then((f)=>{if(c=f,f.on("error",()=>r.socket.destroy()),a){f.destroy();return}i("REQUEST_GRANTED"),f.pipe(r.socket),r.socket.pipe(f),f.on("close",()=>r.socket.destroy())}).catch((f)=>{if(w(`SOCKS connect to ${o}:${s} failed: ${f.message}`,{level:"error"}),!a)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}u_(r,(i)=>{if(i){t._handleConnection(r);return}l_(r,e).catch(()=>r.destroy())})},async close(){for(let r of n)r.destroy();n.clear()}}}var a_=0,c_=2;function u_(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 o=n[1];if(n.length<2+o)return;e.off("data",r),e.pause();let a=n.subarray(2,2+o).includes(c_),c=a?n:n.subarray(2+o);if(c.length>0)e.unshift(c);t(a)};e.on("data",r),e.once("error",()=>e.off("data",r))}async function l_(e,t){e.write(Buffer.from([5,a_]));let n=await f_(e);if(n===void 0){e.destroy();return}let{host:r,port:i}=n;if(!ni(r)){e.end(Eu(2));return}let o=t.probeUnauthenticated?await t.probeUnauthenticated(i,r):{};if(w(`SOCKS unauthenticated client refused for ${r}:${i}`+(o.deniedReason!==void 0?" (denied by policy)":"")),i!==22){e.end(Eu(2));return}let s=o.deniedReason??"This proxy requires authentication, and this client did not offer an authentication method, so the connection was refused.";e.write(Eu(0)),e.write(Buffer.from(`SSH-2.0-policy_refusal\r
77
+ `)),e.end(d_(s))}function Eu(e){return Buffer.from([5,e,0,1,0,0,0,0,0,0])}function f_(e){return new Promise((t)=>{let n=Buffer.alloc(0),r=(s)=>{e.off("data",o),clearTimeout(i),t(s)},i=setTimeout(()=>r(void 0),5000),o=(s)=>{if(n=Buffer.concat([n,s]),n.length<4)return;if(n[0]!==5||n[1]!==1){r(void 0);return}let a=n[3];if(a===1){if(n.length<10)return;let c=Array.from(n.subarray(4,8)).join(".");r({host:c,port:n.readUInt16BE(8)})}else if(a===3){if(n.length<5)return;let c=n[4];if(n.length<5+c+2)return;r({host:n.subarray(5,5+c).toString("utf8"),port:n.readUInt16BE(5+c)})}else if(a===4){if(n.length<22)return;let c=[];for(let u=0;u<16;u+=2)c.push(n.readUInt16BE(4+u).toString(16));r({host:c.join(":"),port:n.readUInt16BE(20)})}else r(void 0)};e.on("data",o),e.resume(),e.once("error",()=>r(void 0)),e.once("close",()=>r(void 0))})}function d_(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]),Ls(1),Ls(n.length),n,Ls(r.length),r]),o=8-(5+i.length)%8;if(o<4)o+=8;return Buffer.concat([Ls(1+i.length+o),Buffer.from([o]),i,Buffer.alloc(o)])}function Ls(e){let t=Buffer.alloc(4);return t.writeUInt32BE(e,0),t}import{createServer as p_,connect as Zh}from"net";import{join as h_}from"path";import{tmpdir as m_}from"os";import{unlink as jh}from"fs/promises";function Us(e,t,n,r){return new Promise((i,o)=>{let[s,a]=n??[0,0],c=s,u=()=>{while(r.has(c)&&c<=a)c++;if(c>a){o(Error(`No free port in range ${s}-${a} (excluding ${[...r].join(",")})`));return}let l=()=>{e.removeListener("error",f),i()},f=(p)=>{if(e.removeListener("listening",l),n&&p?.code==="EADDRINUSE"&&c<a){c++,u();return}o(p??Error("listen error"))};e.once("error",f),e.once("listening",l),t(n?c:0)};u()})}var g_=new Set([4,5]),y_=1e4,v_=0;function x_(){return h_(m_(),`srt-mux-${process.pid}-${(v_++).toString(36)}.sock`)}function Gh(e){let t=e.firstByteTimeoutMs??y_,n=Ie()==="windows",r,i,o=new Set;function s(c){if(r===void 0&&i===void 0){w("mux: HTTP dispatch before backend bound; dropping",{level:"error"}),c.destroy();return}let u=r?Zh(r):Zh(i,"127.0.0.1");u.on("error",(l)=>{let f=l.code??"ERR";if(w(`mux: HTTP backend dial failed: ${l.message}`,{level:"error"}),!c.destroyed)c.end(`HTTP/1.1 502 Bad Gateway\r
78
78
  Connection: close\r
79
79
  \r
80
80
  mux backend dial failed (${f})
81
- `)}),c.on("error",()=>u.destroy()),c.once("close",()=>u.destroy()),u.once("close",()=>c.destroy()),c.pipe(u),u.pipe(c)}let a=d_((c)=>{o.add(c),c.once("close",()=>o.delete(c)),c.on("error",(l)=>w(`mux: client socket error: ${l.message}`));let u=setTimeout(()=>{w("mux: first-byte timeout; destroying connection"),c.destroy()},t);if(typeof u.unref==="function")u.unref();c.once("readable",()=>{clearTimeout(u);let l=c.read(1);if(!l||l.length===0){c.destroy();return}if(c.unshift(l),m_.has(l[0]))e.handleSocksConnection(c);else s(c)})});return{server:a,getPort(){let c=a.address();return c&&typeof c==="object"?c.port:void 0},async listenHttpBackend(){if(!n){let u=v_();await Zh(u).catch(()=>{}),await new Promise((l,f)=>{e.httpServer.once("error",f),e.httpServer.listen(u,()=>{e.httpServer.removeListener("error",f),l()})}),r=u,w(`mux: HTTP backend listening on ${u}`);return}await Us(e.httpServer,(u)=>e.httpServer.listen(u,"127.0.0.1"),e.httpBackendPortRange,new Set);let c=e.httpServer.address();return i=c&&typeof c==="object"?c.port:void 0,w(`mux: HTTP backend listening on 127.0.0.1:${i}`),i},async close(){for(let c of o)c.destroy();if(o.clear(),await new Promise((c)=>a.close(()=>c())),await new Promise((c)=>e.httpServer.close(()=>c())),r)await Zh(r).catch(()=>{}),r=void 0;i=void 0},unref(){a.unref(),e.httpServer.unref()}}}import{randomInt as x_,randomUUID as b_}from"crypto";var ii="fake_value_",Gh="abcdefghijklmnopqrstuvwxyz0123456789_-";function S_(e){let t=ii+b_(),n=Buffer.byteLength(e)-t.length;if(n<=0)return t;let r=t;for(let i=0;i<n;i++)r+=Gh[x_(Gh.length)];return r}class Eu{byName=new Map;bySentinel=new Map;allSentinelsPrefixed=!0;refs=new Map;lease=null;register(e,t,n,r){return this.registerWithSentinel(e,S_(t),t,n,r)}registerWithSentinel(e,t,n,r,i){let o=this.byName.get(e);if(o!==void 0&&o.realValue===n)return o.injectHosts=r,o.injectHeaders=i,this.lease?.add(o),o.sentinel;if(this.bySentinel.has(t))throw Error("credential sentinel collision");if(!t.startsWith(ii))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(ii));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 o=0;o<i.length;o++)i[o]=this.substituteInHeaderValue(r,i[o],t,n);else e[r]=this.substituteInHeaderValue(r,i,t,n)}}substituteInHeaderValue(e,t,n,r){let i=e.toLowerCase(),o=this.substituteInString(t,n,r,i);if(i!=="authorization")return o;let s=/^(\s*basic\s+)([a-z0-9+/]+={0,2})(\s*)$/i.exec(o);if(s===null)return o;let a=s[2],c=Buffer.from(a,"base64");if(a.length%4!==0||c.toString("base64")!==a)return o;let u=c.toString("utf8");if(!Buffer.from(u,"utf8").equals(c))return o;let l=this.substituteInString(u,n,r,i);if(l===u)return o;return`${s[1]}${Buffer.from(l,"utf8").toString("base64")}${s[3]}`}substituteInString(e,t,n,r){if(this.allSentinelsPrefixed&&!e.includes(ii))return e;let i=e;for(let o of this.bySentinel.values()){if(!i.includes(o.sentinel))continue;if(!o.injectHosts.some((s)=>n(t,s)))continue;if(o.injectHeaders!==void 0&&!o.injectHeaders.includes(r))continue;i=i.split(o.sentinel).join(o.realValue)}return i}}import{randomUUID as I_}from"crypto";import*as rr from"fs";import{tmpdir as P_}from"os";import{join as Qh}from"path";function C_(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 w_(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 qh(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 E_(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 __(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 o=Number(e.slice(i,r)),s=o,a=!1;if(e[r]===","){r++;let c=r;while(/[0-9]/.test(e[r]??""))r++;if(r===c)a=!0,s=void 0;else s=Number(e.slice(c,r))}if(e[r]!=="}")return null;if(!Number.isFinite(o)||o>4096||s!==void 0&&(!Number.isFinite(s)||s>4096))return{next:r+1,unbounded:a,error:"finite repetitions must be at most 4096"};if(r++,e[r]==="?")r++;return{next:r,unbounded:a}}function T_(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=(o)=>{let s=r();if(s.lastAtom?.hasUnboundedQuantifier&&o.hasUnboundedQuantifier&&s.lastAtom.repeatClass!==null&&o.repeatClass!==null&&qh(s.lastAtom.repeatClass,o.repeatClass))s.error="adjacent unbounded repetition with overlapping input is not supported";if(s.previousAtom=s.lastAtom,s.lastAtom=o,s.atomCount===0)s.simpleClass=o.repeatClass;else s.simpleClass=null;if(s.atomCount++,o.kind==="group")s.containsQuantifier||=o.containsQuantifier,s.containsAlternation||=o.containsAlternation;s.hasUnboundedQuantifier||=o.hasUnboundedQuantifier};for(let o=0;o<e.length;){if(r().error!==void 0)return{groupCount:n,error:r().error};let s=e[o];if(s==="\\"){let c=e[o+1];if(c!==void 0&&/[1-9]/.test(c)||c==="k"&&e[o+2]==="<")return{groupCount:n,error:"backreferences are not supported by the safe extractor"};let u=c==="b"||c==="B";if(i({kind:"token",containsQuantifier:!1,containsAlternation:!1,hasUnboundedQuantifier:!1,repeatClass:w_(c)}),o+=c===void 0?1:2,u)r().previousAtom=null,r().lastAtom=null;continue}if(s==="["){i({kind:"token",containsQuantifier:!1,containsAlternation:!1,hasUnboundedQuantifier:!1,repeatClass:{kind:"unknown"}}),o=C_(e,o);continue}if(s==="("){let c=E_(e,o);if(c.capturing)n++;t.push({previousAtom:null,lastAtom:null,atomCount:0,simpleClass:null,containsQuantifier:!1,containsAlternation:!1,hasUnboundedQuantifier:!1}),o=c.next;continue}if(s===")"){if(t.length>1){let c=t.pop();if(c.error!==void 0)return{groupCount:n,error:c.error};i({kind:"group",containsQuantifier:c.containsQuantifier,containsAlternation:c.containsAlternation,hasUnboundedQuantifier:c.hasUnboundedQuantifier,repeatClass:c.atomCount===1&&!c.containsAlternation?c.simpleClass:null})}o++;continue}if(s==="|"){r().containsAlternation=!0,r().previousAtom=null,r().lastAtom=null,o++;continue}let a=__(e,o);if(a!==null){if(a.error)return{groupCount:n,error:a.error};let c=r(),u=c.lastAtom;if(a.unbounded&&u?.kind==="group"&&(u.containsQuantifier||u.containsAlternation))return{groupCount:n,error:"nested unbounded repetition or unbounded alternation is not supported"};if(a.unbounded&&c.previousAtom?.hasUnboundedQuantifier&&u!==null&&c.previousAtom.repeatClass!==null&&u.repeatClass!==null&&qh(c.previousAtom.repeatClass,u.repeatClass))return{groupCount:n,error:"adjacent unbounded repetition with overlapping input is not supported"};if(c.containsQuantifier=!0,u!==null)c.lastAtom={...u,containsQuantifier:!0,hasUnboundedQuantifier:u.hasUnboundedQuantifier||a.unbounded};c.hasUnboundedQuantifier||=a.unbounded,o=a.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;o++}return{groupCount:n,error:r().error}}function _u(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=T_(e);if(n.error!==void 0)throw Error(`Credential extract pattern rejected: ${n.error}`);return{regex:t,groupCount:n.groupCount}}function A_(e,t=""){_u(e);try{return new RegExp(e,t)}catch{throw Error("Credential extract pattern is not supported by this runtime")}}function zs(e,t,n,r={}){if(e.length>1048576)throw Error("Credential extraction input exceeds the 1048576-character limit");let i=A_(t,"gd"),o=new Map,s=new Map,a=[],c=0;for(let f of e.matchAll(i)){if(c++,c>4096)throw Error("Credential extraction exceeds the 4096-match limit");let p=f[1];if(p===void 0)throw Error(`Credential extraction matched at offset ${f.index} without a group-1 capture; group 1 must capture the credential value on every match.`);if(p.length===0)continue;let h=o.get(p);if(h===void 0)o.set(p,h=o.size);let[d,g]=f.indices[1],x=n(p,h);if(!s.has(p))s.set(p,x);a.push({start:d,end:g,sentinel:x})}if(o.size===0)return null;if(r.maskDuplicates){let f=[...o.keys()].sort((p,h)=>h.length-p.length);for(let p of f){let h=s.get(p);if(h===p)continue;for(let d=e.indexOf(p);d!==-1;d=e.indexOf(p,d+1)){let g=d+p.length;if(a.some((x)=>d<x.end&&x.start<g))continue;a.push({start:d,end:g,sentinel:h})}}a.sort((p,h)=>p.start-h.start)}let u="",l=0;for(let f of a)u+=e.slice(l,f.start)+f.sentinel,l=f.end;return{fakeContent:u+e.slice(l),captures:[...o.keys()]}}var Xh="(eyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+)";function Tu(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=Tu(t[0]);if(typeof n!=="object"||n===null||!("alg"in n))return!1;return Tu(t[1])!==void 0}var k_=9999999999,Jh="c3J0LWZha2U";function Au(e){return Buffer.from(e,"utf8").toString("base64url")}function Ms(e){let t=Au(JSON.stringify({alg:"HS256",typ:"JWT"})),n=Au(JSON.stringify({sub:ii+e,exp:k_}));return`${t}.${n}.${Jh}`}function Vs(e,t,n){let[r,i]=e.split("."),o=Tu(i??"");if(typeof o!=="object"||o===null||Array.isArray(o))return null;let s=o,a=[];for(let u of t){let l=s[u];if(typeof l==="string")a.push([u,l])}if(a.length===0)return null;let c=new Map;for(let[u,l]of a){let f=n(u,l);s[u]=f,c.set(u,f)}return{fakeToken:`${r}.${Au(JSON.stringify(s))}.${Jh}`,claimSentinels:c}}var R_="file:";class ku{dir;byKey=new Map;write(e,t){if(this.dir===void 0)this.dir=rr.mkdtempSync(Qh(P_(),"srt-credmask-"));let n=this.byKey.get(e);if(n===void 0)n=Qh(this.dir,`${this.byKey.size}.fake`),this.byKey.set(e,n);return rr.rmSync(n,{force:!0}),rr.writeFileSync(n,t,{mode:384}),n}dispose(){if(this.dir!==void 0)try{rr.rmSync(this.dir,{recursive:!0,force:!0})}catch(e){w(`MaskedFileStore cleanup failed: ${e}`,{level:"error"})}this.dir=void 0,this.byKey.clear()}get dirPath(){return this.dir}}function Yh(e,t,n,r){let i=[],o=[];for(let s of e){if(s.mode!=="mask")continue;let a=Ye(s.path),c;try{if(rr.statSync(a).isDirectory()){w(`[credential-mask] Skipping masked file entry that resolves to a directory: ${s.path} \u2014 use mode "deny" for directories.`,{level:"warn"});continue}let d=rr.readFileSync(a);if(c=d.toString("utf8"),Buffer.byteLength(c,"utf8")!==d.length){w(`[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(h){w(`[credential-mask] Skipping masked file (unreadable on host): ${s.path} \u2014 ${h.message}`);continue}let u=s.injectHosts??t,l=R_+a,f;if(s.extract===void 0&&s.decode===void 0)f=n.register(l,c,u);else{let h=s.extract??Xh,d=0,g=zs(c,h,(x,b)=>{if(s.decode==="jwt"&&!Fs(x))return x;let S=`${l}#${b}`;if(s.decode==="jwt"&&s.maskClaims?.length){let C=Vs(x,s.maskClaims,(I,k)=>n.register(`${l}#jwt${b}.${I}`,k,u));if(C===null)return w(`[credential-mask] ${s.path}: verified JWT candidate has none of maskClaims ${JSON.stringify(s.maskClaims)} as `+"string claims \u2014 left unmasked."),x;let T=s.maskClaims.filter((I)=>!C.claimSentinels.has(I));if(T.length>0)w(`[credential-mask] ${s.path}: maskClaims ${JSON.stringify(T)} absent or non-string in a `+"verified JWT \u2014 skipped.");return d++,n.registerWithSentinel(S,C.fakeToken,x,u)}return d++,s.decode==="jwt"?n.registerWithSentinel(S,Ms(I_()),x,u):n.register(S,x,u)},{maskDuplicates:s.maskDuplicates??!1});if(g===null||d===0){let x=s.decode==="jwt"?s.maskClaims?.length?`decode "jwt" with pattern "${h}" that matched no verified JWT with maskable claims (maskClaims: ${JSON.stringify(s.maskClaims)})`:`decode "jwt" with pattern "${h}" that matched no verified JWT`:`extract pattern "${h}" 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"){w(`[credential-mask] ${s.path} has ${x} \u2014 degrading to `+'mode "deny".',{level:"warn"}),o.push(a);continue}let S=`[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(S),w(S,{level:"warn"});continue}f=g.fakeContent}let p=r.write(l,f);i.push({realPath:a,fakePath:p})}return{binds:i,degradeToDenyPaths:o}}import{randomUUID as B_}from"crypto";var Ws="env:";function e0(e,t,n,r=process.env){let i={},o=[];for(let s of e){if(s.mode!=="mask")continue;let a=r[s.name];if(a===void 0)continue;let c=s.injectHosts??t;if(s.decode==="jwt"){if(!Fs(a)){let l=`[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(l),w(l,{level:"warn"});continue}if(s.maskClaims?.length){let l=Vs(a,s.maskClaims,(p,h)=>n.register(`${Ws}${s.name}#${p}`,h,c,s.injectHeaders));if(l===null){let p=`[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(p),w(p,{level:"warn"});continue}let f=s.maskClaims.filter((p)=>!l.claimSentinels.has(p));if(f.length>0)w(`[credential-mask] env var "${s.name}": maskClaims ${JSON.stringify(f)} absent or non-string in the `+"JWT \u2014 skipped.");i[s.name]=n.registerWithSentinel(`${Ws}${s.name}`,l.fakeToken,a,c,s.injectHeaders);continue}i[s.name]=n.registerWithSentinel(`${Ws}${s.name}`,Ms(B_()),a,c,s.injectHeaders);continue}if(s.extract===void 0){i[s.name]=n.register(s.name,a,c,s.injectHeaders);continue}let u=zs(a,s.extract,(l,f)=>n.register(`${Ws}${s.name}#${f}`,l,c,s.injectHeaders));if(u===null){let l=s.onExtractNoMatch??"warn";if(l==="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(l==="deny"){w(`[credential-mask] extract pattern /${s.extract}/ matched nothing in the value of ${s.name} \u2014 unsetting the variable.`,{level:"warn"}),o.push(s.name);continue}let f=`[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(f),w(f,{level:"warn"});continue}i[s.name]=u.fakeContent}return{setEnvVars:i,degradeToUnsetNames:o}}var t0="AWS_ACCESS_KEY_ID",r0="AWS_SECRET_ACCESS_KEY",n0="AWS_SESSION_TOKEN";class Iu{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 i0(e,t,n,r,i,o=process.env){let s=[...t??[]],a=new Set(s.flatMap((f)=>[f.accessKeyIdVar,f.secretAccessKeyVar,...f.sessionTokenVar?[f.sessionTokenVar]:[]]));if(![t0,r0,n0].some((f)=>a.has(f)))s.push({accessKeyIdVar:t0,secretAccessKeyVar:r0,sessionTokenVar:n0});let u=(f)=>e.find((p)=>p.name===f&&p.mode==="mask"&&p.extract===void 0&&p.decode===void 0),l=(f)=>u(f)!==void 0?r[f]:void 0;for(let f of s){let p=l(f.accessKeyIdVar),h=l(f.secretAccessKeyVar)!==void 0,d=o[f.accessKeyIdVar],g=o[f.secretAccessKeyVar];if(p===void 0||!h||d===void 0||g===void 0){if(h&&p===void 0){let C=`[sandbox-runtime] WARNING: "${f.secretAccessKeyVar}" is masked but "${f.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(C),w(C,{level:"warn"})}continue}let x=u(f.accessKeyIdVar),S=(f.sessionTokenVar!==void 0?l(f.sessionTokenVar):void 0)!==void 0&&f.sessionTokenVar!==void 0?o[f.sessionTokenVar]:void 0;i.register({accessKeyIdSentinel:p,realAccessKeyId:d,realSecretAccessKey:g,...S!==void 0?{realSessionToken:S}:{},injectHosts:x.injectHosts??n}),w(`[credential-aws] registered SigV4 pair for ${f.accessKeyIdVar}/${f.secretAccessKeyVar}`+(S!==void 0?" (+session token)":""))}}function N_(e){return{streaming:e?.streaming??"deny",presigned:e?.presigned??"deny",sigv4a:e?.sigv4a??"deny"}}function o0(e,t,n){let r=N_(t);return(i,o,s,a)=>{if(e.size===0)return;let c=yh(s,o);if(c===null)return;let u=e.lookup(c.accessKeyId);if(u===void 0)return;if(!u.injectHosts.some((d)=>n(a,d)))return;if(c.kind!=="header-sigv4"){if(r[c.kind]==="passthrough"){w(`[credential-aws] ${c.kind} request with masked credential passed through un-resigned per credentials.sigv4.${c.kind} (its signature covers the placeholder secret and will fail upstream)`);return}return{action:"deny",reason:`AWS SigV4 ${c.kind} request uses a masked credential but cannot be re-signed by the sandbox proxy; denied by policy. Set credentials.sigv4.${c.kind} to "passthrough" to forward it unmodified (it will fail upstream: the signature covers the masked placeholder).`}}let l=vh(ri(s.authorization));if(l===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 f=ri(s["x-amz-date"]);if(f===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 p=[...l.signedHeaders];for(let d of p){if(d==="host")continue;if(d==="x-amz-security-token"&&u.realSessionToken!==void 0)continue;if(s[d]===void 0)return{action:"deny",reason:`AWS SigV4 request uses a masked credential but signed header "${d}" is missing; the proxy cannot re-sign it.`}}if(u.realSessionToken!==void 0&&!p.includes("x-amz-security-token"))p.push("x-amz-security-token");let h=ri(s["x-amz-content-sha256"]);return{action:"resign",payloadHash:h===Ds?Ds:void 0,apply(d,g,x){if(u.realSessionToken!==void 0)d["x-amz-security-token"]=u.realSessionToken;if(d["x-amz-content-sha256"]!==void 0&&h!==Ds)d["x-amz-content-sha256"]=x;let{authorization:b}=xh({method:i,requestTarget:o,headers:d,hostHeader:g,signedHeaders:p,payloadHash:x,amzDate:f,scope:{date:l.date,region:l.region,service:l.service},accessKeyId:u.realAccessKeyId,secretAccessKey:u.realSecretAccessKey});d.authorization=b}}}}import{spawnSync as D_}from"child_process";import*as oi from"fs";function Nr(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(!oi.statSync(i).isFile())return!1;return oi.accessSync(i,oi.constants.X_OK),!0}catch{return!1}};if(e.includes("/"))return r(e)?e.trim():null;for(let i of t.split(":")){let o=`${i||"."}/${e}`;if(r(o))return o.trim()}return null}let n=D_("which",[e],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1000});if(n.status===0&&n.stdout)return n.stdout.trim();return null}import*as en from"fs";import{randomBytes as YT}from"crypto";function It(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{createHash as oT,randomBytes as R0}from"crypto";import*as K from"fs";import{spawn as E0}from"child_process";import{tmpdir as Xs}from"os";import ke,{join as _0}from"path";import{spawn as $_}from"child_process";import{text as s0}from"stream/consumers";var O_={ms:1e4};class Hs extends Error{constructor(e){super(`ripgrep timed out after ${e} ms`);this.name="RipgrepTimeoutError"}}async function Pu(e,t,n,r={command:"rg"}){let{command:i,args:o=[],argv0:s}=r,a=$_(i,[...o,...e,t],{argv0:s,env:{PATH:process.env.PATH??"/usr/bin:/bin"},signal:n,windowsHide:!0}),c=O_.ms,u=!1,l=setTimeout(()=>{u=!0,a.kill("SIGKILL")},c),f,p,h;try{[f,p,h]=await Promise.all([s0(a.stdout),s0(a.stderr),new Promise((d,g)=>{a.on("close",d),a.on("error",g)})])}finally{clearTimeout(l)}if(u)throw new Hs(c);if(h===0)return f.trim().split(`
82
- `).filter(Boolean);if(h===1)return[];throw Error(`ripgrep failed with exit code ${h}: ${p}`)}import{join as br,dirname as L_}from"path";import{fileURLToPath as U_}from"url";import*as Ks from"fs";import{homedir as z_}from"os";var Ru=new Map,Bu=null;function F_(){if(Bu)return Bu;let e=[],t=z_();return e.push(br("/usr","lib","node_modules","@anthropic-ai","sandbox-runtime"),br("/usr","local","lib","node_modules","@anthropic-ai","sandbox-runtime"),br("/opt","homebrew","lib","node_modules","@anthropic-ai","sandbox-runtime"),br(t,".npm","lib","node_modules","@anthropic-ai","sandbox-runtime"),br(t,".npm-global","lib","node_modules","@anthropic-ai","sandbox-runtime")),Bu=e,e}function a0(){let e=process.arch;switch(e){case"x64":case"x86_64":return"x64";case"arm64":case"aarch64":return"arm64";case"ia32":case"x86":return w("[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 w(`[SeccompFilter] Unsupported architecture: ${e}. Only x64 and arm64 are supported.`),null}}function M_(e){let t=a0();if(!t)return[];let n=L_(U_(import.meta.url)),r=br("vendor","seccomp",t,e);return[br(n,r),br(n,"..","..",r),br(n,"..",r)]}function Nu(e){let t=e??"";if(Ru.has(t))return Ru.get(t);let n=V_(e);return Ru.set(t,n),n}function V_(e){if(e){if(Ks.existsSync(e))return w(`[SeccompFilter] Using apply-seccomp binary from explicit path: ${e}`),e;w(`[SeccompFilter] Explicit path provided but file not found: ${e}`)}let t=a0();if(!t)return w(`[SeccompFilter] Cannot find apply-seccomp binary: unsupported architecture ${process.arch}`),null;w(`[SeccompFilter] Looking for apply-seccomp binary for architecture: ${t}`);for(let n of M_("apply-seccomp"))if(Ks.existsSync(n))return w(`[SeccompFilter] Found apply-seccomp binary: ${n} (${t})`),n;for(let n of F_()){let r=br(n,"vendor","seccomp",t,"apply-seccomp");if(Ks.existsSync(r))return w(`[SeccompFilter] Found apply-seccomp binary in global install: ${r} (${t})`),r}return w(`[SeccompFilter] apply-seccomp binary not found in any expected location (${t})`),null}import{spawnSync as W_}from"child_process";import{createHash as H_}from"crypto";import*as Q from"fs";import nr from"path";class Ji extends Error{}var K_={dir:"/run/srt-stubs",uid:0,lockWaitMs:2000,flockPath:"/usr/bin/flock"},si=K_,Z_,l0;var Zs=Q.constants.O_CLOEXEC??524288,Du={kind:"masked"},c0={kind:"real"},Xi={kind:"unregistered"},j_=new Set(["ENOENT","EACCES"]),G_=new Set(["ENOENT","ENOTDIR","EROFS"]),Sr=null,Sn=null,q_=0;function Qi(e){return e?.code}function Ou(e){return H_("sha256").update(e).digest("hex")}function Lu(){if(process.platform!=="linux")return"off";let{dir:e,uid:t,flockPath:n}=si;if(process.geteuid?.()!==t)return"off";try{Q.accessSync(n,Q.constants.X_OK)}catch(i){return j_.has(Qi(i)??"")?"off":"error"}try{Q.mkdirSync(e,{mode:448}),Q.chmodSync(e,448)}catch(i){let o=Qi(i)??"";if(o!=="EEXIST")return G_.has(o)?"off":"error"}let r;try{r=Q.lstatSync(e)}catch{return"error"}if(!r.isDirectory()||r.uid!==t||(r.mode&511)!==448)return w(`[Sandbox Linux] ${e} is not a 0700 directory owned by uid ${t}; mask stubs are not shared`,{level:"warn"}),"off";return e}function f0(e,t){try{return Q.openSync(nr.join(e,t),Q.constants.O_RDONLY|Q.constants.O_CREAT|Q.constants.O_NOFOLLOW|Zs,384)}catch{return null}}function d0(e,t){try{return W_(si.flockPath,[...t,"3"],{stdio:["ignore","ignore","ignore",e],timeout:si.lockWaitMs+5000}).status===0}catch{return!1}}function u0(e,t,n){let r=f0(e,t);if(r===null)return null;let i=(si.lockWaitMs/1000).toFixed(3);if(d0(r,[n,"-w",i]))return r;return Q.closeSync(r),null}function p0(e){try{Q.closeSync(e)}catch{}}function h0(){let e=Lu();if(e==="off")return!1;if(e==="error")throw new Ji(`srt: cannot read the mask stub registry ${si.dir}; refusing to start the sandbox`);if(Sr===null)Sr=u0(e,"lock","-s");if(Sr!==null&&Sn===null)Sn=u0(e,"claims","-x");if(Sr===null||Sn===null)throw new Ji(`srt: mask stub registry ${e} is busy (no ${Sr===null?"shared":"claims"} lock within ${si.lockWaitMs} ms); refusing to start the sandbox rather than risk a mask another call removes`);return!0}function js(){if(Sn===null)return;p0(Sn),Sn=null}function X_(){if(Sr===null)return;p0(Sr),Sr=null}function m0(){let e=Lu();if(e==="off")return null;if(e==="error"||Sr===null||Sn===null)throw new Ji("srt: mask stub claimed without holding the registry; refusing to start the sandbox");return e}function Yi(e){try{return Q.lstatSync(e,{bigint:!0})}catch(t){return Qi(t)==="ENOENT"?"absent":"unknown"}}function g0(e){try{let t=JSON.parse(Q.readFileSync(e,"utf8")),{v:n,type:r,uid:i,dev:o,ino:s,ctimeNs:a,path:c}=t,u=(l)=>typeof l==="string"&&/^\d+$/.test(l);if(n!==1||r!=="f"&&r!=="d"||typeof i!=="number"||!u(o)||!u(s)||!u(a)||typeof c!=="string"||!c.startsWith("/"))return null;return{type:r,uid:i,dev:BigInt(o),ino:BigInt(s),ctimeNs:BigInt(a),dest:c}}catch{return null}}function y0(e,t){return nr.join(e,`${Ou(t)}.stub`)}function J_(e,t){let n=Ou(t.dest),r=nr.join(e,`${n}.stub.${process.pid}-${++q_}`),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});Q.writeFileSync(r,i+`
83
- `,{flag:"wx",mode:384}),Q.renameSync(r,nr.join(e,`${n}.stub`))}function v0(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 Uu(e){let t=nr.dirname(e),n;try{n=Q.openSync(t,Q.constants.O_RDONLY|Q.constants.O_DIRECTORY|Q.constants.O_NOFOLLOW|Zs)}catch{return null}try{if(Q.readlinkSync(`/proc/self/fd/${n}`)===t)return n}catch{}return Q.closeSync(n),null}function x0(e,t,n){return{type:e,uid:Number(t.uid),dev:t.dev,ino:t.ino,ctimeNs:t.ctimeNs,dest:n}}function Q_(e){let t=Uu(e);if(t===null)return null;try{let n;try{n=Q.openSync(`/proc/self/fd/${t}/${nr.basename(e)}`,Q.constants.O_RDONLY|Q.constants.O_CREAT|Q.constants.O_EXCL|Q.constants.O_NOFOLLOW|Zs,292)}catch(r){return Qi(r)==="EEXIST"?"exists":null}try{return l0?.(e),x0("f",Q.fstatSync(n,{bigint:!0}),e)}finally{Q.closeSync(n)}}finally{Q.closeSync(t)}}function Y_(e,t){let n=Uu(e);if(n===null)return null;try{let r=`/proc/self/fd/${n}/${nr.basename(e)}`;try{Q.mkdirSync(r,{mode:493})}catch(o){return Qi(o)==="EEXIST"?"exists":null}l0?.(e);let i;try{i=Q.openSync(r,Q.constants.O_RDONLY|Q.constants.O_DIRECTORY|Q.constants.O_NOFOLLOW|Zs)}catch{return null}try{let o=Q.fstatSync(i,{bigint:!0});if(!o.isDirectory()||o.uid!==BigInt(process.geteuid?.()??-1)||o.nlink>BigInt(2)||Q.readdirSync(`/proc/self/fd/${i}`).length!==0)return null;if(t)Q.fchownSync(i,t.uid,t.gid);return x0("d",Q.fstatSync(i,{bigint:!0}),e)}catch{return null}finally{Q.closeSync(i)}}finally{Q.closeSync(n)}}function eT(e){let t=Uu(e.dest);if(t===null)return;try{let n=`/proc/self/fd/${t}/${nr.basename(e.dest)}`,r=Yi(n);if(typeof r==="object"&&v0(r,e)){if(e.type==="d")Q.rmdirSync(n);else Q.unlinkSync(n);w(`[Sandbox Linux] Removed shared mask stub: ${e.dest}`)}}catch{}finally{Q.closeSync(t)}}function tT(e){try{Q.unlinkSync(e)}catch{}}function $u(e,t,n,r){let i=g0(y0(e,t));return i!==null&&i.type===r&&i.dest===t&&v0(n,i)}function b0(e,t,n){let r=m0();if(r===null)return Xi;if(Z_?.(e)==="unregistered")return Xi;let i=Yi(e);if(i==="unknown")return Xi;if(i!=="absent")return $u(r,e,i,t)?Du:c0;let o=n();if(o==="exists"){let s=Yi(e);return typeof s==="object"&&$u(r,e,s,t)?Du:c0}if(o===null)return Xi;try{J_(r,o)}catch(s){w(`[Sandbox Linux] mask stub marker not written for ${e}: ${s}`,{level:"warn"})}return Du}function rT(e){return b0(e,"f",()=>Q_(e))}function nT(e,t){return b0(e,"d",()=>Y_(e,t))}function S0(e,t){let n=m0();if(n===null)return null;let r=(o)=>t.some((s)=>o.startsWith(s+"/")),i=[];for(let o=nr.dirname(e);r(o);o=nr.dirname(o))i.unshift(o);for(let o of i){let s=Yi(o);if(typeof s==="object"&&$u(n,o,s,"d"))return o}return null}function C0(e,t){try{return e()}catch(n){if(n instanceof Ji)throw n;return w(`[Sandbox Linux] mask stub not recorded for ${t}: ${n}`,{level:"warn"}),Xi}}function zu(e){return C0(()=>rT(e),e)}function w0(e,t){return C0(()=>nT(e,t),e)}function iT(e){let t;try{t=Q.readdirSync(e)}catch{return}let n=[],r=[];for(let o of t){let s=/^([0-9a-f]{64})\.stub(\..*)?$/.exec(o);if(s===null)continue;let a=nr.join(e,o);if(r.push(a),s[2]===void 0){let c=g0(a);if(c!==null&&Ou(c.dest)===s[1])n.push(c)}}let i=(o)=>o.dest.split("/").length;n.sort((o,s)=>o.type===s.type?i(s)-i(o):o.type==="f"?-1:1);for(let o of n)eT(o);for(let o of r)tT(o)}function Fu(e,t){let n=Lu(),r=Sr!==null;if(js(),X_(),n==="off"){for(let o of e)t(o);return[]}if(n==="error")return[...e];if(!r&&e.length===0)return[];let i=f0(n,"lock");if(i===null)return[...e];try{if(!d0(i,["-x","-n"]))return[...e];for(let o of e)if(Yi(y0(n,o))==="absent")t(o);return iT(n),[]}catch(o){return w(`[Sandbox Linux] mask stub sweep failed: ${o}`,{level:"warn"}),[...e]}finally{Q.closeSync(i)}}var Wu=3;function sT(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,o])=>`${i}=${o}`),...t]}function Mu(e,t){let n=e.split(ke.sep),r="";for(let i of n){if(!i)continue;let o=r+ke.sep+i;try{if(K.lstatSync(o).isSymbolicLink()){if(t.some((c)=>o.startsWith(c+"/")||o===c))return o}}catch{break}r=o}return null}var aT=40;function T0(e){let t=e;for(let n=0;n<aT;n++){try{return K.realpathSync(t)}catch{}let r=t,i=[],o=null;while(o===null){let c=ke.dirname(r);if(c===r)return null;i.unshift(ke.basename(r)),r=c;try{o=K.realpathSync(r)}catch{}}let s=ke.join(o,i[0]),a=null;try{a=K.readlinkSync(s)}catch{}if(a===null)return ke.join(o,...i);t=ke.join(ke.resolve(ke.dirname(s),a),...i.slice(1))}return null}function cT(e){let t=e.split(ke.sep),n="";for(let r of t){if(!r)continue;let i=n+ke.sep+r;try{let o=K.statSync(i);if(o.isFile()||o.isSymbolicLink())return!0}catch{break}n=i}return!1}function uT(e){let t=e.split(ke.sep),n="";for(let r of t){if(!r)continue;let i=n+ke.sep+r;if(!K.existsSync(i))return i;n=i}return e}async function lT(e={command:"rg"},t=Wu,n=!1,r){let i=process.cwd(),o=new AbortController,s=r??o.signal,a=$o(),c=[...wi.map((d)=>ke.resolve(i,d)),...a.map((d)=>ke.resolve(i,d))],u=ke.resolve(i,".git"),l=!1;try{l=K.statSync(u).isDirectory()}catch{}if(l){if(c.push(ke.resolve(i,".git/hooks")),!n)c.push(ke.resolve(i,".git/config"))}let f=[];for(let d of wi)f.push("--iglob",d);for(let d of a)f.push("--iglob",`**/${d}/**`);if(f.push("--iglob","**/.git/hooks/**"),!n)f.push("--iglob","**/.git/config");let p=["--files","--hidden","--no-ignore","--max-depth",String(t),...f,"-g","!**/node_modules/**"],h;try{h=await Pu(p,i,s,e)}catch(d){if(d instanceof Hs)throw Error(`mandatory deny scan failed: ${d}`);w(`[Sandbox] ripgrep scan failed, retrying once: ${d}`);try{h=await Pu(p,i,s,e)}catch(g){throw Error(`mandatory deny scan failed: ${g}`)}}for(let d of h){let g=ke.resolve(i,d),x=!1;for(let b of[...a,".git"]){let S=qa(b),C=g.split(ke.sep),T=C.findIndex((I)=>qa(I)===S);if(T!==-1){if(b===".git"){let I=C.slice(0,T+1).join(ke.sep);if(d.includes(".git/hooks"))c.push(ke.join(I,"hooks"));else if(d.includes(".git/config"))c.push(ke.join(I,"config"))}else c.push(C.slice(0,T+1).join(ke.sep));x=!0;break}}if(!x)c.push(g)}return[...new Set(c)]}var Js=Xs();function B0(e,t,n,r){let i=process.getuid?.();if(i===void 0)return;let o=(l,f)=>{try{let p=K.lstatSync(l);return(f?p.isDirectory():p.isFile())&&p.uid===i&&(p.mode&18)===0}catch{return!1}};if(!o(e,!0))return;let s=ke.join(e,t),a=ke.join(s,n),c=Buffer.from(r,"utf8");try{K.mkdirSync(s,{mode:493})}catch(l){if(l.code!=="EEXIST")return}if(!o(s,!0))return;try{let l=K.lstatSync(a);if(l.isFile()&&l.uid===i&&(l.mode&146)===0&&l.size===c.length&&(c.length===0||K.readFileSync(a).equals(c)))return a}catch{}let u=`${a}.${process.pid}.${R0(4).toString("hex")}`;try{return K.chmodSync(s,493),K.writeFileSync(u,c,{flag:"wx",mode:292}),K.chmodSync(u,292),K.renameSync(u,a),a}catch{try{K.rmSync(u,{force:!0})}catch{}return}}var eo;function fT(){if(process.getuid?.()!==0||process.env.ARA_SRT_FILE_MASK!=="empty")return"/dev/null";let e=B0(Js,"srt-empty-file","empty","");if(e)return e;if(eo)try{let r=K.lstatSync(eo);if(r.isFile()&&r.size===0&&r.uid===0&&(r.mode&146)===0)return eo}catch{}let t=K.mkdtempSync(ke.join(Js,"claude-empty-file-"));no.add(t),K.chmodSync(t,493);let n=ke.join(t,"empty");return K.writeFileSync(n,"",{flag:"wx",mode:292}),K.chmodSync(n,292),eo=n,n}var to="/etc/ssh/ssh_config";function dT(e){return`# Added by the sandbox: this sandbox reaches the network only through its proxy.
81
+ `)}),c.on("error",()=>u.destroy()),c.once("close",()=>u.destroy()),u.once("close",()=>c.destroy()),c.pipe(u),u.pipe(c)}let a=p_((c)=>{o.add(c),c.once("close",()=>o.delete(c)),c.on("error",(l)=>w(`mux: client socket error: ${l.message}`));let u=setTimeout(()=>{w("mux: first-byte timeout; destroying connection"),c.destroy()},t);if(typeof u.unref==="function")u.unref();c.once("readable",()=>{clearTimeout(u);let l=c.read(1);if(!l||l.length===0){c.destroy();return}if(c.unshift(l),g_.has(l[0]))e.handleSocksConnection(c);else s(c)})});return{server:a,getPort(){let c=a.address();return c&&typeof c==="object"?c.port:void 0},async listenHttpBackend(){if(!n){let u=x_();await jh(u).catch(()=>{}),await new Promise((l,f)=>{e.httpServer.once("error",f),e.httpServer.listen(u,()=>{e.httpServer.removeListener("error",f),l()})}),r=u,w(`mux: HTTP backend listening on ${u}`);return}await Us(e.httpServer,(u)=>e.httpServer.listen(u,"127.0.0.1"),e.httpBackendPortRange,new Set);let c=e.httpServer.address();return i=c&&typeof c==="object"?c.port:void 0,w(`mux: HTTP backend listening on 127.0.0.1:${i}`),i},async close(){for(let c of o)c.destroy();if(o.clear(),await new Promise((c)=>a.close(()=>c())),await new Promise((c)=>e.httpServer.close(()=>c())),r)await jh(r).catch(()=>{}),r=void 0;i=void 0},unref(){a.unref(),e.httpServer.unref()}}}import{randomInt as b_,randomUUID as S_}from"crypto";var si="fake_value_",qh="abcdefghijklmnopqrstuvwxyz0123456789_-";function C_(e){let t=si+S_(),n=Buffer.byteLength(e)-t.length;if(n<=0)return t;let r=t;for(let i=0;i<n;i++)r+=qh[b_(qh.length)];return r}class _u{byName=new Map;bySentinel=new Map;allSentinelsPrefixed=!0;refs=new Map;lease=null;register(e,t,n,r){return this.registerWithSentinel(e,C_(t),t,n,r)}registerWithSentinel(e,t,n,r,i){let o=this.byName.get(e);if(o!==void 0&&o.realValue===n)return o.injectHosts=r,o.injectHeaders=i,this.lease?.add(o),o.sentinel;if(this.bySentinel.has(t))throw Error("credential sentinel collision");if(!t.startsWith(si))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(si));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 o=0;o<i.length;o++)i[o]=this.substituteInHeaderValue(r,i[o],t,n);else e[r]=this.substituteInHeaderValue(r,i,t,n)}}substituteInHeaderValue(e,t,n,r){let i=e.toLowerCase(),o=this.substituteInString(t,n,r,i);if(i!=="authorization")return o;let s=/^(\s*basic\s+)([a-z0-9+/]+={0,2})(\s*)$/i.exec(o);if(s===null)return o;let a=s[2],c=Buffer.from(a,"base64");if(a.length%4!==0||c.toString("base64")!==a)return o;let u=c.toString("utf8");if(!Buffer.from(u,"utf8").equals(c))return o;let l=this.substituteInString(u,n,r,i);if(l===u)return o;return`${s[1]}${Buffer.from(l,"utf8").toString("base64")}${s[3]}`}substituteInString(e,t,n,r){if(this.allSentinelsPrefixed&&!e.includes(si))return e;let i=e;for(let o of this.bySentinel.values()){if(!i.includes(o.sentinel))continue;if(!o.injectHosts.some((s)=>n(t,s)))continue;if(o.injectHeaders!==void 0&&!o.injectHeaders.includes(r))continue;i=i.split(o.sentinel).join(o.realValue)}return i}}import{randomUUID as P_}from"crypto";import*as rr from"fs";import{tmpdir as R_}from"os";import{join as Yh}from"path";function w_(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 E_(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 Xh(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 __(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 T_(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 o=Number(e.slice(i,r)),s=o,a=!1;if(e[r]===","){r++;let c=r;while(/[0-9]/.test(e[r]??""))r++;if(r===c)a=!0,s=void 0;else s=Number(e.slice(c,r))}if(e[r]!=="}")return null;if(!Number.isFinite(o)||o>4096||s!==void 0&&(!Number.isFinite(s)||s>4096))return{next:r+1,unbounded:a,error:"finite repetitions must be at most 4096"};if(r++,e[r]==="?")r++;return{next:r,unbounded:a}}function A_(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=(o)=>{let s=r();if(s.lastAtom?.hasUnboundedQuantifier&&o.hasUnboundedQuantifier&&s.lastAtom.repeatClass!==null&&o.repeatClass!==null&&Xh(s.lastAtom.repeatClass,o.repeatClass))s.error="adjacent unbounded repetition with overlapping input is not supported";if(s.previousAtom=s.lastAtom,s.lastAtom=o,s.atomCount===0)s.simpleClass=o.repeatClass;else s.simpleClass=null;if(s.atomCount++,o.kind==="group")s.containsQuantifier||=o.containsQuantifier,s.containsAlternation||=o.containsAlternation;s.hasUnboundedQuantifier||=o.hasUnboundedQuantifier};for(let o=0;o<e.length;){if(r().error!==void 0)return{groupCount:n,error:r().error};let s=e[o];if(s==="\\"){let c=e[o+1];if(c!==void 0&&/[1-9]/.test(c)||c==="k"&&e[o+2]==="<")return{groupCount:n,error:"backreferences are not supported by the safe extractor"};let u=c==="b"||c==="B";if(i({kind:"token",containsQuantifier:!1,containsAlternation:!1,hasUnboundedQuantifier:!1,repeatClass:E_(c)}),o+=c===void 0?1:2,u)r().previousAtom=null,r().lastAtom=null;continue}if(s==="["){i({kind:"token",containsQuantifier:!1,containsAlternation:!1,hasUnboundedQuantifier:!1,repeatClass:{kind:"unknown"}}),o=w_(e,o);continue}if(s==="("){let c=__(e,o);if(c.capturing)n++;t.push({previousAtom:null,lastAtom:null,atomCount:0,simpleClass:null,containsQuantifier:!1,containsAlternation:!1,hasUnboundedQuantifier:!1}),o=c.next;continue}if(s===")"){if(t.length>1){let c=t.pop();if(c.error!==void 0)return{groupCount:n,error:c.error};i({kind:"group",containsQuantifier:c.containsQuantifier,containsAlternation:c.containsAlternation,hasUnboundedQuantifier:c.hasUnboundedQuantifier,repeatClass:c.atomCount===1&&!c.containsAlternation?c.simpleClass:null})}o++;continue}if(s==="|"){r().containsAlternation=!0,r().previousAtom=null,r().lastAtom=null,o++;continue}let a=T_(e,o);if(a!==null){if(a.error)return{groupCount:n,error:a.error};let c=r(),u=c.lastAtom;if(a.unbounded&&u?.kind==="group"&&(u.containsQuantifier||u.containsAlternation))return{groupCount:n,error:"nested unbounded repetition or unbounded alternation is not supported"};if(a.unbounded&&c.previousAtom?.hasUnboundedQuantifier&&u!==null&&c.previousAtom.repeatClass!==null&&u.repeatClass!==null&&Xh(c.previousAtom.repeatClass,u.repeatClass))return{groupCount:n,error:"adjacent unbounded repetition with overlapping input is not supported"};if(c.containsQuantifier=!0,u!==null)c.lastAtom={...u,containsQuantifier:!0,hasUnboundedQuantifier:u.hasUnboundedQuantifier||a.unbounded};c.hasUnboundedQuantifier||=a.unbounded,o=a.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;o++}return{groupCount:n,error:r().error}}function Tu(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=A_(e);if(n.error!==void 0)throw Error(`Credential extract pattern rejected: ${n.error}`);return{regex:t,groupCount:n.groupCount}}function k_(e,t=""){Tu(e);try{return new RegExp(e,t)}catch{throw Error("Credential extract pattern is not supported by this runtime")}}function zs(e,t,n,r={}){if(e.length>1048576)throw Error("Credential extraction input exceeds the 1048576-character limit");let i=k_(t,"gd"),o=new Map,s=new Map,a=[],c=0;for(let f of e.matchAll(i)){if(c++,c>4096)throw Error("Credential extraction exceeds the 4096-match limit");let p=f[1];if(p===void 0)throw Error(`Credential extraction matched at offset ${f.index} without a group-1 capture; group 1 must capture the credential value on every match.`);if(p.length===0)continue;let h=o.get(p);if(h===void 0)o.set(p,h=o.size);let[d,g]=f.indices[1],v=n(p,h);if(!s.has(p))s.set(p,v);a.push({start:d,end:g,sentinel:v})}if(o.size===0)return null;if(r.maskDuplicates){let f=[...o.keys()].sort((p,h)=>h.length-p.length);for(let p of f){let h=s.get(p);if(h===p)continue;for(let d=e.indexOf(p);d!==-1;d=e.indexOf(p,d+1)){let g=d+p.length;if(a.some((v)=>d<v.end&&v.start<g))continue;a.push({start:d,end:g,sentinel:h})}}a.sort((p,h)=>p.start-h.start)}let u="",l=0;for(let f of a)u+=e.slice(l,f.start)+f.sentinel,l=f.end;return{fakeContent:u+e.slice(l),captures:[...o.keys()]}}var Jh="(eyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+)";function Au(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=Au(t[0]);if(typeof n!=="object"||n===null||!("alg"in n))return!1;return Au(t[1])!==void 0}var I_=9999999999,Qh="c3J0LWZha2U";function ku(e){return Buffer.from(e,"utf8").toString("base64url")}function Ms(e){let t=ku(JSON.stringify({alg:"HS256",typ:"JWT"})),n=ku(JSON.stringify({sub:si+e,exp:I_}));return`${t}.${n}.${Qh}`}function Vs(e,t,n){let[r,i]=e.split("."),o=Au(i??"");if(typeof o!=="object"||o===null||Array.isArray(o))return null;let s=o,a=[];for(let u of t){let l=s[u];if(typeof l==="string")a.push([u,l])}if(a.length===0)return null;let c=new Map;for(let[u,l]of a){let f=n(u,l);s[u]=f,c.set(u,f)}return{fakeToken:`${r}.${ku(JSON.stringify(s))}.${Qh}`,claimSentinels:c}}var B_="file:";class Iu{dir;byKey=new Map;write(e,t){if(this.dir===void 0)this.dir=rr.mkdtempSync(Yh(R_(),"srt-credmask-"));let n=this.byKey.get(e);if(n===void 0)n=Yh(this.dir,`${this.byKey.size}.fake`),this.byKey.set(e,n);return rr.rmSync(n,{force:!0}),rr.writeFileSync(n,t,{mode:384}),n}dispose(){if(this.dir!==void 0)try{rr.rmSync(this.dir,{recursive:!0,force:!0})}catch(e){w(`MaskedFileStore cleanup failed: ${e}`,{level:"error"})}this.dir=void 0,this.byKey.clear()}get dirPath(){return this.dir}}function e0(e,t,n,r){let i=[],o=[];for(let s of e){if(s.mode!=="mask")continue;let a=Ye(s.path),c;try{if(rr.statSync(a).isDirectory()){w(`[credential-mask] Skipping masked file entry that resolves to a directory: ${s.path} \u2014 use mode "deny" for directories.`,{level:"warn"});continue}let d=rr.readFileSync(a);if(c=d.toString("utf8"),Buffer.byteLength(c,"utf8")!==d.length){w(`[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(h){w(`[credential-mask] Skipping masked file (unreadable on host): ${s.path} \u2014 ${h.message}`);continue}let u=s.injectHosts??t,l=B_+a,f;if(s.extract===void 0&&s.decode===void 0)f=n.register(l,c,u);else{let h=s.extract??Jh,d=0,g=zs(c,h,(v,b)=>{if(s.decode==="jwt"&&!Fs(v))return v;let S=`${l}#${b}`;if(s.decode==="jwt"&&s.maskClaims?.length){let C=Vs(v,s.maskClaims,(I,k)=>n.register(`${l}#jwt${b}.${I}`,k,u));if(C===null)return w(`[credential-mask] ${s.path}: verified JWT candidate has none of maskClaims ${JSON.stringify(s.maskClaims)} as `+"string claims \u2014 left unmasked."),v;let T=s.maskClaims.filter((I)=>!C.claimSentinels.has(I));if(T.length>0)w(`[credential-mask] ${s.path}: maskClaims ${JSON.stringify(T)} absent or non-string in a `+"verified JWT \u2014 skipped.");return d++,n.registerWithSentinel(S,C.fakeToken,v,u)}return d++,s.decode==="jwt"?n.registerWithSentinel(S,Ms(P_()),v,u):n.register(S,v,u)},{maskDuplicates:s.maskDuplicates??!1});if(g===null||d===0){let v=s.decode==="jwt"?s.maskClaims?.length?`decode "jwt" with pattern "${h}" that matched no verified JWT with maskable claims (maskClaims: ${JSON.stringify(s.maskClaims)})`:`decode "jwt" with pattern "${h}" that matched no verified JWT`:`extract pattern "${h}" that matched nothing`,b=s.onExtractNoMatch??"warn";if(b==="error")throw Error(`credentials.files entry "${s.path}": ${v} (onExtractNoMatch: "error"). Fix the config, change to "warn"/"deny", or remove the entry.`);if(b==="deny"){w(`[credential-mask] ${s.path} has ${v} \u2014 degrading to `+'mode "deny".',{level:"warn"}),o.push(a);continue}let S=`[sandbox-runtime] WARNING: credentials.files entry "${s.path}" has ${v} 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),w(S,{level:"warn"});continue}f=g.fakeContent}let p=r.write(l,f);i.push({realPath:a,fakePath:p})}return{binds:i,degradeToDenyPaths:o}}import{randomUUID as N_}from"crypto";var Ws="env:";function t0(e,t,n,r=process.env){let i={},o=[];for(let s of e){if(s.mode!=="mask")continue;let a=r[s.name];if(a===void 0)continue;let c=s.injectHosts??t;if(s.decode==="jwt"){if(!Fs(a)){let l=`[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(l),w(l,{level:"warn"});continue}if(s.maskClaims?.length){let l=Vs(a,s.maskClaims,(p,h)=>n.register(`${Ws}${s.name}#${p}`,h,c,s.injectHeaders));if(l===null){let p=`[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(p),w(p,{level:"warn"});continue}let f=s.maskClaims.filter((p)=>!l.claimSentinels.has(p));if(f.length>0)w(`[credential-mask] env var "${s.name}": maskClaims ${JSON.stringify(f)} absent or non-string in the `+"JWT \u2014 skipped.");i[s.name]=n.registerWithSentinel(`${Ws}${s.name}`,l.fakeToken,a,c,s.injectHeaders);continue}i[s.name]=n.registerWithSentinel(`${Ws}${s.name}`,Ms(N_()),a,c,s.injectHeaders);continue}if(s.extract===void 0){i[s.name]=n.register(s.name,a,c,s.injectHeaders);continue}let u=zs(a,s.extract,(l,f)=>n.register(`${Ws}${s.name}#${f}`,l,c,s.injectHeaders));if(u===null){let l=s.onExtractNoMatch??"warn";if(l==="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(l==="deny"){w(`[credential-mask] extract pattern /${s.extract}/ matched nothing in the value of ${s.name} \u2014 unsetting the variable.`,{level:"warn"}),o.push(s.name);continue}let f=`[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(f),w(f,{level:"warn"});continue}i[s.name]=u.fakeContent}return{setEnvVars:i,degradeToUnsetNames:o}}var r0="AWS_ACCESS_KEY_ID",n0="AWS_SECRET_ACCESS_KEY",i0="AWS_SESSION_TOKEN";class Pu{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 o0(e,t,n,r,i,o=process.env){let s=[...t??[]],a=new Set(s.flatMap((f)=>[f.accessKeyIdVar,f.secretAccessKeyVar,...f.sessionTokenVar?[f.sessionTokenVar]:[]]));if(![r0,n0,i0].some((f)=>a.has(f)))s.push({accessKeyIdVar:r0,secretAccessKeyVar:n0,sessionTokenVar:i0});let u=(f)=>e.find((p)=>p.name===f&&p.mode==="mask"&&p.extract===void 0&&p.decode===void 0),l=(f)=>u(f)!==void 0?r[f]:void 0;for(let f of s){let p=l(f.accessKeyIdVar),h=l(f.secretAccessKeyVar)!==void 0,d=o[f.accessKeyIdVar],g=o[f.secretAccessKeyVar];if(p===void 0||!h||d===void 0||g===void 0){if(h&&p===void 0){let C=`[sandbox-runtime] WARNING: "${f.secretAccessKeyVar}" is masked but "${f.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(C),w(C,{level:"warn"})}continue}let v=u(f.accessKeyIdVar),S=(f.sessionTokenVar!==void 0?l(f.sessionTokenVar):void 0)!==void 0&&f.sessionTokenVar!==void 0?o[f.sessionTokenVar]:void 0;i.register({accessKeyIdSentinel:p,realAccessKeyId:d,realSecretAccessKey:g,...S!==void 0?{realSessionToken:S}:{},injectHosts:v.injectHosts??n}),w(`[credential-aws] registered SigV4 pair for ${f.accessKeyIdVar}/${f.secretAccessKeyVar}`+(S!==void 0?" (+session token)":""))}}function D_(e){return{streaming:e?.streaming??"deny",presigned:e?.presigned??"deny",sigv4a:e?.sigv4a??"deny"}}function s0(e,t,n){let r=D_(t);return(i,o,s,a)=>{if(e.size===0)return;let c=vh(s,o);if(c===null)return;let u=e.lookup(c.accessKeyId);if(u===void 0)return;if(!u.injectHosts.some((d)=>n(a,d)))return;if(c.kind!=="header-sigv4"){if(r[c.kind]==="passthrough"){w(`[credential-aws] ${c.kind} request with masked credential passed through un-resigned per credentials.sigv4.${c.kind} (its signature covers the placeholder secret and will fail upstream)`);return}return{action:"deny",reason:`AWS SigV4 ${c.kind} request uses a masked credential but cannot be re-signed by the sandbox proxy; denied by policy. Set credentials.sigv4.${c.kind} to "passthrough" to forward it unmodified (it will fail upstream: the signature covers the masked placeholder).`}}let l=xh(ii(s.authorization));if(l===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 f=ii(s["x-amz-date"]);if(f===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 p=[...l.signedHeaders];for(let d of p){if(d==="host")continue;if(d==="x-amz-security-token"&&u.realSessionToken!==void 0)continue;if(s[d]===void 0)return{action:"deny",reason:`AWS SigV4 request uses a masked credential but signed header "${d}" is missing; the proxy cannot re-sign it.`}}if(u.realSessionToken!==void 0&&!p.includes("x-amz-security-token"))p.push("x-amz-security-token");let h=ii(s["x-amz-content-sha256"]);return{action:"resign",payloadHash:h===Ds?Ds:void 0,apply(d,g,v){if(u.realSessionToken!==void 0)d["x-amz-security-token"]=u.realSessionToken;if(d["x-amz-content-sha256"]!==void 0&&h!==Ds)d["x-amz-content-sha256"]=v;let{authorization:b}=bh({method:i,requestTarget:o,headers:d,hostHeader:g,signedHeaders:p,payloadHash:v,amzDate:f,scope:{date:l.date,region:l.region,service:l.service},accessKeyId:u.realAccessKeyId,secretAccessKey:u.realSecretAccessKey});d.authorization=b}}}}import{spawnSync as $_}from"child_process";import*as ai from"fs";function Nr(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(!ai.statSync(i).isFile())return!1;return ai.accessSync(i,ai.constants.X_OK),!0}catch{return!1}};if(e.includes("/"))return r(e)?e.trim():null;for(let i of t.split(":")){let o=`${i||"."}/${e}`;if(r(o))return o.trim()}return null}let n=$_("which",[e],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1000});if(n.status===0&&n.stdout)return n.stdout.trim();return null}import*as en from"fs";import{randomBytes as eA}from"crypto";function It(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{createHash as sT,randomBytes as B0}from"crypto";import*as K from"fs";import{spawn as _0}from"child_process";import{tmpdir as Xs}from"os";import ke,{join as T0}from"path";import{spawn as O_}from"child_process";import{text as a0}from"stream/consumers";var L_={ms:1e4};class Hs extends Error{constructor(e){super(`ripgrep timed out after ${e} ms`);this.name="RipgrepTimeoutError"}}async function Ru(e,t,n,r={command:"rg"}){let{command:i,args:o=[],argv0:s}=r,a=O_(i,[...o,...e,t],{argv0:s,env:{PATH:process.env.PATH??"/usr/bin:/bin"},signal:n,windowsHide:!0}),c=L_.ms,u=!1,l=setTimeout(()=>{u=!0,a.kill("SIGKILL")},c),f,p,h;try{[f,p,h]=await Promise.all([a0(a.stdout),a0(a.stderr),new Promise((d,g)=>{a.on("close",d),a.on("error",g)})])}finally{clearTimeout(l)}if(u)throw new Hs(c);if(h===0)return f.trim().split(`
82
+ `).filter(Boolean);if(h===1)return[];throw Error(`ripgrep failed with exit code ${h}: ${p}`)}import{join as br,dirname as U_}from"path";import{fileURLToPath as z_}from"url";import*as Ks from"fs";import{homedir as F_}from"os";var Bu=new Map,Nu=null;function M_(){if(Nu)return Nu;let e=[],t=F_();return e.push(br("/usr","lib","node_modules","@anthropic-ai","sandbox-runtime"),br("/usr","local","lib","node_modules","@anthropic-ai","sandbox-runtime"),br("/opt","homebrew","lib","node_modules","@anthropic-ai","sandbox-runtime"),br(t,".npm","lib","node_modules","@anthropic-ai","sandbox-runtime"),br(t,".npm-global","lib","node_modules","@anthropic-ai","sandbox-runtime")),Nu=e,e}function c0(){let e=process.arch;switch(e){case"x64":case"x86_64":return"x64";case"arm64":case"aarch64":return"arm64";case"ia32":case"x86":return w("[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 w(`[SeccompFilter] Unsupported architecture: ${e}. Only x64 and arm64 are supported.`),null}}function V_(e){let t=c0();if(!t)return[];let n=U_(z_(import.meta.url)),r=br("vendor","seccomp",t,e);return[br(n,r),br(n,"..","..",r),br(n,"..",r)]}function Du(e){let t=e??"";if(Bu.has(t))return Bu.get(t);let n=W_(e);return Bu.set(t,n),n}function W_(e){if(e){if(Ks.existsSync(e))return w(`[SeccompFilter] Using apply-seccomp binary from explicit path: ${e}`),e;w(`[SeccompFilter] Explicit path provided but file not found: ${e}`)}let t=c0();if(!t)return w(`[SeccompFilter] Cannot find apply-seccomp binary: unsupported architecture ${process.arch}`),null;w(`[SeccompFilter] Looking for apply-seccomp binary for architecture: ${t}`);for(let n of V_("apply-seccomp"))if(Ks.existsSync(n))return w(`[SeccompFilter] Found apply-seccomp binary: ${n} (${t})`),n;for(let n of M_()){let r=br(n,"vendor","seccomp",t,"apply-seccomp");if(Ks.existsSync(r))return w(`[SeccompFilter] Found apply-seccomp binary in global install: ${r} (${t})`),r}return w(`[SeccompFilter] apply-seccomp binary not found in any expected location (${t})`),null}import{spawnSync as H_}from"child_process";import{createHash as K_}from"crypto";import*as Q from"fs";import nr from"path";class Qi extends Error{}var Z_={dir:"/run/srt-stubs",uid:0,lockWaitMs:2000,flockPath:"/usr/bin/flock"},ci=Z_,j_,f0;var Zs=Q.constants.O_CLOEXEC??524288,$u={kind:"masked"},u0={kind:"real"},Ji={kind:"unregistered"},G_=new Set(["ENOENT","EACCES"]),q_=new Set(["ENOENT","ENOTDIR","EROFS"]),Sr=null,Sn=null,X_=0;function Yi(e){return e?.code}function Lu(e){return K_("sha256").update(e).digest("hex")}function Uu(){if(process.platform!=="linux")return"off";let{dir:e,uid:t,flockPath:n}=ci;if(process.geteuid?.()!==t)return"off";try{Q.accessSync(n,Q.constants.X_OK)}catch(i){return G_.has(Yi(i)??"")?"off":"error"}try{Q.mkdirSync(e,{mode:448}),Q.chmodSync(e,448)}catch(i){let o=Yi(i)??"";if(o!=="EEXIST")return q_.has(o)?"off":"error"}let r;try{r=Q.lstatSync(e)}catch{return"error"}if(!r.isDirectory()||r.uid!==t||(r.mode&511)!==448)return w(`[Sandbox Linux] ${e} is not a 0700 directory owned by uid ${t}; mask stubs are not shared`,{level:"warn"}),"off";return e}function d0(e,t){try{return Q.openSync(nr.join(e,t),Q.constants.O_RDONLY|Q.constants.O_CREAT|Q.constants.O_NOFOLLOW|Zs,384)}catch{return null}}function p0(e,t){try{return H_(ci.flockPath,[...t,"3"],{stdio:["ignore","ignore","ignore",e],timeout:ci.lockWaitMs+5000}).status===0}catch{return!1}}function l0(e,t,n){let r=d0(e,t);if(r===null)return null;let i=(ci.lockWaitMs/1000).toFixed(3);if(p0(r,[n,"-w",i]))return r;return Q.closeSync(r),null}function h0(e){try{Q.closeSync(e)}catch{}}function m0(){let e=Uu();if(e==="off")return!1;if(e==="error")throw new Qi(`srt: cannot read the mask stub registry ${ci.dir}; refusing to start the sandbox`);if(Sr===null)Sr=l0(e,"lock","-s");if(Sr!==null&&Sn===null)Sn=l0(e,"claims","-x");if(Sr===null||Sn===null)throw new Qi(`srt: mask stub registry ${e} is busy (no ${Sr===null?"shared":"claims"} lock within ${ci.lockWaitMs} ms); refusing to start the sandbox rather than risk a mask another call removes`);return!0}function js(){if(Sn===null)return;h0(Sn),Sn=null}function J_(){if(Sr===null)return;h0(Sr),Sr=null}function g0(){let e=Uu();if(e==="off")return null;if(e==="error"||Sr===null||Sn===null)throw new Qi("srt: mask stub claimed without holding the registry; refusing to start the sandbox");return e}function eo(e){try{return Q.lstatSync(e,{bigint:!0})}catch(t){return Yi(t)==="ENOENT"?"absent":"unknown"}}function y0(e){try{let t=JSON.parse(Q.readFileSync(e,"utf8")),{v:n,type:r,uid:i,dev:o,ino:s,ctimeNs:a,path:c}=t,u=(l)=>typeof l==="string"&&/^\d+$/.test(l);if(n!==1||r!=="f"&&r!=="d"||typeof i!=="number"||!u(o)||!u(s)||!u(a)||typeof c!=="string"||!c.startsWith("/"))return null;return{type:r,uid:i,dev:BigInt(o),ino:BigInt(s),ctimeNs:BigInt(a),dest:c}}catch{return null}}function v0(e,t){return nr.join(e,`${Lu(t)}.stub`)}function Q_(e,t){let n=Lu(t.dest),r=nr.join(e,`${n}.stub.${process.pid}-${++X_}`),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});Q.writeFileSync(r,i+`
83
+ `,{flag:"wx",mode:384}),Q.renameSync(r,nr.join(e,`${n}.stub`))}function x0(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 zu(e){let t=nr.dirname(e),n;try{n=Q.openSync(t,Q.constants.O_RDONLY|Q.constants.O_DIRECTORY|Q.constants.O_NOFOLLOW|Zs)}catch{return null}try{if(Q.readlinkSync(`/proc/self/fd/${n}`)===t)return n}catch{}return Q.closeSync(n),null}function b0(e,t,n){return{type:e,uid:Number(t.uid),dev:t.dev,ino:t.ino,ctimeNs:t.ctimeNs,dest:n}}function Y_(e){let t=zu(e);if(t===null)return null;try{let n;try{n=Q.openSync(`/proc/self/fd/${t}/${nr.basename(e)}`,Q.constants.O_RDONLY|Q.constants.O_CREAT|Q.constants.O_EXCL|Q.constants.O_NOFOLLOW|Zs,292)}catch(r){return Yi(r)==="EEXIST"?"exists":null}try{return f0?.(e),b0("f",Q.fstatSync(n,{bigint:!0}),e)}finally{Q.closeSync(n)}}finally{Q.closeSync(t)}}function eT(e,t){let n=zu(e);if(n===null)return null;try{let r=`/proc/self/fd/${n}/${nr.basename(e)}`;try{Q.mkdirSync(r,{mode:493})}catch(o){return Yi(o)==="EEXIST"?"exists":null}f0?.(e);let i;try{i=Q.openSync(r,Q.constants.O_RDONLY|Q.constants.O_DIRECTORY|Q.constants.O_NOFOLLOW|Zs)}catch{return null}try{let o=Q.fstatSync(i,{bigint:!0});if(!o.isDirectory()||o.uid!==BigInt(process.geteuid?.()??-1)||o.nlink>BigInt(2)||Q.readdirSync(`/proc/self/fd/${i}`).length!==0)return null;if(t)Q.fchownSync(i,t.uid,t.gid);return b0("d",Q.fstatSync(i,{bigint:!0}),e)}catch{return null}finally{Q.closeSync(i)}}finally{Q.closeSync(n)}}function tT(e){let t=zu(e.dest);if(t===null)return;try{let n=`/proc/self/fd/${t}/${nr.basename(e.dest)}`,r=eo(n);if(typeof r==="object"&&x0(r,e)){if(e.type==="d")Q.rmdirSync(n);else Q.unlinkSync(n);w(`[Sandbox Linux] Removed shared mask stub: ${e.dest}`)}}catch{}finally{Q.closeSync(t)}}function rT(e){try{Q.unlinkSync(e)}catch{}}function Ou(e,t,n,r){let i=y0(v0(e,t));return i!==null&&i.type===r&&i.dest===t&&x0(n,i)}function S0(e,t,n){let r=g0();if(r===null)return Ji;if(j_?.(e)==="unregistered")return Ji;let i=eo(e);if(i==="unknown")return Ji;if(i!=="absent")return Ou(r,e,i,t)?$u:u0;let o=n();if(o==="exists"){let s=eo(e);return typeof s==="object"&&Ou(r,e,s,t)?$u:u0}if(o===null)return Ji;try{Q_(r,o)}catch(s){w(`[Sandbox Linux] mask stub marker not written for ${e}: ${s}`,{level:"warn"})}return $u}function nT(e){return S0(e,"f",()=>Y_(e))}function iT(e,t){return S0(e,"d",()=>eT(e,t))}function C0(e,t){let n=g0();if(n===null)return null;let r=(o)=>t.some((s)=>o.startsWith(s+"/")),i=[];for(let o=nr.dirname(e);r(o);o=nr.dirname(o))i.unshift(o);for(let o of i){let s=eo(o);if(typeof s==="object"&&Ou(n,o,s,"d"))return o}return null}function w0(e,t){try{return e()}catch(n){if(n instanceof Qi)throw n;return w(`[Sandbox Linux] mask stub not recorded for ${t}: ${n}`,{level:"warn"}),Ji}}function Fu(e){return w0(()=>nT(e),e)}function E0(e,t){return w0(()=>iT(e,t),e)}function oT(e){let t;try{t=Q.readdirSync(e)}catch{return}let n=[],r=[];for(let o of t){let s=/^([0-9a-f]{64})\.stub(\..*)?$/.exec(o);if(s===null)continue;let a=nr.join(e,o);if(r.push(a),s[2]===void 0){let c=y0(a);if(c!==null&&Lu(c.dest)===s[1])n.push(c)}}let i=(o)=>o.dest.split("/").length;n.sort((o,s)=>o.type===s.type?i(s)-i(o):o.type==="f"?-1:1);for(let o of n)tT(o);for(let o of r)rT(o)}function Mu(e,t){let n=Uu(),r=Sr!==null;if(js(),J_(),n==="off"){for(let o of e)t(o);return[]}if(n==="error")return[...e];if(!r&&e.length===0)return[];let i=d0(n,"lock");if(i===null)return[...e];try{if(!p0(i,["-x","-n"]))return[...e];for(let o of e)if(eo(v0(n,o))==="absent")t(o);return oT(n),[]}catch(o){return w(`[Sandbox Linux] mask stub sweep failed: ${o}`,{level:"warn"}),[...e]}finally{Q.closeSync(i)}}var Hu=3;function aT(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,o])=>`${i}=${o}`),...t]}function Vu(e,t){let n=e.split(ke.sep),r="";for(let i of n){if(!i)continue;let o=r+ke.sep+i;try{if(K.lstatSync(o).isSymbolicLink()){if(t.some((c)=>o.startsWith(c+"/")||o===c))return o}}catch{break}r=o}return null}var cT=40;function A0(e){let t=e;for(let n=0;n<cT;n++){try{return K.realpathSync(t)}catch{}let r=t,i=[],o=null;while(o===null){let c=ke.dirname(r);if(c===r)return null;i.unshift(ke.basename(r)),r=c;try{o=K.realpathSync(r)}catch{}}let s=ke.join(o,i[0]),a=null;try{a=K.readlinkSync(s)}catch{}if(a===null)return ke.join(o,...i);t=ke.join(ke.resolve(ke.dirname(s),a),...i.slice(1))}return null}function uT(e){let t=e.split(ke.sep),n="";for(let r of t){if(!r)continue;let i=n+ke.sep+r;try{let o=K.statSync(i);if(o.isFile()||o.isSymbolicLink())return!0}catch{break}n=i}return!1}function lT(e){let t=e.split(ke.sep),n="";for(let r of t){if(!r)continue;let i=n+ke.sep+r;if(!K.existsSync(i))return i;n=i}return e}async function fT(e={command:"rg"},t=Hu,n=!1,r){let i=process.cwd(),o=new AbortController,s=r??o.signal,a=$o(),c=[..._i.map((d)=>ke.resolve(i,d)),...a.map((d)=>ke.resolve(i,d))],u=ke.resolve(i,".git"),l=!1;try{l=K.statSync(u).isDirectory()}catch{}if(l){if(c.push(ke.resolve(i,".git/hooks")),!n)c.push(ke.resolve(i,".git/config"))}let f=[];for(let d of _i)f.push("--iglob",d);for(let d of a)f.push("--iglob",`**/${d}/**`);if(f.push("--iglob","**/.git/hooks/**"),!n)f.push("--iglob","**/.git/config");let p=["--files","--hidden","--no-ignore","--max-depth",String(t),...f,"-g","!**/node_modules/**"],h;try{h=await Ru(p,i,s,e)}catch(d){if(d instanceof Hs)throw Error(`mandatory deny scan failed: ${d}`);w(`[Sandbox] ripgrep scan failed, retrying once: ${d}`);try{h=await Ru(p,i,s,e)}catch(g){throw Error(`mandatory deny scan failed: ${g}`)}}for(let d of h){let g=ke.resolve(i,d),v=!1;for(let b of[...a,".git"]){let S=qa(b),C=g.split(ke.sep),T=C.findIndex((I)=>qa(I)===S);if(T!==-1){if(b===".git"){let I=C.slice(0,T+1).join(ke.sep);if(d.includes(".git/hooks"))c.push(ke.join(I,"hooks"));else if(d.includes(".git/config"))c.push(ke.join(I,"config"))}else c.push(C.slice(0,T+1).join(ke.sep));v=!0;break}}if(!v)c.push(g)}return[...new Set(c)]}var Js=Xs();function N0(e,t,n,r){let i=process.getuid?.();if(i===void 0)return;let o=(l,f)=>{try{let p=K.lstatSync(l);return(f?p.isDirectory():p.isFile())&&p.uid===i&&(p.mode&18)===0}catch{return!1}};if(!o(e,!0))return;let s=ke.join(e,t),a=ke.join(s,n),c=Buffer.from(r,"utf8");try{K.mkdirSync(s,{mode:493})}catch(l){if(l.code!=="EEXIST")return}if(!o(s,!0))return;try{let l=K.lstatSync(a);if(l.isFile()&&l.uid===i&&(l.mode&146)===0&&l.size===c.length&&(c.length===0||K.readFileSync(a).equals(c)))return a}catch{}let u=`${a}.${process.pid}.${B0(4).toString("hex")}`;try{return K.chmodSync(s,493),K.writeFileSync(u,c,{flag:"wx",mode:292}),K.chmodSync(u,292),K.renameSync(u,a),a}catch{try{K.rmSync(u,{force:!0})}catch{}return}}var to;function dT(){if(process.getuid?.()!==0||process.env.ARA_SRT_FILE_MASK!=="empty")return"/dev/null";let e=N0(Js,"srt-empty-file","empty","");if(e)return e;if(to)try{let r=K.lstatSync(to);if(r.isFile()&&r.size===0&&r.uid===0&&(r.mode&146)===0)return to}catch{}let t=K.mkdtempSync(ke.join(Js,"claude-empty-file-"));io.add(t),K.chmodSync(t,493);let n=ke.join(t,"empty");return K.writeFileSync(n,"",{flag:"wx",mode:292}),K.chmodSync(n,292),to=n,n}var ro="/etc/ssh/ssh_config";function pT(e){return`# Added by the sandbox: this sandbox reaches the network only through its proxy.
84
84
  Host * !localhost !127.0.0.1 !::1
85
85
  ProxyCommand /bin/sh -c 'h=$0; case $h in *:*) h="[$h]";; esac; exec socat - "PROXY:127.0.0.1:$h:$1,proxyport=3128\${SRT_SSH_PROXY_AUTH:+,proxyauth=$SRT_SSH_PROXY_AUTH}"' %h %p
86
86
 
87
87
  Host *
88
- `+e}var ai;function pT(e,t){let n;try{if(!K.statSync(to).isFile())return;n=K.realpathSync(to)}catch{return}let r=[to,n],i=(o)=>r.some((s)=>s===o||s.startsWith(`${o}/`));for(let o of t){let s=o;try{s=K.realpathSync(o)}catch{}if(i(o)||i(s))return}for(let o of e){let s=Ye(o).replace(/\/+$/,"");if(s===""||/[*?[{]/.test(s)||i(s))return}if(ai&&K.existsSync(ai))return ai;try{let o=dT(K.readFileSync(to,"utf8")),s=oT("sha256").update(o).digest("hex").slice(0,16),a=B0(Js,`srt-ssh-config-${s}`,"ssh_config",o);if(a)return ai=a,a;let c=K.mkdtempSync(ke.join(Js,"srt-ssh-config-"));no.add(c),K.chmodSync(c,493);let u=ke.join(c,"ssh_config");return K.writeFileSync(u,o,{flag:"wx",mode:292}),K.chmodSync(u,292),ai=u,u}catch(o){w(`[Sandbox Linux] ssh_config through the proxy unavailable: ${o.message}`);return}}var ro=new Set,no=new Set;function A0(e,t){return e===t?fT():"/dev/null"}var hT="ARA_SRT_MASKED_PATHS",mT=16384;function gT(e,t,n=mT){let r=[],i=0;for(let o of new Set(e)){if(o.includes(`
88
+ `+e}var ui;function hT(e,t){let n;try{if(!K.statSync(ro).isFile())return;n=K.realpathSync(ro)}catch{return}let r=[ro,n],i=(o)=>r.some((s)=>s===o||s.startsWith(`${o}/`));for(let o of t){let s=o;try{s=K.realpathSync(o)}catch{}if(i(o)||i(s))return}for(let o of e){let s=Ye(o).replace(/\/+$/,"");if(s===""||/[*?[{]/.test(s)||i(s))return}if(ui&&K.existsSync(ui))return ui;try{let o=pT(K.readFileSync(ro,"utf8")),s=sT("sha256").update(o).digest("hex").slice(0,16),a=N0(Js,`srt-ssh-config-${s}`,"ssh_config",o);if(a)return ui=a,a;let c=K.mkdtempSync(ke.join(Js,"srt-ssh-config-"));io.add(c),K.chmodSync(c,493);let u=ke.join(c,"ssh_config");return K.writeFileSync(u,o,{flag:"wx",mode:292}),K.chmodSync(u,292),ui=u,u}catch(o){w(`[Sandbox Linux] ssh_config through the proxy unavailable: ${o.message}`);return}}var no=new Set,io=new Set;function k0(e,t){return e===t?dT():"/dev/null"}var mT="ARA_SRT_MASKED_PATHS",gT=16384;function yT(e,t,n=gT){let r=[],i=0;for(let o of new Set(e)){if(o.includes(`
89
89
  `))continue;if(o!==t&&!o.startsWith(t==="/"?"/":t+"/"))continue;let s=o.split("'").length-1,a=Buffer.byteLength(o)+4*s+(r.length>0?1:0);if(i+a>n)break;r.push(o),i+=a}return r.length>0?r.join(`
90
- `):void 0}function yT(e){try{let t=K.lstatSync(e);return t.isFile()&&t.size===0}catch{return!1}}var Dr=0,k0=!1;function Gs(){if(k0)return;process.on("exit",()=>{Qs({force:!0})}),k0=!0}function Qs(e){if(!e?.force){if(Dr>0)Dr--;if(Dr>0){w(`[Sandbox Linux] Deferring mount point cleanup \u2014 ${Dr} sandbox(es) still active`);return}}else Dr=0;let t=[],n=[];for(let o of ro)try{let s=K.statSync(o);if(s.isFile()&&s.size===0)t.push(o);else if(s.isDirectory())n.push(o)}catch{}let r=(o)=>o.split("/").length;n.sort((o,s)=>r(s)-r(o));let i=Fu([...t,...n],(o)=>{try{let s=K.statSync(o);if(s.isFile()&&s.size===0)K.unlinkSync(o),w(`[Sandbox Linux] Cleaned up bwrap mount point (file): ${o}`);else if(s.isDirectory()){if(K.readdirSync(o).length!==0)return;K.rmdirSync(o),w(`[Sandbox Linux] Cleaned up bwrap mount point (dir): ${o}`)}}catch{}});ro.clear();for(let o of i)ro.add(o);for(let o of no)try{K.rmSync(o,{recursive:!0,force:!0})}catch{}no.clear(),eo=void 0,ai=void 0}function I0(e){try{return K.accessSync(e,K.constants.X_OK),!0}catch{return!1}}function N0(e){let{seccompConfig:t,bwrapPath:n,socatPath:r}=e??{},i=[],o=[];if(n){if(!I0(n))i.push(`bubblewrap (bwrap) not executable at ${n}`)}else if(Nr("bwrap")===null)i.push("bubblewrap (bwrap) not installed");if(r){if(!I0(r))i.push(`socat not executable at ${r}`)}else if(Nr("socat")===null)i.push("socat not installed");if(!t?.argv0&&Nu(t?.applyPath)===null)o.push("seccomp not available - unix socket access not restricted");return{warnings:o,errors:i}}async function D0(e,t,n,r,i){let o=n??"socat",s=R0(8).toString("hex"),a=_0(Xs(),`claude-http-${s}.sock`),c=_0(Xs(),`claude-socks-${s}.sock`),u=[`UNIX-LISTEN:${a},fork,reuseaddr`,`TCP:localhost:${e},keepalive,keepidle=10,keepintvl=5,keepcnt=3`];w(`Starting HTTP bridge: ${o} ${u.join(" ")}`);let l=E0(o,u,{stdio:"ignore"});if(l.on("error",(d)=>{w(`HTTP bridge process error: ${d}`,{level:"error"})}),l.on("exit",(d,g)=>{w(`HTTP bridge process exited with code ${d}, signal ${g}`,{level:d===0?"info":"error"})}),!l.pid)throw Error("Failed to start HTTP bridge process");let f,p;if(t===e)f=l,p=a;else{p=c;let d=[`UNIX-LISTEN:${c},fork,reuseaddr`,`TCP:localhost:${t},keepalive,keepidle=10,keepintvl=5,keepcnt=3`];if(w(`Starting SOCKS bridge: ${o} ${d.join(" ")}`),f=E0(o,d,{stdio:"ignore"}),f.on("error",(g)=>{w(`SOCKS bridge process error: ${g}`,{level:"error"})}),f.on("exit",(g,x)=>{w(`SOCKS bridge process exited with code ${g}, signal ${x}`,{level:g===0?"info":"error"})}),!f.pid){if(l.pid)try{process.kill(l.pid,"SIGTERM")}catch{}throw Error("Failed to start SOCKS bridge process")}}let h=200;for(let d=0;d<h;d++){if(!l.pid||l.killed||!f.pid||f.killed)throw Error("Linux bridge process died unexpectedly");try{if(K.existsSync(a)&&K.existsSync(p)){if(r!==void 0){let g=i??r;for(let x of new Set([a,p]))K.chownSync(x,r,g),K.chmodSync(x,384)}w(`Linux bridges ready after ${d+1} attempts`);break}}catch(g){w(`Error checking sockets (attempt ${d+1}): ${g}`,{level:"error"})}if(d===h-1){if(l.pid)try{process.kill(l.pid,"SIGTERM")}catch{}if(f.pid)try{process.kill(f.pid,"SIGTERM")}catch{}throw Error(`Failed to create bridge sockets after ${h} attempts`)}await new Promise((g)=>setTimeout(g,5))}return{httpSocketPath:a,socksSocketPath:p,httpBridgeProcess:l,socksBridgeProcess:f,httpProxyPort:e,socksProxyPort:t}}function vT(e,t){if(t){if(!e)throw Error("seccompConfig.argv0 requires seccompConfig.applyPath");return`ARGV0=${It([t])} ${It([e])} `}let n=Nu(e);return n?`${It([n])} `:void 0}function Vu(e,t,n){if(n===void 0)return[e,"-c",t];return[e,"-c",`${$0(n)}; exec "$0" "$@"`,e,"-c",t]}function $0(e){if(!Number.isSafeInteger(e)||e<3||e>9)throw Error("bad_start_fd");return`printf . >&${e}; exec ${e}>&-`}function xT(e,t,n,r,i,o,s,a){let c=i||"bash",u=It([o??"socat"]),l=s===void 0?"":` ${s}>&-`,f=["srt_payload_pid=",`${u} TCP4-LISTEN:3128,bind=127.0.0.1,fork,reuseaddr ${It([`UNIX-CONNECT:${e}`])} >/dev/null 2>&1${l} &`,"srt_http_proxy_pid=$!",`${u} TCP4-LISTEN:1080,bind=127.0.0.1,fork,reuseaddr ${It([`UNIX-CONNECT:${t}`])} >/dev/null 2>&1${l} &`,"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((d)=>`{ true <>/dev/tcp/127.0.0.1/${d}; } 2>/dev/null || { ${u} -u OPEN:/dev/null TCP4:127.0.0.1:${d},connect-timeout=0.1,retry=480,interval=0.005 >/dev/null 2>&1${l} & 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; }`],p=r===void 0&&s!==void 0?`{ ${$0(s)}; trap '' INT QUIT; exec ${a?n:It([c,"-c",n])}; }`:(r??"")+It(Vu(c,n,s));return[...f,`${p} <&0 &`,"srt_payload_pid=$!",'wait "$srt_payload_pid"',"srt_payload_status=$?","srt_payload_pid=",'exit "$srt_payload_status"'].join(`
91
- `)}function qs(e){try{if(K.lstatSync(e).isSymbolicLink())return K.realpathSync(e)}catch{}return e}function P0(e,t,n,r){let i=t==="/"?"/":t+"/";e.push("--tmpfs",t);for(let o of n)if(o.startsWith(i)||o===t)e.push("--bind",o,o),w(`[Sandbox Linux] Re-bound write path wiped by denyRead tmpfs: ${o}`);for(let o of r)if(o.startsWith(i)||o===t){if(!K.existsSync(o)){w(`[Sandbox Linux] Skipping non-existent read allow path: ${o}`);continue}if(n.some((s)=>(s.startsWith(i)||s===t)&&(o===s||o.startsWith(s+"/"))))continue;e.push("--ro-bind",o,o),w(`[Sandbox Linux] Re-allowed read access within denied region: ${o}`)}}async function bT(e,t,n,r,i={command:"rg"},o=Wu,s=!1,a,c,u=[]){let l=[],f=[],p=[],h=new Set,d=new Map,g=new Map;if(t){l.push("--ro-bind","/","/");for(let W of t.allowOnly||[]){let te=Ye(W).replace(/\/+$/,"")||"/";if(w(`[Sandbox Linux] Processing write path: ${W} -> ${te}`),te.startsWith("/dev/")){w(`[Sandbox Linux] Skipping /dev path: ${te}`);continue}if(!K.existsSync(te)){w(`[Sandbox Linux] Skipping non-existent write path: ${te}`);continue}try{let J=K.realpathSync(te),ce=te.replace(/\/+$/,"");if(J!==ce&&Do(te,J)){w(`[Sandbox Linux] Skipping symlink write path pointing outside expected location: ${W} -> ${J}`);continue}}catch{w(`[Sandbox Linux] Skipping write path that could not be resolved: ${te}`);continue}l.push("--bind",te,te),f.push(te)}let D,F=()=>{if(D!==void 0)return D;let W=[];for(let J of f){W.push(J);try{let ce=K.realpathSync(J);if(ce!==J)W.push(ce)}catch{}}let te=[];if(e){let J=[],ce=new Set(["proc","dev","sys"]);for(let ae of e.denyOnly||[])if(Ye(ae)==="/")try{for(let ee of K.readdirSync("/"))if(!ce.has(ee))J.push("/"+ee)}catch{}else J.push(ae);if(K.existsSync("/etc/ssh/ssh_config.d"))J.push("/etc/ssh/ssh_config.d");for(let ae of J){let ee=Ye(ae),Ee=!1;try{Ee=K.statSync(ee).isDirectory()}catch{continue}if(!Ee)continue;te.push(ee);try{let $e=K.realpathSync(ee);if($e!==ee)te.push($e)}catch{}}}return D={allowedWritePathsBothForms:W,prospectiveReadDenyTmpfsDirsBothForms:te},D},H=(W)=>f.some((te)=>W.startsWith(te+"/")||W===te),re=[...t.denyWithinAllow||[],...await lT(i,o,s,a)];h0();let se=new Set;for(let W of re){let te=Ye(W);if(te.startsWith("/dev/"))continue;let J=T0(te);if(J===null||J.startsWith("/dev/"))continue;if(Mu(J,f))continue;let ce=!1;try{ce=K.statSync(J).isDirectory()}catch{continue}if(!ce)continue;if(H(J)){let ae=d.get(J);if(ae===void 0)ae=new Set,d.set(J,ae);ae.add(te)}}let Pe=new Map,ue=(W)=>{let te=Pe.get(W);if(te!==void 0)return te;let{allowedWritePathsBothForms:J,prospectiveReadDenyTmpfsDirsBothForms:ce}=F(),ae=J.some((ee)=>ee.startsWith(W+"/"))||ce.some((ee)=>ee===W||ee.startsWith(W+"/"))||ce.some((ee)=>[W,...d.get(W)??[]].some((Ee)=>Ee===ee||Ee.startsWith(ee+"/")));return Pe.set(W,ae),ae},de=[...d.keys()];for(let W of re){let te=Ye(W);if(te.startsWith("/dev/"))continue;let J=T0(te);if(J===null){let ee=Mu(te,f);if(ee&&!se.has(ee))se.add(ee),p.push("--ro-bind","/dev/null",ee),g.set(ee,te);w(`[Sandbox Linux] Deny path could not be resolved through symlinks, failing closed: ${te}`);continue}if(J!==te)w(`[Sandbox Linux] Resolved symlinked deny path: ${te} -> ${J}`);if(J.startsWith("/dev/"))continue;if(se.has(J))continue;se.add(J);let ce=Mu(J,f);if(ce){if(!se.has(ce))se.add(ce),p.push("--ro-bind","/dev/null",ce),g.set(ce,te);w(`[Sandbox Linux] Mounted /dev/null at symlink ${ce} to prevent symlink replacement attack`);continue}if(!K.existsSync(J)){if(cT(J)){w(`[Sandbox Linux] Skipping deny path with file ancestor (cannot create paths under a file): ${J}`);continue}let ee=ke.dirname(J);while(ee!=="/"&&!K.existsSync(ee))ee=ke.dirname(ee);let Ee=H(ee)||H(J),$e=de.filter((ye)=>ee===ye||ee.startsWith(ye+"/")),qe=$e.length>0&&!$e.some(ue);if(Ee&&!qe){let ye=uT(J),oe=S0(ye,f)??ye;if(oe!==J){if(!h.has(oe)){let Oe=w0(oe,c),_e=K.mkdtempSync(ke.join(Xs(),"claude-empty-"));if(K.chmodSync(_e,365),no.add(_e),p.push("--ro-bind",_e,oe),g.set(oe,te),h.add(oe),Oe.kind==="unregistered")ro.add(oe);Gs(),w(`[Sandbox Linux] Mounted empty dir at ${oe} to block creation of ${J}`)}}else{let Oe=zu(oe),_e=A0(J,te);if(Oe.kind==="masked")p.push("--ro-bind",_e,oe),g.set(oe,te),Gs(),w(`[Sandbox Linux] Masked shared stub at ${oe} with ${_e} to block creation of ${J}`);else if(Oe.kind==="real")p.push("--ro-bind",oe,oe),g.set(oe,te);else p.push("--ro-bind",_e,oe),g.set(oe,te),ro.add(oe),Gs(),w(`[Sandbox Linux] Mounted ${_e} at ${oe} to block creation of ${J}`)}}else if(qe)w(`[Sandbox Linux] Skipping non-existent deny path inside a read-only denied directory (already uncreatable): ${J}`);else w(`[Sandbox Linux] Skipping non-existent deny path not within allowed paths: ${J}`);continue}if(H(J)){if((yT(J)?zu(J):void 0)?.kind==="masked")p.push("--ro-bind",A0(J,te),J),Gs();else p.push("--ro-bind",J,J);g.set(J,te)}else w(`[Sandbox Linux] Skipping deny path not within allowed paths: ${J}`)}}else l.push("--bind","/","/");let x=[],b=(e?.allowWithinDeny||[]).map((D)=>Ye(D)),S=new Map,C=[],T=new Set(["proc","dev","sys"]);for(let D of e?.denyOnly||[])if(Ye(D)==="/"){for(let F of K.readdirSync("/"))if(!T.has(F))x.push("/"+F)}else x.push(D);if(e&&K.existsSync("/etc/ssh/ssh_config.d"))x.push("/etc/ssh/ssh_config.d");let I=x.map((D)=>Ye(D)).sort((D,F)=>D.split("/").length-F.split("/").length);for(let D of I){if(!K.existsSync(D)){w(`[Sandbox Linux] Skipping non-existent read deny path: ${D}`);continue}if(K.statSync(D).isDirectory())C.push(D),P0(l,D,f,b);else{if(b.includes(D)){w(`[Sandbox Linux] Skipping read deny for re-allowed path: ${D}`);continue}let H=qs(D);l.push("--ro-bind","/dev/null",H),S.set(H,"/dev/null"),S.set(D,"/dev/null")}}for(let{realPath:D,fakePath:F}of n??[]){let H=qs(D);l.push("--ro-bind",F,H),S.set(H,F),S.set(D,F)}let k=(D)=>C.some((F)=>{if(!(D===F||D.startsWith(F+"/")))return!1;return!f.some((se)=>(se===F||se.startsWith(F+"/"))&&(D===se||D.startsWith(se+"/")))}),R=[...h].filter((D)=>{let F=g.get(D)??D;return!S.has(D)&&!k(D)&&!k(F)&&!f.some((H)=>H===D||H.startsWith(D+"/"))}),V=[];for(let D=0;D<p.length;D+=3){let F=p[D+2],H=g.get(F)??F;if(S.has(F))continue;if(k(F)||k(H)){w(`[Sandbox Linux] Skipping denyWrite bind already hidden by denyRead tmpfs: ${F}`);continue}if(R.some((re)=>F.startsWith(re+"/"))){w(`[Sandbox Linux] Skipping denyWrite bind under an empty-directory mask: ${F}`);continue}if(l.push(p[D],p[D+1],F),V.push(F),p[D+1]!==F)u.push(F);if(H!==F)V.push(H)}for(let D of C)if(V.some((F)=>D.startsWith(F+"/")))w(`[Sandbox Linux] Re-applying denyRead tmpfs re-exposed by denyWrite bind: ${D}`),P0(l,D,f,b);for(let[D,F]of S)if(V.some((H)=>D.startsWith(H+"/"))){if(qs(D)!==D)continue;w(`[Sandbox Linux] Re-applying file mask re-exposed by denyWrite bind: ${D}`),l.push("--ro-bind",F,D)}if(r!==void 0)l.push("--ro-bind",r,r);return l}async function O0(e){let{command:t,commandId:n,needsNetworkRestriction:r,httpSocketPath:i,socksSocketPath:o,httpProxyPort:s,socksProxyPort:a,proxyAuthToken:c,caCertPath:u,readConfig:l,writeConfig:f,unsetEnvVars:p,setEnvVars:h,maskedFileBinds:d,maskedFileStoreDir:g,enableWeakerNestedSandbox:x,runAsUid:b,runAsGid:S,runAsHostUid:C,runAsHostGid:T,runAsHostHome:I,runAsHostUser:k,setprivPath:R,allowAllUnixSockets:V,binShell:D,ripgrepConfig:F={command:"rg"},mandatoryDenySearchDepth:H=Wu,allowGitConfig:re=!1,gitSafeDirectories:se,seccompConfig:Pe,bwrapPath:ue,socatPath:de,observeSocketPath:W,startFd:te,argvCommand:J,abortSignal:ce}=e,ae=l&&l.denyOnly.length>0||d!==void 0&&d.length>0,ee=f!==void 0,Ee=p!==void 0&&p.length>0||h!==void 0&&Object.keys(h).length>0,$e=(se?.length??0)>0;if(!r&&!ae&&!ee&&!Ee&&!$e)return t;Dr++;let qe=[],ye=["--new-session","--die-with-parent"],oe=new Map,Oe=[],_e,it=!1;try{if(!V)if(_e=vT(Pe?.applyPath,Pe?.argv0),!_e)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 w("[Sandbox Linux] Applying seccomp filter for Unix socket blocking");else w("[Sandbox Linux] Skipping seccomp filter - allowAllUnixSockets is enabled");if(W&&_e)if(K.existsSync(W))Oe.push("--bind",W,W),oe.set("SRT_OBSERVE_SOCK",W),oe.set("SRT_ENCODED_CMD",zt(n??t));else w("[Sandbox Linux] observe socket missing \u2014 supervisor not running; "+"continuing without violation monitoring");if(Ee)for(let[Ut,cr]of Object.entries(h??{}))oe.set(Ut,cr);if(se&&se.length>0){let Ut=Oo({safeDirs:se,unsetEnvVars:p,setEnvVars:h});for(let[cr,Ro]of Object.entries(Ut))oe.set(cr,Ro)}if(r){if(ye.push("--unshare-net"),i&&o){if(!K.existsSync(i))throw Error(`Linux HTTP bridge socket does not exist: ${i}. The bridge process may have died. Try reinitializing the sandbox.`);if(!K.existsSync(o))throw Error(`Linux SOCKS bridge socket does not exist: ${o}. The bridge process may have died. Try reinitializing the sandbox.`);if(Oe.push("--bind",i,i),o!==i)Oe.push("--bind",o,o);it=!0;let Ut=Nn(3128,1080,u,c,f===void 0,zt(n??t));for(let cr of Ut){let Ro=cr.indexOf("=");oe.set(cr.slice(0,Ro),cr.slice(Ro+1))}if(s!==void 0)oe.set("CLAUDE_CODE_HOST_HTTP_PROXY_PORT",String(s));if(a!==void 0)oe.set("CLAUDE_CODE_HOST_SOCKS_PROXY_PORT",String(a))}}let rt=await bT(l,f,d,g,F,H,re,ce,C===void 0?void 0:{uid:C,gid:T??C},qe);js(),ye.push(...rt);let ot=gT(qe,process.cwd());if(ot!==void 0)oe.set(hT,ot);if(ye.push(...Oe),it){let Ut=pT(l?.denyOnly??[],(d??[]).flatMap(({realPath:cr})=>[cr,qs(cr)]));if(Ut)ye.push("--ro-bind",Ut,to)}if(ye.push("--dev","/dev"),ye.push("--unshare-pid"),!x){if(ye.push("--unshare-user","--cap-drop","ALL","--proc","/proc"),!_e)ye.push("--ro-bind","/dev/null","/proc/sysrq-trigger")}else ye.push("--unshare-user","--bind","/proc","/proc");if(b!==void 0)ye.push("--uid",String(b)),ye.push("--gid",String(S??b));if(C!==void 0){if(I)oe.set("HOME",I);if(k)oe.set("USER",k),oe.set("LOGNAME",k)}let st=D||"bash",Xe=Nr(st);if(!Xe)throw Error(`Shell '${st}' not found in PATH`);if(ye.push("--",Xe,"-c"),r&&i&&o){let Ut=xT(i,o,t,_e,Xe,de,te,J);ye.push(Ut)}else if(_e){let Ut=_e+It(Vu(Xe,t,te));ye.push(Ut)}else ye.push(te===void 0?t:`exec ${It(Vu(Xe,t,te))}`);let at=[ue??"bwrap",...ye],Ob=It(sT({bwrapCommand:at,uid:C,gid:T,setprivPath:R,unsetEnvVars:p,setEnvVars:Object.fromEntries(oe)})),Si=[];if(r)Si.push("network");if(ae||ee)Si.push("filesystem");if(Ee)Si.push("env");if(_e)Si.push("seccomp(unix-block)");return w(`[Sandbox Linux] Wrapped command with bwrap (${Si.join(", ")} restrictions)`),Ob}catch(rt){if(Dr>0)Dr--;if(js(),Dr===0)Fu([],()=>{});throw rt}}import{spawn as ST}from"child_process";import*as $r from"path";class Ys{violations=[];totalCount=0;maxSize=100;listeners=new Set;addViolation(e){if(this.violations.push({...e,line:Hu(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=zt(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 ci(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,o]of Object.entries(n))if(i!=="*"&&t.includes(i)&&o.some((s)=>e.includes(s)))return!0;return!1}function Hu(e){return e.replace(/[\x00-\x1f\x7f-\x9f]+/g," ").trim()}function CT(e=!1){let t=process.cwd(),n=[];for(let r of wi)n.push($r.resolve(t,r)),n.push(`**/${r}`);for(let r of $o())n.push($r.resolve(t,r)),n.push(`**/${r}/**`);if(n.push($r.resolve(t,".git/hooks")),n.push("**/.git/hooks/**"),!e)n.push($r.resolve(t,".git/config")),n.push("**/.git/config");return[...new Set(n)]}var L0=`_${Math.random().toString(36).slice(2,11)}_SBX`;function wT(e){return`CMD64_${zt(e)}_END_${L0}`}function ui(e){return xt(e)?`(regex ${ir(Ai(e))})`:`(subpath ${ir(e)})`}function Gu(e){return Ai(e).slice(0,-1)+"(/.*)?$"}function Cn(e){return xt(e)?`(regex ${ir(Gu(e))})`:`(subpath ${ir(e)})`}function U0(e){return e.replace(/\[[^\]]*\]|[*?]+/g,"x")}function Zu(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 Ku(e){let t=Ye(e);return{path:t,glob:xt(t)}}function z0(e,t){return e.test(t.glob?U0(t.path):t.path)}function ea(e,t){let n=e.glob?U0(e.path):e.path;return n.startsWith(t==="/"?"/":t+"/")&&n!==t}function ET(e,t){return{denies:(e.denyOnly||[]).map(Ku),allows:(e.allowWithinDeny||[]).map(Ku),writeRoots:(t||[]).map(Ku)}}function _T(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((a)=>i.path.startsWith(a+"/")))t.push(Cn(i.path));continue}let o=new RegExp(Gu(i.path));if(o.test("/"))n=!0;let s=e.allows.filter((a)=>z0(o,a)).map((a)=>ui(a.path));t.push(Zu(Cn(i.path),s))}return{filters:t,coversRoot:n}}function F0(e){let t=e.split(/[*?[\]]/)[0];if(!t||t==="/")return"/";return t.endsWith("/")?t.slice(0,-1):$r.dirname(t)}function TT(e,t){let{denies:n,allows:r,writeRoots:i}=e;if(i.length===0)return[];let o=i.filter((f)=>f.glob).map((f)=>new RegExp(Ai(f.path))),s=i.filter((f)=>!f.glob).map((f)=>f.path),a=(f)=>s.some((p)=>ea({path:f,glob:!1},p))||o.some((p)=>p.test(f)),c=(f)=>[...r,...i].filter((p)=>ea(p,f)).map((p)=>ui(p.path)),u=new Set,l=(f)=>{for(let p of f)if(a(p))u.add(`(literal ${ir(p)})`)};for(let f of n)if(f.glob){let p=F0(f.path);if(!(o.length>0||s.some((x)=>p===x||ea({path:p,glob:!1},x)||ea({path:x,glob:!1},p))))continue;let d=new RegExp(Gu(f.path)),g=[...r,...i].filter((x)=>z0(d,x)).map((x)=>ui(x.path));if(u.add(Zu(Cn(f.path),g)),p!=="/")l([p,...ju(p)])}else{if(!a(f.path))continue;u.add(Zu(Cn(f.path),c(f.path))),l(ju(f.path))}return Jr("deny",["file-write-unlink"],u,t)}function Jr(e,t,n,r){if(n.size===0)return[];return[`(${e} ${t.join(" ")}`,...[...n].map((i)=>` ${i}`),` (with message "${r}"))`]}function ju(e){let t=[],n=$r.dirname(e);while(n!=="/"&&n!=="."){t.push(n);let r=$r.dirname(n);if(r===n)break;n=r}return t}function M0(e,t){let n=new Set;for(let r of e){let i=Ye(r);n.add(Cn(i));let o;if(xt(i)){if(o=F0(i),o==="/")continue;n.add(`(literal ${ir(o)})`)}else o=i;for(let s of ju(o))n.add(`(literal ${ir(s)})`)}return Jr("deny",["file-write-unlink","file-write-create"],n,t)}function AT(e,t){if(!e)return["(allow file-read*)"];let n=[];n.push("(allow file-read*)");let r=e.denies.some((c)=>c.path==="/"),i=new Set(e.denies.map((c)=>Cn(c.path)));n.push(...Jr("deny",["file-read*"],i,t));let o=new Set(e.allows.map((c)=>ui(c.path)));n.push(...Jr("allow",["file-read*"],o,t));let s=_T(e);if(n.push(...Jr("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(...M0(e.denies.map((c)=>c.path),t));let a=new Set(e.writeRoots.map((c)=>ui(c.path)));return n.push(...Jr("allow",["file-write-unlink","file-write-create"],a,t)),n}function kT(e,t,n=!1){if(!e)return["(allow file-write*)"];let r=[],i=new Set;for(let a of e.allowOnly||[])i.add(ui(Ye(a)));r.push(...Jr("allow",["file-write*"],i,t));let o=[...e.denyWithinAllow||[],...CT(n)],s=new Set;for(let a of o)s.add(Cn(Ye(a)));return r.push(...Jr("deny",["file-write*"],s,t)),r.push(...M0(o,t)),r}function IT({readConfig:e,writeConfig:t,httpProxyPort:n,socksProxyPort:r,needsNetworkRestriction:i,allowUnixSockets:o,allowAllUnixSockets:s,allowLocalBinding:a,allowMachLookup:c,allowPty:u,allowGitConfig:l=!1,enableWeakerNetworkIsolation:f=!1,allowAppleEvents:p=!1,logTag:h}){let d=["(version 1)",`(deny default (with message "${h}"))`,"",`; LogTag: ${h}`,"","; 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")',")","",...f?["; trustd.agent - needed for Go TLS certificate verification (weaker network isolation)",'(allow mach-lookup (global-name "com.apple.trustd.agent"))']:[],...p?["; 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"))']:[],...c&&c.length>0?["; User-specified XPC/Mach services",...c.map((x)=>x.endsWith("*")?`(allow mach-lookup (global-name-prefix ${ir(x.slice(0,-1))}))`:`(allow mach-lookup (global-name ${ir(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(d.push("; Network"),!i)d.push("(allow network*)");else{if(a)d.push('(allow network-bind (local ip "*:*"))'),d.push('(allow network-inbound (local ip "*:*"))'),d.push('(allow network-outbound (remote ip "localhost:*"))');if(s)d.push("(allow system-socket (socket-domain AF_UNIX))"),d.push('(allow network-bind (local unix-socket (path-regex #"^/")))'),d.push('(allow network-outbound (remote unix-socket (path-regex #"^/")))');else if(o&&o.length>0){d.push("(allow system-socket (socket-domain AF_UNIX))");for(let x of o){let b=Ye(x);d.push(`(allow network-bind (local unix-socket (subpath ${ir(b)})))`),d.push(`(allow network-outbound (remote unix-socket (subpath ${ir(b)})))`)}}if(n!==void 0)d.push(`(allow network-bind (local ip "localhost:${n}"))`),d.push(`(allow network-inbound (local ip "localhost:${n}"))`),d.push(`(allow network-outbound (remote ip "localhost:${n}"))`);if(r!==void 0&&r!==n)d.push(`(allow network-bind (local ip "localhost:${r}"))`),d.push(`(allow network-inbound (local ip "localhost:${r}"))`),d.push(`(allow network-outbound (remote ip "localhost:${r}"))`)}d.push("");let g=e?ET(e,t?.allowOnly):void 0;if(d.push("; File read"),d.push(...AT(g,h)),d.push(""),d.push("; File write"),d.push(...kT(t,h,l)),g){let x=TT(g,h);if(x.length>0)d.push(""),d.push("; File read: keep read-denied paths inside write roots in place"),d.push(...x)}if(u)d.push(""),d.push("; Pseudo-terminal (pty) support"),d.push("(allow pseudo-tty)"),d.push("(allow file-ioctl"),d.push(' (literal "/dev/ptmx")'),d.push(' (regex #"^/dev/ttys")'),d.push(")"),d.push("(allow file-read* file-write*"),d.push(' (literal "/dev/ptmx")'),d.push(' (regex #"^/dev/ttys")'),d.push(")");return d.join(`
92
- `)}function ir(e){return JSON.stringify(e)}function V0(e){let{command:t,commandId:n,needsNetworkRestriction:r,httpProxyPort:i,socksProxyPort:o,proxyAuthToken:s,caCertPath:a,allowUnixSockets:c,allowAllUnixSockets:u,allowLocalBinding:l,allowMachLookup:f,readConfig:p,writeConfig:h,unsetEnvVars:d,setEnvVars:g,maskedFileBinds:x,allowPty:b,allowGitConfig:S=!1,gitSafeDirectories:C,enableWeakerNetworkIsolation:T=!1,allowAppleEvents:I=!1,binShell:k}=e,R=p;if(x&&x.length>0)w("[Sandbox macOS] file mask degrades to deny on macOS until the interposer lands"),R={denyOnly:[...p?.denyOnly??[],...x.map((ae)=>ae.realPath)],allowWithinDeny:p?.allowWithinDeny};let V=R&&R.denyOnly.length>0,D=h!==void 0,F=d!==void 0&&d.length>0||g!==void 0&&Object.keys(g).length>0,H=(C?.length??0)>0;if(!r&&!V&&!D&&!F&&!H)return t;let re=n??t,se=wT(re),Pe=IT({readConfig:R,writeConfig:h,httpProxyPort:i,socksProxyPort:o,needsNetworkRestriction:r,allowUnixSockets:c,allowAllUnixSockets:u,allowLocalBinding:l,allowMachLookup:f,allowPty:b,allowGitConfig:S,enableWeakerNetworkIsolation:T,allowAppleEvents:I,logTag:se}),ue=Nn(i,o,a,s,h===void 0,zt(re));if(l&&r){let Ee=(d??[]).includes("JAVA_TOOL_OPTIONS")?"":process.env.JAVA_TOOL_OPTIONS??"",$e=Ee.includes("-Djava.net.preferIPv4Stack=true")?Ee:[Ee,"-Djava.net.preferIPv4Stack=true"].filter(Boolean).join(" ");ue.push(`JAVA_TOOL_OPTIONS=${$e}`)}if(C&&C.length>0){let ae=Oo({safeDirs:C,unsetEnvVars:d,setEnvVars:g});for(let[ee,Ee]of Object.entries(ae))ue.push(`${ee}=${Ee}`)}let de=k||"bash",W=Nr(de);if(!W)throw Error(`Shell '${de}' not found in PATH`);let te=(d??[]).flatMap((ae)=>["-u",ae]),J=Object.entries(g??{}).map(([ae,ee])=>`${ae}=${ee}`),ce=It(["env",...te,...J,...ue,"/usr/bin/sandbox-exec","-p",Pe,W,"-c",t]);return w(`[Sandbox macOS] Applied restrictions - network: ${!!(i||o)}, read: ${R?"allowAllExcept"in R?"allowAllExcept":"denyAllExcept":"none"}, write: ${h?"allowAllExcept"in h?"allowAllExcept":"denyAllExcept":"none"}`),ce}function W0(e,t,n=(r)=>r){let r=/CMD64_(.+?)_END/,i=/Sandbox:\s+(.+)$/,o=ST("log",["stream","--predicate",`(eventMessage ENDSWITH "${L0}")`,"--style","compact"]);return o.stdout?.on("data",(s)=>{let a=s.toString().split(`
93
- `),c=a.find((d)=>d.includes("Sandbox:")&&d.includes("deny")),u=a.find((d)=>d.startsWith("CMD64_"));if(!c)return;let l=c.match(i);if(!l?.[1])return;let f=l[1],p,h;if(u){if(h=u.match(r)?.[1],h)try{p=n(cn(h))}catch{}}if(f.includes("mDNSResponder")||f.includes("mach-lookup com.apple.diagnosticd")||f.includes("mach-lookup com.apple.analyticsd"))return;if(ci(f,p,t))return;e({line:f,command:p,encodedCommand:h,timestamp:new Date})}),o.stderr?.on("data",(s)=>{w(`[Sandbox Monitor] Log stream stderr: ${s.toString()}`)}),o.on("error",(s)=>{w(`[Sandbox Monitor] Failed to start log stream: ${s.message}`)}),o.on("exit",(s)=>{w(`[Sandbox Monitor] Log stream exited with code: ${s}`)}),()=>{w("[Sandbox Monitor] Stopping log monitor"),o.kill("SIGTERM")}}import{randomBytes as PT}from"crypto";import{chmodSync as H0,chownSync as RT,mkdtempSync as BT,rmSync as NT}from"fs";import{createServer as DT}from"net";import{tmpdir as $T}from"os";import{join as K0,posix as OT}from"path";import{createInterface as LT}from"readline";function Z0(e,t){let{allowWritePaths:n,denyWritePaths:r,ignoreViolations:i,resolveCommandText:o=(C)=>C,consumerUid:s,consumerGid:a}=t,c=BT(K0($T(),"srt-obs-")),u=K0(c,`s${PT(4).toString("hex")}.sock`),l=(C,T)=>C===T||C.startsWith(T.endsWith("/")?T:T+"/"),f=(C)=>{let T=OT.normalize(C);if(r.some((I)=>l(T,I)))return!0;return!n.some((I)=>l(T,I))},p=(C,T)=>{if(C.observe_init_error){w(`[Sandbox Linux Monitor] observe filter not installed: ${C.observe_init_error}`);return}if(typeof C.path!=="string")return;if(!C.path.startsWith("/"))return;if(!f(C.path))return;let I;if(T)try{I=o(cn(T))}catch{}if(ci(C.path,I,i))return;let k={line:`deny ${C.syscall??"syscall"} ${C.path}`,command:I,encodedCommand:T,timestamp:new Date};e(k)},h,d=new Promise((C)=>{h=C}),g=u,x=DT((C)=>{let T,I=LT({input:C});I.on("line",(k)=>{if(!k)return;let R;try{R=JSON.parse(k)}catch{return}if(R.encodedCommand&&T===void 0)T=R.encodedCommand;p(R,T??R.encodedCommand)}),C.on("error",()=>I.close()),C.on("close",()=>I.close())});x.on("error",(C)=>{w(`[Sandbox Linux Monitor] listen failed: ${C.message} - violation monitoring disabled`,{level:"warn"}),g=void 0,h()}),x.listen(u,()=>{if(s!==void 0)H0(c,457),RT(u,s,a??s),H0(u,384);h()});let b=new Set;return x.on("connection",(C)=>{b.add(C),C.on("close",()=>b.delete(C))}),{get observeSocketPath(){return g},ready:d,stop:()=>{w("[Sandbox Linux Monitor] stopping");for(let C of b)C.destroy();x.close();try{NT(c,{recursive:!0,force:!0})}catch{}}}}import*as tt from"fs";import*as X0 from"net";import*as et from"path";import{spawn as UT,spawnSync as zT}from"child_process";import{once as FT}from"events";import{fileURLToPath as MT}from"url";class me extends Error{code;subcommand;constructor(e,t,n){super(t);this.name="WindowsSandboxError",this.code=e,this.subcommand=n}}var ta=[60080,60089],j0=["-NoProfile","-Command"];function ra(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 me("bin_shell_invalid",`binShell.exe must be an absolute path (got ${JSON.stringify(e.exe)})`);if(!Array.isArray(e.args))throw new me("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(),o=et.win32.isAbsolute(e);if(!o&&e!==r)throw new me("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(!o)throw new me("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:o?e:"pwsh.exe",args:j0};case"powershell":case"powershell.exe":return{exe:o?e:et.win32.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe"),args:j0};case"cmd":case"cmd.exe":return o?{exe:e,args:n.args}:n;default:throw new me("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 J0(){let e=et.dirname(MT(import.meta.url));return et.resolve(e,"..","..")}var Q0={x64:"x64",arm64:"arm64"},VT=et.join(J0(),"vendor","srt-win",Q0[process.arch]??process.arch,"srt-win.exe");function WT(){let e=J0(),t=Q0[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 me("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 Y0="--srt-win";function Nt(e){if(e?.path===void 0)throw new me("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 me("srt_win_not_found",`windows.srtWin.path is set to '${e.path}' but the file does not exist`);return{exe:e.path,prependArgs:[Y0]}}function li(e,t={}){let{exe:n,prependArgs:r}=t.srtWin??Nt(),i=zT(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 me("srt_win_timeout",`srt-win ${e.join(" ")} timed out after ${t.timeoutMs??15000}ms`+(i.signal?` (killed by ${i.signal})`:""),e[0]);throw new me("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 io(e,t={}){let{exe:n,prependArgs:r}=t.srtWin??Nt(),i=t.timeoutMs??15000;return new Promise((o,s)=>{let a=UT(n,[...r,...e],{windowsHide:!0}),c=!1,u=i>0?setTimeout(()=>{c=!0,a.kill()},i):void 0,l="",f="";a.stdout?.setEncoding("utf8").on("data",(p)=>l+=p),a.stderr?.setEncoding("utf8").on("data",(p)=>f+=p),a.stdin?.on("error",()=>{}).end(t.stdin),a.once("error",(p)=>{clearTimeout(u),s(new me("spawn_failed",`srt-win ${e[0]}: spawn failed: ${p.message}`,e[0]))}),a.once("close",(p,h)=>{if(clearTimeout(u),c){s(new me("srt_win_timeout",`srt-win ${e.join(" ")} timed out after ${i}ms`+(h?` (killed by ${h})`:"")+HT(f),e[0]));return}o({status:p,signal:h,stdout:l.trim(),stderr:f.trim()})})})}function HT(e){let t=e.trim().split(/\r?\n/).pop()?.trim();return t?`; last output: ${t.slice(0,300)}`:""}function em(e,t){if(t.status!==0)throw new me("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 me("srt_win_bad_json",`srt-win ${e.join(" ")}: unparseable JSON output ${JSON.stringify(t.stdout)}: ${n.message}`,e[0])}}function Xu(e,t){return em(e,li(e,t))}async function Ju(e,t){return em(e,await io(e,t))}async function tm(e,t){let n=await io(e,t),r;try{r=JSON.parse(n.stdout)}catch(i){throw new me("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 rm(e){let t=["wfp","status"];if(e)t.push("--sublayer-guid",e);return t}function na(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 ia(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 nm(e={}){let t=["status"];if(e.sublayerGuid)t.push("--sublayer-guid",e.sublayerGuid);let n=Xu(t,{srtWin:e.srtWin});return{user:ia(n.user),wfp:na(n.wfp)}}async function im(e={}){let t=["status"];if(e.sublayerGuid)t.push("--sublayer-guid",e.sublayerGuid);let n=await Ju(t,{srtWin:e.srtWin});return{user:ia(n.user),wfp:na(n.wfp)}}function om(e={}){return na(Xu(rm(e.sublayerGuid),{srtWin:e.srtWin}))}async function sm(e={}){return na(await Ju(rm(e.sublayerGuid),{srtWin:e.srtWin}))}async function Qu(e={}){let t=e.target,n;if(!t){let[r,i]=e.proxyPortRange??ta;for(let o=0;o<5;o++){let s=X0.createServer();s.listen(0,"127.0.0.1"),await FT(s,"listening");let a=s.address().port;if(a<r||a>i){n=s,t=`127.0.0.1:${a}`;break}s.close()}if(!t)throw new me("wfp_verify_bind_failed",`verifyWindowsWfpEgress: could not bind a loopback listener outside the WFP permit range [${r},${i}] in 5 attempts`)}try{let r=li(["wfp","verify","--target",t],{timeoutMs:30000,srtWin:e.srtWin});w(`[Sandbox Windows] wfp verify exit=${r.status}: ${r.stderr||r.stdout}`);let i;try{i=JSON.parse(r.stdout)}catch{throw new me("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 me("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 me("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 Yu(e={}){return ia(Xu(["user","status"],{srtWin:e.srtWin}))}async function oo(e={}){return ia(await Ju(["user","status"],{srtWin:e.srtWin}))}function el(e,t={}){let n=e??Yu(t);if(!n.caCertThumb||!n.caCertPem)return null;return{pem:n.caCertPem,thumb:n.caCertThumb}}function KT(e,t={}){let n=li(["user","trust-ca",e],{timeoutMs:60000,srtWin:t.srtWin});cm(e,n)}async function am(e,t={}){let n=await io(["user","trust-ca",e],{timeoutMs:60000,srtWin:t.srtWin});cm(e,n)}function cm(e,t){if(w(`[Sandbox Windows] user trust-ca exit=${t.status}: ${t.stderr||t.stdout}`),t.status!==0)throw new me("trust_ca_failed",`srt-win user trust-ca '${e}' failed (exit ${t.status}): ${t.stderr||t.stdout}`)}function um(){let e=process.env.ProgramData;if(!e)throw Error("ProgramData is not set");return et.win32.join(e,"sandbox-runtime")}async function tl(e={}){let t=e.status??await oo({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:um();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"),o=et.join(r,"cert.pem"),s=et.join(r,"key.pem"),a=(e.regenerateWithinDays??30)*24*60*60*1000,c=(x,b)=>{let S=`${x}.tmp.${process.pid}`;tt.writeFileSync(S,b),tt.renameSync(S,x)},u=async(x,b,S,C)=>{c(o,x),c(s,b);let T=C||t.caCertThumb!==S;if(T){let I=et.join(r,`.trust.${process.pid}.${Date.now()}.pem`);tt.writeFileSync(I,x);try{await am(I,{srtWin:e.srtWin})}finally{tt.rmSync(I,{force:!0})}}return w(`[Sandbox Windows] persistent CA ${C?"generated":"reused"} (thumb=${S}${T&&!C?", trust reconciled":""})`),{certPem:x,keyPem:b,certPath:o,keyPath:s,thumbprint:S,generated:C,trusted:T}},l=()=>{let x;try{x=JSON.parse(tt.readFileSync(i,"utf8"))}catch(S){w(`[Sandbox Windows] persistent CA ca.json unreadable (${S.message})`,{level:"warn"});return}if(typeof x.certPem!=="string"||typeof x.keyPem!=="string")return;let b=Hi(x.certPem,x.keyPem);if(!b.ok){w(`[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=l();if(x&&x.notAfter.getTime()-Date.now()>a)return await u(x.certPem,x.keyPem,x.thumbprint,!1);if(x)w(`[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 S=et.join(r,b);if(tt.statSync(S).mtimeMs<x)tt.rmSync(S,{force:!0})}}catch{}let f=Cs({cn:"sandbox-runtime persistent CA"});c(i,JSON.stringify({certPem:f.certPem,keyPem:f.keyPem}));let p=l(),{certPem:h,keyPem:d,thumbprint:g}=p??{certPem:f.certPem,keyPem:f.keyPem,thumbprint:Qn(f.certPem)};return await u(h,d,g,!0)}function rl(e){return e.timeoutMs??120000}function lm(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 fm(e){if(e instanceof me&&e.code==="srt_win_timeout")throw new me("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 dm(e){if(w(`[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 me("install_wfp_failed",`srt-win install: WFP filter install failed: ${t}`);case 14:throw new me("install_user_failed",`srt-win install: sandbox user provisioning failed: ${t}`);case 13:throw new me("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 me("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 me("install_failed",`srt-win install failed (exit ${e.status}): ${t}`)}}function ZT(e={}){let t=e.srtWin??Nt(),n;try{n=li(lm(e),{timeoutMs:rl(e),srtWin:t})}catch(i){fm(i)}dm(n);let r=nm({sublayerGuid:e.sublayerGuid,srtWin:t});return n.status===10?{...r,cancelled:!0}:r}async function jT(e={}){let t=e.srtWin??Nt(),n;try{n=await io(lm(e),{timeoutMs:rl(e),srtWin:t})}catch(i){fm(i)}dm(n);let r=await im({sublayerGuid:e.sublayerGuid,srtWin:t});return n.status===10?{...r,cancelled:!0}:r}function GT(e={}){let t=["uninstall"];if(e.sublayerGuid)t.push("--sublayer-guid",e.sublayerGuid);if(e.keepUser)t.push("--keep-user");let n=li(t,{timeoutMs:rl(e),srtWin:e.srtWin});if(w(`[Sandbox Windows] uninstall exit=${n.status}: ${n.stderr||n.stdout}`),n.status===10)return{cancelled:!0};if(n.status!==0)throw new me("uninstall_failed",`srt-win uninstall failed (exit ${n.status}): ${n.stderr||n.stdout}`);return{}}function oa(e,t){let n=new Set;for(let r of e){let i=Ye(r),o=Ei(i);if(_i(i)&&!o){n.add(i);continue}let s=o?un(i,{caseInsensitive:!0}):[i];for(let a of s){if(!tt.statSync(a,{throwIfNoEntry:!1})){if(t?.mode==="deny"&&!o)n.add(/[\\/]$/.test(r)&&!/[\\/]$/.test(a)?a+"\\":a);continue}n.add(a)}}return[...n]}function qT(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 me("mapped_drive_cwd",r.message??"mapped/network-drive working directory","exec"),{drive:r.drive})}catch{}}return}var G0=60000;async function pm(e,t,n,r,i,o){let s=["acl",e,"--holder-pid",`${t}`,"--sandbox-user-sid",n];try{return await io(s,{timeoutMs:G0,stdin:r,srtWin:o})}catch(a){if(!(a instanceof me)||a.code!=="srt_win_timeout")throw a;let c=i.slice(0,3).join(", "),u=i.length>3?` and ${i.length-3} more`:"";throw new me("srt_win_timeout",`srt-win acl ${e} did not finish within ${G0}ms on ${c||"no paths"}${u}. Another srt-win ACL change is holding the per-user ACL lock (a deny stamp or grant on a large folder, which rewrites every file below it), or one of these folders is that large. Use a smaller folder, or let the other change finish and try again. (${a.message})`,"acl")}}async function nl(e){let t=e.holderPid??process.pid,n=JSON.stringify({denyRead:e.denyRead,denyWrite:e.denyWrite}),r=await pm("stamp",t,e.sandboxUserSid,n,[...e.denyRead,...e.denyWrite],e.srtWin);if(w(`[Sandbox Windows] acl stamp exit=${r.status}: ${r.stderr||r.stdout}`),r.status!==0)throw new me("acl_stamp_failed",`srt-win acl stamp exited ${r.status} `+(r.status===2?"(partial \u2014 some inputs skipped)":"(failed)")+`: ${r.stderr||r.stdout}`)}async function sa(e){let t=e.holderPid??process.pid;try{let n=await tm(["acl","restore","--holder-pid",`${t}`,"--sandbox-user-sid",e.sandboxUserSid,"--json"],{timeoutMs:60000,srtWin:e.srtWin});if(!n.ok)w(`[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){w(`[Sandbox Windows] acl restore: ${n.message}`,{level:"error"});return}}async function il(e){let t=e.holderPid??process.pid,n=JSON.stringify({read:e.read,write:e.write}),r=await pm("grant",t,e.sandboxUserSid,n,[...e.write,...e.read],e.srtWin);if(w(`[Sandbox Windows] acl grant exit=${r.status}: ${r.stderr||r.stdout}`),r.status!==0)throw new me("acl_grant_failed",`srt-win acl grant exited ${r.status}: ${r.stderr||r.stdout}`)}async function aa(e){let t=e.holderPid??process.pid;try{let n=await tm(["acl","revoke","--holder-pid",`${t}`,"--sandbox-user-sid",e.sandboxUserSid,"--json"],{timeoutMs:60000,srtWin:e.srtWin});if(!n.ok)w(`[Sandbox Windows] acl revoke exited non-zero: ${n.stderr}`,{level:"error"});return n.json}catch(n){w(`[Sandbox Windows] acl revoke: ${n.message}`,{level:"error"});return}}function hm(e){let t=e.holderPid??process.pid;for(let n of["revoke","restore"])try{li(["acl",n,"--holder-pid",`${t}`,"--sandbox-user-sid",e.sandboxUserSid,"--json"],{timeoutMs:60000,srtWin:e.srtWin})}catch(r){w(`[Sandbox Windows] acl ${n} at exit: ${r.message}`,{level:"error"})}}function mm(e){let{exe:t,prependArgs:n}=e.srtWin??Nt(),r=XT(Nn(e.httpProxyPort,e.socksProxyPort,e.caCertPath?.replace(/\\/g,"/"),e.proxyAuthToken,void 0,zt(e.commandId??e.command)));delete r.TMPDIR,delete r.NO_PROXY,delete r.no_proxy;let i=Ti({safeDirs:[e.cwd??process.cwd(),...e.allowWrite??[],...e.gitSafeDirectories??[]],schannelCa:e.caCertPath!==void 0,baseEnv:e.setEnvVars}),o=[t,...n,"exec"];if(e.quiet!==!1)o.push("--quiet");for(let l of e.denyRead??[])o.push("--deny-read",l);for(let l of e.denyWrite??[])o.push("--deny-write",l);let s={PATH:process.env.PATH,PATHEXT:process.env.PATHEXT,...e.setEnvVars??{},...r,...i};for(let[l,f]of Object.entries(s))if(f!==void 0)o.push("--env",`${l}=${f}`);o.push("--");let a=e.binShell??ra(void 0);o.push(a.exe,...a.args,e.command);let c=o.reduce((l,f)=>l+f.length+3,0);if(c>30000)throw new me("argv_too_long",`Windows sandbox argv is ~${c} chars (CreateProcessW limit is 32 767).`);let u={...process.env,...r};return{argv:o,env:u}}function XT(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 qu(e){let t=e?` --sublayer-guid ${e}`:"";return`Windows sandbox needs a one-time install (one UAC prompt):
90
+ `):void 0}function vT(e){try{let t=K.lstatSync(e);return t.isFile()&&t.size===0}catch{return!1}}var Dr=0,I0=!1;function Gs(){if(I0)return;process.on("exit",()=>{Qs({force:!0})}),I0=!0}function Qs(e){if(!e?.force){if(Dr>0)Dr--;if(Dr>0){w(`[Sandbox Linux] Deferring mount point cleanup \u2014 ${Dr} sandbox(es) still active`);return}}else Dr=0;let t=[],n=[];for(let o of no)try{let s=K.statSync(o);if(s.isFile()&&s.size===0)t.push(o);else if(s.isDirectory())n.push(o)}catch{}let r=(o)=>o.split("/").length;n.sort((o,s)=>r(s)-r(o));let i=Mu([...t,...n],(o)=>{try{let s=K.statSync(o);if(s.isFile()&&s.size===0)K.unlinkSync(o),w(`[Sandbox Linux] Cleaned up bwrap mount point (file): ${o}`);else if(s.isDirectory()){if(K.readdirSync(o).length!==0)return;K.rmdirSync(o),w(`[Sandbox Linux] Cleaned up bwrap mount point (dir): ${o}`)}}catch{}});no.clear();for(let o of i)no.add(o);for(let o of io)try{K.rmSync(o,{recursive:!0,force:!0})}catch{}io.clear(),to=void 0,ui=void 0}function P0(e){try{return K.accessSync(e,K.constants.X_OK),!0}catch{return!1}}function D0(e){let{seccompConfig:t,bwrapPath:n,socatPath:r}=e??{},i=[],o=[];if(n){if(!P0(n))i.push(`bubblewrap (bwrap) not executable at ${n}`)}else if(Nr("bwrap")===null)i.push("bubblewrap (bwrap) not installed");if(r){if(!P0(r))i.push(`socat not executable at ${r}`)}else if(Nr("socat")===null)i.push("socat not installed");if(!t?.argv0&&Du(t?.applyPath)===null)o.push("seccomp not available - unix socket access not restricted");return{warnings:o,errors:i}}async function $0(e,t,n,r,i){let o=n??"socat",s=B0(8).toString("hex"),a=T0(Xs(),`claude-http-${s}.sock`),c=T0(Xs(),`claude-socks-${s}.sock`),u=[`UNIX-LISTEN:${a},fork,reuseaddr`,`TCP:localhost:${e},keepalive,keepidle=10,keepintvl=5,keepcnt=3`];w(`Starting HTTP bridge: ${o} ${u.join(" ")}`);let l=_0(o,u,{stdio:"ignore"});if(l.on("error",(d)=>{w(`HTTP bridge process error: ${d}`,{level:"error"})}),l.on("exit",(d,g)=>{w(`HTTP bridge process exited with code ${d}, signal ${g}`,{level:d===0?"info":"error"})}),!l.pid)throw Error("Failed to start HTTP bridge process");let f,p;if(t===e)f=l,p=a;else{p=c;let d=[`UNIX-LISTEN:${c},fork,reuseaddr`,`TCP:localhost:${t},keepalive,keepidle=10,keepintvl=5,keepcnt=3`];if(w(`Starting SOCKS bridge: ${o} ${d.join(" ")}`),f=_0(o,d,{stdio:"ignore"}),f.on("error",(g)=>{w(`SOCKS bridge process error: ${g}`,{level:"error"})}),f.on("exit",(g,v)=>{w(`SOCKS bridge process exited with code ${g}, signal ${v}`,{level:g===0?"info":"error"})}),!f.pid){if(l.pid)try{process.kill(l.pid,"SIGTERM")}catch{}throw Error("Failed to start SOCKS bridge process")}}let h=200;for(let d=0;d<h;d++){if(!l.pid||l.killed||!f.pid||f.killed)throw Error("Linux bridge process died unexpectedly");try{if(K.existsSync(a)&&K.existsSync(p)){if(r!==void 0){let g=i??r;for(let v of new Set([a,p]))K.chownSync(v,r,g),K.chmodSync(v,384)}w(`Linux bridges ready after ${d+1} attempts`);break}}catch(g){w(`Error checking sockets (attempt ${d+1}): ${g}`,{level:"error"})}if(d===h-1){if(l.pid)try{process.kill(l.pid,"SIGTERM")}catch{}if(f.pid)try{process.kill(f.pid,"SIGTERM")}catch{}throw Error(`Failed to create bridge sockets after ${h} attempts`)}await new Promise((g)=>setTimeout(g,5))}return{httpSocketPath:a,socksSocketPath:p,httpBridgeProcess:l,socksBridgeProcess:f,httpProxyPort:e,socksProxyPort:t}}function xT(e,t){if(t){if(!e)throw Error("seccompConfig.argv0 requires seccompConfig.applyPath");return`ARGV0=${It([t])} ${It([e])} `}let n=Du(e);return n?`${It([n])} `:void 0}function Wu(e,t,n){if(n===void 0)return[e,"-c",t];return[e,"-c",`${O0(n)}; exec "$0" "$@"`,e,"-c",t]}function O0(e){if(!Number.isSafeInteger(e)||e<3||e>9)throw Error("bad_start_fd");return`printf . >&${e}; exec ${e}>&-`}function bT(e,t,n,r,i,o,s,a){let c=i||"bash",u=It([o??"socat"]),l=s===void 0?"":` ${s}>&-`,f=["srt_payload_pid=",`${u} TCP4-LISTEN:3128,bind=127.0.0.1,fork,reuseaddr ${It([`UNIX-CONNECT:${e}`])} >/dev/null 2>&1${l} &`,"srt_http_proxy_pid=$!",`${u} TCP4-LISTEN:1080,bind=127.0.0.1,fork,reuseaddr ${It([`UNIX-CONNECT:${t}`])} >/dev/null 2>&1${l} &`,"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((d)=>`{ true <>/dev/tcp/127.0.0.1/${d}; } 2>/dev/null || { ${u} -u OPEN:/dev/null TCP4:127.0.0.1:${d},connect-timeout=0.1,retry=480,interval=0.005 >/dev/null 2>&1${l} & 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; }`],p=r===void 0&&s!==void 0?`{ ${O0(s)}; trap '' INT QUIT; exec ${a?n:It([c,"-c",n])}; }`:(r??"")+It(Wu(c,n,s));return[...f,`${p} <&0 &`,"srt_payload_pid=$!",'wait "$srt_payload_pid"',"srt_payload_status=$?","srt_payload_pid=",'exit "$srt_payload_status"'].join(`
91
+ `)}function qs(e){try{if(K.lstatSync(e).isSymbolicLink())return K.realpathSync(e)}catch{}return e}function R0(e,t,n,r){let i=t==="/"?"/":t+"/";e.push("--tmpfs",t);for(let o of n)if(o.startsWith(i)||o===t)e.push("--bind",o,o),w(`[Sandbox Linux] Re-bound write path wiped by denyRead tmpfs: ${o}`);for(let o of r)if(o.startsWith(i)||o===t){if(!K.existsSync(o)){w(`[Sandbox Linux] Skipping non-existent read allow path: ${o}`);continue}if(n.some((s)=>(s.startsWith(i)||s===t)&&(o===s||o.startsWith(s+"/"))))continue;e.push("--ro-bind",o,o),w(`[Sandbox Linux] Re-allowed read access within denied region: ${o}`)}}async function ST(e,t,n,r,i={command:"rg"},o=Hu,s=!1,a,c,u=[]){let l=[],f=[],p=[],h=new Set,d=new Map,g=new Map;if(t){l.push("--ro-bind","/","/");for(let W of t.allowOnly||[]){let te=Ye(W).replace(/\/+$/,"")||"/";if(w(`[Sandbox Linux] Processing write path: ${W} -> ${te}`),te.startsWith("/dev/")){w(`[Sandbox Linux] Skipping /dev path: ${te}`);continue}if(!K.existsSync(te)){w(`[Sandbox Linux] Skipping non-existent write path: ${te}`);continue}try{let J=K.realpathSync(te),ce=te.replace(/\/+$/,"");if(J!==ce&&Do(te,J)){w(`[Sandbox Linux] Skipping symlink write path pointing outside expected location: ${W} -> ${J}`);continue}}catch{w(`[Sandbox Linux] Skipping write path that could not be resolved: ${te}`);continue}l.push("--bind",te,te),f.push(te)}let D,F=()=>{if(D!==void 0)return D;let W=[];for(let J of f){W.push(J);try{let ce=K.realpathSync(J);if(ce!==J)W.push(ce)}catch{}}let te=[];if(e){let J=[],ce=new Set(["proc","dev","sys"]);for(let ae of e.denyOnly||[])if(Ye(ae)==="/")try{for(let ee of K.readdirSync("/"))if(!ce.has(ee))J.push("/"+ee)}catch{}else J.push(ae);if(K.existsSync("/etc/ssh/ssh_config.d"))J.push("/etc/ssh/ssh_config.d");for(let ae of J){let ee=Ye(ae),Ee=!1;try{Ee=K.statSync(ee).isDirectory()}catch{continue}if(!Ee)continue;te.push(ee);try{let $e=K.realpathSync(ee);if($e!==ee)te.push($e)}catch{}}}return D={allowedWritePathsBothForms:W,prospectiveReadDenyTmpfsDirsBothForms:te},D},H=(W)=>f.some((te)=>W.startsWith(te+"/")||W===te),re=[...t.denyWithinAllow||[],...await fT(i,o,s,a)];m0();let se=new Set;for(let W of re){let te=Ye(W);if(te.startsWith("/dev/"))continue;let J=A0(te);if(J===null||J.startsWith("/dev/"))continue;if(Vu(J,f))continue;let ce=!1;try{ce=K.statSync(J).isDirectory()}catch{continue}if(!ce)continue;if(H(J)){let ae=d.get(J);if(ae===void 0)ae=new Set,d.set(J,ae);ae.add(te)}}let Pe=new Map,ue=(W)=>{let te=Pe.get(W);if(te!==void 0)return te;let{allowedWritePathsBothForms:J,prospectiveReadDenyTmpfsDirsBothForms:ce}=F(),ae=J.some((ee)=>ee.startsWith(W+"/"))||ce.some((ee)=>ee===W||ee.startsWith(W+"/"))||ce.some((ee)=>[W,...d.get(W)??[]].some((Ee)=>Ee===ee||Ee.startsWith(ee+"/")));return Pe.set(W,ae),ae},de=[...d.keys()];for(let W of re){let te=Ye(W);if(te.startsWith("/dev/"))continue;let J=A0(te);if(J===null){let ee=Vu(te,f);if(ee&&!se.has(ee))se.add(ee),p.push("--ro-bind","/dev/null",ee),g.set(ee,te);w(`[Sandbox Linux] Deny path could not be resolved through symlinks, failing closed: ${te}`);continue}if(J!==te)w(`[Sandbox Linux] Resolved symlinked deny path: ${te} -> ${J}`);if(J.startsWith("/dev/"))continue;if(se.has(J))continue;se.add(J);let ce=Vu(J,f);if(ce){if(!se.has(ce))se.add(ce),p.push("--ro-bind","/dev/null",ce),g.set(ce,te);w(`[Sandbox Linux] Mounted /dev/null at symlink ${ce} to prevent symlink replacement attack`);continue}if(!K.existsSync(J)){if(uT(J)){w(`[Sandbox Linux] Skipping deny path with file ancestor (cannot create paths under a file): ${J}`);continue}let ee=ke.dirname(J);while(ee!=="/"&&!K.existsSync(ee))ee=ke.dirname(ee);let Ee=H(ee)||H(J),$e=de.filter((ye)=>ee===ye||ee.startsWith(ye+"/")),qe=$e.length>0&&!$e.some(ue);if(Ee&&!qe){let ye=lT(J),oe=C0(ye,f)??ye;if(oe!==J){if(!h.has(oe)){let Oe=E0(oe,c),_e=K.mkdtempSync(ke.join(Xs(),"claude-empty-"));if(K.chmodSync(_e,365),io.add(_e),p.push("--ro-bind",_e,oe),g.set(oe,te),h.add(oe),Oe.kind==="unregistered")no.add(oe);Gs(),w(`[Sandbox Linux] Mounted empty dir at ${oe} to block creation of ${J}`)}}else{let Oe=Fu(oe),_e=k0(J,te);if(Oe.kind==="masked")p.push("--ro-bind",_e,oe),g.set(oe,te),Gs(),w(`[Sandbox Linux] Masked shared stub at ${oe} with ${_e} to block creation of ${J}`);else if(Oe.kind==="real")p.push("--ro-bind",oe,oe),g.set(oe,te);else p.push("--ro-bind",_e,oe),g.set(oe,te),no.add(oe),Gs(),w(`[Sandbox Linux] Mounted ${_e} at ${oe} to block creation of ${J}`)}}else if(qe)w(`[Sandbox Linux] Skipping non-existent deny path inside a read-only denied directory (already uncreatable): ${J}`);else w(`[Sandbox Linux] Skipping non-existent deny path not within allowed paths: ${J}`);continue}if(H(J)){if((vT(J)?Fu(J):void 0)?.kind==="masked")p.push("--ro-bind",k0(J,te),J),Gs();else p.push("--ro-bind",J,J);g.set(J,te)}else w(`[Sandbox Linux] Skipping deny path not within allowed paths: ${J}`)}}else l.push("--bind","/","/");let v=[],b=(e?.allowWithinDeny||[]).map((D)=>Ye(D)),S=new Map,C=[],T=new Set(["proc","dev","sys"]);for(let D of e?.denyOnly||[])if(Ye(D)==="/"){for(let F of K.readdirSync("/"))if(!T.has(F))v.push("/"+F)}else v.push(D);if(e&&K.existsSync("/etc/ssh/ssh_config.d"))v.push("/etc/ssh/ssh_config.d");let I=v.map((D)=>Ye(D)).sort((D,F)=>D.split("/").length-F.split("/").length);for(let D of I){if(!K.existsSync(D)){w(`[Sandbox Linux] Skipping non-existent read deny path: ${D}`);continue}if(K.statSync(D).isDirectory())C.push(D),R0(l,D,f,b);else{if(b.includes(D)){w(`[Sandbox Linux] Skipping read deny for re-allowed path: ${D}`);continue}let H=qs(D);l.push("--ro-bind","/dev/null",H),S.set(H,"/dev/null"),S.set(D,"/dev/null")}}for(let{realPath:D,fakePath:F}of n??[]){let H=qs(D);l.push("--ro-bind",F,H),S.set(H,F),S.set(D,F)}let k=(D)=>C.some((F)=>{if(!(D===F||D.startsWith(F+"/")))return!1;return!f.some((se)=>(se===F||se.startsWith(F+"/"))&&(D===se||D.startsWith(se+"/")))}),R=[...h].filter((D)=>{let F=g.get(D)??D;return!S.has(D)&&!k(D)&&!k(F)&&!f.some((H)=>H===D||H.startsWith(D+"/"))}),V=[];for(let D=0;D<p.length;D+=3){let F=p[D+2],H=g.get(F)??F;if(S.has(F))continue;if(k(F)||k(H)){w(`[Sandbox Linux] Skipping denyWrite bind already hidden by denyRead tmpfs: ${F}`);continue}if(R.some((re)=>F.startsWith(re+"/"))){w(`[Sandbox Linux] Skipping denyWrite bind under an empty-directory mask: ${F}`);continue}if(l.push(p[D],p[D+1],F),V.push(F),p[D+1]!==F)u.push(F);if(H!==F)V.push(H)}for(let D of C)if(V.some((F)=>D.startsWith(F+"/")))w(`[Sandbox Linux] Re-applying denyRead tmpfs re-exposed by denyWrite bind: ${D}`),R0(l,D,f,b);for(let[D,F]of S)if(V.some((H)=>D.startsWith(H+"/"))){if(qs(D)!==D)continue;w(`[Sandbox Linux] Re-applying file mask re-exposed by denyWrite bind: ${D}`),l.push("--ro-bind",F,D)}if(r!==void 0)l.push("--ro-bind",r,r);return l}async function L0(e){let{command:t,commandId:n,needsNetworkRestriction:r,httpSocketPath:i,socksSocketPath:o,httpProxyPort:s,socksProxyPort:a,proxyAuthToken:c,caCertPath:u,readConfig:l,writeConfig:f,unsetEnvVars:p,setEnvVars:h,maskedFileBinds:d,maskedFileStoreDir:g,enableWeakerNestedSandbox:v,runAsUid:b,runAsGid:S,runAsHostUid:C,runAsHostGid:T,runAsHostHome:I,runAsHostUser:k,setprivPath:R,allowAllUnixSockets:V,binShell:D,ripgrepConfig:F={command:"rg"},mandatoryDenySearchDepth:H=Hu,allowGitConfig:re=!1,gitSafeDirectories:se,seccompConfig:Pe,bwrapPath:ue,socatPath:de,observeSocketPath:W,startFd:te,argvCommand:J,abortSignal:ce}=e,ae=l&&l.denyOnly.length>0||d!==void 0&&d.length>0,ee=f!==void 0,Ee=p!==void 0&&p.length>0||h!==void 0&&Object.keys(h).length>0,$e=(se?.length??0)>0;if(!r&&!ae&&!ee&&!Ee&&!$e)return t;Dr++;let qe=[],ye=["--new-session","--die-with-parent"],oe=new Map,Oe=[],_e,it=!1;try{if(!V)if(_e=xT(Pe?.applyPath,Pe?.argv0),!_e)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 w("[Sandbox Linux] Applying seccomp filter for Unix socket blocking");else w("[Sandbox Linux] Skipping seccomp filter - allowAllUnixSockets is enabled");if(W&&_e)if(K.existsSync(W))Oe.push("--bind",W,W),oe.set("SRT_OBSERVE_SOCK",W),oe.set("SRT_ENCODED_CMD",zt(n??t));else w("[Sandbox Linux] observe socket missing \u2014 supervisor not running; "+"continuing without violation monitoring");if(Ee)for(let[Ut,cr]of Object.entries(h??{}))oe.set(Ut,cr);if(se&&se.length>0){let Ut=Oo({safeDirs:se,unsetEnvVars:p,setEnvVars:h});for(let[cr,Ro]of Object.entries(Ut))oe.set(cr,Ro)}if(r){if(ye.push("--unshare-net"),i&&o){if(!K.existsSync(i))throw Error(`Linux HTTP bridge socket does not exist: ${i}. The bridge process may have died. Try reinitializing the sandbox.`);if(!K.existsSync(o))throw Error(`Linux SOCKS bridge socket does not exist: ${o}. The bridge process may have died. Try reinitializing the sandbox.`);if(Oe.push("--bind",i,i),o!==i)Oe.push("--bind",o,o);it=!0;let Ut=Dn(3128,1080,u,c,f===void 0,zt(n??t));for(let cr of Ut){let Ro=cr.indexOf("=");oe.set(cr.slice(0,Ro),cr.slice(Ro+1))}if(s!==void 0)oe.set("CLAUDE_CODE_HOST_HTTP_PROXY_PORT",String(s));if(a!==void 0)oe.set("CLAUDE_CODE_HOST_SOCKS_PROXY_PORT",String(a))}}let rt=await ST(l,f,d,g,F,H,re,ce,C===void 0?void 0:{uid:C,gid:T??C},qe);js(),ye.push(...rt);let ot=yT(qe,process.cwd());if(ot!==void 0)oe.set(mT,ot);if(ye.push(...Oe),it){let Ut=hT(l?.denyOnly??[],(d??[]).flatMap(({realPath:cr})=>[cr,qs(cr)]));if(Ut)ye.push("--ro-bind",Ut,ro)}if(ye.push("--dev","/dev"),ye.push("--unshare-pid"),!v){if(ye.push("--unshare-user","--cap-drop","ALL","--proc","/proc"),!_e)ye.push("--ro-bind","/dev/null","/proc/sysrq-trigger")}else ye.push("--unshare-user","--bind","/proc","/proc");if(b!==void 0)ye.push("--uid",String(b)),ye.push("--gid",String(S??b));if(C!==void 0){if(I)oe.set("HOME",I);if(k)oe.set("USER",k),oe.set("LOGNAME",k)}let st=D||"bash",Xe=Nr(st);if(!Xe)throw Error(`Shell '${st}' not found in PATH`);if(ye.push("--",Xe,"-c"),r&&i&&o){let Ut=bT(i,o,t,_e,Xe,de,te,J);ye.push(Ut)}else if(_e){let Ut=_e+It(Wu(Xe,t,te));ye.push(Ut)}else ye.push(te===void 0?t:`exec ${It(Wu(Xe,t,te))}`);let at=[ue??"bwrap",...ye],Ub=It(aT({bwrapCommand:at,uid:C,gid:T,setprivPath:R,unsetEnvVars:p,setEnvVars:Object.fromEntries(oe)})),wi=[];if(r)wi.push("network");if(ae||ee)wi.push("filesystem");if(Ee)wi.push("env");if(_e)wi.push("seccomp(unix-block)");return w(`[Sandbox Linux] Wrapped command with bwrap (${wi.join(", ")} restrictions)`),Ub}catch(rt){if(Dr>0)Dr--;if(js(),Dr===0)Mu([],()=>{});throw rt}}import{spawn as CT}from"child_process";import*as $r from"path";class Ys{violations=[];totalCount=0;maxSize=100;listeners=new Set;addViolation(e){if(this.violations.push({...e,line:Ku(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=zt(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 li(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,o]of Object.entries(n))if(i!=="*"&&t.includes(i)&&o.some((s)=>e.includes(s)))return!0;return!1}function Ku(e){return e.replace(/[\x00-\x1f\x7f-\x9f]+/g," ").trim()}function wT(e=!1){let t=process.cwd(),n=[];for(let r of _i)n.push($r.resolve(t,r)),n.push(`**/${r}`);for(let r of $o())n.push($r.resolve(t,r)),n.push(`**/${r}/**`);if(n.push($r.resolve(t,".git/hooks")),n.push("**/.git/hooks/**"),!e)n.push($r.resolve(t,".git/config")),n.push("**/.git/config");return[...new Set(n)]}var U0=`_${Math.random().toString(36).slice(2,11)}_SBX`;function ET(e){return`CMD64_${zt(e)}_END_${U0}`}function fi(e){return bt(e)?`(regex ${ir(Ii(e))})`:`(subpath ${ir(e)})`}function qu(e){return Ii(e).slice(0,-1)+"(/.*)?$"}function Cn(e){return bt(e)?`(regex ${ir(qu(e))})`:`(subpath ${ir(e)})`}function z0(e){return e.replace(/\[[^\]]*\]|[*?]+/g,"x")}function ju(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 Zu(e){let t=Ye(e);return{path:t,glob:bt(t)}}function F0(e,t){return e.test(t.glob?z0(t.path):t.path)}function ea(e,t){let n=e.glob?z0(e.path):e.path;return n.startsWith(t==="/"?"/":t+"/")&&n!==t}function _T(e,t){return{denies:(e.denyOnly||[]).map(Zu),allows:(e.allowWithinDeny||[]).map(Zu),writeRoots:(t||[]).map(Zu)}}function TT(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((a)=>i.path.startsWith(a+"/")))t.push(Cn(i.path));continue}let o=new RegExp(qu(i.path));if(o.test("/"))n=!0;let s=e.allows.filter((a)=>F0(o,a)).map((a)=>fi(a.path));t.push(ju(Cn(i.path),s))}return{filters:t,coversRoot:n}}function M0(e){let t=e.split(/[*?[\]]/)[0];if(!t||t==="/")return"/";return t.endsWith("/")?t.slice(0,-1):$r.dirname(t)}function AT(e,t){let{denies:n,allows:r,writeRoots:i}=e;if(i.length===0)return[];let o=i.filter((f)=>f.glob).map((f)=>new RegExp(Ii(f.path))),s=i.filter((f)=>!f.glob).map((f)=>f.path),a=(f)=>s.some((p)=>ea({path:f,glob:!1},p))||o.some((p)=>p.test(f)),c=(f)=>[...r,...i].filter((p)=>ea(p,f)).map((p)=>fi(p.path)),u=new Set,l=(f)=>{for(let p of f)if(a(p))u.add(`(literal ${ir(p)})`)};for(let f of n)if(f.glob){let p=M0(f.path);if(!(o.length>0||s.some((v)=>p===v||ea({path:p,glob:!1},v)||ea({path:v,glob:!1},p))))continue;let d=new RegExp(qu(f.path)),g=[...r,...i].filter((v)=>F0(d,v)).map((v)=>fi(v.path));if(u.add(ju(Cn(f.path),g)),p!=="/")l([p,...Gu(p)])}else{if(!a(f.path))continue;u.add(ju(Cn(f.path),c(f.path))),l(Gu(f.path))}return Jr("deny",["file-write-unlink"],u,t)}function Jr(e,t,n,r){if(n.size===0)return[];return[`(${e} ${t.join(" ")}`,...[...n].map((i)=>` ${i}`),` (with message "${r}"))`]}function Gu(e){let t=[],n=$r.dirname(e);while(n!=="/"&&n!=="."){t.push(n);let r=$r.dirname(n);if(r===n)break;n=r}return t}function V0(e,t){let n=new Set;for(let r of e){let i=Ye(r);n.add(Cn(i));let o;if(bt(i)){if(o=M0(i),o==="/")continue;n.add(`(literal ${ir(o)})`)}else o=i;for(let s of Gu(o))n.add(`(literal ${ir(s)})`)}return Jr("deny",["file-write-unlink","file-write-create"],n,t)}function kT(e,t){if(!e)return["(allow file-read*)"];let n=[];n.push("(allow file-read*)");let r=e.denies.some((c)=>c.path==="/"),i=new Set(e.denies.map((c)=>Cn(c.path)));n.push(...Jr("deny",["file-read*"],i,t));let o=new Set(e.allows.map((c)=>fi(c.path)));n.push(...Jr("allow",["file-read*"],o,t));let s=TT(e);if(n.push(...Jr("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(...V0(e.denies.map((c)=>c.path),t));let a=new Set(e.writeRoots.map((c)=>fi(c.path)));return n.push(...Jr("allow",["file-write-unlink","file-write-create"],a,t)),n}function IT(e,t,n=!1){if(!e)return["(allow file-write*)"];let r=[],i=new Set;for(let a of e.allowOnly||[])i.add(fi(Ye(a)));r.push(...Jr("allow",["file-write*"],i,t));let o=[...e.denyWithinAllow||[],...wT(n)],s=new Set;for(let a of o)s.add(Cn(Ye(a)));return r.push(...Jr("deny",["file-write*"],s,t)),r.push(...V0(o,t)),r}function PT({readConfig:e,writeConfig:t,httpProxyPort:n,socksProxyPort:r,needsNetworkRestriction:i,allowUnixSockets:o,allowAllUnixSockets:s,allowLocalBinding:a,allowMachLookup:c,allowPty:u,allowGitConfig:l=!1,enableWeakerNetworkIsolation:f=!1,allowAppleEvents:p=!1,logTag:h}){let d=["(version 1)",`(deny default (with message "${h}"))`,"",`; LogTag: ${h}`,"","; 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")',")","",...f?["; trustd.agent - needed for Go TLS certificate verification (weaker network isolation)",'(allow mach-lookup (global-name "com.apple.trustd.agent"))']:[],...p?["; 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"))']:[],...c&&c.length>0?["; User-specified XPC/Mach services",...c.map((v)=>v.endsWith("*")?`(allow mach-lookup (global-name-prefix ${ir(v.slice(0,-1))}))`:`(allow mach-lookup (global-name ${ir(v)}))`)]:[],"","; 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(d.push("; Network"),!i)d.push("(allow network*)");else{if(a)d.push('(allow network-bind (local ip "*:*"))'),d.push('(allow network-inbound (local ip "*:*"))'),d.push('(allow network-outbound (remote ip "localhost:*"))');if(s)d.push("(allow system-socket (socket-domain AF_UNIX))"),d.push('(allow network-bind (local unix-socket (path-regex #"^/")))'),d.push('(allow network-outbound (remote unix-socket (path-regex #"^/")))');else if(o&&o.length>0){d.push("(allow system-socket (socket-domain AF_UNIX))");for(let v of o){let b=Ye(v);d.push(`(allow network-bind (local unix-socket (subpath ${ir(b)})))`),d.push(`(allow network-outbound (remote unix-socket (subpath ${ir(b)})))`)}}if(n!==void 0)d.push(`(allow network-bind (local ip "localhost:${n}"))`),d.push(`(allow network-inbound (local ip "localhost:${n}"))`),d.push(`(allow network-outbound (remote ip "localhost:${n}"))`);if(r!==void 0&&r!==n)d.push(`(allow network-bind (local ip "localhost:${r}"))`),d.push(`(allow network-inbound (local ip "localhost:${r}"))`),d.push(`(allow network-outbound (remote ip "localhost:${r}"))`)}d.push("");let g=e?_T(e,t?.allowOnly):void 0;if(d.push("; File read"),d.push(...kT(g,h)),d.push(""),d.push("; File write"),d.push(...IT(t,h,l)),g){let v=AT(g,h);if(v.length>0)d.push(""),d.push("; File read: keep read-denied paths inside write roots in place"),d.push(...v)}if(u)d.push(""),d.push("; Pseudo-terminal (pty) support"),d.push("(allow pseudo-tty)"),d.push("(allow file-ioctl"),d.push(' (literal "/dev/ptmx")'),d.push(' (regex #"^/dev/ttys")'),d.push(")"),d.push("(allow file-read* file-write*"),d.push(' (literal "/dev/ptmx")'),d.push(' (regex #"^/dev/ttys")'),d.push(")");return d.join(`
92
+ `)}function ir(e){return JSON.stringify(e)}function W0(e){let{command:t,commandId:n,needsNetworkRestriction:r,httpProxyPort:i,socksProxyPort:o,proxyAuthToken:s,caCertPath:a,allowUnixSockets:c,allowAllUnixSockets:u,allowLocalBinding:l,allowMachLookup:f,readConfig:p,writeConfig:h,unsetEnvVars:d,setEnvVars:g,maskedFileBinds:v,allowPty:b,allowGitConfig:S=!1,gitSafeDirectories:C,enableWeakerNetworkIsolation:T=!1,allowAppleEvents:I=!1,binShell:k}=e,R=p;if(v&&v.length>0)w("[Sandbox macOS] file mask degrades to deny on macOS until the interposer lands"),R={denyOnly:[...p?.denyOnly??[],...v.map((ae)=>ae.realPath)],allowWithinDeny:p?.allowWithinDeny};let V=R&&R.denyOnly.length>0,D=h!==void 0,F=d!==void 0&&d.length>0||g!==void 0&&Object.keys(g).length>0,H=(C?.length??0)>0;if(!r&&!V&&!D&&!F&&!H)return t;let re=n??t,se=ET(re),Pe=PT({readConfig:R,writeConfig:h,httpProxyPort:i,socksProxyPort:o,needsNetworkRestriction:r,allowUnixSockets:c,allowAllUnixSockets:u,allowLocalBinding:l,allowMachLookup:f,allowPty:b,allowGitConfig:S,enableWeakerNetworkIsolation:T,allowAppleEvents:I,logTag:se}),ue=Dn(i,o,a,s,h===void 0,zt(re));if(l&&r){let Ee=(d??[]).includes("JAVA_TOOL_OPTIONS")?"":process.env.JAVA_TOOL_OPTIONS??"",$e=Ee.includes("-Djava.net.preferIPv4Stack=true")?Ee:[Ee,"-Djava.net.preferIPv4Stack=true"].filter(Boolean).join(" ");ue.push(`JAVA_TOOL_OPTIONS=${$e}`)}if(C&&C.length>0){let ae=Oo({safeDirs:C,unsetEnvVars:d,setEnvVars:g});for(let[ee,Ee]of Object.entries(ae))ue.push(`${ee}=${Ee}`)}let de=k||"bash",W=Nr(de);if(!W)throw Error(`Shell '${de}' not found in PATH`);let te=(d??[]).flatMap((ae)=>["-u",ae]),J=Object.entries(g??{}).map(([ae,ee])=>`${ae}=${ee}`),ce=It(["env",...te,...J,...ue,"/usr/bin/sandbox-exec","-p",Pe,W,"-c",t]);return w(`[Sandbox macOS] Applied restrictions - network: ${!!(i||o)}, read: ${R?"allowAllExcept"in R?"allowAllExcept":"denyAllExcept":"none"}, write: ${h?"allowAllExcept"in h?"allowAllExcept":"denyAllExcept":"none"}`),ce}function H0(e,t,n=(r)=>r){let r=/CMD64_(.+?)_END/,i=/Sandbox:\s+(.+)$/,o=CT("log",["stream","--predicate",`(eventMessage ENDSWITH "${U0}")`,"--style","compact"]);return o.stdout?.on("data",(s)=>{let a=s.toString().split(`
93
+ `),c=a.find((d)=>d.includes("Sandbox:")&&d.includes("deny")),u=a.find((d)=>d.startsWith("CMD64_"));if(!c)return;let l=c.match(i);if(!l?.[1])return;let f=l[1],p,h;if(u){if(h=u.match(r)?.[1],h)try{p=n(cn(h))}catch{}}if(f.includes("mDNSResponder")||f.includes("mach-lookup com.apple.diagnosticd")||f.includes("mach-lookup com.apple.analyticsd"))return;if(li(f,p,t))return;e({line:f,command:p,encodedCommand:h,timestamp:new Date})}),o.stderr?.on("data",(s)=>{w(`[Sandbox Monitor] Log stream stderr: ${s.toString()}`)}),o.on("error",(s)=>{w(`[Sandbox Monitor] Failed to start log stream: ${s.message}`)}),o.on("exit",(s)=>{w(`[Sandbox Monitor] Log stream exited with code: ${s}`)}),()=>{w("[Sandbox Monitor] Stopping log monitor"),o.kill("SIGTERM")}}import{randomBytes as RT}from"crypto";import{chmodSync as K0,chownSync as BT,mkdtempSync as NT,rmSync as DT}from"fs";import{createServer as $T}from"net";import{tmpdir as OT}from"os";import{join as Z0,posix as LT}from"path";import{createInterface as UT}from"readline";function j0(e,t){let{allowWritePaths:n,denyWritePaths:r,ignoreViolations:i,resolveCommandText:o=(C)=>C,consumerUid:s,consumerGid:a}=t,c=NT(Z0(OT(),"srt-obs-")),u=Z0(c,`s${RT(4).toString("hex")}.sock`),l=(C,T)=>C===T||C.startsWith(T.endsWith("/")?T:T+"/"),f=(C)=>{let T=LT.normalize(C);if(r.some((I)=>l(T,I)))return!0;return!n.some((I)=>l(T,I))},p=(C,T)=>{if(C.observe_init_error){w(`[Sandbox Linux Monitor] observe filter not installed: ${C.observe_init_error}`);return}if(typeof C.path!=="string")return;if(!C.path.startsWith("/"))return;if(!f(C.path))return;let I;if(T)try{I=o(cn(T))}catch{}if(li(C.path,I,i))return;let k={line:`deny ${C.syscall??"syscall"} ${C.path}`,command:I,encodedCommand:T,timestamp:new Date};e(k)},h,d=new Promise((C)=>{h=C}),g=u,v=$T((C)=>{let T,I=UT({input:C});I.on("line",(k)=>{if(!k)return;let R;try{R=JSON.parse(k)}catch{return}if(R.encodedCommand&&T===void 0)T=R.encodedCommand;p(R,T??R.encodedCommand)}),C.on("error",()=>I.close()),C.on("close",()=>I.close())});v.on("error",(C)=>{w(`[Sandbox Linux Monitor] listen failed: ${C.message} - violation monitoring disabled`,{level:"warn"}),g=void 0,h()}),v.listen(u,()=>{if(s!==void 0)K0(c,457),BT(u,s,a??s),K0(u,384);h()});let b=new Set;return v.on("connection",(C)=>{b.add(C),C.on("close",()=>b.delete(C))}),{get observeSocketPath(){return g},ready:d,stop:()=>{w("[Sandbox Linux Monitor] stopping");for(let C of b)C.destroy();v.close();try{DT(c,{recursive:!0,force:!0})}catch{}}}}import*as tt from"fs";import*as J0 from"net";import*as et from"path";import{spawn as zT,spawnSync as FT}from"child_process";import{once as MT}from"events";import{fileURLToPath as VT}from"url";class me extends Error{code;subcommand;constructor(e,t,n){super(t);this.name="WindowsSandboxError",this.code=e,this.subcommand=n}}var ta=[60080,60089],G0=["-NoProfile","-Command"];function ra(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 me("bin_shell_invalid",`binShell.exe must be an absolute path (got ${JSON.stringify(e.exe)})`);if(!Array.isArray(e.args))throw new me("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(),o=et.win32.isAbsolute(e);if(!o&&e!==r)throw new me("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(!o)throw new me("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:o?e:"pwsh.exe",args:G0};case"powershell":case"powershell.exe":return{exe:o?e:et.win32.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe"),args:G0};case"cmd":case"cmd.exe":return o?{exe:e,args:n.args}:n;default:throw new me("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 Q0(){let e=et.dirname(VT(import.meta.url));return et.resolve(e,"..","..")}var Y0={x64:"x64",arm64:"arm64"},WT=et.join(Q0(),"vendor","srt-win",Y0[process.arch]??process.arch,"srt-win.exe");function HT(){let e=Q0(),t=Y0[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 me("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 em="--srt-win";function Nt(e){if(e?.path===void 0)throw new me("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 me("srt_win_not_found",`windows.srtWin.path is set to '${e.path}' but the file does not exist`);return{exe:e.path,prependArgs:[em]}}function di(e,t={}){let{exe:n,prependArgs:r}=t.srtWin??Nt(),i=FT(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 me("srt_win_timeout",`srt-win ${e.join(" ")} timed out after ${t.timeoutMs??15000}ms`+(i.signal?` (killed by ${i.signal})`:""),e[0]);throw new me("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 oo(e,t={}){let{exe:n,prependArgs:r}=t.srtWin??Nt(),i=t.timeoutMs??15000;return new Promise((o,s)=>{let a=zT(n,[...r,...e],{windowsHide:!0}),c=!1,u=i>0?setTimeout(()=>{c=!0,a.kill()},i):void 0,l="",f="";a.stdout?.setEncoding("utf8").on("data",(p)=>l+=p),a.stderr?.setEncoding("utf8").on("data",(p)=>f+=p),a.stdin?.on("error",()=>{}).end(t.stdin),a.once("error",(p)=>{clearTimeout(u),s(new me("spawn_failed",`srt-win ${e[0]}: spawn failed: ${p.message}`,e[0]))}),a.once("close",(p,h)=>{if(clearTimeout(u),c){s(new me("srt_win_timeout",`srt-win ${e.join(" ")} timed out after ${i}ms`+(h?` (killed by ${h})`:"")+KT(f),e[0]));return}o({status:p,signal:h,stdout:l.trim(),stderr:f.trim()})})})}function KT(e){let t=e.trim().split(/\r?\n/).pop()?.trim();return t?`; last output: ${t.slice(0,300)}`:""}function tm(e,t){if(t.status!==0)throw new me("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 me("srt_win_bad_json",`srt-win ${e.join(" ")}: unparseable JSON output ${JSON.stringify(t.stdout)}: ${n.message}`,e[0])}}function Ju(e,t){return tm(e,di(e,t))}async function Qu(e,t){return tm(e,await oo(e,t))}async function rm(e,t){let n=await oo(e,t),r;try{r=JSON.parse(n.stdout)}catch(i){throw new me("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 nm(e){let t=["wfp","status"];if(e)t.push("--sublayer-guid",e);return t}function na(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 ia(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 im(e={}){let t=["status"];if(e.sublayerGuid)t.push("--sublayer-guid",e.sublayerGuid);let n=Ju(t,{srtWin:e.srtWin});return{user:ia(n.user),wfp:na(n.wfp)}}async function om(e={}){let t=["status"];if(e.sublayerGuid)t.push("--sublayer-guid",e.sublayerGuid);let n=await Qu(t,{srtWin:e.srtWin});return{user:ia(n.user),wfp:na(n.wfp)}}function sm(e={}){return na(Ju(nm(e.sublayerGuid),{srtWin:e.srtWin}))}async function am(e={}){return na(await Qu(nm(e.sublayerGuid),{srtWin:e.srtWin}))}async function Yu(e={}){let t=e.target,n;if(!t){let[r,i]=e.proxyPortRange??ta;for(let o=0;o<5;o++){let s=J0.createServer();s.listen(0,"127.0.0.1"),await MT(s,"listening");let a=s.address().port;if(a<r||a>i){n=s,t=`127.0.0.1:${a}`;break}s.close()}if(!t)throw new me("wfp_verify_bind_failed",`verifyWindowsWfpEgress: could not bind a loopback listener outside the WFP permit range [${r},${i}] in 5 attempts`)}try{let r=di(["wfp","verify","--target",t],{timeoutMs:30000,srtWin:e.srtWin});w(`[Sandbox Windows] wfp verify exit=${r.status}: ${r.stderr||r.stdout}`);let i;try{i=JSON.parse(r.stdout)}catch{throw new me("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 me("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 me("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 el(e={}){return ia(Ju(["user","status"],{srtWin:e.srtWin}))}async function so(e={}){return ia(await Qu(["user","status"],{srtWin:e.srtWin}))}function tl(e,t={}){let n=e??el(t);if(!n.caCertThumb||!n.caCertPem)return null;return{pem:n.caCertPem,thumb:n.caCertThumb}}function ZT(e,t={}){let n=di(["user","trust-ca",e],{timeoutMs:60000,srtWin:t.srtWin});um(e,n)}async function cm(e,t={}){let n=await oo(["user","trust-ca",e],{timeoutMs:60000,srtWin:t.srtWin});um(e,n)}function um(e,t){if(w(`[Sandbox Windows] user trust-ca exit=${t.status}: ${t.stderr||t.stdout}`),t.status!==0)throw new me("trust_ca_failed",`srt-win user trust-ca '${e}' failed (exit ${t.status}): ${t.stderr||t.stdout}`)}function lm(){let e=process.env.ProgramData;if(!e)throw Error("ProgramData is not set");return et.win32.join(e,"sandbox-runtime")}async function rl(e={}){let t=e.status??await so({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:lm();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"),o=et.join(r,"cert.pem"),s=et.join(r,"key.pem"),a=(e.regenerateWithinDays??30)*24*60*60*1000,c=(v,b)=>{let S=`${v}.tmp.${process.pid}`;tt.writeFileSync(S,b),tt.renameSync(S,v)},u=async(v,b,S,C)=>{c(o,v),c(s,b);let T=C||t.caCertThumb!==S;if(T){let I=et.join(r,`.trust.${process.pid}.${Date.now()}.pem`);tt.writeFileSync(I,v);try{await cm(I,{srtWin:e.srtWin})}finally{tt.rmSync(I,{force:!0})}}return w(`[Sandbox Windows] persistent CA ${C?"generated":"reused"} (thumb=${S}${T&&!C?", trust reconciled":""})`),{certPem:v,keyPem:b,certPath:o,keyPath:s,thumbprint:S,generated:C,trusted:T}},l=()=>{let v;try{v=JSON.parse(tt.readFileSync(i,"utf8"))}catch(S){w(`[Sandbox Windows] persistent CA ca.json unreadable (${S.message})`,{level:"warn"});return}if(typeof v.certPem!=="string"||typeof v.keyPem!=="string")return;let b=Zi(v.certPem,v.keyPem);if(!b.ok){w(`[Sandbox Windows] persistent CA invalid (${b.reason})`,{level:"warn"});return}return{certPem:v.certPem,keyPem:v.keyPem,thumbprint:b.thumbprint,notAfter:b.notAfter}};if(!e.force){let v=l();if(v&&v.notAfter.getTime()-Date.now()>a)return await u(v.certPem,v.keyPem,v.thumbprint,!1);if(v)w(`[Sandbox Windows] persistent CA expiring ${v.notAfter.toISOString()}; regenerating`,{level:"warn"})}tt.mkdirSync(r,{recursive:!0});try{let v=Date.now()-300000;for(let b of tt.readdirSync(r)){if(!b.includes(".tmp.")&&!b.startsWith(".trust."))continue;let S=et.join(r,b);if(tt.statSync(S).mtimeMs<v)tt.rmSync(S,{force:!0})}}catch{}let f=Cs({cn:"sandbox-runtime persistent CA"});c(i,JSON.stringify({certPem:f.certPem,keyPem:f.keyPem}));let p=l(),{certPem:h,keyPem:d,thumbprint:g}=p??{certPem:f.certPem,keyPem:f.keyPem,thumbprint:Yn(f.certPem)};return await u(h,d,g,!0)}function nl(e){return e.timeoutMs??120000}function fm(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 dm(e){if(e instanceof me&&e.code==="srt_win_timeout")throw new me("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 pm(e){if(w(`[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 me("install_wfp_failed",`srt-win install: WFP filter install failed: ${t}`);case 14:throw new me("install_user_failed",`srt-win install: sandbox user provisioning failed: ${t}`);case 13:throw new me("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 me("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 me("install_failed",`srt-win install failed (exit ${e.status}): ${t}`)}}function jT(e={}){let t=e.srtWin??Nt(),n;try{n=di(fm(e),{timeoutMs:nl(e),srtWin:t})}catch(i){dm(i)}pm(n);let r=im({sublayerGuid:e.sublayerGuid,srtWin:t});return n.status===10?{...r,cancelled:!0}:r}async function GT(e={}){let t=e.srtWin??Nt(),n;try{n=await oo(fm(e),{timeoutMs:nl(e),srtWin:t})}catch(i){dm(i)}pm(n);let r=await om({sublayerGuid:e.sublayerGuid,srtWin:t});return n.status===10?{...r,cancelled:!0}:r}function qT(e={}){let t=["uninstall"];if(e.sublayerGuid)t.push("--sublayer-guid",e.sublayerGuid);if(e.keepUser)t.push("--keep-user");let n=di(t,{timeoutMs:nl(e),srtWin:e.srtWin});if(w(`[Sandbox Windows] uninstall exit=${n.status}: ${n.stderr||n.stdout}`),n.status===10)return{cancelled:!0};if(n.status!==0)throw new me("uninstall_failed",`srt-win uninstall failed (exit ${n.status}): ${n.stderr||n.stdout}`);return{}}function oa(e,t){let n=new Set;for(let r of e){let i=Ye(r),o=Ti(i);if(Ai(i)&&!o){n.add(i);continue}let s=o?un(i,{caseInsensitive:!0}):[i];for(let a of s){if(!tt.statSync(a,{throwIfNoEntry:!1})){if(t?.mode==="deny"&&!o)n.add(/[\\/]$/.test(r)&&!/[\\/]$/.test(a)?a+"\\":a);continue}n.add(a)}}return[...n]}function XT(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 me("mapped_drive_cwd",r.message??"mapped/network-drive working directory","exec"),{drive:r.drive})}catch{}}return}var q0=60000;async function hm(e,t,n,r,i,o){let s=["acl",e,"--holder-pid",`${t}`,"--sandbox-user-sid",n];try{return await oo(s,{timeoutMs:q0,stdin:r,srtWin:o})}catch(a){if(!(a instanceof me)||a.code!=="srt_win_timeout")throw a;let c=i.slice(0,3).join(", "),u=i.length>3?` and ${i.length-3} more`:"";throw new me("srt_win_timeout",`srt-win acl ${e} did not finish within ${q0}ms on ${c||"no paths"}${u}. Another srt-win ACL change is holding the per-user ACL lock (a deny stamp or grant on a large folder, which rewrites every file below it), or one of these folders is that large. Use a smaller folder, or let the other change finish and try again. (${a.message})`,"acl")}}async function il(e){let t=e.holderPid??process.pid,n=JSON.stringify({denyRead:e.denyRead,denyWrite:e.denyWrite}),r=await hm("stamp",t,e.sandboxUserSid,n,[...e.denyRead,...e.denyWrite],e.srtWin);if(w(`[Sandbox Windows] acl stamp exit=${r.status}: ${r.stderr||r.stdout}`),r.status!==0)throw new me("acl_stamp_failed",`srt-win acl stamp exited ${r.status} `+(r.status===2?"(partial \u2014 some inputs skipped)":"(failed)")+`: ${r.stderr||r.stdout}`)}async function sa(e){let t=e.holderPid??process.pid;try{let n=await rm(["acl","restore","--holder-pid",`${t}`,"--sandbox-user-sid",e.sandboxUserSid,"--json"],{timeoutMs:60000,srtWin:e.srtWin});if(!n.ok)w(`[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){w(`[Sandbox Windows] acl restore: ${n.message}`,{level:"error"});return}}async function ol(e){let t=e.holderPid??process.pid,n=JSON.stringify({read:e.read,write:e.write}),r=await hm("grant",t,e.sandboxUserSid,n,[...e.write,...e.read],e.srtWin);if(w(`[Sandbox Windows] acl grant exit=${r.status}: ${r.stderr||r.stdout}`),r.status!==0)throw new me("acl_grant_failed",`srt-win acl grant exited ${r.status}: ${r.stderr||r.stdout}`)}async function aa(e){let t=e.holderPid??process.pid;try{let n=await rm(["acl","revoke","--holder-pid",`${t}`,"--sandbox-user-sid",e.sandboxUserSid,"--json"],{timeoutMs:60000,srtWin:e.srtWin});if(!n.ok)w(`[Sandbox Windows] acl revoke exited non-zero: ${n.stderr}`,{level:"error"});return n.json}catch(n){w(`[Sandbox Windows] acl revoke: ${n.message}`,{level:"error"});return}}function mm(e){let t=e.holderPid??process.pid;for(let n of["revoke","restore"])try{di(["acl",n,"--holder-pid",`${t}`,"--sandbox-user-sid",e.sandboxUserSid,"--json"],{timeoutMs:60000,srtWin:e.srtWin})}catch(r){w(`[Sandbox Windows] acl ${n} at exit: ${r.message}`,{level:"error"})}}function gm(e){let{exe:t,prependArgs:n}=e.srtWin??Nt(),r=JT(Dn(e.httpProxyPort,e.socksProxyPort,e.caCertPath?.replace(/\\/g,"/"),e.proxyAuthToken,void 0,zt(e.commandId??e.command)));delete r.TMPDIR,delete r.NO_PROXY,delete r.no_proxy;let i=ki({safeDirs:[e.cwd??process.cwd(),...e.allowWrite??[],...e.gitSafeDirectories??[]],schannelCa:e.caCertPath!==void 0,baseEnv:e.setEnvVars}),o=[t,...n,"exec"];if(e.quiet!==!1)o.push("--quiet");for(let l of e.denyRead??[])o.push("--deny-read",l);for(let l of e.denyWrite??[])o.push("--deny-write",l);let s={PATH:process.env.PATH,PATHEXT:process.env.PATHEXT,...e.setEnvVars??{},...r,...i};for(let[l,f]of Object.entries(s))if(f!==void 0)o.push("--env",`${l}=${f}`);o.push("--");let a=e.binShell??ra(void 0);o.push(a.exe,...a.args,e.command);let c=o.reduce((l,f)=>l+f.length+3,0);if(c>30000)throw new me("argv_too_long",`Windows sandbox argv is ~${c} chars (CreateProcessW limit is 32 767).`);let u={...process.env,...r};return{argv:o,env:u}}function JT(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 Xu(e){let t=e?` --sublayer-guid ${e}`:"";return`Windows sandbox needs a one-time install (one UAC prompt):
94
94
  npx sandbox-runtime windows-install
95
95
  `+" \u2014 or call installWindowsSandbox(), or run "+`\`srt-win.exe install${t}\` directly.
96
- No logout is needed: the WFP filter keys on the dedicated \`srt-sandbox\` user's SID, so your network is unaffected.`}function q0(e){try{return{status:"fulfilled",value:e()}}catch(t){return{status:"rejected",reason:t}}}function gm(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 o=t.value;if(!o.provisioned||!o.credPresent)r.push(`Sandbox user is not provisioned (user=${o.provisioned}, cred=${o.credPresent}). `+qu(e));let s=n();if(s.status==="rejected")return r.push(`srt-win wfp status failed: ${s.reason.message}`),{errors:r,warnings:i};let a=s.value;if(a.state==="cannot-read")w(`[Sandbox Windows] wfp status cannot-read (non-elevated): ${a.hint}`);else if(a.state!=="installed"){if(o.provisioned&&o.credPresent)r.push(`WFP filters not installed under sublayer ${e??"(default)"}. `+qu(e))}else if(a.portRange)w(`[Sandbox Windows] WFP installed: ${a.filters} filters, proxy port range ${a.portRange[0]}-${a.portRange[1]}`);return{errors:r,warnings:i}}function ym(e={}){let t;try{t=e.srtWin??Nt()}catch(n){return{errors:[n.message],warnings:[]}}return w(`[Sandbox Windows] using srt-win at ${t.exe}`),gm(e.sublayerGuid,q0(()=>Yu({srtWin:t})),()=>q0(()=>om({sublayerGuid:e.sublayerGuid,srtWin:t})))}async function ol(e={}){let t;try{t=e.srtWin??Nt()}catch(i){return{errors:[i.message],warnings:[]}}w(`[Sandbox Windows] using srt-win at ${t.exe}`);let[n,r]=await Promise.allSettled([oo({srtWin:t}),sm({sublayerGuid:e.sublayerGuid,srtWin:t})]);return gm(e.sublayerGuid,n,()=>r)}import{isIP as JT}from"net";function so(e){if(e.startsWith("[")){let r=e.indexOf("]");if(r===-1)return{hostPattern:e,port:void 0};let i=e.slice(1,r),o=vt(i)??i,s=e.slice(r+1);if(s==="")return{hostPattern:o,port:void 0};let a=vm(s.startsWith(":")?s.slice(1):"");return a===void 0?{hostPattern:e,port:void 0}:{hostPattern:o,port:a}}let t=e.lastIndexOf(":");if(t===-1)return{hostPattern:e,port:void 0};if(e.indexOf(":")!==t)return{hostPattern:vt(e)??e,port:void 0};let n=vm(e.slice(t+1));if(n===void 0)return{hostPattern:e,port:void 0};return{hostPattern:e.slice(0,t),port:n}}function vm(e){if(!/^[1-9][0-9]{0,4}$/.test(e))return;let t=Number(e);return t>65535?void 0:t}function ao(e){return so(e).hostPattern}function Or(e,t){let n=e.toLowerCase();if(t==="*")return!0;if(t.startsWith("*.")){if(JT(tr(n)))return!1;let r=t.substring(2).toLowerCase();return n.endsWith("."+r)}return n===t.toLowerCase()}function co(e,t,n){let{hostPattern:r,port:i}=so(n);if(i!==void 0&&i!==t)return!1;return Or(e,r)}function ca(e,t){let n=t.map(ao);if(!e.startsWith("*."))return n.some((i)=>Or(e,i));let r=e.slice(2).toLowerCase();return n.some((i)=>{if(!i.startsWith("*."))return!1;let o=i.slice(2).toLowerCase();return r===o||r.endsWith("."+o)})}import{isIP as QT}from"net";var xm="<allowAllDomains>";function sl(e,t,n,r){if(!ti(t))return{verdict:"deny",reason:"malformed host"};let i=vt(t)??t;for(let o of e.deniedDomains)if(co(i,n,o))return{verdict:"deny",reason:e.deniedDomainReasons?.[o]??"host is on the deny list",rule:o};for(let o of e.allowedDomains)if(co(i,n,o))return{verdict:"allow",rule:o};if(e.allowAllDomains){if(Ts(i)||QT(i)!==0&&!_s(i))return{verdict:"deny",reason:"host is not on the public internet"};return{verdict:"allow",rule:xm}}if(!r||e.strictAllowlist)return{verdict:"deny",reason:"host is not on the allow list"};return{verdict:"ask"}}function al(e,t,n){if(!e.allowAllDomains)return!1;let r=sl(e,t,n,!1);return r.verdict==="allow"&&r.rule===xm}async function bm(e,t,n,r,i){if(al(e,t,n))return th(t,r);if(e.refuseLocalDestinations)return rh(t,r,i);return t}import{EOL as cl}from"os";import{dirname as ul}from"path";var O,lo,fo,po,Gt,Qr,Yr,Sm=!1,ua,di,tn,De,rn,_n,Tn,fi,la,Cm=!1,hi,En=new Ys,or=new Eu,mi=new Iu,pi=new gu;function Im(){let e=O?.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)pi.register(r,t,n.hosts,e.url)}return[e.tokenEnvVar]}function eA(e){return O?.network.brokerForward?.rules.some((t)=>t.hosts.includes(e))??!1}var ho=new ku;function tA(){if(Sm)return;let e=()=>gl().catch((t)=>{w(`Cleanup failed in registerCleanup ${t}`,{level:"error"})});process.once("exit",()=>{let t=Tn;if(t)hm({sandboxUserSid:t,srtWin:hi}),_n=void 0,Tn=void 0;e()}),process.once("SIGINT",e),process.once("SIGTERM",e),Sm=!0}var rA=1024,wn=new Map;function Pm(e,t){let n=t?.commandId,r=t?.commandText??e;if(n===void 0||n===r)return;let i=cn(zt(n));wn.delete(i),wn.set(i,r);while(wn.size>rA){let o=wn.keys().next().value;if(o===void 0)break;wn.delete(o)}}function wm(e){return wn.get(e)??e}function ll(e,t){let n=t?(()=>{let r=cn(t);return wn.get(r)??Hu(r)})():void 0;if(ci(e,n,O?.ignoreViolations))return;En.addViolation({line:e,encodedCommand:t,command:n,timestamp:new Date})}function nA(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 Em(e,t,n,r){let i=(s)=>(ll(`deny network-outbound ${t}:${e} (${s})`,r),!1);if(!O)return w("No config available, denying network request"),i("sandbox policy unavailable");let o=sl(O.network,t,e,n!==void 0);if(o.verdict==="allow")return w(`Allowed by config rule: ${t}:${e}`),!0;if(o.verdict==="deny"){if(o.reason==="malformed host")w(`Denying malformed host: ${JSON.stringify(t)}:${e}`,{level:"error"});else if(o.rule!==void 0)w(`Denied by config rule: ${t}:${e}`);else w(`No matching config rule, denying: ${t}:${e}`);return i(o.reason)}w(`No matching config rule, asking user: ${t}:${e}`);try{if(await n({host:t,port:e}))return w(`User allowed: ${t}:${e}`),!0;return w(`User denied: ${t}:${e}`),i("user denied")}catch(s){return w(`Error in permission callback: ${s}`,{level:"error"}),i("permission prompt failed")}}var fa=!1;function iA(e){fa=e}function oA(){if(!fa&&!O?.credentials)return;return(e,t)=>{if(!O?.credentials)return;or.substituteInHeaders(e,t,Or)}}function sA(){if(!fa&&!O?.credentials)return;return(e)=>O?.credentials?or.sentinelsForHost(e,Or):void 0}function aA(){if(!fa&&!O?.credentials)return;return(e,t,n,r)=>!O?.credentials?void 0:o0(mi,O?.credentials?.sigv4,Or)(e,t,n,r)}function cA(e){if(!O?.network.mitmProxy)return;let{socketPath:t,domains:n}=O.network.mitmProxy,r=vt(e)??e;for(let i of n)if(Or(r,i))return w(`Host ${e} matches MITM pattern ${i}`),t;return}function uA(e,t=443){if(O&&al(O.network,vt(e)??e,t))return!1;let n=O?.network.tlsTerminate?.excludeDomains;if(!n?.length)return!0;let r=vt(e)??e;if(eA(r))return!0;for(let i of n){if(!Or(r,i))continue;w(`Host ${e} matches tlsTerminate.excludeDomains pattern ${i}; skipping TLS termination`);let o=or.namesInjectableAt(r,Or);if(o.length>0)w(`tlsTerminate.excludeDomains: masked credential(s) ${o.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 _m(e,t){let n=vt(e)??e;return O?bm(O.network,n,t):n}async function lA(e,t){let n=oA(),r=sA();lo=$h({filter:(a,c,u,l)=>Em(a,c,e,l),getMitmSocketPath:cA,mitmCA:De,shouldTerminateTLS:uA,resolveDestination:_m,filterRequest:O?.network.filterRequest,onFilterRequestDenied:({method:a,url:c,reason:u,encodedCommand:l})=>{ll(`deny http-request ${a} ${nA(c)} (${u})`,l)},mutateHeaders:n,mutateHeadersPlaintext:O?.credentials?.allowPlaintextInject?n:void 0,getBrokerForward:(a,c)=>O?.network.brokerForward?pi.forwardFor(a,c):void 0,getBodySubstitutions:r,getBodySubstitutionsPlaintext:O?.credentials?.allowPlaintextInject?r:void 0,planSigv4:aA(),parentProxy:tn,proxyAuthToken:rn}),fo=Hh({filter:(a,c,u)=>Em(a,c,e,u),resolveDestination:_m,parentProxy:tn,proxyAuthToken:rn,probeUnauthenticated:async(a,c)=>{if(!O)return{};let u=vt(c)??c;for(let l of O.network.deniedDomains)if(co(u,a,l)){let f=O.network.deniedDomainReasons?.[l]??"host is on the deny list";return ll(`deny network-outbound ${c}:${a} (${f})`,void 0),{deniedReason:f}}return{}}}),po=jh({httpServer:lo,handleSocksConnection:(a)=>fo.handleConnection(a),httpBackendPortRange:t});let i=po,o=await i.listenHttpBackend();await Us(i.server,(a)=>i.server.listen(a,"127.0.0.1"),t,o!==void 0?new Set([o]):new Set);let s=i.getPort();if(s===void 0)throw Error("Failed to get mux proxy server port");return i.unref(),w(`Mux proxy (HTTP+SOCKS) listening on localhost:${s}`),s}async function fA(e,t,n=!1){if(await Yr?.catch(()=>{return}),await fi?.catch(()=>{return}),Qr){await Qr;return}if(O=e,tn=fu(e.network.parentProxy),tn)w(`Parent proxy configured: http=${hu(tn.httpUrl)} https=${hu(tn.httpsUrl)}`);if(e.network.tlsTerminate&&e.network.mitmProxy)throw Error("network.tlsTerminate and network.mitmProxy are mutually exclusive");let r=e.network.tlsTerminate,i=Ie()==="windows"&&r!==void 0&&!r.caCertPath&&!r.caKeyPath;if(De=r&&!i?ou(r):void 0,De&&e.runAsHostUid!==void 0&&Ie()==="linux"){if(en.chmodSync(ul(De.trustBundlePath),457),en.chmodSync(De.trustBundlePath,420),De.ephemeral)en.chmodSync(ul(De.certPath),457),en.chmodSync(De.certPath,420)}let o=await Nm();if(o.errors.length>0)throw Error(`Sandbox dependencies not available: ${o.errors.join(", ")}`);if(n&&Ie()==="macos")ua=W0(En.addViolation.bind(En),O.ignoreViolations,wm),w("Started macOS sandbox log monitor");if(n&&Ie()==="linux")di=Z0(En.addViolation.bind(En),{allowWritePaths:[...Bn(e.runAsHostHome),...O.filesystem.allowWrite],denyWritePaths:O.filesystem.denyWrite,ignoreViolations:O.ignoreViolations,resolveCommandText:wm,consumerUid:e.runAsHostUid,consumerGid:e.runAsHostGid}),di.ready,w("Started Linux seccomp violation monitor");if(tA(),Ie()==="windows"){hi=Nt(e.windows?.srtWin);let s=hi,a=await oo({srtWin:s});if(!a.provisioned||!a.credPresent)throw O=void 0,new me("not_provisioned",`Windows sandbox user is not provisioned (user=${a.provisioned}, cred=${a.credPresent}). Run \`npx sandbox-runtime windows-install\` (one UAC prompt) to provision it.`);if(!Cm){try{await Qu({proxyPortRange:e.windows?.proxyPortRange,srtWin:s})}catch(c){throw O=void 0,c}Cm=!0}if(i&&r)try{let c=await tl({status:a,srtWin:s});De=ou({caCertPem:c.certPem,caKeyPem:c.keyPem,caCertPath:c.certPath,caKeyPath:c.keyPath,extraCaCertPaths:r.extraCaCertPaths})}catch(c){throw O=void 0,c}if(r&&De&&!i){let c=el(a),u=Qn(De.certPem);if(!c)throw O=void 0,new me("trust_ca_not_installed",`tlsTerminate on Windows requires the sandbox to be installed with this CA (thumb=${u}): run \`srt-win user trust-ca ${De.certPath}\`. Per-exec installs into the sandbox user's Root store are not supported.`);if(c.thumb!==u)throw O=void 0,new me("trust_ca_thumbprint_mismatch",`tlsTerminate on Windows: the sandbox's installed CA (thumb=${c.thumb}) doesn't match this session's CA (thumb=${u}). Run \`srt-win user trust-ca ${De.certPath}\` to update it.`)}try{let c=gA(e);if(De)c.grantRead.push(ul(De.trustBundlePath));if(!a.sid)throw Error("sandbox user SID missing from `srt-win user status` (provisioned but in an inconsistent state)");let u=a.sid;Tn=u;let l=async()=>{if(c.grantRead.length>0||c.grantWrite.length>0)await il({sandboxUserSid:u,read:c.grantRead,write:c.grantWrite,srtWin:s});if(c.denyRead.length>0||c.denyWrite.length>0)await nl({sandboxUserSid:u,denyRead:c.denyRead,denyWrite:c.denyWrite,srtWin:s});if(c.grantRead.length>0||c.grantWrite.length>0||c.denyRead.length>0||c.denyWrite.length>0)_n=c,w(`[Sandbox Windows] fs applied: ${c.grantWrite.length} grantWrite, ${c.grantRead.length} grantRead, ${c.denyRead.length} denyRead, ${c.denyWrite.length} denyWrite`)},f=(async()=>{try{await l()}catch(p){throw await aa({sandboxUserSid:u,srtWin:s}),await sa({sandboxUserSid:u,srtWin:s}),Tn=void 0,p}})();fi=f;try{await f}finally{if(fi===f)fi=void 0}if(Yr)throw Error("Sandbox was reset during initialization");la=$m(e)}catch(c){throw O=void 0,await Yr?.catch(()=>{return}),c}}Qr=(async()=>{try{let s=Ie()==="windows"?O.windows?.proxyPortRange??ta:void 0;rn=O.network.httpProxyPort!==void 0?void 0:YT(16).toString("hex");let c=O.network.httpProxyPort===void 0||O.network.socksProxyPort===void 0?await lA(t,s):void 0,u=O.network.httpProxyPort??c,l=O.network.socksProxyPort??c;if(De&&c!==void 0&&Ie()==="windows")De.crlUrl=`http://127.0.0.1:${c}${Ss}`;if(O.network.httpProxyPort!==void 0)w(`Using external HTTP proxy on port ${u}`);if(O.network.socksProxyPort!==void 0)w(`Using external SOCKS proxy on port ${l}`);let f;if(Ie()==="linux")f=await D0(u,l,O.socatPath,O.runAsHostUid,O.runAsHostGid);let p={httpProxyPort:u,socksProxyPort:l,linuxBridge:f};return Gt=p,w("Network infrastructure initialized"),p}catch(s){throw Qr=void 0,Gt=void 0,gl().catch((a)=>{w(`Cleanup failed in initializationPromise ${a}`,{level:"error"})}),s}})(),await Qr}function Rm(){let e=Ie();if(e==="linux")return Ga()!=="1";return e==="macos"||e==="windows"}function dA(){return O!==void 0}function Bm(e){if(!Rm())return{done:{errors:["Unsupported platform"],warnings:[]}};let t=[],n=[],r=Ie();if(r==="linux"){let i=e??O?.ripgrep??{command:"rg"};if(Nr(i.command)===null)t.push(`ripgrep (${i.command}) not found`);let o=N0({seccompConfig:O?.seccomp,bwrapPath:O?.bwrapPath,socatPath:O?.socatPath});t.push(...o.errors),n.push(...o.warnings)}else if(r==="windows"){let i;try{i=Nt(O?.windows?.srtWin)}catch(o){return t.push(o.message),{done:{errors:t,warnings:n}}}return{windows:{sublayerGuid:O?.windows?.sublayerGuid??O?.windows?.wfpSublayerGuid,srtWin:i}}}return{done:{errors:t,warnings:n}}}function pA(e){let t=Bm(e);if("done"in t)return t.done;return ym(t.windows)}async function Nm(e){let t=Bm(e);if("done"in t)return t.done;return ol(t.windows)}function dl(e,t){if(!e)return{denyReadPaths:[],unsetEnvVars:[],setEnvVars:{},maskedFileBinds:[],maskedFileStoreDir:void 0};let n=da(e),r=[...new Set((t??[]).map(ao))],i=[];for(let l of e.envVars??[])if(l.mode==="deny")i.push(l.name);let{setEnvVars:o,degradeToUnsetNames:s}=e0(e.envVars??[],r,or);i.push(...s),i0(e.envVars??[],e.awsPairs,r,o,mi);let a=e.files??[],{binds:c,degradeToDenyPaths:u}=Yh(a,r,or,ho);return{denyReadPaths:[...new Set([...n,...u])],unsetEnvVars:[...new Set(i)],setEnvVars:o,maskedFileBinds:c,maskedFileStoreDir:ho.dirPath}}function da(e){let t=e?.files??[];return[...new Set(t.filter((n)=>n.mode==="deny").map((n)=>n.path))]}function Dm(e,t){return[...new Set([...e,...t.denyReadPaths])]}function hA(){if(!O||O.filesystem.disabled)return{denyOnly:[],allowWithinDeny:[]};let e=Dm(O.filesystem.denyRead,dl(O.credentials,O.network.allowedDomains)),t=[];for(let r of e){let i=Tr(r);if(Ie()==="linux"&&xt(i)){let o=un(r);w(`[Sandbox] Expanded glob pattern "${r}" to ${o.length} paths on Linux`),t.push(...o)}else t.push(i)}let n=[];for(let r of O.filesystem.allowRead??[]){let i=Tr(r);if(Ie()==="linux"&&xt(i)){let o=un(r);w(`[Sandbox] Expanded allowRead glob pattern "${r}" to ${o.length} paths on Linux`),n.push(...o)}else n.push(i)}return{denyOnly:t,allowWithinDeny:n}}function mA(){if(!O)return{allowOnly:Bn(),denyWithinAllow:[]};if(O.filesystem.disabled)return{allowOnly:["/"],denyWithinAllow:[]};let e=O.filesystem.allowWrite.map((r)=>Tr(r)).filter((r)=>{if(Ie()==="linux"&&xt(r))return w(`Skipping glob pattern on Linux/WSL: ${r}`),!1;return!0}),t=O.filesystem.denyWrite.map((r)=>Tr(r)).filter((r)=>{if(Ie()==="linux"&&xt(r))return w(`Skipping glob pattern on Linux/WSL: ${r}`),!1;return!0});return{allowOnly:[...Bn(fl()),...e],denyWithinAllow:t}}function gA(e){let t=e.filesystem;if(t?.disabled)return{grantRead:[],grantWrite:[],denyRead:[],denyWrite:[]};let n=oa,r=n([...new Set([...t?.denyRead??[],...da(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 $m(e){return{disabled:e.filesystem.disabled??!1,denyRead:[...e.filesystem.denyRead],denyWrite:[...e.filesystem.denyWrite],allowRead:[...e.filesystem.allowRead??[]],allowWrite:[...e.filesystem.allowWrite],credFiles:da(e.credentials)}}function uo(e,t){if(e.length!==t.length)return!1;let n=new Set(e);return t.every((r)=>n.has(r))}function yA(e,t){return e.disabled===t.disabled&&uo(e.denyRead,t.denyRead)&&uo(e.denyWrite,t.denyWrite)&&uo(e.allowRead,t.allowRead)&&uo(e.allowWrite,t.allowWrite)&&uo(e.credFiles,t.credFiles)}function vA(e){return la!==void 0&&yA(la,$m(e))}function xA(){if(!O)return{};let e=O.network.allowedDomains,t=O.network.deniedDomains;return{allowedHosts:e,...t.length>0&&{deniedHosts:t}}}function Om(){return O?.network?.allowUnixSockets}function Tm(){return O?.network?.allowAllUnixSockets}function Lm(){return O?.network?.allowLocalBinding}function Um(){return O?.network?.allowMachLookup}function zm(){return O?.ignoreViolations}function Fm(){return O?.enableWeakerNestedSandbox}function bA(){return O?.runAsUid}function SA(){return O?.runAsGid}function CA(){return O?.runAsHostUid}function wA(){return O?.runAsHostGid}function fl(){return O?.runAsHostHome}function EA(){return O?.runAsHostUser}function _A(){return O?.enableWeakerNetworkIsolation}function TA(){return O?.allowAppleEvents}function AA(){return O?.ripgrep??{command:"rg"}}function kA(){return O?.mandatoryDenySearchDepth??3}function Am(){return O?.filesystem?.allowGitConfig??!1}function Mm(e){return[...O?.git?.safeDirectories??[],...e?.git?.safeDirectories??[]]}function IA(){return O?.seccomp}function PA(){return rn}function pl(){return Gt?.httpProxyPort}function hl(){return Gt?.socksProxyPort}function Vm(){return Gt?.linuxBridge?.httpSocketPath}function Wm(){return Gt?.linuxBridge?.socksSocketPath}async function ml(){if(!O)return!1;if(Qr)try{return await Qr,!0}catch{return!1}return Gt!==void 0}async function Hm(e,t,n,r,i){let o=Ie(),s=i?.commandId;Pm(e,i);let a=n?.filesystem!==void 0?n.filesystem.disabled??!1:O?.filesystem.disabled??!1,c=dl(n?.credentials??O?.credentials,n?.network?.allowedDomains??O?.network?.allowedDomains);c.unsetEnvVars.push(...Im());let u,l;if(!a){let x=(k)=>k.map((R)=>Tr(R)).filter((R)=>{if(Ie()==="linux"&&xt(R))return w(`[Sandbox] Skipping glob write pattern on Linux: ${R}`),!1;return!0}),b=x(n?.filesystem?.allowWrite??O?.filesystem.allowWrite??[]);u={allowOnly:[...Bn(n?.runAsHostHome??fl()),...b],denyWithinAllow:x(n?.filesystem?.denyWrite??O?.filesystem.denyWrite??[])};let S=Dm(n?.filesystem?.denyRead??O?.filesystem.denyRead??[],c),C=[];for(let k of S){let R=Tr(k);if(Ie()==="linux"&&xt(R))C.push(...un(k));else C.push(R)}let T=n?.filesystem?.allowRead??O?.filesystem.allowRead??[],I=[];for(let k of T){let R=Tr(k);if(Ie()==="linux"&&xt(R))I.push(...un(k));else I.push(R)}if(De)I.push(De.certPath,De.trustBundlePath);l={denyOnly:C,allowWithinDeny:I}}let f=n?.network?.allowedDomains!==void 0||O?.network?.allowedDomains!==void 0,p=f,h=f;if(h)await ml();let d=n?.allowPty??O?.allowPty,g=Mm(n);switch(o){case"macos":return V0({command:e,commandId:s,needsNetworkRestriction:p,httpProxyPort:h?pl():void 0,socksProxyPort:h?hl():void 0,proxyAuthToken:h?rn:void 0,caCertPath:De?.trustBundlePath,readConfig:l,writeConfig:u,unsetEnvVars:c.unsetEnvVars,setEnvVars:c.setEnvVars,maskedFileBinds:c.maskedFileBinds,allowUnixSockets:Om(),allowAllUnixSockets:Tm(),allowLocalBinding:Lm(),allowMachLookup:Um(),ignoreViolations:zm(),allowPty:d,allowGitConfig:Am(),gitSafeDirectories:g,enableWeakerNetworkIsolation:_A(),allowAppleEvents:TA(),binShell:t});case"linux":return O0({command:e,commandId:s,needsNetworkRestriction:p,httpSocketPath:h?Vm():void 0,socksSocketPath:h?Wm():void 0,httpProxyPort:h?Gt?.httpProxyPort:void 0,socksProxyPort:h?Gt?.socksProxyPort:void 0,proxyAuthToken:h?rn:void 0,caCertPath:De?.trustBundlePath,readConfig:l,writeConfig:u,unsetEnvVars:c.unsetEnvVars,setEnvVars:c.setEnvVars,maskedFileBinds:c.maskedFileBinds,maskedFileStoreDir:c.maskedFileStoreDir,enableWeakerNestedSandbox:Fm(),runAsUid:bA(),runAsGid:SA(),runAsHostUid:CA(),runAsHostGid:wA(),runAsHostHome:fl(),runAsHostUser:EA(),setprivPath:"/usr/bin/setpriv",allowAllUnixSockets:Tm(),binShell:t,ripgrepConfig:AA(),mandatoryDenySearchDepth:kA(),allowGitConfig:Am(),gitSafeDirectories:g,seccompConfig:IA(),bwrapPath:O?.bwrapPath,socatPath:O?.socatPath,observeSocketPath:di?.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: ${o}`)}}async function RA(e,t,n,r,i,o){if(Ie()==="windows"){let u=n?.network?.allowedDomains!==void 0||O?.network?.allowedDomains!==void 0;if(u)await ml();let l=dl(n?.credentials??O?.credentials,n?.network?.allowedDomains??O?.network?.allowedDomains);l.unsetEnvVars.push(...Im());let f=n?.filesystem,p=[],h=[];if(!f?.disabled){if(f?.allowRead?.length||f?.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 d=[...f?.denyRead??[],...da(n?.credentials)],g=f?.denyWrite??[];if(d.length>0||g.length>0){let x=new Set(_n?.denyRead??[]),b=new Set(_n?.denyWrite??[]),S=oa;p=S(d,{mode:"deny"}).filter((C)=>!x.has(C)),h=S(g,{mode:"deny"}).filter((C)=>!x.has(C)&&!b.has(C))}}return Pm(e,o),mm({command:e,commandId:o?.commandId,httpProxyPort:u?pl():void 0,socksProxyPort:u?hl():void 0,proxyAuthToken:u?rn:void 0,setEnvVars:l.setEnvVars,denyRead:p,denyWrite:h,cwd:i,allowWrite:_n?.grantWrite,gitSafeDirectories:Mm(n),caCertPath:De?.trustBundlePath,binShell:ra(t),srtWin:n?.windows?.srtWin?Nt(n.windows.srtWin):hi??Nt(O?.windows?.srtWin)})}if(typeof t==="object")throw Error("binShell object form is Windows-only; pass a shell path string on macOS/Linux");let a=await Hm(e,t,n,r,o);return{argv:[t??"/bin/bash","-c",a],env:process.env}}function BA(){return O}function NA(){or.clear(),mi.clear(),pi.clear(),ho.dispose()}function DA(e){if(Ie()==="windows"&&O&&!vA(e))w("[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;O=structuredClone({...e,network:n}),O.network.filterRequest=t,tn=fu(e.network.parentProxy),w("Sandbox configuration updated")}function $A(){Qs()}var OA=1500;function km(e,t){if(!e.pid||e.exitCode!==null||e.signalCode!==null)return Promise.resolve();try{process.kill(e.pid,"SIGTERM"),w(`Sent SIGTERM to ${t} bridge process`)}catch(n){if(n.code!=="ESRCH")w(`Error killing ${t} bridge: ${n}`,{level:"error"});return Promise.resolve()}return new Promise((n)=>{let r=!1,i=()=>{if(r)return;r=!0,clearTimeout(o),n()};e.once("exit",()=>{w(`${t} bridge process exited`),i()});let o=setTimeout(()=>{if(e.exitCode===null&&e.signalCode===null){w(`${t} bridge did not exit, forcing SIGKILL`,{level:"warn"});try{if(e.pid)process.kill(e.pid,"SIGKILL")}catch{}}i()},OA);o.unref?.()})}function LA(e){return new Promise((t)=>{if(typeof e.closeAllConnections==="function")e.closeAllConnections();e.close((n)=>{if(n&&n.message!=="Server is not running.")w(`Error closing HTTP proxy server: ${n.message}`,{level:"error"});t()})})}async function UA(){if(fi)await fi.catch(()=>{return});if(_n&&Tn){let t=Tn,n=hi,r=new Set(["revoked","stillHeld","restored","alreadyOriginal"]),i=(o,s)=>{if(!r.has(s.status))w(`[Sandbox Windows] ${o}: '${s.path}' ${s.status} \u2014 `+"ACE may be left in place; resolve and run `srt-win acl recover` to clear",{level:"warn"})};for(let o of await aa({sandboxUserSid:t,srtWin:n})??[])i("grant revoke",o);for(let o of await sa({sandboxUserSid:t,srtWin:n})??[])i("deny restore",o)}if(_n=void 0,Tn=void 0,la=void 0,hi=void 0,Qs({force:!0}),ua)ua(),ua=void 0;if(di)di.stop(),di=void 0;if(Gt?.linuxBridge){let{httpSocketPath:t,socksSocketPath:n,httpBridgeProcess:r,socksBridgeProcess:i}=Gt.linuxBridge;if(await Promise.all([km(r,"HTTP"),km(i,"SOCKS")]),t)try{en.rmSync(t,{force:!0}),w("Cleaned up HTTP socket")}catch(o){w(`HTTP socket cleanup error: ${o}`,{level:"error"})}if(n)try{en.rmSync(n,{force:!0}),w("Cleaned up SOCKS socket")}catch(o){w(`SOCKS socket cleanup error: ${o}`,{level:"error"})}}let e=[];if(De)e.push(Xp(De));if(po)e.push(po.close().catch((t)=>{w(`Error closing mux proxy server: ${t.message}`,{level:"error"})}));if(lo)e.push(LA(lo));if(fo){let t=fo.close().catch((n)=>{w(`Error closing SOCKS proxy server: ${n.message}`,{level:"error"})});e.push(t)}await Promise.all(e),po=void 0,lo=void 0,rn=void 0,fo=void 0,Gt=void 0,Qr=void 0,tn=void 0,De=void 0,or.clear(),mi.clear(),ho.dispose()}async function gl(){if(Yr)return Yr;Yr=UA();try{await Yr}finally{Yr=void 0}}function zA(){return En}function FA(e,t){if(!O)return t;let n=En.getViolationsForCommand(e);if(n.length===0)return t;let r=t;r+=cl+"<sandbox_violations>"+cl;for(let i of n)r+=i.line+cl;return r+="</sandbox_violations>",r}function MA(){if(Ie()!=="linux"||!O||O.filesystem.disabled)return[];let e=[],t=[...O.filesystem.allowWrite,...O.filesystem.denyWrite];for(let n of t){let r=Tr(n);if(xt(r))e.push(n)}return e}var VA={initialize:fA,isSupportedPlatform:Rm,isSandboxingEnabled:dA,checkDependencies:pA,checkDependenciesAsync:Nm,getFsReadConfig:hA,getFsWriteConfig:mA,getNetworkRestrictionConfig:xA,getAllowUnixSockets:Om,getAllowLocalBinding:Lm,getAllowMachLookup:Um,getIgnoreViolations:zm,getEnableWeakerNestedSandbox:Fm,getProxyPort:pl,getProxyAuthToken:PA,getSocksProxyPort:hl,getLinuxHttpSocketPath:Vm,getLinuxSocksSocketPath:Wm,waitForNetworkInitialization:ml,wrapWithSandbox:Hm,wrapWithSandboxArgv:RA,cleanupAfterCommand:$A,beginCredentialLease:()=>{or.beginLease(),pi.beginLease()},endCredentialLease:()=>Object.assign(or.endLease(),{brokerForward:pi.endLease()}),releaseCredentialLease:(e)=>{pi.release(e.brokerForward??[]),mi.forget(or.release(e))},reset:gl,getMitmCA:()=>De,getSentinelRegistry:()=>or,getAwsPairRegistry:()=>mi,getMaskedFileStore:()=>ho,getSandboxViolationStore:zA,annotateStderrWithSandboxFailures:FA,getLinuxGlobPatternWarnings:MA,getConfig:BA,updateConfig:DA,clearMaskedCredentials:NA,setLiveCredentialInjectors:iA};import{isIP as jI}from"net";import{isAbsolute as GI}from"path";function yo(e){let t=Object.values(e).filter((r)=>typeof r==="number");return Object.entries(e).filter(([r,i])=>t.indexOf(+r)===-1).map(([r,i])=>i)}function vl(e,t="|"){return e.map((n)=>Sl(n)).join(t)}function vo(e,t){if(typeof t==="bigint")return t.toString();return t}class Km{constructor(e){this._getter=e,this._value=void 0}get value(){let e=this._getter;if(e!==void 0)this._value=e(),this._getter=void 0;return this._value}}function pa(e){return new Km(e)}function Zm(e){return e===null||e===void 0}function ha(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function jm(e,t){let n=e/t,r=Math.round(n),i=4*Number.EPSILON*Math.max(Math.abs(n),1);if(Math.abs(n-r)<i)return 0;return n-r}function sr(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function ma(e){let t=Object.getOwnPropertyDescriptor(e,"shape");return t?.get?t.get.raw:t?.value}function Lr(e){return ma(e._zod.def)??e._zod.def.shape}function Gm(e,t,n){Object.defineProperty(e,t,{get(){let r=n();return sr(this,t,r),r},enumerable:!0,configurable:!0})}function qm(e,t,n){if(t in e)sr(e,t,n);else e[t]=n}function An(e,t,n,r){let i=Lr(t);for(let o of n){let s=Object.getOwnPropertyDescriptor(i,o);if(!s.enumerable)continue;if(s.get)Gm(e,o,()=>{let a=t._zod.def.shape[o];return r?r(a,o):a});else qm(e,o,r?r(s.value,o):s.value)}}function WA(e,t){for(let n of Reflect.ownKeys(t)){let r=Object.getOwnPropertyDescriptor(t,n);if(!r.enumerable)continue;if(r.get)Gm(e,n,()=>t[n]);else qm(e,n,r.value)}}function Dt(...e){let t={};for(let n of e){let r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}function Xm(e){return JSON.stringify(e)}function Jm(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var xl="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function go(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var Qm=pa(()=>{if(_t.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function kn(e){if(go(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;if(typeof t!=="function")return!0;let n=t.prototype;if(go(n)===!1)return!1;if(Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)return!1;return!0}function bl(e){if(kn(e))return{...e};if(Array.isArray(e))return[...e];if(e instanceof Map)return new Map(e);if(e instanceof Set)return new Set(e);return e}var Ym=new Set(["string","number","symbol"]);function gi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ar(e,t,n){let r=new e._zod.constr(t??e._zod.def);if(!t||n?.parent)r._zod.parent=e;return r}function Y(e){let t=e;if(!t)return{};if(typeof t==="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}if(delete t.message,typeof t.error==="string")return{...t,error:()=>t.error};return t}function Sl(e){if(typeof e==="bigint")return e.toString()+"n";if(typeof e==="string")return`"${e}"`;return`${e}`}function eg(e){return Object.keys(e).filter((t)=>e[t]._zod.optin!==void 0&&e[t]._zod.optout==="optional")}var ga=(()=>({safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]}))(),Cl={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function HA(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let o={};return An(o,e,ya(e,t)),ar(e,Dt(n,{shape:o,checks:[]}))}function ya(e,t){let n=Lr(e),r=[];for(let i of Reflect.ownKeys(t)){if(!Object.getOwnPropertyDescriptor(n,i)?.enumerable)throw Error(`Unrecognized key: "${String(i)}"`);if(t[i])r.push(i)}return r}function KA(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let o=new Set(ya(e,t)),s={};return An(s,e,Reflect.ownKeys(Lr(e)).filter((a)=>!o.has(a))),ar(e,Dt(n,{shape:s,checks:[]}))}function ZA(e,t){if(!kn(t))throw Error("Invalid input to extend: expected a plain object");let n=e._zod.def.checks;if(n&&n.length>0){let i=Lr(e);for(let o of Reflect.ownKeys(t))if(Object.getOwnPropertyDescriptor(i,o)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return ar(e,Dt(e._zod.def,{shape:tg(e,t)}))}function tg(e,t){let n={};return An(n,e,Reflect.ownKeys(Lr(e))),WA(n,t),n}function jA(e,t){if(!kn(t))throw Error("Invalid input to safeExtend: expected a plain object");return ar(e,Dt(e._zod.def,{shape:tg(e,t)}))}function GA(e,t){if(!t?._zod?.def)throw Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let n={};An(n,e,Reflect.ownKeys(Lr(e))),An(n,t,Reflect.ownKeys(Lr(t)));let r=Dt(e._zod.def,{shape:n,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return ar(e,r)}function rg(e,t,n,r="partial"){let o=t._zod.def.checks;if(o&&o.length>0)throw Error(`.${r}() cannot be used on object schemas containing refinements`);let a=n?new Set(ya(t,n)):void 0,c={};return An(c,t,Reflect.ownKeys(Lr(t)),e&&((u,l)=>a&&!a.has(l)?u:new e({type:"optional",innerType:u}))),ar(t,Dt(t._zod.def,{shape:c,checks:[]}))}function qA(e,t,n){let r=n?new Set(ya(t,n)):void 0,i={};return An(i,t,Reflect.ownKeys(Lr(t)),(o,s)=>r&&!r.has(s)?o:new e({type:"nonoptional",innerType:o})),ar(t,Dt(t._zod.def,{shape:i}))}function qt(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function ng(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function Cr(e,t){return t.map((n)=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function mo(e){return typeof e==="string"?e:e?.message}function wl(e){let t=[];for(let n of e??[]){let r=n._zod.def;if(!/_(length|size)$|_equals$/.test(r.check))break;let i=r.maximum??r.length??r.size;if(i>=0)t.push([i,n])}return t}function va(e,t,n){var r;for(let i=t;i<e.length;i++)(r=e[i]).schema??(r.schema=n)}function wr(e,t,n){var r;let i=e.inst?._zod?.traits;if(i?.has("$ZodType"))if(i.has("$ZodCheck"))(r=e).schema??(r.schema=e.inst);else e.schema=e.inst;let o=e.schema!==e.inst?e.schema?._zod.def?.error:void 0,s=e.message?e.message:mo(e.inst?._zod.def?.error?.(e))??mo(o?.(e))??mo(t?.error?.(e))??mo(n.customError?.(e))??mo(n.localeError?.(e))??"Invalid input",a={};for(let c of Object.keys(e)){if(c==="inst"||c==="schema"||c==="continue"||c==="input"||c==="__proto__")continue;a[c]=e[c]}if(a.path??(a.path=[]),a.message=s,t?.reportInput)a.input=e.input;return a}var XA=/[\uD800-\uDBFF]/;function xa(e){let t=e.length;if(!XA.test(e))return t;let n=t;for(let r=0;r<t-1;r++)if((e.charCodeAt(r)&64512)===55296&&(e.charCodeAt(r+1)&64512)===56320)n--,r++;return n}function ba(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function ig(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let n=e;if(n&&Object.getPrototypeOf(n)!==Object.prototype&&"constructor"in n&&n.constructor)return n.constructor.name}}return t}function In(...e){let[t,n,r]=e;if(typeof t==="string")return{message:t,code:"custom",input:n,inst:r};return{...t}}function og(e,t){for(let n in t){let r=Object.getOwnPropertyDescriptor(t,n);if(r.get)Object.defineProperty(e,n,{...r,enumerable:!1});else JA(e,n,r.value)}}function Ur(e,t,n,r=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:r,value:n}),n}function Sa(e,t,n){return Ur(e,t,n,!1)}function sg(e,t){for(let n in e){let r=e[n];Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){return Ur(this,n,r(this))},set(i){Ur(this,n,i)}})}return t}function JA(e,t,n){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?n:Ur(this,t,n.bind(this))},set(r){Ur(this,t,r)}})}function QA(e,t){let n=Object.getPrototypeOf(e);return t in n?void 0:n}var yl,nn=!1,YA={configurable:!0,get(){nn=!0;return}};function Be(e,t,n){let r=Object.getPrototypeOf(e._zod);if(t in r&&yl!==e._zod){yl=void 0;return}yl=e._zod,Object.defineProperty(r,t,{configurable:!0,get(){Object.defineProperty(this,t,YA);let i=nn;nn=!1;try{let o=n(this);if(nn)delete this[t];else Object.defineProperty(this,t,{configurable:!0,writable:!0,value:o});return nn=nn||i,o}catch(o){throw delete this[t],nn=nn||i,o}},set(i){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:i})}})}function ek(e,t,n,r){let i=QA(e,t);if(!i)return;Object.defineProperty(i,t,{configurable:!0,get(){let o={configurable:!0,writable:!0,enumerable:r,value:void 0};return Object.defineProperty(this,t,o),o.value=n(this),Object.defineProperty(this,t,o),o.value},set(o){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:r,value:o})}})}var tk="~constantCatch";function ag(e){let t=()=>e;return t[tk]=!0,t}var cg,lg=Object.freeze({status:"aborted"}),El={value:void 0,enumerable:!1},ug="captureStackTrace"in Error?Error:null;function rk(e){let t=ug;if(t){let n=t.stackTraceLimit;if(typeof n==="number"){try{t.stackTraceLimit=0}catch{return ug=null,new e}try{return new e}finally{t.stackTraceLimit=n}}}return new e}function N(e,t,n,r){let i={};function o(p){this.def=p,this.constr=f,this.traits=new Set}o.prototype=i;let s=n,a=s&&new WeakSet;function c(p,h){if(!p._zod){El.value=new o(h);try{Object.defineProperty(p,"_zod",El)}finally{El.value=void 0}}else if(p._zod.traits.has(e))return;if(p._zod.traits.add(e),t(p,h),a){let g=Object.getPrototypeOf(p),x=p._zod.constr.prototype,b=g;while(b&&b!==x)b=Object.getPrototypeOf(b);let S=b??g;if(!a.has(S))a.add(S),og(S,s)}let d=f.prototype;for(let g in d){if(!Object.prototype.hasOwnProperty.call(d,g))continue;if(!(g in p))p[g]=d[g].bind(p)}}let u=r?.Parent??Object;class l extends u{}Object.defineProperty(l,"name",{value:e});function f(p){let h=r?.Parent?rk(l):this;c(h,p);let d=h._zod.deferred;if(d){for(let x of d)x();h._zod.deferred=void 0}let g=globalThis.__zod_globalConfig?.postProcessor;if(g)g(h);return h}return Object.defineProperty(f,"init",{value:c}),Object.defineProperty(f,Symbol.hasInstance,{value:(p)=>{if(r?.Parent&&p instanceof r.Parent)return!0;return p?._zod?.traits?.has(e)}}),Object.defineProperty(f,"name",{value:e}),f}class Er extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class xo extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}}(cg=globalThis).__zod_globalConfig??(cg.__zod_globalConfig={});var _t=globalThis.__zod_globalConfig;function Pt(e){if(e)Object.assign(_t,e);return _t}function nk(){let e=this._zod;return e.message??(e.message=JSON.stringify(e.def,vo,2)),e.message}function ik(e){this._zod.message=e}var ok={get:nk,set:ik,enumerable:!0,configurable:!0},Tl={value:void 0,enumerable:!1},fg=new WeakSet([Object.prototype,Error.prototype]),dg=(e,t)=>{e.name="$ZodError",Tl.value=t,Object.defineProperty(e,"issues",Tl),Tl.value=void 0,Object.defineProperty(e,"message",ok);let n=Object.getPrototypeOf(e);if(!fg.has(n))fg.add(n),Object.defineProperty(n,"toString",{configurable:!0,enumerable:!1,get(){let r=()=>this.message;return Object.defineProperty(this,"toString",{value:r,configurable:!0,writable:!0}),r},set(r){Object.defineProperty(this,"toString",{value:r,configurable:!0,writable:!0})}})},pg=N("$ZodError",dg),$N=N("$ZodError",dg,void 0,{Parent:Error});function sk(e,t,n){if(!Object.prototype.hasOwnProperty.call(e,t))if(t==="__proto__")Object.defineProperty(e,t,{value:n(),writable:!0,enumerable:!0,configurable:!0});else e[t]=n();return e[t]}function Al(e,t=(n)=>n.message){let n={},r=[];for(let i of e.issues)if(i.path.length>0)sk(n,i.path[0],()=>[]).push(t(i));else r.push(t(i));return{formErrors:r,fieldErrors:n}}function kl(e,t=(n)=>n.message){let n={_errors:[]},r=(i,o=[])=>{for(let s of i.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map((a)=>r({issues:a},[...o,...s.path]));else if(s.code==="invalid_key")r({issues:s.issues},[...o,...s.path]);else if(s.code==="invalid_element")r({issues:s.issues},[...o,...s.path]);else{let a=[...o,...s.path];if(a.length===0)n._errors.push(t(s));else{let c=n,u=0;while(u<a.length){let l=a[u],f=u===a.length-1;if(l==="_errors"){if(f)c._errors.push(t(s));u++;continue}if(!Object.prototype.hasOwnProperty.call(c,l))Object.defineProperty(c,l,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});let p=c[l];if(f)p._errors.push(t(s));c=p,u++}}}};return r(e),n}function Ca(e,t){return{callee:t?.callee??e,Err:t?.Err}}var wa=(e)=>{let t=(n,r,i,o)=>{let s=i?{...i,async:!1}:{async:!1},a=n._zod.run({value:r,issues:[]},s);if(a instanceof Promise)throw new Er;if(a.issues.length){let c=new(o?.Err??e)(a.issues.map((u)=>wr(u,s,Pt())));throw xl(c,o?.callee??t),c}return a.value};return t};var Ea=(e)=>{let t=async(n,r,i,o)=>{let s=i?{...i,async:!0}:{async:!0},a=n._zod.run({value:r,issues:[]},s);if(a instanceof Promise)a=await a;if(a.issues.length){let c=new(o?.Err??e)(a.issues.map((u)=>wr(u,s,Pt())));throw xl(c,o?.callee??t),c}return a.value};return t};var _a=(e)=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},i);if(o instanceof Promise)throw new Er;return o.issues.length?hg(e,o.issues,i):{success:!0,data:o.value}};function hg(e,t,n){let r;return{success:!1,get error(){if(!r)r=new e(t.map((i)=>wr(i,n,Pt()))),t=void 0,n=void 0;return r},set error(i){r=i,t=void 0,n=void 0}}}var Ta=(e)=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},o=t._zod.run({value:n,issues:[]},i);if(o instanceof Promise)o=await o;return o.issues.length?hg(e,o.issues,i):{success:!0,data:o.value}};var ak=Symbol.for("zod.compile.invalid"),ck=Symbol.for("zod.compile.fallback"),Il=(e,t,n)=>{let r=e._zod.bag.validator;if(r!==void 0){if(r(t)!==ak)return!0;if(r.definite===!0&&n===void 0)return!1}return uk(e,t,n)};function uk(e,t,n){let r=n?{...n,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},i=e._zod.bag.fallbackRun,o;if(i)r[ck]=!0,o=i({value:t,issues:[]},r);else o=e._zod.run({value:t,issues:[]},r);if(o instanceof Promise)throw new Er;return o.issues.length===0}var Pl=async(e,t,n)=>{let r=n?{...n,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0},i=e._zod.run({value:t,issues:[]},r);if(i instanceof Promise)i=await i;return i.issues.length===0},mg=(e)=>{let t=wa(e),n=(r,i,o,s)=>{let a=o?{...o,direction:"backward"}:{direction:"backward"};return t(r,i,a,Ca(n,s))};return n};var gg=(e)=>{let t=wa(e),n=(r,i,o,s)=>t(r,i,o,Ca(n,s));return n};var yg=(e)=>{let t=Ea(e),n=async(r,i,o,s)=>{let a=o?{...o,direction:"backward"}:{direction:"backward"};return await t(r,i,a,Ca(n,s))};return n};var vg=(e)=>{let t=Ea(e),n=async(r,i,o,s)=>await t(r,i,o,Ca(n,s));return n};var xg=(e)=>(t,n,r)=>{let i=r?{...r,direction:"backward"}:{direction:"backward"};return _a(e)(t,n,i)};var bg=(e)=>(t,n,r)=>_a(e)(t,n,r);var Sg=(e)=>async(t,n,r)=>{let i=r?{...r,direction:"backward"}:{direction:"backward"};return Ta(e)(t,n,i)};var Cg=(e)=>async(t,n,r)=>Ta(e)(t,n,r);var wg=/^[cC][0-9a-z]{6,}$/,Eg=/^[0-9a-z]+$/,_g=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,Tg=/^[0-9a-vA-V]{20}$/,Ag=/^[A-Za-z0-9]{27}$/,kg=/^[a-zA-Z0-9_-]{21}$/;function Ig(e){return new RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}var Pg=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var Rg=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Bl=(e)=>{if(!e)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)};var Bg=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var lk="^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$";function Ng(){return new RegExp(lk,"u")}var Dg=/^(?:(?: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])$/,$g=/^(([0-9a-fA-F]{1,4}:){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}|:))$/;var Og=/^((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])\/([0-9]|[1-2][0-9]|3[0-2])$/,Lg=/^(([0-9a-fA-F]{1,4}:){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}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Ug=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,zg=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/;var Fg=/^https?$/,Mg=/^\+[1-9]\d{6,14}$/;var Vg="(?:(?:\\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])))";function fk(e){return new RegExp(`^${e}$`)}var Wg=fk(Vg);function Rl(e){return typeof e.precision==="number"?e.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":e.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${e.precision}}`:e.seconds?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?":"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function Hg(e){return new RegExp(`^${Rl(e)}$`)}function Kg(e){let t=["Z"];if(e.offset)t.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let n=`${Rl({precision:e.precision,seconds:!0})}(?:${t.join("|")})`,r=e.local?`${n}|${Rl({precision:e.precision})}`:n;return new RegExp(`^${Vg}T(?:${r})$`)}var Zg=/^[\s\S]{0,}$/;var Nl=/^-?\d+$/,bo=/^-?\d+(?:\.\d+)?$/,jg=/^(?:true|false)$/i;var Gg=/^[^A-Z]*$/,qg=/^[^a-z]*$/;var yt=N("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])});var Dl=(e)=>{let t=e.value;return!Zm(t)&&t.length!==void 0},Aa={number:"number",bigint:"bigint",object:"date"},$l=N("$ZodCheckLessThan",(e,t)=>{yt.init(e,t);let n=Aa[typeof t.value];e._zod.check=(r)=>{if(t.inclusive?r.value<=t.value:r.value<t.value)return;r.issues.push({origin:Aa[typeof r.value]??n,code:"too_big",maximum:typeof t.value==="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Ol=N("$ZodCheckGreaterThan",(e,t)=>{yt.init(e,t);let n=Aa[typeof t.value];e._zod.check=(r)=>{if(t.inclusive?r.value>=t.value:r.value>t.value)return;r.issues.push({origin:Aa[typeof r.value]??n,code:"too_small",minimum:typeof t.value==="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Xg=N("$ZodCheckMultipleOf",(e,t)=>{yt.init(e,t),e._zod.check=(n)=>{if(typeof n.value!==typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof n.value==="bigint"?t.value!==BigInt(0)&&n.value%t.value===BigInt(0):jm(n.value,t.value)===0)return;n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Jg=N("$ZodCheckNumberFormat",(e,t)=>{yt.init(e,t),t.format=t.format||"float64";let n=t.format?.includes("int"),r=n?"int":"number",[i,o]=ga[t.format];e._zod.check=(s)=>{let a=s.value;if(n){if(!Number.isInteger(a)){s.issues.push({expected:r,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){if(a>0)s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort});else s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}if(a<i)s.issues.push({origin:"number",input:a,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort});if(a>o)s.issues.push({origin:"number",input:a,code:"too_big",maximum:o,inclusive:!0,inst:e,continue:!t.abort})}});var Qg=N("$ZodCheckMaxLength",(e,t)=>{var n;yt.init(e,t),(n=e._zod.def).when??(n.when=Dl),e._zod.check=(r)=>{let i=r.value,o=i.length;if((typeof i==="string"&&o>t.maximum?xa(i):o)<=t.maximum)return;let a=ba(i);r.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),Yg=N("$ZodCheckMinLength",(e,t)=>{var n;yt.init(e,t),(n=e._zod.def).when??(n.when=Dl),e._zod.check=(r)=>{let i=r.value,o=i.length;if((typeof i==="string"&&o>=t.minimum&&o<t.minimum*2?xa(i):o)>=t.minimum)return;let a=ba(i);r.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),ey=N("$ZodCheckLengthEquals",(e,t)=>{var n;yt.init(e,t),(n=e._zod.def).when??(n.when=Dl),e._zod.check=(r)=>{let i=r.value,o=i.length,s=typeof i==="string"&&o>=t.length&&o<=t.length*2?xa(i):o;if(s===t.length)return;let a=ba(i),c=s>t.length;r.issues.push({origin:a,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),So=N("$ZodCheckStringFormat",(e,t)=>{var n,r;if(yt.init(e,t),t.pattern)(n=e._zod).check??(n.check=(i)=>{if(t.pattern.lastIndex=0,t.pattern.test(i.value))return;i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})});else(r=e._zod).check??(r.check=()=>{})}),ty=N("$ZodCheckRegex",(e,t)=>{So.init(e,t),e._zod.check=(n)=>{if(t.pattern.lastIndex=0,t.pattern.test(n.value))return;n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),ry=N("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Gg),So.init(e,t)}),ny=N("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=qg),So.init(e,t)}),iy=N("$ZodCheckIncludes",(e,t)=>{yt.init(e,t);let n=gi(t.includes),r=new RegExp(typeof t.position==="number"?`^.{${t.position},}${n}`:n);t.pattern=r,e._zod.check=(i)=>{if(i.value.includes(t.includes,t.position))return;i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:i.value,inst:e,continue:!t.abort})}}),oy=N("$ZodCheckStartsWith",(e,t)=>{yt.init(e,t);let n=new RegExp(`^${gi(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.check=(r)=>{if(r.value.startsWith(t.prefix))return;r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),sy=N("$ZodCheckEndsWith",(e,t)=>{yt.init(e,t);let n=new RegExp(`.*${gi(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.check=(r)=>{if(r.value.endsWith(t.suffix))return;r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}});var ay=N("$ZodCheckOverwrite",(e,t)=>{yt.init(e,t),e._zod.check=(n)=>{n.value=t.tx(n.value)}});class Ll{constructor(e=[],t={}){this.content=[],this.indent=0,this.args=e,this.closed=t}indented(e){this.indent+=1;try{e(this)}finally{this.indent-=1}}write(e){if(typeof e==="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
96
+ No logout is needed: the WFP filter keys on the dedicated \`srt-sandbox\` user's SID, so your network is unaffected.`}function X0(e){try{return{status:"fulfilled",value:e()}}catch(t){return{status:"rejected",reason:t}}}function ym(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 o=t.value;if(!o.provisioned||!o.credPresent)r.push(`Sandbox user is not provisioned (user=${o.provisioned}, cred=${o.credPresent}). `+Xu(e));let s=n();if(s.status==="rejected")return r.push(`srt-win wfp status failed: ${s.reason.message}`),{errors:r,warnings:i};let a=s.value;if(a.state==="cannot-read")w(`[Sandbox Windows] wfp status cannot-read (non-elevated): ${a.hint}`);else if(a.state!=="installed"){if(o.provisioned&&o.credPresent)r.push(`WFP filters not installed under sublayer ${e??"(default)"}. `+Xu(e))}else if(a.portRange)w(`[Sandbox Windows] WFP installed: ${a.filters} filters, proxy port range ${a.portRange[0]}-${a.portRange[1]}`);return{errors:r,warnings:i}}function vm(e={}){let t;try{t=e.srtWin??Nt()}catch(n){return{errors:[n.message],warnings:[]}}return w(`[Sandbox Windows] using srt-win at ${t.exe}`),ym(e.sublayerGuid,X0(()=>el({srtWin:t})),()=>X0(()=>sm({sublayerGuid:e.sublayerGuid,srtWin:t})))}async function sl(e={}){let t;try{t=e.srtWin??Nt()}catch(i){return{errors:[i.message],warnings:[]}}w(`[Sandbox Windows] using srt-win at ${t.exe}`);let[n,r]=await Promise.allSettled([so({srtWin:t}),am({sublayerGuid:e.sublayerGuid,srtWin:t})]);return ym(e.sublayerGuid,n,()=>r)}import{isIP as QT}from"net";function ao(e){if(e.startsWith("[")){let r=e.indexOf("]");if(r===-1)return{hostPattern:e,port:void 0};let i=e.slice(1,r),o=xt(i)??i,s=e.slice(r+1);if(s==="")return{hostPattern:o,port:void 0};let a=xm(s.startsWith(":")?s.slice(1):"");return a===void 0?{hostPattern:e,port:void 0}:{hostPattern:o,port:a}}let t=e.lastIndexOf(":");if(t===-1)return{hostPattern:e,port:void 0};if(e.indexOf(":")!==t)return{hostPattern:xt(e)??e,port:void 0};let n=xm(e.slice(t+1));if(n===void 0)return{hostPattern:e,port:void 0};return{hostPattern:e.slice(0,t),port:n}}function xm(e){if(!/^[1-9][0-9]{0,4}$/.test(e))return;let t=Number(e);return t>65535?void 0:t}function wn(e){return ao(e).hostPattern}function Or(e,t){let n=e.toLowerCase();if(t==="*")return!0;if(t.startsWith("*.")){if(QT(tr(n)))return!1;let r=t.substring(2).toLowerCase();return n.endsWith("."+r)}return n===t.toLowerCase()}function co(e,t,n){let{hostPattern:r,port:i}=ao(n);if(i!==void 0&&i!==t)return!1;return Or(e,r)}function ca(e,t){let n=t.map(wn);if(!e.startsWith("*."))return n.some((i)=>Or(e,i));let r=e.slice(2).toLowerCase();return n.some((i)=>{if(!i.startsWith("*."))return!1;let o=i.slice(2).toLowerCase();return r===o||r.endsWith("."+o)})}import{isIP as YT}from"net";var bm="<allowAllDomains>";function al(e,t,n,r){if(!ni(t))return{verdict:"deny",reason:"malformed host"};let i=xt(t)??t,o=!1;for(let s of e.deniedDomains)if(co(i,n,s)){if(e.allowAllDomains&&e.allowlistCarveOuts?.includes(s)){o=!0;continue}return{verdict:"deny",reason:e.deniedDomainReasons?.[s]??"host is on the deny list",rule:s}}for(let s of o?[]:e.allowedDomains)if(co(i,n,s))return{verdict:"allow",rule:s};if(e.allowAllDomains){if(Ts(i)||YT(i)!==0&&!_s(i))return{verdict:"deny",reason:"host is not on the public internet"};return{verdict:"allow",rule:bm}}if(!r||e.strictAllowlist)return{verdict:"deny",reason:"host is not on the allow list"};return{verdict:"ask"}}function cl(e,t,n){if(!e.allowAllDomains)return!1;let r=al(e,t,n,!1);return r.verdict==="allow"&&r.rule===bm}async function Sm(e,t,n,r,i){if(cl(e,t,n))return th(t,r);if(e.refuseLocalDestinations)return nh(t,r,i);return t}import{EOL as ul}from"os";import{dirname as ll}from"path";var O,lo,fo,po,Gt,Qr,Yr,Cm=!1,ua,hi,tn,De,rn,Tn,An,pi,la,wm=!1,gi,_n=new Ys,or=new _u,yi=new Pu,mi=new yu;function Pm(){let e=O?.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)mi.register(r,t,n.hosts,e.url)}return[e.tokenEnvVar]}function tA(e){return O?.network.brokerForward?.rules.some((t)=>t.hosts.includes(e))??!1}var ho=new Iu;function rA(){if(Cm)return;let e=()=>yl().catch((t)=>{w(`Cleanup failed in registerCleanup ${t}`,{level:"error"})});process.once("exit",()=>{let t=An;if(t)mm({sandboxUserSid:t,srtWin:gi}),Tn=void 0,An=void 0;e()}),process.once("SIGINT",e),process.once("SIGTERM",e),Cm=!0}var nA=1024,En=new Map;function Rm(e,t){let n=t?.commandId,r=t?.commandText??e;if(n===void 0||n===r)return;let i=cn(zt(n));En.delete(i),En.set(i,r);while(En.size>nA){let o=En.keys().next().value;if(o===void 0)break;En.delete(o)}}function Em(e){return En.get(e)??e}function fl(e,t){let n=t?(()=>{let r=cn(t);return En.get(r)??Ku(r)})():void 0;if(li(e,n,O?.ignoreViolations))return;_n.addViolation({line:e,encodedCommand:t,command:n,timestamp:new Date})}function iA(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 _m(e,t,n,r){let i=(s)=>(fl(`deny network-outbound ${t}:${e} (${s})`,r),!1);if(!O)return w("No config available, denying network request"),i("sandbox policy unavailable");let o=al(O.network,t,e,n!==void 0);if(o.verdict==="allow")return w(`Allowed by config rule: ${t}:${e}`),!0;if(o.verdict==="deny"){if(o.reason==="malformed host")w(`Denying malformed host: ${JSON.stringify(t)}:${e}`,{level:"error"});else if(o.rule!==void 0)w(`Denied by config rule: ${t}:${e}`);else w(`No matching config rule, denying: ${t}:${e}`);return i(o.reason)}w(`No matching config rule, asking user: ${t}:${e}`);try{if(await n({host:t,port:e}))return w(`User allowed: ${t}:${e}`),!0;return w(`User denied: ${t}:${e}`),i("user denied")}catch(s){return w(`Error in permission callback: ${s}`,{level:"error"}),i("permission prompt failed")}}var fa=!1;function oA(e){fa=e}function sA(){if(!fa&&!O?.credentials)return;return(e,t)=>{if(!O?.credentials)return;or.substituteInHeaders(e,t,Or)}}function aA(){if(!fa&&!O?.credentials)return;return(e)=>O?.credentials?or.sentinelsForHost(e,Or):void 0}function cA(){if(!fa&&!O?.credentials)return;return(e,t,n,r)=>!O?.credentials?void 0:s0(yi,O?.credentials?.sigv4,Or)(e,t,n,r)}function uA(e){if(!O?.network.mitmProxy)return;let{socketPath:t,domains:n}=O.network.mitmProxy,r=xt(e)??e;for(let i of n)if(Or(r,i))return w(`Host ${e} matches MITM pattern ${i}`),t;return}function lA(e,t=443){if(O&&cl(O.network,xt(e)??e,t))return!1;let n=O?.network.tlsTerminate?.excludeDomains;if(!n?.length)return!0;let r=xt(e)??e;if(tA(r))return!0;for(let i of n){if(!Or(r,i))continue;w(`Host ${e} matches tlsTerminate.excludeDomains pattern ${i}; skipping TLS termination`);let o=or.namesInjectableAt(r,Or);if(o.length>0)w(`tlsTerminate.excludeDomains: masked credential(s) ${o.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 Tm(e,t){let n=xt(e)??e;return O?Sm(O.network,n,t):n}async function fA(e,t){let n=sA(),r=aA();lo=Oh({filter:(a,c,u,l)=>_m(a,c,e,l),getMitmSocketPath:uA,mitmCA:De,shouldTerminateTLS:lA,resolveDestination:Tm,filterRequest:O?.network.filterRequest,onFilterRequestDenied:({method:a,url:c,reason:u,encodedCommand:l})=>{fl(`deny http-request ${a} ${iA(c)} (${u})`,l)},mutateHeaders:n,mutateHeadersPlaintext:O?.credentials?.allowPlaintextInject?n:void 0,getBrokerForward:(a,c)=>O?.network.brokerForward?mi.forwardFor(a,c):void 0,getBodySubstitutions:r,getBodySubstitutionsPlaintext:O?.credentials?.allowPlaintextInject?r:void 0,planSigv4:cA(),parentProxy:tn,proxyAuthToken:rn}),fo=Kh({filter:(a,c,u)=>_m(a,c,e,u),resolveDestination:Tm,parentProxy:tn,proxyAuthToken:rn,probeUnauthenticated:async(a,c)=>{if(!O)return{};let u=xt(c)??c;for(let l of O.network.deniedDomains){if(O.network.allowAllDomains&&O.network.allowlistCarveOuts?.includes(l))continue;if(co(u,a,l)){let f=O.network.deniedDomainReasons?.[l]??"host is on the deny list";return fl(`deny network-outbound ${c}:${a} (${f})`,void 0),{deniedReason:f}}}return{}}}),po=Gh({httpServer:lo,handleSocksConnection:(a)=>fo.handleConnection(a),httpBackendPortRange:t});let i=po,o=await i.listenHttpBackend();await Us(i.server,(a)=>i.server.listen(a,"127.0.0.1"),t,o!==void 0?new Set([o]):new Set);let s=i.getPort();if(s===void 0)throw Error("Failed to get mux proxy server port");return i.unref(),w(`Mux proxy (HTTP+SOCKS) listening on localhost:${s}`),s}async function dA(e,t,n=!1){if(await Yr?.catch(()=>{return}),await pi?.catch(()=>{return}),Qr){await Qr;return}if(O=e,tn=du(e.network.parentProxy),tn)w(`Parent proxy configured: http=${mu(tn.httpUrl)} https=${mu(tn.httpsUrl)}`);if(e.network.tlsTerminate&&e.network.mitmProxy)throw Error("network.tlsTerminate and network.mitmProxy are mutually exclusive");let r=e.network.tlsTerminate,i=Ie()==="windows"&&r!==void 0&&!r.caCertPath&&!r.caKeyPath;if(De=r&&!i?ou(r):void 0,De&&e.runAsHostUid!==void 0&&Ie()==="linux"){if(en.chmodSync(ll(De.trustBundlePath),457),en.chmodSync(De.trustBundlePath,420),De.ephemeral)en.chmodSync(ll(De.certPath),457),en.chmodSync(De.certPath,420)}let o=await Dm();if(o.errors.length>0)throw Error(`Sandbox dependencies not available: ${o.errors.join(", ")}`);if(n&&Ie()==="macos")ua=H0(_n.addViolation.bind(_n),O.ignoreViolations,Em),w("Started macOS sandbox log monitor");if(n&&Ie()==="linux")hi=j0(_n.addViolation.bind(_n),{allowWritePaths:[...Nn(e.runAsHostHome),...O.filesystem.allowWrite],denyWritePaths:O.filesystem.denyWrite,ignoreViolations:O.ignoreViolations,resolveCommandText:Em,consumerUid:e.runAsHostUid,consumerGid:e.runAsHostGid}),hi.ready,w("Started Linux seccomp violation monitor");if(rA(),Ie()==="windows"){gi=Nt(e.windows?.srtWin);let s=gi,a=await so({srtWin:s});if(!a.provisioned||!a.credPresent)throw O=void 0,new me("not_provisioned",`Windows sandbox user is not provisioned (user=${a.provisioned}, cred=${a.credPresent}). Run \`npx sandbox-runtime windows-install\` (one UAC prompt) to provision it.`);if(!wm){try{await Yu({proxyPortRange:e.windows?.proxyPortRange,srtWin:s})}catch(c){throw O=void 0,c}wm=!0}if(i&&r)try{let c=await rl({status:a,srtWin:s});De=ou({caCertPem:c.certPem,caKeyPem:c.keyPem,caCertPath:c.certPath,caKeyPath:c.keyPath,extraCaCertPaths:r.extraCaCertPaths})}catch(c){throw O=void 0,c}if(r&&De&&!i){let c=tl(a),u=Yn(De.certPem);if(!c)throw O=void 0,new me("trust_ca_not_installed",`tlsTerminate on Windows requires the sandbox to be installed with this CA (thumb=${u}): run \`srt-win user trust-ca ${De.certPath}\`. Per-exec installs into the sandbox user's Root store are not supported.`);if(c.thumb!==u)throw O=void 0,new me("trust_ca_thumbprint_mismatch",`tlsTerminate on Windows: the sandbox's installed CA (thumb=${c.thumb}) doesn't match this session's CA (thumb=${u}). Run \`srt-win user trust-ca ${De.certPath}\` to update it.`)}try{let c=yA(e);if(De)c.grantRead.push(ll(De.trustBundlePath));if(!a.sid)throw Error("sandbox user SID missing from `srt-win user status` (provisioned but in an inconsistent state)");let u=a.sid;An=u;let l=async()=>{if(c.grantRead.length>0||c.grantWrite.length>0)await ol({sandboxUserSid:u,read:c.grantRead,write:c.grantWrite,srtWin:s});if(c.denyRead.length>0||c.denyWrite.length>0)await il({sandboxUserSid:u,denyRead:c.denyRead,denyWrite:c.denyWrite,srtWin:s});if(c.grantRead.length>0||c.grantWrite.length>0||c.denyRead.length>0||c.denyWrite.length>0)Tn=c,w(`[Sandbox Windows] fs applied: ${c.grantWrite.length} grantWrite, ${c.grantRead.length} grantRead, ${c.denyRead.length} denyRead, ${c.denyWrite.length} denyWrite`)},f=(async()=>{try{await l()}catch(p){throw await aa({sandboxUserSid:u,srtWin:s}),await sa({sandboxUserSid:u,srtWin:s}),An=void 0,p}})();pi=f;try{await f}finally{if(pi===f)pi=void 0}if(Yr)throw Error("Sandbox was reset during initialization");la=Om(e)}catch(c){throw O=void 0,await Yr?.catch(()=>{return}),c}}Qr=(async()=>{try{let s=Ie()==="windows"?O.windows?.proxyPortRange??ta:void 0;rn=O.network.httpProxyPort!==void 0?void 0:eA(16).toString("hex");let c=O.network.httpProxyPort===void 0||O.network.socksProxyPort===void 0?await fA(t,s):void 0,u=O.network.httpProxyPort??c,l=O.network.socksProxyPort??c;if(De&&c!==void 0&&Ie()==="windows")De.crlUrl=`http://127.0.0.1:${c}${Ss}`;if(O.network.httpProxyPort!==void 0)w(`Using external HTTP proxy on port ${u}`);if(O.network.socksProxyPort!==void 0)w(`Using external SOCKS proxy on port ${l}`);let f;if(Ie()==="linux")f=await $0(u,l,O.socatPath,O.runAsHostUid,O.runAsHostGid);let p={httpProxyPort:u,socksProxyPort:l,linuxBridge:f};return Gt=p,w("Network infrastructure initialized"),p}catch(s){throw Qr=void 0,Gt=void 0,yl().catch((a)=>{w(`Cleanup failed in initializationPromise ${a}`,{level:"error"})}),s}})(),await Qr}function Bm(){let e=Ie();if(e==="linux")return Ga()!=="1";return e==="macos"||e==="windows"}function pA(){return O!==void 0}function Nm(e){if(!Bm())return{done:{errors:["Unsupported platform"],warnings:[]}};let t=[],n=[],r=Ie();if(r==="linux"){let i=e??O?.ripgrep??{command:"rg"};if(Nr(i.command)===null)t.push(`ripgrep (${i.command}) not found`);let o=D0({seccompConfig:O?.seccomp,bwrapPath:O?.bwrapPath,socatPath:O?.socatPath});t.push(...o.errors),n.push(...o.warnings)}else if(r==="windows"){let i;try{i=Nt(O?.windows?.srtWin)}catch(o){return t.push(o.message),{done:{errors:t,warnings:n}}}return{windows:{sublayerGuid:O?.windows?.sublayerGuid??O?.windows?.wfpSublayerGuid,srtWin:i}}}return{done:{errors:t,warnings:n}}}function hA(e){let t=Nm(e);if("done"in t)return t.done;return vm(t.windows)}async function Dm(e){let t=Nm(e);if("done"in t)return t.done;return sl(t.windows)}function pl(e,t){if(!e)return{denyReadPaths:[],unsetEnvVars:[],setEnvVars:{},maskedFileBinds:[],maskedFileStoreDir:void 0};let n=da(e),r=[...new Set((t??[]).map(wn))],i=[];for(let l of e.envVars??[])if(l.mode==="deny")i.push(l.name);let{setEnvVars:o,degradeToUnsetNames:s}=t0(e.envVars??[],r,or);i.push(...s),o0(e.envVars??[],e.awsPairs,r,o,yi);let a=e.files??[],{binds:c,degradeToDenyPaths:u}=e0(a,r,or,ho);return{denyReadPaths:[...new Set([...n,...u])],unsetEnvVars:[...new Set(i)],setEnvVars:o,maskedFileBinds:c,maskedFileStoreDir:ho.dirPath}}function da(e){let t=e?.files??[];return[...new Set(t.filter((n)=>n.mode==="deny").map((n)=>n.path))]}function $m(e,t){return[...new Set([...e,...t.denyReadPaths])]}function mA(){if(!O||O.filesystem.disabled)return{denyOnly:[],allowWithinDeny:[]};let e=$m(O.filesystem.denyRead,pl(O.credentials,O.network.allowedDomains)),t=[];for(let r of e){let i=Tr(r);if(Ie()==="linux"&&bt(i)){let o=un(r);w(`[Sandbox] Expanded glob pattern "${r}" to ${o.length} paths on Linux`),t.push(...o)}else t.push(i)}let n=[];for(let r of O.filesystem.allowRead??[]){let i=Tr(r);if(Ie()==="linux"&&bt(i)){let o=un(r);w(`[Sandbox] Expanded allowRead glob pattern "${r}" to ${o.length} paths on Linux`),n.push(...o)}else n.push(i)}return{denyOnly:t,allowWithinDeny:n}}function gA(){if(!O)return{allowOnly:Nn(),denyWithinAllow:[]};if(O.filesystem.disabled)return{allowOnly:["/"],denyWithinAllow:[]};let e=O.filesystem.allowWrite.map((r)=>Tr(r)).filter((r)=>{if(Ie()==="linux"&&bt(r))return w(`Skipping glob pattern on Linux/WSL: ${r}`),!1;return!0}),t=O.filesystem.denyWrite.map((r)=>Tr(r)).filter((r)=>{if(Ie()==="linux"&&bt(r))return w(`Skipping glob pattern on Linux/WSL: ${r}`),!1;return!0});return{allowOnly:[...Nn(dl()),...e],denyWithinAllow:t}}function yA(e){let t=e.filesystem;if(t?.disabled)return{grantRead:[],grantWrite:[],denyRead:[],denyWrite:[]};let n=oa,r=n([...new Set([...t?.denyRead??[],...da(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 Om(e){return{disabled:e.filesystem.disabled??!1,denyRead:[...e.filesystem.denyRead],denyWrite:[...e.filesystem.denyWrite],allowRead:[...e.filesystem.allowRead??[]],allowWrite:[...e.filesystem.allowWrite],credFiles:da(e.credentials)}}function uo(e,t){if(e.length!==t.length)return!1;let n=new Set(e);return t.every((r)=>n.has(r))}function vA(e,t){return e.disabled===t.disabled&&uo(e.denyRead,t.denyRead)&&uo(e.denyWrite,t.denyWrite)&&uo(e.allowRead,t.allowRead)&&uo(e.allowWrite,t.allowWrite)&&uo(e.credFiles,t.credFiles)}function xA(e){return la!==void 0&&vA(la,Om(e))}function bA(){if(!O)return{};let e=O.network.allowedDomains,t=O.network.deniedDomains;return{allowedHosts:e,...t.length>0&&{deniedHosts:t}}}function Lm(){return O?.network?.allowUnixSockets}function Am(){return O?.network?.allowAllUnixSockets}function Um(){return O?.network?.allowLocalBinding}function zm(){return O?.network?.allowMachLookup}function Fm(){return O?.ignoreViolations}function Mm(){return O?.enableWeakerNestedSandbox}function SA(){return O?.runAsUid}function CA(){return O?.runAsGid}function wA(){return O?.runAsHostUid}function EA(){return O?.runAsHostGid}function dl(){return O?.runAsHostHome}function _A(){return O?.runAsHostUser}function TA(){return O?.enableWeakerNetworkIsolation}function AA(){return O?.allowAppleEvents}function kA(){return O?.ripgrep??{command:"rg"}}function IA(){return O?.mandatoryDenySearchDepth??3}function km(){return O?.filesystem?.allowGitConfig??!1}function Vm(e){return[...O?.git?.safeDirectories??[],...e?.git?.safeDirectories??[]]}function PA(){return O?.seccomp}function RA(){return rn}function hl(){return Gt?.httpProxyPort}function ml(){return Gt?.socksProxyPort}function Wm(){return Gt?.linuxBridge?.httpSocketPath}function Hm(){return Gt?.linuxBridge?.socksSocketPath}async function gl(){if(!O)return!1;if(Qr)try{return await Qr,!0}catch{return!1}return Gt!==void 0}async function Km(e,t,n,r,i){let o=Ie(),s=i?.commandId;Rm(e,i);let a=n?.filesystem!==void 0?n.filesystem.disabled??!1:O?.filesystem.disabled??!1,c=pl(n?.credentials??O?.credentials,n?.network?.allowedDomains??O?.network?.allowedDomains);c.unsetEnvVars.push(...Pm());let u,l;if(!a){let v=(k)=>k.map((R)=>Tr(R)).filter((R)=>{if(Ie()==="linux"&&bt(R))return w(`[Sandbox] Skipping glob write pattern on Linux: ${R}`),!1;return!0}),b=v(n?.filesystem?.allowWrite??O?.filesystem.allowWrite??[]);u={allowOnly:[...Nn(n?.runAsHostHome??dl()),...b],denyWithinAllow:v(n?.filesystem?.denyWrite??O?.filesystem.denyWrite??[])};let S=$m(n?.filesystem?.denyRead??O?.filesystem.denyRead??[],c),C=[];for(let k of S){let R=Tr(k);if(Ie()==="linux"&&bt(R))C.push(...un(k));else C.push(R)}let T=n?.filesystem?.allowRead??O?.filesystem.allowRead??[],I=[];for(let k of T){let R=Tr(k);if(Ie()==="linux"&&bt(R))I.push(...un(k));else I.push(R)}if(De)I.push(De.certPath,De.trustBundlePath);l={denyOnly:C,allowWithinDeny:I}}let f=n?.network?.allowedDomains!==void 0||O?.network?.allowedDomains!==void 0,p=f,h=f;if(h)await gl();let d=n?.allowPty??O?.allowPty,g=Vm(n);switch(o){case"macos":return W0({command:e,commandId:s,needsNetworkRestriction:p,httpProxyPort:h?hl():void 0,socksProxyPort:h?ml():void 0,proxyAuthToken:h?rn:void 0,caCertPath:De?.trustBundlePath,readConfig:l,writeConfig:u,unsetEnvVars:c.unsetEnvVars,setEnvVars:c.setEnvVars,maskedFileBinds:c.maskedFileBinds,allowUnixSockets:Lm(),allowAllUnixSockets:Am(),allowLocalBinding:Um(),allowMachLookup:zm(),ignoreViolations:Fm(),allowPty:d,allowGitConfig:km(),gitSafeDirectories:g,enableWeakerNetworkIsolation:TA(),allowAppleEvents:AA(),binShell:t});case"linux":return L0({command:e,commandId:s,needsNetworkRestriction:p,httpSocketPath:h?Wm():void 0,socksSocketPath:h?Hm():void 0,httpProxyPort:h?Gt?.httpProxyPort:void 0,socksProxyPort:h?Gt?.socksProxyPort:void 0,proxyAuthToken:h?rn:void 0,caCertPath:De?.trustBundlePath,readConfig:l,writeConfig:u,unsetEnvVars:c.unsetEnvVars,setEnvVars:c.setEnvVars,maskedFileBinds:c.maskedFileBinds,maskedFileStoreDir:c.maskedFileStoreDir,enableWeakerNestedSandbox:Mm(),runAsUid:SA(),runAsGid:CA(),runAsHostUid:wA(),runAsHostGid:EA(),runAsHostHome:dl(),runAsHostUser:_A(),setprivPath:"/usr/bin/setpriv",allowAllUnixSockets:Am(),binShell:t,ripgrepConfig:kA(),mandatoryDenySearchDepth:IA(),allowGitConfig:km(),gitSafeDirectories:g,seccompConfig:PA(),bwrapPath:O?.bwrapPath,socatPath:O?.socatPath,observeSocketPath:hi?.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: ${o}`)}}async function BA(e,t,n,r,i,o){if(Ie()==="windows"){let u=n?.network?.allowedDomains!==void 0||O?.network?.allowedDomains!==void 0;if(u)await gl();let l=pl(n?.credentials??O?.credentials,n?.network?.allowedDomains??O?.network?.allowedDomains);l.unsetEnvVars.push(...Pm());let f=n?.filesystem,p=[],h=[];if(!f?.disabled){if(f?.allowRead?.length||f?.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 d=[...f?.denyRead??[],...da(n?.credentials)],g=f?.denyWrite??[];if(d.length>0||g.length>0){let v=new Set(Tn?.denyRead??[]),b=new Set(Tn?.denyWrite??[]),S=oa;p=S(d,{mode:"deny"}).filter((C)=>!v.has(C)),h=S(g,{mode:"deny"}).filter((C)=>!v.has(C)&&!b.has(C))}}return Rm(e,o),gm({command:e,commandId:o?.commandId,httpProxyPort:u?hl():void 0,socksProxyPort:u?ml():void 0,proxyAuthToken:u?rn:void 0,setEnvVars:l.setEnvVars,denyRead:p,denyWrite:h,cwd:i,allowWrite:Tn?.grantWrite,gitSafeDirectories:Vm(n),caCertPath:De?.trustBundlePath,binShell:ra(t),srtWin:n?.windows?.srtWin?Nt(n.windows.srtWin):gi??Nt(O?.windows?.srtWin)})}if(typeof t==="object")throw Error("binShell object form is Windows-only; pass a shell path string on macOS/Linux");let a=await Km(e,t,n,r,o);return{argv:[t??"/bin/bash","-c",a],env:process.env}}function NA(){return O}function DA(){or.clear(),yi.clear(),mi.clear(),ho.dispose()}function $A(e){if(Ie()==="windows"&&O&&!xA(e))w("[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;O=structuredClone({...e,network:n}),O.network.filterRequest=t,tn=du(e.network.parentProxy),w("Sandbox configuration updated")}function OA(){Qs()}var LA=1500;function Im(e,t){if(!e.pid||e.exitCode!==null||e.signalCode!==null)return Promise.resolve();try{process.kill(e.pid,"SIGTERM"),w(`Sent SIGTERM to ${t} bridge process`)}catch(n){if(n.code!=="ESRCH")w(`Error killing ${t} bridge: ${n}`,{level:"error"});return Promise.resolve()}return new Promise((n)=>{let r=!1,i=()=>{if(r)return;r=!0,clearTimeout(o),n()};e.once("exit",()=>{w(`${t} bridge process exited`),i()});let o=setTimeout(()=>{if(e.exitCode===null&&e.signalCode===null){w(`${t} bridge did not exit, forcing SIGKILL`,{level:"warn"});try{if(e.pid)process.kill(e.pid,"SIGKILL")}catch{}}i()},LA);o.unref?.()})}function UA(e){return new Promise((t)=>{if(typeof e.closeAllConnections==="function")e.closeAllConnections();e.close((n)=>{if(n&&n.message!=="Server is not running.")w(`Error closing HTTP proxy server: ${n.message}`,{level:"error"});t()})})}async function zA(){if(pi)await pi.catch(()=>{return});if(Tn&&An){let t=An,n=gi,r=new Set(["revoked","stillHeld","restored","alreadyOriginal"]),i=(o,s)=>{if(!r.has(s.status))w(`[Sandbox Windows] ${o}: '${s.path}' ${s.status} \u2014 `+"ACE may be left in place; resolve and run `srt-win acl recover` to clear",{level:"warn"})};for(let o of await aa({sandboxUserSid:t,srtWin:n})??[])i("grant revoke",o);for(let o of await sa({sandboxUserSid:t,srtWin:n})??[])i("deny restore",o)}if(Tn=void 0,An=void 0,la=void 0,gi=void 0,Qs({force:!0}),ua)ua(),ua=void 0;if(hi)hi.stop(),hi=void 0;if(Gt?.linuxBridge){let{httpSocketPath:t,socksSocketPath:n,httpBridgeProcess:r,socksBridgeProcess:i}=Gt.linuxBridge;if(await Promise.all([Im(r,"HTTP"),Im(i,"SOCKS")]),t)try{en.rmSync(t,{force:!0}),w("Cleaned up HTTP socket")}catch(o){w(`HTTP socket cleanup error: ${o}`,{level:"error"})}if(n)try{en.rmSync(n,{force:!0}),w("Cleaned up SOCKS socket")}catch(o){w(`SOCKS socket cleanup error: ${o}`,{level:"error"})}}let e=[];if(De)e.push(Jp(De));if(po)e.push(po.close().catch((t)=>{w(`Error closing mux proxy server: ${t.message}`,{level:"error"})}));if(lo)e.push(UA(lo));if(fo){let t=fo.close().catch((n)=>{w(`Error closing SOCKS proxy server: ${n.message}`,{level:"error"})});e.push(t)}await Promise.all(e),po=void 0,lo=void 0,rn=void 0,fo=void 0,Gt=void 0,Qr=void 0,tn=void 0,De=void 0,or.clear(),yi.clear(),ho.dispose()}async function yl(){if(Yr)return Yr;Yr=zA();try{await Yr}finally{Yr=void 0}}function FA(){return _n}function MA(e,t){if(!O)return t;let n=_n.getViolationsForCommand(e);if(n.length===0)return t;let r=t;r+=ul+"<sandbox_violations>"+ul;for(let i of n)r+=i.line+ul;return r+="</sandbox_violations>",r}function VA(){if(Ie()!=="linux"||!O||O.filesystem.disabled)return[];let e=[],t=[...O.filesystem.allowWrite,...O.filesystem.denyWrite];for(let n of t){let r=Tr(n);if(bt(r))e.push(n)}return e}var WA={initialize:dA,isSupportedPlatform:Bm,isSandboxingEnabled:pA,checkDependencies:hA,checkDependenciesAsync:Dm,getFsReadConfig:mA,getFsWriteConfig:gA,getNetworkRestrictionConfig:bA,getAllowUnixSockets:Lm,getAllowLocalBinding:Um,getAllowMachLookup:zm,getIgnoreViolations:Fm,getEnableWeakerNestedSandbox:Mm,getProxyPort:hl,getProxyAuthToken:RA,getSocksProxyPort:ml,getLinuxHttpSocketPath:Wm,getLinuxSocksSocketPath:Hm,waitForNetworkInitialization:gl,wrapWithSandbox:Km,wrapWithSandboxArgv:BA,cleanupAfterCommand:OA,beginCredentialLease:()=>{or.beginLease(),mi.beginLease()},endCredentialLease:()=>Object.assign(or.endLease(),{brokerForward:mi.endLease()}),releaseCredentialLease:(e)=>{mi.release(e.brokerForward??[]),yi.forget(or.release(e))},reset:yl,getMitmCA:()=>De,getSentinelRegistry:()=>or,getAwsPairRegistry:()=>yi,getMaskedFileStore:()=>ho,getSandboxViolationStore:FA,annotateStderrWithSandboxFailures:MA,getLinuxGlobPatternWarnings:VA,getConfig:NA,updateConfig:$A,clearMaskedCredentials:DA,setLiveCredentialInjectors:oA};import{isIP as GI}from"net";import{isAbsolute as qI}from"path";function yo(e){let t=Object.values(e).filter((r)=>typeof r==="number");return Object.entries(e).filter(([r,i])=>t.indexOf(+r)===-1).map(([r,i])=>i)}function xl(e,t="|"){return e.map((n)=>Cl(n)).join(t)}function vo(e,t){if(typeof t==="bigint")return t.toString();return t}class Zm{constructor(e){this._getter=e,this._value=void 0}get value(){let e=this._getter;if(e!==void 0)this._value=e(),this._getter=void 0;return this._value}}function pa(e){return new Zm(e)}function jm(e){return e===null||e===void 0}function ha(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function Gm(e,t){let n=e/t,r=Math.round(n),i=4*Number.EPSILON*Math.max(Math.abs(n),1);if(Math.abs(n-r)<i)return 0;return n-r}function sr(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function ma(e){let t=Object.getOwnPropertyDescriptor(e,"shape");return t?.get?t.get.raw:t?.value}function Lr(e){return ma(e._zod.def)??e._zod.def.shape}function qm(e,t,n){Object.defineProperty(e,t,{get(){let r=n();return sr(this,t,r),r},enumerable:!0,configurable:!0})}function Xm(e,t,n){if(t in e)sr(e,t,n);else e[t]=n}function kn(e,t,n,r){let i=Lr(t);for(let o of n){let s=Object.getOwnPropertyDescriptor(i,o);if(!s.enumerable)continue;if(s.get)qm(e,o,()=>{let a=t._zod.def.shape[o];return r?r(a,o):a});else Xm(e,o,r?r(s.value,o):s.value)}}function HA(e,t){for(let n of Reflect.ownKeys(t)){let r=Object.getOwnPropertyDescriptor(t,n);if(!r.enumerable)continue;if(r.get)qm(e,n,()=>t[n]);else Xm(e,n,r.value)}}function Dt(...e){let t={};for(let n of e){let r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}function Jm(e){return JSON.stringify(e)}function Qm(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var bl="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function go(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var Ym=pa(()=>{if(Tt.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function In(e){if(go(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;if(typeof t!=="function")return!0;let n=t.prototype;if(go(n)===!1)return!1;if(Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)return!1;return!0}function Sl(e){if(In(e))return{...e};if(Array.isArray(e))return[...e];if(e instanceof Map)return new Map(e);if(e instanceof Set)return new Set(e);return e}var eg=new Set(["string","number","symbol"]);function vi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ar(e,t,n){let r=new e._zod.constr(t??e._zod.def);if(!t||n?.parent)r._zod.parent=e;return r}function Y(e){let t=e;if(!t)return{};if(typeof t==="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}if(delete t.message,typeof t.error==="string")return{...t,error:()=>t.error};return t}function Cl(e){if(typeof e==="bigint")return e.toString()+"n";if(typeof e==="string")return`"${e}"`;return`${e}`}function tg(e){return Object.keys(e).filter((t)=>e[t]._zod.optin!==void 0&&e[t]._zod.optout==="optional")}var ga=(()=>({safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]}))(),wl={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function KA(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let o={};return kn(o,e,ya(e,t)),ar(e,Dt(n,{shape:o,checks:[]}))}function ya(e,t){let n=Lr(e),r=[];for(let i of Reflect.ownKeys(t)){if(!Object.getOwnPropertyDescriptor(n,i)?.enumerable)throw Error(`Unrecognized key: "${String(i)}"`);if(t[i])r.push(i)}return r}function ZA(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let o=new Set(ya(e,t)),s={};return kn(s,e,Reflect.ownKeys(Lr(e)).filter((a)=>!o.has(a))),ar(e,Dt(n,{shape:s,checks:[]}))}function jA(e,t){if(!In(t))throw Error("Invalid input to extend: expected a plain object");let n=e._zod.def.checks;if(n&&n.length>0){let i=Lr(e);for(let o of Reflect.ownKeys(t))if(Object.getOwnPropertyDescriptor(i,o)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return ar(e,Dt(e._zod.def,{shape:rg(e,t)}))}function rg(e,t){let n={};return kn(n,e,Reflect.ownKeys(Lr(e))),HA(n,t),n}function GA(e,t){if(!In(t))throw Error("Invalid input to safeExtend: expected a plain object");return ar(e,Dt(e._zod.def,{shape:rg(e,t)}))}function qA(e,t){if(!t?._zod?.def)throw Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let n={};kn(n,e,Reflect.ownKeys(Lr(e))),kn(n,t,Reflect.ownKeys(Lr(t)));let r=Dt(e._zod.def,{shape:n,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return ar(e,r)}function ng(e,t,n,r="partial"){let o=t._zod.def.checks;if(o&&o.length>0)throw Error(`.${r}() cannot be used on object schemas containing refinements`);let a=n?new Set(ya(t,n)):void 0,c={};return kn(c,t,Reflect.ownKeys(Lr(t)),e&&((u,l)=>a&&!a.has(l)?u:new e({type:"optional",innerType:u}))),ar(t,Dt(t._zod.def,{shape:c,checks:[]}))}function XA(e,t,n){let r=n?new Set(ya(t,n)):void 0,i={};return kn(i,t,Reflect.ownKeys(Lr(t)),(o,s)=>r&&!r.has(s)?o:new e({type:"nonoptional",innerType:o})),ar(t,Dt(t._zod.def,{shape:i}))}function qt(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function ig(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function Cr(e,t){return t.map((n)=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function mo(e){return typeof e==="string"?e:e?.message}function El(e){let t=[];for(let n of e??[]){let r=n._zod.def;if(!/_(length|size)$|_equals$/.test(r.check))break;let i=r.maximum??r.length??r.size;if(i>=0)t.push([i,n])}return t}function va(e,t,n){var r;for(let i=t;i<e.length;i++)(r=e[i]).schema??(r.schema=n)}function wr(e,t,n){var r;let i=e.inst?._zod?.traits;if(i?.has("$ZodType"))if(i.has("$ZodCheck"))(r=e).schema??(r.schema=e.inst);else e.schema=e.inst;let o=e.schema!==e.inst?e.schema?._zod.def?.error:void 0,s=e.message?e.message:mo(e.inst?._zod.def?.error?.(e))??mo(o?.(e))??mo(t?.error?.(e))??mo(n.customError?.(e))??mo(n.localeError?.(e))??"Invalid input",a={};for(let c of Object.keys(e)){if(c==="inst"||c==="schema"||c==="continue"||c==="input"||c==="__proto__")continue;a[c]=e[c]}if(a.path??(a.path=[]),a.message=s,t?.reportInput)a.input=e.input;return a}var JA=/[\uD800-\uDBFF]/;function xa(e){let t=e.length;if(!JA.test(e))return t;let n=t;for(let r=0;r<t-1;r++)if((e.charCodeAt(r)&64512)===55296&&(e.charCodeAt(r+1)&64512)===56320)n--,r++;return n}function ba(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function og(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let n=e;if(n&&Object.getPrototypeOf(n)!==Object.prototype&&"constructor"in n&&n.constructor)return n.constructor.name}}return t}function Pn(...e){let[t,n,r]=e;if(typeof t==="string")return{message:t,code:"custom",input:n,inst:r};return{...t}}function sg(e,t){for(let n in t){let r=Object.getOwnPropertyDescriptor(t,n);if(r.get)Object.defineProperty(e,n,{...r,enumerable:!1});else QA(e,n,r.value)}}function Ur(e,t,n,r=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:r,value:n}),n}function Sa(e,t,n){return Ur(e,t,n,!1)}function ag(e,t){for(let n in e){let r=e[n];Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){return Ur(this,n,r(this))},set(i){Ur(this,n,i)}})}return t}function QA(e,t,n){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?n:Ur(this,t,n.bind(this))},set(r){Ur(this,t,r)}})}function YA(e,t){let n=Object.getPrototypeOf(e);return t in n?void 0:n}var vl,nn=!1,ek={configurable:!0,get(){nn=!0;return}};function Be(e,t,n){let r=Object.getPrototypeOf(e._zod);if(t in r&&vl!==e._zod){vl=void 0;return}vl=e._zod,Object.defineProperty(r,t,{configurable:!0,get(){Object.defineProperty(this,t,ek);let i=nn;nn=!1;try{let o=n(this);if(nn)delete this[t];else Object.defineProperty(this,t,{configurable:!0,writable:!0,value:o});return nn=nn||i,o}catch(o){throw delete this[t],nn=nn||i,o}},set(i){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:i})}})}function tk(e,t,n,r){let i=YA(e,t);if(!i)return;Object.defineProperty(i,t,{configurable:!0,get(){let o={configurable:!0,writable:!0,enumerable:r,value:void 0};return Object.defineProperty(this,t,o),o.value=n(this),Object.defineProperty(this,t,o),o.value},set(o){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:r,value:o})}})}var rk="~constantCatch";function cg(e){let t=()=>e;return t[rk]=!0,t}var ug,fg=Object.freeze({status:"aborted"}),_l={value:void 0,enumerable:!1},lg="captureStackTrace"in Error?Error:null;function nk(e){let t=lg;if(t){let n=t.stackTraceLimit;if(typeof n==="number"){try{t.stackTraceLimit=0}catch{return lg=null,new e}try{return new e}finally{t.stackTraceLimit=n}}}return new e}function N(e,t,n,r){let i={};function o(p){this.def=p,this.constr=f,this.traits=new Set}o.prototype=i;let s=n,a=s&&new WeakSet;function c(p,h){if(!p._zod){_l.value=new o(h);try{Object.defineProperty(p,"_zod",_l)}finally{_l.value=void 0}}else if(p._zod.traits.has(e))return;if(p._zod.traits.add(e),t(p,h),a){let g=Object.getPrototypeOf(p),v=p._zod.constr.prototype,b=g;while(b&&b!==v)b=Object.getPrototypeOf(b);let S=b??g;if(!a.has(S))a.add(S),sg(S,s)}let d=f.prototype;for(let g in d){if(!Object.prototype.hasOwnProperty.call(d,g))continue;if(!(g in p))p[g]=d[g].bind(p)}}let u=r?.Parent??Object;class l extends u{}Object.defineProperty(l,"name",{value:e});function f(p){let h=r?.Parent?nk(l):this;c(h,p);let d=h._zod.deferred;if(d){for(let v of d)v();h._zod.deferred=void 0}let g=globalThis.__zod_globalConfig?.postProcessor;if(g)g(h);return h}return Object.defineProperty(f,"init",{value:c}),Object.defineProperty(f,Symbol.hasInstance,{value:(p)=>{if(r?.Parent&&p instanceof r.Parent)return!0;return p?._zod?.traits?.has(e)}}),Object.defineProperty(f,"name",{value:e}),f}class Er extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class xo extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}}(ug=globalThis).__zod_globalConfig??(ug.__zod_globalConfig={});var Tt=globalThis.__zod_globalConfig;function Pt(e){if(e)Object.assign(Tt,e);return Tt}function ik(){let e=this._zod;return e.message??(e.message=JSON.stringify(e.def,vo,2)),e.message}function ok(e){this._zod.message=e}var sk={get:ik,set:ok,enumerable:!0,configurable:!0},Al={value:void 0,enumerable:!1},dg=new WeakSet([Object.prototype,Error.prototype]),pg=(e,t)=>{e.name="$ZodError",Al.value=t,Object.defineProperty(e,"issues",Al),Al.value=void 0,Object.defineProperty(e,"message",sk);let n=Object.getPrototypeOf(e);if(!dg.has(n))dg.add(n),Object.defineProperty(n,"toString",{configurable:!0,enumerable:!1,get(){let r=()=>this.message;return Object.defineProperty(this,"toString",{value:r,configurable:!0,writable:!0}),r},set(r){Object.defineProperty(this,"toString",{value:r,configurable:!0,writable:!0})}})},hg=N("$ZodError",pg),$N=N("$ZodError",pg,void 0,{Parent:Error});function ak(e,t,n){if(!Object.prototype.hasOwnProperty.call(e,t))if(t==="__proto__")Object.defineProperty(e,t,{value:n(),writable:!0,enumerable:!0,configurable:!0});else e[t]=n();return e[t]}function kl(e,t=(n)=>n.message){let n={},r=[];for(let i of e.issues)if(i.path.length>0)ak(n,i.path[0],()=>[]).push(t(i));else r.push(t(i));return{formErrors:r,fieldErrors:n}}function Il(e,t=(n)=>n.message){let n={_errors:[]},r=(i,o=[])=>{for(let s of i.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map((a)=>r({issues:a},[...o,...s.path]));else if(s.code==="invalid_key")r({issues:s.issues},[...o,...s.path]);else if(s.code==="invalid_element")r({issues:s.issues},[...o,...s.path]);else{let a=[...o,...s.path];if(a.length===0)n._errors.push(t(s));else{let c=n,u=0;while(u<a.length){let l=a[u],f=u===a.length-1;if(l==="_errors"){if(f)c._errors.push(t(s));u++;continue}if(!Object.prototype.hasOwnProperty.call(c,l))Object.defineProperty(c,l,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});let p=c[l];if(f)p._errors.push(t(s));c=p,u++}}}};return r(e),n}function Ca(e,t){return{callee:t?.callee??e,Err:t?.Err}}var wa=(e)=>{let t=(n,r,i,o)=>{let s=i?{...i,async:!1}:{async:!1},a=n._zod.run({value:r,issues:[]},s);if(a instanceof Promise)throw new Er;if(a.issues.length){let c=new(o?.Err??e)(a.issues.map((u)=>wr(u,s,Pt())));throw bl(c,o?.callee??t),c}return a.value};return t};var Ea=(e)=>{let t=async(n,r,i,o)=>{let s=i?{...i,async:!0}:{async:!0},a=n._zod.run({value:r,issues:[]},s);if(a instanceof Promise)a=await a;if(a.issues.length){let c=new(o?.Err??e)(a.issues.map((u)=>wr(u,s,Pt())));throw bl(c,o?.callee??t),c}return a.value};return t};var _a=(e)=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},i);if(o instanceof Promise)throw new Er;return o.issues.length?mg(e,o.issues,i):{success:!0,data:o.value}};function mg(e,t,n){let r;return{success:!1,get error(){if(!r)r=new e(t.map((i)=>wr(i,n,Pt()))),t=void 0,n=void 0;return r},set error(i){r=i,t=void 0,n=void 0}}}var Ta=(e)=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},o=t._zod.run({value:n,issues:[]},i);if(o instanceof Promise)o=await o;return o.issues.length?mg(e,o.issues,i):{success:!0,data:o.value}};var ck=Symbol.for("zod.compile.invalid"),uk=Symbol.for("zod.compile.fallback"),Pl=(e,t,n)=>{let r=e._zod.bag.validator;if(r!==void 0){if(r(t)!==ck)return!0;if(r.definite===!0&&n===void 0)return!1}return lk(e,t,n)};function lk(e,t,n){let r=n?{...n,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},i=e._zod.bag.fallbackRun,o;if(i)r[uk]=!0,o=i({value:t,issues:[]},r);else o=e._zod.run({value:t,issues:[]},r);if(o instanceof Promise)throw new Er;return o.issues.length===0}var Rl=async(e,t,n)=>{let r=n?{...n,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0},i=e._zod.run({value:t,issues:[]},r);if(i instanceof Promise)i=await i;return i.issues.length===0},gg=(e)=>{let t=wa(e),n=(r,i,o,s)=>{let a=o?{...o,direction:"backward"}:{direction:"backward"};return t(r,i,a,Ca(n,s))};return n};var yg=(e)=>{let t=wa(e),n=(r,i,o,s)=>t(r,i,o,Ca(n,s));return n};var vg=(e)=>{let t=Ea(e),n=async(r,i,o,s)=>{let a=o?{...o,direction:"backward"}:{direction:"backward"};return await t(r,i,a,Ca(n,s))};return n};var xg=(e)=>{let t=Ea(e),n=async(r,i,o,s)=>await t(r,i,o,Ca(n,s));return n};var bg=(e)=>(t,n,r)=>{let i=r?{...r,direction:"backward"}:{direction:"backward"};return _a(e)(t,n,i)};var Sg=(e)=>(t,n,r)=>_a(e)(t,n,r);var Cg=(e)=>async(t,n,r)=>{let i=r?{...r,direction:"backward"}:{direction:"backward"};return Ta(e)(t,n,i)};var wg=(e)=>async(t,n,r)=>Ta(e)(t,n,r);var Eg=/^[cC][0-9a-z]{6,}$/,_g=/^[0-9a-z]+$/,Tg=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,Ag=/^[0-9a-vA-V]{20}$/,kg=/^[A-Za-z0-9]{27}$/,Ig=/^[a-zA-Z0-9_-]{21}$/;function Pg(e){return new RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}var Rg=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var Bg=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Nl=(e)=>{if(!e)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)};var Ng=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var fk="^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$";function Dg(){return new RegExp(fk,"u")}var $g=/^(?:(?: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])$/,Og=/^(([0-9a-fA-F]{1,4}:){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}|:))$/;var Lg=/^((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])\/([0-9]|[1-2][0-9]|3[0-2])$/,Ug=/^(([0-9a-fA-F]{1,4}:){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}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,zg=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Fg=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/;var Mg=/^https?$/,Vg=/^\+[1-9]\d{6,14}$/;var Wg="(?:(?:\\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])))";function dk(e){return new RegExp(`^${e}$`)}var Hg=dk(Wg);function Bl(e){return typeof e.precision==="number"?e.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":e.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${e.precision}}`:e.seconds?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?":"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function Kg(e){return new RegExp(`^${Bl(e)}$`)}function Zg(e){let t=["Z"];if(e.offset)t.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let n=`${Bl({precision:e.precision,seconds:!0})}(?:${t.join("|")})`,r=e.local?`${n}|${Bl({precision:e.precision})}`:n;return new RegExp(`^${Wg}T(?:${r})$`)}var jg=/^[\s\S]{0,}$/;var Dl=/^-?\d+$/,bo=/^-?\d+(?:\.\d+)?$/,Gg=/^(?:true|false)$/i;var qg=/^[^A-Z]*$/,Xg=/^[^a-z]*$/;var yt=N("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])});var $l=(e)=>{let t=e.value;return!jm(t)&&t.length!==void 0},Aa={number:"number",bigint:"bigint",object:"date"},Ol=N("$ZodCheckLessThan",(e,t)=>{yt.init(e,t);let n=Aa[typeof t.value];e._zod.check=(r)=>{if(t.inclusive?r.value<=t.value:r.value<t.value)return;r.issues.push({origin:Aa[typeof r.value]??n,code:"too_big",maximum:typeof t.value==="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Ll=N("$ZodCheckGreaterThan",(e,t)=>{yt.init(e,t);let n=Aa[typeof t.value];e._zod.check=(r)=>{if(t.inclusive?r.value>=t.value:r.value>t.value)return;r.issues.push({origin:Aa[typeof r.value]??n,code:"too_small",minimum:typeof t.value==="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Jg=N("$ZodCheckMultipleOf",(e,t)=>{yt.init(e,t),e._zod.check=(n)=>{if(typeof n.value!==typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof n.value==="bigint"?t.value!==BigInt(0)&&n.value%t.value===BigInt(0):Gm(n.value,t.value)===0)return;n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Qg=N("$ZodCheckNumberFormat",(e,t)=>{yt.init(e,t),t.format=t.format||"float64";let n=t.format?.includes("int"),r=n?"int":"number",[i,o]=ga[t.format];e._zod.check=(s)=>{let a=s.value;if(n){if(!Number.isInteger(a)){s.issues.push({expected:r,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){if(a>0)s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort});else s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}if(a<i)s.issues.push({origin:"number",input:a,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort});if(a>o)s.issues.push({origin:"number",input:a,code:"too_big",maximum:o,inclusive:!0,inst:e,continue:!t.abort})}});var Yg=N("$ZodCheckMaxLength",(e,t)=>{var n;yt.init(e,t),(n=e._zod.def).when??(n.when=$l),e._zod.check=(r)=>{let i=r.value,o=i.length;if((typeof i==="string"&&o>t.maximum?xa(i):o)<=t.maximum)return;let a=ba(i);r.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),ey=N("$ZodCheckMinLength",(e,t)=>{var n;yt.init(e,t),(n=e._zod.def).when??(n.when=$l),e._zod.check=(r)=>{let i=r.value,o=i.length;if((typeof i==="string"&&o>=t.minimum&&o<t.minimum*2?xa(i):o)>=t.minimum)return;let a=ba(i);r.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),ty=N("$ZodCheckLengthEquals",(e,t)=>{var n;yt.init(e,t),(n=e._zod.def).when??(n.when=$l),e._zod.check=(r)=>{let i=r.value,o=i.length,s=typeof i==="string"&&o>=t.length&&o<=t.length*2?xa(i):o;if(s===t.length)return;let a=ba(i),c=s>t.length;r.issues.push({origin:a,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),So=N("$ZodCheckStringFormat",(e,t)=>{var n,r;if(yt.init(e,t),t.pattern)(n=e._zod).check??(n.check=(i)=>{if(t.pattern.lastIndex=0,t.pattern.test(i.value))return;i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})});else(r=e._zod).check??(r.check=()=>{})}),ry=N("$ZodCheckRegex",(e,t)=>{So.init(e,t),e._zod.check=(n)=>{if(t.pattern.lastIndex=0,t.pattern.test(n.value))return;n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),ny=N("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=qg),So.init(e,t)}),iy=N("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Xg),So.init(e,t)}),oy=N("$ZodCheckIncludes",(e,t)=>{yt.init(e,t);let n=vi(t.includes),r=new RegExp(typeof t.position==="number"?`^.{${t.position},}${n}`:n);t.pattern=r,e._zod.check=(i)=>{if(i.value.includes(t.includes,t.position))return;i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:i.value,inst:e,continue:!t.abort})}}),sy=N("$ZodCheckStartsWith",(e,t)=>{yt.init(e,t);let n=new RegExp(`^${vi(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.check=(r)=>{if(r.value.startsWith(t.prefix))return;r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),ay=N("$ZodCheckEndsWith",(e,t)=>{yt.init(e,t);let n=new RegExp(`.*${vi(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.check=(r)=>{if(r.value.endsWith(t.suffix))return;r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}});var cy=N("$ZodCheckOverwrite",(e,t)=>{yt.init(e,t),e._zod.check=(n)=>{n.value=t.tx(n.value)}});class Ul{constructor(e=[],t={}){this.content=[],this.indent=0,this.args=e,this.closed=t}indented(e){this.indent+=1;try{e(this)}finally{this.indent-=1}}write(e){if(typeof e==="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
97
97
  `).filter((o)=>o),r=Math.min(...n.map((o)=>o.length-o.trimStart().length)),i=n.map((o)=>o.slice(r)).map((o)=>" ".repeat(this.indent*2)+o);for(let o of i)this.content.push(o)}compile(){let e=Function,t=this?.content??[""];return new e(...Object.keys(this.closed),`return function (${this.args.join(", ")}) {
98
98
  ${t.join(`
99
99
  `)}
100
- };`)(...Object.values(this.closed))}}var uy={major:4,minor:6,patch:6};var Me=N("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=uy;let r=e._zod.def.checks,i=e._zod.traits.has("$ZodCheck")?[e,...r??[]]:r?.length?[...r]:[];for(let o of i)for(let s of o._zod.onattach)s(e);if(i.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let o=(a,c,u)=>{if(a.memo)return a;let l=qt(a),f;for(let p of c){if(p._zod.def.when){if(ng(a))continue;if(!p._zod.def.when(a))continue}else if(l)continue;let h=a.issues.length,d=p._zod.check(a);if(d instanceof Promise&&u?.async===!1)throw new Er;if(f||d instanceof Promise)f=(f??Promise.resolve()).then(async()=>{if(await d,a.issues.length===h)return;if(va(a.issues,h,e),!l)l=qt(a,h)});else{if(a.issues.length===h)continue;if(va(a.issues,h,e),!l)l=qt(a,h)}}if(f)return f.then(()=>a);return a},s=(a,c,u)=>{if(qt(a))return a.aborted=!0,a;let l=o(c,i,u);if(l instanceof Promise){if(u.async===!1)throw new Er;return l.then((f)=>e._zod.parse(f,u))}return e._zod.parse(l,u)};e._zod.run=(a,c)=>{if(c.skipChecks)return e._zod.parse(a,c);if(c.direction==="backward"){let l=e._zod.parse({value:a.value,issues:[]},{...c,skipChecks:!0});if(l instanceof Promise)return l.then((f)=>s(f,a,c));return s(l,a,c)}let u=e._zod.parse(a,c);if(u instanceof Promise){if(c.async===!1)throw new Er;return u.then((l)=>o(l,i,c))}return o(u,i,c)}}},{get "~standard"(){return Sa(this,"~standard",zl(this))},set "~standard"(e){Ur(this,"~standard",e)}}),wy=(e,t)=>e.issues.length?{issues:e.issues.map((n)=>wr(n,t,Pt()))}:{value:e.value};async function dk(e,t){let n={async:!0};return wy(await e._zod.run({value:t,issues:[]},n),n)}function zl(e){return{validate:(t)=>{let n={async:!1};try{let r=e._zod.run({value:t,issues:[]},n);if(!(r instanceof Promise))return wy(r,n)}catch(r){}return dk(e,t)},vendor:"zod",version:1}}var Ra=N("$ZodString",(e,t)=>{Me.init(e,t),e._zod.pattern=t.pattern??Zg,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch(i){}if(typeof n.value==="string")return n;return n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),Ve=N("$ZodStringFormat",(e,t)=>{So.init(e,t),Ra.init(e,t)}),Ey=N("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Rg),Ve.init(e,t)}),_y=N("$ZodUUID",(e,t)=>{if(t.version){let r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Bl(r))}else t.pattern??(t.pattern=Bl());Ve.init(e,t)}),Ty=N("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Bg),Ve.init(e,t)}),Ay=1,Ia=2;function ky(e){try{if(typeof URL<"u"&&typeof URL.canParse==="function")return URL.canParse(e);return new URL(e),!0}catch{return!1}}function pk(e,t){if(!("normalize"in t)&&!("hostname"in t)&&!("protocol"in t))return ky(e)||Ia;return hk(e,t)}function hk(e,t){if(!t.normalize&&t.protocol?.source===Fg.source&&!/^https?:\/\//i.test(e))return Ay;try{if(typeof URL<"u"){let n=URL;if(typeof n.parse==="function")return n.parse(e)??Ia}return new URL(e)}catch{return Ia}}var mk=/[\t\n\r]/g;function ly(e){return e.replace(mk,"")}function gk(e,t){return t.lastIndex=0,t.test(e.hostname)}function yk(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(":")?e.protocol.slice(0,-1):e.protocol)}var Iy=N("$ZodURL",(e,t)=>{Ve.init(e,t),e._zod.check=(n)=>{try{let r=n.value.trim(),i=pk(r,t);if(i===Ay){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});return}if(i===Ia){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort});return}if(i===!0){n.value=ly(r);return}if(t.hostname&&!gk(i,t.hostname))n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort});if(t.protocol&&!yk(i,t.protocol))n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort});n.value=t.normalize?i.href:ly(r);return}catch(r){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),Py=N("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Ng()),Ve.init(e,t)}),Ry=N("$ZodNanoID",(e,t)=>{if(t.length!==void 0&&(!Number.isInteger(t.length)||t.length<1))throw Error(`Invalid nanoid length: ${t.length}`);t.pattern??(t.pattern=t.length===void 0?kg:Ig(t.length)),Ve.init(e,t)}),By=N("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=wg),Ve.init(e,t)}),Ny=N("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Eg),Ve.init(e,t)}),Dy=N("$ZodULID",(e,t)=>{t.pattern??(t.pattern=_g),Ve.init(e,t)}),$y=N("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Tg),Ve.init(e,t)}),Oy=N("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Ag),Ve.init(e,t)}),Ly=N("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Kg(t)),Ve.init(e,t)}),Uy=N("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Wg),Ve.init(e,t)}),zy=N("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Hg(t)),Ve.init(e,t)}),Fy=N("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Pg),Ve.init(e,t)}),My=N("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Dg),Ve.init(e,t)}),vk=/^[0-9a-fA-F:.]+$/;function Vy(e){if(!vk.test(e))return!1;return ky(`http://[${e}]`)}var Wy=N("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=$g),Ve.init(e,t),e._zod.check=(n)=>{if(!Vy(n.value))n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}});var Hy=N("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Og),Ve.init(e,t)});function xk(e){let t=e.split("/");if(t.length!==2)return!1;let[n,r]=t;if(!r)return!1;let i=Number(r);if(`${i}`!==r)return!1;if(i<0||i>128)return!1;return Vy(n)}var Ky=N("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Lg),Ve.init(e,t),e._zod.check=(n)=>{if(!xk(n.value))n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}});function Zy(e){if(e==="")return!0;if(/\s/.test(e))return!1;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var Fl=/^[0-9a-zA-Z+/]*={0,2}$/,jy=N("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Fl),Ve.init(e,t),e._zod.check=(n)=>{if(Zy(n.value))return;n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}}),Ba=/^[A-Za-z0-9_-]*$/;function bk(e){if(!Ba.test(e))return!1;let t=e.replace(/[-_]/g,(r)=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return Zy(n)}var Gy=N("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Ba),Ve.init(e,t),e._zod.check=(n)=>{if(bk(n.value))return;n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),qy=N("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Mg),Ve.init(e,t)});function Sk(e,t=null){try{let n=e.split(".");if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));if("typ"in i&&i?.typ!=="JWT")return!1;if(!i.alg)return!1;if(t&&(!("alg"in i)||i.alg!==t))return!1;return!0}catch{return!1}}var Xy=N("$ZodJWT",(e,t)=>{Ve.init(e,t),e._zod.check=(n)=>{if(Sk(n.value,t.alg))return;n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}});var Ml=N("$ZodNumber",(e,t)=>{Me.init(e,t),e._zod.pattern=bo,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch(s){}let i=n.value;if(typeof i==="number"&&!Number.isNaN(i)&&Number.isFinite(i))return n;let o=typeof i==="number"?Number.isNaN(i)?"NaN":!Number.isFinite(i)?String(i):void 0:void 0;return n.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...o?{received:o}:{}}),n}}),Jy=N("$ZodNumberFormat",(e,t)=>{Jg.init(e,t),Ml.init(e,t)}),Qy=N("$ZodBoolean",(e,t)=>{Me.init(e,t),e._zod.pattern=jg,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Boolean(n.value)}catch(o){}let i=n.value;if(typeof i==="boolean")return n;return n.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),n}});var Yy=N("$ZodUnknown",(e,t)=>{Me.init(e,t),e._zod.parse=(n)=>n}),ev=N("$ZodNever",(e,t)=>{Me.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function Ck(e,t){let n=wl(e._zod.def.checks);if(!n.length)return;let r=Math.min(...n.map((o)=>o[0])),i=e._zod.parse;e._zod.parse=(o,s)=>{let a=t(o.value);if(a>r&&!s?.skipChecks&&s?.direction!=="backward"){for(let[c,u]of wl(e._zod.def.checks))if(a>c&&u._zod.def.when(o)){let l=o.issues.length;return u._zod.check(o),o.issues[l].continue=!1,va(o.issues,l,e),o}}return i(o,s)}}var wk=(e)=>Array.isArray(e)?e.length:-1;function fy(e,t,n){if(e.issues.length)t.issues.push(...Cr(n,e.issues));t.value[n]=e.value}var tv=N("$ZodArray",(e,t)=>{Me.init(e,t);let n=_t.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),r;r.value=n?n.alloc(e,r,Array(o.length),i):Array(o.length);let s=[],a=i?.abortEarly;for(let c=0;c<o.length;c++){let u=o[c],l=t.element._zod.run({value:u,issues:[]},i);if(l instanceof Promise)s.push(l.then((f)=>fy(f,r,c)));else if(fy(l,r,c),a&&l.issues.length!==0&&qt(l))break}if(s.length)return Promise.all(s).then(()=>r);return r},Ck(e,wk)});function Pa(e,t,n,r,i,o){let s=n in r,a=o==="optional";if(!s&&a&&i==="optional")return;if(e.issues.length){if(i!==void 0&&a&&!s)return;t.issues.push(...Cr(n,e.issues))}if(!s&&i===void 0){if(!e.issues.length)t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}if(e.value===void 0){if(s||i==="defaulted"&&!a)t.value[n]=void 0}else t.value[n]=e.value}var Ek=[];function rv(e){let t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),r=n.length?n:Ek,i=r.length?[...t,...r]:t;for(let s of i)if(!e.shape?.[s]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${String(s)}": expected a Zod schema`);let o=eg(e.shape);return{...e,allKeys:i,symbolKeys:r,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(o)}}function nv(e,t,n,r,i,o,s){let a=[],c=i.keySet,u=i.catchall._zod,l=u.def.type,{optin:f,optout:p}=u,h=0;for(let d in t){if(s&&n.issues.length!==h){if(qt(n,h))break;h=n.issues.length}if(c.has(d))continue;if(d==="__proto__"){if(l==="never")a.push(d);continue}if(l==="never"){a.push(d);continue}let g=u.run({value:t[d],issues:[]},r);if(g instanceof Promise)e.push(g.then((x)=>Pa(x,n,d,t,f,p)));else Pa(g,n,d,t,f,p)}if(a.length)n.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:o,continue:!0});if(!e.length)return n;return Promise.all(e).then(()=>n)}var _k=N("$ZodObject",(e,t)=>{Me.init(e,t);let n=Object.getOwnPropertyDescriptor(t,"shape"),r=n?.get?n.get.raw:t.shape??{};if(r){let u=()=>{let l={...r};return Object.defineProperty(t,"shape",{value:l}),u.raw=l,l};u.raw=r,Object.defineProperty(t,"shape",{get:u})}let i=pa(()=>rv(t));Be(e,"propValues",(u)=>{let l=u.def.shape,f={};for(let p in l){let h=l[p]._zod;if(h.values){if(!Object.prototype.hasOwnProperty.call(f,p))sr(f,p,new Set);for(let d of h.values)f[p].add(d);if(h.optin!==void 0)f[p].add(void 0)}}return f});let o=go,s=t.catchall,a,c=_t.memoizer;c?.attach(e),e._zod.parse=(u,l)=>{a??(a=i.value);let f=u.value;if(!o(f))return u.issues.push({expected:"object",code:"invalid_type",input:f,inst:e}),u;u.value=c?c.alloc(e,u,{},l):{};let p=[],h=a.shape,d=l?.abortEarly,g=u.issues.length;for(let x of a.allKeys){if(d&&u.issues.length!==g){if(qt(u,g))break;g=u.issues.length}if(x==="__proto__")continue;let b=h[x],S=b._zod.optin,C=b._zod.optout,T=b._zod.run({value:f[x],issues:[]},l);if(T instanceof Promise)p.push(T.then((I)=>Pa(I,u,x,f,S,C)));else Pa(T,u,x,f,S,C)}if(!s)return p.length?Promise.all(p).then(()=>u):u;return nv(p,f,u,l,i.value,e,d===!0)}}),iv=N("$ZodObjectJIT",(e,t)=>{_k.init(e,t);let n=e._zod.parse,r=pa(()=>rv(t)),i=_t.memoizer,o=(h)=>{let d=r.value,g=d.symbolKeys,x=new Ll(["payload","ctx"],{shape:h,inst:e,memo:i,syms:g}),b=(I)=>`shape[${I}]._zod.run({ value: input[${I}], issues: [] }, ctx)`,S=(I,k)=>`
100
+ };`)(...Object.values(this.closed))}}var ly={major:4,minor:6,patch:6};var We=N("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=ly;let r=e._zod.def.checks,i=e._zod.traits.has("$ZodCheck")?[e,...r??[]]:r?.length?[...r]:[];for(let o of i)for(let s of o._zod.onattach)s(e);if(i.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let o=(a,c,u)=>{if(a.memo)return a;let l=qt(a),f;for(let p of c){if(p._zod.def.when){if(ig(a))continue;if(!p._zod.def.when(a))continue}else if(l)continue;let h=a.issues.length,d=p._zod.check(a);if(d instanceof Promise&&u?.async===!1)throw new Er;if(f||d instanceof Promise)f=(f??Promise.resolve()).then(async()=>{if(await d,a.issues.length===h)return;if(va(a.issues,h,e),!l)l=qt(a,h)});else{if(a.issues.length===h)continue;if(va(a.issues,h,e),!l)l=qt(a,h)}}if(f)return f.then(()=>a);return a},s=(a,c,u)=>{if(qt(a))return a.aborted=!0,a;let l=o(c,i,u);if(l instanceof Promise){if(u.async===!1)throw new Er;return l.then((f)=>e._zod.parse(f,u))}return e._zod.parse(l,u)};e._zod.run=(a,c)=>{if(c.skipChecks)return e._zod.parse(a,c);if(c.direction==="backward"){let l=e._zod.parse({value:a.value,issues:[]},{...c,skipChecks:!0});if(l instanceof Promise)return l.then((f)=>s(f,a,c));return s(l,a,c)}let u=e._zod.parse(a,c);if(u instanceof Promise){if(c.async===!1)throw new Er;return u.then((l)=>o(l,i,c))}return o(u,i,c)}}},{get "~standard"(){return Sa(this,"~standard",Fl(this))},set "~standard"(e){Ur(this,"~standard",e)}}),Ey=(e,t)=>e.issues.length?{issues:e.issues.map((n)=>wr(n,t,Pt()))}:{value:e.value};async function pk(e,t){let n={async:!0};return Ey(await e._zod.run({value:t,issues:[]},n),n)}function Fl(e){return{validate:(t)=>{let n={async:!1};try{let r=e._zod.run({value:t,issues:[]},n);if(!(r instanceof Promise))return Ey(r,n)}catch(r){}return pk(e,t)},vendor:"zod",version:1}}var Ra=N("$ZodString",(e,t)=>{We.init(e,t),e._zod.pattern=t.pattern??jg,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch(i){}if(typeof n.value==="string")return n;return n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),He=N("$ZodStringFormat",(e,t)=>{So.init(e,t),Ra.init(e,t)}),_y=N("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Bg),He.init(e,t)}),Ty=N("$ZodUUID",(e,t)=>{if(t.version){let r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Nl(r))}else t.pattern??(t.pattern=Nl());He.init(e,t)}),Ay=N("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Ng),He.init(e,t)}),ky=1,Ia=2;function Iy(e){try{if(typeof URL<"u"&&typeof URL.canParse==="function")return URL.canParse(e);return new URL(e),!0}catch{return!1}}function hk(e,t){if(!("normalize"in t)&&!("hostname"in t)&&!("protocol"in t))return Iy(e)||Ia;return mk(e,t)}function mk(e,t){if(!t.normalize&&t.protocol?.source===Mg.source&&!/^https?:\/\//i.test(e))return ky;try{if(typeof URL<"u"){let n=URL;if(typeof n.parse==="function")return n.parse(e)??Ia}return new URL(e)}catch{return Ia}}var gk=/[\t\n\r]/g;function fy(e){return e.replace(gk,"")}function yk(e,t){return t.lastIndex=0,t.test(e.hostname)}function vk(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(":")?e.protocol.slice(0,-1):e.protocol)}var Py=N("$ZodURL",(e,t)=>{He.init(e,t),e._zod.check=(n)=>{try{let r=n.value.trim(),i=hk(r,t);if(i===ky){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});return}if(i===Ia){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort});return}if(i===!0){n.value=fy(r);return}if(t.hostname&&!yk(i,t.hostname))n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort});if(t.protocol&&!vk(i,t.protocol))n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort});n.value=t.normalize?i.href:fy(r);return}catch(r){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),Ry=N("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Dg()),He.init(e,t)}),By=N("$ZodNanoID",(e,t)=>{if(t.length!==void 0&&(!Number.isInteger(t.length)||t.length<1))throw Error(`Invalid nanoid length: ${t.length}`);t.pattern??(t.pattern=t.length===void 0?Ig:Pg(t.length)),He.init(e,t)}),Ny=N("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Eg),He.init(e,t)}),Dy=N("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=_g),He.init(e,t)}),$y=N("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Tg),He.init(e,t)}),Oy=N("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Ag),He.init(e,t)}),Ly=N("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=kg),He.init(e,t)}),Uy=N("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Zg(t)),He.init(e,t)}),zy=N("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Hg),He.init(e,t)}),Fy=N("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Kg(t)),He.init(e,t)}),My=N("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Rg),He.init(e,t)}),Vy=N("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=$g),He.init(e,t)}),xk=/^[0-9a-fA-F:.]+$/;function Wy(e){if(!xk.test(e))return!1;return Iy(`http://[${e}]`)}var Hy=N("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Og),He.init(e,t),e._zod.check=(n)=>{if(!Wy(n.value))n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}});var Ky=N("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Lg),He.init(e,t)});function bk(e){let t=e.split("/");if(t.length!==2)return!1;let[n,r]=t;if(!r)return!1;let i=Number(r);if(`${i}`!==r)return!1;if(i<0||i>128)return!1;return Wy(n)}var Zy=N("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Ug),He.init(e,t),e._zod.check=(n)=>{if(!bk(n.value))n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}});function jy(e){if(e==="")return!0;if(/\s/.test(e))return!1;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var Ml=/^[0-9a-zA-Z+/]*={0,2}$/,Gy=N("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Ml),He.init(e,t),e._zod.check=(n)=>{if(jy(n.value))return;n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}}),Ba=/^[A-Za-z0-9_-]*$/;function Sk(e){if(!Ba.test(e))return!1;let t=e.replace(/[-_]/g,(r)=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return jy(n)}var qy=N("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Ba),He.init(e,t),e._zod.check=(n)=>{if(Sk(n.value))return;n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),Xy=N("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Vg),He.init(e,t)});function Ck(e,t=null){try{let n=e.split(".");if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));if("typ"in i&&i?.typ!=="JWT")return!1;if(!i.alg)return!1;if(t&&(!("alg"in i)||i.alg!==t))return!1;return!0}catch{return!1}}var Jy=N("$ZodJWT",(e,t)=>{He.init(e,t),e._zod.check=(n)=>{if(Ck(n.value,t.alg))return;n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}});var Vl=N("$ZodNumber",(e,t)=>{We.init(e,t),e._zod.pattern=bo,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch(s){}let i=n.value;if(typeof i==="number"&&!Number.isNaN(i)&&Number.isFinite(i))return n;let o=typeof i==="number"?Number.isNaN(i)?"NaN":!Number.isFinite(i)?String(i):void 0:void 0;return n.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...o?{received:o}:{}}),n}}),Qy=N("$ZodNumberFormat",(e,t)=>{Qg.init(e,t),Vl.init(e,t)}),Yy=N("$ZodBoolean",(e,t)=>{We.init(e,t),e._zod.pattern=Gg,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Boolean(n.value)}catch(o){}let i=n.value;if(typeof i==="boolean")return n;return n.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),n}});var ev=N("$ZodUnknown",(e,t)=>{We.init(e,t),e._zod.parse=(n)=>n}),tv=N("$ZodNever",(e,t)=>{We.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function wk(e,t){let n=El(e._zod.def.checks);if(!n.length)return;let r=Math.min(...n.map((o)=>o[0])),i=e._zod.parse;e._zod.parse=(o,s)=>{let a=t(o.value);if(a>r&&!s?.skipChecks&&s?.direction!=="backward"){for(let[c,u]of El(e._zod.def.checks))if(a>c&&u._zod.def.when(o)){let l=o.issues.length;return u._zod.check(o),o.issues[l].continue=!1,va(o.issues,l,e),o}}return i(o,s)}}var Ek=(e)=>Array.isArray(e)?e.length:-1;function dy(e,t,n){if(e.issues.length)t.issues.push(...Cr(n,e.issues));t.value[n]=e.value}var rv=N("$ZodArray",(e,t)=>{We.init(e,t);let n=Tt.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),r;r.value=n?n.alloc(e,r,Array(o.length),i):Array(o.length);let s=[],a=i?.abortEarly;for(let c=0;c<o.length;c++){let u=o[c],l=t.element._zod.run({value:u,issues:[]},i);if(l instanceof Promise)s.push(l.then((f)=>dy(f,r,c)));else if(dy(l,r,c),a&&l.issues.length!==0&&qt(l))break}if(s.length)return Promise.all(s).then(()=>r);return r},wk(e,Ek)});function Pa(e,t,n,r,i,o){let s=n in r,a=o==="optional";if(!s&&a&&i==="optional")return;if(e.issues.length){if(i!==void 0&&a&&!s)return;t.issues.push(...Cr(n,e.issues))}if(!s&&i===void 0){if(!e.issues.length)t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}if(e.value===void 0){if(s||i==="defaulted"&&!a)t.value[n]=void 0}else t.value[n]=e.value}var _k=[];function nv(e){let t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),r=n.length?n:_k,i=r.length?[...t,...r]:t;for(let s of i)if(!e.shape?.[s]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${String(s)}": expected a Zod schema`);let o=tg(e.shape);return{...e,allKeys:i,symbolKeys:r,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(o)}}function iv(e,t,n,r,i,o,s){let a=[],c=i.keySet,u=i.catchall._zod,l=u.def.type,{optin:f,optout:p}=u,h=0;for(let d in t){if(s&&n.issues.length!==h){if(qt(n,h))break;h=n.issues.length}if(c.has(d))continue;if(d==="__proto__"){if(l==="never")a.push(d);continue}if(l==="never"){a.push(d);continue}let g=u.run({value:t[d],issues:[]},r);if(g instanceof Promise)e.push(g.then((v)=>Pa(v,n,d,t,f,p)));else Pa(g,n,d,t,f,p)}if(a.length)n.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:o,continue:!0});if(!e.length)return n;return Promise.all(e).then(()=>n)}var Tk=N("$ZodObject",(e,t)=>{We.init(e,t);let n=Object.getOwnPropertyDescriptor(t,"shape"),r=n?.get?n.get.raw:t.shape??{};if(r){let u=()=>{let l={...r};return Object.defineProperty(t,"shape",{value:l}),u.raw=l,l};u.raw=r,Object.defineProperty(t,"shape",{get:u})}let i=pa(()=>nv(t));Be(e,"propValues",(u)=>{let l=u.def.shape,f={};for(let p in l){let h=l[p]._zod;if(h.values){if(!Object.prototype.hasOwnProperty.call(f,p))sr(f,p,new Set);for(let d of h.values)f[p].add(d);if(h.optin!==void 0)f[p].add(void 0)}}return f});let o=go,s=t.catchall,a,c=Tt.memoizer;c?.attach(e),e._zod.parse=(u,l)=>{a??(a=i.value);let f=u.value;if(!o(f))return u.issues.push({expected:"object",code:"invalid_type",input:f,inst:e}),u;u.value=c?c.alloc(e,u,{},l):{};let p=[],h=a.shape,d=l?.abortEarly,g=u.issues.length;for(let v of a.allKeys){if(d&&u.issues.length!==g){if(qt(u,g))break;g=u.issues.length}if(v==="__proto__")continue;let b=h[v],S=b._zod.optin,C=b._zod.optout,T=b._zod.run({value:f[v],issues:[]},l);if(T instanceof Promise)p.push(T.then((I)=>Pa(I,u,v,f,S,C)));else Pa(T,u,v,f,S,C)}if(!s)return p.length?Promise.all(p).then(()=>u):u;return iv(p,f,u,l,i.value,e,d===!0)}}),ov=N("$ZodObjectJIT",(e,t)=>{Tk.init(e,t);let n=e._zod.parse,r=pa(()=>nv(t)),i=Tt.memoizer,o=(h)=>{let d=r.value,g=d.symbolKeys,v=new Ul(["payload","ctx"],{shape:h,inst:e,memo:i,syms:g}),b=(I)=>`shape[${I}]._zod.run({ value: input[${I}], issues: [] }, ctx)`,S=(I,k)=>`
101
101
  let ${I}_ab = false;
102
102
  for (let i = 0; i < ${I}.issues.length; i++) {
103
103
  const iss = ${I}.issues[i];
@@ -108,7 +108,7 @@ ${t.join(`
108
108
  if (${I}_ab && ctx && ctx.abortEarly) {
109
109
  payload.value = newResult;
110
110
  return payload;
111
- }`;x.write("const input = payload.value;");let C=Object.create(null),T=0;for(let I of d.allKeys)C[I]=`key_${T++}`;x.write(i?"const newResult = memo.alloc(inst, payload, {}, ctx);":"const newResult = {};");for(let I of d.allKeys){if(I==="__proto__")continue;let k=C[I],R=typeof I==="symbol"?`syms[${g.indexOf(I)}]`:Xm(I),V=`${R} in input`,D=h[I],F=D?._zod?.optin,H=F!==void 0,re=D?._zod?.optout==="optional";if(x.write(`const ${k} = ${b(R)};`),H&&re){let se=F==="optional"?`${k}_present`:`${k}.value !== undefined || ${k}_present`;x.write(`
111
+ }`;v.write("const input = payload.value;");let C=Object.create(null),T=0;for(let I of d.allKeys)C[I]=`key_${T++}`;v.write(i?"const newResult = memo.alloc(inst, payload, {}, ctx);":"const newResult = {};");for(let I of d.allKeys){if(I==="__proto__")continue;let k=C[I],R=typeof I==="symbol"?`syms[${g.indexOf(I)}]`:Jm(I),V=`${R} in input`,D=h[I],F=D?._zod?.optin,H=F!==void 0,re=D?._zod?.optout==="optional";if(v.write(`const ${k} = ${b(R)};`),H&&re){let se=F==="optional"?`${k}_present`:`${k}.value !== undefined || ${k}_present`;v.write(`
112
112
  const ${k}_present = ${V};
113
113
  if (!${k}.issues.length || ${k}_present) {
114
114
  if (${k}.issues.length) {${S(k,R)}
@@ -119,7 +119,7 @@ ${t.join(`
119
119
  }
120
120
  }
121
121
 
122
- `)}else if(!H)x.write(`
122
+ `)}else if(!H)v.write(`
123
123
  const ${k}_present = ${V};
124
124
  if (${k}.issues.length) {${S(k,R)}
125
125
  }
@@ -140,13 +140,13 @@ ${t.join(`
140
140
  newResult[${R}] = ${k}.value;
141
141
  }
142
142
 
143
- `);else if(x.write(`
143
+ `);else if(v.write(`
144
144
  if (${k}.issues.length) {${S(k,R)}
145
145
  }
146
- `),F==="defaulted")x.write(`newResult[${R}] = ${k}.value;`);else x.write(`
146
+ `),F==="defaulted")v.write(`newResult[${R}] = ${k}.value;`);else v.write(`
147
147
  if (${k}.value !== undefined || ${V}) {
148
148
  newResult[${R}] = ${k}.value;
149
149
  }
150
- `)}return x.write("payload.value = newResult;"),x.write("return payload;"),x.compile()},s,a=go,c=!_t.jitless,l=c&&Qm.value,f=t.catchall,p;e._zod.parse=(h,d)=>{p??(p=r.value);let g=h.value;if(!a(g))return h.issues.push({expected:"object",code:"invalid_type",input:g,inst:e}),h;if(c&&l&&d?.async===!1&&d.jitless!==!0){if(!s)s=o(t.shape);if(h=s(h,d),!f)return h;return nv([],g,h,d,p,e,d?.abortEarly===!0)}return n(h,d)}});function dy(e,t,n,r){for(let o of e)if(o.issues.length===0)return t.value=o.value,t;let i=e.filter((o)=>!qt(o));if(i.length===1)return t.value=i[0].value,i[0];return t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map((o)=>o.issues.map((s)=>wr(s,r,Pt())))}),t}var ov=N("$ZodUnion",(e,t)=>{Me.init(e,t),Be(e,"optin",(r)=>r.def.options.some((i)=>i._zod.optin==="defaulted")?"defaulted":r.def.options.some((i)=>i._zod.optin!==void 0)?"optional":void 0),Be(e,"optout",(r)=>r.def.options.some((i)=>i._zod.optout==="optional")?"optional":void 0),Be(e,"values",(r)=>{if(r.def.options.every((i)=>i._zod.values))return new Set(r.def.options.flatMap((i)=>Array.from(i._zod.values)));return}),Be(e,"pattern",(r)=>{if(r.def.options.every((i)=>i._zod.pattern)){let i=r.def.options.map((o)=>o._zod.pattern);return new RegExp(`^(${i.map((o)=>ha(o.source)).join("|")})$`)}return});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let o=!1,s=[];for(let a of t.options){let c=a._zod.run({value:r.value,issues:[]},i);if(c instanceof Promise)s.push(c),o=!0;else{if(c.issues.length===0)return c;s.push(c)}}if(!o)return dy(s,r,e,i);return Promise.all(s).then((a)=>dy(a,r,e,i))}});var sv=N("$ZodIntersection",(e,t)=>{Me.init(e,t),e._zod.parse=(n,r)=>{let i=n.value,o=t.left._zod.run({value:i,issues:[]},r),s=t.right._zod.run({value:i,issues:[]},r);if(o instanceof Promise||s instanceof Promise)return Promise.all([o,s]).then(([c,u])=>py(n,c,u));return py(n,o,s)}});function Ul(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(kn(e)&&kn(t)){let n=Object.keys(t),r=Object.keys(e).filter((o)=>n.indexOf(o)!==-1),i={...e,...t};if(Object.prototype.hasOwnProperty.call(i,"__proto__"))delete i.__proto__;for(let o of r){if(o==="__proto__")continue;let s=Ul(e[o],t[o]);if(!s.valid)return{valid:!1,mergeErrorPath:[o,...s.mergeErrorPath]};i[o]=s.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],o=t[r],s=Ul(i,o);if(!s.valid)return{valid:!1,mergeErrorPath:[r,...s.mergeErrorPath]};n.push(s.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function py(e,t,n){let r=new Map,i,o=new Map,s=(u,l)=>{let f;if(u.code==="unrecognized_keys"&&!u.path?.length)i??(i=u),f=u.keys;else if(u.code==="invalid_key"&&u.origin==="record"&&u.path?.length===1){let p=String(u.path[0]);if(!o.has(p))o.set(p,u);f=[p]}else return!1;for(let p of f){if(!r.has(p))r.set(p,{});r.get(p)[l]=!0}return!0};for(let u of t.issues)if(!s(u,"l"))e.issues.push(u);for(let u of n.issues)if(!s(u,"r"))e.issues.push(u);let a=[...r].filter(([,u])=>u.l&&u.r).map(([u])=>u);if(a.length){let u=i?a.filter((l)=>i.keys.includes(l)):[];if(u.length)e.issues.push({...i,keys:u});for(let l of a)if(!u.includes(l)&&o.has(l))e.issues.push(o.get(l))}let c=Ul(t.value,n.value);if(!c.valid){if(qt(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return e.value=c.data,e}var av=N("$ZodTuple",(e,t)=>{Me.init(e,t);let n=t.items,r=_t.memoizer;r?.attach(e),e._zod.parse=(i,o)=>{let s=i.value;if(!Array.isArray(s))return i.issues.push({input:s,inst:e,expected:"tuple",code:"invalid_type"}),i;i.value=r?r.alloc(e,i,[],o):[];let a=[],c=hy(n,"optin"),u=hy(n,"optout");if(!t.rest){if(s.length<c)return i.issues.push({code:"too_small",minimum:c,inclusive:!0,input:s,inst:e,origin:"array"}),i;if(s.length>n.length)i.issues.push({code:"too_big",maximum:n.length,inclusive:!0,input:s,inst:e,origin:"array"})}let l=Array(n.length),f=t.rest?o?.abortEarly:void 0,p=!1;for(let h=0;h<n.length;h++){let d=n[h]._zod.run({value:s[h],issues:[]},o);if(d instanceof Promise)a.push(d.then((g)=>{l[h]=g}));else if(l[h]=d,f&&!p&&d.issues.length)p=qt(d)}if(t.rest&&!p){let h=n.length-1,d=s.slice(n.length),g=i.issues.length;for(let x of d){if(f&&i.issues.length!==g){if(qt(i,g))break;g=i.issues.length}h++;let b=t.rest._zod.run({value:x,issues:[]},o);if(b instanceof Promise)a.push(b.then((S)=>my(S,i,h)));else my(b,i,h)}}if(a.length)return Promise.all(a).then(()=>gy(l,i,n,s,u));return gy(l,i,n,s,u)}});function hy(e,t){for(let n=e.length-1;n>=0;n--)if(!(t==="optin"?e[n]._zod.optin!==void 0:e[n]._zod.optout==="optional"))return n+1;return 0}function my(e,t,n){if(e.issues.length)t.issues.push(...Cr(n,e.issues));t.value[n]=e.value}function gy(e,t,n,r,i){for(let o=0;o<n.length;o++){let s=e[o],a=o<r.length;if(!a&&o>=i&&n[o]._zod.optin==="optional"){t.value.length=o;break}if(s.issues.length){if(!a&&o>=i){t.value.length=o;break}t.issues.push(...Cr(o,s.issues))}t.value[o]=s.value}for(let o=t.value.length-1;o>=r.length;o--)if(n[o]._zod.optout==="optional"&&t.value[o]===void 0)t.value.length=o;else break;return t}var cv=N("$ZodRecord",(e,t)=>{Me.init(e,t);let n=_t.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let o=r.value;if(!kn(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),r;let s=[],a=t.keyType._zod.values;if(a&&!t.partial){r.value=n?n.alloc(e,r,{},i):{};let c=new Set;for(let l of a)if(typeof l==="string"||typeof l==="number"||typeof l==="symbol"){if(c.add(typeof l==="number"?l.toString():l),l==="__proto__")continue;let f=t.keyType._zod.run({value:l,issues:[]},i);if(f instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(f.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:f.issues.map((d)=>wr(d,i,Pt())),input:l,path:[l],inst:e});continue}let p=f.value;if(p==="__proto__")continue;let h=t.valueType._zod.run({value:o[l],issues:[]},i);if(h instanceof Promise)s.push(h.then((d)=>{if(d.issues.length)r.issues.push(...Cr(l,d.issues));r.value[p]=d.value}));else{if(h.issues.length)r.issues.push(...Cr(l,h.issues));r.value[p]=h.value}}let u;for(let l in o)if(!c.has(l))if(t.mode==="loose"){if(l==="__proto__")continue;r.value[l]=o[l]}else u=u??[],u.push(l);if(u&&u.length>0)r.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:u,continue:!0})}else{r.value=n?n.alloc(e,r,{},i):{};let c;for(let u of Reflect.ownKeys(o)){if(u==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(o,u))continue;let l=t.keyType._zod.run({value:u,issues:[]},i);if(l instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof u==="string"&&bo.test(u)&&l.issues.length){let d=t.keyType._zod.run({value:Number(u),issues:[]},i);if(d instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(d.issues.length===0)l=d}if(l.issues.length){if(t.mode==="loose")r.value[u]=o[u];else if(a)c=c??[],c.push(u);else r.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map((d)=>wr(d,i,Pt())),input:u,path:[u],inst:e});continue}let p=l.value;if(p==="__proto__")continue;let h=t.valueType._zod.run({value:o[u],issues:[]},i);if(h instanceof Promise)s.push(h.then((d)=>{if(d.issues.length)r.issues.push(...Cr(u,d.issues));r.value[p]=d.value}));else{if(h.issues.length)r.issues.push(...Cr(u,h.issues));r.value[p]=h.value}}if(c&&c.length>0)r.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:c,continue:!0})}if(s.length)return Promise.all(s).then(()=>r);return r}});var uv=N("$ZodEnum",(e,t)=>{Me.init(e,t);let n=yo(t.entries),r=new Set(n);e._zod.values=r,Be(e,"pattern",(i)=>{let o=yo(i.def.entries).filter((s)=>Ym.has(typeof s));return new RegExp(o.length?`^(${o.map((s)=>gi(s.toString())).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(i,o)=>{let s=i.value;if(r.has(s))return i;return i.issues.push({code:"invalid_value",values:n,input:s,inst:e}),i}});var lv=N("$ZodTransform",(e,t)=>{Me.init(e,t),e._zod.optin="optional",_t.memoizer?.guard(e),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new xo(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then((s)=>(n.value=s,n));if(i instanceof Promise)throw new Er;return n.value=i,n}});function yy(e,t){return e.value=t.issues.length?void 0:t.value,e}var Vl=N("$ZodOptional",(e,t)=>{Me.init(e,t),Be(e,"optin",(n)=>n.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),e._zod.optout="optional",Be(e,"values",(n)=>{let r=n.def.innerType._zod.values;return r?new Set([...r,void 0]):void 0}),Be(e,"pattern",(n)=>{let r=n.def.innerType._zod.pattern;return r?new RegExp(`^(${ha(r.source)})?$`):void 0}),e._zod.parse=(n,r)=>{if(n.value===void 0){if(t.innerType._zod.optin!=="defaulted")return n;let i=t.innerType._zod.run({value:n.value,issues:[]},r);if(i instanceof Promise)return i.then((o)=>yy(n,o));return yy(n,i)}return t.innerType._zod.run(n,r)}}),fv=N("$ZodExactOptional",(e,t)=>{Vl.init(e,t),Be(e,"values",(n)=>n.def.innerType._zod.values),Be(e,"pattern",(n)=>n.def.innerType._zod.pattern),e._zod.parse=(n,r)=>t.innerType._zod.run(n,r)}),dv=N("$ZodNullable",(e,t)=>{Me.init(e,t),Be(e,"optin",(n)=>n.def.innerType._zod.optin),Be(e,"optout",(n)=>n.def.innerType._zod.optout),Be(e,"pattern",(n)=>{let r=n.def.innerType._zod.pattern;return r?new RegExp(`^(${ha(r.source)}|null)$`):void 0}),Be(e,"values",(n)=>n.def.innerType._zod.values?new Set([...n.def.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>{if(n.value===null)return n;return t.innerType._zod.run(n,r)}}),pv=N("$ZodDefault",(e,t)=>{Me.init(e,t),e._zod.optin="defaulted",Be(e,"values",(n)=>n.def.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)return n.value=t.defaultValue,n;let i=t.innerType._zod.run(n,r);if(i instanceof Promise)return i.then((o)=>vy(o,t));return vy(i,t)}});function vy(e,t){if(e.value===void 0)e.value=t.defaultValue;return e}var hv=N("$ZodPrefault",(e,t)=>{Me.init(e,t),e._zod.optin="defaulted",Be(e,"values",(n)=>n.def.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)n.value=t.defaultValue;return t.innerType._zod.run(n,r)}}),mv=N("$ZodNonOptional",(e,t)=>{Me.init(e,t),Be(e,"values",(n)=>{let r=n.def.innerType._zod.values;return r?new Set([...r].filter((i)=>i!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);if(i instanceof Promise)return i.then((o)=>xy(o,e));return xy(i,e)}});function xy(e,t){if(!e.issues.length&&e.value===void 0)e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t});return e}function by(e,t,n,r){if(!t.issues.length){if(e.value=t.value,t.memo)e.memo=!0;return e}return e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map((i)=>wr(i,r,Pt()))},input:e.value}),e}var gv=N("$ZodCatch",(e,t)=>{Me.init(e,t),Be(e,"optin",(n)=>n.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),Be(e,"optout",(n)=>n.def.innerType._zod.optout),Be(e,"values",(n)=>n.def.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);let i=t.innerType._zod.run({value:n.value,issues:[]},r);if(i instanceof Promise)return i.then((o)=>by(n,o,t,r));return by(n,i,t,r)}});var Wl=N("$ZodPipe",(e,t)=>{Me.init(e,t),Be(e,"values",(n)=>n.def.in._zod.values),Be(e,"optin",(n)=>n.def.in._zod.optin),Be(e,"optout",(n)=>n.def.out._zod.optout),Be(e,"propValues",(n)=>n.def.in._zod.propValues),e._zod.parse=(n,r)=>{if(r.direction==="backward"){let o=t.out._zod.run(n,r);if(o instanceof Promise)return o.then((s)=>ka(s,t.in,r));return ka(o,t.in,r)}let i=t.in._zod.run(n,r);if(i instanceof Promise)return i.then((o)=>ka(o,t.out,r));return ka(i,t.out,r)}});function ka(e,t,n){if(e.issues.some((r)=>r.code!=="unrecognized_keys"))return e.aborted=!0,e;return t._zod.run({value:e.value,issues:e.issues},n)}var yv=N("$ZodPreprocess",(e,t)=>{Wl.init(e,t)}),vv=N("$ZodReadonly",(e,t)=>{Me.init(e,t),Be(e,"propValues",(n)=>n.def.innerType._zod.propValues),Be(e,"values",(n)=>n.def.innerType._zod.values),Be(e,"optin",(n)=>n.def.innerType?._zod?.optin),Be(e,"optout",(n)=>n.def.innerType?._zod?.optout),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);let i=t.innerType._zod.run(n,r);if(i instanceof Promise)return i.then(Sy);return Sy(i)}});function Sy(e){if(!e.memo)e.value=Object.freeze(e.value);return e}var xv=N("$ZodCustom",(e,t)=>{yt.init(e,t),Me.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=(n)=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then((o)=>Cy(o,n,r,e));Cy(i,n,r,e);return}});function Cy(e,t,n,r){if(!e){let i={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};if(r._zod.def.params)i.params=r._zod.def.params;t.issues.push(In(i))}}class Sv extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform");this.name="ZodCyclicError"}}var Kl="~memo",bv=[];function Cv(e){return e!==null&&typeof e==="object"}function Hl(e){return e.map((t)=>t.path?{...t,path:t.path.slice()}:{...t})}var wv=new WeakMap,Co=0,$a=1,wo=2;function Oa(e,t,n){let r=wv.get(e);if(r!==void 0)return r?wo:Co;if(t.has(e))return wo;t.add(e);let i=Co,o=(l)=>{if(i!==wo&&l?._zod){let f=Oa(l,t,n);if(f>i)i=f}},s=(l,f)=>{let p=Co;for(let h of Reflect.ownKeys(l)){let d=Object.getOwnPropertyDescriptor(l,h);if(f&&!d.enumerable)continue;let g=d.get?$a:d.value?._zod?Oa(d.value,t,n):Co;if(g>p)p=g}return p},a=(l)=>{if(l>i)i=l},c=e._zod.def,u=c.type;switch(u){case"object":{let l=ma(c);a(l?s(l,!0):$a),o(c.catchall);break}case"array":o(c.element);break;case"tuple":for(let l of c.items)o(l);o(c.rest);break;case"record":case"map":o(c.keyType),o(c.valueType);break;case"set":o(c.valueType);break;case"union":for(let l of c.options)o(l);break;case"intersection":o(c.left),o(c.right);break;case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":o(c.innerType);break;case"pipe":o(c.in),o(c.out);break;case"function":o(c.input),o(c.output);break;case"lazy":{let l=c._cachedInner??(n?e._zod.innerType:void 0);a(l?Oa(l,t,!1):$a);break}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":break;default:for(let l in c){let f=Object.getOwnPropertyDescriptor(c,l);if(!f||f.get)continue;let p=f.value;if(!p||typeof p!=="object")continue;if(p._zod)o(p);else if(Array.isArray(p))for(let h of p)o(h)}}return t.delete(e),Tk(e,i)}function Tk(e,t){if(t!==$a)wv.set(e,t===wo);return t}function Ak(e,t){let n=e.buckets.get(t);if(!n)n=new WeakMap,e.buckets.set(t,n);return n}var Na,Da=[],kk={alloc(e,t,n){let r=Na;if(!r)return n;Na=void 0;let i={value:n,issues:null};return r.set(t.value,i),Da.push(i),n},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let n=e._zod.parse,r=(i,o)=>{if(o.direction!=="backward"&&Ik(o,i.value))throw new Sv;return n(i,o)};if(e._zod.parse=r,e._zod.run===n)e._zod.run=r})},attach(e){var t;let n,r=!1,i,o;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let s=e._zod.parse,a=(c,u)=>{if(n===void 0){let b=Oa(e,new Set,!1);if(b===Co){if(e._zod.parse=s,e._zod.run===a)e._zod.run=s;return s(c,u)}if(b===wo||r)n=!0;else r=!0}let l=c.value;if(!Cv(l))return s(c,u);let f=u[Kl];if(!f)f={buckets:new WeakMap,backEdges:void 0},u[Kl]=f;let p;if(i===u)p=o;else p=Ak(f,e),i=u,o=p;let h=p.get(l);if(h){if(c.value=h.value,h.issues){if(h.issues.length)c.issues.push(...Hl(h.issues))}else c.memo=!0,f.backEdges??(f.backEdges=new WeakSet),f.backEdges.add(h.value);return c}Na=p;let d=Da.length,g=s(c,u);Na=void 0;let x=Da.length>d?Da.pop():void 0;if(g instanceof Promise)return g.then((b)=>{if(x)x.issues=b.issues.length?Hl(b.issues):bv;return b});if(x)x.issues=g.issues.length?Hl(g.issues):bv;return g};if(e._zod.parse=a,e._zod.run===s)e._zod.run=a})}};function Zl(){return kk}function Ik(e,t){let n=e[Kl]?.backEdges;return n!==void 0&&Cv(t)&&n.has(t)}var Pk=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function t(o){return e[o]??null}let n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",currency_code:"currency code",credit_card:"credit card number",iban:"IBAN",jwt:"JWT",template_literal:"input"},r={nan:"NaN"};function i(o,s){if(o==="number"&&typeof s==="number"&&!Number.isFinite(s))return String(s);return r[o]??o}return(o)=>{switch(o.code){case"invalid_type":{let s=i(o.expected),a=ig(o.input),c=i(a,o.input);return`Invalid input: expected ${s}, received ${c}`}case"invalid_value":if(o.values.length===1)return`Invalid input: expected ${Sl(o.values[0])}`;return`Invalid option: expected one of ${vl(o.values,"|")}`;case"too_big":{let s=o.exact?"exactly ":o.inclusive?"<=":"<",a=t(o.origin);if(a)return`Too big: expected ${o.origin??"value"} to have ${s}${o.maximum.toString()} ${a.unit??"elements"}`;return`Too big: expected ${o.origin??"value"} to be ${s}${o.maximum.toString()}`}case"too_small":{let s=o.exact?"exactly ":o.inclusive?">=":">",a=t(o.origin);if(a)return`Too small: expected ${o.origin} to have ${s}${o.minimum.toString()} ${a.unit}`;return`Too small: expected ${o.origin} to be ${s}${o.minimum.toString()}`}case"invalid_format":{let s=o;if(s.format==="starts_with")return`Invalid string: must start with "${s.prefix}"`;if(s.format==="ends_with")return`Invalid string: must end with "${s.suffix}"`;if(s.format==="includes")return`Invalid string: must include "${s.includes}"`;if(s.format==="regex")return`Invalid string: must match pattern ${s.pattern}`;return`Invalid ${n[s.format]??o.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${o.divisor}`;case"unrecognized_keys":return`Unrecognized key${o.keys.length>1?"s":""}: ${vl(o.keys,", ")}`;case"invalid_key":return`Invalid key in ${o.origin}`;case"invalid_union":if(o.options&&Array.isArray(o.options)&&o.options.length>0)return`Invalid discriminator value. Expected ${o.options.map((a)=>`'${a}'`).join(" | ")}`;if(o.inclusive===!1)return"Invalid input: more than one option matched";return"Invalid input";case"invalid_element":return`Invalid value in ${o.origin}`;default:return"Invalid input"}}};function jl(){return{localeError:Pk()}}var Ev;class _v{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];if(this._map.set(e,n),n&&typeof n==="object"&&"id"in n)this._idmap.set(n.id,e);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);if(t&&typeof t==="object"&&"id"in t)this._idmap.delete(t.id);return this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function Tv(){return new _v}(Ev=globalThis).__zod_globalRegistry??(Ev.__zod_globalRegistry=Tv());var on=globalThis.__zod_globalRegistry;function Av(e){if(e.checks)e.checks=[...e.checks];return e}function kv(e,t){return new e(Av({type:"string",...Y(t)}))}function Iv(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...Y(t)})}function Pv(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...Y(t)})}function Rv(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...Y(t)})}function Bv(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Y(t)})}function Nv(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Y(t)})}function Dv(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Y(t)})}function $v(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...Y(t)})}function Ov(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...Y(t)})}function Lv(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...Y(t)})}function Uv(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...Y(t)})}function zv(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...Y(t)})}function Fv(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...Y(t)})}function Mv(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...Y(t)})}function Vv(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...Y(t)})}function Wv(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...Y(t)})}function Hv(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...Y(t)})}function Kv(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Y(t)})}function Zv(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Y(t)})}function jv(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...Y(t)})}function Gv(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...Y(t)})}function qv(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...Y(t)})}function Xv(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...Y(t)})}function Jv(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Y(t)})}function Qv(e,t){return new e({type:"string",format:"date",check:"string_format",...Y(t)})}function Yv(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...Y(t)})}function ex(e,t){return new e({type:"string",format:"duration",check:"string_format",...Y(t)})}function tx(e,t){return new e(Av({type:"number",checks:[],...Y(t)}))}function rx(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...Y(t)})}function nx(e,t){return new e({type:"boolean",...Y(t)})}function ix(e){return new e({type:"unknown"})}function ox(e,t){return new e({type:"never",...Y(t)})}function La(e,t){return new $l({check:"less_than",...Y(t),value:e,inclusive:!1})}function Eo(e,t){return new $l({check:"less_than",...Y(t),value:e,inclusive:!0})}function Ua(e,t){return new Ol({check:"greater_than",...Y(t),value:e,inclusive:!1})}function _o(e,t){return new Ol({check:"greater_than",...Y(t),value:e,inclusive:!0})}function za(e,t){return new Xg({check:"multiple_of",...Y(t),value:e})}function Fa(e,t){return new Qg({check:"max_length",...Y(t),maximum:e})}function vi(e,t){return new Yg({check:"min_length",...Y(t),minimum:e})}function Ma(e,t){return new ey({check:"length_equals",...Y(t),length:e})}function Gl(e,t){return new ty({check:"string_format",format:"regex",...Y(t),pattern:e})}function ql(e){return new ry({check:"string_format",format:"lowercase",...Y(e)})}function Xl(e){return new ny({check:"string_format",format:"uppercase",...Y(e)})}function Jl(e,t){return new iy({check:"string_format",format:"includes",...Y(t),includes:e})}function Ql(e,t){return new oy({check:"string_format",format:"starts_with",...Y(t),prefix:e})}function Yl(e,t){return new sy({check:"string_format",format:"ends_with",...Y(t),suffix:e})}function sn(e){return new ay({check:"overwrite",tx:e})}function ef(e){return sn((t)=>t.normalize(e))}function tf(){return sn((e)=>e.trim())}function rf(){return sn((e)=>e.toLowerCase())}function nf(){return sn((e)=>e.toUpperCase())}function of(){return sn((e)=>Jm(e))}function sx(e,t,n){return new e({type:"array",element:t,...Y(n)})}function ax(e,t,n){let r=Y(n);return r.abort??(r.abort=!0),new e({type:"custom",check:"custom",fn:t,...r})}function cx(e,t,n){return new e({type:"custom",check:"custom",fn:t,...Y(n)})}function ux(e,t){let n=Rk((r)=>(r.addIssue=(i)=>{if(typeof i==="string")r.issues.push(In(i,r.value,n._zod.def));else{let o=i;if(o.fatal)o.continue=!1;if(o.code??(o.code="custom"),!("input"in o))o.input=r.value;o.inst??(o.inst=n),o.continue??(o.continue=!n._zod.def.abort),r.issues.push(In(o))}},e(r.value,r)),t);return n}function Rk(e,t){let n=new yt({check:"custom",...Y(t)});return n._zod.check=e,n}function To(e,...t){for(let n of t)for(let r of Reflect.ownKeys(n))if(Object.prototype.propertyIsEnumerable.call(n,r))sr(e,r,n[r]);return e}function af(e){let t=e?.target??"draft-2020-12";if(t==="draft-4")t="draft-04";if(t==="draft-7")t="draft-07";return{processors:e.processors??{},metadataRegistry:e?.metadata??on,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??"ref",reused:e?.reused??"inline",intersections:[],deferred:[],external:e?.external??void 0}}function Pn(e,t,n,r,i){let o=typeof t.unrepresentable==="function"?t.unrepresentable({zodSchema:e,path:r.path,message:i}):t.unrepresentable;if(o==="any")return!1;if(o===void 0||o==="throw")throw Error(i);return Object.assign(n,o),!0}function Ze(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,o=t.seen.get(e);if(o){if(o.count++,n.schemaPath.includes(e))o.cycle=n.path;return o.schema}let s={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,s),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let a=e._zod.toJSONSchema?.();if(a)s.schema=a;else{let l={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,l);else{let p=s.schema,h=t.processors[i.type];if(!h)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);h(e,t,p,l)}let f=e._zod.parent;if(f){if(!s.ref)s.ref=f;Ze(f,t,l),t.seen.get(f).isParent=!0}}let c=t.metadataRegistry.get(e);if(c)To(s.schema,c);if(t.io==="input"&&Tt(e))delete s.schema.examples,delete s.schema.default;if(t.io==="input"&&"_prefault"in s.schema)(r=s.schema).default??(r.default=s.schema._prefault);return delete s.schema._prefault,t.seen.get(e).schema}function lx(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function cf(e,t){let n=e.seen.get(t);if(!n)throw Error("Unprocessed schema. This is a bug in Zod.");if(e.external&&e.sharedDefsExtractedFor===e.external)return;let r=new Map;for(let s of e.seen.entries()){let a=e.metadataRegistry.get(s[0])?.id;if(a){let c=r.get(a);if(c&&c!==s[0])throw Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(a,s[0])}}let i=(s)=>{let a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let f=e.external.registry.get(s[0])?.id,p=e.external.uri??((d)=>d);if(f)return{ref:p(f)};let h=s[1].defId??s[1].schema.id??`schema${e.counter++}`;return s[1].defId=h,{defId:h,ref:`${p("__shared")}#/${a}/${lx(h)}`}}let c="#",u=`${c}/${a}/`;if(s[1]===n&&!s[1].schema.id)return{ref:c};let l=s[1].schema.id??`__schema${e.counter++}`;return{defId:l,ref:u+lx(l)}},o=(s)=>{if(s[1].schema.$ref)return;let a=s[1],{ref:c,defId:u}=i(s);if(a.def={...a.schema},u)a.defId=u;let l=a.schema;for(let f in l)delete l[f];l.$ref=c};if(e.cycles==="throw")for(let s of e.seen.entries()){let a=s[1];if(a.cycle)throw Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
150
+ `)}return v.write("payload.value = newResult;"),v.write("return payload;"),v.compile()},s,a=go,c=!Tt.jitless,l=c&&Ym.value,f=t.catchall,p;e._zod.parse=(h,d)=>{p??(p=r.value);let g=h.value;if(!a(g))return h.issues.push({expected:"object",code:"invalid_type",input:g,inst:e}),h;if(c&&l&&d?.async===!1&&d.jitless!==!0){if(!s)s=o(t.shape);if(h=s(h,d),!f)return h;return iv([],g,h,d,p,e,d?.abortEarly===!0)}return n(h,d)}});function py(e,t,n,r){for(let o of e)if(o.issues.length===0)return t.value=o.value,t;let i=e.filter((o)=>!qt(o));if(i.length===1)return t.value=i[0].value,i[0];return t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map((o)=>o.issues.map((s)=>wr(s,r,Pt())))}),t}var sv=N("$ZodUnion",(e,t)=>{We.init(e,t),Be(e,"optin",(r)=>r.def.options.some((i)=>i._zod.optin==="defaulted")?"defaulted":r.def.options.some((i)=>i._zod.optin!==void 0)?"optional":void 0),Be(e,"optout",(r)=>r.def.options.some((i)=>i._zod.optout==="optional")?"optional":void 0),Be(e,"values",(r)=>{if(r.def.options.every((i)=>i._zod.values))return new Set(r.def.options.flatMap((i)=>Array.from(i._zod.values)));return}),Be(e,"pattern",(r)=>{if(r.def.options.every((i)=>i._zod.pattern)){let i=r.def.options.map((o)=>o._zod.pattern);return new RegExp(`^(${i.map((o)=>ha(o.source)).join("|")})$`)}return});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let o=!1,s=[];for(let a of t.options){let c=a._zod.run({value:r.value,issues:[]},i);if(c instanceof Promise)s.push(c),o=!0;else{if(c.issues.length===0)return c;s.push(c)}}if(!o)return py(s,r,e,i);return Promise.all(s).then((a)=>py(a,r,e,i))}});var av=N("$ZodIntersection",(e,t)=>{We.init(e,t),e._zod.parse=(n,r)=>{let i=n.value,o=t.left._zod.run({value:i,issues:[]},r),s=t.right._zod.run({value:i,issues:[]},r);if(o instanceof Promise||s instanceof Promise)return Promise.all([o,s]).then(([c,u])=>hy(n,c,u));return hy(n,o,s)}});function zl(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(In(e)&&In(t)){let n=Object.keys(t),r=Object.keys(e).filter((o)=>n.indexOf(o)!==-1),i={...e,...t};if(Object.prototype.hasOwnProperty.call(i,"__proto__"))delete i.__proto__;for(let o of r){if(o==="__proto__")continue;let s=zl(e[o],t[o]);if(!s.valid)return{valid:!1,mergeErrorPath:[o,...s.mergeErrorPath]};i[o]=s.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],o=t[r],s=zl(i,o);if(!s.valid)return{valid:!1,mergeErrorPath:[r,...s.mergeErrorPath]};n.push(s.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function hy(e,t,n){let r=new Map,i,o=new Map,s=(u,l)=>{let f;if(u.code==="unrecognized_keys"&&!u.path?.length)i??(i=u),f=u.keys;else if(u.code==="invalid_key"&&u.origin==="record"&&u.path?.length===1){let p=String(u.path[0]);if(!o.has(p))o.set(p,u);f=[p]}else return!1;for(let p of f){if(!r.has(p))r.set(p,{});r.get(p)[l]=!0}return!0};for(let u of t.issues)if(!s(u,"l"))e.issues.push(u);for(let u of n.issues)if(!s(u,"r"))e.issues.push(u);let a=[...r].filter(([,u])=>u.l&&u.r).map(([u])=>u);if(a.length){let u=i?a.filter((l)=>i.keys.includes(l)):[];if(u.length)e.issues.push({...i,keys:u});for(let l of a)if(!u.includes(l)&&o.has(l))e.issues.push(o.get(l))}let c=zl(t.value,n.value);if(!c.valid){if(qt(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return e.value=c.data,e}var cv=N("$ZodTuple",(e,t)=>{We.init(e,t);let n=t.items,r=Tt.memoizer;r?.attach(e),e._zod.parse=(i,o)=>{let s=i.value;if(!Array.isArray(s))return i.issues.push({input:s,inst:e,expected:"tuple",code:"invalid_type"}),i;i.value=r?r.alloc(e,i,[],o):[];let a=[],c=my(n,"optin"),u=my(n,"optout");if(!t.rest){if(s.length<c)return i.issues.push({code:"too_small",minimum:c,inclusive:!0,input:s,inst:e,origin:"array"}),i;if(s.length>n.length)i.issues.push({code:"too_big",maximum:n.length,inclusive:!0,input:s,inst:e,origin:"array"})}let l=Array(n.length),f=t.rest?o?.abortEarly:void 0,p=!1;for(let h=0;h<n.length;h++){let d=n[h]._zod.run({value:s[h],issues:[]},o);if(d instanceof Promise)a.push(d.then((g)=>{l[h]=g}));else if(l[h]=d,f&&!p&&d.issues.length)p=qt(d)}if(t.rest&&!p){let h=n.length-1,d=s.slice(n.length),g=i.issues.length;for(let v of d){if(f&&i.issues.length!==g){if(qt(i,g))break;g=i.issues.length}h++;let b=t.rest._zod.run({value:v,issues:[]},o);if(b instanceof Promise)a.push(b.then((S)=>gy(S,i,h)));else gy(b,i,h)}}if(a.length)return Promise.all(a).then(()=>yy(l,i,n,s,u));return yy(l,i,n,s,u)}});function my(e,t){for(let n=e.length-1;n>=0;n--)if(!(t==="optin"?e[n]._zod.optin!==void 0:e[n]._zod.optout==="optional"))return n+1;return 0}function gy(e,t,n){if(e.issues.length)t.issues.push(...Cr(n,e.issues));t.value[n]=e.value}function yy(e,t,n,r,i){for(let o=0;o<n.length;o++){let s=e[o],a=o<r.length;if(!a&&o>=i&&n[o]._zod.optin==="optional"){t.value.length=o;break}if(s.issues.length){if(!a&&o>=i){t.value.length=o;break}t.issues.push(...Cr(o,s.issues))}t.value[o]=s.value}for(let o=t.value.length-1;o>=r.length;o--)if(n[o]._zod.optout==="optional"&&t.value[o]===void 0)t.value.length=o;else break;return t}var uv=N("$ZodRecord",(e,t)=>{We.init(e,t);let n=Tt.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let o=r.value;if(!In(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),r;let s=[],a=t.keyType._zod.values;if(a&&!t.partial){r.value=n?n.alloc(e,r,{},i):{};let c=new Set;for(let l of a)if(typeof l==="string"||typeof l==="number"||typeof l==="symbol"){if(c.add(typeof l==="number"?l.toString():l),l==="__proto__")continue;let f=t.keyType._zod.run({value:l,issues:[]},i);if(f instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(f.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:f.issues.map((d)=>wr(d,i,Pt())),input:l,path:[l],inst:e});continue}let p=f.value;if(p==="__proto__")continue;let h=t.valueType._zod.run({value:o[l],issues:[]},i);if(h instanceof Promise)s.push(h.then((d)=>{if(d.issues.length)r.issues.push(...Cr(l,d.issues));r.value[p]=d.value}));else{if(h.issues.length)r.issues.push(...Cr(l,h.issues));r.value[p]=h.value}}let u;for(let l in o)if(!c.has(l))if(t.mode==="loose"){if(l==="__proto__")continue;r.value[l]=o[l]}else u=u??[],u.push(l);if(u&&u.length>0)r.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:u,continue:!0})}else{r.value=n?n.alloc(e,r,{},i):{};let c;for(let u of Reflect.ownKeys(o)){if(u==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(o,u))continue;let l=t.keyType._zod.run({value:u,issues:[]},i);if(l instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof u==="string"&&bo.test(u)&&l.issues.length){let d=t.keyType._zod.run({value:Number(u),issues:[]},i);if(d instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(d.issues.length===0)l=d}if(l.issues.length){if(t.mode==="loose")r.value[u]=o[u];else if(a)c=c??[],c.push(u);else r.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map((d)=>wr(d,i,Pt())),input:u,path:[u],inst:e});continue}let p=l.value;if(p==="__proto__")continue;let h=t.valueType._zod.run({value:o[u],issues:[]},i);if(h instanceof Promise)s.push(h.then((d)=>{if(d.issues.length)r.issues.push(...Cr(u,d.issues));r.value[p]=d.value}));else{if(h.issues.length)r.issues.push(...Cr(u,h.issues));r.value[p]=h.value}}if(c&&c.length>0)r.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:c,continue:!0})}if(s.length)return Promise.all(s).then(()=>r);return r}});var lv=N("$ZodEnum",(e,t)=>{We.init(e,t);let n=yo(t.entries),r=new Set(n);e._zod.values=r,Be(e,"pattern",(i)=>{let o=yo(i.def.entries).filter((s)=>eg.has(typeof s));return new RegExp(o.length?`^(${o.map((s)=>vi(s.toString())).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(i,o)=>{let s=i.value;if(r.has(s))return i;return i.issues.push({code:"invalid_value",values:n,input:s,inst:e}),i}});var fv=N("$ZodTransform",(e,t)=>{We.init(e,t),e._zod.optin="optional",Tt.memoizer?.guard(e),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new xo(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then((s)=>(n.value=s,n));if(i instanceof Promise)throw new Er;return n.value=i,n}});function vy(e,t){return e.value=t.issues.length?void 0:t.value,e}var Wl=N("$ZodOptional",(e,t)=>{We.init(e,t),Be(e,"optin",(n)=>n.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),e._zod.optout="optional",Be(e,"values",(n)=>{let r=n.def.innerType._zod.values;return r?new Set([...r,void 0]):void 0}),Be(e,"pattern",(n)=>{let r=n.def.innerType._zod.pattern;return r?new RegExp(`^(${ha(r.source)})?$`):void 0}),e._zod.parse=(n,r)=>{if(n.value===void 0){if(t.innerType._zod.optin!=="defaulted")return n;let i=t.innerType._zod.run({value:n.value,issues:[]},r);if(i instanceof Promise)return i.then((o)=>vy(n,o));return vy(n,i)}return t.innerType._zod.run(n,r)}}),dv=N("$ZodExactOptional",(e,t)=>{Wl.init(e,t),Be(e,"values",(n)=>n.def.innerType._zod.values),Be(e,"pattern",(n)=>n.def.innerType._zod.pattern),e._zod.parse=(n,r)=>t.innerType._zod.run(n,r)}),pv=N("$ZodNullable",(e,t)=>{We.init(e,t),Be(e,"optin",(n)=>n.def.innerType._zod.optin),Be(e,"optout",(n)=>n.def.innerType._zod.optout),Be(e,"pattern",(n)=>{let r=n.def.innerType._zod.pattern;return r?new RegExp(`^(${ha(r.source)}|null)$`):void 0}),Be(e,"values",(n)=>n.def.innerType._zod.values?new Set([...n.def.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>{if(n.value===null)return n;return t.innerType._zod.run(n,r)}}),hv=N("$ZodDefault",(e,t)=>{We.init(e,t),e._zod.optin="defaulted",Be(e,"values",(n)=>n.def.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)return n.value=t.defaultValue,n;let i=t.innerType._zod.run(n,r);if(i instanceof Promise)return i.then((o)=>xy(o,t));return xy(i,t)}});function xy(e,t){if(e.value===void 0)e.value=t.defaultValue;return e}var mv=N("$ZodPrefault",(e,t)=>{We.init(e,t),e._zod.optin="defaulted",Be(e,"values",(n)=>n.def.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)n.value=t.defaultValue;return t.innerType._zod.run(n,r)}}),gv=N("$ZodNonOptional",(e,t)=>{We.init(e,t),Be(e,"values",(n)=>{let r=n.def.innerType._zod.values;return r?new Set([...r].filter((i)=>i!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);if(i instanceof Promise)return i.then((o)=>by(o,e));return by(i,e)}});function by(e,t){if(!e.issues.length&&e.value===void 0)e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t});return e}function Sy(e,t,n,r){if(!t.issues.length){if(e.value=t.value,t.memo)e.memo=!0;return e}return e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map((i)=>wr(i,r,Pt()))},input:e.value}),e}var yv=N("$ZodCatch",(e,t)=>{We.init(e,t),Be(e,"optin",(n)=>n.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),Be(e,"optout",(n)=>n.def.innerType._zod.optout),Be(e,"values",(n)=>n.def.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);let i=t.innerType._zod.run({value:n.value,issues:[]},r);if(i instanceof Promise)return i.then((o)=>Sy(n,o,t,r));return Sy(n,i,t,r)}});var Hl=N("$ZodPipe",(e,t)=>{We.init(e,t),Be(e,"values",(n)=>n.def.in._zod.values),Be(e,"optin",(n)=>n.def.in._zod.optin),Be(e,"optout",(n)=>n.def.out._zod.optout),Be(e,"propValues",(n)=>n.def.in._zod.propValues),e._zod.parse=(n,r)=>{if(r.direction==="backward"){let o=t.out._zod.run(n,r);if(o instanceof Promise)return o.then((s)=>ka(s,t.in,r));return ka(o,t.in,r)}let i=t.in._zod.run(n,r);if(i instanceof Promise)return i.then((o)=>ka(o,t.out,r));return ka(i,t.out,r)}});function ka(e,t,n){if(e.issues.some((r)=>r.code!=="unrecognized_keys"))return e.aborted=!0,e;return t._zod.run({value:e.value,issues:e.issues},n)}var vv=N("$ZodPreprocess",(e,t)=>{Hl.init(e,t)}),xv=N("$ZodReadonly",(e,t)=>{We.init(e,t),Be(e,"propValues",(n)=>n.def.innerType._zod.propValues),Be(e,"values",(n)=>n.def.innerType._zod.values),Be(e,"optin",(n)=>n.def.innerType?._zod?.optin),Be(e,"optout",(n)=>n.def.innerType?._zod?.optout),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);let i=t.innerType._zod.run(n,r);if(i instanceof Promise)return i.then(Cy);return Cy(i)}});function Cy(e){if(!e.memo)e.value=Object.freeze(e.value);return e}var bv=N("$ZodCustom",(e,t)=>{yt.init(e,t),We.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=(n)=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then((o)=>wy(o,n,r,e));wy(i,n,r,e);return}});function wy(e,t,n,r){if(!e){let i={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};if(r._zod.def.params)i.params=r._zod.def.params;t.issues.push(Pn(i))}}class Cv extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform");this.name="ZodCyclicError"}}var Zl="~memo",Sv=[];function wv(e){return e!==null&&typeof e==="object"}function Kl(e){return e.map((t)=>t.path?{...t,path:t.path.slice()}:{...t})}var Ev=new WeakMap,Co=0,$a=1,wo=2;function Oa(e,t,n){let r=Ev.get(e);if(r!==void 0)return r?wo:Co;if(t.has(e))return wo;t.add(e);let i=Co,o=(l)=>{if(i!==wo&&l?._zod){let f=Oa(l,t,n);if(f>i)i=f}},s=(l,f)=>{let p=Co;for(let h of Reflect.ownKeys(l)){let d=Object.getOwnPropertyDescriptor(l,h);if(f&&!d.enumerable)continue;let g=d.get?$a:d.value?._zod?Oa(d.value,t,n):Co;if(g>p)p=g}return p},a=(l)=>{if(l>i)i=l},c=e._zod.def,u=c.type;switch(u){case"object":{let l=ma(c);a(l?s(l,!0):$a),o(c.catchall);break}case"array":o(c.element);break;case"tuple":for(let l of c.items)o(l);o(c.rest);break;case"record":case"map":o(c.keyType),o(c.valueType);break;case"set":o(c.valueType);break;case"union":for(let l of c.options)o(l);break;case"intersection":o(c.left),o(c.right);break;case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":o(c.innerType);break;case"pipe":o(c.in),o(c.out);break;case"function":o(c.input),o(c.output);break;case"lazy":{let l=c._cachedInner??(n?e._zod.innerType:void 0);a(l?Oa(l,t,!1):$a);break}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":break;default:for(let l in c){let f=Object.getOwnPropertyDescriptor(c,l);if(!f||f.get)continue;let p=f.value;if(!p||typeof p!=="object")continue;if(p._zod)o(p);else if(Array.isArray(p))for(let h of p)o(h)}}return t.delete(e),Ak(e,i)}function Ak(e,t){if(t!==$a)Ev.set(e,t===wo);return t}function kk(e,t){let n=e.buckets.get(t);if(!n)n=new WeakMap,e.buckets.set(t,n);return n}var Na,Da=[],Ik={alloc(e,t,n){let r=Na;if(!r)return n;Na=void 0;let i={value:n,issues:null};return r.set(t.value,i),Da.push(i),n},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let n=e._zod.parse,r=(i,o)=>{if(o.direction!=="backward"&&Pk(o,i.value))throw new Cv;return n(i,o)};if(e._zod.parse=r,e._zod.run===n)e._zod.run=r})},attach(e){var t;let n,r=!1,i,o;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let s=e._zod.parse,a=(c,u)=>{if(n===void 0){let b=Oa(e,new Set,!1);if(b===Co){if(e._zod.parse=s,e._zod.run===a)e._zod.run=s;return s(c,u)}if(b===wo||r)n=!0;else r=!0}let l=c.value;if(!wv(l))return s(c,u);let f=u[Zl];if(!f)f={buckets:new WeakMap,backEdges:void 0},u[Zl]=f;let p;if(i===u)p=o;else p=kk(f,e),i=u,o=p;let h=p.get(l);if(h){if(c.value=h.value,h.issues){if(h.issues.length)c.issues.push(...Kl(h.issues))}else c.memo=!0,f.backEdges??(f.backEdges=new WeakSet),f.backEdges.add(h.value);return c}Na=p;let d=Da.length,g=s(c,u);Na=void 0;let v=Da.length>d?Da.pop():void 0;if(g instanceof Promise)return g.then((b)=>{if(v)v.issues=b.issues.length?Kl(b.issues):Sv;return b});if(v)v.issues=g.issues.length?Kl(g.issues):Sv;return g};if(e._zod.parse=a,e._zod.run===s)e._zod.run=a})}};function jl(){return Ik}function Pk(e,t){let n=e[Zl]?.backEdges;return n!==void 0&&wv(t)&&n.has(t)}var Rk=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function t(o){return e[o]??null}let n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",currency_code:"currency code",credit_card:"credit card number",iban:"IBAN",jwt:"JWT",template_literal:"input"},r={nan:"NaN"};function i(o,s){if(o==="number"&&typeof s==="number"&&!Number.isFinite(s))return String(s);return r[o]??o}return(o)=>{switch(o.code){case"invalid_type":{let s=i(o.expected),a=og(o.input),c=i(a,o.input);return`Invalid input: expected ${s}, received ${c}`}case"invalid_value":if(o.values.length===1)return`Invalid input: expected ${Cl(o.values[0])}`;return`Invalid option: expected one of ${xl(o.values,"|")}`;case"too_big":{let s=o.exact?"exactly ":o.inclusive?"<=":"<",a=t(o.origin);if(a)return`Too big: expected ${o.origin??"value"} to have ${s}${o.maximum.toString()} ${a.unit??"elements"}`;return`Too big: expected ${o.origin??"value"} to be ${s}${o.maximum.toString()}`}case"too_small":{let s=o.exact?"exactly ":o.inclusive?">=":">",a=t(o.origin);if(a)return`Too small: expected ${o.origin} to have ${s}${o.minimum.toString()} ${a.unit}`;return`Too small: expected ${o.origin} to be ${s}${o.minimum.toString()}`}case"invalid_format":{let s=o;if(s.format==="starts_with")return`Invalid string: must start with "${s.prefix}"`;if(s.format==="ends_with")return`Invalid string: must end with "${s.suffix}"`;if(s.format==="includes")return`Invalid string: must include "${s.includes}"`;if(s.format==="regex")return`Invalid string: must match pattern ${s.pattern}`;return`Invalid ${n[s.format]??o.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${o.divisor}`;case"unrecognized_keys":return`Unrecognized key${o.keys.length>1?"s":""}: ${xl(o.keys,", ")}`;case"invalid_key":return`Invalid key in ${o.origin}`;case"invalid_union":if(o.options&&Array.isArray(o.options)&&o.options.length>0)return`Invalid discriminator value. Expected ${o.options.map((a)=>`'${a}'`).join(" | ")}`;if(o.inclusive===!1)return"Invalid input: more than one option matched";return"Invalid input";case"invalid_element":return`Invalid value in ${o.origin}`;default:return"Invalid input"}}};function Gl(){return{localeError:Rk()}}var _v;class Tv{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];if(this._map.set(e,n),n&&typeof n==="object"&&"id"in n)this._idmap.set(n.id,e);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);if(t&&typeof t==="object"&&"id"in t)this._idmap.delete(t.id);return this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function Av(){return new Tv}(_v=globalThis).__zod_globalRegistry??(_v.__zod_globalRegistry=Av());var on=globalThis.__zod_globalRegistry;function kv(e){if(e.checks)e.checks=[...e.checks];return e}function Iv(e,t){return new e(kv({type:"string",...Y(t)}))}function Pv(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...Y(t)})}function Rv(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...Y(t)})}function Bv(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...Y(t)})}function Nv(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Y(t)})}function Dv(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Y(t)})}function $v(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Y(t)})}function Ov(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...Y(t)})}function Lv(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...Y(t)})}function Uv(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...Y(t)})}function zv(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...Y(t)})}function Fv(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...Y(t)})}function Mv(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...Y(t)})}function Vv(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...Y(t)})}function Wv(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...Y(t)})}function Hv(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...Y(t)})}function Kv(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...Y(t)})}function Zv(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Y(t)})}function jv(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Y(t)})}function Gv(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...Y(t)})}function qv(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...Y(t)})}function Xv(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...Y(t)})}function Jv(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...Y(t)})}function Qv(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Y(t)})}function Yv(e,t){return new e({type:"string",format:"date",check:"string_format",...Y(t)})}function ex(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...Y(t)})}function tx(e,t){return new e({type:"string",format:"duration",check:"string_format",...Y(t)})}function rx(e,t){return new e(kv({type:"number",checks:[],...Y(t)}))}function nx(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...Y(t)})}function ix(e,t){return new e({type:"boolean",...Y(t)})}function ox(e){return new e({type:"unknown"})}function sx(e,t){return new e({type:"never",...Y(t)})}function La(e,t){return new Ol({check:"less_than",...Y(t),value:e,inclusive:!1})}function Eo(e,t){return new Ol({check:"less_than",...Y(t),value:e,inclusive:!0})}function Ua(e,t){return new Ll({check:"greater_than",...Y(t),value:e,inclusive:!1})}function _o(e,t){return new Ll({check:"greater_than",...Y(t),value:e,inclusive:!0})}function za(e,t){return new Jg({check:"multiple_of",...Y(t),value:e})}function Fa(e,t){return new Yg({check:"max_length",...Y(t),maximum:e})}function bi(e,t){return new ey({check:"min_length",...Y(t),minimum:e})}function Ma(e,t){return new ty({check:"length_equals",...Y(t),length:e})}function ql(e,t){return new ry({check:"string_format",format:"regex",...Y(t),pattern:e})}function Xl(e){return new ny({check:"string_format",format:"lowercase",...Y(e)})}function Jl(e){return new iy({check:"string_format",format:"uppercase",...Y(e)})}function Ql(e,t){return new oy({check:"string_format",format:"includes",...Y(t),includes:e})}function Yl(e,t){return new sy({check:"string_format",format:"starts_with",...Y(t),prefix:e})}function ef(e,t){return new ay({check:"string_format",format:"ends_with",...Y(t),suffix:e})}function sn(e){return new cy({check:"overwrite",tx:e})}function tf(e){return sn((t)=>t.normalize(e))}function rf(){return sn((e)=>e.trim())}function nf(){return sn((e)=>e.toLowerCase())}function of(){return sn((e)=>e.toUpperCase())}function sf(){return sn((e)=>Qm(e))}function ax(e,t,n){return new e({type:"array",element:t,...Y(n)})}function cx(e,t,n){let r=Y(n);return r.abort??(r.abort=!0),new e({type:"custom",check:"custom",fn:t,...r})}function ux(e,t,n){return new e({type:"custom",check:"custom",fn:t,...Y(n)})}function lx(e,t){let n=Bk((r)=>(r.addIssue=(i)=>{if(typeof i==="string")r.issues.push(Pn(i,r.value,n._zod.def));else{let o=i;if(o.fatal)o.continue=!1;if(o.code??(o.code="custom"),!("input"in o))o.input=r.value;o.inst??(o.inst=n),o.continue??(o.continue=!n._zod.def.abort),r.issues.push(Pn(o))}},e(r.value,r)),t);return n}function Bk(e,t){let n=new yt({check:"custom",...Y(t)});return n._zod.check=e,n}function To(e,...t){for(let n of t)for(let r of Reflect.ownKeys(n))if(Object.prototype.propertyIsEnumerable.call(n,r))sr(e,r,n[r]);return e}function cf(e){let t=e?.target??"draft-2020-12";if(t==="draft-4")t="draft-04";if(t==="draft-7")t="draft-07";return{processors:e.processors??{},metadataRegistry:e?.metadata??on,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??"ref",reused:e?.reused??"inline",intersections:[],deferred:[],external:e?.external??void 0}}function Rn(e,t,n,r,i){let o=typeof t.unrepresentable==="function"?t.unrepresentable({zodSchema:e,path:r.path,message:i}):t.unrepresentable;if(o==="any")return!1;if(o===void 0||o==="throw")throw Error(i);return Object.assign(n,o),!0}function Ze(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,o=t.seen.get(e);if(o){if(o.count++,n.schemaPath.includes(e))o.cycle=n.path;return o.schema}let s={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,s),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let a=e._zod.toJSONSchema?.();if(a)s.schema=a;else{let l={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,l);else{let p=s.schema,h=t.processors[i.type];if(!h)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);h(e,t,p,l)}let f=e._zod.parent;if(f){if(!s.ref)s.ref=f;Ze(f,t,l),t.seen.get(f).isParent=!0}}let c=t.metadataRegistry.get(e);if(c)To(s.schema,c);if(t.io==="input"&&At(e))delete s.schema.examples,delete s.schema.default;if(t.io==="input"&&"_prefault"in s.schema)(r=s.schema).default??(r.default=s.schema._prefault);return delete s.schema._prefault,t.seen.get(e).schema}function fx(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function uf(e,t){let n=e.seen.get(t);if(!n)throw Error("Unprocessed schema. This is a bug in Zod.");if(e.external&&e.sharedDefsExtractedFor===e.external)return;let r=new Map;for(let s of e.seen.entries()){let a=e.metadataRegistry.get(s[0])?.id;if(a){let c=r.get(a);if(c&&c!==s[0])throw Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(a,s[0])}}let i=(s)=>{let a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let f=e.external.registry.get(s[0])?.id,p=e.external.uri??((d)=>d);if(f)return{ref:p(f)};let h=s[1].defId??s[1].schema.id??`schema${e.counter++}`;return s[1].defId=h,{defId:h,ref:`${p("__shared")}#/${a}/${fx(h)}`}}let c="#",u=`${c}/${a}/`;if(s[1]===n&&!s[1].schema.id)return{ref:c};let l=s[1].schema.id??`__schema${e.counter++}`;return{defId:l,ref:u+fx(l)}},o=(s)=>{if(s[1].schema.$ref)return;let a=s[1],{ref:c,defId:u}=i(s);if(a.def={...a.schema},u)a.defId=u;let l=a.schema;for(let f in l)delete l[f];l.$ref=c};if(e.cycles==="throw")for(let s of e.seen.entries()){let a=s[1];if(a.cycle)throw Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
151
151
 
152
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let s of e.seen.entries()){let a=s[1];if(t===s[0]){o(s);continue}if(e.external){let u=e.external.registry.get(s[0])?.id;if(t!==s[0]&&u){o(s);continue}}if(e.metadataRegistry.get(s[0])?.id){o(s);continue}if(a.cycle){o(s);continue}if(a.count>1){if(e.reused==="ref")o(s)}}if(e.external)e.sharedDefsExtractedFor=e.external}function px(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let n=[];for(let r of t){if(!r||typeof r!=="object")return;px(r);let i=Object.keys(r);if(i.length!==1||i[0]!=="type")return;let o=r.type;for(let s of Array.isArray(o)?o:[o]){if(typeof s!=="string")return;if(!n.includes(s))n.push(s)}}delete e.anyOf,e.type=n.length===1?n[0]:n}var hx=new Set(["type","properties","required","additionalProperties"]),fx=["oneOf","anyOf"];function dx(e){let t=e.additionalProperties;if(t===void 0||t===!1||typeof t!=="object"||t===null)return null;return Object.keys(t).length?t:null}function sf(e){let t=[];for(let o of e){if(typeof o!=="object"||o.type!=="object")return null;for(let s in o)if(!hx.has(s))return null;t.push(o)}let n={},r=new Set;for(let o of t){for(let s in o.properties){if(Object.prototype.hasOwnProperty.call(n,s))continue;let a=[];for(let u of t){let l=u.properties?.[s]??dx(u);if(l===null||l===void 0)continue;if(!a.some((f)=>JSON.stringify(f)===JSON.stringify(l)))a.push(l)}let c=a.length===1?a[0]:sf(a)??{allOf:a};sr(n,s,c)}for(let s of o.required??[])r.add(s)}let i={type:"object",properties:n};if(r.size)i.required=[...r];if(t.every((o)=>o.additionalProperties===!1))i.additionalProperties=!1;else{let o=[];for(let s of t){let a=dx(s);if(a&&!o.some((c)=>JSON.stringify(c)===JSON.stringify(a)))o.push(a)}if(o.length===1)i.additionalProperties=o[0];else if(o.length>1)i.additionalProperties={allOf:o}}return i}function Bk(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let i of hx)if(i in e)return;let n=t.filter((i)=>fx.some((o)=>Array.isArray(i[o]))),r=null;if(!n.length)r=sf(t);else{let i=n[0],o=fx.find((c)=>Array.isArray(i[c]));if(Object.keys(i).length!==1)return;let s=t.filter((c)=>c!==i),a=i[o].map((c)=>sf([...s,c]));if(a.some((c)=>!c))return;r={[o]:a}}if(!r)return;delete e.allOf,To(e,r)}function uf(e,t){let n=e.seen.get(t);if(!n)throw Error("Unprocessed schema. This is a bug in Zod.");let r=(a)=>{let c=e.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,l={...u},f=c.ref;if(c.ref=null,f){r(f);let h=e.seen.get(f),d=h.schema;if(d.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"))u.allOf=u.allOf??[],u.allOf.push(d);else To(u,d);if(To(u,l),a._zod.parent===f)for(let x in u){if(x==="$ref"||x==="allOf")continue;if(!(x in l))delete u[x]}if(d.$ref&&h.def)for(let x in u){if(x==="$ref"||x==="allOf")continue;if(x in h.def&&JSON.stringify(u[x])===JSON.stringify(h.def[x]))delete u[x]}}let p=a._zod.parent;if(p&&p!==f){r(p);let h=e.seen.get(p);if(h?.schema.$ref){if(u.$ref=h.schema.$ref,h.def)for(let d in u){if(d==="$ref"||d==="allOf")continue;if(d in h.def&&JSON.stringify(u[d])===JSON.stringify(h.def[d]))delete u[d]}}}e.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let a of[...e.seen.entries()].reverse())r(a[0]);if(e.target!=="openapi-3.0")for(let a of e.seen.entries())px(a[1].def??a[1].schema);for(let a of e.deferred)a();if(e.intersections.length){let a=new Map;for(let c of e.seen.values())for(let u of[c.schema,c.def]){let l=u?.allOf;if(!Array.isArray(l))continue;let f=a.get(l);if(f)f.push(u);else a.set(l,[u])}for(let c of e.intersections)for(let u of a.get(c)??[])Bk(u)}}let i={};if(e.target==="draft-2020-12")i.$schema="https://json-schema.org/draft/2020-12/schema";else if(e.target==="draft-07")i.$schema="http://json-schema.org/draft-07/schema#";else if(e.target==="draft-04")i.$schema="http://json-schema.org/draft-04/schema#";else if(e.target==="openapi-3.0");if(e.external?.uri){let a=e.external.registry.get(t)?.id;if(!a)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(a)}To(i,n.defId?n.schema:n.def??n.schema);let o=e.metadataRegistry.get(t)?.id;if(o!==void 0&&i.id===o)delete i.id;let s=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let a of e.seen.entries()){let c=a[1];if(c.def&&c.defId){if(c.def.id===c.defId)delete c.def.id;sr(s,c.defId,c.def)}}if(e.external)e.sharedEmitDoneFor=e.external;if(e.external);else if(Object.keys(s).length>0)if(e.target==="draft-2020-12")i.$defs=s;else i.definitions=s;try{let a=JSON.parse(JSON.stringify(i));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:Ao(t,"input",e.processors),output:Ao(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch(a){throw Error("Error converting schema to JSON.")}}function Tt(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return Tt(r.element,n);if(r.type==="set")return Tt(r.valueType,n);if(r.type==="lazy")return Tt(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault"||r.type==="catch")return Tt(r.innerType,n);if(r.type==="intersection")return Tt(r.left,n)||Tt(r.right,n);if(r.type==="record"||r.type==="map")return Tt(r.keyType,n)||Tt(r.valueType,n);if(r.type==="pipe"){if(e._zod.traits.has("$ZodCodec"))return!0;return Tt(r.in,n)||Tt(r.out,n)}if(r.type==="object"){for(let i in r.shape)if(Tt(r.shape[i],n))return!0;return!1}if(r.type==="union"){for(let i of r.options)if(Tt(i,n))return!0;return!1}if(r.type==="tuple"){for(let i of r.items)if(Tt(i,n))return!0;if(r.rest&&Tt(r.rest,n))return!0;return!1}return!1}var mx=(e,t={})=>(n)=>{let r=af({...n,processors:t});return Ze(e,r),cf(r,e),uf(r,e)},Ao=(e,t,n={})=>(r)=>{let{libraryOptions:i,target:o}=r??{},s=af({...i??{},target:o,io:t,processors:n});return Ze(e,s),cf(s,e),uf(s,e)};var xi=(e,t,n)=>{if(e[t]===void 0||n>e[t])e[t]=n},bi=(e,t,n)=>{if(e[t]===void 0||n<e[t])e[t]=n},gx=(e,t)=>{xi(e,"minimum",t),bi(e,"maximum",t)},bx=(e,t)=>{if(e.multipleOf??(e.multipleOf=[]),!e.multipleOf.includes(t))e.multipleOf.push(t)},Sx=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},Cx=(e,t)=>{e.mime=e.mime?e.mime.filter((n)=>t.includes(n)):[...t]},wx=(e,t)=>{if(e.format=t,t.includes("int"))e.isInt=!0},yx=(e,t)=>xi(e,"minimum",t.minimum),vx=(e,t)=>bi(e,"maximum",t.maximum),xx=(e)=>(t,n)=>{wx(t,n.format);let[r,i]=e[n.format];xi(t,"minimum",r),bi(t,"maximum",i)},Nk={greater_than:(e,t)=>xi(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>bi(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>bx(e,t.value),number_format:xx(ga),bigint_format:xx(Cl),min_length:yx,max_length:vx,length_equals:(e,t)=>gx(e,t.length),min_size:yx,max_size:vx,size_equals:(e,t)=>gx(e,t.size),string_format:(e,t)=>{if(wx(e,t.format),t.pattern)Sx(e,t.pattern);if(t.format==="base64"||t.format==="base64url")e.contentEncoding=t.format;if(t.local||t.precision===-1)e.laxFormat=!0},mime_type:(e,t)=>Cx(e,t.mime)};function $t(e){let t={},n=e._zod.def,r=e._zod.traits.has("$ZodCheck")?[e,...n.checks??[]]:n.checks??[];for(let o of r)Nk[o._zod.def.check]?.(t,o._zod.def);let i=e._zod.bag;if(i.minimum!==void 0)xi(t,"minimum",i.minimum);if(i.exclusiveMinimum!==void 0)xi(t,"exclusiveMinimum",i.exclusiveMinimum);if(i.maximum!==void 0)bi(t,"maximum",i.maximum);if(i.exclusiveMaximum!==void 0)bi(t,"exclusiveMaximum",i.exclusiveMaximum);if(i.multipleOf!==void 0)bx(t,i.multipleOf);if(i.format!==void 0){if(t.format??(t.format=i.format),i.format.includes("int"))t.isInt=!0}if(i.mime)Cx(t,i.mime);for(let o of i.patterns??[])Sx(t,o);return t}var Dk={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},$k=new Map([[Fl,Ug],[Ba,zg]]),Ex=(e)=>$k.get(e)??e,_x=(e,t,n,r)=>{let i=n;i.type="string";let{minimum:o,maximum:s,format:a,patterns:c,contentEncoding:u,laxFormat:l}=$t(e);if(typeof o==="number")i.minLength=o;if(typeof s==="number")i.maxLength=s;if(a){if(i.format=Dk[a]??a,i.format==="")delete i.format;if(a==="time"||l)delete i.format}if(u)i.contentEncoding=u;if(c&&c.size>0){let f=[...c].map(Ex);if(f.length===1)i.pattern=f[0].source;else if(f.length>1)i.allOf=[...f.map((p)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:p.source}))]}},Tx=(e,t,n,r)=>{let i=n,{minimum:o,maximum:s,multipleOf:a,exclusiveMaximum:c,exclusiveMinimum:u,isInt:l}=$t(e);i.type=l?"integer":"number";let f=typeof u==="number"&&u>=(o??Number.NEGATIVE_INFINITY),p=typeof c==="number"&&c<=(s??Number.POSITIVE_INFINITY),h=t.target==="draft-04"||t.target==="openapi-3.0";if(f)if(h)i.minimum=u,i.exclusiveMinimum=!0;else i.exclusiveMinimum=u;else if(typeof o==="number")i.minimum=o;if(p)if(h)i.maximum=c,i.exclusiveMaximum=!0;else i.exclusiveMaximum=c;else if(typeof s==="number")i.maximum=s;if(a){let d=new Set;for(let b of a)if(Number.isFinite(b)&&b!==0)d.add(Math.abs(b));else Pn(e,t,i,r,`A multipleOf divisor of ${b} cannot be represented in JSON Schema`);let[g,...x]=d;if(g!==void 0)i.multipleOf=g;if(x.length)i.allOf=[...i.allOf??[],...x.map((b)=>({multipleOf:b}))]}},Ax=(e,t,n,r)=>{n.type="boolean"};var kx=(e,t,n,r)=>{n.not={}};var Ix=(e,t,n,r)=>{};var Px=(e,t,n,r)=>{let i=e._zod.def,o=yo(i.entries);if(o.length===0){n.not={};return}if(o.every((s)=>typeof s==="number"))n.type="number";if(o.every((s)=>typeof s==="string"))n.type="string";n.enum=o};var Rx=(e,t,n,r)=>{Pn(e,t,n,r,"Custom types cannot be represented in JSON Schema")};var Bx=(e,t,n,r)=>{Pn(e,t,n,r,"Transforms cannot be represented in JSON Schema")};var Nx=(e,t,n,r)=>{let i=n,o=e._zod.def,{minimum:s,maximum:a}=$t(e);if(typeof s==="number")i.minItems=s;if(typeof a==="number")i.maxItems=a;i.type="array",i.items=Ze(o.element,t,{...r,path:[...r.path,"items"]})};function ko(e){let t=e._zod.def;if(t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform"))return ko(t.out);if(t.type==="catch")return ko(t.innerType);return e._zod.optin}var Dx=(e,t,n,r)=>{let i=n,o=e._zod.def,s=o.shape;if(Object.getOwnPropertySymbols(s).length&&Pn(e,t,i,r,"Symbol keys cannot be represented in JSON Schema"))return;i.type="object",i.properties={};for(let u in s)sr(i.properties,u,Ze(s[u],t,{...r,path:[...r.path,"properties",u]}));let c=[];for(let u of Object.keys(s)){let l=o.shape[u];if(t.io==="input"?ko(l)===void 0:l._zod.optout===void 0)c.push(u)}if(c.length>0)i.required=c;if(o.catchall?._zod.def.type==="never")i.additionalProperties=!1;else if(!o.catchall){if(t.io==="output")i.additionalProperties=!1}else if(o.catchall)i.additionalProperties=Ze(o.catchall,t,{...r,path:[...r.path,"additionalProperties"]})},$x=(e,t,n,r)=>{let i=e._zod.def,o=i.inclusive===!1,s=i.options.map((a,c)=>Ze(a,t,{...r,path:[...r.path,o?"oneOf":"anyOf",c]}));if(o)n.oneOf=s;else n.anyOf=s},Ox=(e,t,n,r)=>{let i=e._zod.def,o=Ze(i.left,t,{...r,path:[...r.path,"allOf",0]}),s=Ze(i.right,t,{...r,path:[...r.path,"allOf",1]}),a=(u)=>("allOf"in u)&&Object.keys(u).length===1,c=[...a(o)?o.allOf:[o],...a(s)?s.allOf:[s]];n.allOf=c,t.intersections.push(c)},Lx=(e,t,n,r)=>{let i=n,o=e._zod.def;i.type="array";let s=t.target==="draft-2020-12"?"prefixItems":"items",a=t.target==="draft-2020-12"?"items":t.target==="openapi-3.0"?"items":"additionalItems",c=o.items.map((g,x)=>Ze(g,t,{...r,path:[...r.path,s,x]})),u=o.rest?Ze(o.rest,t,{...r,path:[...r.path,a,...t.target==="openapi-3.0"?[o.items.length]:[]]}):null,l=o.items.length;while(l>0){let g=o.items[l-1];if(!(t.io==="input"?ko(g)!==void 0:g._zod.optout==="optional"))break;l--}let f=o.items.length,p=!o.rest;if(t.target==="draft-2020-12"){if(i.prefixItems=c,p)i.items=!1;else if(u)i.items=u;if(l>0)i.minItems=l;if(p)i.maxItems=f}else if(t.target==="openapi-3.0"){if(i.items={anyOf:c},u)i.items.anyOf.push(u);if(l>0)i.minItems=l;if(p)i.maxItems=f}else{if(i.items=c,p)i.additionalItems=!1;else if(u)i.additionalItems=u;if(l>0)i.minItems=l;if(p)i.maxItems=f}let{minimum:h,maximum:d}=$t(e);if(typeof h==="number")i.minItems=h;if(typeof d==="number")i.maxItems=d};function lf(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);let d=e.get(t)?.def;if(!d)return t;let g=lf(e,d,n);return g===d?t:g}for(let d of["anyOf","oneOf"]){let g=t[d];if(!Array.isArray(g))continue;let x=g.map((b)=>lf(e,b,n));if(x.some((b,S)=>b!==g[S]))t={...t,[d]:x}}let r=Array.isArray(t.type)?t.type:[t.type],i=!r.includes("string")&&r.some((d)=>d==="number"||d==="integer"),o=t.enum??(t.const!==void 0?[t.const]:void 0);if(!i&&!o?.some((d)=>typeof d==="number"))return t;let{minimum:s,maximum:a,exclusiveMinimum:c,exclusiveMaximum:u,multipleOf:l,format:f,id:p,...h}=t;if(h.enum)h.enum=h.enum.map((d)=>typeof d==="number"?String(d):d);else if(typeof h.const==="number")h.const=String(h.const);if(!i)return h;if(h.type="string",!o)h.pattern=(r.includes("number")?bo:Nl).source;return h}var ff=new WeakMap;function Ok(e){let t=new Map;for(let r of e.seen.values())if(r.def&&!t.has(r.schema))t.set(r.schema,r);let n=new Map;for(let r of ff.get(e)??[]){let i=e.seen.get(r),o=(i?.def??i?.schema)?.propertyNames;if(!o||o===!0||n.has(o))continue;let s=lf(t,o,new Set);if(s!==o)n.set(o,s)}if(!n.size)return;for(let r of e.seen.values())for(let i of[r.schema,r.def]){let o=i&&n.get(i.propertyNames);if(o)i.propertyNames=o}}var Ux=(e,t,n,r)=>{let i=n,o=e._zod.def;i.type="object";let s=o.keyType,a=$t(s).patterns;if(o.mode==="loose"&&a&&a.size>0){let l=Ze(o.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});i.patternProperties={};for(let f of a)sr(i.patternProperties,Ex(f).source,l)}else{if(t.target==="draft-07"||t.target==="draft-2020-12"){i.propertyNames=Ze(o.keyType,t,{...r,path:[...r.path,"propertyNames"]});let l=ff.get(t);if(!l)l=[],ff.set(t,l),t.deferred.push(()=>Ok(t));l.push(e)}i.additionalProperties=Ze(o.valueType,t,{...r,path:[...r.path,"additionalProperties"]})}let c=s._zod.values,u=t.io==="input"&&ko(o.valueType)!==void 0;if(c&&!o.partial&&!u){let l=[...c].filter((f)=>typeof f==="string"||typeof f==="number");if(l.length>0)i.required=l.map(String)}},zx=(e,t,n,r)=>{let i=e._zod.def,o=Ze(i.innerType,t,r),s=t.seen.get(e);if(t.target==="openapi-3.0")s.ref=i.innerType,n.nullable=!0;else n.anyOf=[o,{type:"null"}]},Fx=(e,t,n,r)=>{let i=e._zod.def;Ze(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType},df=Symbol();function Mx(e,t,n,r,i){let o=!1,s=JSON.stringify(e,(a,c)=>{if(typeof c!=="bigint")return c;return o=!0,null});if(!o)return JSON.parse(s);return Pn(t,n,r,i,"BigInt defaults cannot be represented in JSON Schema"),df}var Vx=(e,t,n,r)=>{let i=e._zod.def;Ze(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType;let s=Mx(i.defaultValue,e,t,n,r);if(s!==df)n.default=s},Wx=(e,t,n,r)=>{let i=e._zod.def;Ze(i.innerType,t,r);let o=t.seen.get(e);if(o.ref=i.innerType,t.io!=="input")return;let s=Mx(i.defaultValue,e,t,n,r);if(s!==df)n._prefault=s},Hx=(e,t,n,r)=>{let i=e._zod.def;Ze(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType;let s;try{s=i.catchValue(void 0)}catch{Pn(e,t,n,r,"Dynamic catch values are not supported in JSON Schema");return}n.default=s},Kx=(e,t,n,r)=>{let i=e._zod.def,o=i.in._zod.traits.has("$ZodTransform"),s=t.io==="input"?o?i.out:i.in:i.out;Ze(s,t,r);let a=t.seen.get(e);a.ref=s},Zx=(e,t,n,r)=>{let i=e._zod.def;Ze(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType,n.readOnly=!0};var pf=(e,t,n,r)=>{let i=e._zod.def;Ze(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType};var jx=new WeakSet([Object.prototype,Error.prototype]);function Wa(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let r=n(this);return Object.defineProperty(this,t,{value:r,configurable:!0,writable:!0}),r},set(r){Object.defineProperty(this,t,{value:r,configurable:!0,writable:!0})}})}var Kk=(e,t)=>{pg.init(e,t),e.name="ZodError";let n=Object.getPrototypeOf(e);if(jx.has(n))return;jx.add(n),Wa(n,"format",(r)=>(i)=>kl(r,i)),Wa(n,"flatten",(r)=>(i)=>Al(r,i)),Wa(n,"addIssue",(r)=>(i)=>{r.issues.push(i),r.message=JSON.stringify(r.issues,vo,2)}),Wa(n,"addIssues",(r)=>(i)=>{r.issues.push(...i),r.message=JSON.stringify(r.issues,vo,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}})};var Ot=N("ZodError",Kk,void 0,{Parent:Error});var Gx=wa(Ot),qx=Ea(Ot),Xx=_a(Ot),Jx=Ta(Ot),Qx=mg(Ot),Yx=gg(Ot),eb=yg(Ot),tb=vg(Ot),rb=xg(Ot),nb=bg(Ot),ib=Sg(Ot),ob=Cg(Ot);function jk(){if(!_t.localeError)Pt(jl())}function Io(){if(!_t.memoizer)Pt({memoizer:Zl()})}var je=N("ZodType",(e,t)=>(jk(),Me.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(Dt(t,{checks:[...t.checks??[],...e.map((n)=>typeof n==="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return ar(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(HI(e,t))},superRefine(e,t){return this.check(KI(e,t))},overwrite(e){return this.check(sn(e))},optional(){return ub(this)},exactOptional(){return RI(this)},nullable(){return lb(this)},nullish(){return ub(lb(this))},nonoptional(e){return LI(this,e)},array(){return We(this)},or(e){return _I([this,e])},and(e){return AI(this,e)},transform(e){return fb(this,mb(e))},default(e){return DI(this,e)},prefault(e){return OI(this,e)},catch(e){return zI(this,e)},pipe(e){return fb(this,e)},readonly(){return VI(this)},describe(e){let t=this.clone();return on.add(t,{description:e}),t},meta(...e){if(e.length===0)return on.get(this);let t=this.clone();return on.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get "~standard"(){return Sa(this,"~standard",{...zl(this),jsonSchema:{input:Ao(this,"input"),output:Ao(this,"output")}})},set "~standard"(e){Ur(this,"~standard",e)},parse:function e(t,n){return Gx(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await qx(this,t,n,{callee:e})},safeParse(e,t){return Xx(this,e,t)},async safeParseAsync(e,t){return Jx(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){Ur(this,"spa",e)},validate(e,t){return Il(this,e,t)},validateAsync(e,t){return Pl(this,e,t)},encode:function e(t,n){return Qx(this,t,n,{callee:e})},decode:function e(t,n){return Yx(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await eb(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await tb(this,t,n,{callee:e})},safeEncode(e,t){return rb(this,e,t)},safeDecode(e,t){return nb(this,e,t)},async safeEncodeAsync(e,t){return ib(this,e,t)},async safeDecodeAsync(e,t){return ob(this,e,t)},toJSONSchema(e){return mx(this,{})(e)},get description(){return on.get(this)?.description},get _def(){return this._zod.def}}),db=N("_ZodString",(e,t)=>{Ra.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,r,i)=>_x(e,n,r,i)},sg({format:(e)=>$t(e).format??null,minLength:(e)=>$t(e).minimum??null,maxLength:(e)=>$t(e).maximum??null},{regex(...e){return this.check(Gl(...e))},includes(...e){return this.check(Jl(...e))},startsWith(...e){return this.check(Ql(...e))},endsWith(...e){return this.check(Yl(...e))},min(...e){return this.check(vi(...e))},max(...e){return this.check(Fa(...e))},length(...e){return this.check(Ma(...e))},nonempty(...e){return this.check(vi(1,...e))},lowercase(e){return this.check(ql(e))},uppercase(e){return this.check(Xl(e))},trim(){return this.check(tf())},normalize(...e){return this.check(ef(...e))},toLowerCase(){return this.check(rf())},toUpperCase(){return this.check(nf())},slugify(){return this.check(of())}})),Gk=N("ZodString",(e,t)=>{Ra.init(e,t),db.init(e,t)},{email(e){return this.check(Iv(Yk,e))},url(e){return this.check($v(tI,e))},jwt(e){return this.check(Xv(gI,e))},emoji(e){return this.check(Ov(rI,e))},guid(e){return this.check(Pv(eI,e))},uuid(e){return this.check(Rv(Ha,e))},uuidv4(e){return this.check(Bv(Ha,e))},uuidv6(e){return this.check(Nv(Ha,e))},uuidv7(e){return this.check(Dv(Ha,e))},nanoid(e){return this.check(Lv(nI,e))},cuid(e){return this.check(Uv(iI,e))},cuid2(e){return this.check(zv(oI,e))},ulid(e){return this.check(Fv(sI,e))},base64(e){return this.check(jv(pI,e))},base64url(e){return this.check(Gv(hI,e))},xid(e){return this.check(Mv(aI,e))},ksuid(e){return this.check(Vv(cI,e))},ipv4(e){return this.check(Wv(uI,e))},ipv6(e){return this.check(Hv(lI,e))},cidrv4(e){return this.check(Kv(fI,e))},cidrv6(e){return this.check(Zv(dI,e))},e164(e){return this.check(qv(mI,e))},datetime(e){return this.check(Jv(qk,e))},date(e){return this.check(Qv(Xk,e))},time(e){return this.check(Yv(Jk,e))},duration(e){return this.check(ex(Qk,e))}});function ge(e){return kv(Gk,e)}var Ge=N("ZodStringFormat",(e,t)=>{Ve.init(e,t),db.init(e,t)}),qk=N("ZodISODateTime",(e,t)=>{Ly.init(e,t),Ge.init(e,t)}),Xk=N("ZodISODate",(e,t)=>{Uy.init(e,t),Ge.init(e,t)}),Jk=N("ZodISOTime",(e,t)=>{zy.init(e,t),Ge.init(e,t)}),Qk=N("ZodISODuration",(e,t)=>{Fy.init(e,t),Ge.init(e,t)}),Yk=N("ZodEmail",(e,t)=>{Ty.init(e,t),Ge.init(e,t)});var eI=N("ZodGUID",(e,t)=>{Ey.init(e,t),Ge.init(e,t)});var Ha=N("ZodUUID",(e,t)=>{_y.init(e,t),Ge.init(e,t)});var tI=N("ZodURL",(e,t)=>{Iy.init(e,t),Ge.init(e,t)});var rI=N("ZodEmoji",(e,t)=>{Py.init(e,t),Ge.init(e,t)});var nI=N("ZodNanoID",(e,t)=>{Ry.init(e,t),Ge.init(e,t)});var iI=N("ZodCUID",(e,t)=>{By.init(e,t),Ge.init(e,t)});var oI=N("ZodCUID2",(e,t)=>{Ny.init(e,t),Ge.init(e,t)});var sI=N("ZodULID",(e,t)=>{Dy.init(e,t),Ge.init(e,t)});var aI=N("ZodXID",(e,t)=>{$y.init(e,t),Ge.init(e,t)});var cI=N("ZodKSUID",(e,t)=>{Oy.init(e,t),Ge.init(e,t)});var uI=N("ZodIPv4",(e,t)=>{My.init(e,t),Ge.init(e,t)});var lI=N("ZodIPv6",(e,t)=>{Wy.init(e,t),Ge.init(e,t)});var fI=N("ZodCIDRv4",(e,t)=>{Hy.init(e,t),Ge.init(e,t)});var dI=N("ZodCIDRv6",(e,t)=>{Ky.init(e,t),Ge.init(e,t)});var pI=N("ZodBase64",(e,t)=>{jy.init(e,t),Ge.init(e,t)});var hI=N("ZodBase64URL",(e,t)=>{Gy.init(e,t),Ge.init(e,t)});var mI=N("ZodE164",(e,t)=>{qy.init(e,t),Ge.init(e,t)});var gI=N("ZodJWT",(e,t)=>{Xy.init(e,t),Ge.init(e,t)});var pb=N("ZodNumber",(e,t)=>{Ml.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Tx(e,n,r,i),e.isFinite=!0},sg({minValue:(e)=>{let{minimum:t,exclusiveMinimum:n}=$t(e);return Math.max(t??Number.NEGATIVE_INFINITY,n??Number.NEGATIVE_INFINITY)},maxValue:(e)=>{let{maximum:t,exclusiveMaximum:n}=$t(e);return Math.min(t??Number.POSITIVE_INFINITY,n??Number.POSITIVE_INFINITY)},isInt:(e)=>{let{isInt:t,multipleOf:n}=$t(e);return!!t||!!n?.some(Number.isSafeInteger)},format:(e)=>$t(e).format??null},{gt(e,t){return this.check(Ua(e,t))},gte(e,t){return this.check(_o(e,t))},min(e,t){return this.check(_o(e,t))},lt(e,t){return this.check(La(e,t))},lte(e,t){return this.check(Eo(e,t))},max(e,t){return this.check(Eo(e,t))},int(e){return this.check(sb(e))},safe(e){return this.check(sb(e))},positive(e){return this.check(Ua(0,e))},nonnegative(e){return this.check(_o(0,e))},negative(e){return this.check(La(0,e))},nonpositive(e){return this.check(Eo(0,e))},multipleOf(e,t){return this.check(za(e,t))},step(e,t){return this.check(za(e,t))},finite(){return this}}));function zr(e){return tx(pb,e)}var yI=N("ZodNumberFormat",(e,t)=>{Jy.init(e,t),pb.init(e,t)});function sb(e){return rx(yI,e)}var vI=N("ZodBoolean",(e,t)=>{Qy.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Ax(e,n,r,i)});function Lt(e){return nx(vI,e)}var xI=N("ZodUnknown",(e,t)=>{Yy.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Ix(e,n,r,i)});function ab(){return ix(xI)}var bI=N("ZodNever",(e,t)=>{ev.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,r,i)=>kx(e,n,r,i)});function SI(e){return ox(bI,e)}var CI=N("ZodArray",(e,t)=>{Io(),tv.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Nx(e,n,r,i),e.element=t.element},{min(e,t){return this.check(vi(e,t))},nonempty(e){return this.check(vi(1,e))},max(e,t){return this.check(Fa(e,t))},length(e,t){return this.check(Ma(e,t))},unwrap(){return this.element}});function We(e,t){return sx(CI,e,t)}var wI=N("ZodObject",(e,t)=>{Io(),iv.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Dx(e,n,r,i),ek(e,"shape",(n)=>n._zod.def.shape,!1)},{keyof(){return Rn(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(Dt(this._zod.def,{catchall:e}))},passthrough(){return this.clone(Dt(this._zod.def,{catchall:ab()}))},loose(){return this.clone(Dt(this._zod.def,{catchall:ab()}))},strict(){return this.clone(Dt(this._zod.def,{catchall:SI()}))},strip(){return this.clone(Dt(this._zod.def,{catchall:void 0}))},extend(e){return ZA(this,e)},safeExtend(e){return jA(this,e)},merge(e){return GA(this,e)},pick(e){return HA(this,e)},omit(e){return KA(this,e)},partial(...e){return rg(mf,this,e[0])},exactPartial(...e){return rg(gb,this,e[0],"exactPartial")},required(...e){return qA(yb,this,e[0])}});function pt(e,t){let n={type:"object",shape:e??{},...Y(t)};return new wI(n)}var EI=N("ZodUnion",(e,t)=>{ov.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,r,i)=>$x(e,n,r,i),e.options=t.options});function _I(e,t){return new EI({type:"union",options:e,...Y(t)})}var TI=N("ZodIntersection",(e,t)=>{sv.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Ox(e,n,r,i)});function AI(e,t){return new TI({type:"intersection",left:e,right:t})}var kI=N("ZodTuple",(e,t)=>{Io(),av.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Lx(e,n,r,i)},{rest(e){return this.clone({...this._zod.def,rest:e})},partial(){let e=this._zod.def;if(e.checks?.length)throw Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...e,items:e.items.map((t)=>new mf({type:"optional",innerType:t}))})}});function II(e,t,n){let r=t instanceof Me,i=r?n:t;return new kI({type:"tuple",items:e,rest:r?t:null,...Y(i)})}var cb=N("ZodRecord",(e,t)=>{Io(),cv.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Ux(e,n,r,i),e.keyType=t.keyType,e.valueType=t.valueType});function hb(e,t,n){if(!t||!t._zod)return new cb({type:"record",keyType:ge(),valueType:e,...Y(t)});return new cb({type:"record",keyType:e,valueType:t,...Y(n)})}var hf=N("ZodEnum",(e,t)=>{uv.init(e,t),je.init(e,t),e._zod.processJSONSchema=(r,i,o)=>Px(e,r,i,o),e.enum=t.entries,e.options=[...e._zod.values];let n=new Set(Object.keys(t.entries));e.extract=(r,i)=>{let o={};for(let s of r)if(n.has(s))o[s]=t.entries[s];else throw Error(`Key ${s} not found in enum`);return new hf({...t,checks:[],...Y(i),entries:o})},e.exclude=(r,i)=>{let o={...t.entries};for(let s of r)if(n.has(s))delete o[s];else throw Error(`Key ${s} not found in enum`);return new hf({...t,checks:[],...Y(i),entries:o})}});function Rn(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map((r)=>[r,r])):e;return new hf({type:"enum",entries:n,...Y(t)})}var PI=N("ZodTransform",(e,t)=>{Io(),lv.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Bx(e,n,r,i),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new xo(e.constructor.name);n.addIssue=(o)=>{if(typeof o==="string")n.issues.push(In(o,n.value,t));else{let s=o;if(s.fatal)s.continue=!1;if(s.code??(s.code="custom"),!("input"in s))s.input=n.value;s.inst??(s.inst=e),n.issues.push(In(s))}};let i=t.transform(n.value,n);if(i instanceof Promise)return i.then((o)=>(n.value=o,n));return n.value=i,n}});function mb(e){return new PI({type:"transform",transform:e})}var mf=N("ZodOptional",(e,t)=>{Vl.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,r,i)=>pf(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function ub(e){return new mf({type:"optional",innerType:e})}var gb=N("ZodExactOptional",(e,t)=>{fv.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,r,i)=>pf(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function RI(e){return new gb({type:"optional",innerType:e})}var BI=N("ZodNullable",(e,t)=>{dv.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,r,i)=>zx(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function lb(e){return new BI({type:"nullable",innerType:e})}var NI=N("ZodDefault",(e,t)=>{pv.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Vx(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function DI(e,t){return new NI({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():bl(t)}})}var $I=N("ZodPrefault",(e,t)=>{hv.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Wx(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function OI(e,t){return new $I({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():bl(t)}})}var yb=N("ZodNonOptional",(e,t)=>{mv.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Fx(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function LI(e,t){return new yb({type:"nonoptional",innerType:e,...Y(t)})}var UI=N("ZodCatch",(e,t)=>{gv.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Hx(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function zI(e,t){return new UI({type:"catch",innerType:e,catchValue:typeof t==="function"?t:ag(t)})}var vb=N("ZodPipe",(e,t)=>{Wl.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Kx(e,n,r,i),e.in=t.in,e.out=t.out});function fb(e,t){return new vb({type:"pipe",in:e,out:t})}var FI=N("ZodPreprocess",(e,t)=>{vb.init(e,t),yv.init(e,t)}),MI=N("ZodReadonly",(e,t)=>{vv.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Zx(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function VI(e){return new MI({type:"readonly",innerType:e})}var xb=N("ZodCustom",(e,t)=>{xv.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Rx(e,n,r,i)});function WI(e,t){return ax(xb,e??(()=>!0),t)}function HI(e,t={}){return cx(xb,e,t)}function KI(e,t){return ux(e,t)}function ZI(e,t){return new FI({type:"pipe",in:mb(e),out:t})}var At={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};var bb;(function(e){})(bb||(bb={}));var He=1e4;function Eb(e){return ZI((t,n)=>{if(typeof t==="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).length>He)return n.addIssue({code:"custom",message:`At most ${He} entries`}),lg;return t},e)}function yf(e){if(jI(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 vf='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.',Za=ge().refine(yf,{message:vf});function _b(e){let t=e.indexOf(":");return!(t!==-1&&e.indexOf(":",t+1)!==-1)||e.startsWith("[")}var qI=ge().refine((e)=>_b(e)&&yf(so(e).hostPattern),{message:vf+' An optional ":port" suffix (1-65535) restricts the entry to that port.'}),XI=ge().refine((e)=>{if(!_b(e))return!1;let{hostPattern:t}=so(e);return t==="*"||yf(t)},{message:vf+' In deniedDomains a bare "*" (deny-all) is also accepted, and an optional ":port" suffix (1-65535) restricts the entry to that port.'}),Po=ge().min(1,"Path cannot be empty"),Cb=ge().min(1,"Path cannot be empty").refine((e)=>GI(e),{message:"Binary path must be absolute"}),JI=pt({socketPath:ge().min(1).describe("Unix socket path to the MITM proxy"),domains:We(Za).max(He).min(1).describe('Domains to route through the MITM proxy (e.g., ["api.example.com", "*.internal.org"])')}),QI=pt({http:ge().url().optional().describe("Upstream proxy URL for plain HTTP traffic"),https:ge().url().optional().describe("Upstream proxy URL for HTTPS/CONNECT traffic (falls back to http if unset)"),noProxy:ge().optional().describe("Comma-separated NO_PROXY list (hostname suffixes and CIDR ranges). Matching destinations connect directly instead of via the parent proxy.")}),Tb=Rn(["deny","mask"]),Ka=ge().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"),Ab=ge().superRefine((e,t)=>{try{let{groupCount:n}=_u(e);if(n<1)t.addIssue({code:At.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:At.custom,message:n instanceof Error?n.message:"Credential extract pattern is invalid"})}}),YI=pt({path:Po.describe("Path to a credential file or directory. Supports the same path forms as filesystem.denyRead (absolute paths and ~ expansion)."),mode:Tb.describe("Access mode for this path"),extract:Ab.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:Rn(["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:Rn(["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:We(ge().min(1)).max(He).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:Lt().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:We(Za).max(He).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".')}),e2=pt({name:Ka.describe("Environment variable name"),mode:Tb.describe("Access mode for this environment variable"),extract:Ab.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:Rn(["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:Rn(["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:We(ge().min(1)).max(He).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:We(Za).max(He).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:We(ge().regex(/^[a-z0-9-]{1,64}$/)).max(He).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".')}),t2=pt({accessKeyIdVar:Ka.describe("Name of the masked env var holding the AWS access key id."),secretAccessKeyVar:Ka.describe("Name of the masked env var holding the AWS secret access key."),sessionTokenVar:Ka.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(),gf=Rn(["deny","passthrough"]),r2=pt({streaming:gf.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:gf.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:gf.optional().describe('Policy for SigV4A (AWS4-ECDSA-P256-SHA256) asymmetric signatures: there is no shared-key HMAC to recompute. Default "deny".')}).strict(),kb=pt({files:We(YI).max(He).optional().describe("Credential files or directories to protect"),envVars:We(e2).max(He).optional().describe("Environment variables to protect"),allowPlaintextInject:Lt().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:We(t2).max(He).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:r2.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(),wb=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/,n2=/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?$/,i2=pt({url:ge().url().refine((e)=>new URL(e).protocol==="https:",{message:"brokerForward.url must be https"}),tokenEnvVar:ge().regex(wb),rules:We(pt({envVar:ge().regex(wb),hosts:We(ge().regex(n2)).min(1).max(16)}).strict()).max(He).min(1).max(32)}).strict(),Ib=pt({allowedDomains:We(qI).max(He).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:We(XI).max(He).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:Eb(hb(ge(),ge().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.'),allowAllDomains:Lt().optional().describe("ARA PATCH (open egress): if true, a host no allowedDomains entry matches is allowed too, after deniedDomains, unless it names or resolves to a loopback, private, link-local or otherwise non-public address. Such a host is always tunnelled (never TLS-terminated), so credential injection stays scoped to allowedDomains."),refuseLocalDestinations:Lt().optional().describe("ARA PATCH (local destinations): if true, a name that allowedDomains (or the ask callback) admits is resolved once and dialled at that address, and refused when it resolves to loopback, a link-local address (169.254.0.0/16 with cloud metadata, fe80::/10) or one of this machine's own interface addresses. Other private addresses stay reachable. An IP literal or localhost entry is dialled as given. Not applied to connections that leave through a parent proxy or the external MITM socket."),strictAllowlist:Lt().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:We(ge()).max(He).optional().describe("macOS only: Unix socket paths to allow. Ignored on Linux (seccomp cannot filter by path)."),allowAllUnixSockets:Lt().optional().describe("If true, allow all Unix sockets (disables blocking on both platforms)."),allowLocalBinding:Lt().optional().describe("Whether to allow binding to local ports (default: false)"),allowMachLookup:We(ge().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).'})).max(He).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:zr().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:zr().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:JI.optional().describe("Optional MITM proxy configuration. Routes matching domains through an upstream proxy via Unix socket while SRT still handles allow/deny filtering."),filterRequest:WI((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:pt({caCertPath:ge().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:ge().min(1).optional().describe("Path to the PEM-encoded private key for caCertPath."),excludeDomains:We(Za).max(He).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:We(ge().min(1)).max(He).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:QI.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:i2.optional().describe("Credential placeholders a remote broker swaps (see broker-forward.ts).")}),Pb=pt({disabled:Lt().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:We(Po).max(He).describe("Paths denied for reading"),allowRead:We(Po).max(He).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:We(Po).max(He).describe("Paths allowed for writing"),denyWrite:We(Po).max(He).describe("Paths denied for writing (takes precedence over allowWrite)"),allowGitConfig:Lt().optional().describe("Allow writes to .git/config files (default: false). Enables git remote URL updates while keeping .git/hooks protected.")}),Rb=Eb(hb(ge(),We(ge()).max(He))).describe('Map of command patterns to filesystem paths to ignore violations for. Use "*" to match all commands'),Bb=pt({command:ge().describe("The ripgrep command to execute"),args:We(ge()).max(He).optional().describe("Additional arguments to pass before ripgrep args"),argv0:ge().optional().describe("Override argv[0] when spawning (for multicall binaries that dispatch on argv[0])")}),Nb=pt({safeDirectories:We(ge()).max(He).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.")}),Db=pt({path:ge().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.")}),$b=pt({sandboxUser:ge().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:ge().guid().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:ge().guid().optional().describe("Deprecated alias for sublayerGuid."),proxyPortRange:II([zr().int().min(1),zr().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:Db.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.")}),o2=pt({applyPath:ge().optional().describe("Path to the apply-seccomp binary"),argv0:ge().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.")}),s2=pt({network:Ib.describe("Network restrictions configuration"),filesystem:Pb.describe("Filesystem restrictions configuration"),credentials:kb.optional().describe("Credential handling configuration. Only the explicitly declared files and environment variables are restricted."),ignoreViolations:Rb.optional().describe("Optional configuration for ignoring specific violations"),enableWeakerNestedSandbox:Lt().optional().describe("Enable weaker nested sandbox mode (for Docker environments)"),runAsUid:zr().int().nonnegative().optional().describe("ARA: uid to drop the sandboxed command to (bwrap --uid)"),runAsGid:zr().int().nonnegative().optional().describe("ARA: gid to drop the sandboxed command to (bwrap --gid)"),runAsHostUid:zr().int().positive().optional().describe("ARA: real host uid used to launch the sandboxed bwrap child"),runAsHostGid:zr().int().positive().optional().describe("ARA: real host gid used to launch the sandboxed bwrap child"),runAsHostHome:ge().min(1).optional().describe("ARA: HOME set inside a real-host-uid sandbox child"),runAsHostUser:ge().min(1).optional().describe("ARA: USER and LOGNAME set inside a real-host-uid sandbox child"),enableWeakerNetworkIsolation:Lt().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:Lt().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:Bb.optional().describe('Custom ripgrep configuration (default: { command: "rg" })'),mandatoryDenySearchDepth:zr().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:Lt().optional().describe("Allow pseudo-terminal (pty) operations (macOS only)"),seccomp:o2.optional().describe("Custom seccomp binary paths (Linux only)."),bwrapPath:Cb.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:Cb.optional().describe('Linux only: absolute path to the socat binary. When set, this path is used directly instead of resolving "socat" via PATH.'),windows:$b.optional().describe("Windows-specific settings (WFP sublayer, proxy port range)."),git:Nb.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(ao),i=(c,u)=>{for(let[l,f]of c.entries())if(!ca(f,r))t.addIssue({code:At.custom,path:[...u,l],message:`injectHosts entry "${f}" is not reachable via `+`network.allowedDomains \u2014 add "${f}" (or a covering wildcard) to allowedDomains, or remove it from injectHosts.`})},o=!1,s=(c,u)=>{if(c.injectHosts)i(c.injectHosts,[...u,"injectHosts"]);if(c.mode!=="mask")return;o=!0;let l=e.network.tlsTerminate?.excludeDomains;if(l?.length){if(c.injectHosts){for(let[f,p]of c.injectHosts.entries())if(ca(p,l))t.addIssue({code:At.custom,path:[...u,"injectHosts",f],message:`injectHosts entry "${p}" 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((f)=>ca(f,l)))t.addIssue({code:At.custom,path:u,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(c.injectHosts!==void 0&&c.injectHosts.length===0)t.addIssue({code:At.custom,path:u,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[c,u]of(n.envVars??[]).entries()){if(s(u,["credentials","envVars",c]),u.maskClaims!==void 0&&u.decode===void 0)t.addIssue({code:At.custom,path:["credentials","envVars",c,"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(u.maskClaims!==void 0&&u.maskClaims.length===0)t.addIssue({code:At.custom,path:["credentials","envVars",c,"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[c,u]of(n.files??[]).entries()){if(s(u,["credentials","files",c]),u.maskClaims!==void 0&&u.decode===void 0)t.addIssue({code:At.custom,path:["credentials","files",c,"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(u.maskClaims!==void 0&&u.maskClaims.length===0)t.addIssue({code:At.custom,path:["credentials","files",c,"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(u.mode==="mask"&&u.path.endsWith("/"))t.addIssue({code:At.custom,path:["credentials","files",c,"path"],message:`Credential mode "mask" applies to a single file, not a directory. Use mode "deny" for "${u.path}", or point at the credential file inside it.`})}let a=new Set;for(let[c,u]of(n.awsPairs??[]).entries()){let l=[["accessKeyIdVar",u.accessKeyIdVar],["secretAccessKeyVar",u.secretAccessKeyVar]];if(u.sessionTokenVar!==void 0)l.push(["sessionTokenVar",u.sessionTokenVar]);for(let[f,p]of l){let h=["credentials","awsPairs",c,f];if(a.has(p)){t.addIssue({code:At.custom,path:h,message:`"${p}" appears in more than one awsPairs slot (within `+"or across pairs) \u2014 each variable can fill exactly one slot."});continue}a.add(p);let d=(n.envVars??[]).find((g)=>g.name===p);if(d===void 0||d.mode!=="mask")t.addIssue({code:At.custom,path:h,message:`"${p}" 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(d.extract!==void 0||d.decode!==void 0)t.addIssue({code:At.custom,path:h,message:`"${p}" 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(o&&e.network.tlsTerminate===void 0&&!n.allowPlaintextInject)t.addIssue({code:At.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{kb as CredentialsConfigSchema,ta as DEFAULT_WINDOWS_PROXY_PORT_RANGE,Pb as FilesystemConfigSchema,Nb as GitConfigSchema,Rb as IgnoreViolationsConfigSchema,Ib as NetworkConfigSchema,Bb as RipgrepConfigSchema,Y0 as SRT_WIN_DISPATCH_ARG1,VA as SandboxManager,s2 as SandboxRuntimeConfigSchema,Ys as SandboxViolationStore,Db as SrtWinConfigSchema,VT as VENDORED_SRT_WIN_EXE,$b as WindowsConfigSchema,me as WindowsSandboxError,Ti as buildGitConfigEnv,Qn as certThumbprint,ol as checkWindowsDependenciesAsync,nm as checkWindowsSandboxStatus,im as checkWindowsSandboxStatusAsync,tl as ensurePersistentWindowsCa,oa as expandWindowsFsPaths,Cs as generateCa,Bn as getDefaultWritePaths,WT as getSrtWinPath,el as getWindowsSandboxCaCert,Yu as getWindowsSandboxUserStatus,oo as getWindowsSandboxUserStatusAsync,om as getWindowsWfpStatus,sm as getWindowsWfpStatusAsync,Ga as getWslVersion,il as grantWindowsAcl,ZT as installWindowsSandbox,jT as installWindowsSandboxAsync,_i as isUncPath,ra as parseWindowsBinShell,qT as parseWindowsSandboxError,Nt as resolveSrtWin,sa as restoreWindowsAcl,aa as revokeWindowsAcl,nl as stampWindowsAcl,GT as uninstallWindowsSandbox,Hi as validateCaPair,Qu as verifyWindowsWfpEgress,qu as windowsInstallInstructions,um as windowsStateDir,KT as windowsTrustCa,am as windowsTrustCaAsync};
152
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let s of e.seen.entries()){let a=s[1];if(t===s[0]){o(s);continue}if(e.external){let u=e.external.registry.get(s[0])?.id;if(t!==s[0]&&u){o(s);continue}}if(e.metadataRegistry.get(s[0])?.id){o(s);continue}if(a.cycle){o(s);continue}if(a.count>1){if(e.reused==="ref")o(s)}}if(e.external)e.sharedDefsExtractedFor=e.external}function hx(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let n=[];for(let r of t){if(!r||typeof r!=="object")return;hx(r);let i=Object.keys(r);if(i.length!==1||i[0]!=="type")return;let o=r.type;for(let s of Array.isArray(o)?o:[o]){if(typeof s!=="string")return;if(!n.includes(s))n.push(s)}}delete e.anyOf,e.type=n.length===1?n[0]:n}var mx=new Set(["type","properties","required","additionalProperties"]),dx=["oneOf","anyOf"];function px(e){let t=e.additionalProperties;if(t===void 0||t===!1||typeof t!=="object"||t===null)return null;return Object.keys(t).length?t:null}function af(e){let t=[];for(let o of e){if(typeof o!=="object"||o.type!=="object")return null;for(let s in o)if(!mx.has(s))return null;t.push(o)}let n={},r=new Set;for(let o of t){for(let s in o.properties){if(Object.prototype.hasOwnProperty.call(n,s))continue;let a=[];for(let u of t){let l=u.properties?.[s]??px(u);if(l===null||l===void 0)continue;if(!a.some((f)=>JSON.stringify(f)===JSON.stringify(l)))a.push(l)}let c=a.length===1?a[0]:af(a)??{allOf:a};sr(n,s,c)}for(let s of o.required??[])r.add(s)}let i={type:"object",properties:n};if(r.size)i.required=[...r];if(t.every((o)=>o.additionalProperties===!1))i.additionalProperties=!1;else{let o=[];for(let s of t){let a=px(s);if(a&&!o.some((c)=>JSON.stringify(c)===JSON.stringify(a)))o.push(a)}if(o.length===1)i.additionalProperties=o[0];else if(o.length>1)i.additionalProperties={allOf:o}}return i}function Nk(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let i of mx)if(i in e)return;let n=t.filter((i)=>dx.some((o)=>Array.isArray(i[o]))),r=null;if(!n.length)r=af(t);else{let i=n[0],o=dx.find((c)=>Array.isArray(i[c]));if(Object.keys(i).length!==1)return;let s=t.filter((c)=>c!==i),a=i[o].map((c)=>af([...s,c]));if(a.some((c)=>!c))return;r={[o]:a}}if(!r)return;delete e.allOf,To(e,r)}function lf(e,t){let n=e.seen.get(t);if(!n)throw Error("Unprocessed schema. This is a bug in Zod.");let r=(a)=>{let c=e.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,l={...u},f=c.ref;if(c.ref=null,f){r(f);let h=e.seen.get(f),d=h.schema;if(d.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"))u.allOf=u.allOf??[],u.allOf.push(d);else To(u,d);if(To(u,l),a._zod.parent===f)for(let v in u){if(v==="$ref"||v==="allOf")continue;if(!(v in l))delete u[v]}if(d.$ref&&h.def)for(let v in u){if(v==="$ref"||v==="allOf")continue;if(v in h.def&&JSON.stringify(u[v])===JSON.stringify(h.def[v]))delete u[v]}}let p=a._zod.parent;if(p&&p!==f){r(p);let h=e.seen.get(p);if(h?.schema.$ref){if(u.$ref=h.schema.$ref,h.def)for(let d in u){if(d==="$ref"||d==="allOf")continue;if(d in h.def&&JSON.stringify(u[d])===JSON.stringify(h.def[d]))delete u[d]}}}e.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let a of[...e.seen.entries()].reverse())r(a[0]);if(e.target!=="openapi-3.0")for(let a of e.seen.entries())hx(a[1].def??a[1].schema);for(let a of e.deferred)a();if(e.intersections.length){let a=new Map;for(let c of e.seen.values())for(let u of[c.schema,c.def]){let l=u?.allOf;if(!Array.isArray(l))continue;let f=a.get(l);if(f)f.push(u);else a.set(l,[u])}for(let c of e.intersections)for(let u of a.get(c)??[])Nk(u)}}let i={};if(e.target==="draft-2020-12")i.$schema="https://json-schema.org/draft/2020-12/schema";else if(e.target==="draft-07")i.$schema="http://json-schema.org/draft-07/schema#";else if(e.target==="draft-04")i.$schema="http://json-schema.org/draft-04/schema#";else if(e.target==="openapi-3.0");if(e.external?.uri){let a=e.external.registry.get(t)?.id;if(!a)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(a)}To(i,n.defId?n.schema:n.def??n.schema);let o=e.metadataRegistry.get(t)?.id;if(o!==void 0&&i.id===o)delete i.id;let s=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let a of e.seen.entries()){let c=a[1];if(c.def&&c.defId){if(c.def.id===c.defId)delete c.def.id;sr(s,c.defId,c.def)}}if(e.external)e.sharedEmitDoneFor=e.external;if(e.external);else if(Object.keys(s).length>0)if(e.target==="draft-2020-12")i.$defs=s;else i.definitions=s;try{let a=JSON.parse(JSON.stringify(i));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:Ao(t,"input",e.processors),output:Ao(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch(a){throw Error("Error converting schema to JSON.")}}function At(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return At(r.element,n);if(r.type==="set")return At(r.valueType,n);if(r.type==="lazy")return At(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault"||r.type==="catch")return At(r.innerType,n);if(r.type==="intersection")return At(r.left,n)||At(r.right,n);if(r.type==="record"||r.type==="map")return At(r.keyType,n)||At(r.valueType,n);if(r.type==="pipe"){if(e._zod.traits.has("$ZodCodec"))return!0;return At(r.in,n)||At(r.out,n)}if(r.type==="object"){for(let i in r.shape)if(At(r.shape[i],n))return!0;return!1}if(r.type==="union"){for(let i of r.options)if(At(i,n))return!0;return!1}if(r.type==="tuple"){for(let i of r.items)if(At(i,n))return!0;if(r.rest&&At(r.rest,n))return!0;return!1}return!1}var gx=(e,t={})=>(n)=>{let r=cf({...n,processors:t});return Ze(e,r),uf(r,e),lf(r,e)},Ao=(e,t,n={})=>(r)=>{let{libraryOptions:i,target:o}=r??{},s=cf({...i??{},target:o,io:t,processors:n});return Ze(e,s),uf(s,e),lf(s,e)};var Si=(e,t,n)=>{if(e[t]===void 0||n>e[t])e[t]=n},Ci=(e,t,n)=>{if(e[t]===void 0||n<e[t])e[t]=n},yx=(e,t)=>{Si(e,"minimum",t),Ci(e,"maximum",t)},Sx=(e,t)=>{if(e.multipleOf??(e.multipleOf=[]),!e.multipleOf.includes(t))e.multipleOf.push(t)},Cx=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},wx=(e,t)=>{e.mime=e.mime?e.mime.filter((n)=>t.includes(n)):[...t]},Ex=(e,t)=>{if(e.format=t,t.includes("int"))e.isInt=!0},vx=(e,t)=>Si(e,"minimum",t.minimum),xx=(e,t)=>Ci(e,"maximum",t.maximum),bx=(e)=>(t,n)=>{Ex(t,n.format);let[r,i]=e[n.format];Si(t,"minimum",r),Ci(t,"maximum",i)},Dk={greater_than:(e,t)=>Si(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>Ci(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>Sx(e,t.value),number_format:bx(ga),bigint_format:bx(wl),min_length:vx,max_length:xx,length_equals:(e,t)=>yx(e,t.length),min_size:vx,max_size:xx,size_equals:(e,t)=>yx(e,t.size),string_format:(e,t)=>{if(Ex(e,t.format),t.pattern)Cx(e,t.pattern);if(t.format==="base64"||t.format==="base64url")e.contentEncoding=t.format;if(t.local||t.precision===-1)e.laxFormat=!0},mime_type:(e,t)=>wx(e,t.mime)};function $t(e){let t={},n=e._zod.def,r=e._zod.traits.has("$ZodCheck")?[e,...n.checks??[]]:n.checks??[];for(let o of r)Dk[o._zod.def.check]?.(t,o._zod.def);let i=e._zod.bag;if(i.minimum!==void 0)Si(t,"minimum",i.minimum);if(i.exclusiveMinimum!==void 0)Si(t,"exclusiveMinimum",i.exclusiveMinimum);if(i.maximum!==void 0)Ci(t,"maximum",i.maximum);if(i.exclusiveMaximum!==void 0)Ci(t,"exclusiveMaximum",i.exclusiveMaximum);if(i.multipleOf!==void 0)Sx(t,i.multipleOf);if(i.format!==void 0){if(t.format??(t.format=i.format),i.format.includes("int"))t.isInt=!0}if(i.mime)wx(t,i.mime);for(let o of i.patterns??[])Cx(t,o);return t}var $k={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Ok=new Map([[Ml,zg],[Ba,Fg]]),_x=(e)=>Ok.get(e)??e,Tx=(e,t,n,r)=>{let i=n;i.type="string";let{minimum:o,maximum:s,format:a,patterns:c,contentEncoding:u,laxFormat:l}=$t(e);if(typeof o==="number")i.minLength=o;if(typeof s==="number")i.maxLength=s;if(a){if(i.format=$k[a]??a,i.format==="")delete i.format;if(a==="time"||l)delete i.format}if(u)i.contentEncoding=u;if(c&&c.size>0){let f=[...c].map(_x);if(f.length===1)i.pattern=f[0].source;else if(f.length>1)i.allOf=[...f.map((p)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:p.source}))]}},Ax=(e,t,n,r)=>{let i=n,{minimum:o,maximum:s,multipleOf:a,exclusiveMaximum:c,exclusiveMinimum:u,isInt:l}=$t(e);i.type=l?"integer":"number";let f=typeof u==="number"&&u>=(o??Number.NEGATIVE_INFINITY),p=typeof c==="number"&&c<=(s??Number.POSITIVE_INFINITY),h=t.target==="draft-04"||t.target==="openapi-3.0";if(f)if(h)i.minimum=u,i.exclusiveMinimum=!0;else i.exclusiveMinimum=u;else if(typeof o==="number")i.minimum=o;if(p)if(h)i.maximum=c,i.exclusiveMaximum=!0;else i.exclusiveMaximum=c;else if(typeof s==="number")i.maximum=s;if(a){let d=new Set;for(let b of a)if(Number.isFinite(b)&&b!==0)d.add(Math.abs(b));else Rn(e,t,i,r,`A multipleOf divisor of ${b} cannot be represented in JSON Schema`);let[g,...v]=d;if(g!==void 0)i.multipleOf=g;if(v.length)i.allOf=[...i.allOf??[],...v.map((b)=>({multipleOf:b}))]}},kx=(e,t,n,r)=>{n.type="boolean"};var Ix=(e,t,n,r)=>{n.not={}};var Px=(e,t,n,r)=>{};var Rx=(e,t,n,r)=>{let i=e._zod.def,o=yo(i.entries);if(o.length===0){n.not={};return}if(o.every((s)=>typeof s==="number"))n.type="number";if(o.every((s)=>typeof s==="string"))n.type="string";n.enum=o};var Bx=(e,t,n,r)=>{Rn(e,t,n,r,"Custom types cannot be represented in JSON Schema")};var Nx=(e,t,n,r)=>{Rn(e,t,n,r,"Transforms cannot be represented in JSON Schema")};var Dx=(e,t,n,r)=>{let i=n,o=e._zod.def,{minimum:s,maximum:a}=$t(e);if(typeof s==="number")i.minItems=s;if(typeof a==="number")i.maxItems=a;i.type="array",i.items=Ze(o.element,t,{...r,path:[...r.path,"items"]})};function ko(e){let t=e._zod.def;if(t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform"))return ko(t.out);if(t.type==="catch")return ko(t.innerType);return e._zod.optin}var $x=(e,t,n,r)=>{let i=n,o=e._zod.def,s=o.shape;if(Object.getOwnPropertySymbols(s).length&&Rn(e,t,i,r,"Symbol keys cannot be represented in JSON Schema"))return;i.type="object",i.properties={};for(let u in s)sr(i.properties,u,Ze(s[u],t,{...r,path:[...r.path,"properties",u]}));let c=[];for(let u of Object.keys(s)){let l=o.shape[u];if(t.io==="input"?ko(l)===void 0:l._zod.optout===void 0)c.push(u)}if(c.length>0)i.required=c;if(o.catchall?._zod.def.type==="never")i.additionalProperties=!1;else if(!o.catchall){if(t.io==="output")i.additionalProperties=!1}else if(o.catchall)i.additionalProperties=Ze(o.catchall,t,{...r,path:[...r.path,"additionalProperties"]})},Ox=(e,t,n,r)=>{let i=e._zod.def,o=i.inclusive===!1,s=i.options.map((a,c)=>Ze(a,t,{...r,path:[...r.path,o?"oneOf":"anyOf",c]}));if(o)n.oneOf=s;else n.anyOf=s},Lx=(e,t,n,r)=>{let i=e._zod.def,o=Ze(i.left,t,{...r,path:[...r.path,"allOf",0]}),s=Ze(i.right,t,{...r,path:[...r.path,"allOf",1]}),a=(u)=>("allOf"in u)&&Object.keys(u).length===1,c=[...a(o)?o.allOf:[o],...a(s)?s.allOf:[s]];n.allOf=c,t.intersections.push(c)},Ux=(e,t,n,r)=>{let i=n,o=e._zod.def;i.type="array";let s=t.target==="draft-2020-12"?"prefixItems":"items",a=t.target==="draft-2020-12"?"items":t.target==="openapi-3.0"?"items":"additionalItems",c=o.items.map((g,v)=>Ze(g,t,{...r,path:[...r.path,s,v]})),u=o.rest?Ze(o.rest,t,{...r,path:[...r.path,a,...t.target==="openapi-3.0"?[o.items.length]:[]]}):null,l=o.items.length;while(l>0){let g=o.items[l-1];if(!(t.io==="input"?ko(g)!==void 0:g._zod.optout==="optional"))break;l--}let f=o.items.length,p=!o.rest;if(t.target==="draft-2020-12"){if(i.prefixItems=c,p)i.items=!1;else if(u)i.items=u;if(l>0)i.minItems=l;if(p)i.maxItems=f}else if(t.target==="openapi-3.0"){if(i.items={anyOf:c},u)i.items.anyOf.push(u);if(l>0)i.minItems=l;if(p)i.maxItems=f}else{if(i.items=c,p)i.additionalItems=!1;else if(u)i.additionalItems=u;if(l>0)i.minItems=l;if(p)i.maxItems=f}let{minimum:h,maximum:d}=$t(e);if(typeof h==="number")i.minItems=h;if(typeof d==="number")i.maxItems=d};function ff(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);let d=e.get(t)?.def;if(!d)return t;let g=ff(e,d,n);return g===d?t:g}for(let d of["anyOf","oneOf"]){let g=t[d];if(!Array.isArray(g))continue;let v=g.map((b)=>ff(e,b,n));if(v.some((b,S)=>b!==g[S]))t={...t,[d]:v}}let r=Array.isArray(t.type)?t.type:[t.type],i=!r.includes("string")&&r.some((d)=>d==="number"||d==="integer"),o=t.enum??(t.const!==void 0?[t.const]:void 0);if(!i&&!o?.some((d)=>typeof d==="number"))return t;let{minimum:s,maximum:a,exclusiveMinimum:c,exclusiveMaximum:u,multipleOf:l,format:f,id:p,...h}=t;if(h.enum)h.enum=h.enum.map((d)=>typeof d==="number"?String(d):d);else if(typeof h.const==="number")h.const=String(h.const);if(!i)return h;if(h.type="string",!o)h.pattern=(r.includes("number")?bo:Dl).source;return h}var df=new WeakMap;function Lk(e){let t=new Map;for(let r of e.seen.values())if(r.def&&!t.has(r.schema))t.set(r.schema,r);let n=new Map;for(let r of df.get(e)??[]){let i=e.seen.get(r),o=(i?.def??i?.schema)?.propertyNames;if(!o||o===!0||n.has(o))continue;let s=ff(t,o,new Set);if(s!==o)n.set(o,s)}if(!n.size)return;for(let r of e.seen.values())for(let i of[r.schema,r.def]){let o=i&&n.get(i.propertyNames);if(o)i.propertyNames=o}}var zx=(e,t,n,r)=>{let i=n,o=e._zod.def;i.type="object";let s=o.keyType,a=$t(s).patterns;if(o.mode==="loose"&&a&&a.size>0){let l=Ze(o.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});i.patternProperties={};for(let f of a)sr(i.patternProperties,_x(f).source,l)}else{if(t.target==="draft-07"||t.target==="draft-2020-12"){i.propertyNames=Ze(o.keyType,t,{...r,path:[...r.path,"propertyNames"]});let l=df.get(t);if(!l)l=[],df.set(t,l),t.deferred.push(()=>Lk(t));l.push(e)}i.additionalProperties=Ze(o.valueType,t,{...r,path:[...r.path,"additionalProperties"]})}let c=s._zod.values,u=t.io==="input"&&ko(o.valueType)!==void 0;if(c&&!o.partial&&!u){let l=[...c].filter((f)=>typeof f==="string"||typeof f==="number");if(l.length>0)i.required=l.map(String)}},Fx=(e,t,n,r)=>{let i=e._zod.def,o=Ze(i.innerType,t,r),s=t.seen.get(e);if(t.target==="openapi-3.0")s.ref=i.innerType,n.nullable=!0;else n.anyOf=[o,{type:"null"}]},Mx=(e,t,n,r)=>{let i=e._zod.def;Ze(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType},pf=Symbol();function Vx(e,t,n,r,i){let o=!1,s=JSON.stringify(e,(a,c)=>{if(typeof c!=="bigint")return c;return o=!0,null});if(!o)return JSON.parse(s);return Rn(t,n,r,i,"BigInt defaults cannot be represented in JSON Schema"),pf}var Wx=(e,t,n,r)=>{let i=e._zod.def;Ze(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType;let s=Vx(i.defaultValue,e,t,n,r);if(s!==pf)n.default=s},Hx=(e,t,n,r)=>{let i=e._zod.def;Ze(i.innerType,t,r);let o=t.seen.get(e);if(o.ref=i.innerType,t.io!=="input")return;let s=Vx(i.defaultValue,e,t,n,r);if(s!==pf)n._prefault=s},Kx=(e,t,n,r)=>{let i=e._zod.def;Ze(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType;let s;try{s=i.catchValue(void 0)}catch{Rn(e,t,n,r,"Dynamic catch values are not supported in JSON Schema");return}n.default=s},Zx=(e,t,n,r)=>{let i=e._zod.def,o=i.in._zod.traits.has("$ZodTransform"),s=t.io==="input"?o?i.out:i.in:i.out;Ze(s,t,r);let a=t.seen.get(e);a.ref=s},jx=(e,t,n,r)=>{let i=e._zod.def;Ze(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType,n.readOnly=!0};var hf=(e,t,n,r)=>{let i=e._zod.def;Ze(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType};var Gx=new WeakSet([Object.prototype,Error.prototype]);function Wa(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let r=n(this);return Object.defineProperty(this,t,{value:r,configurable:!0,writable:!0}),r},set(r){Object.defineProperty(this,t,{value:r,configurable:!0,writable:!0})}})}var Zk=(e,t)=>{hg.init(e,t),e.name="ZodError";let n=Object.getPrototypeOf(e);if(Gx.has(n))return;Gx.add(n),Wa(n,"format",(r)=>(i)=>Il(r,i)),Wa(n,"flatten",(r)=>(i)=>kl(r,i)),Wa(n,"addIssue",(r)=>(i)=>{r.issues.push(i),r.message=JSON.stringify(r.issues,vo,2)}),Wa(n,"addIssues",(r)=>(i)=>{r.issues.push(...i),r.message=JSON.stringify(r.issues,vo,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}})};var Ot=N("ZodError",Zk,void 0,{Parent:Error});var qx=wa(Ot),Xx=Ea(Ot),Jx=_a(Ot),Qx=Ta(Ot),Yx=gg(Ot),eb=yg(Ot),tb=vg(Ot),rb=xg(Ot),nb=bg(Ot),ib=Sg(Ot),ob=Cg(Ot),sb=wg(Ot);function Gk(){if(!Tt.localeError)Pt(Gl())}function Io(){if(!Tt.memoizer)Pt({memoizer:jl()})}var je=N("ZodType",(e,t)=>(Gk(),We.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(Dt(t,{checks:[...t.checks??[],...e.map((n)=>typeof n==="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return ar(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(KI(e,t))},superRefine(e,t){return this.check(ZI(e,t))},overwrite(e){return this.check(sn(e))},optional(){return lb(this)},exactOptional(){return BI(this)},nullable(){return fb(this)},nullish(){return lb(fb(this))},nonoptional(e){return UI(this,e)},array(){return ze(this)},or(e){return TI([this,e])},and(e){return kI(this,e)},transform(e){return db(this,gb(e))},default(e){return $I(this,e)},prefault(e){return LI(this,e)},catch(e){return FI(this,e)},pipe(e){return db(this,e)},readonly(){return WI(this)},describe(e){let t=this.clone();return on.add(t,{description:e}),t},meta(...e){if(e.length===0)return on.get(this);let t=this.clone();return on.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get "~standard"(){return Sa(this,"~standard",{...Fl(this),jsonSchema:{input:Ao(this,"input"),output:Ao(this,"output")}})},set "~standard"(e){Ur(this,"~standard",e)},parse:function e(t,n){return qx(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await Xx(this,t,n,{callee:e})},safeParse(e,t){return Jx(this,e,t)},async safeParseAsync(e,t){return Qx(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){Ur(this,"spa",e)},validate(e,t){return Pl(this,e,t)},validateAsync(e,t){return Rl(this,e,t)},encode:function e(t,n){return Yx(this,t,n,{callee:e})},decode:function e(t,n){return eb(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await tb(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await rb(this,t,n,{callee:e})},safeEncode(e,t){return nb(this,e,t)},safeDecode(e,t){return ib(this,e,t)},async safeEncodeAsync(e,t){return ob(this,e,t)},async safeDecodeAsync(e,t){return sb(this,e,t)},toJSONSchema(e){return gx(this,{})(e)},get description(){return on.get(this)?.description},get _def(){return this._zod.def}}),pb=N("_ZodString",(e,t)=>{Ra.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Tx(e,n,r,i)},ag({format:(e)=>$t(e).format??null,minLength:(e)=>$t(e).minimum??null,maxLength:(e)=>$t(e).maximum??null},{regex(...e){return this.check(ql(...e))},includes(...e){return this.check(Ql(...e))},startsWith(...e){return this.check(Yl(...e))},endsWith(...e){return this.check(ef(...e))},min(...e){return this.check(bi(...e))},max(...e){return this.check(Fa(...e))},length(...e){return this.check(Ma(...e))},nonempty(...e){return this.check(bi(1,...e))},lowercase(e){return this.check(Xl(e))},uppercase(e){return this.check(Jl(e))},trim(){return this.check(rf())},normalize(...e){return this.check(tf(...e))},toLowerCase(){return this.check(nf())},toUpperCase(){return this.check(of())},slugify(){return this.check(sf())}})),qk=N("ZodString",(e,t)=>{Ra.init(e,t),pb.init(e,t)},{email(e){return this.check(Pv(eI,e))},url(e){return this.check(Ov(rI,e))},jwt(e){return this.check(Jv(yI,e))},emoji(e){return this.check(Lv(nI,e))},guid(e){return this.check(Rv(tI,e))},uuid(e){return this.check(Bv(Ha,e))},uuidv4(e){return this.check(Nv(Ha,e))},uuidv6(e){return this.check(Dv(Ha,e))},uuidv7(e){return this.check($v(Ha,e))},nanoid(e){return this.check(Uv(iI,e))},cuid(e){return this.check(zv(oI,e))},cuid2(e){return this.check(Fv(sI,e))},ulid(e){return this.check(Mv(aI,e))},base64(e){return this.check(Gv(hI,e))},base64url(e){return this.check(qv(mI,e))},xid(e){return this.check(Vv(cI,e))},ksuid(e){return this.check(Wv(uI,e))},ipv4(e){return this.check(Hv(lI,e))},ipv6(e){return this.check(Kv(fI,e))},cidrv4(e){return this.check(Zv(dI,e))},cidrv6(e){return this.check(jv(pI,e))},e164(e){return this.check(Xv(gI,e))},datetime(e){return this.check(Qv(Xk,e))},date(e){return this.check(Yv(Jk,e))},time(e){return this.check(ex(Qk,e))},duration(e){return this.check(tx(Yk,e))}});function ge(e){return Iv(qk,e)}var Ge=N("ZodStringFormat",(e,t)=>{He.init(e,t),pb.init(e,t)}),Xk=N("ZodISODateTime",(e,t)=>{Uy.init(e,t),Ge.init(e,t)}),Jk=N("ZodISODate",(e,t)=>{zy.init(e,t),Ge.init(e,t)}),Qk=N("ZodISOTime",(e,t)=>{Fy.init(e,t),Ge.init(e,t)}),Yk=N("ZodISODuration",(e,t)=>{My.init(e,t),Ge.init(e,t)}),eI=N("ZodEmail",(e,t)=>{Ay.init(e,t),Ge.init(e,t)});var tI=N("ZodGUID",(e,t)=>{_y.init(e,t),Ge.init(e,t)});var Ha=N("ZodUUID",(e,t)=>{Ty.init(e,t),Ge.init(e,t)});var rI=N("ZodURL",(e,t)=>{Py.init(e,t),Ge.init(e,t)});var nI=N("ZodEmoji",(e,t)=>{Ry.init(e,t),Ge.init(e,t)});var iI=N("ZodNanoID",(e,t)=>{By.init(e,t),Ge.init(e,t)});var oI=N("ZodCUID",(e,t)=>{Ny.init(e,t),Ge.init(e,t)});var sI=N("ZodCUID2",(e,t)=>{Dy.init(e,t),Ge.init(e,t)});var aI=N("ZodULID",(e,t)=>{$y.init(e,t),Ge.init(e,t)});var cI=N("ZodXID",(e,t)=>{Oy.init(e,t),Ge.init(e,t)});var uI=N("ZodKSUID",(e,t)=>{Ly.init(e,t),Ge.init(e,t)});var lI=N("ZodIPv4",(e,t)=>{Vy.init(e,t),Ge.init(e,t)});var fI=N("ZodIPv6",(e,t)=>{Hy.init(e,t),Ge.init(e,t)});var dI=N("ZodCIDRv4",(e,t)=>{Ky.init(e,t),Ge.init(e,t)});var pI=N("ZodCIDRv6",(e,t)=>{Zy.init(e,t),Ge.init(e,t)});var hI=N("ZodBase64",(e,t)=>{Gy.init(e,t),Ge.init(e,t)});var mI=N("ZodBase64URL",(e,t)=>{qy.init(e,t),Ge.init(e,t)});var gI=N("ZodE164",(e,t)=>{Xy.init(e,t),Ge.init(e,t)});var yI=N("ZodJWT",(e,t)=>{Jy.init(e,t),Ge.init(e,t)});var hb=N("ZodNumber",(e,t)=>{Vl.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Ax(e,n,r,i),e.isFinite=!0},ag({minValue:(e)=>{let{minimum:t,exclusiveMinimum:n}=$t(e);return Math.max(t??Number.NEGATIVE_INFINITY,n??Number.NEGATIVE_INFINITY)},maxValue:(e)=>{let{maximum:t,exclusiveMaximum:n}=$t(e);return Math.min(t??Number.POSITIVE_INFINITY,n??Number.POSITIVE_INFINITY)},isInt:(e)=>{let{isInt:t,multipleOf:n}=$t(e);return!!t||!!n?.some(Number.isSafeInteger)},format:(e)=>$t(e).format??null},{gt(e,t){return this.check(Ua(e,t))},gte(e,t){return this.check(_o(e,t))},min(e,t){return this.check(_o(e,t))},lt(e,t){return this.check(La(e,t))},lte(e,t){return this.check(Eo(e,t))},max(e,t){return this.check(Eo(e,t))},int(e){return this.check(ab(e))},safe(e){return this.check(ab(e))},positive(e){return this.check(Ua(0,e))},nonnegative(e){return this.check(_o(0,e))},negative(e){return this.check(La(0,e))},nonpositive(e){return this.check(Eo(0,e))},multipleOf(e,t){return this.check(za(e,t))},step(e,t){return this.check(za(e,t))},finite(){return this}}));function zr(e){return rx(hb,e)}var vI=N("ZodNumberFormat",(e,t)=>{Qy.init(e,t),hb.init(e,t)});function ab(e){return nx(vI,e)}var xI=N("ZodBoolean",(e,t)=>{Yy.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,r,i)=>kx(e,n,r,i)});function Lt(e){return ix(xI,e)}var bI=N("ZodUnknown",(e,t)=>{ev.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Px(e,n,r,i)});function cb(){return ox(bI)}var SI=N("ZodNever",(e,t)=>{tv.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Ix(e,n,r,i)});function CI(e){return sx(SI,e)}var wI=N("ZodArray",(e,t)=>{Io(),rv.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Dx(e,n,r,i),e.element=t.element},{min(e,t){return this.check(bi(e,t))},nonempty(e){return this.check(bi(1,e))},max(e,t){return this.check(Fa(e,t))},length(e,t){return this.check(Ma(e,t))},unwrap(){return this.element}});function ze(e,t){return ax(wI,e,t)}var EI=N("ZodObject",(e,t)=>{Io(),ov.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,r,i)=>$x(e,n,r,i),tk(e,"shape",(n)=>n._zod.def.shape,!1)},{keyof(){return Bn(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(Dt(this._zod.def,{catchall:e}))},passthrough(){return this.clone(Dt(this._zod.def,{catchall:cb()}))},loose(){return this.clone(Dt(this._zod.def,{catchall:cb()}))},strict(){return this.clone(Dt(this._zod.def,{catchall:CI()}))},strip(){return this.clone(Dt(this._zod.def,{catchall:void 0}))},extend(e){return jA(this,e)},safeExtend(e){return GA(this,e)},merge(e){return qA(this,e)},pick(e){return KA(this,e)},omit(e){return ZA(this,e)},partial(...e){return ng(gf,this,e[0])},exactPartial(...e){return ng(yb,this,e[0],"exactPartial")},required(...e){return XA(vb,this,e[0])}});function pt(e,t){let n={type:"object",shape:e??{},...Y(t)};return new EI(n)}var _I=N("ZodUnion",(e,t)=>{sv.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Ox(e,n,r,i),e.options=t.options});function TI(e,t){return new _I({type:"union",options:e,...Y(t)})}var AI=N("ZodIntersection",(e,t)=>{av.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Lx(e,n,r,i)});function kI(e,t){return new AI({type:"intersection",left:e,right:t})}var II=N("ZodTuple",(e,t)=>{Io(),cv.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Ux(e,n,r,i)},{rest(e){return this.clone({...this._zod.def,rest:e})},partial(){let e=this._zod.def;if(e.checks?.length)throw Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...e,items:e.items.map((t)=>new gf({type:"optional",innerType:t}))})}});function PI(e,t,n){let r=t instanceof We,i=r?n:t;return new II({type:"tuple",items:e,rest:r?t:null,...Y(i)})}var ub=N("ZodRecord",(e,t)=>{Io(),uv.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,r,i)=>zx(e,n,r,i),e.keyType=t.keyType,e.valueType=t.valueType});function mb(e,t,n){if(!t||!t._zod)return new ub({type:"record",keyType:ge(),valueType:e,...Y(t)});return new ub({type:"record",keyType:e,valueType:t,...Y(n)})}var mf=N("ZodEnum",(e,t)=>{lv.init(e,t),je.init(e,t),e._zod.processJSONSchema=(r,i,o)=>Rx(e,r,i,o),e.enum=t.entries,e.options=[...e._zod.values];let n=new Set(Object.keys(t.entries));e.extract=(r,i)=>{let o={};for(let s of r)if(n.has(s))o[s]=t.entries[s];else throw Error(`Key ${s} not found in enum`);return new mf({...t,checks:[],...Y(i),entries:o})},e.exclude=(r,i)=>{let o={...t.entries};for(let s of r)if(n.has(s))delete o[s];else throw Error(`Key ${s} not found in enum`);return new mf({...t,checks:[],...Y(i),entries:o})}});function Bn(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map((r)=>[r,r])):e;return new mf({type:"enum",entries:n,...Y(t)})}var RI=N("ZodTransform",(e,t)=>{Io(),fv.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Nx(e,n,r,i),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new xo(e.constructor.name);n.addIssue=(o)=>{if(typeof o==="string")n.issues.push(Pn(o,n.value,t));else{let s=o;if(s.fatal)s.continue=!1;if(s.code??(s.code="custom"),!("input"in s))s.input=n.value;s.inst??(s.inst=e),n.issues.push(Pn(s))}};let i=t.transform(n.value,n);if(i instanceof Promise)return i.then((o)=>(n.value=o,n));return n.value=i,n}});function gb(e){return new RI({type:"transform",transform:e})}var gf=N("ZodOptional",(e,t)=>{Wl.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,r,i)=>hf(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function lb(e){return new gf({type:"optional",innerType:e})}var yb=N("ZodExactOptional",(e,t)=>{dv.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,r,i)=>hf(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function BI(e){return new yb({type:"optional",innerType:e})}var NI=N("ZodNullable",(e,t)=>{pv.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Fx(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function fb(e){return new NI({type:"nullable",innerType:e})}var DI=N("ZodDefault",(e,t)=>{hv.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Wx(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function $I(e,t){return new DI({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():Sl(t)}})}var OI=N("ZodPrefault",(e,t)=>{mv.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Hx(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function LI(e,t){return new OI({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():Sl(t)}})}var vb=N("ZodNonOptional",(e,t)=>{gv.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Mx(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function UI(e,t){return new vb({type:"nonoptional",innerType:e,...Y(t)})}var zI=N("ZodCatch",(e,t)=>{yv.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Kx(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function FI(e,t){return new zI({type:"catch",innerType:e,catchValue:typeof t==="function"?t:cg(t)})}var xb=N("ZodPipe",(e,t)=>{Hl.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Zx(e,n,r,i),e.in=t.in,e.out=t.out});function db(e,t){return new xb({type:"pipe",in:e,out:t})}var MI=N("ZodPreprocess",(e,t)=>{xb.init(e,t),vv.init(e,t)}),VI=N("ZodReadonly",(e,t)=>{xv.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,r,i)=>jx(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function WI(e){return new VI({type:"readonly",innerType:e})}var bb=N("ZodCustom",(e,t)=>{bv.init(e,t),je.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Bx(e,n,r,i)});function HI(e,t){return cx(bb,e??(()=>!0),t)}function KI(e,t={}){return ux(bb,e,t)}function ZI(e,t){return lx(e,t)}function jI(e,t){return new MI({type:"pipe",in:gb(e),out:t})}var vt={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};var Sb;(function(e){})(Sb||(Sb={}));var Fe=1e4;function Tb(e){return jI((t,n)=>{if(typeof t==="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).length>Fe)return n.addIssue({code:"custom",message:`At most ${Fe} entries`}),fg;return t},e)}function vf(e){if(GI(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 xf='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.',Za=ge().refine(vf,{message:xf});function Ab(e){let t=e.indexOf(":");return!(t!==-1&&e.indexOf(":",t+1)!==-1)||e.startsWith("[")}var XI=ge().refine((e)=>Ab(e)&&vf(ao(e).hostPattern),{message:xf+' An optional ":port" suffix (1-65535) restricts the entry to that port.'}),wb=ge().refine((e)=>{if(!Ab(e))return!1;let{hostPattern:t}=ao(e);return t==="*"||vf(t)},{message:xf+' In deniedDomains a bare "*" (deny-all) is also accepted, and an optional ":port" suffix (1-65535) restricts the entry to that port.'}),Po=ge().min(1,"Path cannot be empty"),Eb=ge().min(1,"Path cannot be empty").refine((e)=>qI(e),{message:"Binary path must be absolute"}),JI=pt({socketPath:ge().min(1).describe("Unix socket path to the MITM proxy"),domains:ze(Za).max(Fe).min(1).describe('Domains to route through the MITM proxy (e.g., ["api.example.com", "*.internal.org"])')}),QI=pt({http:ge().url().optional().describe("Upstream proxy URL for plain HTTP traffic"),https:ge().url().optional().describe("Upstream proxy URL for HTTPS/CONNECT traffic (falls back to http if unset)"),noProxy:ge().optional().describe("Comma-separated NO_PROXY list (hostname suffixes and CIDR ranges). Matching destinations connect directly instead of via the parent proxy.")}),kb=Bn(["deny","mask"]),Ka=ge().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"),Ib=ge().superRefine((e,t)=>{try{let{groupCount:n}=Tu(e);if(n<1)t.addIssue({code:vt.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:vt.custom,message:n instanceof Error?n.message:"Credential extract pattern is invalid"})}}),YI=pt({path:Po.describe("Path to a credential file or directory. Supports the same path forms as filesystem.denyRead (absolute paths and ~ expansion)."),mode:kb.describe("Access mode for this path"),extract:Ib.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:Bn(["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:Bn(["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:ze(ge().min(1)).max(Fe).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:Lt().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:ze(Za).max(Fe).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".')}),e2=pt({name:Ka.describe("Environment variable name"),mode:kb.describe("Access mode for this environment variable"),extract:Ib.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:Bn(["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:Bn(["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:ze(ge().min(1)).max(Fe).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:ze(Za).max(Fe).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:ze(ge().regex(/^[a-z0-9-]{1,64}$/)).max(Fe).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".')}),t2=pt({accessKeyIdVar:Ka.describe("Name of the masked env var holding the AWS access key id."),secretAccessKeyVar:Ka.describe("Name of the masked env var holding the AWS secret access key."),sessionTokenVar:Ka.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(),yf=Bn(["deny","passthrough"]),r2=pt({streaming:yf.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:yf.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:yf.optional().describe('Policy for SigV4A (AWS4-ECDSA-P256-SHA256) asymmetric signatures: there is no shared-key HMAC to recompute. Default "deny".')}).strict(),Pb=pt({files:ze(YI).max(Fe).optional().describe("Credential files or directories to protect"),envVars:ze(e2).max(Fe).optional().describe("Environment variables to protect"),allowPlaintextInject:Lt().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:ze(t2).max(Fe).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:r2.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(),_b=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/,n2=/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?$/,i2=pt({url:ge().url().refine((e)=>new URL(e).protocol==="https:",{message:"brokerForward.url must be https"}),tokenEnvVar:ge().regex(_b),rules:ze(pt({envVar:ge().regex(_b),hosts:ze(ge().regex(n2)).min(1).max(16)}).strict()).max(Fe).min(1).max(32)}).strict(),Rb=pt({allowedDomains:ze(XI).max(Fe).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:ze(wb).max(Fe).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:Tb(mb(ge(),ge().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.'),allowAllDomains:Lt().optional().describe("ARA PATCH (open egress): if true, a host no allowedDomains entry matches is allowed too, after deniedDomains, unless it names or resolves to a loopback, private, link-local or otherwise non-public address. Such a host is always tunnelled (never TLS-terminated), so credential injection stays scoped to allowedDomains."),allowlistCarveOuts:ze(wb).max(Fe).optional().describe("ARA PATCH (open egress): deniedDomains entries that only carve hosts out of an allowedDomains wildcard (customer-run hosts below a provider wildcard, such as EC2 and RDS names below *.amazonaws.com), not out of the public internet. With allowAllDomains, a host only such entries deny is allowed as any other public host is: dialled only at a public address it resolves to, never TLS-terminated, no credentials. Without allowAllDomains they deny as deniedDomains does. Each entry must be a deniedDomains entry and a wildcard strictly below an allowedDomains wildcard, and the key cannot be combined with credentials.allowPlaintextInject; a config that breaks either rule is refused."),refuseLocalDestinations:Lt().optional().describe("ARA PATCH (local destinations): if true, a name that allowedDomains (or the ask callback) admits is resolved once and dialled at that address, and refused when it resolves to loopback, a link-local address (169.254.0.0/16 with cloud metadata, fe80::/10) or one of this machine's own interface addresses. Other private addresses stay reachable. An IP literal or localhost entry is dialled as given. Not applied to connections that leave through a parent proxy or the external MITM socket."),strictAllowlist:Lt().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:ze(ge()).max(Fe).optional().describe("macOS only: Unix socket paths to allow. Ignored on Linux (seccomp cannot filter by path)."),allowAllUnixSockets:Lt().optional().describe("If true, allow all Unix sockets (disables blocking on both platforms)."),allowLocalBinding:Lt().optional().describe("Whether to allow binding to local ports (default: false)"),allowMachLookup:ze(ge().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).'})).max(Fe).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:zr().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:zr().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:JI.optional().describe("Optional MITM proxy configuration. Routes matching domains through an upstream proxy via Unix socket while SRT still handles allow/deny filtering."),filterRequest:HI((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:pt({caCertPath:ge().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:ge().min(1).optional().describe("Path to the PEM-encoded private key for caCertPath."),excludeDomains:ze(Za).max(Fe).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:ze(ge().min(1)).max(Fe).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:QI.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:i2.optional().describe("Credential placeholders a remote broker swaps (see broker-forward.ts).")}),Bb=pt({disabled:Lt().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:ze(Po).max(Fe).describe("Paths denied for reading"),allowRead:ze(Po).max(Fe).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:ze(Po).max(Fe).describe("Paths allowed for writing"),denyWrite:ze(Po).max(Fe).describe("Paths denied for writing (takes precedence over allowWrite)"),allowGitConfig:Lt().optional().describe("Allow writes to .git/config files (default: false). Enables git remote URL updates while keeping .git/hooks protected.")}),Nb=Tb(mb(ge(),ze(ge()).max(Fe))).describe('Map of command patterns to filesystem paths to ignore violations for. Use "*" to match all commands'),Db=pt({command:ge().describe("The ripgrep command to execute"),args:ze(ge()).max(Fe).optional().describe("Additional arguments to pass before ripgrep args"),argv0:ge().optional().describe("Override argv[0] when spawning (for multicall binaries that dispatch on argv[0])")}),$b=pt({safeDirectories:ze(ge()).max(Fe).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.")}),Ob=pt({path:ge().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.")}),Lb=pt({sandboxUser:ge().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:ge().guid().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:ge().guid().optional().describe("Deprecated alias for sublayerGuid."),proxyPortRange:PI([zr().int().min(1),zr().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:Ob.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.")}),o2=pt({applyPath:ge().optional().describe("Path to the apply-seccomp binary"),argv0:ge().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.")}),s2=pt({network:Rb.describe("Network restrictions configuration"),filesystem:Bb.describe("Filesystem restrictions configuration"),credentials:Pb.optional().describe("Credential handling configuration. Only the explicitly declared files and environment variables are restricted."),ignoreViolations:Nb.optional().describe("Optional configuration for ignoring specific violations"),enableWeakerNestedSandbox:Lt().optional().describe("Enable weaker nested sandbox mode (for Docker environments)"),runAsUid:zr().int().nonnegative().optional().describe("ARA: uid to drop the sandboxed command to (bwrap --uid)"),runAsGid:zr().int().nonnegative().optional().describe("ARA: gid to drop the sandboxed command to (bwrap --gid)"),runAsHostUid:zr().int().positive().optional().describe("ARA: real host uid used to launch the sandboxed bwrap child"),runAsHostGid:zr().int().positive().optional().describe("ARA: real host gid used to launch the sandboxed bwrap child"),runAsHostHome:ge().min(1).optional().describe("ARA: HOME set inside a real-host-uid sandbox child"),runAsHostUser:ge().min(1).optional().describe("ARA: USER and LOGNAME set inside a real-host-uid sandbox child"),enableWeakerNetworkIsolation:Lt().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:Lt().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:Db.optional().describe('Custom ripgrep configuration (default: { command: "rg" })'),mandatoryDenySearchDepth:zr().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:Lt().optional().describe("Allow pseudo-terminal (pty) operations (macOS only)"),seccomp:o2.optional().describe("Custom seccomp binary paths (Linux only)."),bwrapPath:Eb.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:Eb.optional().describe('Linux only: absolute path to the socat binary. When set, this path is used directly instead of resolving "socat" via PATH.'),windows:Lb.optional().describe("Windows-specific settings (WFP sublayer, proxy port range)."),git:$b.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.network.allowlistCarveOuts??[],r=e.network.allowedDomains.map(wn).filter((l)=>l.startsWith("*.")).map((l)=>l.slice(1).toLowerCase());for(let[l,f]of n.entries()){let p=wn(f).toLowerCase(),h=p.startsWith("*.")&&r.some((d)=>p.slice(1).endsWith(d)&&p.slice(1)!==d);if(!e.network.deniedDomains.includes(f)||!h)t.addIssue({code:vt.custom,path:["network","allowlistCarveOuts",l],message:`allowlistCarveOuts entry "${f}" must be a deniedDomains entry that is a wildcard strictly below an allowedDomains wildcard (e.g. "*.rds.amazonaws.com" below "*.amazonaws.com").`})}if(n.length>0&&e.credentials?.allowPlaintextInject)t.addIssue({code:vt.custom,path:["network","allowlistCarveOuts"],message:"allowlistCarveOuts cannot be combined with credentials.allowPlaintextInject."});let i=e.credentials;if(!i)return;let o=e.network.allowedDomains.map(wn),s=(l,f)=>{for(let[p,h]of l.entries())if(!ca(h,o))t.addIssue({code:vt.custom,path:[...f,p],message:`injectHosts entry "${h}" is not reachable via `+`network.allowedDomains \u2014 add "${h}" (or a covering wildcard) to allowedDomains, or remove it from injectHosts.`})},a=!1,c=(l,f)=>{if(l.injectHosts)s(l.injectHosts,[...f,"injectHosts"]);if(l.mode!=="mask")return;a=!0;let p=e.network.tlsTerminate?.excludeDomains;if(p?.length){if(l.injectHosts){for(let[h,d]of l.injectHosts.entries())if(ca(d,p))t.addIssue({code:vt.custom,path:[...f,"injectHosts",h],message:`injectHosts entry "${d}" 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(o.length>0&&o.every((h)=>ca(h,p)))t.addIssue({code:vt.custom,path:f,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:vt.custom,path:f,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,f]of(i.envVars??[]).entries()){if(c(f,["credentials","envVars",l]),f.maskClaims!==void 0&&f.decode===void 0)t.addIssue({code:vt.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(f.maskClaims!==void 0&&f.maskClaims.length===0)t.addIssue({code:vt.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,f]of(i.files??[]).entries()){if(c(f,["credentials","files",l]),f.maskClaims!==void 0&&f.decode===void 0)t.addIssue({code:vt.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(f.maskClaims!==void 0&&f.maskClaims.length===0)t.addIssue({code:vt.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(f.mode==="mask"&&f.path.endsWith("/"))t.addIssue({code:vt.custom,path:["credentials","files",l,"path"],message:`Credential mode "mask" applies to a single file, not a directory. Use mode "deny" for "${f.path}", or point at the credential file inside it.`})}let u=new Set;for(let[l,f]of(i.awsPairs??[]).entries()){let p=[["accessKeyIdVar",f.accessKeyIdVar],["secretAccessKeyVar",f.secretAccessKeyVar]];if(f.sessionTokenVar!==void 0)p.push(["sessionTokenVar",f.sessionTokenVar]);for(let[h,d]of p){let g=["credentials","awsPairs",l,h];if(u.has(d)){t.addIssue({code:vt.custom,path:g,message:`"${d}" appears in more than one awsPairs slot (within `+"or across pairs) \u2014 each variable can fill exactly one slot."});continue}u.add(d);let v=(i.envVars??[]).find((b)=>b.name===d);if(v===void 0||v.mode!=="mask")t.addIssue({code:vt.custom,path:g,message:`"${d}" 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(v.extract!==void 0||v.decode!==void 0)t.addIssue({code:vt.custom,path:g,message:`"${d}" 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&&!i.allowPlaintextInject)t.addIssue({code:vt.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{Pb as CredentialsConfigSchema,ta as DEFAULT_WINDOWS_PROXY_PORT_RANGE,Bb as FilesystemConfigSchema,$b as GitConfigSchema,Nb as IgnoreViolationsConfigSchema,Rb as NetworkConfigSchema,Db as RipgrepConfigSchema,em as SRT_WIN_DISPATCH_ARG1,WA as SandboxManager,s2 as SandboxRuntimeConfigSchema,Ys as SandboxViolationStore,Ob as SrtWinConfigSchema,WT as VENDORED_SRT_WIN_EXE,Lb as WindowsConfigSchema,me as WindowsSandboxError,ki as buildGitConfigEnv,Yn as certThumbprint,sl as checkWindowsDependenciesAsync,im as checkWindowsSandboxStatus,om as checkWindowsSandboxStatusAsync,rl as ensurePersistentWindowsCa,oa as expandWindowsFsPaths,Cs as generateCa,Nn as getDefaultWritePaths,HT as getSrtWinPath,tl as getWindowsSandboxCaCert,el as getWindowsSandboxUserStatus,so as getWindowsSandboxUserStatusAsync,sm as getWindowsWfpStatus,am as getWindowsWfpStatusAsync,Ga as getWslVersion,ol as grantWindowsAcl,jT as installWindowsSandbox,GT as installWindowsSandboxAsync,Ai as isUncPath,ra as parseWindowsBinShell,XT as parseWindowsSandboxError,Nt as resolveSrtWin,sa as restoreWindowsAcl,aa as revokeWindowsAcl,il as stampWindowsAcl,qT as uninstallWindowsSandbox,Zi as validateCaPair,Yu as verifyWindowsWfpEgress,Xu as windowsInstallInstructions,lm as windowsStateDir,ZT as windowsTrustCa,cm as windowsTrustCaAsync};