@reason-machines/cli-darwin-arm64 0.2.687 → 0.2.689

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,22 +1,22 @@
1
1
  // @bun
2
- var c0=Object.create;var{getPrototypeOf:u0,defineProperty:$c,getOwnPropertyNames:d0}=Object;var Wc=Object.prototype.hasOwnProperty;function f0(e){return this[e]}var p0,h0,no=(e,t,n)=>{var r=e!=null&&typeof e==="object";if(r){var i=t?p0??=new WeakMap:h0??=new WeakMap,s=i.get(e);if(s)return s}n=e!=null?c0(u0(e)):{};let a=t||!e||!e.__esModule||!Wc.call(e,"default")?$c(n,"default",{value:e,enumerable:!0}):n;if(e&&typeof e==="object"||typeof e==="function"){for(let o of d0(e))if(!Wc.call(a,o))$c(a,o,{get:f0.bind(e,o),enumerable:!0})}if(r)i.set(e,a);return a};var de=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var ui=import.meta.require;var ve=de(function(s1,jc){jc.exports={options:{usePureJavaScript:!1}}});var Qc=de(function(a1,Xc){var ao={};Xc.exports=ao;var zc={};ao.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=w0(e,t);else{var i=0,s=t.length,a=t.charAt(0),o=[0];for(i=0;i<e.length;++i){for(var l=0,c=e[i];l<o.length;++l)c+=o[l]<<8,o[l]=c%s,c=c/s|0;while(c>0)o.push(c%s),c=c/s|0}for(i=0;e[i]===0&&i<e.length-1;++i)r+=a;for(i=o.length-1;i>=0;--i)r+=t[o[i]]}if(n){var u=new RegExp(".{1,"+n+"}","g");r=r.match(u).join(`\r
3
- `)}return r};ao.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=zc[t];if(!n){n=zc[t]=[];for(var r=0;r<t.length;++r)n[t.charCodeAt(r)]=r}e=e.replace(/\s/g,"");var i=t.length,s=t.charAt(0),a=[0];for(var r=0;r<e.length;r++){var o=n[e.charCodeAt(r)];if(o===void 0)return;for(var l=0,c=o;l<a.length;++l)c+=a[l]*i,a[l]=c&255,c>>=8;while(c>0)a.push(c&255),c>>=8}for(var u=0;e[u]===s&&u<e.length-1;++u)a.push(0);if(typeof Buffer<"u")return Buffer.from(a.reverse());return new Uint8Array(a.reverse())};function w0(e,t){var n=0,r=t.length,i=t.charAt(0),s=[0];for(n=0;n<e.length();++n){for(var a=0,o=e.at(n);a<s.length;++a)o+=s[a]<<8,s[a]=o%r,o=o/r|0;while(o>0)s.push(o%r),o=o/r|0}var l="";for(n=0;e.at(n)===0&&n<e.length()-1;++n)l+=i;for(n=s.length-1;n>=0;--n)l+=t[s[n]];return l}});var Pe=de(function(o1,eu){var Yc=ve(),Jc=Qc(),T=eu.exports=Yc.util=Yc.util||{};(function(){if(typeof process<"u"&&process.nextTick){if(T.nextTick=process.nextTick,typeof setImmediate==="function")T.setImmediate=setImmediate;else T.setImmediate=T.nextTick;return}if(typeof setImmediate==="function"){T.setImmediate=function(){return setImmediate.apply(void 0,arguments)},T.nextTick=function(o){return setImmediate(o)};return}if(T.setImmediate=function(o){setTimeout(o,0)},typeof window<"u"&&typeof window.postMessage==="function"){let o=function(l){if(l.source===window&&l.data===e){l.stopPropagation();var c=t.slice();t.length=0,c.forEach(function(u){u()})}};var a=o,e="forge.setImmediate",t=[];T.setImmediate=function(l){if(t.push(l),t.length===1)window.postMessage(e,"*")},window.addEventListener("message",o,!0)}if(typeof MutationObserver<"u"){var n=Date.now(),r=!0,i=document.createElement("div"),t=[];new MutationObserver(function(){var l=t.slice();t.length=0,l.forEach(function(c){c()})}).observe(i,{attributes:!0});var s=T.setImmediate;T.setImmediate=function(l){if(Date.now()-n>15)n=Date.now(),s(l);else if(t.push(l),t.length===1)i.setAttribute("a",r=!r)}}T.nextTick=T.setImmediate})();T.isNodejs=typeof process<"u"&&process.versions&&process.versions.node;T.globalScope=function(){if(T.isNodejs)return global;return typeof self>"u"?window:self}();T.isArray=Array.isArray||function(e){return Object.prototype.toString.call(e)==="[object Array]"};T.isArrayBuffer=function(e){return typeof ArrayBuffer<"u"&&e instanceof ArrayBuffer};T.isArrayBufferView=function(e){return e&&T.isArrayBuffer(e.buffer)&&e.byteLength!==void 0};function mi(e){if(!(e===8||e===16||e===24||e===32))throw Error("Only 8, 16, 24, or 32 bits supported: "+e)}T.ByteBuffer=oo;function oo(e){if(this.data="",this.read=0,typeof e==="string")this.data=e;else if(T.isArrayBuffer(e)||T.isArrayBufferView(e))if(typeof Buffer<"u"&&e instanceof Buffer)this.data=e.toString("binary");else{var t=new Uint8Array(e);try{this.data=String.fromCharCode.apply(null,t)}catch(r){for(var n=0;n<t.length;++n)this.putByte(t[n])}}else if(e instanceof oo||typeof e==="object"&&typeof e.data==="string"&&typeof e.read==="number")this.data=e.data,this.read=e.read;this._constructedStringLength=0}T.ByteStringBuffer=oo;var E0=4096;T.ByteStringBuffer.prototype._optimizeConstructedString=function(e){if(this._constructedStringLength+=e,this._constructedStringLength>E0)this.data.substr(0,1),this._constructedStringLength=0};T.ByteStringBuffer.prototype.length=function(){return this.data.length-this.read};T.ByteStringBuffer.prototype.isEmpty=function(){return this.length()<=0};T.ByteStringBuffer.prototype.putByte=function(e){return this.putBytes(String.fromCharCode(e))};T.ByteStringBuffer.prototype.fillWithByte=function(e,t){e=String.fromCharCode(e);var n=this.data;while(t>0){if(t&1)n+=e;if(t>>>=1,t>0)e+=e}return this.data=n,this._optimizeConstructedString(t),this};T.ByteStringBuffer.prototype.putBytes=function(e){return this.data+=e,this._optimizeConstructedString(e.length),this};T.ByteStringBuffer.prototype.putString=function(e){return this.putBytes(T.encodeUtf8(e))};T.ByteStringBuffer.prototype.putInt16=function(e){return this.putBytes(String.fromCharCode(e>>8&255)+String.fromCharCode(e&255))};T.ByteStringBuffer.prototype.putInt24=function(e){return this.putBytes(String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e&255))};T.ByteStringBuffer.prototype.putInt32=function(e){return this.putBytes(String.fromCharCode(e>>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e&255))};T.ByteStringBuffer.prototype.putInt16Le=function(e){return this.putBytes(String.fromCharCode(e&255)+String.fromCharCode(e>>8&255))};T.ByteStringBuffer.prototype.putInt24Le=function(e){return this.putBytes(String.fromCharCode(e&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e>>16&255))};T.ByteStringBuffer.prototype.putInt32Le=function(e){return this.putBytes(String.fromCharCode(e&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>24&255))};T.ByteStringBuffer.prototype.putInt=function(e,t){mi(t);var n="";do t-=8,n+=String.fromCharCode(e>>t&255);while(t>0);return this.putBytes(n)};T.ByteStringBuffer.prototype.putSignedInt=function(e,t){if(e<0)e+=2<<t-1;return this.putInt(e,t)};T.ByteStringBuffer.prototype.putBuffer=function(e){return this.putBytes(e.getBytes())};T.ByteStringBuffer.prototype.getByte=function(){return this.data.charCodeAt(this.read++)};T.ByteStringBuffer.prototype.getInt16=function(){var e=this.data.charCodeAt(this.read)<<8^this.data.charCodeAt(this.read+1);return this.read+=2,e};T.ByteStringBuffer.prototype.getInt24=function(){var e=this.data.charCodeAt(this.read)<<16^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2);return this.read+=3,e};T.ByteStringBuffer.prototype.getInt32=function(){var e=this.data.charCodeAt(this.read)<<24^this.data.charCodeAt(this.read+1)<<16^this.data.charCodeAt(this.read+2)<<8^this.data.charCodeAt(this.read+3);return this.read+=4,e};T.ByteStringBuffer.prototype.getInt16Le=function(){var e=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8;return this.read+=2,e};T.ByteStringBuffer.prototype.getInt24Le=function(){var e=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2)<<16;return this.read+=3,e};T.ByteStringBuffer.prototype.getInt32Le=function(){var e=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2)<<16^this.data.charCodeAt(this.read+3)<<24;return this.read+=4,e};T.ByteStringBuffer.prototype.getInt=function(e){mi(e);var t=0;do t=(t<<8)+this.data.charCodeAt(this.read++),e-=8;while(e>0);return t};T.ByteStringBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),n=2<<e-2;if(t>=n)t-=n<<1;return t};T.ByteStringBuffer.prototype.getBytes=function(e){var t;if(e)e=Math.min(this.length(),e),t=this.data.slice(this.read,this.read+e),this.read+=e;else if(e===0)t="";else t=this.read===0?this.data:this.data.slice(this.read),this.clear();return t};T.ByteStringBuffer.prototype.bytes=function(e){return typeof e>"u"?this.data.slice(this.read):this.data.slice(this.read,this.read+e)};T.ByteStringBuffer.prototype.at=function(e){return this.data.charCodeAt(this.read+e)};T.ByteStringBuffer.prototype.setAt=function(e,t){return this.data=this.data.substr(0,this.read+e)+String.fromCharCode(t)+this.data.substr(this.read+e+1),this};T.ByteStringBuffer.prototype.last=function(){return this.data.charCodeAt(this.data.length-1)};T.ByteStringBuffer.prototype.copy=function(){var e=T.createBuffer(this.data);return e.read=this.read,e};T.ByteStringBuffer.prototype.compact=function(){if(this.read>0)this.data=this.data.slice(this.read),this.read=0;return this};T.ByteStringBuffer.prototype.clear=function(){return this.data="",this.read=0,this};T.ByteStringBuffer.prototype.truncate=function(e){var t=Math.max(0,this.length()-e);return this.data=this.data.substr(this.read,t),this.read=0,this};T.ByteStringBuffer.prototype.toHex=function(){var e="";for(var t=this.read;t<this.data.length;++t){var n=this.data.charCodeAt(t);if(n<16)e+="0";e+=n.toString(16)}return e};T.ByteStringBuffer.prototype.toString=function(){return T.decodeUtf8(this.bytes())};function T0(e,t){t=t||{},this.read=t.readOffset||0,this.growSize=t.growSize||1024;var n=T.isArrayBuffer(e),r=T.isArrayBufferView(e);if(n||r){if(n)this.data=new DataView(e);else this.data=new DataView(e.buffer,e.byteOffset,e.byteLength);this.write="writeOffset"in t?t.writeOffset:this.data.byteLength;return}if(this.data=new DataView(new ArrayBuffer(0)),this.write=0,e!==null&&e!==void 0)this.putBytes(e);if("writeOffset"in t)this.write=t.writeOffset}T.DataBuffer=T0;T.DataBuffer.prototype.length=function(){return this.write-this.read};T.DataBuffer.prototype.isEmpty=function(){return this.length()<=0};T.DataBuffer.prototype.accommodate=function(e,t){if(this.length()>=e)return this;t=Math.max(t||this.growSize,e);var n=new Uint8Array(this.data.buffer,this.data.byteOffset,this.data.byteLength),r=new Uint8Array(this.length()+t);return r.set(n),this.data=new DataView(r.buffer),this};T.DataBuffer.prototype.putByte=function(e){return this.accommodate(1),this.data.setUint8(this.write++,e),this};T.DataBuffer.prototype.fillWithByte=function(e,t){this.accommodate(t);for(var n=0;n<t;++n)this.data.setUint8(e);return this};T.DataBuffer.prototype.putBytes=function(e,t){if(T.isArrayBufferView(e)){var n=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r=n.byteLength-n.byteOffset;this.accommodate(r);var i=new Uint8Array(this.data.buffer,this.write);return i.set(n),this.write+=r,this}if(T.isArrayBuffer(e)){var n=new Uint8Array(e);this.accommodate(n.byteLength);var i=new Uint8Array(this.data.buffer);return i.set(n,this.write),this.write+=n.byteLength,this}if(e instanceof T.DataBuffer||typeof e==="object"&&typeof e.read==="number"&&typeof e.write==="number"&&T.isArrayBufferView(e.data)){var n=new Uint8Array(e.data.byteLength,e.read,e.length());this.accommodate(n.byteLength);var i=new Uint8Array(e.data.byteLength,this.write);return i.set(n),this.write+=n.byteLength,this}if(e instanceof T.ByteStringBuffer)e=e.data,t="binary";if(t=t||"binary",typeof e==="string"){var s;if(t==="hex")return this.accommodate(Math.ceil(e.length/2)),s=new Uint8Array(this.data.buffer,this.write),this.write+=T.binary.hex.decode(e,s,this.write),this;if(t==="base64")return this.accommodate(Math.ceil(e.length/4)*3),s=new Uint8Array(this.data.buffer,this.write),this.write+=T.binary.base64.decode(e,s,this.write),this;if(t==="utf8")e=T.encodeUtf8(e),t="binary";if(t==="binary"||t==="raw")return this.accommodate(e.length),s=new Uint8Array(this.data.buffer,this.write),this.write+=T.binary.raw.decode(s),this;if(t==="utf16")return this.accommodate(e.length*2),s=new Uint16Array(this.data.buffer,this.write),this.write+=T.text.utf16.encode(s),this;throw Error("Invalid encoding: "+t)}throw Error("Invalid parameter: "+e)};T.DataBuffer.prototype.putBuffer=function(e){return this.putBytes(e),e.clear(),this};T.DataBuffer.prototype.putString=function(e){return this.putBytes(e,"utf16")};T.DataBuffer.prototype.putInt16=function(e){return this.accommodate(2),this.data.setInt16(this.write,e),this.write+=2,this};T.DataBuffer.prototype.putInt24=function(e){return this.accommodate(3),this.data.setInt16(this.write,e>>8&65535),this.data.setInt8(this.write,e>>16&255),this.write+=3,this};T.DataBuffer.prototype.putInt32=function(e){return this.accommodate(4),this.data.setInt32(this.write,e),this.write+=4,this};T.DataBuffer.prototype.putInt16Le=function(e){return this.accommodate(2),this.data.setInt16(this.write,e,!0),this.write+=2,this};T.DataBuffer.prototype.putInt24Le=function(e){return this.accommodate(3),this.data.setInt8(this.write,e>>16&255),this.data.setInt16(this.write,e>>8&65535,!0),this.write+=3,this};T.DataBuffer.prototype.putInt32Le=function(e){return this.accommodate(4),this.data.setInt32(this.write,e,!0),this.write+=4,this};T.DataBuffer.prototype.putInt=function(e,t){mi(t),this.accommodate(t/8);do t-=8,this.data.setInt8(this.write++,e>>t&255);while(t>0);return this};T.DataBuffer.prototype.putSignedInt=function(e,t){if(mi(t),this.accommodate(t/8),e<0)e+=2<<t-1;return this.putInt(e,t)};T.DataBuffer.prototype.getByte=function(){return this.data.getInt8(this.read++)};T.DataBuffer.prototype.getInt16=function(){var e=this.data.getInt16(this.read);return this.read+=2,e};T.DataBuffer.prototype.getInt24=function(){var e=this.data.getInt16(this.read)<<8^this.data.getInt8(this.read+2);return this.read+=3,e};T.DataBuffer.prototype.getInt32=function(){var e=this.data.getInt32(this.read);return this.read+=4,e};T.DataBuffer.prototype.getInt16Le=function(){var e=this.data.getInt16(this.read,!0);return this.read+=2,e};T.DataBuffer.prototype.getInt24Le=function(){var e=this.data.getInt8(this.read)^this.data.getInt16(this.read+1,!0)<<8;return this.read+=3,e};T.DataBuffer.prototype.getInt32Le=function(){var e=this.data.getInt32(this.read,!0);return this.read+=4,e};T.DataBuffer.prototype.getInt=function(e){mi(e);var t=0;do t=(t<<8)+this.data.getInt8(this.read++),e-=8;while(e>0);return t};T.DataBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),n=2<<e-2;if(t>=n)t-=n<<1;return t};T.DataBuffer.prototype.getBytes=function(e){var t;if(e)e=Math.min(this.length(),e),t=this.data.slice(this.read,this.read+e),this.read+=e;else if(e===0)t="";else t=this.read===0?this.data:this.data.slice(this.read),this.clear();return t};T.DataBuffer.prototype.bytes=function(e){return typeof e>"u"?this.data.slice(this.read):this.data.slice(this.read,this.read+e)};T.DataBuffer.prototype.at=function(e){return this.data.getUint8(this.read+e)};T.DataBuffer.prototype.setAt=function(e,t){return this.data.setUint8(e,t),this};T.DataBuffer.prototype.last=function(){return this.data.getUint8(this.write-1)};T.DataBuffer.prototype.copy=function(){return new T.DataBuffer(this)};T.DataBuffer.prototype.compact=function(){if(this.read>0){var e=new Uint8Array(this.data.buffer,this.read),t=new Uint8Array(e.byteLength);t.set(e),this.data=new DataView(t),this.write-=this.read,this.read=0}return this};T.DataBuffer.prototype.clear=function(){return this.data=new DataView(new ArrayBuffer(0)),this.read=this.write=0,this};T.DataBuffer.prototype.truncate=function(e){return this.write=Math.max(0,this.length()-e),this.read=Math.min(this.read,this.write),this};T.DataBuffer.prototype.toHex=function(){var e="";for(var t=this.read;t<this.data.byteLength;++t){var n=this.data.getUint8(t);if(n<16)e+="0";e+=n.toString(16)}return e};T.DataBuffer.prototype.toString=function(e){var t=new Uint8Array(this.data,this.read,this.length());if(e=e||"utf8",e==="binary"||e==="raw")return T.binary.raw.encode(t);if(e==="hex")return T.binary.hex.encode(t);if(e==="base64")return T.binary.base64.encode(t);if(e==="utf8")return T.text.utf8.decode(t);if(e==="utf16")return T.text.utf16.decode(t);throw Error("Invalid encoding: "+e)};T.createBuffer=function(e,t){if(t=t||"raw",e!==void 0&&t==="utf8")e=T.encodeUtf8(e);return new T.ByteBuffer(e)};T.fillString=function(e,t){var n="";while(t>0){if(t&1)n+=e;if(t>>>=1,t>0)e+=e}return n};T.xorBytes=function(e,t,n){var r="",i="",s="",a=0,o=0;for(;n>0;--n,++a){if(i=e.charCodeAt(a)^t.charCodeAt(a),o>=10)r+=s,s="",o=0;s+=String.fromCharCode(i),++o}return r+=s,r};T.hexToBytes=function(e){var t="",n=0;if(e.length&!0)n=1,t+=String.fromCharCode(parseInt(e[0],16));for(;n<e.length;n+=2)t+=String.fromCharCode(parseInt(e.substr(n,2),16));return t};T.bytesToHex=function(e){return T.createBuffer(e).toHex()};T.int32ToBytes=function(e){return String.fromCharCode(e>>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e&255)};var Nr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",Dr=[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],Zc="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";T.encode64=function(e,t){var n="",r="",i,s,a,o=0;while(o<e.length){if(i=e.charCodeAt(o++),s=e.charCodeAt(o++),a=e.charCodeAt(o++),n+=Nr.charAt(i>>2),n+=Nr.charAt((i&3)<<4|s>>4),isNaN(s))n+="==";else n+=Nr.charAt((s&15)<<2|a>>6),n+=isNaN(a)?"=":Nr.charAt(a&63);if(t&&n.length>t)r+=n.substr(0,t)+`\r
2
+ var l0=Object.create;var{getPrototypeOf:c0,defineProperty:$c,getOwnPropertyNames:u0}=Object;var Wc=Object.prototype.hasOwnProperty;function d0(e){return this[e]}var f0,p0,no=(e,t,n)=>{var r=e!=null&&typeof e==="object";if(r){var i=t?f0??=new WeakMap:p0??=new WeakMap,s=i.get(e);if(s)return s}n=e!=null?l0(c0(e)):{};let a=t||!e||!e.__esModule||!Wc.call(e,"default")?$c(n,"default",{value:e,enumerable:!0}):n;if(e&&typeof e==="object"||typeof e==="function"){for(let o of u0(e))if(!Wc.call(a,o))$c(a,o,{get:d0.bind(e,o),enumerable:!0})}if(r)i.set(e,a);return a};var de=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var ui=import.meta.require;var ye=de(function(i1,jc){jc.exports={options:{usePureJavaScript:!1}}});var Qc=de(function(s1,Xc){var ao={};Xc.exports=ao;var zc={};ao.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=C0(e,t);else{var i=0,s=t.length,a=t.charAt(0),o=[0];for(i=0;i<e.length;++i){for(var l=0,c=e[i];l<o.length;++l)c+=o[l]<<8,o[l]=c%s,c=c/s|0;while(c>0)o.push(c%s),c=c/s|0}for(i=0;e[i]===0&&i<e.length-1;++i)r+=a;for(i=o.length-1;i>=0;--i)r+=t[o[i]]}if(n){var u=new RegExp(".{1,"+n+"}","g");r=r.match(u).join(`\r
3
+ `)}return r};ao.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=zc[t];if(!n){n=zc[t]=[];for(var r=0;r<t.length;++r)n[t.charCodeAt(r)]=r}e=e.replace(/\s/g,"");var i=t.length,s=t.charAt(0),a=[0];for(var r=0;r<e.length;r++){var o=n[e.charCodeAt(r)];if(o===void 0)return;for(var l=0,c=o;l<a.length;++l)c+=a[l]*i,a[l]=c&255,c>>=8;while(c>0)a.push(c&255),c>>=8}for(var u=0;e[u]===s&&u<e.length-1;++u)a.push(0);if(typeof Buffer<"u")return Buffer.from(a.reverse());return new Uint8Array(a.reverse())};function C0(e,t){var n=0,r=t.length,i=t.charAt(0),s=[0];for(n=0;n<e.length();++n){for(var a=0,o=e.at(n);a<s.length;++a)o+=s[a]<<8,s[a]=o%r,o=o/r|0;while(o>0)s.push(o%r),o=o/r|0}var l="";for(n=0;e.at(n)===0&&n<e.length()-1;++n)l+=i;for(n=s.length-1;n>=0;--n)l+=t[s[n]];return l}});var Ne=de(function(a1,eu){var Yc=ye(),Jc=Qc(),T=eu.exports=Yc.util=Yc.util||{};(function(){if(typeof process<"u"&&process.nextTick){if(T.nextTick=process.nextTick,typeof setImmediate==="function")T.setImmediate=setImmediate;else T.setImmediate=T.nextTick;return}if(typeof setImmediate==="function"){T.setImmediate=function(){return setImmediate.apply(void 0,arguments)},T.nextTick=function(o){return setImmediate(o)};return}if(T.setImmediate=function(o){setTimeout(o,0)},typeof window<"u"&&typeof window.postMessage==="function"){let o=function(l){if(l.source===window&&l.data===e){l.stopPropagation();var c=t.slice();t.length=0,c.forEach(function(u){u()})}};var a=o,e="forge.setImmediate",t=[];T.setImmediate=function(l){if(t.push(l),t.length===1)window.postMessage(e,"*")},window.addEventListener("message",o,!0)}if(typeof MutationObserver<"u"){var n=Date.now(),r=!0,i=document.createElement("div"),t=[];new MutationObserver(function(){var l=t.slice();t.length=0,l.forEach(function(c){c()})}).observe(i,{attributes:!0});var s=T.setImmediate;T.setImmediate=function(l){if(Date.now()-n>15)n=Date.now(),s(l);else if(t.push(l),t.length===1)i.setAttribute("a",r=!r)}}T.nextTick=T.setImmediate})();T.isNodejs=typeof process<"u"&&process.versions&&process.versions.node;T.globalScope=function(){if(T.isNodejs)return global;return typeof self>"u"?window:self}();T.isArray=Array.isArray||function(e){return Object.prototype.toString.call(e)==="[object Array]"};T.isArrayBuffer=function(e){return typeof ArrayBuffer<"u"&&e instanceof ArrayBuffer};T.isArrayBufferView=function(e){return e&&T.isArrayBuffer(e.buffer)&&e.byteLength!==void 0};function mi(e){if(!(e===8||e===16||e===24||e===32))throw Error("Only 8, 16, 24, or 32 bits supported: "+e)}T.ByteBuffer=oo;function oo(e){if(this.data="",this.read=0,typeof e==="string")this.data=e;else if(T.isArrayBuffer(e)||T.isArrayBufferView(e))if(typeof Buffer<"u"&&e instanceof Buffer)this.data=e.toString("binary");else{var t=new Uint8Array(e);try{this.data=String.fromCharCode.apply(null,t)}catch(r){for(var n=0;n<t.length;++n)this.putByte(t[n])}}else if(e instanceof oo||typeof e==="object"&&typeof e.data==="string"&&typeof e.read==="number")this.data=e.data,this.read=e.read;this._constructedStringLength=0}T.ByteStringBuffer=oo;var w0=4096;T.ByteStringBuffer.prototype._optimizeConstructedString=function(e){if(this._constructedStringLength+=e,this._constructedStringLength>w0)this.data.substr(0,1),this._constructedStringLength=0};T.ByteStringBuffer.prototype.length=function(){return this.data.length-this.read};T.ByteStringBuffer.prototype.isEmpty=function(){return this.length()<=0};T.ByteStringBuffer.prototype.putByte=function(e){return this.putBytes(String.fromCharCode(e))};T.ByteStringBuffer.prototype.fillWithByte=function(e,t){e=String.fromCharCode(e);var n=this.data;while(t>0){if(t&1)n+=e;if(t>>>=1,t>0)e+=e}return this.data=n,this._optimizeConstructedString(t),this};T.ByteStringBuffer.prototype.putBytes=function(e){return this.data+=e,this._optimizeConstructedString(e.length),this};T.ByteStringBuffer.prototype.putString=function(e){return this.putBytes(T.encodeUtf8(e))};T.ByteStringBuffer.prototype.putInt16=function(e){return this.putBytes(String.fromCharCode(e>>8&255)+String.fromCharCode(e&255))};T.ByteStringBuffer.prototype.putInt24=function(e){return this.putBytes(String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e&255))};T.ByteStringBuffer.prototype.putInt32=function(e){return this.putBytes(String.fromCharCode(e>>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e&255))};T.ByteStringBuffer.prototype.putInt16Le=function(e){return this.putBytes(String.fromCharCode(e&255)+String.fromCharCode(e>>8&255))};T.ByteStringBuffer.prototype.putInt24Le=function(e){return this.putBytes(String.fromCharCode(e&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e>>16&255))};T.ByteStringBuffer.prototype.putInt32Le=function(e){return this.putBytes(String.fromCharCode(e&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>24&255))};T.ByteStringBuffer.prototype.putInt=function(e,t){mi(t);var n="";do t-=8,n+=String.fromCharCode(e>>t&255);while(t>0);return this.putBytes(n)};T.ByteStringBuffer.prototype.putSignedInt=function(e,t){if(e<0)e+=2<<t-1;return this.putInt(e,t)};T.ByteStringBuffer.prototype.putBuffer=function(e){return this.putBytes(e.getBytes())};T.ByteStringBuffer.prototype.getByte=function(){return this.data.charCodeAt(this.read++)};T.ByteStringBuffer.prototype.getInt16=function(){var e=this.data.charCodeAt(this.read)<<8^this.data.charCodeAt(this.read+1);return this.read+=2,e};T.ByteStringBuffer.prototype.getInt24=function(){var e=this.data.charCodeAt(this.read)<<16^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2);return this.read+=3,e};T.ByteStringBuffer.prototype.getInt32=function(){var e=this.data.charCodeAt(this.read)<<24^this.data.charCodeAt(this.read+1)<<16^this.data.charCodeAt(this.read+2)<<8^this.data.charCodeAt(this.read+3);return this.read+=4,e};T.ByteStringBuffer.prototype.getInt16Le=function(){var e=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8;return this.read+=2,e};T.ByteStringBuffer.prototype.getInt24Le=function(){var e=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2)<<16;return this.read+=3,e};T.ByteStringBuffer.prototype.getInt32Le=function(){var e=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2)<<16^this.data.charCodeAt(this.read+3)<<24;return this.read+=4,e};T.ByteStringBuffer.prototype.getInt=function(e){mi(e);var t=0;do t=(t<<8)+this.data.charCodeAt(this.read++),e-=8;while(e>0);return t};T.ByteStringBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),n=2<<e-2;if(t>=n)t-=n<<1;return t};T.ByteStringBuffer.prototype.getBytes=function(e){var t;if(e)e=Math.min(this.length(),e),t=this.data.slice(this.read,this.read+e),this.read+=e;else if(e===0)t="";else t=this.read===0?this.data:this.data.slice(this.read),this.clear();return t};T.ByteStringBuffer.prototype.bytes=function(e){return typeof e>"u"?this.data.slice(this.read):this.data.slice(this.read,this.read+e)};T.ByteStringBuffer.prototype.at=function(e){return this.data.charCodeAt(this.read+e)};T.ByteStringBuffer.prototype.setAt=function(e,t){return this.data=this.data.substr(0,this.read+e)+String.fromCharCode(t)+this.data.substr(this.read+e+1),this};T.ByteStringBuffer.prototype.last=function(){return this.data.charCodeAt(this.data.length-1)};T.ByteStringBuffer.prototype.copy=function(){var e=T.createBuffer(this.data);return e.read=this.read,e};T.ByteStringBuffer.prototype.compact=function(){if(this.read>0)this.data=this.data.slice(this.read),this.read=0;return this};T.ByteStringBuffer.prototype.clear=function(){return this.data="",this.read=0,this};T.ByteStringBuffer.prototype.truncate=function(e){var t=Math.max(0,this.length()-e);return this.data=this.data.substr(this.read,t),this.read=0,this};T.ByteStringBuffer.prototype.toHex=function(){var e="";for(var t=this.read;t<this.data.length;++t){var n=this.data.charCodeAt(t);if(n<16)e+="0";e+=n.toString(16)}return e};T.ByteStringBuffer.prototype.toString=function(){return T.decodeUtf8(this.bytes())};function E0(e,t){t=t||{},this.read=t.readOffset||0,this.growSize=t.growSize||1024;var n=T.isArrayBuffer(e),r=T.isArrayBufferView(e);if(n||r){if(n)this.data=new DataView(e);else this.data=new DataView(e.buffer,e.byteOffset,e.byteLength);this.write="writeOffset"in t?t.writeOffset:this.data.byteLength;return}if(this.data=new DataView(new ArrayBuffer(0)),this.write=0,e!==null&&e!==void 0)this.putBytes(e);if("writeOffset"in t)this.write=t.writeOffset}T.DataBuffer=E0;T.DataBuffer.prototype.length=function(){return this.write-this.read};T.DataBuffer.prototype.isEmpty=function(){return this.length()<=0};T.DataBuffer.prototype.accommodate=function(e,t){if(this.length()>=e)return this;t=Math.max(t||this.growSize,e);var n=new Uint8Array(this.data.buffer,this.data.byteOffset,this.data.byteLength),r=new Uint8Array(this.length()+t);return r.set(n),this.data=new DataView(r.buffer),this};T.DataBuffer.prototype.putByte=function(e){return this.accommodate(1),this.data.setUint8(this.write++,e),this};T.DataBuffer.prototype.fillWithByte=function(e,t){this.accommodate(t);for(var n=0;n<t;++n)this.data.setUint8(e);return this};T.DataBuffer.prototype.putBytes=function(e,t){if(T.isArrayBufferView(e)){var n=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r=n.byteLength-n.byteOffset;this.accommodate(r);var i=new Uint8Array(this.data.buffer,this.write);return i.set(n),this.write+=r,this}if(T.isArrayBuffer(e)){var n=new Uint8Array(e);this.accommodate(n.byteLength);var i=new Uint8Array(this.data.buffer);return i.set(n,this.write),this.write+=n.byteLength,this}if(e instanceof T.DataBuffer||typeof e==="object"&&typeof e.read==="number"&&typeof e.write==="number"&&T.isArrayBufferView(e.data)){var n=new Uint8Array(e.data.byteLength,e.read,e.length());this.accommodate(n.byteLength);var i=new Uint8Array(e.data.byteLength,this.write);return i.set(n),this.write+=n.byteLength,this}if(e instanceof T.ByteStringBuffer)e=e.data,t="binary";if(t=t||"binary",typeof e==="string"){var s;if(t==="hex")return this.accommodate(Math.ceil(e.length/2)),s=new Uint8Array(this.data.buffer,this.write),this.write+=T.binary.hex.decode(e,s,this.write),this;if(t==="base64")return this.accommodate(Math.ceil(e.length/4)*3),s=new Uint8Array(this.data.buffer,this.write),this.write+=T.binary.base64.decode(e,s,this.write),this;if(t==="utf8")e=T.encodeUtf8(e),t="binary";if(t==="binary"||t==="raw")return this.accommodate(e.length),s=new Uint8Array(this.data.buffer,this.write),this.write+=T.binary.raw.decode(s),this;if(t==="utf16")return this.accommodate(e.length*2),s=new Uint16Array(this.data.buffer,this.write),this.write+=T.text.utf16.encode(s),this;throw Error("Invalid encoding: "+t)}throw Error("Invalid parameter: "+e)};T.DataBuffer.prototype.putBuffer=function(e){return this.putBytes(e),e.clear(),this};T.DataBuffer.prototype.putString=function(e){return this.putBytes(e,"utf16")};T.DataBuffer.prototype.putInt16=function(e){return this.accommodate(2),this.data.setInt16(this.write,e),this.write+=2,this};T.DataBuffer.prototype.putInt24=function(e){return this.accommodate(3),this.data.setInt16(this.write,e>>8&65535),this.data.setInt8(this.write,e>>16&255),this.write+=3,this};T.DataBuffer.prototype.putInt32=function(e){return this.accommodate(4),this.data.setInt32(this.write,e),this.write+=4,this};T.DataBuffer.prototype.putInt16Le=function(e){return this.accommodate(2),this.data.setInt16(this.write,e,!0),this.write+=2,this};T.DataBuffer.prototype.putInt24Le=function(e){return this.accommodate(3),this.data.setInt8(this.write,e>>16&255),this.data.setInt16(this.write,e>>8&65535,!0),this.write+=3,this};T.DataBuffer.prototype.putInt32Le=function(e){return this.accommodate(4),this.data.setInt32(this.write,e,!0),this.write+=4,this};T.DataBuffer.prototype.putInt=function(e,t){mi(t),this.accommodate(t/8);do t-=8,this.data.setInt8(this.write++,e>>t&255);while(t>0);return this};T.DataBuffer.prototype.putSignedInt=function(e,t){if(mi(t),this.accommodate(t/8),e<0)e+=2<<t-1;return this.putInt(e,t)};T.DataBuffer.prototype.getByte=function(){return this.data.getInt8(this.read++)};T.DataBuffer.prototype.getInt16=function(){var e=this.data.getInt16(this.read);return this.read+=2,e};T.DataBuffer.prototype.getInt24=function(){var e=this.data.getInt16(this.read)<<8^this.data.getInt8(this.read+2);return this.read+=3,e};T.DataBuffer.prototype.getInt32=function(){var e=this.data.getInt32(this.read);return this.read+=4,e};T.DataBuffer.prototype.getInt16Le=function(){var e=this.data.getInt16(this.read,!0);return this.read+=2,e};T.DataBuffer.prototype.getInt24Le=function(){var e=this.data.getInt8(this.read)^this.data.getInt16(this.read+1,!0)<<8;return this.read+=3,e};T.DataBuffer.prototype.getInt32Le=function(){var e=this.data.getInt32(this.read,!0);return this.read+=4,e};T.DataBuffer.prototype.getInt=function(e){mi(e);var t=0;do t=(t<<8)+this.data.getInt8(this.read++),e-=8;while(e>0);return t};T.DataBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),n=2<<e-2;if(t>=n)t-=n<<1;return t};T.DataBuffer.prototype.getBytes=function(e){var t;if(e)e=Math.min(this.length(),e),t=this.data.slice(this.read,this.read+e),this.read+=e;else if(e===0)t="";else t=this.read===0?this.data:this.data.slice(this.read),this.clear();return t};T.DataBuffer.prototype.bytes=function(e){return typeof e>"u"?this.data.slice(this.read):this.data.slice(this.read,this.read+e)};T.DataBuffer.prototype.at=function(e){return this.data.getUint8(this.read+e)};T.DataBuffer.prototype.setAt=function(e,t){return this.data.setUint8(e,t),this};T.DataBuffer.prototype.last=function(){return this.data.getUint8(this.write-1)};T.DataBuffer.prototype.copy=function(){return new T.DataBuffer(this)};T.DataBuffer.prototype.compact=function(){if(this.read>0){var e=new Uint8Array(this.data.buffer,this.read),t=new Uint8Array(e.byteLength);t.set(e),this.data=new DataView(t),this.write-=this.read,this.read=0}return this};T.DataBuffer.prototype.clear=function(){return this.data=new DataView(new ArrayBuffer(0)),this.read=this.write=0,this};T.DataBuffer.prototype.truncate=function(e){return this.write=Math.max(0,this.length()-e),this.read=Math.min(this.read,this.write),this};T.DataBuffer.prototype.toHex=function(){var e="";for(var t=this.read;t<this.data.byteLength;++t){var n=this.data.getUint8(t);if(n<16)e+="0";e+=n.toString(16)}return e};T.DataBuffer.prototype.toString=function(e){var t=new Uint8Array(this.data,this.read,this.length());if(e=e||"utf8",e==="binary"||e==="raw")return T.binary.raw.encode(t);if(e==="hex")return T.binary.hex.encode(t);if(e==="base64")return T.binary.base64.encode(t);if(e==="utf8")return T.text.utf8.decode(t);if(e==="utf16")return T.text.utf16.decode(t);throw Error("Invalid encoding: "+e)};T.createBuffer=function(e,t){if(t=t||"raw",e!==void 0&&t==="utf8")e=T.encodeUtf8(e);return new T.ByteBuffer(e)};T.fillString=function(e,t){var n="";while(t>0){if(t&1)n+=e;if(t>>>=1,t>0)e+=e}return n};T.xorBytes=function(e,t,n){var r="",i="",s="",a=0,o=0;for(;n>0;--n,++a){if(i=e.charCodeAt(a)^t.charCodeAt(a),o>=10)r+=s,s="",o=0;s+=String.fromCharCode(i),++o}return r+=s,r};T.hexToBytes=function(e){var t="",n=0;if(e.length&!0)n=1,t+=String.fromCharCode(parseInt(e[0],16));for(;n<e.length;n+=2)t+=String.fromCharCode(parseInt(e.substr(n,2),16));return t};T.bytesToHex=function(e){return T.createBuffer(e).toHex()};T.int32ToBytes=function(e){return String.fromCharCode(e>>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e&255)};var Nr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",Dr=[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],Zc="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";T.encode64=function(e,t){var n="",r="",i,s,a,o=0;while(o<e.length){if(i=e.charCodeAt(o++),s=e.charCodeAt(o++),a=e.charCodeAt(o++),n+=Nr.charAt(i>>2),n+=Nr.charAt((i&3)<<4|s>>4),isNaN(s))n+="==";else n+=Nr.charAt((s&15)<<2|a>>6),n+=isNaN(a)?"=":Nr.charAt(a&63);if(t&&n.length>t)r+=n.substr(0,t)+`\r
4
4
  `,n=n.substr(t)}return r+=n,r};T.decode64=function(e){e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");var t="",n,r,i,s,a=0;while(a<e.length)if(n=Dr[e.charCodeAt(a++)-43],r=Dr[e.charCodeAt(a++)-43],i=Dr[e.charCodeAt(a++)-43],s=Dr[e.charCodeAt(a++)-43],t+=String.fromCharCode(n<<2|r>>4),i!==64){if(t+=String.fromCharCode((r&15)<<4|i>>2),s!==64)t+=String.fromCharCode((i&3)<<6|s)}return t};T.encodeUtf8=function(e){return unescape(encodeURIComponent(e))};T.decodeUtf8=function(e){return decodeURIComponent(escape(e))};T.binary={raw:{},hex:{},base64:{},base58:{},baseN:{encode:Jc.encode,decode:Jc.decode}};T.binary.raw.encode=function(e){return String.fromCharCode.apply(null,e)};T.binary.raw.decode=function(e,t,n){var r=t;if(!r)r=new Uint8Array(e.length);n=n||0;var i=n;for(var s=0;s<e.length;++s)r[i++]=e.charCodeAt(s);return t?i-n:r};T.binary.hex.encode=T.bytesToHex;T.binary.hex.decode=function(e,t,n){var r=t;if(!r)r=new Uint8Array(Math.ceil(e.length/2));n=n||0;var i=0,s=n;if(e.length&1)i=1,r[s++]=parseInt(e[0],16);for(;i<e.length;i+=2)r[s++]=parseInt(e.substr(i,2),16);return t?s-n:r};T.binary.base64.encode=function(e,t){var n="",r="",i,s,a,o=0;while(o<e.byteLength){if(i=e[o++],s=e[o++],a=e[o++],n+=Nr.charAt(i>>2),n+=Nr.charAt((i&3)<<4|s>>4),isNaN(s))n+="==";else n+=Nr.charAt((s&15)<<2|a>>6),n+=isNaN(a)?"=":Nr.charAt(a&63);if(t&&n.length>t)r+=n.substr(0,t)+`\r
5
- `,n=n.substr(t)}return r+=n,r};T.binary.base64.decode=function(e,t,n){var r=t;if(!r)r=new Uint8Array(Math.ceil(e.length/4)*3);e=e.replace(/[^A-Za-z0-9\+\/\=]/g,""),n=n||0;var i,s,a,o,l=0,c=n;while(l<e.length)if(i=Dr[e.charCodeAt(l++)-43],s=Dr[e.charCodeAt(l++)-43],a=Dr[e.charCodeAt(l++)-43],o=Dr[e.charCodeAt(l++)-43],r[c++]=i<<2|s>>4,a!==64){if(r[c++]=(s&15)<<4|a>>2,o!==64)r[c++]=(a&3)<<6|o}return t?c-n:r.subarray(0,c)};T.binary.base58.encode=function(e,t){return T.binary.baseN.encode(e,Zc,t)};T.binary.base58.decode=function(e,t){return T.binary.baseN.decode(e,Zc,t)};T.text={utf8:{},utf16:{}};T.text.utf8.encode=function(e,t,n){e=T.encodeUtf8(e);var r=t;if(!r)r=new Uint8Array(e.length);n=n||0;var i=n;for(var s=0;s<e.length;++s)r[i++]=e.charCodeAt(s);return t?i-n:r};T.text.utf8.decode=function(e){return T.decodeUtf8(String.fromCharCode.apply(null,e))};T.text.utf16.encode=function(e,t,n){var r=t;if(!r)r=new Uint8Array(e.length*2);var i=new Uint16Array(r.buffer);n=n||0;var s=n,a=n;for(var o=0;o<e.length;++o)i[a++]=e.charCodeAt(o),s+=2;return t?s-n:r};T.text.utf16.decode=function(e){return String.fromCharCode.apply(null,new Uint16Array(e.buffer))};T.deflate=function(e,t,n){if(t=T.decode64(e.deflate(T.encode64(t)).rval),n){var r=2,i=t.charCodeAt(1);if(i&32)r=6;t=t.substring(r,t.length-4)}return t};T.inflate=function(e,t,n){var r=e.inflate(T.encode64(t)).rval;return r===null?null:T.decode64(r)};var lo=function(e,t,n){if(!e)throw Error("WebStorage not available.");var r;if(n===null)r=e.removeItem(t);else n=T.encode64(JSON.stringify(n)),r=e.setItem(t,n);if(typeof r<"u"&&r.rval!==!0){var i=Error(r.error.message);throw i.id=r.error.id,i.name=r.error.name,i}},co=function(e,t){if(!e)throw Error("WebStorage not available.");var n=e.getItem(t);if(e.init)if(n.rval===null){if(n.error){var r=Error(n.error.message);throw r.id=n.error.id,r.name=n.error.name,r}n=null}else n=n.rval;if(n!==null)n=JSON.parse(T.decode64(n));return n},A0=function(e,t,n,r){var i=co(e,t);if(i===null)i={};i[n]=r,lo(e,t,i)},_0=function(e,t,n){var r=co(e,t);if(r!==null)r=n in r?r[n]:null;return r},k0=function(e,t,n){var r=co(e,t);if(r!==null&&n in r){delete r[n];var i=!0;for(var s in r){i=!1;break}if(i)r=null;lo(e,t,r)}},I0=function(e,t){lo(e,t,null)},_s=function(e,t,n){var r=null;if(typeof n>"u")n=["web","flash"];var i,s=!1,a=null;for(var o in n){i=n[o];try{if(i==="flash"||i==="both"){if(t[0]===null)throw Error("Flash local storage not available.");r=e.apply(this,t),s=i==="flash"}if(i==="web"||i==="both")t[0]=localStorage,r=e.apply(this,t),s=!0}catch(l){a=l}if(s)break}if(!s)throw a;return r};T.setItem=function(e,t,n,r,i){_s(A0,arguments,i)};T.getItem=function(e,t,n,r){return _s(_0,arguments,r)};T.removeItem=function(e,t,n,r){_s(k0,arguments,r)};T.clearItems=function(e,t,n){_s(I0,arguments,n)};T.isEmpty=function(e){for(var t in e)if(e.hasOwnProperty(t))return!1;return!0};T.format=function(e){var t=/%./g,n,r,i=0,s=[],a=0;while(n=t.exec(e)){if(r=e.substring(a,t.lastIndex-2),r.length>0)s.push(r);a=t.lastIndex;var o=n[0][1];switch(o){case"s":case"o":if(i<arguments.length)s.push(arguments[i+++1]);else s.push("<?>");break;case"%":s.push("%");break;default:s.push("<%"+o+"?>")}}return s.push(e.substring(a)),s.join("")};T.formatNumber=function(e,t,n,r){var i=e,s=isNaN(t=Math.abs(t))?2:t,a=n===void 0?",":n,o=r===void 0?".":r,l=i<0?"-":"",c=parseInt(i=Math.abs(+i||0).toFixed(s),10)+"",u=c.length>3?c.length%3:0;return l+(u?c.substr(0,u)+o:"")+c.substr(u).replace(/(\d{3})(?=\d)/g,"$1"+o)+(s?a+Math.abs(i-c).toFixed(s).slice(2):"")};T.formatSize=function(e){if(e>=1073741824)e=T.formatNumber(e/1073741824,2,".","")+" GiB";else if(e>=1048576)e=T.formatNumber(e/1048576,2,".","")+" MiB";else if(e>=1024)e=T.formatNumber(e/1024,0)+" KiB";else e=T.formatNumber(e,0)+" bytes";return e};T.bytesFromIP=function(e){if(e.indexOf(".")!==-1)return T.bytesFromIPv4(e);if(e.indexOf(":")!==-1)return T.bytesFromIPv6(e);return null};T.bytesFromIPv4=function(e){if(e=e.split("."),e.length!==4)return null;var t=T.createBuffer();for(var n=0;n<e.length;++n){var r=parseInt(e[n],10);if(isNaN(r))return null;t.putByte(r)}return t.getBytes()};T.bytesFromIPv6=function(e){var t=0;e=e.split(":").filter(function(a){if(a.length===0)++t;return!0});var n=(8-e.length+t)*2,r=T.createBuffer();for(var i=0;i<8;++i){if(!e[i]||e[i].length===0){r.fillWithByte(0,n),n=0;continue}var s=T.hexToBytes(e[i]);if(s.length<2)r.putByte(0);r.putBytes(s)}return r.getBytes()};T.bytesToIP=function(e){if(e.length===4)return T.bytesToIPv4(e);if(e.length===16)return T.bytesToIPv6(e);return null};T.bytesToIPv4=function(e){if(e.length!==4)return null;var t=[];for(var n=0;n<e.length;++n)t.push(e.charCodeAt(n));return t.join(".")};T.bytesToIPv6=function(e){if(e.length!==16)return null;var t=[],n=[],r=0;for(var i=0;i<e.length;i+=2){var s=T.bytesToHex(e[i]+e[i+1]);while(s[0]==="0"&&s!=="0")s=s.substr(1);if(s==="0"){var a=n[n.length-1],o=t.length;if(!a||o!==a.end+1)n.push({start:o,end:o});else if(a.end=o,a.end-a.start>n[r].end-n[r].start)r=n.length-1}t.push(s)}if(n.length>0){var l=n[r];if(l.end-l.start>0){if(t.splice(l.start,l.end-l.start+1,""),l.start===0)t.unshift("");if(l.end===7)t.push("")}}return t.join(":")};T.estimateCores=function(e,t){if(typeof e==="function")t=e,e={};if(e=e||{},"cores"in T&&!e.update)return t(null,T.cores);if(typeof navigator<"u"&&"hardwareConcurrency"in navigator&&navigator.hardwareConcurrency>0)return T.cores=navigator.hardwareConcurrency,t(null,T.cores);if(typeof Worker>"u")return T.cores=1,t(null,T.cores);if(typeof Blob>"u")return T.cores=2,t(null,T.cores);var n=URL.createObjectURL(new Blob(["(",function(){self.addEventListener("message",function(a){var o=Date.now(),l=o+4;while(Date.now()<l);self.postMessage({st:o,et:l})})}.toString(),")()"],{type:"application/javascript"}));r([],5,16);function r(a,o,l){if(o===0){var c=Math.floor(a.reduce(function(u,d){return u+d},0)/a.length);return T.cores=Math.max(1,c),URL.revokeObjectURL(n),t(null,T.cores)}i(l,function(u,d){a.push(s(l,d)),r(a,o-1,l)})}function i(a,o){var l=[],c=[];for(var u=0;u<a;++u){var d=new Worker(n);d.addEventListener("message",function(p){if(c.push(p.data),c.length===a){for(var h=0;h<a;++h)l[h].terminate();o(null,c)}}),l.push(d)}for(var u=0;u<a;++u)l[u].postMessage(u)}function s(a,o){var l=[];for(var c=0;c<a;++c){var u=o[c],d=l[c]=[];for(var p=0;p<a;++p){if(c===p)continue;var h=o[p];if(u.st>h.st&&u.st<h.et||h.st>u.st&&h.st<u.et)d.push(p)}}return l.reduce(function(f,v){return Math.max(f,v.length)},0)}}});var ks=de(function(l1,tu){var ut=ve();Pe();tu.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 uo=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)};uo.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)};uo.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()};uo.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 po=de(function(c1,ru){var dt=ve();Pe();dt.cipher=dt.cipher||{};var we=ru.exports=dt.cipher.modes=dt.cipher.modes||{};we.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)};we.ecb.prototype.start=function(e){};we.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])};we.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])};we.ecb.prototype.pad=function(e,t){var n=e.length()===this.blockSize?this.blockSize:this.blockSize-e.length();return e.fillWithByte(n,n),!0};we.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};we.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)};we.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=Is(e.iv,this.blockSize),this._prev=this._iv.slice(0)};we.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};we.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)};we.cbc.prototype.pad=function(e,t){var n=e.length()===this.blockSize?this.blockSize:this.blockSize-e.length();return e.fillWithByte(n,n),!0};we.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};we.cfb=function(e){e=e||{},this.name="CFB",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=Array(this._ints),this._partialBlock=Array(this._ints),this._partialOutput=dt.util.createBuffer(),this._partialBytes=0};we.cfb.prototype.start=function(e){if(!("iv"in e))throw Error("Invalid IV parameter.");this._iv=Is(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0};we.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 s=(this.blockSize-r)%this.blockSize;if(s>0)s=this.blockSize-s;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(s>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(s>0&&!n)return t.putBytes(this._partialOutput.getBytes(s-this._partialBytes)),this._partialBytes=s,!0;t.putBytes(this._partialOutput.getBytes(r-this._partialBytes)),this._partialBytes=0};we.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 s=(this.blockSize-r)%this.blockSize;if(s>0)s=this.blockSize-s;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(s>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(s>0&&!n)return t.putBytes(this._partialOutput.getBytes(s-this._partialBytes)),this._partialBytes=s,!0;t.putBytes(this._partialOutput.getBytes(r-this._partialBytes)),this._partialBytes=0};we.ofb=function(e){e=e||{},this.name="OFB",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=Array(this._ints),this._partialOutput=dt.util.createBuffer(),this._partialBytes=0};we.ofb.prototype.start=function(e){if(!("iv"in e))throw Error("Invalid IV parameter.");this._iv=Is(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0};we.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 s=(this.blockSize-r)%this.blockSize;if(s>0)s=this.blockSize-s;this._partialOutput.clear();for(var i=0;i<this._ints;++i)this._partialOutput.putInt32(e.getInt32()^this._outBlock[i]);if(s>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(s>0&&!n)return t.putBytes(this._partialOutput.getBytes(s-this._partialBytes)),this._partialBytes=s,!0;t.putBytes(this._partialOutput.getBytes(r-this._partialBytes)),this._partialBytes=0};we.ofb.prototype.decrypt=we.ofb.prototype.encrypt;we.ctr=function(e){e=e||{},this.name="CTR",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=Array(this._ints),this._partialOutput=dt.util.createBuffer(),this._partialBytes=0};we.ctr.prototype.start=function(e){if(!("iv"in e))throw Error("Invalid IV parameter.");this._iv=Is(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0};we.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 s=(this.blockSize-r)%this.blockSize;if(s>0)s=this.blockSize-s;this._partialOutput.clear();for(var i=0;i<this._ints;++i)this._partialOutput.putInt32(e.getInt32()^this._outBlock[i]);if(s>0)e.read-=this.blockSize;if(this._partialBytes>0)this._partialOutput.getBytes(this._partialBytes);if(s>0&&!n)return t.putBytes(this._partialOutput.getBytes(s-this._partialBytes)),this._partialBytes=s,!0;t.putBytes(this._partialOutput.getBytes(r-this._partialBytes)),this._partialBytes=0}Rs(this._inBlock)};we.ctr.prototype.decrypt=we.ctr.prototype.encrypt;we.gcm=function(e){e=e||{},this.name="GCM",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=Array(this._ints),this._outBlock=Array(this._ints),this._partialOutput=dt.util.createBuffer(),this._partialBytes=0,this._R=3774873600};we.gcm.prototype.start=function(e){if(!("iv"in e))throw Error("Invalid IV parameter.");var t=dt.util.createBuffer(e.iv);this._cipherLength=0;var n;if("additionalData"in e)n=dt.util.createBuffer(e.additionalData);else n=dt.util.createBuffer();if(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=dt.util.createBuffer(e.tag).getBytes(),this._tag.length!==this._tagLength/8)throw Error("Authentication tag does not match tag length.")}this._hashBlock=Array(this._ints),this.tag=null,this._hashSubkey=Array(this._ints),this.cipher.encrypt([0,0,0,0],this._hashSubkey),this.componentBits=4,this._m=this.generateHashTable(this._hashSubkey,this.componentBits);var r=t.length();if(r===12)this._j0=[t.getInt32(),t.getInt32(),t.getInt32(),1];else{this._j0=[0,0,0,0];while(t.length()>0)this._j0=this.ghash(this._hashSubkey,this._j0,[t.getInt32(),t.getInt32(),t.getInt32(),t.getInt32()]);this._j0=this.ghash(this._hashSubkey,this._j0,[0,0].concat(fo(r*8)))}this._inBlock=this._j0.slice(0),Rs(this._inBlock),this._partialBytes=0,n=dt.util.createBuffer(n),this._aDataLength=fo(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()])};we.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 s=(this.blockSize-r)%this.blockSize;if(s>0)s=this.blockSize-s;this._partialOutput.clear();for(var i=0;i<this._ints;++i)this._partialOutput.putInt32(e.getInt32()^this._outBlock[i]);if(s<=0||n){if(n){var a=r%this.blockSize;this._cipherLength+=a,this._partialOutput.truncate(this.blockSize-a)}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(s>0&&!n)return e.read-=this.blockSize,t.putBytes(this._partialOutput.getBytes(s-this._partialBytes)),this._partialBytes=s,!0;t.putBytes(this._partialOutput.getBytes(r-this._partialBytes)),this._partialBytes=0}this._s=this.ghash(this._hashSubkey,this._s,this._outBlock),Rs(this._inBlock)};we.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),Rs(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};we.gcm.prototype.afterFinish=function(e,t){var n=!0;if(t.decrypt&&t.overflow)e.truncate(this.blockSize-t.overflow);this.tag=dt.util.createBuffer();var r=this._aDataLength.concat(fo(this._cipherLength*8));this._s=this.ghash(this._hashSubkey,this._s,r);var i=[];this.cipher.encrypt(this._j0,i);for(var s=0;s<this._ints;++s)this.tag.putInt32(this._s[s]^i[s]);if(this.tag.truncate(this.tag.length()%(this._tagLength/8)),t.decrypt&&this.tag.bytes()!==this._tag)n=!1;return n};we.gcm.prototype.multiply=function(e,t){var n=[0,0,0,0],r=t.slice(0);for(var i=0;i<128;++i){var s=e[i/32|0]&1<<31-i%32;if(s)n[0]^=r[0],n[1]^=r[1],n[2]^=r[2],n[3]^=r[3];this.pow(r,r)}return n};we.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};we.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,s=this._m[n][i];t[0]^=s[0],t[1]^=s[1],t[2]^=s[2],t[3]^=s[3]}return t};we.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)};we.gcm.prototype.generateHashTable=function(e,t){var n=8/t,r=4*n,i=16*n,s=Array(i);for(var a=0;a<i;++a){var o=[0,0,0,0],l=a/r|0,c=(r-1-a%r)*t;o[l]=1<<t-1<<c,s[a]=this.generateSubHashTable(this.multiply(o,e),t)}return s};we.gcm.prototype.generateSubHashTable=function(e,t){var n=1<<t,r=n>>>1,i=Array(n);i[r]=e.slice(0);var s=r>>>1;while(s>0)this.pow(i[2*s],i[s]=[]),s>>=1;s=2;while(s<r){for(var a=1;a<s;++a){var o=i[s],l=i[a];i[s+a]=[o[0]^l[0],o[1]^l[1],o[2]^l[2],o[3]^l[3]]}s*=2}i[0]=[0,0,0,0];for(s=r+1;s<n;++s){var c=i[s^r];i[s]=[e[0]^c[0],e[1]^c[1],e[2]^c[2],e[3]^c[3]]}return i};function Is(e,t){if(typeof e==="string")e=dt.util.createBuffer(e);if(dt.util.isArray(e)&&e.length>4){var n=e;e=dt.util.createBuffer();for(var r=0;r<n.length;++r)e.putByte(n[r])}if(e.length()<t)throw Error("Invalid IV length; got "+e.length()+" bytes and expected "+t+" bytes.");if(!dt.util.isArray(e)){var i=[],s=t/4;for(var r=0;r<s;++r)i.push(e.getInt32());e=i}return e}function Rs(e){e[e.length-1]=e[e.length-1]+1&4294967295}function fo(e){return[e/4294967296|0,e&4294967295]}});var Lr=de(function(u1,au){var He=ve();ks();po();Pe();au.exports=He.aes=He.aes||{};He.aes.startEncrypting=function(e,t,n,r){var i=Bs({key:e,output:n,decrypt:!1,mode:r});return i.start(t),i};He.aes.createEncryptionCipher=function(e,t){return Bs({key:e,output:null,decrypt:!1,mode:t})};He.aes.startDecrypting=function(e,t,n,r){var i=Bs({key:e,output:n,decrypt:!0,mode:r});return i.start(t),i};He.aes.createDecryptionCipher=function(e,t){return Bs({key:e,output:null,decrypt:!0,mode:t})};He.aes.Algorithm=function(e,t){if(!mo)iu();var n=this;n.name=e,n.mode=new t({blockSize:16,cipher:{encrypt:function(r,i){return go(n._w,r,i,!1)},decrypt:function(r,i){return go(n._w,r,i,!0)}}}),n._init=!1};He.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=He.util.createBuffer(t);else if(He.util.isArray(t)&&(t.length===16||t.length===24||t.length===32)){n=t,t=He.util.createBuffer();for(var r=0;r<n.length;++r)t.putByte(n[r])}if(!He.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(!He.util.isArray(t)||!(t.length===4||t.length===6||t.length===8))throw Error("Invalid key parameter.");var s=this.mode.name,a=["CFB","OFB","CTR","GCM"].indexOf(s)!==-1;this._w=su(t,e.decrypt&&!a),this._init=!0};He.aes._expandKey=function(e,t){if(!mo)iu();return su(e,t)};He.aes._updateBlock=go;Tn("AES-ECB",He.cipher.modes.ecb);Tn("AES-CBC",He.cipher.modes.cbc);Tn("AES-CFB",He.cipher.modes.cfb);Tn("AES-OFB",He.cipher.modes.ofb);Tn("AES-CTR",He.cipher.modes.ctr);Tn("AES-GCM",He.cipher.modes.gcm);function Tn(e,t){var n=function(){return new He.aes.Algorithm(e,t)};He.cipher.registerAlgorithm(e,n)}var mo=!1,En=4,bt,ho,nu,nn,qt;function iu(){mo=!0,nu=[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),ho=Array(256),nn=[,,,,],qt=[,,,,];for(var t=0;t<4;++t)nn[t]=Array(256),qt[t]=Array(256);var n=0,r=0,i,s,a,o,l,c,u;for(var t=0;t<256;++t){o=r^r<<1^r<<2^r<<3^r<<4,o=o>>8^o&255^99,bt[n]=o,ho[o]=n,l=e[o],i=e[n],s=e[i],a=e[s],c=l<<24^o<<16^o<<8^(o^l),u=(i^s^a)<<24^(n^a)<<16^(n^s^a)<<8^(n^i^a);for(var d=0;d<4;++d)nn[d][n]=c,qt[d][o]=u,c=c<<24|c>>>8,u=u<<24|u>>>8;if(n===0)n=r=1;else n=i^e[e[e[i^a]]],r^=e[e[r]]}}function su(e,t){var n=e.slice(0),r,i=1,s=n.length,a=s+6+1,o=En*a;for(var l=s;l<o;++l){if(r=n[l-1],l%s===0)r=bt[r>>>16&255]<<24^bt[r>>>8&255]<<16^bt[r&255]<<8^bt[r>>>24]^nu[i]<<24,i++;else if(s>6&&l%s===4)r=bt[r>>>24]<<24^bt[r>>>16&255]<<16^bt[r>>>8&255]<<8^bt[r&255];n[l]=n[l-s]^r}if(t){var c,u=qt[0],d=qt[1],p=qt[2],h=qt[3],f=n.slice(0);o=n.length;for(var l=0,v=o-En;l<o;l+=En,v-=En)if(l===0||l===o-En)f[l]=n[v],f[l+1]=n[v+3],f[l+2]=n[v+2],f[l+3]=n[v+1];else for(var x=0;x<En;++x)c=n[v+x],f[l+(3&-x)]=u[bt[c>>>24]]^d[bt[c>>>16&255]]^p[bt[c>>>8&255]]^h[bt[c&255]];n=f}return n}function go(e,t,n,r){var i=e.length/4-1,s,a,o,l,c;if(r)s=qt[0],a=qt[1],o=qt[2],l=qt[3],c=ho;else s=nn[0],a=nn[1],o=nn[2],l=nn[3],c=bt;var u,d,p,h,f,v,x;u=t[0]^e[0],d=t[r?3:1]^e[1],p=t[2]^e[2],h=t[r?1:3]^e[3];var S=3;for(var A=1;A<i;++A)f=s[u>>>24]^a[d>>>16&255]^o[p>>>8&255]^l[h&255]^e[++S],v=s[d>>>24]^a[p>>>16&255]^o[h>>>8&255]^l[u&255]^e[++S],x=s[p>>>24]^a[h>>>16&255]^o[u>>>8&255]^l[d&255]^e[++S],h=s[h>>>24]^a[u>>>16&255]^o[d>>>8&255]^l[p&255]^e[++S],u=f,d=v,p=x;n[0]=c[u>>>24]<<24^c[d>>>16&255]<<16^c[p>>>8&255]<<8^c[h&255]^e[++S],n[r?3:1]=c[d>>>24]<<24^c[p>>>16&255]<<16^c[h>>>8&255]<<8^c[u&255]^e[++S],n[2]=c[p>>>24]<<24^c[h>>>16&255]<<16^c[u>>>8&255]<<8^c[d&255]^e[++S],n[r?1:3]=c[h>>>24]<<24^c[u>>>16&255]<<16^c[d>>>8&255]<<8^c[p&255]^e[++S]}function Bs(e){e=e||{};var t=(e.mode||"CBC").toUpperCase(),n="AES-"+t,r;if(e.decrypt)r=He.cipher.createDecipher(n,e.key);else r=He.cipher.createCipher(n,e.key);var i=r.start;return r.start=function(s,a){var o=null;if(a instanceof He.util.ByteBuffer)o=a,a={};a=a||{},a.output=o,a.iv=s,i.call(r,a)},r}});var Or=de(function(d1,ou){var yi=ve();yi.pki=yi.pki||{};var yo=ou.exports=yi.pki.oids=yi.oids=yi.oids||{};function U(e,t){yo[e]=t,yo[t]=e}function Ue(e,t){yo[e]=t}U("1.2.840.113549.1.1.1","rsaEncryption");U("1.2.840.113549.1.1.4","md5WithRSAEncryption");U("1.2.840.113549.1.1.5","sha1WithRSAEncryption");U("1.2.840.113549.1.1.7","RSAES-OAEP");U("1.2.840.113549.1.1.8","mgf1");U("1.2.840.113549.1.1.9","pSpecified");U("1.2.840.113549.1.1.10","RSASSA-PSS");U("1.2.840.113549.1.1.11","sha256WithRSAEncryption");U("1.2.840.113549.1.1.12","sha384WithRSAEncryption");U("1.2.840.113549.1.1.13","sha512WithRSAEncryption");U("1.3.101.112","EdDSA25519");U("1.2.840.10040.4.3","dsa-with-sha1");U("1.3.14.3.2.7","desCBC");U("1.3.14.3.2.26","sha1");U("1.3.14.3.2.29","sha1WithRSASignature");U("2.16.840.1.101.3.4.2.1","sha256");U("2.16.840.1.101.3.4.2.2","sha384");U("2.16.840.1.101.3.4.2.3","sha512");U("2.16.840.1.101.3.4.2.4","sha224");U("2.16.840.1.101.3.4.2.5","sha512-224");U("2.16.840.1.101.3.4.2.6","sha512-256");U("1.2.840.113549.2.2","md2");U("1.2.840.113549.2.5","md5");U("1.2.840.113549.1.7.1","data");U("1.2.840.113549.1.7.2","signedData");U("1.2.840.113549.1.7.3","envelopedData");U("1.2.840.113549.1.7.4","signedAndEnvelopedData");U("1.2.840.113549.1.7.5","digestedData");U("1.2.840.113549.1.7.6","encryptedData");U("1.2.840.113549.1.9.1","emailAddress");U("1.2.840.113549.1.9.2","unstructuredName");U("1.2.840.113549.1.9.3","contentType");U("1.2.840.113549.1.9.4","messageDigest");U("1.2.840.113549.1.9.5","signingTime");U("1.2.840.113549.1.9.6","counterSignature");U("1.2.840.113549.1.9.7","challengePassword");U("1.2.840.113549.1.9.8","unstructuredAddress");U("1.2.840.113549.1.9.14","extensionRequest");U("1.2.840.113549.1.9.20","friendlyName");U("1.2.840.113549.1.9.21","localKeyId");U("1.2.840.113549.1.9.22.1","x509Certificate");U("1.2.840.113549.1.12.10.1.1","keyBag");U("1.2.840.113549.1.12.10.1.2","pkcs8ShroudedKeyBag");U("1.2.840.113549.1.12.10.1.3","certBag");U("1.2.840.113549.1.12.10.1.4","crlBag");U("1.2.840.113549.1.12.10.1.5","secretBag");U("1.2.840.113549.1.12.10.1.6","safeContentsBag");U("1.2.840.113549.1.5.13","pkcs5PBES2");U("1.2.840.113549.1.5.12","pkcs5PBKDF2");U("1.2.840.113549.1.12.1.1","pbeWithSHAAnd128BitRC4");U("1.2.840.113549.1.12.1.2","pbeWithSHAAnd40BitRC4");U("1.2.840.113549.1.12.1.3","pbeWithSHAAnd3-KeyTripleDES-CBC");U("1.2.840.113549.1.12.1.4","pbeWithSHAAnd2-KeyTripleDES-CBC");U("1.2.840.113549.1.12.1.5","pbeWithSHAAnd128BitRC2-CBC");U("1.2.840.113549.1.12.1.6","pbewithSHAAnd40BitRC2-CBC");U("1.2.840.113549.2.7","hmacWithSHA1");U("1.2.840.113549.2.8","hmacWithSHA224");U("1.2.840.113549.2.9","hmacWithSHA256");U("1.2.840.113549.2.10","hmacWithSHA384");U("1.2.840.113549.2.11","hmacWithSHA512");U("1.2.840.113549.3.7","des-EDE3-CBC");U("2.16.840.1.101.3.4.1.2","aes128-CBC");U("2.16.840.1.101.3.4.1.22","aes192-CBC");U("2.16.840.1.101.3.4.1.42","aes256-CBC");U("2.5.4.3","commonName");U("2.5.4.4","surname");U("2.5.4.5","serialNumber");U("2.5.4.6","countryName");U("2.5.4.7","localityName");U("2.5.4.8","stateOrProvinceName");U("2.5.4.9","streetAddress");U("2.5.4.10","organizationName");U("2.5.4.11","organizationalUnitName");U("2.5.4.12","title");U("2.5.4.13","description");U("2.5.4.15","businessCategory");U("2.5.4.17","postalCode");U("2.5.4.42","givenName");U("2.5.4.65","pseudonym");U("1.3.6.1.4.1.311.60.2.1.2","jurisdictionOfIncorporationStateOrProvinceName");U("1.3.6.1.4.1.311.60.2.1.3","jurisdictionOfIncorporationCountryName");U("2.16.840.1.113730.1.1","nsCertType");U("2.16.840.1.113730.1.13","nsComment");Ue("2.5.29.1","authorityKeyIdentifier");Ue("2.5.29.2","keyAttributes");Ue("2.5.29.3","certificatePolicies");Ue("2.5.29.4","keyUsageRestriction");Ue("2.5.29.5","policyMapping");Ue("2.5.29.6","subtreesConstraint");Ue("2.5.29.7","subjectAltName");Ue("2.5.29.8","issuerAltName");Ue("2.5.29.9","subjectDirectoryAttributes");Ue("2.5.29.10","basicConstraints");Ue("2.5.29.11","nameConstraints");Ue("2.5.29.12","policyConstraints");Ue("2.5.29.13","basicConstraints");U("2.5.29.14","subjectKeyIdentifier");U("2.5.29.15","keyUsage");Ue("2.5.29.16","privateKeyUsagePeriod");U("2.5.29.17","subjectAltName");U("2.5.29.18","issuerAltName");U("2.5.29.19","basicConstraints");Ue("2.5.29.20","cRLNumber");Ue("2.5.29.21","cRLReason");Ue("2.5.29.22","expirationDate");Ue("2.5.29.23","instructionCode");Ue("2.5.29.24","invalidityDate");Ue("2.5.29.25","cRLDistributionPoints");Ue("2.5.29.26","issuingDistributionPoint");Ue("2.5.29.27","deltaCRLIndicator");Ue("2.5.29.28","issuingDistributionPoint");Ue("2.5.29.29","certificateIssuer");Ue("2.5.29.30","nameConstraints");U("2.5.29.31","cRLDistributionPoints");U("2.5.29.32","certificatePolicies");Ue("2.5.29.33","policyMappings");Ue("2.5.29.34","policyConstraints");U("2.5.29.35","authorityKeyIdentifier");Ue("2.5.29.36","policyConstraints");U("2.5.29.37","extKeyUsage");Ue("2.5.29.46","freshestCRL");Ue("2.5.29.54","inhibitAnyPolicy");U("1.3.6.1.4.1.11129.2.4.2","timestampList");U("1.3.6.1.5.5.7.1.1","authorityInfoAccess");U("1.3.6.1.5.5.7.3.1","serverAuth");U("1.3.6.1.5.5.7.3.2","clientAuth");U("1.3.6.1.5.5.7.3.3","codeSigning");U("1.3.6.1.5.5.7.3.4","emailProtection");U("1.3.6.1.5.5.7.3.8","timeStamping")});var Gt=de(function(f1,cu){var qe=ve();Pe();Or();var K=cu.exports=qe.asn1=qe.asn1||{};K.Class={UNIVERSAL:0,APPLICATION:64,CONTEXT_SPECIFIC:128,PRIVATE:192};K.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};K.maxDepth=256;K.create=function(e,t,n,r,i){if(qe.util.isArray(r)){var s=[];for(var a=0;a<r.length;++a)if(r[a]!==void 0)s.push(r[a]);r=s}var o={tagClass:e,type:t,constructed:n,composed:n||qe.util.isArray(r),value:r};if(i&&"bitStringContents"in i)o.bitStringContents=i.bitStringContents,o.original=K.copy(o);return o};K.copy=function(e,t){var n;if(qe.util.isArray(e)){n=[];for(var r=0;r<e.length;++r)n.push(K.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:K.copy(e.value,t)},t&&!t.excludeBitStringContents)n.bitStringContents=e.bitStringContents;return n};K.equals=function(e,t,n){if(qe.util.isArray(e)){if(!qe.util.isArray(t))return!1;if(e.length!==t.length)return!1;for(var r=0;r<e.length;++r)if(!K.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&&K.equals(e.value,t.value);if(n&&n.includeBitStringContents)i=i&&e.bitStringContents===t.bitStringContents;return i};K.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 vi(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 R0=function(e,t){var n=e.getByte();if(t--,n===128)return;var r,i=n&128;if(!i)r=n;else{var s=n&127;vi(e,t,s),r=e.getInt(s<<3)}if(r<0)throw Error("Negative length: "+r);return r};K.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=K.maxDepth;if(typeof e==="string")e=qe.util.createBuffer(e);var n=e.length(),r=Ps(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 Ps(e,t,n,r){if(n>=r.maxDepth)throw Error("ASN.1 parsing error: Max depth exceeded.");var i;vi(e,t,2);var s=e.getByte();t--;var a=s&192,o=s&31;i=e.length();var l=R0(e,t);if(t-=i-e.length(),l!==void 0&&l>t){if(r.strict){var c=Error("Too few bytes to read ASN.1 value.");throw c.available=e.length(),c.remaining=t,c.requested=l,c}l=t}var u,d,p=(s&32)===32;if(p)if(u=[],l===void 0)for(;;){if(vi(e,t,2),e.bytes(2)===String.fromCharCode(0,0)){e.getBytes(2),t-=2;break}i=e.length(),u.push(Ps(e,t,n+1,r)),t-=i-e.length()}else while(l>0)i=e.length(),u.push(Ps(e,l,n+1,r)),t-=i-e.length(),l-=i-e.length();if(u===void 0&&a===K.Class.UNIVERSAL&&o===K.Type.BITSTRING)d=e.bytes(l);if(u===void 0&&r.decodeBitStrings&&a===K.Class.UNIVERSAL&&o===K.Type.BITSTRING&&l>1){var h=e.read,f=t,v=0;if(o===K.Type.BITSTRING)vi(e,t,1),v=e.getByte(),t--;if(v===0)try{i=e.length();var x={strict:!0,decodeBitStrings:!1,maxDepth:r.maxDepth},S=Ps(e,t,n+1,x),A=i-e.length();if(t-=A,o==K.Type.BITSTRING)A++;var b=S.tagClass;if(A===l&&(b===K.Class.UNIVERSAL||b===K.Class.CONTEXT_SPECIFIC))u=[S]}catch(R){}if(u===void 0)e.read=h,t=f}if(u===void 0){if(l===void 0){if(r.strict)throw Error("Non-constructed ASN.1 object of indefinite length.");l=t}if(o===K.Type.BMPSTRING){u="";for(;l>0;l-=2)vi(e,t,2),u+=String.fromCharCode(e.getInt16()),t-=2}else u=e.getBytes(l),t-=l}var k=d===void 0?null:{bitStringContents:d};return K.create(a,o,p,u,k)}K.toDer=function(e){var t=qe.util.createBuffer(),n=e.tagClass|e.type,r=qe.util.createBuffer(),i=!1;if("bitStringContents"in e){if(i=!0,e.original)i=K.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 s=0;s<e.value.length;++s)if(e.value[s]!==void 0)r.putBuffer(K.toDer(e.value[s]))}else if(e.type===K.Type.BMPSTRING)for(var s=0;s<e.value.length;++s)r.putInt16(e.value.charCodeAt(s));else if(e.type===K.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 a=r.length(),o="";do o+=String.fromCharCode(a&255),a=a>>>8;while(a>0);t.putByte(o.length|128);for(var s=o.length-1;s>=0;--s)t.putByte(o.charCodeAt(s))}return t.putBuffer(r),t};K.oidToDer=function(e){var t=e.split("."),n=qe.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 s,a,o,l;for(var c=1;c<t.length;++c){if(s=!0,a=[],o=c===1?40*r+i:parseInt(t[c],10),o>4294967295)throw Error("OID value too large; max is 32-bits.");do{if(l=o&127,o=o>>>7,!s)l|=128;a.push(l),s=!1}while(o>0);for(var u=a.length-1;u>=0;--u)n.putByte(a[u])}return n};K.derToOid=function(e){var t;if(typeof e==="string")e=qe.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};K.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),s=parseInt(e.substr(6,2),10),a=parseInt(e.substr(8,2),10),o=0;if(e.length>11){var l=e.charAt(10),c=10;if(l!=="+"&&l!=="-")o=parseInt(e.substr(10,2),10),c+=2}if(t.setUTCFullYear(n,r,i),t.setUTCHours(s,a,o,0),c){if(l=e.charAt(c),l==="+"||l==="-"){var u=parseInt(e.substr(c+1,2),10),d=parseInt(e.substr(c+4,2),10),p=u*60+d;if(p*=60000,l==="+")t.setTime(+t-p);else t.setTime(+t+p)}}return t};K.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),s=parseInt(e.substr(8,2),10),a=parseInt(e.substr(10,2),10),o=parseInt(e.substr(12,2),10),l=0,c=0,u=!1;if(e.charAt(e.length-1)==="Z")u=!0;var d=e.length-5,p=e.charAt(d);if(p==="+"||p==="-"){var h=parseInt(e.substr(d+1,2),10),f=parseInt(e.substr(d+4,2),10);if(c=h*60+f,c*=60000,p==="+")c*=-1;u=!0}if(e.charAt(14)===".")l=parseFloat(e.substr(14),10)*1000;if(u)t.setUTCFullYear(n,r,i),t.setUTCHours(s,a,o,l),t.setTime(+t+c);else t.setFullYear(n,r,i),t.setHours(s,a,o,l);return t};K.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};K.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};K.integerToDer=function(e){var t=qe.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};K.derToInteger=function(e){if(typeof e==="string")e=qe.util.createBuffer(e);var t=e.length()*8;if(t>32)throw Error("Integer too large; max is 32-bits.");return e.getSignedInt(t)};K.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&&qe.util.isArray(t.value)){var s=0;for(var a=0;i&&a<t.value.length;++a){var o=t.value[a];i=!!o.optional;var l=e.value[s];if(!l){if(!o.optional){if(i=!1,r)r.push("["+t.name+'] Missing required element. Expected tag class "'+o.tagClass+'", type "'+o.type+'"')}continue}var c=typeof o.tagClass<"u"&&typeof o.type<"u";if(c&&(l.tagClass!==o.tagClass||l.type!==o.type))if(o.optional){i=!0;continue}else{if(i=!1,r)r.push("["+t.name+"] Tag mismatch. Expected ("+o.tagClass+","+o.type+"), got ("+l.tagClass+","+l.type+")");break}var u=K.validate(l,o,n,r);if(u)++s,i=!0;else if(o.optional)i=!0;else{i=!1;break}}}if(i&&n){if(t.capture)n[t.capture]=e.value;if(t.captureAsn1)n[t.captureAsn1]=e;if(t.captureBitStringContents&&"bitStringContents"in e)n[t.captureBitStringContents]=e.bitStringContents;if(t.captureBitStringValue&&"bitStringContents"in e){var d;if(e.bitStringContents.length<2)n[t.captureBitStringValue]="";else{var 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 lu=/[^\\u0000-\\u00ff]/;K.prettyPrint=function(e,t,n){var r="";if(t=t||0,n=n||2,t>0)r+=`
5
+ `,n=n.substr(t)}return r+=n,r};T.binary.base64.decode=function(e,t,n){var r=t;if(!r)r=new Uint8Array(Math.ceil(e.length/4)*3);e=e.replace(/[^A-Za-z0-9\+\/\=]/g,""),n=n||0;var i,s,a,o,l=0,c=n;while(l<e.length)if(i=Dr[e.charCodeAt(l++)-43],s=Dr[e.charCodeAt(l++)-43],a=Dr[e.charCodeAt(l++)-43],o=Dr[e.charCodeAt(l++)-43],r[c++]=i<<2|s>>4,a!==64){if(r[c++]=(s&15)<<4|a>>2,o!==64)r[c++]=(a&3)<<6|o}return t?c-n:r.subarray(0,c)};T.binary.base58.encode=function(e,t){return T.binary.baseN.encode(e,Zc,t)};T.binary.base58.decode=function(e,t){return T.binary.baseN.decode(e,Zc,t)};T.text={utf8:{},utf16:{}};T.text.utf8.encode=function(e,t,n){e=T.encodeUtf8(e);var r=t;if(!r)r=new Uint8Array(e.length);n=n||0;var i=n;for(var s=0;s<e.length;++s)r[i++]=e.charCodeAt(s);return t?i-n:r};T.text.utf8.decode=function(e){return T.decodeUtf8(String.fromCharCode.apply(null,e))};T.text.utf16.encode=function(e,t,n){var r=t;if(!r)r=new Uint8Array(e.length*2);var i=new Uint16Array(r.buffer);n=n||0;var s=n,a=n;for(var o=0;o<e.length;++o)i[a++]=e.charCodeAt(o),s+=2;return t?s-n:r};T.text.utf16.decode=function(e){return String.fromCharCode.apply(null,new Uint16Array(e.buffer))};T.deflate=function(e,t,n){if(t=T.decode64(e.deflate(T.encode64(t)).rval),n){var r=2,i=t.charCodeAt(1);if(i&32)r=6;t=t.substring(r,t.length-4)}return t};T.inflate=function(e,t,n){var r=e.inflate(T.encode64(t)).rval;return r===null?null:T.decode64(r)};var lo=function(e,t,n){if(!e)throw Error("WebStorage not available.");var r;if(n===null)r=e.removeItem(t);else n=T.encode64(JSON.stringify(n)),r=e.setItem(t,n);if(typeof r<"u"&&r.rval!==!0){var i=Error(r.error.message);throw i.id=r.error.id,i.name=r.error.name,i}},co=function(e,t){if(!e)throw Error("WebStorage not available.");var n=e.getItem(t);if(e.init)if(n.rval===null){if(n.error){var r=Error(n.error.message);throw r.id=n.error.id,r.name=n.error.name,r}n=null}else n=n.rval;if(n!==null)n=JSON.parse(T.decode64(n));return n},T0=function(e,t,n,r){var i=co(e,t);if(i===null)i={};i[n]=r,lo(e,t,i)},A0=function(e,t,n){var r=co(e,t);if(r!==null)r=n in r?r[n]:null;return r},_0=function(e,t,n){var r=co(e,t);if(r!==null&&n in r){delete r[n];var i=!0;for(var s in r){i=!1;break}if(i)r=null;lo(e,t,r)}},k0=function(e,t){lo(e,t,null)},_s=function(e,t,n){var r=null;if(typeof n>"u")n=["web","flash"];var i,s=!1,a=null;for(var o in n){i=n[o];try{if(i==="flash"||i==="both"){if(t[0]===null)throw Error("Flash local storage not available.");r=e.apply(this,t),s=i==="flash"}if(i==="web"||i==="both")t[0]=localStorage,r=e.apply(this,t),s=!0}catch(l){a=l}if(s)break}if(!s)throw a;return r};T.setItem=function(e,t,n,r,i){_s(T0,arguments,i)};T.getItem=function(e,t,n,r){return _s(A0,arguments,r)};T.removeItem=function(e,t,n,r){_s(_0,arguments,r)};T.clearItems=function(e,t,n){_s(k0,arguments,n)};T.isEmpty=function(e){for(var t in e)if(e.hasOwnProperty(t))return!1;return!0};T.format=function(e){var t=/%./g,n,r,i=0,s=[],a=0;while(n=t.exec(e)){if(r=e.substring(a,t.lastIndex-2),r.length>0)s.push(r);a=t.lastIndex;var o=n[0][1];switch(o){case"s":case"o":if(i<arguments.length)s.push(arguments[i+++1]);else s.push("<?>");break;case"%":s.push("%");break;default:s.push("<%"+o+"?>")}}return s.push(e.substring(a)),s.join("")};T.formatNumber=function(e,t,n,r){var i=e,s=isNaN(t=Math.abs(t))?2:t,a=n===void 0?",":n,o=r===void 0?".":r,l=i<0?"-":"",c=parseInt(i=Math.abs(+i||0).toFixed(s),10)+"",u=c.length>3?c.length%3:0;return l+(u?c.substr(0,u)+o:"")+c.substr(u).replace(/(\d{3})(?=\d)/g,"$1"+o)+(s?a+Math.abs(i-c).toFixed(s).slice(2):"")};T.formatSize=function(e){if(e>=1073741824)e=T.formatNumber(e/1073741824,2,".","")+" GiB";else if(e>=1048576)e=T.formatNumber(e/1048576,2,".","")+" MiB";else if(e>=1024)e=T.formatNumber(e/1024,0)+" KiB";else e=T.formatNumber(e,0)+" bytes";return e};T.bytesFromIP=function(e){if(e.indexOf(".")!==-1)return T.bytesFromIPv4(e);if(e.indexOf(":")!==-1)return T.bytesFromIPv6(e);return null};T.bytesFromIPv4=function(e){if(e=e.split("."),e.length!==4)return null;var t=T.createBuffer();for(var n=0;n<e.length;++n){var r=parseInt(e[n],10);if(isNaN(r))return null;t.putByte(r)}return t.getBytes()};T.bytesFromIPv6=function(e){var t=0;e=e.split(":").filter(function(a){if(a.length===0)++t;return!0});var n=(8-e.length+t)*2,r=T.createBuffer();for(var i=0;i<8;++i){if(!e[i]||e[i].length===0){r.fillWithByte(0,n),n=0;continue}var s=T.hexToBytes(e[i]);if(s.length<2)r.putByte(0);r.putBytes(s)}return r.getBytes()};T.bytesToIP=function(e){if(e.length===4)return T.bytesToIPv4(e);if(e.length===16)return T.bytesToIPv6(e);return null};T.bytesToIPv4=function(e){if(e.length!==4)return null;var t=[];for(var n=0;n<e.length;++n)t.push(e.charCodeAt(n));return t.join(".")};T.bytesToIPv6=function(e){if(e.length!==16)return null;var t=[],n=[],r=0;for(var i=0;i<e.length;i+=2){var s=T.bytesToHex(e[i]+e[i+1]);while(s[0]==="0"&&s!=="0")s=s.substr(1);if(s==="0"){var a=n[n.length-1],o=t.length;if(!a||o!==a.end+1)n.push({start:o,end:o});else if(a.end=o,a.end-a.start>n[r].end-n[r].start)r=n.length-1}t.push(s)}if(n.length>0){var l=n[r];if(l.end-l.start>0){if(t.splice(l.start,l.end-l.start+1,""),l.start===0)t.unshift("");if(l.end===7)t.push("")}}return t.join(":")};T.estimateCores=function(e,t){if(typeof e==="function")t=e,e={};if(e=e||{},"cores"in T&&!e.update)return t(null,T.cores);if(typeof navigator<"u"&&"hardwareConcurrency"in navigator&&navigator.hardwareConcurrency>0)return T.cores=navigator.hardwareConcurrency,t(null,T.cores);if(typeof Worker>"u")return T.cores=1,t(null,T.cores);if(typeof Blob>"u")return T.cores=2,t(null,T.cores);var n=URL.createObjectURL(new Blob(["(",function(){self.addEventListener("message",function(a){var o=Date.now(),l=o+4;while(Date.now()<l);self.postMessage({st:o,et:l})})}.toString(),")()"],{type:"application/javascript"}));r([],5,16);function r(a,o,l){if(o===0){var c=Math.floor(a.reduce(function(u,d){return u+d},0)/a.length);return T.cores=Math.max(1,c),URL.revokeObjectURL(n),t(null,T.cores)}i(l,function(u,d){a.push(s(l,d)),r(a,o-1,l)})}function i(a,o){var l=[],c=[];for(var u=0;u<a;++u){var d=new Worker(n);d.addEventListener("message",function(p){if(c.push(p.data),c.length===a){for(var h=0;h<a;++h)l[h].terminate();o(null,c)}}),l.push(d)}for(var u=0;u<a;++u)l[u].postMessage(u)}function s(a,o){var l=[];for(var c=0;c<a;++c){var u=o[c],d=l[c]=[];for(var p=0;p<a;++p){if(c===p)continue;var h=o[p];if(u.st>h.st&&u.st<h.et||h.st>u.st&&h.st<u.et)d.push(p)}}return l.reduce(function(f,v){return Math.max(f,v.length)},0)}}});var ks=de(function(o1,tu){var ut=ye();Ne();tu.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 uo=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)};uo.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)};uo.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()};uo.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 po=de(function(l1,ru){var dt=ye();Ne();dt.cipher=dt.cipher||{};var we=ru.exports=dt.cipher.modes=dt.cipher.modes||{};we.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)};we.ecb.prototype.start=function(e){};we.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])};we.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])};we.ecb.prototype.pad=function(e,t){var n=e.length()===this.blockSize?this.blockSize:this.blockSize-e.length();return e.fillWithByte(n,n),!0};we.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};we.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)};we.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=Is(e.iv,this.blockSize),this._prev=this._iv.slice(0)};we.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};we.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)};we.cbc.prototype.pad=function(e,t){var n=e.length()===this.blockSize?this.blockSize:this.blockSize-e.length();return e.fillWithByte(n,n),!0};we.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};we.cfb=function(e){e=e||{},this.name="CFB",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=Array(this._ints),this._partialBlock=Array(this._ints),this._partialOutput=dt.util.createBuffer(),this._partialBytes=0};we.cfb.prototype.start=function(e){if(!("iv"in e))throw Error("Invalid IV parameter.");this._iv=Is(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0};we.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 s=(this.blockSize-r)%this.blockSize;if(s>0)s=this.blockSize-s;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(s>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(s>0&&!n)return t.putBytes(this._partialOutput.getBytes(s-this._partialBytes)),this._partialBytes=s,!0;t.putBytes(this._partialOutput.getBytes(r-this._partialBytes)),this._partialBytes=0};we.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 s=(this.blockSize-r)%this.blockSize;if(s>0)s=this.blockSize-s;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(s>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(s>0&&!n)return t.putBytes(this._partialOutput.getBytes(s-this._partialBytes)),this._partialBytes=s,!0;t.putBytes(this._partialOutput.getBytes(r-this._partialBytes)),this._partialBytes=0};we.ofb=function(e){e=e||{},this.name="OFB",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=Array(this._ints),this._partialOutput=dt.util.createBuffer(),this._partialBytes=0};we.ofb.prototype.start=function(e){if(!("iv"in e))throw Error("Invalid IV parameter.");this._iv=Is(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0};we.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 s=(this.blockSize-r)%this.blockSize;if(s>0)s=this.blockSize-s;this._partialOutput.clear();for(var i=0;i<this._ints;++i)this._partialOutput.putInt32(e.getInt32()^this._outBlock[i]);if(s>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(s>0&&!n)return t.putBytes(this._partialOutput.getBytes(s-this._partialBytes)),this._partialBytes=s,!0;t.putBytes(this._partialOutput.getBytes(r-this._partialBytes)),this._partialBytes=0};we.ofb.prototype.decrypt=we.ofb.prototype.encrypt;we.ctr=function(e){e=e||{},this.name="CTR",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=Array(this._ints),this._partialOutput=dt.util.createBuffer(),this._partialBytes=0};we.ctr.prototype.start=function(e){if(!("iv"in e))throw Error("Invalid IV parameter.");this._iv=Is(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0};we.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 s=(this.blockSize-r)%this.blockSize;if(s>0)s=this.blockSize-s;this._partialOutput.clear();for(var i=0;i<this._ints;++i)this._partialOutput.putInt32(e.getInt32()^this._outBlock[i]);if(s>0)e.read-=this.blockSize;if(this._partialBytes>0)this._partialOutput.getBytes(this._partialBytes);if(s>0&&!n)return t.putBytes(this._partialOutput.getBytes(s-this._partialBytes)),this._partialBytes=s,!0;t.putBytes(this._partialOutput.getBytes(r-this._partialBytes)),this._partialBytes=0}Rs(this._inBlock)};we.ctr.prototype.decrypt=we.ctr.prototype.encrypt;we.gcm=function(e){e=e||{},this.name="GCM",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=Array(this._ints),this._outBlock=Array(this._ints),this._partialOutput=dt.util.createBuffer(),this._partialBytes=0,this._R=3774873600};we.gcm.prototype.start=function(e){if(!("iv"in e))throw Error("Invalid IV parameter.");var t=dt.util.createBuffer(e.iv);this._cipherLength=0;var n;if("additionalData"in e)n=dt.util.createBuffer(e.additionalData);else n=dt.util.createBuffer();if(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=dt.util.createBuffer(e.tag).getBytes(),this._tag.length!==this._tagLength/8)throw Error("Authentication tag does not match tag length.")}this._hashBlock=Array(this._ints),this.tag=null,this._hashSubkey=Array(this._ints),this.cipher.encrypt([0,0,0,0],this._hashSubkey),this.componentBits=4,this._m=this.generateHashTable(this._hashSubkey,this.componentBits);var r=t.length();if(r===12)this._j0=[t.getInt32(),t.getInt32(),t.getInt32(),1];else{this._j0=[0,0,0,0];while(t.length()>0)this._j0=this.ghash(this._hashSubkey,this._j0,[t.getInt32(),t.getInt32(),t.getInt32(),t.getInt32()]);this._j0=this.ghash(this._hashSubkey,this._j0,[0,0].concat(fo(r*8)))}this._inBlock=this._j0.slice(0),Rs(this._inBlock),this._partialBytes=0,n=dt.util.createBuffer(n),this._aDataLength=fo(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()])};we.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 s=(this.blockSize-r)%this.blockSize;if(s>0)s=this.blockSize-s;this._partialOutput.clear();for(var i=0;i<this._ints;++i)this._partialOutput.putInt32(e.getInt32()^this._outBlock[i]);if(s<=0||n){if(n){var a=r%this.blockSize;this._cipherLength+=a,this._partialOutput.truncate(this.blockSize-a)}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(s>0&&!n)return e.read-=this.blockSize,t.putBytes(this._partialOutput.getBytes(s-this._partialBytes)),this._partialBytes=s,!0;t.putBytes(this._partialOutput.getBytes(r-this._partialBytes)),this._partialBytes=0}this._s=this.ghash(this._hashSubkey,this._s,this._outBlock),Rs(this._inBlock)};we.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),Rs(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};we.gcm.prototype.afterFinish=function(e,t){var n=!0;if(t.decrypt&&t.overflow)e.truncate(this.blockSize-t.overflow);this.tag=dt.util.createBuffer();var r=this._aDataLength.concat(fo(this._cipherLength*8));this._s=this.ghash(this._hashSubkey,this._s,r);var i=[];this.cipher.encrypt(this._j0,i);for(var s=0;s<this._ints;++s)this.tag.putInt32(this._s[s]^i[s]);if(this.tag.truncate(this.tag.length()%(this._tagLength/8)),t.decrypt&&this.tag.bytes()!==this._tag)n=!1;return n};we.gcm.prototype.multiply=function(e,t){var n=[0,0,0,0],r=t.slice(0);for(var i=0;i<128;++i){var s=e[i/32|0]&1<<31-i%32;if(s)n[0]^=r[0],n[1]^=r[1],n[2]^=r[2],n[3]^=r[3];this.pow(r,r)}return n};we.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};we.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,s=this._m[n][i];t[0]^=s[0],t[1]^=s[1],t[2]^=s[2],t[3]^=s[3]}return t};we.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)};we.gcm.prototype.generateHashTable=function(e,t){var n=8/t,r=4*n,i=16*n,s=Array(i);for(var a=0;a<i;++a){var o=[0,0,0,0],l=a/r|0,c=(r-1-a%r)*t;o[l]=1<<t-1<<c,s[a]=this.generateSubHashTable(this.multiply(o,e),t)}return s};we.gcm.prototype.generateSubHashTable=function(e,t){var n=1<<t,r=n>>>1,i=Array(n);i[r]=e.slice(0);var s=r>>>1;while(s>0)this.pow(i[2*s],i[s]=[]),s>>=1;s=2;while(s<r){for(var a=1;a<s;++a){var o=i[s],l=i[a];i[s+a]=[o[0]^l[0],o[1]^l[1],o[2]^l[2],o[3]^l[3]]}s*=2}i[0]=[0,0,0,0];for(s=r+1;s<n;++s){var c=i[s^r];i[s]=[e[0]^c[0],e[1]^c[1],e[2]^c[2],e[3]^c[3]]}return i};function Is(e,t){if(typeof e==="string")e=dt.util.createBuffer(e);if(dt.util.isArray(e)&&e.length>4){var n=e;e=dt.util.createBuffer();for(var r=0;r<n.length;++r)e.putByte(n[r])}if(e.length()<t)throw Error("Invalid IV length; got "+e.length()+" bytes and expected "+t+" bytes.");if(!dt.util.isArray(e)){var i=[],s=t/4;for(var r=0;r<s;++r)i.push(e.getInt32());e=i}return e}function Rs(e){e[e.length-1]=e[e.length-1]+1&4294967295}function fo(e){return[e/4294967296|0,e&4294967295]}});var Lr=de(function(c1,au){var He=ye();ks();po();Ne();au.exports=He.aes=He.aes||{};He.aes.startEncrypting=function(e,t,n,r){var i=Bs({key:e,output:n,decrypt:!1,mode:r});return i.start(t),i};He.aes.createEncryptionCipher=function(e,t){return Bs({key:e,output:null,decrypt:!1,mode:t})};He.aes.startDecrypting=function(e,t,n,r){var i=Bs({key:e,output:n,decrypt:!0,mode:r});return i.start(t),i};He.aes.createDecryptionCipher=function(e,t){return Bs({key:e,output:null,decrypt:!0,mode:t})};He.aes.Algorithm=function(e,t){if(!mo)iu();var n=this;n.name=e,n.mode=new t({blockSize:16,cipher:{encrypt:function(r,i){return go(n._w,r,i,!1)},decrypt:function(r,i){return go(n._w,r,i,!0)}}}),n._init=!1};He.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=He.util.createBuffer(t);else if(He.util.isArray(t)&&(t.length===16||t.length===24||t.length===32)){n=t,t=He.util.createBuffer();for(var r=0;r<n.length;++r)t.putByte(n[r])}if(!He.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(!He.util.isArray(t)||!(t.length===4||t.length===6||t.length===8))throw Error("Invalid key parameter.");var s=this.mode.name,a=["CFB","OFB","CTR","GCM"].indexOf(s)!==-1;this._w=su(t,e.decrypt&&!a),this._init=!0};He.aes._expandKey=function(e,t){if(!mo)iu();return su(e,t)};He.aes._updateBlock=go;Tn("AES-ECB",He.cipher.modes.ecb);Tn("AES-CBC",He.cipher.modes.cbc);Tn("AES-CFB",He.cipher.modes.cfb);Tn("AES-OFB",He.cipher.modes.ofb);Tn("AES-CTR",He.cipher.modes.ctr);Tn("AES-GCM",He.cipher.modes.gcm);function Tn(e,t){var n=function(){return new He.aes.Algorithm(e,t)};He.cipher.registerAlgorithm(e,n)}var mo=!1,En=4,bt,ho,nu,nn,qt;function iu(){mo=!0,nu=[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),ho=Array(256),nn=[,,,,],qt=[,,,,];for(var t=0;t<4;++t)nn[t]=Array(256),qt[t]=Array(256);var n=0,r=0,i,s,a,o,l,c,u;for(var t=0;t<256;++t){o=r^r<<1^r<<2^r<<3^r<<4,o=o>>8^o&255^99,bt[n]=o,ho[o]=n,l=e[o],i=e[n],s=e[i],a=e[s],c=l<<24^o<<16^o<<8^(o^l),u=(i^s^a)<<24^(n^a)<<16^(n^s^a)<<8^(n^i^a);for(var d=0;d<4;++d)nn[d][n]=c,qt[d][o]=u,c=c<<24|c>>>8,u=u<<24|u>>>8;if(n===0)n=r=1;else n=i^e[e[e[i^a]]],r^=e[e[r]]}}function su(e,t){var n=e.slice(0),r,i=1,s=n.length,a=s+6+1,o=En*a;for(var l=s;l<o;++l){if(r=n[l-1],l%s===0)r=bt[r>>>16&255]<<24^bt[r>>>8&255]<<16^bt[r&255]<<8^bt[r>>>24]^nu[i]<<24,i++;else if(s>6&&l%s===4)r=bt[r>>>24]<<24^bt[r>>>16&255]<<16^bt[r>>>8&255]<<8^bt[r&255];n[l]=n[l-s]^r}if(t){var c,u=qt[0],d=qt[1],p=qt[2],h=qt[3],f=n.slice(0);o=n.length;for(var l=0,v=o-En;l<o;l+=En,v-=En)if(l===0||l===o-En)f[l]=n[v],f[l+1]=n[v+3],f[l+2]=n[v+2],f[l+3]=n[v+1];else for(var x=0;x<En;++x)c=n[v+x],f[l+(3&-x)]=u[bt[c>>>24]]^d[bt[c>>>16&255]]^p[bt[c>>>8&255]]^h[bt[c&255]];n=f}return n}function go(e,t,n,r){var i=e.length/4-1,s,a,o,l,c;if(r)s=qt[0],a=qt[1],o=qt[2],l=qt[3],c=ho;else s=nn[0],a=nn[1],o=nn[2],l=nn[3],c=bt;var u,d,p,h,f,v,x;u=t[0]^e[0],d=t[r?3:1]^e[1],p=t[2]^e[2],h=t[r?1:3]^e[3];var S=3;for(var A=1;A<i;++A)f=s[u>>>24]^a[d>>>16&255]^o[p>>>8&255]^l[h&255]^e[++S],v=s[d>>>24]^a[p>>>16&255]^o[h>>>8&255]^l[u&255]^e[++S],x=s[p>>>24]^a[h>>>16&255]^o[u>>>8&255]^l[d&255]^e[++S],h=s[h>>>24]^a[u>>>16&255]^o[d>>>8&255]^l[p&255]^e[++S],u=f,d=v,p=x;n[0]=c[u>>>24]<<24^c[d>>>16&255]<<16^c[p>>>8&255]<<8^c[h&255]^e[++S],n[r?3:1]=c[d>>>24]<<24^c[p>>>16&255]<<16^c[h>>>8&255]<<8^c[u&255]^e[++S],n[2]=c[p>>>24]<<24^c[h>>>16&255]<<16^c[u>>>8&255]<<8^c[d&255]^e[++S],n[r?1:3]=c[h>>>24]<<24^c[u>>>16&255]<<16^c[d>>>8&255]<<8^c[p&255]^e[++S]}function Bs(e){e=e||{};var t=(e.mode||"CBC").toUpperCase(),n="AES-"+t,r;if(e.decrypt)r=He.cipher.createDecipher(n,e.key);else r=He.cipher.createCipher(n,e.key);var i=r.start;return r.start=function(s,a){var o=null;if(a instanceof He.util.ByteBuffer)o=a,a={};a=a||{},a.output=o,a.iv=s,i.call(r,a)},r}});var Or=de(function(u1,ou){var yi=ye();yi.pki=yi.pki||{};var yo=ou.exports=yi.pki.oids=yi.oids=yi.oids||{};function U(e,t){yo[e]=t,yo[t]=e}function Ue(e,t){yo[e]=t}U("1.2.840.113549.1.1.1","rsaEncryption");U("1.2.840.113549.1.1.4","md5WithRSAEncryption");U("1.2.840.113549.1.1.5","sha1WithRSAEncryption");U("1.2.840.113549.1.1.7","RSAES-OAEP");U("1.2.840.113549.1.1.8","mgf1");U("1.2.840.113549.1.1.9","pSpecified");U("1.2.840.113549.1.1.10","RSASSA-PSS");U("1.2.840.113549.1.1.11","sha256WithRSAEncryption");U("1.2.840.113549.1.1.12","sha384WithRSAEncryption");U("1.2.840.113549.1.1.13","sha512WithRSAEncryption");U("1.3.101.112","EdDSA25519");U("1.2.840.10040.4.3","dsa-with-sha1");U("1.3.14.3.2.7","desCBC");U("1.3.14.3.2.26","sha1");U("1.3.14.3.2.29","sha1WithRSASignature");U("2.16.840.1.101.3.4.2.1","sha256");U("2.16.840.1.101.3.4.2.2","sha384");U("2.16.840.1.101.3.4.2.3","sha512");U("2.16.840.1.101.3.4.2.4","sha224");U("2.16.840.1.101.3.4.2.5","sha512-224");U("2.16.840.1.101.3.4.2.6","sha512-256");U("1.2.840.113549.2.2","md2");U("1.2.840.113549.2.5","md5");U("1.2.840.113549.1.7.1","data");U("1.2.840.113549.1.7.2","signedData");U("1.2.840.113549.1.7.3","envelopedData");U("1.2.840.113549.1.7.4","signedAndEnvelopedData");U("1.2.840.113549.1.7.5","digestedData");U("1.2.840.113549.1.7.6","encryptedData");U("1.2.840.113549.1.9.1","emailAddress");U("1.2.840.113549.1.9.2","unstructuredName");U("1.2.840.113549.1.9.3","contentType");U("1.2.840.113549.1.9.4","messageDigest");U("1.2.840.113549.1.9.5","signingTime");U("1.2.840.113549.1.9.6","counterSignature");U("1.2.840.113549.1.9.7","challengePassword");U("1.2.840.113549.1.9.8","unstructuredAddress");U("1.2.840.113549.1.9.14","extensionRequest");U("1.2.840.113549.1.9.20","friendlyName");U("1.2.840.113549.1.9.21","localKeyId");U("1.2.840.113549.1.9.22.1","x509Certificate");U("1.2.840.113549.1.12.10.1.1","keyBag");U("1.2.840.113549.1.12.10.1.2","pkcs8ShroudedKeyBag");U("1.2.840.113549.1.12.10.1.3","certBag");U("1.2.840.113549.1.12.10.1.4","crlBag");U("1.2.840.113549.1.12.10.1.5","secretBag");U("1.2.840.113549.1.12.10.1.6","safeContentsBag");U("1.2.840.113549.1.5.13","pkcs5PBES2");U("1.2.840.113549.1.5.12","pkcs5PBKDF2");U("1.2.840.113549.1.12.1.1","pbeWithSHAAnd128BitRC4");U("1.2.840.113549.1.12.1.2","pbeWithSHAAnd40BitRC4");U("1.2.840.113549.1.12.1.3","pbeWithSHAAnd3-KeyTripleDES-CBC");U("1.2.840.113549.1.12.1.4","pbeWithSHAAnd2-KeyTripleDES-CBC");U("1.2.840.113549.1.12.1.5","pbeWithSHAAnd128BitRC2-CBC");U("1.2.840.113549.1.12.1.6","pbewithSHAAnd40BitRC2-CBC");U("1.2.840.113549.2.7","hmacWithSHA1");U("1.2.840.113549.2.8","hmacWithSHA224");U("1.2.840.113549.2.9","hmacWithSHA256");U("1.2.840.113549.2.10","hmacWithSHA384");U("1.2.840.113549.2.11","hmacWithSHA512");U("1.2.840.113549.3.7","des-EDE3-CBC");U("2.16.840.1.101.3.4.1.2","aes128-CBC");U("2.16.840.1.101.3.4.1.22","aes192-CBC");U("2.16.840.1.101.3.4.1.42","aes256-CBC");U("2.5.4.3","commonName");U("2.5.4.4","surname");U("2.5.4.5","serialNumber");U("2.5.4.6","countryName");U("2.5.4.7","localityName");U("2.5.4.8","stateOrProvinceName");U("2.5.4.9","streetAddress");U("2.5.4.10","organizationName");U("2.5.4.11","organizationalUnitName");U("2.5.4.12","title");U("2.5.4.13","description");U("2.5.4.15","businessCategory");U("2.5.4.17","postalCode");U("2.5.4.42","givenName");U("2.5.4.65","pseudonym");U("1.3.6.1.4.1.311.60.2.1.2","jurisdictionOfIncorporationStateOrProvinceName");U("1.3.6.1.4.1.311.60.2.1.3","jurisdictionOfIncorporationCountryName");U("2.16.840.1.113730.1.1","nsCertType");U("2.16.840.1.113730.1.13","nsComment");Ue("2.5.29.1","authorityKeyIdentifier");Ue("2.5.29.2","keyAttributes");Ue("2.5.29.3","certificatePolicies");Ue("2.5.29.4","keyUsageRestriction");Ue("2.5.29.5","policyMapping");Ue("2.5.29.6","subtreesConstraint");Ue("2.5.29.7","subjectAltName");Ue("2.5.29.8","issuerAltName");Ue("2.5.29.9","subjectDirectoryAttributes");Ue("2.5.29.10","basicConstraints");Ue("2.5.29.11","nameConstraints");Ue("2.5.29.12","policyConstraints");Ue("2.5.29.13","basicConstraints");U("2.5.29.14","subjectKeyIdentifier");U("2.5.29.15","keyUsage");Ue("2.5.29.16","privateKeyUsagePeriod");U("2.5.29.17","subjectAltName");U("2.5.29.18","issuerAltName");U("2.5.29.19","basicConstraints");Ue("2.5.29.20","cRLNumber");Ue("2.5.29.21","cRLReason");Ue("2.5.29.22","expirationDate");Ue("2.5.29.23","instructionCode");Ue("2.5.29.24","invalidityDate");Ue("2.5.29.25","cRLDistributionPoints");Ue("2.5.29.26","issuingDistributionPoint");Ue("2.5.29.27","deltaCRLIndicator");Ue("2.5.29.28","issuingDistributionPoint");Ue("2.5.29.29","certificateIssuer");Ue("2.5.29.30","nameConstraints");U("2.5.29.31","cRLDistributionPoints");U("2.5.29.32","certificatePolicies");Ue("2.5.29.33","policyMappings");Ue("2.5.29.34","policyConstraints");U("2.5.29.35","authorityKeyIdentifier");Ue("2.5.29.36","policyConstraints");U("2.5.29.37","extKeyUsage");Ue("2.5.29.46","freshestCRL");Ue("2.5.29.54","inhibitAnyPolicy");U("1.3.6.1.4.1.11129.2.4.2","timestampList");U("1.3.6.1.5.5.7.1.1","authorityInfoAccess");U("1.3.6.1.5.5.7.3.1","serverAuth");U("1.3.6.1.5.5.7.3.2","clientAuth");U("1.3.6.1.5.5.7.3.3","codeSigning");U("1.3.6.1.5.5.7.3.4","emailProtection");U("1.3.6.1.5.5.7.3.8","timeStamping")});var Gt=de(function(d1,cu){var qe=ye();Ne();Or();var K=cu.exports=qe.asn1=qe.asn1||{};K.Class={UNIVERSAL:0,APPLICATION:64,CONTEXT_SPECIFIC:128,PRIVATE:192};K.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};K.maxDepth=256;K.create=function(e,t,n,r,i){if(qe.util.isArray(r)){var s=[];for(var a=0;a<r.length;++a)if(r[a]!==void 0)s.push(r[a]);r=s}var o={tagClass:e,type:t,constructed:n,composed:n||qe.util.isArray(r),value:r};if(i&&"bitStringContents"in i)o.bitStringContents=i.bitStringContents,o.original=K.copy(o);return o};K.copy=function(e,t){var n;if(qe.util.isArray(e)){n=[];for(var r=0;r<e.length;++r)n.push(K.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:K.copy(e.value,t)},t&&!t.excludeBitStringContents)n.bitStringContents=e.bitStringContents;return n};K.equals=function(e,t,n){if(qe.util.isArray(e)){if(!qe.util.isArray(t))return!1;if(e.length!==t.length)return!1;for(var r=0;r<e.length;++r)if(!K.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&&K.equals(e.value,t.value);if(n&&n.includeBitStringContents)i=i&&e.bitStringContents===t.bitStringContents;return i};K.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 vi(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 I0=function(e,t){var n=e.getByte();if(t--,n===128)return;var r,i=n&128;if(!i)r=n;else{var s=n&127;vi(e,t,s),r=e.getInt(s<<3)}if(r<0)throw Error("Negative length: "+r);return r};K.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=K.maxDepth;if(typeof e==="string")e=qe.util.createBuffer(e);var n=e.length(),r=Ps(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 Ps(e,t,n,r){if(n>=r.maxDepth)throw Error("ASN.1 parsing error: Max depth exceeded.");var i;vi(e,t,2);var s=e.getByte();t--;var a=s&192,o=s&31;i=e.length();var l=I0(e,t);if(t-=i-e.length(),l!==void 0&&l>t){if(r.strict){var c=Error("Too few bytes to read ASN.1 value.");throw c.available=e.length(),c.remaining=t,c.requested=l,c}l=t}var u,d,p=(s&32)===32;if(p)if(u=[],l===void 0)for(;;){if(vi(e,t,2),e.bytes(2)===String.fromCharCode(0,0)){e.getBytes(2),t-=2;break}i=e.length(),u.push(Ps(e,t,n+1,r)),t-=i-e.length()}else while(l>0)i=e.length(),u.push(Ps(e,l,n+1,r)),t-=i-e.length(),l-=i-e.length();if(u===void 0&&a===K.Class.UNIVERSAL&&o===K.Type.BITSTRING)d=e.bytes(l);if(u===void 0&&r.decodeBitStrings&&a===K.Class.UNIVERSAL&&o===K.Type.BITSTRING&&l>1){var h=e.read,f=t,v=0;if(o===K.Type.BITSTRING)vi(e,t,1),v=e.getByte(),t--;if(v===0)try{i=e.length();var x={strict:!0,decodeBitStrings:!1,maxDepth:r.maxDepth},S=Ps(e,t,n+1,x),A=i-e.length();if(t-=A,o==K.Type.BITSTRING)A++;var b=S.tagClass;if(A===l&&(b===K.Class.UNIVERSAL||b===K.Class.CONTEXT_SPECIFIC))u=[S]}catch(R){}if(u===void 0)e.read=h,t=f}if(u===void 0){if(l===void 0){if(r.strict)throw Error("Non-constructed ASN.1 object of indefinite length.");l=t}if(o===K.Type.BMPSTRING){u="";for(;l>0;l-=2)vi(e,t,2),u+=String.fromCharCode(e.getInt16()),t-=2}else u=e.getBytes(l),t-=l}var k=d===void 0?null:{bitStringContents:d};return K.create(a,o,p,u,k)}K.toDer=function(e){var t=qe.util.createBuffer(),n=e.tagClass|e.type,r=qe.util.createBuffer(),i=!1;if("bitStringContents"in e){if(i=!0,e.original)i=K.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 s=0;s<e.value.length;++s)if(e.value[s]!==void 0)r.putBuffer(K.toDer(e.value[s]))}else if(e.type===K.Type.BMPSTRING)for(var s=0;s<e.value.length;++s)r.putInt16(e.value.charCodeAt(s));else if(e.type===K.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 a=r.length(),o="";do o+=String.fromCharCode(a&255),a=a>>>8;while(a>0);t.putByte(o.length|128);for(var s=o.length-1;s>=0;--s)t.putByte(o.charCodeAt(s))}return t.putBuffer(r),t};K.oidToDer=function(e){var t=e.split("."),n=qe.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 s,a,o,l;for(var c=1;c<t.length;++c){if(s=!0,a=[],o=c===1?40*r+i:parseInt(t[c],10),o>4294967295)throw Error("OID value too large; max is 32-bits.");do{if(l=o&127,o=o>>>7,!s)l|=128;a.push(l),s=!1}while(o>0);for(var u=a.length-1;u>=0;--u)n.putByte(a[u])}return n};K.derToOid=function(e){var t;if(typeof e==="string")e=qe.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};K.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),s=parseInt(e.substr(6,2),10),a=parseInt(e.substr(8,2),10),o=0;if(e.length>11){var l=e.charAt(10),c=10;if(l!=="+"&&l!=="-")o=parseInt(e.substr(10,2),10),c+=2}if(t.setUTCFullYear(n,r,i),t.setUTCHours(s,a,o,0),c){if(l=e.charAt(c),l==="+"||l==="-"){var u=parseInt(e.substr(c+1,2),10),d=parseInt(e.substr(c+4,2),10),p=u*60+d;if(p*=60000,l==="+")t.setTime(+t-p);else t.setTime(+t+p)}}return t};K.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),s=parseInt(e.substr(8,2),10),a=parseInt(e.substr(10,2),10),o=parseInt(e.substr(12,2),10),l=0,c=0,u=!1;if(e.charAt(e.length-1)==="Z")u=!0;var d=e.length-5,p=e.charAt(d);if(p==="+"||p==="-"){var h=parseInt(e.substr(d+1,2),10),f=parseInt(e.substr(d+4,2),10);if(c=h*60+f,c*=60000,p==="+")c*=-1;u=!0}if(e.charAt(14)===".")l=parseFloat(e.substr(14),10)*1000;if(u)t.setUTCFullYear(n,r,i),t.setUTCHours(s,a,o,l),t.setTime(+t+c);else t.setFullYear(n,r,i),t.setHours(s,a,o,l);return t};K.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};K.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};K.integerToDer=function(e){var t=qe.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};K.derToInteger=function(e){if(typeof e==="string")e=qe.util.createBuffer(e);var t=e.length()*8;if(t>32)throw Error("Integer too large; max is 32-bits.");return e.getSignedInt(t)};K.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&&qe.util.isArray(t.value)){var s=0;for(var a=0;i&&a<t.value.length;++a){var o=t.value[a];i=!!o.optional;var l=e.value[s];if(!l){if(!o.optional){if(i=!1,r)r.push("["+t.name+'] Missing required element. Expected tag class "'+o.tagClass+'", type "'+o.type+'"')}continue}var c=typeof o.tagClass<"u"&&typeof o.type<"u";if(c&&(l.tagClass!==o.tagClass||l.type!==o.type))if(o.optional){i=!0;continue}else{if(i=!1,r)r.push("["+t.name+"] Tag mismatch. Expected ("+o.tagClass+","+o.type+"), got ("+l.tagClass+","+l.type+")");break}var u=K.validate(l,o,n,r);if(u)++s,i=!0;else if(o.optional)i=!0;else{i=!1;break}}}if(i&&n){if(t.capture)n[t.capture]=e.value;if(t.captureAsn1)n[t.captureAsn1]=e;if(t.captureBitStringContents&&"bitStringContents"in e)n[t.captureBitStringContents]=e.bitStringContents;if(t.captureBitStringValue&&"bitStringContents"in e){var d;if(e.bitStringContents.length<2)n[t.captureBitStringValue]="";else{var 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 lu=/[^\\u0000-\\u00ff]/;K.prettyPrint=function(e,t,n){var r="";if(t=t||0,n=n||2,t>0)r+=`
6
6
  `;var i="";for(var s=0;s<t*n;++s)i+=" ";switch(r+=i+"Tag: ",e.tagClass){case K.Class.UNIVERSAL:r+="Universal:";break;case K.Class.APPLICATION:r+="Application:";break;case K.Class.CONTEXT_SPECIFIC:r+="Context-Specific:";break;case K.Class.PRIVATE:r+="Private:";break}if(e.tagClass===K.Class.UNIVERSAL)switch(r+=e.type,e.type){case K.Type.NONE:r+=" (None)";break;case K.Type.BOOLEAN:r+=" (Boolean)";break;case K.Type.INTEGER:r+=" (Integer)";break;case K.Type.BITSTRING:r+=" (Bit string)";break;case K.Type.OCTETSTRING:r+=" (Octet string)";break;case K.Type.NULL:r+=" (Null)";break;case K.Type.OID:r+=" (Object Identifier)";break;case K.Type.ODESC:r+=" (Object Descriptor)";break;case K.Type.EXTERNAL:r+=" (External or Instance of)";break;case K.Type.REAL:r+=" (Real)";break;case K.Type.ENUMERATED:r+=" (Enumerated)";break;case K.Type.EMBEDDED:r+=" (Embedded PDV)";break;case K.Type.UTF8:r+=" (UTF8)";break;case K.Type.ROID:r+=" (Relative Object Identifier)";break;case K.Type.SEQUENCE:r+=" (Sequence)";break;case K.Type.SET:r+=" (Set)";break;case K.Type.PRINTABLESTRING:r+=" (Printable String)";break;case K.Type.IA5String:r+=" (IA5String (ASCII))";break;case K.Type.UTCTIME:r+=" (UTC time)";break;case K.Type.GENERALIZEDTIME:r+=" (Generalized time)";break;case K.Type.BMPSTRING:r+=" (BMP String)";break}else r+=e.type;if(r+=`
7
7
  `,r+=i+"Constructed: "+e.constructed+`
8
- `,e.composed){var a=0,o="";for(var s=0;s<e.value.length;++s)if(e.value[s]!==void 0){if(a+=1,o+=K.prettyPrint(e.value[s],t+1,n),s+1<e.value.length)o+=","}r+=i+"Sub values: "+a+o}else{if(r+=i+"Value: ",e.type===K.Type.OID){var l=K.derToOid(e.value);if(r+=l,qe.pki&&qe.pki.oids){if(l in qe.pki.oids)r+=" ("+qe.pki.oids[l]+") "}}if(e.type===K.Type.INTEGER)try{r+=K.derToInteger(e.value)}catch(u){r+="0x"+qe.util.bytesToHex(e.value)}else if(e.type===K.Type.BITSTRING){if(e.value.length>1)r+="0x"+qe.util.bytesToHex(e.value.slice(1));else r+="(none)";if(e.value.length>0){var c=e.value.charCodeAt(0);if(c==1)r+=" (1 unused bit shown)";else if(c>1)r+=" ("+c+" unused bits shown)"}}else if(e.type===K.Type.OCTETSTRING){if(!lu.test(e.value))r+="("+e.value+") ";r+="0x"+qe.util.bytesToHex(e.value)}else if(e.type===K.Type.UTF8)try{r+=qe.util.decodeUtf8(e.value)}catch(u){if(u.message==="URI malformed")r+="0x"+qe.util.bytesToHex(e.value)+" (malformed UTF8)";else throw u}else if(e.type===K.Type.PRINTABLESTRING||e.type===K.Type.IA5String)r+=e.value;else if(lu.test(e.value))r+="0x"+qe.util.bytesToHex(e.value);else if(e.value.length===0)r+="[null]";else r+=e.value}return r}});var rr=de(function(p1,uu){var Ns=ve();uu.exports=Ns.md=Ns.md||{};Ns.md.algorithms=Ns.md.algorithms||{}});var An=de(function(h1,du){var xr=ve();rr();Pe();var B0=du.exports=xr.hmac=xr.hmac||{};B0.create=function(){var e=null,t=null,n=null,r=null,i={};return i.start=function(s,a){if(s!==null)if(typeof s==="string")if(s=s.toLowerCase(),s in xr.md.algorithms)t=xr.md.algorithms[s].create();else throw Error('Unknown hash algorithm "'+s+'"');else t=s;if(a===null)a=e;else{if(typeof a==="string")a=xr.util.createBuffer(a);else if(xr.util.isArray(a)){var o=a;a=xr.util.createBuffer();for(var l=0;l<o.length;++l)a.putByte(o[l])}var c=a.length();if(c>t.blockLength)t.start(),t.update(a.bytes()),a=t.digest();n=xr.util.createBuffer(),r=xr.util.createBuffer(),c=a.length();for(var l=0;l<c;++l){var o=a.at(l);n.putByte(54^o),r.putByte(92^o)}if(c<t.blockLength){var o=t.blockLength-c;for(var l=0;l<o;++l)n.putByte(54),r.putByte(92)}e=a,n=n.bytes(),r=r.bytes()}t.start(),t.update(n)},i.update=function(s){t.update(s)},i.getMac=function(){var s=t.digest().bytes();return t.start(),t.update(r),t.update(s),t.digest()},i.digest=i.getMac,i}});var Ls=de(function(g1,gu){var nr=ve();rr();Pe();var pu=gu.exports=nr.md5=nr.md5||{};nr.md.md5=nr.md.algorithms.md5=pu;pu.create=function(){if(!hu)P0();var e=null,t=nr.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 s=0;s<i;++s)r.fullMessageLength.push(0);return t=nr.util.createBuffer(),e={h0:1732584193,h1:4023233417,h2:2562383102,h3:271733878},r},r.start(),r.update=function(i,s){if(s==="utf8")i=nr.util.encodeUtf8(i);var a=i.length;r.messageLength+=a,a=[a/4294967296>>>0,a>>>0];for(var o=r.fullMessageLength.length-1;o>=0;--o)r.fullMessageLength[o]+=a[1],a[1]=a[0]+(r.fullMessageLength[o]/4294967296>>>0),r.fullMessageLength[o]=r.fullMessageLength[o]>>>0,a[0]=a[1]/4294967296>>>0;if(t.putBytes(i),fu(e,n,t),t.read>2048||t.length()===0)t.compact();return r},r.digest=function(){var i=nr.util.createBuffer();i.putBytes(t.bytes());var s=r.fullMessageLength[r.fullMessageLength.length-1]+r.messageLengthSize,a=s&r.blockLength-1;i.putBytes(vo.substr(0,r.blockLength-a));var o,l=0;for(var c=r.fullMessageLength.length-1;c>=0;--c)o=r.fullMessageLength[c]*8+l,l=o/4294967296>>>0,i.putInt32Le(o>>>0);var u={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3};fu(u,n,i);var d=nr.util.createBuffer();return d.putInt32Le(u.h0),d.putInt32Le(u.h1),d.putInt32Le(u.h2),d.putInt32Le(u.h3),d},r};var vo=null,Ds=null,xi=null,_n=null,hu=!1;function P0(){vo=String.fromCharCode(128),vo+=nr.util.fillString(String.fromCharCode(0),64),Ds=[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],xi=[7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22,5,9,14,20,5,9,14,20,5,9,14,20,5,9,14,20,4,11,16,23,4,11,16,23,4,11,16,23,4,11,16,23,6,10,15,21,6,10,15,21,6,10,15,21,6,10,15,21],_n=Array(64);for(var e=0;e<64;++e)_n[e]=Math.floor(Math.abs(Math.sin(e+1))*4294967296);hu=!0}function fu(e,t,n){var r,i,s,a,o,l,c,u,d=n.length();while(d>=64){i=e.h0,s=e.h1,a=e.h2,o=e.h3;for(u=0;u<16;++u)t[u]=n.getInt32Le(),l=o^s&(a^o),r=i+l+_n[u]+t[u],c=xi[u],i=o,o=a,a=s,s+=r<<c|r>>>32-c;for(;u<32;++u)l=a^o&(s^a),r=i+l+_n[u]+t[Ds[u]],c=xi[u],i=o,o=a,a=s,s+=r<<c|r>>>32-c;for(;u<48;++u)l=s^a^o,r=i+l+_n[u]+t[Ds[u]],c=xi[u],i=o,o=a,a=s,s+=r<<c|r>>>32-c;for(;u<64;++u)l=a^(s|~o),r=i+l+_n[u]+t[Ds[u]],c=xi[u],i=o,o=a,a=s,s+=r<<c|r>>>32-c;e.h0=e.h0+i|0,e.h1=e.h1+s|0,e.h2=e.h2+a|0,e.h3=e.h3+o|0,d-=64}}});var sn=de(function(m1,yu){var Us=ve();Pe();var mu=yu.exports=Us.pem=Us.pem||{};mu.encode=function(e,t){t=t||{};var n="-----BEGIN "+e.type+`-----\r
8
+ `,e.composed){var a=0,o="";for(var s=0;s<e.value.length;++s)if(e.value[s]!==void 0){if(a+=1,o+=K.prettyPrint(e.value[s],t+1,n),s+1<e.value.length)o+=","}r+=i+"Sub values: "+a+o}else{if(r+=i+"Value: ",e.type===K.Type.OID){var l=K.derToOid(e.value);if(r+=l,qe.pki&&qe.pki.oids){if(l in qe.pki.oids)r+=" ("+qe.pki.oids[l]+") "}}if(e.type===K.Type.INTEGER)try{r+=K.derToInteger(e.value)}catch(u){r+="0x"+qe.util.bytesToHex(e.value)}else if(e.type===K.Type.BITSTRING){if(e.value.length>1)r+="0x"+qe.util.bytesToHex(e.value.slice(1));else r+="(none)";if(e.value.length>0){var c=e.value.charCodeAt(0);if(c==1)r+=" (1 unused bit shown)";else if(c>1)r+=" ("+c+" unused bits shown)"}}else if(e.type===K.Type.OCTETSTRING){if(!lu.test(e.value))r+="("+e.value+") ";r+="0x"+qe.util.bytesToHex(e.value)}else if(e.type===K.Type.UTF8)try{r+=qe.util.decodeUtf8(e.value)}catch(u){if(u.message==="URI malformed")r+="0x"+qe.util.bytesToHex(e.value)+" (malformed UTF8)";else throw u}else if(e.type===K.Type.PRINTABLESTRING||e.type===K.Type.IA5String)r+=e.value;else if(lu.test(e.value))r+="0x"+qe.util.bytesToHex(e.value);else if(e.value.length===0)r+="[null]";else r+=e.value}return r}});var rr=de(function(f1,uu){var Ns=ye();uu.exports=Ns.md=Ns.md||{};Ns.md.algorithms=Ns.md.algorithms||{}});var An=de(function(p1,du){var xr=ye();rr();Ne();var R0=du.exports=xr.hmac=xr.hmac||{};R0.create=function(){var e=null,t=null,n=null,r=null,i={};return i.start=function(s,a){if(s!==null)if(typeof s==="string")if(s=s.toLowerCase(),s in xr.md.algorithms)t=xr.md.algorithms[s].create();else throw Error('Unknown hash algorithm "'+s+'"');else t=s;if(a===null)a=e;else{if(typeof a==="string")a=xr.util.createBuffer(a);else if(xr.util.isArray(a)){var o=a;a=xr.util.createBuffer();for(var l=0;l<o.length;++l)a.putByte(o[l])}var c=a.length();if(c>t.blockLength)t.start(),t.update(a.bytes()),a=t.digest();n=xr.util.createBuffer(),r=xr.util.createBuffer(),c=a.length();for(var l=0;l<c;++l){var o=a.at(l);n.putByte(54^o),r.putByte(92^o)}if(c<t.blockLength){var o=t.blockLength-c;for(var l=0;l<o;++l)n.putByte(54),r.putByte(92)}e=a,n=n.bytes(),r=r.bytes()}t.start(),t.update(n)},i.update=function(s){t.update(s)},i.getMac=function(){var s=t.digest().bytes();return t.start(),t.update(r),t.update(s),t.digest()},i.digest=i.getMac,i}});var Ls=de(function(h1,gu){var nr=ye();rr();Ne();var pu=gu.exports=nr.md5=nr.md5||{};nr.md.md5=nr.md.algorithms.md5=pu;pu.create=function(){if(!hu)B0();var e=null,t=nr.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 s=0;s<i;++s)r.fullMessageLength.push(0);return t=nr.util.createBuffer(),e={h0:1732584193,h1:4023233417,h2:2562383102,h3:271733878},r},r.start(),r.update=function(i,s){if(s==="utf8")i=nr.util.encodeUtf8(i);var a=i.length;r.messageLength+=a,a=[a/4294967296>>>0,a>>>0];for(var o=r.fullMessageLength.length-1;o>=0;--o)r.fullMessageLength[o]+=a[1],a[1]=a[0]+(r.fullMessageLength[o]/4294967296>>>0),r.fullMessageLength[o]=r.fullMessageLength[o]>>>0,a[0]=a[1]/4294967296>>>0;if(t.putBytes(i),fu(e,n,t),t.read>2048||t.length()===0)t.compact();return r},r.digest=function(){var i=nr.util.createBuffer();i.putBytes(t.bytes());var s=r.fullMessageLength[r.fullMessageLength.length-1]+r.messageLengthSize,a=s&r.blockLength-1;i.putBytes(vo.substr(0,r.blockLength-a));var o,l=0;for(var c=r.fullMessageLength.length-1;c>=0;--c)o=r.fullMessageLength[c]*8+l,l=o/4294967296>>>0,i.putInt32Le(o>>>0);var u={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3};fu(u,n,i);var d=nr.util.createBuffer();return d.putInt32Le(u.h0),d.putInt32Le(u.h1),d.putInt32Le(u.h2),d.putInt32Le(u.h3),d},r};var vo=null,Ds=null,xi=null,_n=null,hu=!1;function B0(){vo=String.fromCharCode(128),vo+=nr.util.fillString(String.fromCharCode(0),64),Ds=[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],xi=[7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22,5,9,14,20,5,9,14,20,5,9,14,20,5,9,14,20,4,11,16,23,4,11,16,23,4,11,16,23,4,11,16,23,6,10,15,21,6,10,15,21,6,10,15,21,6,10,15,21],_n=Array(64);for(var e=0;e<64;++e)_n[e]=Math.floor(Math.abs(Math.sin(e+1))*4294967296);hu=!0}function fu(e,t,n){var r,i,s,a,o,l,c,u,d=n.length();while(d>=64){i=e.h0,s=e.h1,a=e.h2,o=e.h3;for(u=0;u<16;++u)t[u]=n.getInt32Le(),l=o^s&(a^o),r=i+l+_n[u]+t[u],c=xi[u],i=o,o=a,a=s,s+=r<<c|r>>>32-c;for(;u<32;++u)l=a^o&(s^a),r=i+l+_n[u]+t[Ds[u]],c=xi[u],i=o,o=a,a=s,s+=r<<c|r>>>32-c;for(;u<48;++u)l=s^a^o,r=i+l+_n[u]+t[Ds[u]],c=xi[u],i=o,o=a,a=s,s+=r<<c|r>>>32-c;for(;u<64;++u)l=a^(s|~o),r=i+l+_n[u]+t[Ds[u]],c=xi[u],i=o,o=a,a=s,s+=r<<c|r>>>32-c;e.h0=e.h0+i|0,e.h1=e.h1+s|0,e.h2=e.h2+a|0,e.h3=e.h3+o|0,d-=64}}});var sn=de(function(g1,yu){var Us=ye();Ne();var mu=yu.exports=Us.pem=Us.pem||{};mu.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+=Os(r);if(e.contentDomain)r={name:"Content-Domain",values:[e.contentDomain]},n+=Os(r);if(e.dekInfo){if(r={name:"DEK-Info",values:[e.dekInfo.algorithm]},e.dekInfo.parameters)r.values.push(e.dekInfo.parameters);n+=Os(r)}if(e.headers)for(var i=0;i<e.headers.length;++i)n+=Os(e.headers[i]);if(e.procType)n+=`\r
10
10
  `;return n+=Us.util.encode64(e.body,t.maxline||64)+`\r
11
11
  `,n+="-----END "+e.type+`-----\r
12
- `,n};mu.decode=function(e){var t=[],n=L0(e),r=/(?:^|[^\x21-\x7e])([\x21-\x7e]+):\s*([\x21-\x7e\s^:]+)/,i=/\r?\n/,s;while(!0){if(s=n.next(),!s)break;var a=s[1];if(a==="NEW CERTIFICATE REQUEST")a="CERTIFICATE REQUEST";var o={type:a,procType:null,contentDomain:null,dekInfo:null,headers:[],body:Us.util.decode64(s[3])};if(t.push(o),!s[2])continue;var l=s[2].split(i),c=0;while(s&&c<l.length){var u=D0(l[c]);for(var d=c+1;d<l.length;++d){var p=l[d];if(!/\s/.test(p[0]))break;u+=p,c=d}if(s=u.match(r),s){var h={name:s[1],values:[]},f=s[2].split(",");for(var v=0;v<f.length;++v)h.values.push(N0(f[v]));if(!o.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.');o.procType={version:f[0],type:f[1]}}else if(!o.contentDomain&&h.name==="Content-Domain")o.contentDomain=f[0]||"";else if(!o.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.');o.dekInfo={algorithm:f[0],parameters:f[1]||null}}else o.headers.push(h)}++c}if(o.procType==="ENCRYPTED"&&!o.dekInfo)throw Error('Invalid PEM formatted message. The "DEK-Info" header must be present if "Proc-Type" is "ENCRYPTED".')}if(t.length===0)throw Error("Invalid PEM formatted message.");return t};function Os(e){var t=e.name+": ",n=[],r=function(l,c){return" "+c};for(var i=0;i<e.values.length;++i)n.push(e.values[i].replace(/^(\S+\r\n)/,r));t+=n.join(",")+`\r
12
+ `,n};mu.decode=function(e){var t=[],n=D0(e),r=/(?:^|[^\x21-\x7e])([\x21-\x7e]+):\s*([\x21-\x7e\s^:]+)/,i=/\r?\n/,s;while(!0){if(s=n.next(),!s)break;var a=s[1];if(a==="NEW CERTIFICATE REQUEST")a="CERTIFICATE REQUEST";var o={type:a,procType:null,contentDomain:null,dekInfo:null,headers:[],body:Us.util.decode64(s[3])};if(t.push(o),!s[2])continue;var l=s[2].split(i),c=0;while(s&&c<l.length){var u=N0(l[c]);for(var d=c+1;d<l.length;++d){var p=l[d];if(!/\s/.test(p[0]))break;u+=p,c=d}if(s=u.match(r),s){var h={name:s[1],values:[]},f=s[2].split(",");for(var v=0;v<f.length;++v)h.values.push(P0(f[v]));if(!o.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.');o.procType={version:f[0],type:f[1]}}else if(!o.contentDomain&&h.name==="Content-Domain")o.contentDomain=f[0]||"";else if(!o.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.');o.dekInfo={algorithm:f[0],parameters:f[1]||null}}else o.headers.push(h)}++c}if(o.procType==="ENCRYPTED"&&!o.dekInfo)throw Error('Invalid PEM formatted message. The "DEK-Info" header must be present if "Proc-Type" is "ENCRYPTED".')}if(t.length===0)throw Error("Invalid PEM formatted message.");return t};function Os(e){var t=e.name+": ",n=[],r=function(l,c){return" "+c};for(var i=0;i<e.values.length;++i)n.push(e.values[i].replace(/^(\S+\r\n)/,r));t+=n.join(",")+`\r
13
13
  `;var s=0,a=-1;for(var i=0;i<t.length;++i,++s)if(s>65&&a!==-1){var o=t[a];if(o===",")++a,t=t.substr(0,a)+`\r
14
14
  `+t.substr(a);else t=t.substr(0,a)+`\r
15
- `+o+t.substr(a+1);s=i-a-1,a=-1,++i}else if(t[i]===" "||t[i]==="\t"||t[i]===",")a=i;return t}function N0(e){return e.replace(/^\s+/,"")}function D0(e){var t=e.length;while(t>0&&/\s/.test(e.charAt(t-1)))--t;return e.substring(0,t)}function L0(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 s(S,A){S.lastIndex=A;var b=S.exec(e);return b?b.index:e.length}function a(S){for(var A=S;A<e.length&&i.test(e.charAt(A));++A)if(A>S&&e.substr(A,5)==="-----")return e.substring(S,A);return null}function o(S){if(e.charAt(S)==="\r")++S;if(e.charAt(S)!==`
15
+ `+o+t.substr(a+1);s=i-a-1,a=-1,++i}else if(t[i]===" "||t[i]==="\t"||t[i]===",")a=i;return t}function P0(e){return e.replace(/^\s+/,"")}function N0(e){var t=e.length;while(t>0&&/\s/.test(e.charAt(t-1)))--t;return e.substring(0,t)}function D0(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 s(S,A){S.lastIndex=A;var b=S.exec(e);return b?b.index:e.length}function a(S){for(var A=S;A<e.length&&i.test(e.charAt(A));++A)if(A>S&&e.substr(A,5)==="-----")return e.substring(S,A);return null}function o(S){if(e.charAt(S)==="\r")++S;if(e.charAt(S)!==`
16
16
  `)return-1;if(e.charAt(++S)==="\r")++S;return e.charAt(S)===`
17
17
  `?S+1:-1}function l(S,A){for(var b=S;b<A;++b){var k=o(b);if(k!==-1&&k<A)return b}return-1}var c={};for(var u=e.indexOf("-----END ");u!==-1;u=e.indexOf("-----END ",u+1)){var d=a(u+9),p=u;while(p>0&&t.test(e.charAt(p-1)))--p;var h=l(p,u);if(d!==null&&h!==-1){var f="$"+d;(c[f]=c[f]||[]).push({end:u,blank:h})}}var v=0,x=-1;return{next:function(){var S;while((S=e.indexOf("-----BEGIN ",v))!==-1){v=S+1;var A=a(S+11);if(A===null)continue;var b=S+16+A.length,k=s(n,b),R=e.substr(k,9)==="-----END "&&a(k+9)===A;if(b>x)x=s(r,b);var I=null,V=c["$"+A];if(V){var J=0,D=V.length;while(J<D){var W=J+D>>1;if(V[W].end>k)D=W;else J=W+1}I=V[J]||null}var Z=[];if(e.charAt(b)==="\r"){if(e.charAt(b+1)===`
18
18
  `)Z.push(b+2);Z.push(b+1)}else if(e.charAt(b)===`
19
- `)Z.push(b+1);Z.push(b);for(var pe=0;pe<Z.length;++pe){var ge=Z[pe],$e=R?l(ge+1,k):-1,xe=k;if($e===-1&&I)$e=I.blank,xe=I.end;if($e!==-1&&$e<=x){var Le=o($e);return v=xe+14+A.length,[e.substring(S,v),A,e.substring(ge,Le),e.substring(Le,xe)]}if(R&&ge<k)return v=k+14+A.length,[e.substring(S,v),A,void 0,e.substring(ge,k)]}}return null}}}});var Si=de(function(y1,xu){var je=ve();ks();po();Pe();xu.exports=je.des=je.des||{};je.des.startEncrypting=function(e,t,n,r){var i=Vs({key:e,output:n,decrypt:!1,mode:r||(t===null?"ECB":"CBC")});return i.start(t),i};je.des.createEncryptionCipher=function(e,t){return Vs({key:e,output:null,decrypt:!1,mode:t})};je.des.startDecrypting=function(e,t,n,r){var i=Vs({key:e,output:n,decrypt:!0,mode:r||(t===null?"ECB":"CBC")});return i.start(t),i};je.des.createDecryptionCipher=function(e,t){return Vs({key:e,output:null,decrypt:!0,mode:t})};je.des.Algorithm=function(e,t){var n=this;n.name=e,n.mode=new t({blockSize:8,cipher:{encrypt:function(r,i){return vu(n._keys,r,i,!1)},decrypt:function(r,i){return vu(n._keys,r,i,!0)}}}),n._init=!1};je.des.Algorithm.prototype.initialize=function(e){if(this._init)return;var t=je.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=K0(t),this._init=!0};ir("DES-ECB",je.cipher.modes.ecb);ir("DES-CBC",je.cipher.modes.cbc);ir("DES-CFB",je.cipher.modes.cfb);ir("DES-OFB",je.cipher.modes.ofb);ir("DES-CTR",je.cipher.modes.ctr);ir("3DES-ECB",je.cipher.modes.ecb);ir("3DES-CBC",je.cipher.modes.cbc);ir("3DES-CFB",je.cipher.modes.cfb);ir("3DES-OFB",je.cipher.modes.ofb);ir("3DES-CTR",je.cipher.modes.ctr);function ir(e,t){var n=function(){return new je.des.Algorithm(e,t)};je.cipher.registerAlgorithm(e,n)}var O0=[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],U0=[-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],V0=[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],F0=[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],M0=[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],$0=[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],W0=[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],H0=[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 K0(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],s=[0,262144,16,262160,0,262144,16,262160,4096,266240,4112,266256,4096,266240,4112,266256],a=[0,1024,32,1056,0,1024,32,1056,33554432,33555456,33554464,33555488,33554432,33555456,33554464,33555488],o=[0,268435456,524288,268959744,2,268435458,524290,268959746,0,268435456,524288,268959744,2,268435458,524290,268959746],l=[0,65536,2048,67584,536870912,536936448,536872960,536938496,131072,196608,133120,198656,537001984,537067520,537004032,537069568],c=[0,262144,0,262144,2,262146,2,262146,33554432,33816576,33554432,33816576,33554434,33816578,33554434,33816578],u=[0,268435456,8,268435464,0,268435456,8,268435464,1024,268436480,1032,268436488,1024,268436480,1032,268436488],d=[0,32,0,32,1048576,1048608,1048576,1048608,8192,8224,8192,8224,1056768,1056800,1056768,1056800],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],f=[0,4,256,260,0,4,256,260,1,5,257,261,1,5,257,261],v=e.length()>8?3:1,x=[],S=[0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0],A=0,b;for(var k=0;k<v;k++){var R=e.getInt32(),I=e.getInt32();b=(R>>>4^I)&252645135,I^=b,R^=b<<4,b=(I>>>-16^R)&65535,R^=b,I^=b<<-16,b=(R>>>2^I)&858993459,I^=b,R^=b<<2,b=(I>>>-16^R)&65535,R^=b,I^=b<<-16,b=(R>>>1^I)&1431655765,I^=b,R^=b<<1,b=(I>>>8^R)&16711935,R^=b,I^=b<<8,b=(R>>>1^I)&1431655765,I^=b,R^=b<<1,b=R<<8|I>>>20&240,R=I<<24|I<<8&16711680|I>>>8&65280|I>>>24&240,I=b;for(var V=0;V<S.length;++V){if(S[V])R=R<<2|R>>>26,I=I<<2|I>>>26;else R=R<<1|R>>>27,I=I<<1|I>>>27;R&=-15,I&=-15;var J=t[R>>>28]|n[R>>>24&15]|r[R>>>20&15]|i[R>>>16&15]|s[R>>>12&15]|a[R>>>8&15]|o[R>>>4&15],D=l[I>>>28]|c[I>>>24&15]|u[I>>>20&15]|d[I>>>16&15]|p[I>>>12&15]|h[I>>>8&15]|f[I>>>4&15];b=(D>>>16^J)&65535,x[A++]=J^b,x[A++]=D^b<<16}}return x}function vu(e,t,n,r){var i=e.length===32?3:9,s;if(i===3)s=r?[30,-2,-2]:[0,32,2];else s=r?[94,62,-2,32,64,2,30,-2,-2]:[0,32,2,62,30,-2,64,96,2];var a,o=t[0],l=t[1];a=(o>>>4^l)&252645135,l^=a,o^=a<<4,a=(o>>>16^l)&65535,l^=a,o^=a<<16,a=(l>>>2^o)&858993459,o^=a,l^=a<<2,a=(l>>>8^o)&16711935,o^=a,l^=a<<8,a=(o>>>1^l)&1431655765,l^=a,o^=a<<1,o=o<<1|o>>>31,l=l<<1|l>>>31;for(var c=0;c<i;c+=3){var u=s[c+1],d=s[c+2];for(var p=s[c];p!=u;p+=d){var h=l^e[p],f=(l>>>4|l<<28)^e[p+1];a=o,o=l,l=a^(U0[h>>>24&63]|F0[h>>>16&63]|$0[h>>>8&63]|H0[h&63]|O0[f>>>24&63]|V0[f>>>16&63]|M0[f>>>8&63]|W0[f&63])}a=o,o=l,l=a}o=o>>>1|o<<31,l=l>>>1|l<<31,a=(o>>>1^l)&1431655765,l^=a,o^=a<<1,a=(l>>>8^o)&16711935,o^=a,l^=a<<8,a=(l>>>2^o)&858993459,o^=a,l^=a<<2,a=(o>>>16^l)&65535,l^=a,o^=a<<16,a=(o>>>4^l)&252645135,l^=a,o^=a<<4,n[0]=o,n[1]=l}function Vs(e){e=e||{};var t=(e.mode||"CBC").toUpperCase(),n="DES-"+t,r;if(e.decrypt)r=je.cipher.createDecipher(n,e.key);else r=je.cipher.createCipher(n,e.key);var i=r.start;return r.start=function(s,a){var o=null;if(a instanceof je.util.ByteBuffer)o=a,a={};a=a||{},a.output=o,a.iv=s,i.call(r,a)},r}});var Fs=de(function(v1,Su){var Ct=ve();An();rr();Pe();var q0=Ct.pkcs5=Ct.pkcs5||{},Sr;if(Ct.util.isNodejs&&!Ct.options.usePureJavaScript)Sr=ui("crypto");Su.exports=Ct.pbkdf2=q0.pbkdf2=function(e,t,n,r,i,s){if(typeof i==="function")s=i,i=null;if(Ct.util.isNodejs&&!Ct.options.usePureJavaScript&&Sr.pbkdf2&&(i===null||typeof i!=="object")&&(Sr.pbkdf2Sync.length>4||(!i||i==="sha1"))){if(typeof i!=="string")i="sha1";if(e=Buffer.from(e,"binary"),t=Buffer.from(t,"binary"),!s){if(Sr.pbkdf2Sync.length===4)return Sr.pbkdf2Sync(e,t,n,r).toString("binary");return Sr.pbkdf2Sync(e,t,n,r,i).toString("binary")}if(Sr.pbkdf2Sync.length===4)return Sr.pbkdf2(e,t,n,r,function(b,k){if(b)return s(b);s(null,k.toString("binary"))});return Sr.pbkdf2(e,t,n,r,i,function(b,k){if(b)return s(b);s(null,k.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 a=i.digestLength;if(r>4294967295*a){var o=Error("Derived key is too long.");if(s)return s(o);throw o}var l=Math.ceil(r/a),c=r-(l-1)*a,u=Ct.hmac.create();u.start(i,e);var d="",p,h,f;if(!s){for(var v=1;v<=l;++v){u.start(null,null),u.update(t),u.update(Ct.util.int32ToBytes(v)),p=f=u.digest().getBytes();for(var x=2;x<=n;++x)u.start(null,null),u.update(f),h=u.digest().getBytes(),p=Ct.util.xorBytes(p,h,a),f=h;d+=v<l?p:p.substr(0,c)}return d}var v=1,x;function S(){if(v>l)return s(null,d);u.start(null,null),u.update(t),u.update(Ct.util.int32ToBytes(v)),p=f=u.digest().getBytes(),x=2,A()}function A(){if(x<=n)return u.start(null,null),u.update(f),h=u.digest().getBytes(),p=Ct.util.xorBytes(p,h,a),f=h,++x,Ct.util.setImmediate(A);d+=v<l?p:p.substr(0,c),++v,S()}S()}});var So=de(function(x1,Tu){var sr=ve();rr();Pe();var Cu=Tu.exports=sr.sha256=sr.sha256||{};sr.md.sha256=sr.md.algorithms.sha256=Cu;Cu.create=function(){if(!wu)G0();var e=null,t=sr.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 s=0;s<i;++s)r.fullMessageLength.push(0);return t=sr.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,s){if(s==="utf8")i=sr.util.encodeUtf8(i);var a=i.length;r.messageLength+=a,a=[a/4294967296>>>0,a>>>0];for(var o=r.fullMessageLength.length-1;o>=0;--o)r.fullMessageLength[o]+=a[1],a[1]=a[0]+(r.fullMessageLength[o]/4294967296>>>0),r.fullMessageLength[o]=r.fullMessageLength[o]>>>0,a[0]=a[1]/4294967296>>>0;if(t.putBytes(i),bu(e,n,t),t.read>2048||t.length()===0)t.compact();return r},r.digest=function(){var i=sr.util.createBuffer();i.putBytes(t.bytes());var s=r.fullMessageLength[r.fullMessageLength.length-1]+r.messageLengthSize,a=s&r.blockLength-1;i.putBytes(xo.substr(0,r.blockLength-a));var o,l,c=r.fullMessageLength[0]*8;for(var u=0;u<r.fullMessageLength.length-1;++u)o=r.fullMessageLength[u+1]*8,l=o/4294967296>>>0,c+=l,i.putInt32(c>>>0),c=o>>>0;i.putInt32(c);var d={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3,h4:e.h4,h5:e.h5,h6:e.h6,h7:e.h7};bu(d,n,i);var p=sr.util.createBuffer();return p.putInt32(d.h0),p.putInt32(d.h1),p.putInt32(d.h2),p.putInt32(d.h3),p.putInt32(d.h4),p.putInt32(d.h5),p.putInt32(d.h6),p.putInt32(d.h7),p},r};var xo=null,wu=!1,Eu=null;function G0(){xo=String.fromCharCode(128),xo+=sr.util.fillString(String.fromCharCode(0),64),Eu=[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],wu=!0}function bu(e,t,n){var r,i,s,a,o,l,c,u,d,p,h,f,v,x,S,A=n.length();while(A>=64){for(c=0;c<16;++c)t[c]=n.getInt32();for(;c<64;++c)r=t[c-2],r=(r>>>17|r<<15)^(r>>>19|r<<13)^r>>>10,i=t[c-15],i=(i>>>7|i<<25)^(i>>>18|i<<14)^i>>>3,t[c]=r+t[c-7]+i+t[c-16]|0;u=e.h0,d=e.h1,p=e.h2,h=e.h3,f=e.h4,v=e.h5,x=e.h6,S=e.h7;for(c=0;c<64;++c)a=(f>>>6|f<<26)^(f>>>11|f<<21)^(f>>>25|f<<7),o=x^f&(v^x),s=(u>>>2|u<<30)^(u>>>13|u<<19)^(u>>>22|u<<10),l=u&d|p&(u^d),r=S+a+o+Eu[c]+t[c],i=s+l,S=x,x=v,v=f,f=h+r>>>0,h=p,p=d,d=u,u=r+i>>>0;e.h0=e.h0+u|0,e.h1=e.h1+d|0,e.h2=e.h2+p|0,e.h3=e.h3+h|0,e.h4=e.h4+f|0,e.h5=e.h5+v|0,e.h6=e.h6+x|0,e.h7=e.h7+S|0,A-=64}}});var bo=de(function(S1,Au){var ar=ve();Pe();var Ms=null;if(ar.util.isNodejs&&!ar.options.usePureJavaScript&&!process.versions["node-webkit"])Ms=ui("crypto");var j0=Au.exports=ar.prng=ar.prng||{};j0.create=function(e){var t={plugin:e,key:null,seed:null,time:null,reseeds:0,generated:0,keyBytes:""},n=e.md,r=Array(32);for(var i=0;i<32;++i)r[i]=n.create();t.pools=r,t.pool=0,t.generate=function(c,u){if(!u)return t.generateSync(c);var d=t.plugin.cipher,p=t.plugin.increment,h=t.plugin.formatKey,f=t.plugin.formatSeed,v=ar.util.createBuffer();t.key=null,x();function x(S){if(S)return u(S);if(v.length()>=c)return u(null,v.getBytes(c));if(t.generated>1048575)t.key=null;if(t.key===null)return ar.util.nextTick(function(){s(x)});var A=d(t.key,t.seed);t.generated+=A.length,v.putBytes(A),t.key=h(d(t.key,p(t.seed))),t.seed=f(d(t.key,t.seed)),ar.util.setImmediate(x)}},t.generateSync=function(c){var u=t.plugin.cipher,d=t.plugin.increment,p=t.plugin.formatKey,h=t.plugin.formatSeed;t.key=null;var f=ar.util.createBuffer();while(f.length()<c){if(t.generated>1048575)t.key=null;if(t.key===null)a();var v=u(t.key,t.seed);t.generated+=v.length,f.putBytes(v),t.key=p(u(t.key,d(t.seed))),t.seed=h(u(t.key,t.seed))}return f.getBytes(c)};function s(c){if(t.pools[0].messageLength>=32)return o(),c();var u=32-t.pools[0].messageLength<<5;t.seedFile(u,function(d,p){if(d)return c(d);t.collect(p),o(),c()})}function a(){if(t.pools[0].messageLength>=32)return o();var c=32-t.pools[0].messageLength<<5;t.collect(t.seedFileSync(c)),o()}function o(){t.reseeds=t.reseeds===4294967295?0:t.reseeds+1;var c=t.plugin.md.create();c.update(t.keyBytes);var u=1;for(var d=0;d<32;++d){if(t.reseeds%u===0)c.update(t.pools[d].digest().getBytes()),t.pools[d].start();u=u<<1}t.keyBytes=c.digest().getBytes(),c.start(),c.update(t.keyBytes);var p=c.digest().getBytes();t.key=t.plugin.formatKey(t.keyBytes),t.seed=t.plugin.formatSeed(p),t.generated=0}function l(c){var u=null,d=ar.util.globalScope,p=d.crypto||d.msCrypto;if(p&&p.getRandomValues)u=function(R){return p.getRandomValues(R)};var h=ar.util.createBuffer();if(u)while(h.length()<c){var f=Math.max(1,Math.min(c-h.length(),65536)/4),v=new Uint32Array(Math.floor(f));try{u(v);for(var x=0;x<v.length;++x)h.putInt32(v[x])}catch(R){if(!(typeof QuotaExceededError<"u"&&R instanceof QuotaExceededError))throw R}}if(h.length()<c){var S,A,b,k=Math.floor(Math.random()*65536);while(h.length()<c){A=16807*(k&65535),S=16807*(k>>16),A+=(S&32767)<<16,A+=S>>15,A=(A&2147483647)+(A>>31),k=A&4294967295;for(var x=0;x<3;++x)b=k>>>(x<<3),b^=Math.floor(Math.random()*256),h.putByte(b&255)}}return h.getBytes(c)}if(Ms)t.seedFile=function(c,u){Ms.randomBytes(c,function(d,p){if(d)return u(d);u(null,p.toString())})},t.seedFileSync=function(c){return Ms.randomBytes(c).toString()};else t.seedFile=function(c,u){try{u(null,l(c))}catch(d){u(d)}},t.seedFileSync=l;return t.collect=function(c){var u=c.length;for(var d=0;d<u;++d)t.pools[t.pool].update(c.substr(d,1)),t.pool=t.pool===31?0:t.pool+1},t.collectInt=function(c,u){var d="";for(var p=0;p<u;p+=8)d+=String.fromCharCode(c>>p&255);t.collect(d)},t.registerWorker=function(c){if(c===self)t.seedFile=function(d,p){function h(f){var v=f.data;if(v.forge&&v.forge.prng)self.removeEventListener("message",h),p(v.forge.prng.err,v.forge.prng.bytes)}self.addEventListener("message",h),self.postMessage({forge:{prng:{needed:d}}})};else{var u=function(d){var p=d.data;if(p.forge&&p.forge.prng)t.seedFile(p.forge.prng.needed,function(h,f){c.postMessage({forge:{prng:{err:h,bytes:f}}})})};c.addEventListener("message",u)}},t}});var Lt=de(function(b1,Co){var ft=ve();Lr();So();bo();Pe();(function(){if(ft.random&&ft.random.getBytes){Co.exports=ft.random;return}(function(e){var t={},n=[,,,,],r=ft.util.createBuffer();t.formatKey=function(d){var p=ft.util.createBuffer(d);return d=[,,,,],d[0]=p.getInt32(),d[1]=p.getInt32(),d[2]=p.getInt32(),d[3]=p.getInt32(),ft.aes._expandKey(d,!1)},t.formatSeed=function(d){var p=ft.util.createBuffer(d);return d=[,,,,],d[0]=p.getInt32(),d[1]=p.getInt32(),d[2]=p.getInt32(),d[3]=p.getInt32(),d},t.cipher=function(d,p){return ft.aes._updateBlock(d,p,n,!1),r.putInt32(n[0]),r.putInt32(n[1]),r.putInt32(n[2]),r.putInt32(n[3]),r.getBytes()},t.increment=function(d){return++d[3],d},t.md=ft.md.sha256;function i(){var d=ft.prng.create(t);return d.getBytes=function(p,h){return d.generate(p,h)},d.getBytesSync=function(p){return d.generate(p)},d}var s=i(),a=null,o=ft.util.globalScope,l=o.crypto||o.msCrypto;if(l&&l.getRandomValues)a=function(d){return l.getRandomValues(d)};if(ft.options.usePureJavaScript||!ft.util.isNodejs&&!a){if(typeof window>"u"||window.document===void 0);if(s.collectInt(+new Date,32),typeof navigator<"u"){var c="";for(var u in navigator)try{if(typeof navigator[u]=="string")c+=navigator[u]}catch(d){}s.collect(c),c=null}if(e)e().mousemove(function(d){s.collectInt(d.clientX,16),s.collectInt(d.clientY,16)}),e().keypress(function(d){s.collectInt(d.charCode,8)})}if(!ft.random)ft.random=s;else for(var u in s)ft.random[u]=s[u];ft.random.createInstance=i,Co.exports=ft.random})(typeof jQuery<"u"?jQuery:null)})()});var Eo=de(function(C1,Iu){var _t=ve();Pe();var wo=[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],_u=[1,2,3,5],z0=function(e,t){return e<<t&65535|(e&65535)>>16-t},X0=function(e,t){return(e&65535)>>t|e<<16-t&65535};Iu.exports=_t.rc2=_t.rc2||{};_t.rc2.expandKey=function(e,t){if(typeof e==="string")e=_t.util.createBuffer(e);t=t||128;var n=e,r=e.length(),i=t,s=Math.ceil(i/8),a=255>>(i&7),o;for(o=r;o<128;o++)n.putByte(wo[n.at(o-1)+n.at(o-r)&255]);n.setAt(128-s,wo[n.at(128-s)&a]);for(o=127-s;o>=0;o--)n.setAt(o,wo[n.at(o+1)^n.at(o+s)]);return n};var ku=function(e,t,n){var r=!1,i=null,s=null,a=null,o,l,c,u,d=[];e=_t.rc2.expandKey(e,t);for(c=0;c<64;c++)d.push(e.getInt16Le());if(n)o=function(f){for(c=0;c<4;c++)f[c]+=d[u]+(f[(c+3)%4]&f[(c+2)%4])+(~f[(c+3)%4]&f[(c+1)%4]),f[c]=z0(f[c],_u[c]),u++},l=function(f){for(c=0;c<4;c++)f[c]+=d[f[(c+3)%4]&63]};else o=function(f){for(c=3;c>=0;c--)f[c]=X0(f[c],_u[c]),f[c]-=d[u]+(f[(c+3)%4]&f[(c+2)%4])+(~f[(c+3)%4]&f[(c+1)%4]),u--},l=function(f){for(c=3;c>=0;c--)f[c]-=d[f[(c+3)%4]&63]};var p=function(f){var v=[];for(c=0;c<4;c++){var x=i.getInt16Le();if(a!==null)if(n)x^=a.getInt16Le();else a.putInt16Le(x);v.push(x&65535)}u=n?0:63;for(var S=0;S<f.length;S++)for(var A=0;A<f[S][0];A++)f[S][1](v);for(c=0;c<4;c++){if(a!==null)if(n)a.putInt16Le(v[c]);else v[c]^=a.getInt16Le();s.putInt16Le(v[c])}},h=null;return h={start:function(f,v){if(f){if(typeof f==="string")f=_t.util.createBuffer(f)}r=!1,i=_t.util.createBuffer(),s=v||new _t.util.createBuffer,a=f,h.output=s},update:function(f){if(!r)i.putBuffer(f);while(i.length()>=8)p([[5,o],[1,l],[6,o],[1,l],[5,o]])},finish:function(f){var v=!0;if(n)if(f)v=f(8,i,!n);else{var x=i.length()===8?8:8-i.length();i.fillWithByte(x,x)}if(v)r=!0,h.update();if(!n){if(v=i.length()===0,v)if(f)v=f(8,s,!n);else{var S=s.length(),A=s.at(S-1);if(A>S)v=!1;else s.truncate(A)}}return v}},h};_t.rc2.startEncrypting=function(e,t,n){var r=_t.rc2.createEncryptionCipher(e,128);return r.start(t,n),r};_t.rc2.createEncryptionCipher=function(e,t){return ku(e,t,!0)};_t.rc2.startDecrypting=function(e,t,n){var r=_t.rc2.createDecryptionCipher(e,128);return r.start(t,n),r};_t.rc2.createDecryptionCipher=function(e,t){return ku(e,t,!1)}});var Ci=de(function(w1,Uu){var To=ve();Uu.exports=To.jsbn=To.jsbn||{};var br,Q0=244837814094590,Ru=(Q0&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)}To.jsbn.BigInteger=L;function Re(){return new L(null)}function Y0(e,t,n,r,i,s){while(--s>=0){var a=t*this.data[e++]+n.data[r]+i;i=Math.floor(a/67108864),n.data[r++]=a&67108863}return i}function J0(e,t,n,r,i,s){var a=t&32767,o=t>>15;while(--s>=0){var l=this.data[e]&32767,c=this.data[e++]>>15,u=o*l+c*a;l=a*l+((u&32767)<<15)+n.data[r]+(i&1073741823),i=(l>>>30)+(u>>>15)+o*c+(i>>>30),n.data[r++]=l&1073741823}return i}function Bu(e,t,n,r,i,s){var a=t&16383,o=t>>14;while(--s>=0){var l=this.data[e]&16383,c=this.data[e++]>>14,u=o*l+c*a;l=a*l+((u&16383)<<14)+n.data[r]+i,i=(l>>28)+(u>>14)+o*c,n.data[r++]=l&268435455}return i}if(typeof navigator>"u")L.prototype.am=Bu,br=28;else if(Ru&&navigator.appName=="Microsoft Internet Explorer")L.prototype.am=J0,br=30;else if(Ru&&navigator.appName!="Netscape")L.prototype.am=Y0,br=26;else L.prototype.am=Bu,br=28;L.prototype.DB=br;L.prototype.DM=(1<<br)-1;L.prototype.DV=1<<br;var Ao=52;L.prototype.FV=Math.pow(2,Ao);L.prototype.F1=Ao-br;L.prototype.F2=2*br-Ao;var Z0="0123456789abcdefghijklmnopqrstuvwxyz",$s=[],kn,Ot;kn=48;for(Ot=0;Ot<=9;++Ot)$s[kn++]=Ot;kn=97;for(Ot=10;Ot<36;++Ot)$s[kn++]=Ot;kn=65;for(Ot=10;Ot<36;++Ot)$s[kn++]=Ot;function Pu(e){return Z0.charAt(e)}function Nu(e,t){var n=$s[e.charCodeAt(t)];return n==null?-1:n}function eg(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 tg(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 Ur(e){var t=Re();return t.fromInt(e),t}function rg(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,s=0;while(--r>=0){var a=n==8?e[r]&255:Nu(e,r);if(a<0){if(e.charAt(r)=="-")i=!0;continue}if(i=!1,s==0)this.data[this.t++]=a;else if(s+n>this.DB)this.data[this.t-1]|=(a&(1<<this.DB-s)-1)<<s,this.data[this.t++]=a>>this.DB-s;else this.data[this.t-1]|=a<<s;if(s+=n,s>=this.DB)s-=this.DB}if(n==8&&(e[0]&128)!=0){if(this.s=-1,s>0)this.data[this.t-1]|=(1<<this.DB-s)-1<<s}if(this.clamp(),i)L.ZERO.subTo(this,this)}function ng(){var e=this.s&this.DM;while(this.t>0&&this.data[this.t-1]==e)--this.t}function ig(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,s="",a=this.t,o=this.DB-a*this.DB%t;if(a-- >0){if(o<this.DB&&(r=this.data[a]>>o)>0)i=!0,s=Pu(r);while(a>=0){if(o<t)r=(this.data[a]&(1<<o)-1)<<t-o,r|=this.data[--a]>>(o+=this.DB-t);else if(r=this.data[a]>>(o-=t)&n,o<=0)o+=this.DB,--a;if(r>0)i=!0;if(i)s+=Pu(r)}}return i?s:"0"}function sg(){var e=Re();return L.ZERO.subTo(this,e),e}function ag(){return this.s<0?this.negate():this}function og(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 Ws(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 lg(){if(this.t<=0)return 0;return this.DB*(this.t-1)+Ws(this.data[this.t-1]^this.s&this.DM)}function cg(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 ug(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 dg(e,t){var n=e%this.DB,r=this.DB-n,i=(1<<r)-1,s=Math.floor(e/this.DB),a=this.s<<n&this.DM,o;for(o=this.t-1;o>=0;--o)t.data[o+s+1]=this.data[o]>>r|a,a=(this.data[o]&i)<<n;for(o=s-1;o>=0;--o)t.data[o]=0;t.data[s]=a,t.t=this.t+s+1,t.s=this.s,t.clamp()}function fg(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,s=(1<<r)-1;t.data[0]=this.data[n]>>r;for(var a=n+1;a<this.t;++a)t.data[a-n-1]|=(this.data[a]&s)<<i,t.data[a-n]=this.data[a]>>r;if(r>0)t.data[this.t-n-1]|=(this.s&s)<<i;t.t=this.t-n,t.clamp()}function pg(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 hg(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 gg(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 mg(e,t,n){var r=e.abs();if(r.t<=0)return;var i=this.abs();if(i.t<r.t){if(t!=null)t.fromInt(0);if(n!=null)this.copyTo(n);return}if(n==null)n=Re();var s=Re(),a=this.s,o=e.s,l=this.DB-Ws(r.data[r.t-1]);if(l>0)r.lShiftTo(l,s),i.lShiftTo(l,n);else r.copyTo(s),i.copyTo(n);var c=s.t,u=s.data[c-1];if(u==0)return;var d=u*(1<<this.F1)+(c>1?s.data[c-2]>>this.F2:0),p=this.FV/d,h=(1<<this.F1)/d,f=1<<this.F2,v=n.t,x=v-c,S=t==null?Re():t;if(s.dlShiftTo(x,S),n.compareTo(S)>=0)n.data[n.t++]=1,n.subTo(S,n);L.ONE.dlShiftTo(c,S),S.subTo(s,s);while(s.t<c)s.data[s.t++]=0;while(--x>=0){var A=n.data[--v]==u?this.DM:Math.floor(n.data[v]*p+(n.data[v-1]+f)*h);if((n.data[v]+=s.am(0,A,n,x,0,c))<A){s.dlShiftTo(x,S),n.subTo(S,n);while(n.data[v]<--A)n.subTo(S,n)}}if(t!=null){if(n.drShiftTo(c,t),a!=o)L.ZERO.subTo(t,t)}if(n.t=c,n.clamp(),l>0)n.rShiftTo(l,n);if(a<0)L.ZERO.subTo(n,n)}function yg(e){var t=Re();if(this.abs().divRemTo(e,null,t),this.s<0&&t.compareTo(L.ZERO)>0)e.subTo(t,t);return t}function an(e){this.m=e}function vg(e){if(e.s<0||e.compareTo(this.m)>=0)return e.mod(this.m);else return e}function xg(e){return e}function Sg(e){e.divRemTo(this.m,null,e)}function bg(e,t,n){e.multiplyTo(t,n),this.reduce(n)}function Cg(e,t){e.squareTo(t),this.reduce(t)}an.prototype.convert=vg;an.prototype.revert=xg;an.prototype.reduce=Sg;an.prototype.mulTo=bg;an.prototype.sqrTo=Cg;function wg(){if(this.t<1)return 0;var e=this.data[0];if((e&1)==0)return 0;var t=e&3;return t=t*(2-(e&15)*t)&15,t=t*(2-(e&255)*t)&255,t=t*(2-((e&65535)*t&65535))&65535,t=t*(2-e*t%this.DV)%this.DV,t>0?this.DV-t:-t}function on(e){this.m=e,this.mp=e.invDigit(),this.mpl=this.mp&32767,this.mph=this.mp>>15,this.um=(1<<e.DB-15)-1,this.mt2=2*e.t}function Eg(e){var t=Re();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 Tg(e){var t=Re();return e.copyTo(t),this.reduce(t),t}function Ag(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 _g(e,t){e.squareTo(t),this.reduce(t)}function kg(e,t,n){e.multiplyTo(t,n),this.reduce(n)}on.prototype.convert=Eg;on.prototype.revert=Tg;on.prototype.reduce=Ag;on.prototype.mulTo=kg;on.prototype.sqrTo=_g;function Ig(){return(this.t>0?this.data[0]&1:this.s)==0}function Rg(e,t){if(e>4294967295||e<1)return L.ONE;var n=Re(),r=Re(),i=t.convert(this),s=Ws(e)-1;i.copyTo(n);while(--s>=0)if(t.sqrTo(n,r),(e&1<<s)>0)t.mulTo(r,i,n);else{var a=n;n=r,r=a}return t.revert(n)}function Bg(e,t){var n;if(e<256||t.isEven())n=new an(t);else n=new on(t);return this.exp(e,n)}L.prototype.copyTo=eg;L.prototype.fromInt=tg;L.prototype.fromString=rg;L.prototype.clamp=ng;L.prototype.dlShiftTo=cg;L.prototype.drShiftTo=ug;L.prototype.lShiftTo=dg;L.prototype.rShiftTo=fg;L.prototype.subTo=pg;L.prototype.multiplyTo=hg;L.prototype.squareTo=gg;L.prototype.divRemTo=mg;L.prototype.invDigit=wg;L.prototype.isEven=Ig;L.prototype.exp=Rg;L.prototype.toString=ig;L.prototype.negate=sg;L.prototype.abs=ag;L.prototype.compareTo=og;L.prototype.bitLength=lg;L.prototype.mod=yg;L.prototype.modPowInt=Bg;L.ZERO=Ur(0);L.ONE=Ur(1);function Pg(){var e=Re();return this.copyTo(e),e}function Ng(){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 Dg(){return this.t==0?this.s:this.data[0]<<24>>24}function Lg(){return this.t==0?this.s:this.data[0]<<16>>16}function Og(e){return Math.floor(Math.LN2*this.DB/Math.log(e))}function Ug(){if(this.s<0)return-1;else if(this.t<=0||this.t==1&&this.data[0]<=0)return 0;else return 1}function Vg(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=Ur(n),i=Re(),s=Re(),a="";this.divRemTo(r,i,s);while(i.signum()>0)a=(n+s.intValue()).toString(e).substr(1)+a,i.divRemTo(r,i,s);return s.intValue().toString(e)+a}function Fg(e,t){if(this.fromInt(0),t==null)t=10;var n=this.chunkSize(t),r=Math.pow(t,n),i=!1,s=0,a=0;for(var o=0;o<e.length;++o){var l=Nu(e,o);if(l<0){if(e.charAt(o)=="-"&&this.signum()==0)i=!0;continue}if(a=t*a+l,++s>=n)this.dMultiply(r),this.dAddOffset(a,0),s=0,a=0}if(s>0)this.dMultiply(Math.pow(t,s)),this.dAddOffset(a,0);if(i)L.ZERO.subTo(this,this)}function Mg(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),_o,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 $g(){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 Wg(e){return this.compareTo(e)==0}function Hg(e){return this.compareTo(e)<0?this:e}function Kg(e){return this.compareTo(e)>0?this:e}function qg(e,t,n){var r,i,s=Math.min(e.t,this.t);for(r=0;r<s;++r)n.data[r]=t(this.data[r],e.data[r]);if(e.t<this.t){i=e.s&this.DM;for(r=s;r<this.t;++r)n.data[r]=t(this.data[r],i);n.t=this.t}else{i=this.s&this.DM;for(r=s;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 Gg(e,t){return e&t}function jg(e){var t=Re();return this.bitwiseTo(e,Gg,t),t}function _o(e,t){return e|t}function zg(e){var t=Re();return this.bitwiseTo(e,_o,t),t}function Du(e,t){return e^t}function Xg(e){var t=Re();return this.bitwiseTo(e,Du,t),t}function Lu(e,t){return e&~t}function Qg(e){var t=Re();return this.bitwiseTo(e,Lu,t),t}function Yg(){var e=Re();for(var t=0;t<this.t;++t)e.data[t]=this.DM&~this.data[t];return e.t=this.t,e.s=~this.s,e}function Jg(e){var t=Re();if(e<0)this.rShiftTo(-e,t);else this.lShiftTo(e,t);return t}function Zg(e){var t=Re();if(e<0)this.lShiftTo(-e,t);else this.rShiftTo(e,t);return t}function em(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 tm(){for(var e=0;e<this.t;++e)if(this.data[e]!=0)return e*this.DB+em(this.data[e]);if(this.s<0)return this.t*this.DB;return-1}function rm(e){var t=0;while(e!=0)e&=e-1,++t;return t}function nm(){var e=0,t=this.s&this.DM;for(var n=0;n<this.t;++n)e+=rm(this.data[n]^t);return e}function im(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 sm(e,t){var n=L.ONE.shiftLeft(e);return this.bitwiseTo(n,t,n),n}function am(e){return this.changeBit(e,_o)}function om(e){return this.changeBit(e,Lu)}function lm(e){return this.changeBit(e,Du)}function cm(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 um(e){var t=Re();return this.addTo(e,t),t}function dm(e){var t=Re();return this.subTo(e,t),t}function fm(e){var t=Re();return this.multiplyTo(e,t),t}function pm(){var e=Re();return this.squareTo(e),e}function hm(e){var t=Re();return this.divRemTo(e,t,null),t}function gm(e){var t=Re();return this.divRemTo(e,null,t),t}function mm(e){var t=Re(),n=Re();return this.divRemTo(e,t,n),[t,n]}function ym(e){this.data[this.t]=this.am(0,e-1,this,0,0,this.t),++this.t,this.clamp()}function vm(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 bi(){}function Ou(e){return e}function xm(e,t,n){e.multiplyTo(t,n)}function Sm(e,t){e.squareTo(t)}bi.prototype.convert=Ou;bi.prototype.revert=Ou;bi.prototype.mulTo=xm;bi.prototype.sqrTo=Sm;function bm(e){return this.exp(e,new bi)}function Cm(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 wm(e,t,n){--t;var r=n.t=this.t+e.t-t;n.s=0;while(--r>=0)n.data[r]=0;for(r=Math.max(t-this.t,0);r<e.t;++r)n.data[this.t+r-t]=this.am(t-r,e.data[r],n,0,0,this.t+r-t);n.clamp(),n.drShiftTo(1,n)}function In(e){this.r2=Re(),this.q3=Re(),L.ONE.dlShiftTo(2*e.t,this.r2),this.mu=this.r2.divide(e),this.m=e}function Em(e){if(e.s<0||e.t>2*this.m.t)return e.mod(this.m);else if(e.compareTo(this.m)<0)return e;else{var t=Re();return e.copyTo(t),this.reduce(t),t}}function Tm(e){return e}function Am(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 _m(e,t){e.squareTo(t),this.reduce(t)}function km(e,t,n){e.multiplyTo(t,n),this.reduce(n)}In.prototype.convert=Em;In.prototype.revert=Tm;In.prototype.reduce=Am;In.prototype.mulTo=km;In.prototype.sqrTo=_m;function Im(e,t){var n=e.bitLength(),r,i=Ur(1),s;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)s=new an(t);else if(t.isEven())s=new In(t);else s=new on(t);var a=[],o=3,l=r-1,c=(1<<r)-1;if(a[1]=s.convert(this),r>1){var u=Re();s.sqrTo(a[1],u);while(o<=c)a[o]=Re(),s.mulTo(u,a[o-2],a[o]),o+=2}var d=e.t-1,p,h=!0,f=Re(),v;n=Ws(e.data[d])-1;while(d>=0){if(n>=l)p=e.data[d]>>n-l&c;else if(p=(e.data[d]&(1<<n+1)-1)<<l-n,d>0)p|=e.data[d-1]>>this.DB+n-l;o=r;while((p&1)==0)p>>=1,--o;if((n-=o)<0)n+=this.DB,--d;if(h)a[p].copyTo(i),h=!1;else{while(o>1)s.sqrTo(i,f),s.sqrTo(f,i),o-=2;if(o>0)s.sqrTo(i,f);else v=i,i=f,f=v;s.mulTo(f,a[p],i)}while(d>=0&&(e.data[d]&1<<n)==0)if(s.sqrTo(i,f),v=i,i=f,f=v,--n<0)n=this.DB-1,--d}return s.revert(i)}function Rm(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(),s=n.getLowestSetBit();if(s<0)return t;if(i<s)s=i;if(s>0)t.rShiftTo(s,t),n.rShiftTo(s,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(s>0)n.lShiftTo(s,n);return n}function Bm(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 Pm(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=Ur(1),s=Ur(0),a=Ur(0),o=Ur(1);while(n.signum()!=0){while(n.isEven()){if(n.rShiftTo(1,n),t){if(!i.isEven()||!s.isEven())i.addTo(this,i),s.subTo(e,s);i.rShiftTo(1,i)}else if(!s.isEven())s.subTo(e,s);s.rShiftTo(1,s)}while(r.isEven()){if(r.rShiftTo(1,r),t){if(!a.isEven()||!o.isEven())a.addTo(this,a),o.subTo(e,o);a.rShiftTo(1,a)}else if(!o.isEven())o.subTo(e,o);o.rShiftTo(1,o)}if(n.compareTo(r)>=0){if(n.subTo(r,n),t)i.subTo(a,i);s.subTo(o,s)}else{if(r.subTo(n,r),t)a.subTo(i,a);o.subTo(s,o)}}if(r.compareTo(L.ONE)!=0)return L.ZERO;if(o.compareTo(e)>=0)return o.subtract(e);if(o.signum()<0)o.addTo(e,o);else return o;if(o.signum()<0)return o.add(e);else return o}var jt=[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],Nm=67108864/jt[jt.length-1];function Dm(e){var t,n=this.abs();if(n.t==1&&n.data[0]<=jt[jt.length-1]){for(t=0;t<jt.length;++t)if(n.data[0]==jt[t])return!0;return!1}if(n.isEven())return!1;t=1;while(t<jt.length){var r=jt[t],i=t+1;while(i<jt.length&&r<Nm)r*=jt[i++];r=n.modInt(r);while(t<i)if(r%jt[t++]==0)return!1}return n.millerRabin(e)}function Lm(e){var t=this.subtract(L.ONE),n=t.getLowestSetBit();if(n<=0)return!1;var r=t.shiftRight(n),i=Om(),s;for(var a=0;a<e;++a){do s=new L(this.bitLength(),i);while(s.compareTo(L.ONE)<=0||s.compareTo(t)>=0);var o=s.modPow(r,this);if(o.compareTo(L.ONE)!=0&&o.compareTo(t)!=0){var l=1;while(l++<n&&o.compareTo(t)!=0)if(o=o.modPowInt(2,this),o.compareTo(L.ONE)==0)return!1;if(o.compareTo(t)!=0)return!1}}return!0}function Om(){return{nextBytes:function(e){for(var t=0;t<e.length;++t)e[t]=Math.floor(Math.random()*256)}}}L.prototype.chunkSize=Og;L.prototype.toRadix=Vg;L.prototype.fromRadix=Fg;L.prototype.fromNumber=Mg;L.prototype.bitwiseTo=qg;L.prototype.changeBit=sm;L.prototype.addTo=cm;L.prototype.dMultiply=ym;L.prototype.dAddOffset=vm;L.prototype.multiplyLowerTo=Cm;L.prototype.multiplyUpperTo=wm;L.prototype.modInt=Bm;L.prototype.millerRabin=Lm;L.prototype.clone=Pg;L.prototype.intValue=Ng;L.prototype.byteValue=Dg;L.prototype.shortValue=Lg;L.prototype.signum=Ug;L.prototype.toByteArray=$g;L.prototype.equals=Wg;L.prototype.min=Hg;L.prototype.max=Kg;L.prototype.and=jg;L.prototype.or=zg;L.prototype.xor=Xg;L.prototype.andNot=Qg;L.prototype.not=Yg;L.prototype.shiftLeft=Jg;L.prototype.shiftRight=Zg;L.prototype.getLowestSetBit=tm;L.prototype.bitCount=nm;L.prototype.testBit=im;L.prototype.setBit=am;L.prototype.clearBit=om;L.prototype.flipBit=lm;L.prototype.add=um;L.prototype.subtract=dm;L.prototype.multiply=fm;L.prototype.divide=hm;L.prototype.remainder=gm;L.prototype.divideAndRemainder=mm;L.prototype.modPow=Im;L.prototype.modInverse=Pm;L.prototype.pow=bm;L.prototype.gcd=Rm;L.prototype.isProbablePrime=Dm;L.prototype.square=pm});var Rn=de(function(E1,$u){var or=ve();rr();Pe();var Fu=$u.exports=or.sha1=or.sha1||{};or.md.sha1=or.md.algorithms.sha1=Fu;Fu.create=function(){if(!Mu)Um();var e=null,t=or.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 s=0;s<i;++s)r.fullMessageLength.push(0);return t=or.util.createBuffer(),e={h0:1732584193,h1:4023233417,h2:2562383102,h3:271733878,h4:3285377520},r},r.start(),r.update=function(i,s){if(s==="utf8")i=or.util.encodeUtf8(i);var a=i.length;r.messageLength+=a,a=[a/4294967296>>>0,a>>>0];for(var o=r.fullMessageLength.length-1;o>=0;--o)r.fullMessageLength[o]+=a[1],a[1]=a[0]+(r.fullMessageLength[o]/4294967296>>>0),r.fullMessageLength[o]=r.fullMessageLength[o]>>>0,a[0]=a[1]/4294967296>>>0;if(t.putBytes(i),Vu(e,n,t),t.read>2048||t.length()===0)t.compact();return r},r.digest=function(){var i=or.util.createBuffer();i.putBytes(t.bytes());var s=r.fullMessageLength[r.fullMessageLength.length-1]+r.messageLengthSize,a=s&r.blockLength-1;i.putBytes(ko.substr(0,r.blockLength-a));var o,l,c=r.fullMessageLength[0]*8;for(var u=0;u<r.fullMessageLength.length-1;++u)o=r.fullMessageLength[u+1]*8,l=o/4294967296>>>0,c+=l,i.putInt32(c>>>0),c=o>>>0;i.putInt32(c);var d={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3,h4:e.h4};Vu(d,n,i);var p=or.util.createBuffer();return p.putInt32(d.h0),p.putInt32(d.h1),p.putInt32(d.h2),p.putInt32(d.h3),p.putInt32(d.h4),p},r};var ko=null,Mu=!1;function Um(){ko=String.fromCharCode(128),ko+=or.util.fillString(String.fromCharCode(0),64),Mu=!0}function Vu(e,t,n){var r,i,s,a,o,l,c,u,d=n.length();while(d>=64){i=e.h0,s=e.h1,a=e.h2,o=e.h3,l=e.h4;for(u=0;u<16;++u)r=n.getInt32(),t[u]=r,c=o^s&(a^o),r=(i<<5|i>>>27)+c+l+1518500249+r,l=o,o=a,a=(s<<30|s>>>2)>>>0,s=i,i=r;for(;u<20;++u)r=t[u-3]^t[u-8]^t[u-14]^t[u-16],r=r<<1|r>>>31,t[u]=r,c=o^s&(a^o),r=(i<<5|i>>>27)+c+l+1518500249+r,l=o,o=a,a=(s<<30|s>>>2)>>>0,s=i,i=r;for(;u<32;++u)r=t[u-3]^t[u-8]^t[u-14]^t[u-16],r=r<<1|r>>>31,t[u]=r,c=s^a^o,r=(i<<5|i>>>27)+c+l+1859775393+r,l=o,o=a,a=(s<<30|s>>>2)>>>0,s=i,i=r;for(;u<40;++u)r=t[u-6]^t[u-16]^t[u-28]^t[u-32],r=r<<2|r>>>30,t[u]=r,c=s^a^o,r=(i<<5|i>>>27)+c+l+1859775393+r,l=o,o=a,a=(s<<30|s>>>2)>>>0,s=i,i=r;for(;u<60;++u)r=t[u-6]^t[u-16]^t[u-28]^t[u-32],r=r<<2|r>>>30,t[u]=r,c=s&a|o&(s^a),r=(i<<5|i>>>27)+c+l+2400959708+r,l=o,o=a,a=(s<<30|s>>>2)>>>0,s=i,i=r;for(;u<80;++u)r=t[u-6]^t[u-16]^t[u-28]^t[u-32],r=r<<2|r>>>30,t[u]=r,c=s^a^o,r=(i<<5|i>>>27)+c+l+3395469782+r,l=o,o=a,a=(s<<30|s>>>2)>>>0,s=i,i=r;e.h0=e.h0+i|0,e.h1=e.h1+s|0,e.h2=e.h2+a|0,e.h3=e.h3+o|0,e.h4=e.h4+l|0,d-=64}}});var Io=de(function(T1,Hu){var lr=ve();Pe();Lt();Rn();var Wu=Hu.exports=lr.pkcs1=lr.pkcs1||{};Wu.encode_rsa_oaep=function(e,t,n){var r,i,s,a;if(typeof n==="string")r=n,i=arguments[3]||void 0,s=arguments[4]||void 0;else if(n){if(r=n.label||void 0,i=n.seed||void 0,s=n.md||void 0,n.mgf1&&n.mgf1.md)a=n.mgf1.md}if(!s)s=lr.md.sha1.create();else s.start();if(!a)a=s;var o=Math.ceil(e.n.bitLength()/8),l=o-2*s.digestLength-2;if(t.length>l){var c=Error("RSAES-OAEP input message length is too long.");throw c.length=t.length,c.maxLength=l,c}if(!r)r="";s.update(r,"raw");var u=s.digest(),d="",p=l-t.length;for(var h=0;h<p;h++)d+="\x00";var f=u.getBytes()+d+"\x01"+t;if(!i)i=lr.random.getBytes(s.digestLength);else if(i.length!==s.digestLength){var c=Error("Invalid RSAES-OAEP seed. The seed length must match the digest length.");throw c.seedLength=i.length,c.digestLength=s.digestLength,c}var v=Hs(i,o-s.digestLength-1,a),x=lr.util.xorBytes(f,v,f.length),S=Hs(x,s.digestLength,a),A=lr.util.xorBytes(i,S,i.length);return"\x00"+A+x};Wu.decode_rsa_oaep=function(e,t,n){var r,i,s;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)s=n.mgf1.md}var a=Math.ceil(e.n.bitLength()/8);if(t.length!==a){var x=Error("RSAES-OAEP encoded message length is invalid.");throw x.length=t.length,x.expectedLength=a,x}if(i===void 0)i=lr.md.sha1.create();else i.start();if(!s)s=i;if(a<2*i.digestLength+2)throw Error("RSAES-OAEP key is too short for the hash function.");if(!r)r="";i.update(r,"raw");var o=i.digest().getBytes(),l=t.charAt(0),c=t.substring(1,i.digestLength+1),u=t.substring(1+i.digestLength),d=Hs(u,i.digestLength,s),p=lr.util.xorBytes(c,d,c.length),h=Hs(p,a-i.digestLength-1,s),f=lr.util.xorBytes(u,h,u.length),v=f.substring(0,i.digestLength),x=l!=="\x00";for(var S=0;S<i.digestLength;++S)x|=o.charAt(S)!==v.charAt(S);var A=1,b=i.digestLength;for(var k=i.digestLength;k<f.length;k++){var R=f.charCodeAt(k),I=R&1^1,V=A?65534:0;x|=R&V,A=A&I,b+=A}if(x||f.charCodeAt(b)!==1)throw Error("Invalid RSAES-OAEP padding.");return f.substring(b+1)};function Hs(e,t,n){if(!n)n=lr.md.sha1.create();var r="",i=Math.ceil(t/n.digestLength);for(var s=0;s<i;++s){var a=String.fromCharCode(s>>24&255,s>>16&255,s>>8&255,s&255);n.start(),n.update(e+a),r+=n.digest().getBytes()}return r.substring(0,t)}});var Bo=de(function(A1,Ro){var Vr=ve();Pe();Ci();Lt();(function(){if(Vr.prime){Ro.exports=Vr.prime;return}var e=Ro.exports=Vr.prime=Vr.prime||{},t=Vr.jsbn.BigInteger,n=[6,4,2,4,2,4,6,2],r=new t(null);r.fromInt(30);var i=function(d,p){return d|p};e.generateProbablePrime=function(d,p,h){if(typeof p==="function")h=p,p={};p=p||{};var f=p.algorithm||"PRIMEINC";if(typeof f==="string")f={name:f};f.options=f.options||{};var v=p.prng||Vr.random,x={nextBytes:function(S){var A=v.getBytesSync(S.length);for(var b=0;b<S.length;++b)S[b]=A.charCodeAt(b)}};if(f.name==="PRIMEINC")return s(d,x,f.options,h);throw Error("Invalid prime generation algorithm: "+f.name)};function s(d,p,h,f){if("workers"in h)return l(d,p,h,f);return a(d,p,h,f)}function a(d,p,h,f){var v=c(d,p),x=0,S=u(v.bitLength());if("millerRabinTests"in h)S=h.millerRabinTests;var A=10;if("maxBlockTime"in h)A=h.maxBlockTime;o(v,d,p,x,S,A,f)}function o(d,p,h,f,v,x,S){var A=+new Date;do{if(d.bitLength()>p)d=c(p,h);if(d.isProbablePrime(v))return S(null,d);d.dAddOffset(n[f++%8],0)}while(x<0||+new Date-A<x);Vr.util.setImmediate(function(){o(d,p,h,f,v,x,S)})}function l(d,p,h,f){if(typeof Worker>"u")return a(d,p,h,f);var v=c(d,p),x=h.workers,S=h.workLoad||100,A=S*30/8,b=h.workerScript||"forge/prime.worker.js";if(x===-1)return Vr.util.estimateCores(function(R,I){if(R)I=2;x=I-1,k()});k();function k(){x=Math.max(1,x);var R=[];for(var I=0;I<x;++I)R[I]=new Worker(b);var V=x;for(var I=0;I<x;++I)R[I].addEventListener("message",D);var J=!1;function D(W){if(J)return;--V;var Z=W.data;if(Z.found){for(var pe=0;pe<R.length;++pe)R[pe].terminate();return J=!0,f(null,new t(Z.prime,16))}if(v.bitLength()>d)v=c(d,p);var ge=v.toString(16);W.target.postMessage({hex:ge,workLoad:S}),v.dAddOffset(A,0)}}}function c(d,p){var h=new t(d,p),f=d-1;if(!h.testBit(f))h.bitwiseTo(t.ONE.shiftLeft(f),i,h);return h.dAddOffset(31-h.mod(r).byteValue(),0),h}function u(d){if(d<=100)return 27;if(d<=150)return 18;if(d<=200)return 15;if(d<=250)return 12;if(d<=300)return 9;if(d<=350)return 8;if(d<=400)return 7;if(d<=500)return 6;if(d<=600)return 5;if(d<=800)return 4;if(d<=1250)return 3;return 2}})()});var wi=de(function(_1,Yu){var ne=ve();Gt();Ci();Or();Io();Bo();Lt();Pe();if(typeof ke>"u")ke=ne.jsbn.BigInteger;var ke,Po=ne.util.isNodejs?ui("crypto"):null,{asn1:_,util:Ut}=ne;ne.pki=ne.pki||{};Yu.exports=ne.pki.rsa=ne.rsa=ne.rsa||{};var fe=ne.pki,Vm=[6,4,2,4,2,4,6,2],Fm={name:"PrivateKeyInfo",tagClass:_.Class.UNIVERSAL,type:_.Type.SEQUENCE,constructed:!0,value:[{name:"PrivateKeyInfo.version",tagClass:_.Class.UNIVERSAL,type:_.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:_.Class.UNIVERSAL,type:_.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:_.Class.UNIVERSAL,type:_.Type.OID,constructed:!1,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:_.Class.UNIVERSAL,type:_.Type.OCTETSTRING,constructed:!1,capture:"privateKey"}]},Mm={name:"RSAPrivateKey",tagClass:_.Class.UNIVERSAL,type:_.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPrivateKey.version",tagClass:_.Class.UNIVERSAL,type:_.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"RSAPrivateKey.modulus",tagClass:_.Class.UNIVERSAL,type:_.Type.INTEGER,constructed:!1,capture:"privateKeyModulus"},{name:"RSAPrivateKey.publicExponent",tagClass:_.Class.UNIVERSAL,type:_.Type.INTEGER,constructed:!1,capture:"privateKeyPublicExponent"},{name:"RSAPrivateKey.privateExponent",tagClass:_.Class.UNIVERSAL,type:_.Type.INTEGER,constructed:!1,capture:"privateKeyPrivateExponent"},{name:"RSAPrivateKey.prime1",tagClass:_.Class.UNIVERSAL,type:_.Type.INTEGER,constructed:!1,capture:"privateKeyPrime1"},{name:"RSAPrivateKey.prime2",tagClass:_.Class.UNIVERSAL,type:_.Type.INTEGER,constructed:!1,capture:"privateKeyPrime2"},{name:"RSAPrivateKey.exponent1",tagClass:_.Class.UNIVERSAL,type:_.Type.INTEGER,constructed:!1,capture:"privateKeyExponent1"},{name:"RSAPrivateKey.exponent2",tagClass:_.Class.UNIVERSAL,type:_.Type.INTEGER,constructed:!1,capture:"privateKeyExponent2"},{name:"RSAPrivateKey.coefficient",tagClass:_.Class.UNIVERSAL,type:_.Type.INTEGER,constructed:!1,capture:"privateKeyCoefficient"}]},$m={name:"RSAPublicKey",tagClass:_.Class.UNIVERSAL,type:_.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPublicKey.modulus",tagClass:_.Class.UNIVERSAL,type:_.Type.INTEGER,constructed:!1,capture:"publicKeyModulus"},{name:"RSAPublicKey.exponent",tagClass:_.Class.UNIVERSAL,type:_.Type.INTEGER,constructed:!1,capture:"publicKeyExponent"}]},Wm=ne.pki.rsa.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:_.Class.UNIVERSAL,type:_.Type.SEQUENCE,constructed:!0,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:_.Class.UNIVERSAL,type:_.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:_.Class.UNIVERSAL,type:_.Type.OID,constructed:!1,capture:"publicKeyOid"}]},{name:"SubjectPublicKeyInfo.subjectPublicKey",tagClass:_.Class.UNIVERSAL,type:_.Type.BITSTRING,constructed:!1,value:[{name:"SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey",tagClass:_.Class.UNIVERSAL,type:_.Type.SEQUENCE,constructed:!0,optional:!0,captureAsn1:"rsaPublicKey"}]}]},Hm={name:"DigestInfo",tagClass:_.Class.UNIVERSAL,type:_.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm",tagClass:_.Class.UNIVERSAL,type:_.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm.algorithmIdentifier",tagClass:_.Class.UNIVERSAL,type:_.Type.OID,constructed:!1,capture:"algorithmIdentifier"},{name:"DigestInfo.DigestAlgorithm.parameters",tagClass:_.Class.UNIVERSAL,type:_.Type.NULL,capture:"parameters",optional:!0,constructed:!1}]},{name:"DigestInfo.digest",tagClass:_.Class.UNIVERSAL,type:_.Type.OCTETSTRING,constructed:!1,capture:"digest"}]},Ku=function(e,t,n){var r=[_.create(_.Class.UNIVERSAL,_.Type.OID,!1,_.oidToDer(e).getBytes())];if(n)r.push(_.create(_.Class.UNIVERSAL,_.Type.NULL,!1,""));return _.toDer(_.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[_.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,r),_.create(_.Class.UNIVERSAL,_.Type.OCTETSTRING,!1,t)])).getBytes()},Km=function(e){var t;if(e.algorithm in fe.oids)t=fe.oids[e.algorithm];else{var n=Error("Unknown message digest algorithm.");throw n.algorithm=e.algorithm,n}var r=_.oidToDer(t).getBytes(),i=_.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[]),s=_.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[]);s.value.push(_.create(_.Class.UNIVERSAL,_.Type.OID,!1,r)),s.value.push(_.create(_.Class.UNIVERSAL,_.Type.NULL,!1,""));var a=_.create(_.Class.UNIVERSAL,_.Type.OCTETSTRING,!1,e.digest().getBytes());return i.value.push(s),i.value.push(a),_.toDer(i).getBytes()},Xu=function(e,t,n){if(n)return e.modPow(t.e,t.n);if(!t.p||!t.q)return e.modPow(t.d,t.n);if(!t.dP)t.dP=t.d.mod(t.p.subtract(ke.ONE));if(!t.dQ)t.dQ=t.d.mod(t.q.subtract(ke.ONE));if(!t.qInv)t.qInv=t.q.modInverse(t.p);var r;do r=new ke(ne.util.bytesToHex(ne.random.getBytes(t.n.bitLength()/8)),16);while(r.compareTo(t.n)>=0||!r.gcd(t.n).equals(ke.ONE));e=e.multiply(r.modPow(t.e,t.n)).mod(t.n);var i=e.mod(t.p).modPow(t.dP,t.p),s=e.mod(t.q).modPow(t.dQ,t.q);while(i.compareTo(s)<0)i=i.add(t.p);var a=i.subtract(s).multiply(t.qInv).mod(t.p).multiply(t.q).add(s);return a=a.multiply(r.modInverse(t.n)).mod(t.n),a};fe.rsa.encrypt=function(e,t,n){var r=n,i,s=Math.ceil(t.n.bitLength()/8);if(n!==!1&&n!==!0)r=n===2,i=Qu(e,t,n);else i=ne.util.createBuffer(),i.putBytes(e);var a=new ke(i.toHex(),16),o=Xu(a,t,r),l=o.toString(16),c=ne.util.createBuffer(),u=s-Math.ceil(l.length/2);while(u>0)c.putByte(0),--u;return c.putBytes(ne.util.hexToBytes(l)),c.getBytes()};fe.rsa.decrypt=function(e,t,n,r){var i=Math.ceil(t.n.bitLength()/8);if(e.length!==i){var s=Error("Encrypted message length is invalid.");throw s.length=e.length,s.expected=i,s}var a=new ke(ne.util.createBuffer(e).toHex(),16);if(a.compareTo(t.n)>=0)throw Error("Encrypted message is invalid.");var o=Xu(a,t,n),l=o.toString(16),c=ne.util.createBuffer(),u=i-Math.ceil(l.length/2);while(u>0)c.putByte(0),--u;if(c.putBytes(ne.util.hexToBytes(l)),r!==!1)return Ks(c.getBytes(),t,n);return c.getBytes()};fe.rsa.createKeyPairGenerationState=function(e,t,n){if(typeof e==="string")e=parseInt(e,10);e=e||2048,n=n||{};var r=n.prng||ne.random,i={nextBytes:function(o){var l=r.getBytesSync(o.length);for(var c=0;c<o.length;++c)o[c]=l.charCodeAt(c)}},s=n.algorithm||"PRIMEINC",a;if(s==="PRIMEINC")a={algorithm:s,state:0,bits:e,rng:i,eInt:t||65537,e:new ke(null),p:null,q:null,qBits:e>>1,pBits:e-(e>>1),pqState:0,num:null,keys:null},a.e.fromInt(a.eInt);else throw Error("Invalid key generation algorithm: "+s);return a};fe.rsa.stepKeyPairGenerationState=function(e,t){if(!("algorithm"in e))e.algorithm="PRIMEINC";var n=new ke(null);n.fromInt(30);var r=0,i=function(d,p){return d|p},s=+new Date,a,o=0;while(e.keys===null&&(t<=0||o<t)){if(e.state===0){var l=e.p===null?e.pBits:e.qBits,c=l-1;if(e.pqState===0){if(e.num=new ke(l,e.rng),!e.num.testBit(c))e.num.bitwiseTo(ke.ONE.shiftLeft(c),i,e.num);e.num.dAddOffset(31-e.num.mod(n).byteValue(),0),r=0,++e.pqState}else if(e.pqState===1)if(e.num.bitLength()>l)e.pqState=0;else if(e.num.isProbablePrime(Gm(e.num.bitLength())))++e.pqState;else e.num.dAddOffset(Vm[r++%8],0);else if(e.pqState===2)e.pqState=e.num.subtract(ke.ONE).gcd(e.e).compareTo(ke.ONE)===0?3:0;else if(e.pqState===3){if(e.pqState=0,e.p===null)e.p=e.num;else e.q=e.num;if(e.p!==null&&e.q!==null)++e.state;e.num=null}}else if(e.state===1){if(e.p.compareTo(e.q)<0)e.num=e.p,e.p=e.q,e.q=e.num;++e.state}else if(e.state===2)e.p1=e.p.subtract(ke.ONE),e.q1=e.q.subtract(ke.ONE),e.phi=e.p1.multiply(e.q1),++e.state;else if(e.state===3)if(e.phi.gcd(e.e).compareTo(ke.ONE)===0)++e.state;else e.p=null,e.q=null,e.state=0;else if(e.state===4)if(e.n=e.p.multiply(e.q),e.n.bitLength()===e.bits)++e.state;else e.q=null,e.state=0;else if(e.state===5){var u=e.e.modInverse(e.phi);e.keys={privateKey:fe.rsa.setPrivateKey(e.n,e.e,u,e.p,e.q,u.mod(e.p1),u.mod(e.q1),e.q.modInverse(e.p)),publicKey:fe.rsa.setPublicKey(e.n,e.e)}}a=+new Date,o+=a-s,s=a}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(qu("generateKeyPair"))return Po.generateKeyPair("rsa",{modulusLength:e,publicExponent:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}},function(o,l,c){if(o)return r(o);r(null,{privateKey:fe.privateKeyFromPem(c),publicKey:fe.publicKeyFromPem(l)})});if(Gu("generateKey")&&Gu("exportKey"))return Ut.globalScope.crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:zu(t),hash:{name:"SHA-256"}},!0,["sign","verify"]).then(function(o){return Ut.globalScope.crypto.subtle.exportKey("pkcs8",o.privateKey)}).then(void 0,function(o){r(o)}).then(function(o){if(o){var l=fe.privateKeyFromAsn1(_.fromDer(ne.util.createBuffer(o)));r(null,{privateKey:l,publicKey:fe.setRsaPublicKey(l.n,l.e)})}});if(ju("generateKey")&&ju("exportKey")){var i=Ut.globalScope.msCrypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:zu(t),hash:{name:"SHA-256"}},!0,["sign","verify"]);i.oncomplete=function(o){var l=o.target.result,c=Ut.globalScope.msCrypto.subtle.exportKey("pkcs8",l.privateKey);c.oncomplete=function(u){var d=u.target.result,p=fe.privateKeyFromAsn1(_.fromDer(ne.util.createBuffer(d)));r(null,{privateKey:p,publicKey:fe.setRsaPublicKey(p.n,p.e)})},c.onerror=function(u){r(u)}},i.onerror=function(o){r(o)};return}}else if(qu("generateKeyPairSync")){var s=Po.generateKeyPairSync("rsa",{modulusLength:e,publicExponent:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{privateKey:fe.privateKeyFromPem(s.privateKey),publicKey:fe.publicKeyFromPem(s.publicKey)}}}var a=fe.rsa.createKeyPairGenerationState(e,t,n);if(!r)return fe.rsa.stepKeyPairGenerationState(a,0),a.keys;qm(a,n,r)};fe.setRsaPublicKey=fe.rsa.setPublicKey=function(e,t){var n={n:e,e:t};return n.encrypt=function(r,i,s){if(typeof i==="string")i=i.toUpperCase();else if(i===void 0)i="RSAES-PKCS1-V1_5";if(i==="RSAES-PKCS1-V1_5")i={encode:function(o,l,c){return Qu(o,l,2).getBytes()}};else if(i==="RSA-OAEP"||i==="RSAES-OAEP")i={encode:function(o,l){return ne.pkcs1.encode_rsa_oaep(l,o,s)}};else if(["RAW","NONE","NULL",null].indexOf(i)!==-1)i={encode:function(o){return o}};else if(typeof i==="string")throw Error('Unsupported encryption scheme: "'+i+'".');var a=i.encode(r,n,!0);return fe.rsa.encrypt(a,n,!0)},n.verify=function(r,i,s,a){if(typeof s==="string")s=s.toUpperCase();else if(s===void 0)s="RSASSA-PKCS1-V1_5";if(a===void 0)a={_parseAllDigestBytes:!0,_skipPaddingChecks:!1};if(!("_parseAllDigestBytes"in a))a._parseAllDigestBytes=!0;if(!("_skipPaddingChecks"in a))a._skipPaddingChecks=!1;if(s==="RSASSA-PKCS1-V1_5")s={verify:function(l,c){c=Ks(c,n,!0,void 0,a);var u=_.fromDer(c,{parseAllBytes:a._parseAllDigestBytes}),d={},p=[];if(!_.validate(u,Hm,d,p)||u.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 f=_.derToOid(d.algorithmIdentifier);if(!(f===ne.oids.md2||f===ne.oids.md5||f===ne.oids.sha1||f===ne.oids.sha224||f===ne.oids.sha256||f===ne.oids.sha384||f===ne.oids.sha512||f===ne.oids["sha512-224"]||f===ne.oids["sha512-256"])){var h=Error("Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.");throw h.oid=f,h}if(f===ne.oids.md2||f===ne.oids.md5){if(!("parameters"in d))throw Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value. Missing algorithm identifier NULL parameters.")}var v=Ku(f,d.digest,!0),x=Ku(f,d.digest,!1);if(c.substring(0,v.length)!==v&&c.substring(0,x.length)!==x)throw Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value.");return l===d.digest}};else if(s==="NONE"||s==="NULL"||s===null)s={verify:function(l,c){return c=Ks(c,n,!0,void 0,a),l===c}};var o=fe.rsa.decrypt(i,n,!0,!1);return s.verify(r,o,n.n.bitLength())},n};fe.setRsaPrivateKey=fe.rsa.setPrivateKey=function(e,t,n,r,i,s,a,o){var l={n:e,e:t,d:n,p:r,q:i,dP:s,dQ:a,qInv:o};return l.decrypt=function(c,u,d){if(typeof u==="string")u=u.toUpperCase();else if(u===void 0)u="RSAES-PKCS1-V1_5";var p=fe.rsa.decrypt(c,l,!1,!1);if(u==="RSAES-PKCS1-V1_5")u={decode:Ks};else if(u==="RSA-OAEP"||u==="RSAES-OAEP")u={decode:function(h,f){return ne.pkcs1.decode_rsa_oaep(f,h,d)}};else if(["RAW","NONE","NULL",null].indexOf(u)!==-1)u={decode:function(h){return h}};else throw Error('Unsupported encryption scheme: "'+u+'".');return u.decode(p,l,!1)},l.sign=function(c,u){var d=!1;if(typeof u==="string")u=u.toUpperCase();if(u===void 0||u==="RSASSA-PKCS1-V1_5")u={encode:Km},d=1;else if(u==="NONE"||u==="NULL"||u===null)u={encode:function(){return c}},d=1;var p=u.encode(c,l.n.bitLength());return fe.rsa.encrypt(p,l,d)},l};fe.wrapRsaPrivateKey=function(e){return _.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[_.create(_.Class.UNIVERSAL,_.Type.INTEGER,!1,_.integerToDer(0).getBytes()),_.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[_.create(_.Class.UNIVERSAL,_.Type.OID,!1,_.oidToDer(fe.oids.rsaEncryption).getBytes()),_.create(_.Class.UNIVERSAL,_.Type.NULL,!1,"")]),_.create(_.Class.UNIVERSAL,_.Type.OCTETSTRING,!1,_.toDer(e).getBytes())])};fe.privateKeyFromAsn1=function(e){var t={},n=[];if(_.validate(e,Fm,t,n))e=_.fromDer(ne.util.createBuffer(t.privateKey));if(t={},n=[],!_.validate(e,Mm,t,n)){var r=Error("Cannot read private key. ASN.1 object does not contain an RSAPrivateKey.");throw r.errors=n,r}var i,s,a,o,l,c,u,d;return i=ne.util.createBuffer(t.privateKeyModulus).toHex(),s=ne.util.createBuffer(t.privateKeyPublicExponent).toHex(),a=ne.util.createBuffer(t.privateKeyPrivateExponent).toHex(),o=ne.util.createBuffer(t.privateKeyPrime1).toHex(),l=ne.util.createBuffer(t.privateKeyPrime2).toHex(),c=ne.util.createBuffer(t.privateKeyExponent1).toHex(),u=ne.util.createBuffer(t.privateKeyExponent2).toHex(),d=ne.util.createBuffer(t.privateKeyCoefficient).toHex(),fe.setRsaPrivateKey(new ke(i,16),new ke(s,16),new ke(a,16),new ke(o,16),new ke(l,16),new ke(c,16),new ke(u,16),new ke(d,16))};fe.privateKeyToAsn1=fe.privateKeyToRSAPrivateKey=function(e){return _.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[_.create(_.Class.UNIVERSAL,_.Type.INTEGER,!1,_.integerToDer(0).getBytes()),_.create(_.Class.UNIVERSAL,_.Type.INTEGER,!1,cr(e.n)),_.create(_.Class.UNIVERSAL,_.Type.INTEGER,!1,cr(e.e)),_.create(_.Class.UNIVERSAL,_.Type.INTEGER,!1,cr(e.d)),_.create(_.Class.UNIVERSAL,_.Type.INTEGER,!1,cr(e.p)),_.create(_.Class.UNIVERSAL,_.Type.INTEGER,!1,cr(e.q)),_.create(_.Class.UNIVERSAL,_.Type.INTEGER,!1,cr(e.dP)),_.create(_.Class.UNIVERSAL,_.Type.INTEGER,!1,cr(e.dQ)),_.create(_.Class.UNIVERSAL,_.Type.INTEGER,!1,cr(e.qInv))])};fe.publicKeyFromAsn1=function(e){var t={},n=[];if(_.validate(e,Wm,t,n)){var r=_.derToOid(t.publicKeyOid);if(r!==fe.oids.rsaEncryption){var i=Error("Cannot read public key. Unknown OID.");throw i.oid=r,i}e=t.rsaPublicKey}if(n=[],!_.validate(e,$m,t,n)){var i=Error("Cannot read public key. ASN.1 object does not contain an RSAPublicKey.");throw i.errors=n,i}var s=ne.util.createBuffer(t.publicKeyModulus).toHex(),a=ne.util.createBuffer(t.publicKeyExponent).toHex();return fe.setRsaPublicKey(new ke(s,16),new ke(a,16))};fe.publicKeyToAsn1=fe.publicKeyToSubjectPublicKeyInfo=function(e){return _.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[_.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[_.create(_.Class.UNIVERSAL,_.Type.OID,!1,_.oidToDer(fe.oids.rsaEncryption).getBytes()),_.create(_.Class.UNIVERSAL,_.Type.NULL,!1,"")]),_.create(_.Class.UNIVERSAL,_.Type.BITSTRING,!1,[fe.publicKeyToRSAPublicKey(e)])])};fe.publicKeyToRSAPublicKey=function(e){return _.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[_.create(_.Class.UNIVERSAL,_.Type.INTEGER,!1,cr(e.n)),_.create(_.Class.UNIVERSAL,_.Type.INTEGER,!1,cr(e.e))])};function Qu(e,t,n){var r=ne.util.createBuffer(),i=Math.ceil(t.n.bitLength()/8);if(e.length>i-11){var s=Error("Message is too long for PKCS#1 v1.5 padding.");throw s.length=e.length,s.max=i-11,s}r.putByte(0),r.putByte(n);var a=i-3-e.length,o;if(n===0||n===1){o=n===0?0:255;for(var l=0;l<a;++l)r.putByte(o)}else while(a>0){var c=0,u=ne.random.getBytes(a);for(var l=0;l<a;++l)if(o=u.charCodeAt(l),o===0)++c;else r.putByte(o);a=c}return r.putByte(0),r.putBytes(e),r}function Ks(e,t,n,r,i){var s=Math.ceil(t.n.bitLength()/8),a=ne.util.createBuffer(e),o=a.getByte(),l=a.getByte();if(o!==0||n&&l!==0&&l!==1||!n&&l!==2||n&&l===0&&typeof r>"u")throw Error("Encryption block is invalid.");var c=0;if(l===0){c=s-3-r;for(var u=0;u<c;++u)if(a.getByte()!==0)throw Error("Encryption block is invalid.")}else if(l===1){c=0;while(a.length()>1){if(a.getByte()!==255){--a.read;break}++c}if(c<8&&!(i?i._skipPaddingChecks:!1))throw Error("Encryption block is invalid.")}else if(l===2){c=0;while(a.length()>1){if(a.getByte()===0){--a.read;break}++c}if(c<8&&!(i?i._skipPaddingChecks:!1))throw Error("Encryption block is invalid.")}var d=a.getByte();if(d!==0||c!==s-3-a.length())throw Error("Encryption block is invalid.");return a.getBytes()}function qm(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(){s(e.pBits,function(o,l){if(o)return n(o);if(e.p=l,e.q!==null)return a(o,e.q);s(e.qBits,a)})}function s(o,l){ne.prime.generateProbablePrime(o,r,l)}function a(o,l){if(o)return n(o);if(e.q=l,e.p.compareTo(e.q)<0){var c=e.p;e.p=e.q,e.q=c}if(e.p.subtract(ke.ONE).gcd(e.e).compareTo(ke.ONE)!==0){e.p=null,i();return}if(e.q.subtract(ke.ONE).gcd(e.e).compareTo(ke.ONE)!==0){e.q=null,s(e.qBits,a);return}if(e.p1=e.p.subtract(ke.ONE),e.q1=e.q.subtract(ke.ONE),e.phi=e.p1.multiply(e.q1),e.phi.gcd(e.e).compareTo(ke.ONE)!==0){e.p=e.q=null,i();return}if(e.n=e.p.multiply(e.q),e.n.bitLength()!==e.bits){e.q=null,s(e.qBits,a);return}var u=e.e.modInverse(e.phi);e.keys={privateKey:fe.rsa.setPrivateKey(e.n,e.e,u,e.p,e.q,u.mod(e.p1),u.mod(e.q1),e.q.modInverse(e.p)),publicKey:fe.rsa.setPublicKey(e.n,e.e)},n(null,e.keys)}}function cr(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 Gm(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 qu(e){return ne.util.isNodejs&&typeof Po[e]==="function"}function Gu(e){return typeof Ut.globalScope<"u"&&typeof Ut.globalScope.crypto==="object"&&typeof Ut.globalScope.crypto.subtle==="object"&&typeof Ut.globalScope.crypto.subtle[e]==="function"}function ju(e){return typeof Ut.globalScope<"u"&&typeof Ut.globalScope.msCrypto==="object"&&typeof Ut.globalScope.msCrypto.subtle==="object"&&typeof Ut.globalScope.msCrypto.subtle[e]==="function"}function zu(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 Do=de(function(k1,td){var z=ve();Lr();Gt();Si();rr();Or();Fs();sn();Lt();Eo();wi();Pe();if(typeof No>"u")No=z.jsbn.BigInteger;var No,B=z.asn1,ye=z.pki=z.pki||{};td.exports=ye.pbe=z.pbe=z.pbe||{};var ln=ye.oids,jm={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"}]},zm={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"}]}]},Xm={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"}]};ye.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=z.random.getBytesSync(n.saltSize),i=n.count,s=B.integerToDer(i),a,o,l;if(n.algorithm.indexOf("aes")===0||n.algorithm==="des"){var c,u,d;switch(n.algorithm){case"aes128":a=16,c=16,u=ln["aes128-CBC"],d=z.aes.createEncryptionCipher;break;case"aes192":a=24,c=16,u=ln["aes192-CBC"],d=z.aes.createEncryptionCipher;break;case"aes256":a=32,c=16,u=ln["aes256-CBC"],d=z.aes.createEncryptionCipher;break;case"des":a=8,c=8,u=ln.desCBC,d=z.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(),f=ed(h),v=z.pkcs5.pbkdf2(t,r,i,a,f),x=z.random.getBytesSync(c),S=d(v);S.start(x),S.update(B.toDer(e)),S.finish(),l=S.output.getBytes();var A=Qm(r,s,a,h);o=B.create(B.Class.UNIVERSAL,B.Type.SEQUENCE,!0,[B.create(B.Class.UNIVERSAL,B.Type.OID,!1,B.oidToDer(ln.pkcs5PBES2).getBytes()),B.create(B.Class.UNIVERSAL,B.Type.SEQUENCE,!0,[B.create(B.Class.UNIVERSAL,B.Type.SEQUENCE,!0,[B.create(B.Class.UNIVERSAL,B.Type.OID,!1,B.oidToDer(ln.pkcs5PBKDF2).getBytes()),A]),B.create(B.Class.UNIVERSAL,B.Type.SEQUENCE,!0,[B.create(B.Class.UNIVERSAL,B.Type.OID,!1,B.oidToDer(u).getBytes()),B.create(B.Class.UNIVERSAL,B.Type.OCTETSTRING,!1,x)])])])}else if(n.algorithm==="3des"){a=24;var b=new z.util.ByteBuffer(r),v=ye.pbe.generatePkcs12Key(t,b,1,i,a),x=ye.pbe.generatePkcs12Key(t,b,2,i,a),S=z.des.createEncryptionCipher(v);S.start(x),S.update(B.toDer(e)),S.finish(),l=S.output.getBytes(),o=B.create(B.Class.UNIVERSAL,B.Type.SEQUENCE,!0,[B.create(B.Class.UNIVERSAL,B.Type.OID,!1,B.oidToDer(ln["pbeWithSHAAnd3-KeyTripleDES-CBC"]).getBytes()),B.create(B.Class.UNIVERSAL,B.Type.SEQUENCE,!0,[B.create(B.Class.UNIVERSAL,B.Type.OCTETSTRING,!1,r),B.create(B.Class.UNIVERSAL,B.Type.INTEGER,!1,s.getBytes())])])}else{var p=Error("Cannot encrypt private key. Unknown encryption algorithm.");throw p.algorithm=n.algorithm,p}var k=B.create(B.Class.UNIVERSAL,B.Type.SEQUENCE,!0,[o,B.create(B.Class.UNIVERSAL,B.Type.OCTETSTRING,!1,l)]);return k};ye.decryptPrivateKeyInfo=function(e,t){var n=null,r={},i=[];if(!B.validate(e,jm,r,i)){var s=Error("Cannot read encrypted private key. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw s.errors=i,s}var a=B.derToOid(r.encryptionOid),o=ye.pbe.getCipher(a,r.encryptionParams,t),l=z.util.createBuffer(r.encryptedData);if(o.update(l),o.finish())n=B.fromDer(o.output);return n};ye.encryptedPrivateKeyToPem=function(e,t){var n={type:"ENCRYPTED PRIVATE KEY",body:B.toDer(e).getBytes()};return z.pem.encode(n,{maxline:t})};ye.encryptedPrivateKeyFromPem=function(e){var t=z.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)};ye.encryptRsaPrivateKey=function(e,t,n){if(n=n||{},!n.legacy){var r=ye.wrapRsaPrivateKey(ye.privateKeyToAsn1(e));return r=ye.encryptPrivateKeyInfo(r,t,n),ye.encryptedPrivateKeyToPem(r)}var i,s,a,o;switch(n.algorithm){case"aes128":i="AES-128-CBC",a=16,s=z.random.getBytesSync(16),o=z.aes.createEncryptionCipher;break;case"aes192":i="AES-192-CBC",a=24,s=z.random.getBytesSync(16),o=z.aes.createEncryptionCipher;break;case"aes256":i="AES-256-CBC",a=32,s=z.random.getBytesSync(16),o=z.aes.createEncryptionCipher;break;case"3des":i="DES-EDE3-CBC",a=24,s=z.random.getBytesSync(8),o=z.des.createEncryptionCipher;break;case"des":i="DES-CBC",a=8,s=z.random.getBytesSync(8),o=z.des.createEncryptionCipher;break;default:var l=Error('Could not encrypt RSA private key; unsupported encryption algorithm "'+n.algorithm+'".');throw l.algorithm=n.algorithm,l}var c=z.pbe.opensslDeriveBytes(t,s.substr(0,8),a),u=o(c);u.start(s),u.update(B.toDer(ye.privateKeyToAsn1(e))),u.finish();var d={type:"RSA PRIVATE KEY",procType:{version:"4",type:"ENCRYPTED"},dekInfo:{algorithm:i,parameters:z.util.bytesToHex(s).toUpperCase()},body:u.output.getBytes()};return z.pem.encode(d)};ye.decryptRsaPrivateKey=function(e,t){var n=null,r=z.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 s,a;switch(r.dekInfo.algorithm){case"DES-CBC":s=8,a=z.des.createDecryptionCipher;break;case"DES-EDE3-CBC":s=24,a=z.des.createDecryptionCipher;break;case"AES-128-CBC":s=16,a=z.aes.createDecryptionCipher;break;case"AES-192-CBC":s=24,a=z.aes.createDecryptionCipher;break;case"AES-256-CBC":s=32,a=z.aes.createDecryptionCipher;break;case"RC2-40-CBC":s=5,a=function(d){return z.rc2.createDecryptionCipher(d,40)};break;case"RC2-64-CBC":s=8,a=function(d){return z.rc2.createDecryptionCipher(d,64)};break;case"RC2-128-CBC":s=16,a=function(d){return z.rc2.createDecryptionCipher(d,128)};break;default:var i=Error('Could not decrypt private key; unsupported encryption algorithm "'+r.dekInfo.algorithm+'".');throw i.algorithm=r.dekInfo.algorithm,i}var o=z.util.hexToBytes(r.dekInfo.parameters),l=z.pbe.opensslDeriveBytes(t,o.substr(0,8),s),c=a(l);if(c.start(o),c.update(z.util.createBuffer(r.body)),c.finish())n=c.output.getBytes();else return n}else n=r.body;if(r.type==="ENCRYPTED PRIVATE KEY")n=ye.decryptPrivateKeyInfo(B.fromDer(n),t);else n=B.fromDer(n);if(n!==null)n=ye.privateKeyFromAsn1(n);return n};ye.pbe.generatePkcs12Key=function(e,t,n,r,i,s){var a,o;if(!(r>=1))throw Error("PKCS#12 key derivation iteration count must be >= 1.");if(typeof s>"u"||s===null){if(!("sha1"in z.md))throw Error('"sha1" hash algorithm unavailable.');s=z.md.sha1.create()}var l=s.digestLength,c=s.blockLength,u=new z.util.ByteBuffer,d=new z.util.ByteBuffer;if(e!==null&&e!==void 0){for(o=0;o<e.length;o++)d.putInt16(e.charCodeAt(o));d.putInt16(0)}var p=d.length(),h=t.length(),f=new z.util.ByteBuffer;f.fillWithByte(n,c);var v=c*Math.ceil(h/c),x=new z.util.ByteBuffer;for(o=0;o<v;o++)x.putByte(t.at(o%h));var S=c*Math.ceil(p/c),A=new z.util.ByteBuffer;for(o=0;o<S;o++)A.putByte(d.at(o%p));var b=x;b.putBuffer(A);var k=Math.ceil(i/l);for(var R=1;R<=k;R++){var I=new z.util.ByteBuffer;I.putBytes(f.bytes()),I.putBytes(b.bytes());for(var V=0;V<r;V++)s.start(),s.update(I.getBytes()),I=s.digest();var J=new z.util.ByteBuffer;for(o=0;o<c;o++)J.putByte(I.at(o%l));var D=Math.ceil(h/c)+Math.ceil(p/c),W=new z.util.ByteBuffer;for(a=0;a<D;a++){var Z=new z.util.ByteBuffer(b.getBytes(c)),pe=511;for(o=J.length()-1;o>=0;o--)pe=pe>>8,pe+=J.at(o)+Z.at(o),Z.setAt(o,pe&255);W.putBuffer(Z)}b=W,u.putBuffer(I)}return u.truncate(u.length()-i),u};ye.pbe.getCipher=function(e,t,n){switch(e){case ye.oids.pkcs5PBES2:return ye.pbe.getCipherForPBES2(e,t,n);case ye.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:case ye.oids["pbewithSHAAnd40BitRC2-CBC"]:return ye.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}};ye.pbe.getCipherForPBES2=function(e,t,n){var r={},i=[];if(!B.validate(t,zm,r,i)){var s=Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw s.errors=i,s}if(e=B.derToOid(r.kdfOid),e!==ye.oids.pkcs5PBKDF2){var s=Error("Cannot read encrypted private key. Unsupported key derivation function OID.");throw s.oid=e,s.supportedOids=["pkcs5PBKDF2"],s}if(e=B.derToOid(r.encOid),e!==ye.oids["aes128-CBC"]&&e!==ye.oids["aes192-CBC"]&&e!==ye.oids["aes256-CBC"]&&e!==ye.oids["des-EDE3-CBC"]&&e!==ye.oids.desCBC){var s=Error("Cannot read encrypted private key. Unsupported encryption scheme OID.");throw s.oid=e,s.supportedOids=["aes128-CBC","aes192-CBC","aes256-CBC","des-EDE3-CBC","desCBC"],s}var a=r.kdfSalt,o=z.util.createBuffer(r.kdfIterationCount);o=o.getInt(o.length()<<3);var l,c;switch(ye.oids[e]){case"aes128-CBC":l=16,c=z.aes.createDecryptionCipher;break;case"aes192-CBC":l=24,c=z.aes.createDecryptionCipher;break;case"aes256-CBC":l=32,c=z.aes.createDecryptionCipher;break;case"des-EDE3-CBC":l=24,c=z.des.createDecryptionCipher;break;case"desCBC":l=8,c=z.des.createDecryptionCipher;break}var u=Zu(r.prfOid),d=z.pkcs5.pbkdf2(n,a,o,l,u),p=r.encIv,h=c(d);return h.start(p),h};ye.pbe.getCipherForPKCS12PBE=function(e,t,n){var r={},i=[];if(!B.validate(t,Xm,r,i)){var s=Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw s.errors=i,s}var a=z.util.createBuffer(r.salt),o=z.util.createBuffer(r.iterations);o=o.getInt(o.length()<<3);var l,c,u;switch(e){case ye.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:l=24,c=8,u=z.des.startDecrypting;break;case ye.oids["pbewithSHAAnd40BitRC2-CBC"]:l=5,c=8,u=function(v,x){var S=z.rc2.createDecryptionCipher(v,40);return S.start(x,null),S};break;default:var s=Error("Cannot read PKCS #12 PBE data block. Unsupported OID.");throw s.oid=e,s}var d=Zu(r.prfOid),p=ye.pbe.generatePkcs12Key(n,a,1,o,l,d);d.start();var h=ye.pbe.generatePkcs12Key(n,a,2,o,c,d);return u(p,h)};ye.pbe.opensslDeriveBytes=function(e,t,n,r){if(typeof r>"u"||r===null){if(!("md5"in z.md))throw Error('"md5" hash algorithm unavailable.');r=z.md.md5.create()}if(t===null)t="";var i=[Ju(r,e+t)];for(var s=16,a=1;s<n;++a,s+=16)i.push(Ju(r,i[a-1]+e+t));return i.join("").substr(0,n)};function Ju(e,t){return e.start().update(t).digest().getBytes()}function Zu(e){var t;if(!e)t="hmacWithSHA1";else if(t=ye.oids[B.derToOid(e)],!t){var n=Error("Unsupported PRF OID.");throw n.oid=e,n.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"],n}return ed(t)}function ed(e){var t=z.md;switch(e){case"hmacWithSHA224":t=z.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 Qm(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,z.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(ye.oids[r]).getBytes()),B.create(B.Class.UNIVERSAL,B.Type.NULL,!1,"")]));return i}});var Lo=de(function(I1,id){var Bn=ve();Gt();Pe();var G=Bn.asn1,Pn=id.exports=Bn.pkcs7asn1=Bn.pkcs7asn1||{};Bn.pkcs7=Bn.pkcs7||{};Bn.pkcs7.asn1=Pn;var rd={name:"ContentInfo",tagClass:G.Class.UNIVERSAL,type:G.Type.SEQUENCE,constructed:!0,value:[{name:"ContentInfo.ContentType",tagClass:G.Class.UNIVERSAL,type:G.Type.OID,constructed:!1,capture:"contentType"},{name:"ContentInfo.content",tagClass:G.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,captureAsn1:"content"}]};Pn.contentInfoValidator=rd;var nd={name:"EncryptedContentInfo",tagClass:G.Class.UNIVERSAL,type:G.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedContentInfo.contentType",tagClass:G.Class.UNIVERSAL,type:G.Type.OID,constructed:!1,capture:"contentType"},{name:"EncryptedContentInfo.contentEncryptionAlgorithm",tagClass:G.Class.UNIVERSAL,type:G.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedContentInfo.contentEncryptionAlgorithm.algorithm",tagClass:G.Class.UNIVERSAL,type:G.Type.OID,constructed:!1,capture:"encAlgorithm"},{name:"EncryptedContentInfo.contentEncryptionAlgorithm.parameter",tagClass:G.Class.UNIVERSAL,captureAsn1:"encParameter"}]},{name:"EncryptedContentInfo.encryptedContent",tagClass:G.Class.CONTEXT_SPECIFIC,type:0,capture:"encryptedContent",captureAsn1:"encryptedContentAsn1"}]};Pn.envelopedDataValidator={name:"EnvelopedData",tagClass:G.Class.UNIVERSAL,type:G.Type.SEQUENCE,constructed:!0,value:[{name:"EnvelopedData.Version",tagClass:G.Class.UNIVERSAL,type:G.Type.INTEGER,constructed:!1,capture:"version"},{name:"EnvelopedData.RecipientInfos",tagClass:G.Class.UNIVERSAL,type:G.Type.SET,constructed:!0,captureAsn1:"recipientInfos"}].concat(nd)};Pn.encryptedDataValidator={name:"EncryptedData",tagClass:G.Class.UNIVERSAL,type:G.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedData.Version",tagClass:G.Class.UNIVERSAL,type:G.Type.INTEGER,constructed:!1,capture:"version"}].concat(nd)};var Ym={name:"SignerInfo",tagClass:G.Class.UNIVERSAL,type:G.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.version",tagClass:G.Class.UNIVERSAL,type:G.Type.INTEGER,constructed:!1},{name:"SignerInfo.issuerAndSerialNumber",tagClass:G.Class.UNIVERSAL,type:G.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.issuerAndSerialNumber.issuer",tagClass:G.Class.UNIVERSAL,type:G.Type.SEQUENCE,constructed:!0,captureAsn1:"issuer"},{name:"SignerInfo.issuerAndSerialNumber.serialNumber",tagClass:G.Class.UNIVERSAL,type:G.Type.INTEGER,constructed:!1,capture:"serial"}]},{name:"SignerInfo.digestAlgorithm",tagClass:G.Class.UNIVERSAL,type:G.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.digestAlgorithm.algorithm",tagClass:G.Class.UNIVERSAL,type:G.Type.OID,constructed:!1,capture:"digestAlgorithm"},{name:"SignerInfo.digestAlgorithm.parameter",tagClass:G.Class.UNIVERSAL,constructed:!1,captureAsn1:"digestParameter",optional:!0}]},{name:"SignerInfo.authenticatedAttributes",tagClass:G.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,capture:"authenticatedAttributes"},{name:"SignerInfo.digestEncryptionAlgorithm",tagClass:G.Class.UNIVERSAL,type:G.Type.SEQUENCE,constructed:!0,capture:"signatureAlgorithm"},{name:"SignerInfo.encryptedDigest",tagClass:G.Class.UNIVERSAL,type:G.Type.OCTETSTRING,constructed:!1,capture:"signature"},{name:"SignerInfo.unauthenticatedAttributes",tagClass:G.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,optional:!0,capture:"unauthenticatedAttributes"}]};Pn.signedDataValidator={name:"SignedData",tagClass:G.Class.UNIVERSAL,type:G.Type.SEQUENCE,constructed:!0,value:[{name:"SignedData.Version",tagClass:G.Class.UNIVERSAL,type:G.Type.INTEGER,constructed:!1,capture:"version"},{name:"SignedData.DigestAlgorithms",tagClass:G.Class.UNIVERSAL,type:G.Type.SET,constructed:!0,captureAsn1:"digestAlgorithms"},rd,{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:[Ym]}]};Pn.recipientInfoValidator={name:"RecipientInfo",tagClass:G.Class.UNIVERSAL,type:G.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.version",tagClass:G.Class.UNIVERSAL,type:G.Type.INTEGER,constructed:!1,capture:"version"},{name:"RecipientInfo.issuerAndSerial",tagClass:G.Class.UNIVERSAL,type:G.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.issuerAndSerial.issuer",tagClass:G.Class.UNIVERSAL,type:G.Type.SEQUENCE,constructed:!0,captureAsn1:"issuer"},{name:"RecipientInfo.issuerAndSerial.serialNumber",tagClass:G.Class.UNIVERSAL,type:G.Type.INTEGER,constructed:!1,capture:"serial"}]},{name:"RecipientInfo.keyEncryptionAlgorithm",tagClass:G.Class.UNIVERSAL,type:G.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.keyEncryptionAlgorithm.algorithm",tagClass:G.Class.UNIVERSAL,type:G.Type.OID,constructed:!1,capture:"encAlgorithm"},{name:"RecipientInfo.keyEncryptionAlgorithm.parameter",tagClass:G.Class.UNIVERSAL,constructed:!1,captureAsn1:"encParameter",optional:!0}]},{name:"RecipientInfo.encryptedKey",tagClass:G.Class.UNIVERSAL,type:G.Type.OCTETSTRING,constructed:!1,capture:"encKey"}]}});var Oo=de(function(R1,sd){var cn=ve();Pe();cn.mgf=cn.mgf||{};var Jm=sd.exports=cn.mgf.mgf1=cn.mgf1=cn.mgf1||{};Jm.create=function(e){var t={generate:function(n,r){var i=new cn.util.ByteBuffer,s=Math.ceil(r/e.digestLength);for(var a=0;a<s;a++){var o=new cn.util.ByteBuffer;o.putInt32(a),e.start(),e.update(n+o.getBytes()),i.putBuffer(e.digest())}return i.truncate(i.length()-r),i.getBytes()}};return t}});var od=de(function(B1,ad){var qs=ve();Oo();ad.exports=qs.mgf=qs.mgf||{};qs.mgf.mgf1=qs.mgf1});var Gs=de(function(P1,ld){var un=ve();Lt();Pe();var Zm=ld.exports=un.pss=un.pss||{};Zm.create=function(e){if(arguments.length===3)e={md:arguments[0],mgf:arguments[1],saltLength:arguments[2]};var t=e.md,n=e.mgf,r=t.digestLength,i=e.salt||null;if(typeof i==="string")i=un.util.createBuffer(i);var s;if("saltLength"in e)s=e.saltLength;else if(i!==null)s=i.length();else throw Error("Salt length not specified or specific salt not given.");if(i!==null&&i.length()!==s)throw Error("Given salt length does not match length of given salt.");var a=e.prng||un.random,o={};return o.encode=function(l,c){var u,d=c-1,p=Math.ceil(d/8),h=l.digest().getBytes();if(p<r+s+2)throw Error("Message is too long to encrypt.");var f;if(i===null)f=a.getBytesSync(s);else f=i.bytes();var v=new un.util.ByteBuffer;v.fillWithByte(0,8),v.putBytes(h),v.putBytes(f),t.start(),t.update(v.getBytes());var x=t.digest().getBytes(),S=new un.util.ByteBuffer;S.fillWithByte(0,p-s-r-2),S.putByte(1),S.putBytes(f);var A=S.getBytes(),b=p-r-1,k=n.generate(x,b),R="";for(u=0;u<b;u++)R+=String.fromCharCode(A.charCodeAt(u)^k.charCodeAt(u));var I=65280>>8*p-d&255;return R=String.fromCharCode(R.charCodeAt(0)&~I)+R.substr(1),R+x+String.fromCharCode(188)},o.verify=function(l,c,u){var d,p=u-1,h=Math.ceil(p/8);if(c=c.substr(-h),h<r+s+2)throw Error("Inconsistent parameters to PSS signature verification.");if(c.charCodeAt(h-1)!==188)throw Error("Encoded message does not end in 0xBC.");var f=h-r-1,v=c.substr(0,f),x=c.substr(f,r),S=65280>>8*h-p&255;if((v.charCodeAt(0)&S)!==0)throw Error("Bits beyond keysize not zero as expected.");var A=n.generate(x,f),b="";for(d=0;d<f;d++)b+=String.fromCharCode(v.charCodeAt(d)^A.charCodeAt(d));b=String.fromCharCode(b.charCodeAt(0)&~S)+b.substr(1);var k=h-r-s-2;for(d=0;d<k;d++)if(b.charCodeAt(d)!==0)throw Error("Leftmost octets not zero as expected");if(b.charCodeAt(k)!==1)throw Error("Inconsistent PSS signature, 0x01 marker not found");var R=b.substr(-s),I=new un.util.ByteBuffer;I.fillWithByte(0,8),I.putBytes(l),I.putBytes(R),t.start(),t.update(I.getBytes());var V=t.digest().getBytes();return x===V},o}});var Xs=de(function(N1,pd){var ie=ve();Lr();Gt();Si();rr();od();Or();sn();Gs();wi();Pe();var g=ie.asn1,M=pd.exports=ie.pki=ie.pki||{},Be=M.oids,Ye={};Ye.CN=Be.commonName;Ye.commonName="CN";Ye.C=Be.countryName;Ye.countryName="C";Ye.L=Be.localityName;Ye.localityName="L";Ye.ST=Be.stateOrProvinceName;Ye.stateOrProvinceName="ST";Ye.O=Be.organizationName;Ye.organizationName="O";Ye.OU=Be.organizationalUnitName;Ye.organizationalUnitName="OU";Ye.E=Be.emailAddress;Ye.emailAddress="E";var ud=ie.pki.rsa.publicKeyValidator,ey={name:"Certificate",tagClass:g.Class.UNIVERSAL,type:g.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate",tagClass:g.Class.UNIVERSAL,type:g.Type.SEQUENCE,constructed:!0,captureAsn1:"tbsCertificate",value:[{name:"Certificate.TBSCertificate.version",tagClass:g.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.version.integer",tagClass:g.Class.UNIVERSAL,type:g.Type.INTEGER,constructed:!1,capture:"certVersion"}]},{name:"Certificate.TBSCertificate.serialNumber",tagClass:g.Class.UNIVERSAL,type:g.Type.INTEGER,constructed:!1,capture:"certSerialNumber"},{name:"Certificate.TBSCertificate.signature",tagClass:g.Class.UNIVERSAL,type:g.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate.signature.algorithm",tagClass:g.Class.UNIVERSAL,type:g.Type.OID,constructed:!1,capture:"certinfoSignatureOid"},{name:"Certificate.TBSCertificate.signature.parameters",tagClass:g.Class.UNIVERSAL,optional:!0,captureAsn1:"certinfoSignatureParams"}]},{name:"Certificate.TBSCertificate.issuer",tagClass:g.Class.UNIVERSAL,type:g.Type.SEQUENCE,constructed:!0,captureAsn1:"certIssuer"},{name:"Certificate.TBSCertificate.validity",tagClass:g.Class.UNIVERSAL,type:g.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate.validity.notBefore (utc)",tagClass:g.Class.UNIVERSAL,type:g.Type.UTCTIME,constructed:!1,optional:!0,capture:"certValidity1UTCTime"},{name:"Certificate.TBSCertificate.validity.notBefore (generalized)",tagClass:g.Class.UNIVERSAL,type:g.Type.GENERALIZEDTIME,constructed:!1,optional:!0,capture:"certValidity2GeneralizedTime"},{name:"Certificate.TBSCertificate.validity.notAfter (utc)",tagClass:g.Class.UNIVERSAL,type:g.Type.UTCTIME,constructed:!1,optional:!0,capture:"certValidity3UTCTime"},{name:"Certificate.TBSCertificate.validity.notAfter (generalized)",tagClass:g.Class.UNIVERSAL,type:g.Type.GENERALIZEDTIME,constructed:!1,optional:!0,capture:"certValidity4GeneralizedTime"}]},{name:"Certificate.TBSCertificate.subject",tagClass:g.Class.UNIVERSAL,type:g.Type.SEQUENCE,constructed:!0,captureAsn1:"certSubject"},ud,{name:"Certificate.TBSCertificate.issuerUniqueID",tagClass:g.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.issuerUniqueID.id",tagClass:g.Class.UNIVERSAL,type:g.Type.BITSTRING,constructed:!1,captureBitStringValue:"certIssuerUniqueId"}]},{name:"Certificate.TBSCertificate.subjectUniqueID",tagClass:g.Class.CONTEXT_SPECIFIC,type:2,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.subjectUniqueID.id",tagClass:g.Class.UNIVERSAL,type:g.Type.BITSTRING,constructed:!1,captureBitStringValue:"certSubjectUniqueId"}]},{name:"Certificate.TBSCertificate.extensions",tagClass:g.Class.CONTEXT_SPECIFIC,type:3,constructed:!0,captureAsn1:"certExtensions",optional:!0}]},{name:"Certificate.signatureAlgorithm",tagClass:g.Class.UNIVERSAL,type:g.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.signatureAlgorithm.algorithm",tagClass:g.Class.UNIVERSAL,type:g.Type.OID,constructed:!1,capture:"certSignatureOid"},{name:"Certificate.TBSCertificate.signature.parameters",tagClass:g.Class.UNIVERSAL,optional:!0,captureAsn1:"certSignatureParams"}]},{name:"Certificate.signatureValue",tagClass:g.Class.UNIVERSAL,type:g.Type.BITSTRING,constructed:!1,captureBitStringValue:"certSignature"}]},ty={name:"rsapss",tagClass:g.Class.UNIVERSAL,type:g.Type.SEQUENCE,constructed:!0,value:[{name:"rsapss.hashAlgorithm",tagClass:g.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,value:[{name:"rsapss.hashAlgorithm.AlgorithmIdentifier",tagClass:g.Class.UNIVERSAL,type:g.Class.SEQUENCE,constructed:!0,optional:!0,value:[{name:"rsapss.hashAlgorithm.AlgorithmIdentifier.algorithm",tagClass:g.Class.UNIVERSAL,type:g.Type.OID,constructed:!1,capture:"hashOid"}]}]},{name:"rsapss.maskGenAlgorithm",tagClass:g.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier",tagClass:g.Class.UNIVERSAL,type:g.Class.SEQUENCE,constructed:!0,optional:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.algorithm",tagClass:g.Class.UNIVERSAL,type:g.Type.OID,constructed:!1,capture:"maskGenOid"},{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.params",tagClass:g.Class.UNIVERSAL,type:g.Type.SEQUENCE,constructed:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.params.algorithm",tagClass:g.Class.UNIVERSAL,type:g.Type.OID,constructed:!1,capture:"maskGenHashOid"}]}]}]},{name:"rsapss.saltLength",tagClass:g.Class.CONTEXT_SPECIFIC,type:2,optional:!0,value:[{name:"rsapss.saltLength.saltLength",tagClass:g.Class.UNIVERSAL,type:g.Class.INTEGER,constructed:!1,capture:"saltLength"}]},{name:"rsapss.trailerField",tagClass:g.Class.CONTEXT_SPECIFIC,type:3,optional:!0,value:[{name:"rsapss.trailer.trailer",tagClass:g.Class.UNIVERSAL,type:g.Class.INTEGER,constructed:!1,capture:"trailer"}]}]},ry={name:"CertificationRequestInfo",tagClass:g.Class.UNIVERSAL,type:g.Type.SEQUENCE,constructed:!0,captureAsn1:"certificationRequestInfo",value:[{name:"CertificationRequestInfo.integer",tagClass:g.Class.UNIVERSAL,type:g.Type.INTEGER,constructed:!1,capture:"certificationRequestInfoVersion"},{name:"CertificationRequestInfo.subject",tagClass:g.Class.UNIVERSAL,type:g.Type.SEQUENCE,constructed:!0,captureAsn1:"certificationRequestInfoSubject"},ud,{name:"CertificationRequestInfo.attributes",tagClass:g.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,capture:"certificationRequestInfoAttributes",value:[{name:"CertificationRequestInfo.attributes",tagClass:g.Class.UNIVERSAL,type:g.Type.SEQUENCE,constructed:!0,value:[{name:"CertificationRequestInfo.attributes.type",tagClass:g.Class.UNIVERSAL,type:g.Type.OID,constructed:!1},{name:"CertificationRequestInfo.attributes.value",tagClass:g.Class.UNIVERSAL,type:g.Type.SET,constructed:!0}]}]}]},ny={name:"CertificationRequest",tagClass:g.Class.UNIVERSAL,type:g.Type.SEQUENCE,constructed:!0,captureAsn1:"csr",value:[ry,{name:"CertificationRequest.signatureAlgorithm",tagClass:g.Class.UNIVERSAL,type:g.Type.SEQUENCE,constructed:!0,value:[{name:"CertificationRequest.signatureAlgorithm.algorithm",tagClass:g.Class.UNIVERSAL,type:g.Type.OID,constructed:!1,capture:"csrSignatureOid"},{name:"CertificationRequest.signatureAlgorithm.parameters",tagClass:g.Class.UNIVERSAL,optional:!0,captureAsn1:"csrSignatureParams"}]},{name:"CertificationRequest.signature",tagClass:g.Class.UNIVERSAL,type:g.Type.BITSTRING,constructed:!1,captureBitStringValue:"csrSignature"}]};M.RDNAttributesAsArray=function(e,t){var n=[],r,i,s;for(var a=0;a<e.value.length;++a){r=e.value[a];for(var o=0;o<r.value.length;++o){if(s={},i=r.value[o],s.type=g.derToOid(i.value[0].value),s.value=i.value[1].value,s.valueTagClass=i.value[1].type,s.type in Be){if(s.name=Be[s.type],s.name in Ye)s.shortName=Ye[s.name]}if(t)t.update(s.type),t.update(s.value);n.push(s)}}return n};M.CRIAttributesAsArray=function(e){var t=[];for(var n=0;n<e.length;++n){var r=e[n],i=g.derToOid(r.value[0].value),s=r.value[1].value;for(var a=0;a<s.length;++a){var o={};if(o.type=i,o.value=s[a].value,o.valueTagClass=s[a].type,o.type in Be){if(o.name=Be[o.type],o.name in Ye)o.shortName=Ye[o.name]}if(o.type===Be.extensionRequest){o.extensions=[];for(var l=0;l<o.value.length;++l)o.extensions.push(M.certificateExtensionFromAsn1(o.value[l]))}t.push(o)}}return t};function Fr(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 js=function(e,t,n){var r={};if(e!==Be["RSASSA-PSS"])return r;if(n)r={hash:{algorithmOid:Be.sha1},mgf:{algorithmOid:Be.mgf1,hash:{algorithmOid:Be.sha1}},saltLength:20};var i={},s=[];if(!g.validate(t,ty,i,s)){var a=Error("Cannot read RSASSA-PSS parameter block.");throw a.errors=s,a}if(i.hashOid!==void 0)r.hash=r.hash||{},r.hash.algorithmOid=g.derToOid(i.hashOid);if(i.maskGenOid!==void 0)r.mgf=r.mgf||{},r.mgf.algorithmOid=g.derToOid(i.maskGenOid),r.mgf.hash=r.mgf.hash||{},r.mgf.hash.algorithmOid=g.derToOid(i.maskGenHashOid);if(i.saltLength!==void 0)r.saltLength=i.saltLength.charCodeAt(0);return r},zs=function(e){switch(Be[e.signatureOid]){case"sha1WithRSAEncryption":case"sha1WithRSASignature":return ie.md.sha1.create();case"md5WithRSAEncryption":return ie.md.md5.create();case"sha256WithRSAEncryption":return ie.md.sha256.create();case"sha384WithRSAEncryption":return ie.md.sha384.create();case"sha512WithRSAEncryption":return ie.md.sha512.create();case"RSASSA-PSS":return ie.md.sha256.create();default:var t=Error("Could not compute "+e.type+" digest. Unknown signature OID.");throw t.signatureOid=e.signatureOid,t}},dd=function(e){var t=e.certificate,n=e.publicKey||t.publicKey,r;switch(t.signatureOid){case Be.sha1WithRSAEncryption:case Be.sha1WithRSASignature:break;case Be["RSASSA-PSS"]:var i,s;if(i=Be[t.signatureParameters.mgf.hash.algorithmOid],i===void 0||ie.md[i]===void 0){var a=Error("Unsupported MGF hash function.");throw a.oid=t.signatureParameters.mgf.hash.algorithmOid,a.name=i,a}if(s=Be[t.signatureParameters.mgf.algorithmOid],s===void 0||ie.mgf[s]===void 0){var a=Error("Unsupported MGF function.");throw a.oid=t.signatureParameters.mgf.algorithmOid,a.name=s,a}if(s=ie.mgf[s].create(ie.md[i].create()),i=Be[t.signatureParameters.hash.algorithmOid],i===void 0||ie.md[i]===void 0){var a=Error("Unsupported RSASSA-PSS hash function.");throw a.oid=t.signatureParameters.hash.algorithmOid,a.name=i,a}r=ie.pss.create(ie.md[i].create(),s,t.signatureParameters.saltLength);break}return n.verify(e.md.digest().getBytes(),e.signature,r)};M.certificateFromPem=function(e,t,n){var r=ie.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 s=g.fromDer(r.body,n);return M.certificateFromAsn1(s,t)};M.certificateToPem=function(e,t){var n={type:"CERTIFICATE",body:g.toDer(M.certificateToAsn1(e)).getBytes()};return ie.pem.encode(n,{maxline:t})};M.publicKeyFromPem=function(e){var t=ie.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=g.fromDer(t.body);return M.publicKeyFromAsn1(r)};M.publicKeyToPem=function(e,t){var n={type:"PUBLIC KEY",body:g.toDer(M.publicKeyToAsn1(e)).getBytes()};return ie.pem.encode(n,{maxline:t})};M.publicKeyToRSAPublicKeyPem=function(e,t){var n={type:"RSA PUBLIC KEY",body:g.toDer(M.publicKeyToRSAPublicKey(e)).getBytes()};return ie.pem.encode(n,{maxline:t})};M.getPublicKeyFingerprint=function(e,t){t=t||{};var n=t.md||ie.md.sha1.create(),r=t.type||"RSAPublicKey",i;switch(r){case"RSAPublicKey":i=g.toDer(M.publicKeyToRSAPublicKey(e)).getBytes();break;case"SubjectPublicKeyInfo":i=g.toDer(M.publicKeyToAsn1(e)).getBytes();break;default:throw Error('Unknown fingerprint type "'+t.type+'".')}n.start(),n.update(i);var s=n.digest();if(t.encoding==="hex"){var a=s.toHex();if(t.delimiter)return a.match(/.{2}/g).join(t.delimiter);return a}else if(t.encoding==="binary")return s.getBytes();else if(t.encoding)throw Error('Unknown encoding "'+t.encoding+'".');return s};M.certificationRequestFromPem=function(e,t,n){var r=ie.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 s=g.fromDer(r.body,n);return M.certificationRequestFromAsn1(s,t)};M.certificationRequestToPem=function(e,t){var n={type:"CERTIFICATE REQUEST",body:g.toDer(M.certificationRequestToAsn1(e)).getBytes()};return ie.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 Fr(e.issuer,t)},e.issuer.addField=function(t){Vt([t]),e.issuer.attributes.push(t)},e.issuer.attributes=[],e.issuer.hash=null,e.subject={},e.subject.getField=function(t){return Fr(e.subject,t)},e.subject.addField=function(t){Vt([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(Vt(t),e.subject.attributes=t,delete e.subject.uniqueId,n)e.subject.uniqueId=n;e.subject.hash=null},e.setIssuer=function(t,n){if(Vt(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)fd(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||ie.md.sha1.create();var r=Be[e.md.algorithm+"WithRSAEncryption"];if(!r){var i=Error("Could not compute certificate digest. Unknown message digest algorithm OID.");throw i.algorithm=e.md.algorithm,i}e.signatureOid=e.siginfo.algorithmOid=r,e.tbsCertificate=M.getTBSCertificate(e);var s=g.toDer(e.tbsCertificate);e.md.update(s.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,s=Error("The parent certificate did not issue the given child certificate; the child certificate's issuer does not match the parent's subject.");throw s.expectedIssuer=i.attributes,s.actualIssuer=r.attributes,s}var a=t.md;if(a===null){a=zs({signatureOid:t.signatureOid,type:"certificate"});var o=t.tbsCertificate||M.getTBSCertificate(t),l=g.toDer(o);a.update(l.getBytes())}if(a!==null)n=dd({certificate:t,publicKey:e.publicKey,md:a,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 s,a;for(var o=0;n&&o<r.attributes.length;++o)if(s=r.attributes[o],a=i.attributes[o],s.type!==a.type||s.value!==a.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=Be.subjectKeyIdentifier;for(var n=0;n<e.extensions.length;++n){var r=e.extensions[n];if(r.id===t){var i=e.generateSubjectKeyIdentifier().getBytes();return ie.util.hexToBytes(r.subjectKeyIdentifier)===i}}return!1},e};M.certificateFromAsn1=function(e,t){var n={},r=[];if(!g.validate(e,ey,n,r)){var i=Error("Cannot read X.509 certificate. ASN.1 object is not an X509v3 Certificate.");throw i.errors=r,i}var s=g.derToOid(n.publicKeyOid);if(s!==M.oids.rsaEncryption)throw Error("Cannot read public key. OID is not RSA.");var a=M.createCertificate();a.version=n.certVersion?n.certVersion.charCodeAt(0):0;var o=ie.util.createBuffer(n.certSerialNumber);a.serialNumber=o.toHex(),a.signatureOid=ie.asn1.derToOid(n.certSignatureOid),a.signatureParameters=js(a.signatureOid,n.certSignatureParams,!0),a.siginfo.algorithmOid=ie.asn1.derToOid(n.certinfoSignatureOid),a.siginfo.parameters=js(a.siginfo.algorithmOid,n.certinfoSignatureParams,!1),a.signature=n.certSignature;var l=[];if(n.certValidity1UTCTime!==void 0)l.push(g.utcTimeToDate(n.certValidity1UTCTime));if(n.certValidity2GeneralizedTime!==void 0)l.push(g.generalizedTimeToDate(n.certValidity2GeneralizedTime));if(n.certValidity3UTCTime!==void 0)l.push(g.utcTimeToDate(n.certValidity3UTCTime));if(n.certValidity4GeneralizedTime!==void 0)l.push(g.generalizedTimeToDate(n.certValidity4GeneralizedTime));if(l.length>2)throw Error("Cannot read notBefore/notAfter validity times; more than two times were provided in the certificate.");if(l.length<2)throw Error("Cannot read notBefore/notAfter validity times; they were not provided as either UTCTime or GeneralizedTime.");if(a.validity.notBefore=l[0],a.validity.notAfter=l[1],a.tbsCertificate=n.tbsCertificate,t){a.md=zs({signatureOid:a.signatureOid,type:"certificate"});var c=g.toDer(a.tbsCertificate);a.md.update(c.getBytes())}var u=ie.md.sha1.create(),d=g.toDer(n.certIssuer);if(u.update(d.getBytes()),a.issuer.getField=function(f){return Fr(a.issuer,f)},a.issuer.addField=function(f){Vt([f]),a.issuer.attributes.push(f)},a.issuer.attributes=M.RDNAttributesAsArray(n.certIssuer),n.certIssuerUniqueId)a.issuer.uniqueId=n.certIssuerUniqueId;a.issuer.hash=u.digest().toHex();var p=ie.md.sha1.create(),h=g.toDer(n.certSubject);if(p.update(h.getBytes()),a.subject.getField=function(f){return Fr(a.subject,f)},a.subject.addField=function(f){Vt([f]),a.subject.attributes.push(f)},a.subject.attributes=M.RDNAttributesAsArray(n.certSubject),n.certSubjectUniqueId)a.subject.uniqueId=n.certSubjectUniqueId;if(a.subject.hash=p.digest().toHex(),n.certExtensions)a.extensions=M.certificateExtensionsFromAsn1(n.certExtensions);else a.extensions=[];return a.publicKey=M.publicKeyFromAsn1(n.subjectPublicKeyInfo),a};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=g.derToOid(e.value[0].value),t.critical=!1,e.value[1].type===g.Type.BOOLEAN)t.critical=e.value[1].value.charCodeAt(0)!==0,t.value=e.value[2].value;else t.value=e.value[1].value;if(t.id in Be){if(t.name=Be[t.id],t.name==="keyUsage"){var n=g.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=g.fromDer(t.value);if(n.value.length>0&&n.value[0].type===g.Type.BOOLEAN)t.cA=n.value[0].value.charCodeAt(0)!==0;else t.cA=!1;var s=null;if(n.value.length>0&&n.value[0].type===g.Type.INTEGER)s=n.value[0].value;else if(n.value.length>1)s=n.value[1].value;if(s!==null)t.pathLenConstraint=g.derToInteger(s)}else if(t.name==="extKeyUsage"){var n=g.fromDer(t.value);for(var a=0;a<n.value.length;++a){var o=g.derToOid(n.value[a].value);if(o in Be)t[Be[o]]=!0;else t[o]=!0}}else if(t.name==="nsCertType"){var n=g.fromDer(t.value),r=0;if(n.value.length>1)r=n.value.charCodeAt(1);t.client=(r&128)===128,t.server=(r&64)===64,t.email=(r&32)===32,t.objsign=(r&16)===16,t.reserved=(r&8)===8,t.sslCA=(r&4)===4,t.emailCA=(r&2)===2,t.objCA=(r&1)===1}else if(t.name==="subjectAltName"||t.name==="issuerAltName"){t.altNames=[];var l,n=g.fromDer(t.value);for(var c=0;c<n.value.length;++c){l=n.value[c];var u={type:l.type,value:l.value};switch(t.altNames.push(u),l.type){case 1:case 2:case 6:break;case 7:u.ip=ie.util.bytesToIP(l.value);break;case 8:u.oid=g.derToOid(l.value);break;default:}}}else if(t.name==="subjectKeyIdentifier"){var n=g.fromDer(t.value);t.subjectKeyIdentifier=ie.util.bytesToHex(n.value)}}return t};M.certificationRequestFromAsn1=function(e,t){var n={},r=[];if(!g.validate(e,ny,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 s=g.derToOid(n.publicKeyOid);if(s!==M.oids.rsaEncryption)throw Error("Cannot read public key. OID is not RSA.");var a=M.createCertificationRequest();if(a.version=n.csrVersion?n.csrVersion.charCodeAt(0):0,a.signatureOid=ie.asn1.derToOid(n.csrSignatureOid),a.signatureParameters=js(a.signatureOid,n.csrSignatureParams,!0),a.siginfo.algorithmOid=ie.asn1.derToOid(n.csrSignatureOid),a.siginfo.parameters=js(a.siginfo.algorithmOid,n.csrSignatureParams,!1),a.signature=n.csrSignature,a.certificationRequestInfo=n.certificationRequestInfo,t){a.md=zs({signatureOid:a.signatureOid,type:"certification request"});var o=g.toDer(a.certificationRequestInfo);a.md.update(o.getBytes())}var l=ie.md.sha1.create();return a.subject.getField=function(c){return Fr(a.subject,c)},a.subject.addField=function(c){Vt([c]),a.subject.attributes.push(c)},a.subject.attributes=M.RDNAttributesAsArray(n.certificationRequestInfoSubject,l),a.subject.hash=l.digest().toHex(),a.publicKey=M.publicKeyFromAsn1(n.subjectPublicKeyInfo),a.getAttribute=function(c){return Fr(a,c)},a.addAttribute=function(c){Vt([c]),a.attributes.push(c)},a.attributes=M.CRIAttributesAsArray(n.certificationRequestInfoAttributes||[]),a};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 Fr(e.subject,t)},e.subject.addField=function(t){Vt([t]),e.subject.attributes.push(t)},e.subject.attributes=[],e.subject.hash=null,e.publicKey=null,e.attributes=[],e.getAttribute=function(t){return Fr(e,t)},e.addAttribute=function(t){Vt([t]),e.attributes.push(t)},e.md=null,e.setSubject=function(t){Vt(t),e.subject.attributes=t,e.subject.hash=null},e.setAttributes=function(t){Vt(t),e.attributes=t},e.sign=function(t,n){e.md=n||ie.md.sha1.create();var r=Be[e.md.algorithm+"WithRSAEncryption"];if(!r){var i=Error("Could not compute certification request digest. Unknown message digest algorithm OID.");throw i.algorithm=e.md.algorithm,i}e.signatureOid=e.siginfo.algorithmOid=r,e.certificationRequestInfo=M.getCertificationRequestInfo(e);var s=g.toDer(e.certificationRequestInfo);e.md.update(s.getBytes()),e.signature=t.sign(e.md)},e.verify=function(){var t=!1,n=e.md;if(n===null){n=zs({signatureOid:e.signatureOid,type:"certification request"});var r=e.certificationRequestInfo||M.getCertificationRequestInfo(e),i=g.toDer(r);n.update(i.getBytes())}if(n!==null)t=dd({certificate:e,md:n,signature:e.signature});return t},e};function Nn(e){var t=g.create(g.Class.UNIVERSAL,g.Type.SEQUENCE,!0,[]),n,r,i=e.attributes;for(var s=0;s<i.length;++s){n=i[s];var a=n.value,o=g.Type.PRINTABLESTRING;if("valueTagClass"in n){if(o=n.valueTagClass,o===g.Type.UTF8)a=ie.util.encodeUtf8(a)}r=g.create(g.Class.UNIVERSAL,g.Type.SET,!0,[g.create(g.Class.UNIVERSAL,g.Type.SEQUENCE,!0,[g.create(g.Class.UNIVERSAL,g.Type.OID,!1,g.oidToDer(n.type).getBytes()),g.create(g.Class.UNIVERSAL,o,!1,a)])]),t.value.push(r)}return t}function Vt(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 Ye)t.name=M.oids[Ye[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 Ye)t.shortName=Ye[t.name]}if(t.type===Be.extensionRequest){if(t.valueConstructed=!0,t.valueTagClass=g.Type.SEQUENCE,!t.value&&t.extensions){t.value=[];for(var i=0;i<t.extensions.length;++i)t.value.push(M.certificateExtensionToAsn1(fd(t.extensions[i])))}}if(typeof t.value>"u"){var r=Error("Attribute value not specified.");throw r.attribute=t,r}}}function fd(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,s=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)s|=128,r=7;var a=String.fromCharCode(r);if(s!==0)a+=String.fromCharCode(i)+String.fromCharCode(s);else if(i!==0)a+=String.fromCharCode(i);e.value=g.create(g.Class.UNIVERSAL,g.Type.BITSTRING,!1,a)}else if(e.name==="basicConstraints"){if(e.value=g.create(g.Class.UNIVERSAL,g.Type.SEQUENCE,!0,[]),e.cA)e.value.value.push(g.create(g.Class.UNIVERSAL,g.Type.BOOLEAN,!1,String.fromCharCode(255)));if("pathLenConstraint"in e)e.value.value.push(g.create(g.Class.UNIVERSAL,g.Type.INTEGER,!1,g.integerToDer(e.pathLenConstraint).getBytes()))}else if(e.name==="extKeyUsage"){e.value=g.create(g.Class.UNIVERSAL,g.Type.SEQUENCE,!0,[]);var o=e.value.value;for(var l in e){if(e[l]!==!0)continue;if(l in Be)o.push(g.create(g.Class.UNIVERSAL,g.Type.OID,!1,g.oidToDer(Be[l]).getBytes()));else if(l.indexOf(".")!==-1)o.push(g.create(g.Class.UNIVERSAL,g.Type.OID,!1,g.oidToDer(l).getBytes()))}}else if(e.name==="nsCertType"){var r=0,i=0;if(e.client)i|=128,r=7;if(e.server)i|=64,r=6;if(e.email)i|=32,r=5;if(e.objsign)i|=16,r=4;if(e.reserved)i|=8,r=3;if(e.sslCA)i|=4,r=2;if(e.emailCA)i|=2,r=1;if(e.objCA)i|=1,r=0;var a=String.fromCharCode(r);if(i!==0)a+=String.fromCharCode(i);e.value=g.create(g.Class.UNIVERSAL,g.Type.BITSTRING,!1,a)}else if(e.name==="subjectAltName"||e.name==="issuerAltName"){e.value=g.create(g.Class.UNIVERSAL,g.Type.SEQUENCE,!0,[]);var c;for(var u=0;u<e.altNames.length;++u){c=e.altNames[u];var a=c.value;if(c.type===7&&c.ip){if(a=ie.util.bytesFromIP(c.ip),a===null){var n=Error('Extension "ip" value is not a valid IPv4 or IPv6 address.');throw n.extension=e,n}}else if(c.type===8)if(c.oid)a=g.oidToDer(g.oidToDer(c.oid));else a=g.oidToDer(a);e.value.value.push(g.create(g.Class.CONTEXT_SPECIFIC,c.type,!1,a))}}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=g.create(g.Class.UNIVERSAL,g.Type.IA5STRING,!1,e.comment)}else if(e.name==="subjectKeyIdentifier"&&t.cert){var d=t.cert.generateSubjectKeyIdentifier();e.subjectKeyIdentifier=d.toHex(),e.value=g.create(g.Class.UNIVERSAL,g.Type.OCTETSTRING,!1,d.getBytes())}else if(e.name==="authorityKeyIdentifier"&&t.cert){e.value=g.create(g.Class.UNIVERSAL,g.Type.SEQUENCE,!0,[]);var o=e.value.value;if(e.keyIdentifier){var p=e.keyIdentifier===!0?t.cert.generateSubjectKeyIdentifier().getBytes():e.keyIdentifier;o.push(g.create(g.Class.CONTEXT_SPECIFIC,0,!1,p))}if(e.authorityCertIssuer){var h=[g.create(g.Class.CONTEXT_SPECIFIC,4,!0,[Nn(e.authorityCertIssuer===!0?t.cert.issuer:e.authorityCertIssuer)])];o.push(g.create(g.Class.CONTEXT_SPECIFIC,1,!0,h))}if(e.serialNumber){var f=ie.util.hexToBytes(e.serialNumber===!0?t.cert.serialNumber:e.serialNumber);o.push(g.create(g.Class.CONTEXT_SPECIFIC,2,!1,f))}}else if(e.name==="cRLDistributionPoints"){e.value=g.create(g.Class.UNIVERSAL,g.Type.SEQUENCE,!0,[]);var o=e.value.value,v=g.create(g.Class.UNIVERSAL,g.Type.SEQUENCE,!0,[]),x=g.create(g.Class.CONTEXT_SPECIFIC,0,!0,[]),c;for(var u=0;u<e.altNames.length;++u){c=e.altNames[u];var a=c.value;if(c.type===7&&c.ip){if(a=ie.util.bytesFromIP(c.ip),a===null){var n=Error('Extension "ip" value is not a valid IPv4 or IPv6 address.');throw n.extension=e,n}}else if(c.type===8)if(c.oid)a=g.oidToDer(g.oidToDer(c.oid));else a=g.oidToDer(a);x.value.push(g.create(g.Class.CONTEXT_SPECIFIC,c.type,!1,a))}v.value.push(g.create(g.Class.CONTEXT_SPECIFIC,0,!0,[x])),o.push(v)}if(typeof e.value>"u"){var n=Error("Extension value not specified.");throw n.extension=e,n}return e}function Uo(e,t){switch(e){case Be["RSASSA-PSS"]:var n=[];if(t.hash.algorithmOid!==void 0)n.push(g.create(g.Class.CONTEXT_SPECIFIC,0,!0,[g.create(g.Class.UNIVERSAL,g.Type.SEQUENCE,!0,[g.create(g.Class.UNIVERSAL,g.Type.OID,!1,g.oidToDer(t.hash.algorithmOid).getBytes()),g.create(g.Class.UNIVERSAL,g.Type.NULL,!1,"")])]));if(t.mgf.algorithmOid!==void 0)n.push(g.create(g.Class.CONTEXT_SPECIFIC,1,!0,[g.create(g.Class.UNIVERSAL,g.Type.SEQUENCE,!0,[g.create(g.Class.UNIVERSAL,g.Type.OID,!1,g.oidToDer(t.mgf.algorithmOid).getBytes()),g.create(g.Class.UNIVERSAL,g.Type.SEQUENCE,!0,[g.create(g.Class.UNIVERSAL,g.Type.OID,!1,g.oidToDer(t.mgf.hash.algorithmOid).getBytes()),g.create(g.Class.UNIVERSAL,g.Type.NULL,!1,"")])])]));if(t.saltLength!==void 0)n.push(g.create(g.Class.CONTEXT_SPECIFIC,2,!0,[g.create(g.Class.UNIVERSAL,g.Type.INTEGER,!1,g.integerToDer(t.saltLength).getBytes())]));return g.create(g.Class.UNIVERSAL,g.Type.SEQUENCE,!0,n);default:return g.create(g.Class.UNIVERSAL,g.Type.NULL,!1,"")}}function iy(e){var t=g.create(g.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],s=i.value,a=g.Type.UTF8;if("valueTagClass"in i)a=i.valueTagClass;if(a===g.Type.UTF8)s=ie.util.encodeUtf8(s);var o=!1;if("valueConstructed"in i)o=i.valueConstructed;var l=g.create(g.Class.UNIVERSAL,g.Type.SEQUENCE,!0,[g.create(g.Class.UNIVERSAL,g.Type.OID,!1,g.oidToDer(i.type).getBytes()),g.create(g.Class.UNIVERSAL,g.Type.SET,!0,[g.create(g.Class.UNIVERSAL,a,o,s)])]);t.value.push(l)}return t}var sy=new Date("1950-01-01T00:00:00Z"),ay=new Date("2050-01-01T00:00:00Z");function cd(e){if(e>=sy&&e<ay)return g.create(g.Class.UNIVERSAL,g.Type.UTCTIME,!1,g.dateToUtcTime(e));else return g.create(g.Class.UNIVERSAL,g.Type.GENERALIZEDTIME,!1,g.dateToGeneralizedTime(e))}M.getTBSCertificate=function(e){var t=cd(e.validity.notBefore),n=cd(e.validity.notAfter),r=g.create(g.Class.UNIVERSAL,g.Type.SEQUENCE,!0,[g.create(g.Class.CONTEXT_SPECIFIC,0,!0,[g.create(g.Class.UNIVERSAL,g.Type.INTEGER,!1,g.integerToDer(e.version).getBytes())]),g.create(g.Class.UNIVERSAL,g.Type.INTEGER,!1,ie.util.hexToBytes(e.serialNumber)),g.create(g.Class.UNIVERSAL,g.Type.SEQUENCE,!0,[g.create(g.Class.UNIVERSAL,g.Type.OID,!1,g.oidToDer(e.siginfo.algorithmOid).getBytes()),Uo(e.siginfo.algorithmOid,e.siginfo.parameters)]),Nn(e.issuer),g.create(g.Class.UNIVERSAL,g.Type.SEQUENCE,!0,[t,n]),Nn(e.subject),M.publicKeyToAsn1(e.publicKey)]);if(e.issuer.uniqueId)r.value.push(g.create(g.Class.CONTEXT_SPECIFIC,1,!0,[g.create(g.Class.UNIVERSAL,g.Type.BITSTRING,!1,String.fromCharCode(0)+e.issuer.uniqueId)]));if(e.subject.uniqueId)r.value.push(g.create(g.Class.CONTEXT_SPECIFIC,2,!0,[g.create(g.Class.UNIVERSAL,g.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=g.create(g.Class.UNIVERSAL,g.Type.SEQUENCE,!0,[g.create(g.Class.UNIVERSAL,g.Type.INTEGER,!1,g.integerToDer(e.version).getBytes()),Nn(e.subject),M.publicKeyToAsn1(e.publicKey),iy(e)]);return t};M.distinguishedNameToAsn1=function(e){return Nn(e)};M.certificateToAsn1=function(e){var t=e.tbsCertificate||M.getTBSCertificate(e);return g.create(g.Class.UNIVERSAL,g.Type.SEQUENCE,!0,[t,g.create(g.Class.UNIVERSAL,g.Type.SEQUENCE,!0,[g.create(g.Class.UNIVERSAL,g.Type.OID,!1,g.oidToDer(e.signatureOid).getBytes()),Uo(e.signatureOid,e.signatureParameters)]),g.create(g.Class.UNIVERSAL,g.Type.BITSTRING,!1,String.fromCharCode(0)+e.signature)])};M.certificateExtensionsToAsn1=function(e){var t=g.create(g.Class.CONTEXT_SPECIFIC,3,!0,[]),n=g.create(g.Class.UNIVERSAL,g.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=g.create(g.Class.UNIVERSAL,g.Type.SEQUENCE,!0,[]);if(t.value.push(g.create(g.Class.UNIVERSAL,g.Type.OID,!1,g.oidToDer(e.id).getBytes())),e.critical)t.value.push(g.create(g.Class.UNIVERSAL,g.Type.BOOLEAN,!1,String.fromCharCode(255)));var n=e.value;if(typeof e.value!=="string")n=g.toDer(n).getBytes();return t.value.push(g.create(g.Class.UNIVERSAL,g.Type.OCTETSTRING,!1,n)),t};M.certificationRequestToAsn1=function(e){var t=e.certificationRequestInfo||M.getCertificationRequestInfo(e);return g.create(g.Class.UNIVERSAL,g.Type.SEQUENCE,!0,[t,g.create(g.Class.UNIVERSAL,g.Type.SEQUENCE,!0,[g.create(g.Class.UNIVERSAL,g.Type.OID,!1,g.oidToDer(e.signatureOid).getBytes()),Uo(e.signatureOid,e.signatureParameters)]),g.create(g.Class.UNIVERSAL,g.Type.BITSTRING,!1,String.fromCharCode(0)+e.signature)])};M.createCaStore=function(e){var t={certs:{}};t.getIssuer=function(a){var o=n(a.issuer);return o},t.addCertificate=function(a){if(typeof a==="string")a=ie.pki.certificateFromPem(a);if(r(a.subject),!t.hasCertificate(a))if(a.subject.hash in t.certs){var o=t.certs[a.subject.hash];if(!ie.util.isArray(o))o=[o];o.push(a),t.certs[a.subject.hash]=o}else t.certs[a.subject.hash]=a},t.hasCertificate=function(a){if(typeof a==="string")a=ie.pki.certificateFromPem(a);var o=n(a.subject);if(!o)return!1;if(!ie.util.isArray(o))o=[o];var l=g.toDer(M.certificateToAsn1(a)).getBytes();for(var c=0;c<o.length;++c){var u=g.toDer(M.certificateToAsn1(o[c])).getBytes();if(l===u)return!0}return!1},t.listAllCertificates=function(){var a=[];for(var o in t.certs)if(t.certs.hasOwnProperty(o)){var l=t.certs[o];if(!ie.util.isArray(l))a.push(l);else for(var c=0;c<l.length;++c)a.push(l[c])}return a},t.removeCertificate=function(a){var o;if(typeof a==="string")a=ie.pki.certificateFromPem(a);if(r(a.subject),!t.hasCertificate(a))return null;var l=n(a.subject);if(!ie.util.isArray(l))return o=t.certs[a.subject.hash],delete t.certs[a.subject.hash],o;var c=g.toDer(M.certificateToAsn1(a)).getBytes();for(var u=0;u<l.length;++u){var d=g.toDer(M.certificateToAsn1(l[u])).getBytes();if(c===d)o=l[u],l.splice(u,1)}if(l.length===0)delete t.certs[a.subject.hash];return o};function n(a){return r(a),t.certs[a.hash]||null}function r(a){if(!a.hash){var o=ie.md.sha1.create();a.attributes=M.RDNAttributesAsArray(Nn(a),o),a.hash=o.digest().toHex()}}if(e)for(var i=0;i<e.length;++i){var s=e[i];t.addCertificate(s)}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"};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 s=!0,a=null,o=0;do{var l=t.shift(),c=null,u=!1;if(i){if(i<l.validity.notBefore||i>l.validity.notAfter)a={message:"Certificate is not valid yet or has expired.",error:M.certificateError.certificate_expired,notBefore:l.validity.notBefore,notAfter:l.validity.notAfter,now:i}}if(a===null){if(c=t[0]||e.getIssuer(l),c===null){if(l.isIssuer(l))u=!0,c=l}if(c){var d=ie.util.isArray(c)?c.slice():[c],p=!1;while(!p&&d.length>0){c=d.shift();try{p=c.verify(l)}catch(R){}}if(!p)a={message:"Certificate signature is invalid.",error:M.certificateError.bad_certificate}}if(a===null&&(!c||u)&&!e.hasCertificate(l))a={message:"Certificate is not trusted.",error:M.certificateError.unknown_ca}}if(a===null&&c&&!l.isIssuer(c))a={message:"Certificate issuer is invalid.",error:M.certificateError.bad_certificate};if(a===null){var h={keyUsage:!0,basicConstraints:!0};for(var f=0;a===null&&f<l.extensions.length;++f){var v=l.extensions[f];if(v.critical&&!(v.name in h))a={message:"Certificate has an unsupported critical extension.",error:M.certificateError.unsupported_certificate}}}if(a===null&&(!s||t.length===0&&(!c||u))){var x=l.getExtension({id:"2.5.29.19"}),S=l.getExtension("keyUsage");if(S!==null){if(!S.keyCertSign||x===null)a={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(a===null&&x===null)a={message:"Certificate is missing basicConstraints extension and cannot be used as a CA.",error:M.certificateError.bad_certificate};if(a===null&&x!==null&&!x.cA)a={message:"Certificate basicConstraints indicates the certificate is not a CA.",error:M.certificateError.bad_certificate};if(a===null&&x!==null&&"pathLenConstraint"in x){var A=o-1;if(A>x.pathLenConstraint)a={message:"Certificate basicConstraints pathLenConstraint violated.",error:M.certificateError.bad_certificate}}}var b=a===null?!0:a.error,k=n.verify?n.verify(b,o,r):b;if(k===!0)a=null;else{if(b===!0)a={message:"The application rejected the certificate.",error:M.certificateError.bad_certificate};if(k||k===0){if(typeof k==="object"&&!ie.util.isArray(k)){if(k.message)a.message=k.message;if(k.error)a.error=k.error}else if(typeof k==="string")a.error=k}throw a}s=!1,++o}while(t.length>0);return!0}});var Fo=de(function(D1,gd){var Ke=ve();Gt();An();Or();Lo();Do();Lt();wi();Rn();Pe();Xs();var{asn1:C,pki:Ee}=Ke,Ti=gd.exports=Ke.pkcs12=Ke.pkcs12||{},hd={name:"ContentInfo",tagClass:C.Class.UNIVERSAL,type:C.Type.SEQUENCE,constructed:!0,value:[{name:"ContentInfo.contentType",tagClass:C.Class.UNIVERSAL,type:C.Type.OID,constructed:!1,capture:"contentType"},{name:"ContentInfo.content",tagClass:C.Class.CONTEXT_SPECIFIC,constructed:!0,captureAsn1:"content"}]},oy={name:"PFX",tagClass:C.Class.UNIVERSAL,type:C.Type.SEQUENCE,constructed:!0,value:[{name:"PFX.version",tagClass:C.Class.UNIVERSAL,type:C.Type.INTEGER,constructed:!1,capture:"version"},hd,{name:"PFX.macData",tagClass:C.Class.UNIVERSAL,type:C.Type.SEQUENCE,constructed:!0,optional:!0,captureAsn1:"mac",value:[{name:"PFX.macData.mac",tagClass:C.Class.UNIVERSAL,type:C.Type.SEQUENCE,constructed:!0,value:[{name:"PFX.macData.mac.digestAlgorithm",tagClass:C.Class.UNIVERSAL,type:C.Type.SEQUENCE,constructed:!0,value:[{name:"PFX.macData.mac.digestAlgorithm.algorithm",tagClass:C.Class.UNIVERSAL,type:C.Type.OID,constructed:!1,capture:"macAlgorithm"},{name:"PFX.macData.mac.digestAlgorithm.parameters",optional:!0,tagClass:C.Class.UNIVERSAL,captureAsn1:"macAlgorithmParameters"}]},{name:"PFX.macData.mac.digest",tagClass:C.Class.UNIVERSAL,type:C.Type.OCTETSTRING,constructed:!1,capture:"macDigest"}]},{name:"PFX.macData.macSalt",tagClass:C.Class.UNIVERSAL,type:C.Type.OCTETSTRING,constructed:!1,capture:"macSalt"},{name:"PFX.macData.iterations",tagClass:C.Class.UNIVERSAL,type:C.Type.INTEGER,constructed:!1,optional:!0,capture:"macIterations"}]}]},ly={name:"SafeBag",tagClass:C.Class.UNIVERSAL,type:C.Type.SEQUENCE,constructed:!0,value:[{name:"SafeBag.bagId",tagClass:C.Class.UNIVERSAL,type:C.Type.OID,constructed:!1,capture:"bagId"},{name:"SafeBag.bagValue",tagClass:C.Class.CONTEXT_SPECIFIC,constructed:!0,captureAsn1:"bagValue"},{name:"SafeBag.bagAttributes",tagClass:C.Class.UNIVERSAL,type:C.Type.SET,constructed:!0,optional:!0,capture:"bagAttributes"}]},cy={name:"Attribute",tagClass:C.Class.UNIVERSAL,type:C.Type.SEQUENCE,constructed:!0,value:[{name:"Attribute.attrId",tagClass:C.Class.UNIVERSAL,type:C.Type.OID,constructed:!1,capture:"oid"},{name:"Attribute.attrValues",tagClass:C.Class.UNIVERSAL,type:C.Type.SET,constructed:!0,capture:"values"}]},uy={name:"CertBag",tagClass:C.Class.UNIVERSAL,type:C.Type.SEQUENCE,constructed:!0,value:[{name:"CertBag.certId",tagClass:C.Class.UNIVERSAL,type:C.Type.OID,constructed:!1,capture:"certId"},{name:"CertBag.certValue",tagClass:C.Class.CONTEXT_SPECIFIC,constructed:!0,value:[{name:"CertBag.certValue[0]",tagClass:C.Class.UNIVERSAL,type:C.Class.OCTETSTRING,constructed:!1,capture:"cert"}]}]};function Ei(e,t,n,r){var i=[];for(var s=0;s<e.length;s++)for(var a=0;a<e[s].safeBags.length;a++){var o=e[s].safeBags[a];if(r!==void 0&&o.type!==r)continue;if(t===null){i.push(o);continue}if(o.attributes[t]!==void 0&&o.attributes[t].indexOf(n)>=0)i.push(o)}return i}Ti.pkcs12FromAsn1=function(e,t,n){if(typeof t==="string")n=t,t=!0;else if(t===void 0)t=!0;var r={},i=[];if(!C.validate(e,oy,r,i)){var s=Error("Cannot read PKCS#12 PFX. ASN.1 object is not an PKCS#12 PFX.");throw s.errors=s,s}var a={version:r.version.charCodeAt(0),safeContents:[],getBags:function(x){var S={},A;if("localKeyId"in x)A=x.localKeyId;else if("localKeyIdHex"in x)A=Ke.util.hexToBytes(x.localKeyIdHex);if(A===void 0&&!("friendlyName"in x)&&"bagType"in x)S[x.bagType]=Ei(a.safeContents,null,null,x.bagType);if(A!==void 0)S.localKeyId=Ei(a.safeContents,"localKeyId",A,x.bagType);if("friendlyName"in x)S.friendlyName=Ei(a.safeContents,"friendlyName",x.friendlyName,x.bagType);return S},getBagsByFriendlyName:function(x,S){return Ei(a.safeContents,"friendlyName",x,S)},getBagsByLocalKeyId:function(x,S){return Ei(a.safeContents,"localKeyId",x,S)}};if(r.version.charCodeAt(0)!==3){var s=Error("PKCS#12 PFX of version other than 3 not supported.");throw s.version=r.version.charCodeAt(0),s}if(C.derToOid(r.contentType)!==Ee.oids.data){var s=Error("Only PKCS#12 PFX in password integrity mode supported.");throw s.oid=C.derToOid(r.contentType),s}var o=r.content.value[0];if(o.tagClass!==C.Class.UNIVERSAL||o.type!==C.Type.OCTETSTRING)throw Error("PKCS#12 authSafe content data is not an OCTET STRING.");if(o=Vo(o),r.mac){var l=null,c=0,u=C.derToOid(r.macAlgorithm);switch(u){case Ee.oids.sha1:l=Ke.md.sha1.create(),c=20;break;case Ee.oids.sha256:l=Ke.md.sha256.create(),c=32;break;case Ee.oids.sha384:l=Ke.md.sha384.create(),c=48;break;case Ee.oids.sha512:l=Ke.md.sha512.create(),c=64;break;case Ee.oids.md5:l=Ke.md.md5.create(),c=16;break}if(l===null)throw Error("PKCS#12 uses unsupported MAC algorithm: "+u);var d=new Ke.util.ByteBuffer(r.macSalt),p="macIterations"in r?parseInt(Ke.util.bytesToHex(r.macIterations),16):1;if(!(p>=1))throw Error("PKCS#12 MAC iteration count must be >= 1.");var h=Ti.generateKey(n,d,3,p,c,l),f=Ke.hmac.create();f.start(l,h),f.update(o.value);var v=f.getMac();if(v.getBytes()!==r.macDigest)throw Error("PKCS#12 MAC could not be verified. Invalid password?")}else if(Array.isArray(e.value)&&e.value.length>2)throw Error("Invalid PKCS#12. macData field present but MAC was not validated.");return dy(a,o.value,t,n),a};function Vo(e){if(e.composed||e.constructed){var t=Ke.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 dy(e,t,n,r){if(t=C.fromDer(t,n),t.tagClass!==C.Class.UNIVERSAL||t.type!==C.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 s=t.value[i],a={},o=[];if(!C.validate(s,hd,a,o)){var l=Error("Cannot read ContentInfo.");throw l.errors=o,l}var c={encrypted:!1},u=null,d=a.content.value[0];switch(C.derToOid(a.contentType)){case Ee.oids.data:if(d.tagClass!==C.Class.UNIVERSAL||d.type!==C.Type.OCTETSTRING)throw Error("PKCS#12 SafeContents Data is not an OCTET STRING.");u=Vo(d).value;break;case Ee.oids.encryptedData:u=fy(d,r),c.encrypted=!0;break;default:var l=Error("Unsupported PKCS#12 contentType.");throw l.contentType=C.derToOid(a.contentType),l}c.safeBags=py(u,n,r),e.safeContents.push(c)}}function fy(e,t){var n={},r=[];if(!C.validate(e,Ke.pkcs7.asn1.encryptedDataValidator,n,r)){var i=Error("Cannot read EncryptedContentInfo.");throw i.errors=r,i}var s=C.derToOid(n.contentType);if(s!==Ee.oids.data){var i=Error("PKCS#12 EncryptedContentInfo ContentType is not Data.");throw i.oid=s,i}s=C.derToOid(n.encAlgorithm);var a=Ee.pbe.getCipher(s,n.encParameter,t),o=Vo(n.encryptedContentAsn1),l=Ke.util.createBuffer(o.value);if(a.update(l),!a.finish())throw Error("Failed to decrypt PKCS#12 SafeContents.");return a.output.getBytes()}function py(e,t,n){if(!t&&e.length===0)return[];if(e=C.fromDer(e,t),e.tagClass!==C.Class.UNIVERSAL||e.type!==C.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 s=e.value[i],a={},o=[];if(!C.validate(s,ly,a,o)){var l=Error("Cannot read SafeBag.");throw l.errors=o,l}var c={type:C.derToOid(a.bagId),attributes:hy(a.bagAttributes)};r.push(c);var u,d,p=a.bagValue.value[0];switch(c.type){case Ee.oids.pkcs8ShroudedKeyBag:if(p=Ee.decryptPrivateKeyInfo(p,n),p===null)throw Error("Unable to decrypt PKCS#8 ShroudedKeyBag, wrong password?");case Ee.oids.keyBag:try{c.key=Ee.privateKeyFromAsn1(p)}catch(f){c.key=null,c.asn1=p}continue;case Ee.oids.certBag:u=uy,d=function(){if(C.derToOid(a.certId)!==Ee.oids.x509Certificate){var f=Error("Unsupported certificate type, only X.509 supported.");throw f.oid=C.derToOid(a.certId),f}var v=C.fromDer(a.cert,t);try{c.cert=Ee.certificateFromAsn1(v,!0)}catch(x){c.cert=null,c.asn1=v}};break;default:var l=Error("Unsupported PKCS#12 SafeBag type.");throw l.oid=c.type,l}if(u!==void 0&&!C.validate(p,u,a,o)){var l=Error("Cannot read PKCS#12 "+u.name);throw l.errors=o,l}d()}return r}function hy(e){var t={};if(e!==void 0)for(var n=0;n<e.length;++n){var r={},i=[];if(!C.validate(e[n],cy,r,i)){var s=Error("Cannot read PKCS#12 BagAttribute.");throw s.errors=i,s}var a=C.derToOid(r.oid);if(Ee.oids[a]===void 0)continue;t[Ee.oids[a]]=[];for(var o=0;o<r.values.length;++o)t[Ee.oids[a]].push(r.values[o].value)}return t}Ti.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,s;if(i!==null)i=Ke.util.hexToBytes(i);else if(r.generateLocalKeyId)if(t){var a=Ke.util.isArray(t)?t[0]:t;if(typeof a==="string")a=Ee.certificateFromPem(a);var o=Ke.md.sha1.create();o.update(C.toDer(Ee.certificateToAsn1(a)).getBytes()),i=o.digest().getBytes()}else i=Ke.random.getBytes(20);var l=[];if(i!==null)l.push(C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,[C.create(C.Class.UNIVERSAL,C.Type.OID,!1,C.oidToDer(Ee.oids.localKeyId).getBytes()),C.create(C.Class.UNIVERSAL,C.Type.SET,!0,[C.create(C.Class.UNIVERSAL,C.Type.OCTETSTRING,!1,i)])]));if("friendlyName"in r)l.push(C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,[C.create(C.Class.UNIVERSAL,C.Type.OID,!1,C.oidToDer(Ee.oids.friendlyName).getBytes()),C.create(C.Class.UNIVERSAL,C.Type.SET,!0,[C.create(C.Class.UNIVERSAL,C.Type.BMPSTRING,!1,r.friendlyName)])]));if(l.length>0)s=C.create(C.Class.UNIVERSAL,C.Type.SET,!0,l);var c=[],u=[];if(t!==null)if(Ke.util.isArray(t))u=t;else u=[t];var d=[];for(var p=0;p<u.length;++p){if(t=u[p],typeof t==="string")t=Ee.certificateFromPem(t);var h=p===0?s:void 0,f=Ee.certificateToAsn1(t),v=C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,[C.create(C.Class.UNIVERSAL,C.Type.OID,!1,C.oidToDer(Ee.oids.certBag).getBytes()),C.create(C.Class.CONTEXT_SPECIFIC,0,!0,[C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,[C.create(C.Class.UNIVERSAL,C.Type.OID,!1,C.oidToDer(Ee.oids.x509Certificate).getBytes()),C.create(C.Class.CONTEXT_SPECIFIC,0,!0,[C.create(C.Class.UNIVERSAL,C.Type.OCTETSTRING,!1,C.toDer(f).getBytes())])])]),h]);d.push(v)}if(d.length>0){var x=C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,d),S=C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,[C.create(C.Class.UNIVERSAL,C.Type.OID,!1,C.oidToDer(Ee.oids.data).getBytes()),C.create(C.Class.CONTEXT_SPECIFIC,0,!0,[C.create(C.Class.UNIVERSAL,C.Type.OCTETSTRING,!1,C.toDer(x).getBytes())])]);c.push(S)}var A=null;if(e!==null){var b=Ee.wrapRsaPrivateKey(Ee.privateKeyToAsn1(e));if(n===null)A=C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,[C.create(C.Class.UNIVERSAL,C.Type.OID,!1,C.oidToDer(Ee.oids.keyBag).getBytes()),C.create(C.Class.CONTEXT_SPECIFIC,0,!0,[b]),s]);else A=C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,[C.create(C.Class.UNIVERSAL,C.Type.OID,!1,C.oidToDer(Ee.oids.pkcs8ShroudedKeyBag).getBytes()),C.create(C.Class.CONTEXT_SPECIFIC,0,!0,[Ee.encryptPrivateKeyInfo(b,n,r)]),s]);var k=C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,[A]),R=C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,[C.create(C.Class.UNIVERSAL,C.Type.OID,!1,C.oidToDer(Ee.oids.data).getBytes()),C.create(C.Class.CONTEXT_SPECIFIC,0,!0,[C.create(C.Class.UNIVERSAL,C.Type.OCTETSTRING,!1,C.toDer(k).getBytes())])]);c.push(R)}var I=C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,c),V;if(r.useMac){var o=Ke.md.sha1.create(),J=new Ke.util.ByteBuffer(Ke.random.getBytes(r.saltSize)),D=r.count,e=Ti.generateKey(n,J,3,D,20),W=Ke.hmac.create();W.start(o,e),W.update(C.toDer(I).getBytes());var Z=W.getMac();V=C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,[C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,[C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,[C.create(C.Class.UNIVERSAL,C.Type.OID,!1,C.oidToDer(Ee.oids.sha1).getBytes()),C.create(C.Class.UNIVERSAL,C.Type.NULL,!1,"")]),C.create(C.Class.UNIVERSAL,C.Type.OCTETSTRING,!1,Z.getBytes())]),C.create(C.Class.UNIVERSAL,C.Type.OCTETSTRING,!1,J.getBytes()),C.create(C.Class.UNIVERSAL,C.Type.INTEGER,!1,C.integerToDer(D).getBytes())])}return C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,[C.create(C.Class.UNIVERSAL,C.Type.INTEGER,!1,C.integerToDer(3).getBytes()),C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,[C.create(C.Class.UNIVERSAL,C.Type.OID,!1,C.oidToDer(Ee.oids.data).getBytes()),C.create(C.Class.CONTEXT_SPECIFIC,0,!0,[C.create(C.Class.UNIVERSAL,C.Type.OCTETSTRING,!1,C.toDer(I).getBytes())])]),V])};Ti.generateKey=Ke.pbe.generatePkcs12Key});var $o=de(function(L1,md){var Mr=ve();Gt();Or();Do();sn();Fs();Fo();Gs();wi();Pe();Xs();var Mo=Mr.asn1,Dn=md.exports=Mr.pki=Mr.pki||{};Dn.pemToDer=function(e){var t=Mr.pem.decode(e)[0];if(t.procType&&t.procType.type==="ENCRYPTED")throw Error("Could not convert PEM to DER; PEM is encrypted.");return Mr.util.createBuffer(t.body)};Dn.privateKeyFromPem=function(e){var t=Mr.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=Mo.fromDer(t.body);return Dn.privateKeyFromAsn1(r)};Dn.privateKeyToPem=function(e,t){var n={type:"RSA PRIVATE KEY",body:Mo.toDer(Dn.privateKeyToAsn1(e)).getBytes()};return Mr.pem.encode(n,{maxline:t})};Dn.privateKeyInfoToPem=function(e,t){var n={type:"PRIVATE KEY",body:Mo.toDer(e).getBytes()};return Mr.pem.encode(n,{maxline:t})}});var jo=de(function(O1,Ed){var O=ve();Gt();An();Ls();sn();$o();Lt();Rn();Pe();var Js=function(e,t,n,r){var i=O.util.createBuffer(),s=e.length>>1,a=s+(e.length&1),o=e.substr(0,a),l=e.substr(s,a),c=O.util.createBuffer(),u=O.hmac.create();n=t+n;var d=Math.ceil(r/16),p=Math.ceil(r/20);u.start("MD5",o);var h=O.util.createBuffer();c.putBytes(n);for(var f=0;f<d;++f)u.start(null,null),u.update(c.getBytes()),c.putBuffer(u.digest()),u.start(null,null),u.update(c.bytes()+n),h.putBuffer(u.digest());u.start("SHA1",l);var v=O.util.createBuffer();c.clear(),c.putBytes(n);for(var f=0;f<p;++f)u.start(null,null),u.update(c.getBytes()),c.putBuffer(u.digest()),u.start(null,null),u.update(c.bytes()+n),v.putBuffer(u.digest());return i.putBytes(O.util.xorBytes(h.getBytes(),v.getBytes(),r)),i},gy=function(e,t,n){var r=O.hmac.create();r.start("SHA1",e);var i=O.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()},my=function(e,t,n){var r=!1;try{var i=e.deflate(t.fragment.getBytes());t.fragment=O.util.createBuffer(i),t.length=i.length,r=!0}catch(s){}return r},yy=function(e,t,n){var r=!1;try{var i=e.inflate(t.fragment.getBytes());t.fragment=O.util.createBuffer(i),t.length=i.length,r=!0}catch(s){}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 O.util.createBuffer(e.getBytes(n))},Ft=function(e,t,n){e.putInt(n.length(),t<<3),e.putBuffer(n)},y={};y.Versions={TLS_1_0:{major:3,minor:1},TLS_1_1:{major:3,minor:2},TLS_1_2:{major:3,minor:3}};y.SupportedVersions=[y.Versions.TLS_1_1,y.Versions.TLS_1_0];y.Version=y.SupportedVersions[0];y.MaxFragment=15360;y.ConnectionEnd={server:0,client:1};y.PRFAlgorithm={tls_prf_sha256:0};y.BulkCipherAlgorithm={none:null,rc4:0,des3:1,aes:2};y.CipherType={stream:0,block:1,aead:2};y.MACAlgorithm={none:null,hmac_md5:0,hmac_sha1:1,hmac_sha256:2,hmac_sha384:3,hmac_sha512:4};y.CompressionMethod={none:0,deflate:1};y.ContentType={change_cipher_spec:20,alert:21,handshake:22,application_data:23,heartbeat:24};y.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};y.Alert={};y.Alert.Level={warning:1,fatal:2};y.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};y.HeartbeatMessageType={heartbeat_request:1,heartbeat_response:2};y.CipherSuites={};y.getCipherSuite=function(e){var t=null;for(var n in y.CipherSuites){var r=y.CipherSuites[n];if(r.id[0]===e.charCodeAt(0)&&r.id[1]===e.charCodeAt(1)){t=r;break}}return t};y.handleUnexpected=function(e,t){var n=!e.open&&e.entity===y.ConnectionEnd.client;if(!n)e.error(e,{message:"Unexpected message. Received TLS record out of order.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.unexpected_message}})};y.handleHelloRequest=function(e,t,n){if(!e.handshaking&&e.handshakes>0)y.queue(e,y.createAlert(e,{level:y.Alert.Level.warning,description:y.Alert.Description.no_renegotiation})),y.flush(e);e.process()};y.parseHelloMessage=function(e,t,n){var r=null,i=e.entity===y.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:y.Alert.Level.fatal,description:y.Alert.Description.illegal_parameter}});else{var s=t.fragment,a=s.length();if(r={version:{major:s.getByte(),minor:s.getByte()},random:O.util.createBuffer(s.getBytes(32)),session_id:Rt(s,1),extensions:[]},i)r.cipher_suite=s.getBytes(2),r.compression_method=s.getByte();else r.cipher_suites=Rt(s,2),r.compression_methods=Rt(s,1);if(a=n-(a-s.length()),a>0){var o=Rt(s,2);while(o.length()>0)r.extensions.push({type:[o.getByte(),o.getByte()],data:Rt(o,2)});if(!i)for(var l=0;l<r.extensions.length;++l){var c=r.extensions[l];if(c.type[0]===0&&c.type[1]===0){var u=Rt(c.data,2);while(u.length()>0){var d=u.getByte();if(d!==0)break;e.session.extensions.server_name.serverNameList.push(Rt(u,2).getBytes())}}}}if(e.session.version){if(r.version.major!==e.session.version.major||r.version.minor!==e.session.version.minor)return e.error(e,{message:"TLS version change is disallowed during renegotiation.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.protocol_version}})}if(i)e.session.cipherSuite=y.getCipherSuite(r.cipher_suite);else{var p=O.util.createBuffer(r.cipher_suites.bytes());while(p.length()>0)if(e.session.cipherSuite=y.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:y.Alert.Level.fatal,description:y.Alert.Description.handshake_failure},cipherSuite:O.util.bytesToHex(r.cipher_suite)});if(i)e.session.compressionMethod=r.compression_method;else e.session.compressionMethod=y.CompressionMethod.none}return r};y.createSecurityParameters=function(e,t){var n=e.entity===y.ConnectionEnd.client,r=t.random.bytes(),i=n?e.session.sp.client_random:r,s=n?r:y.createRandom().getBytes();e.session.sp={entity:e.entity,prf_algorithm:y.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:s}};y.handleServerHello=function(e,t,n){var r=y.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:y.Alert.Level.fatal,description:y.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=xd,e.session.resuming=!0,e.session.sp.server_random=r.random.bytes();else e.expect=xy,e.session.resuming=!1,y.createSecurityParameters(e,r);e.session.id=i,e.process()};y.handleClientHello=function(e,t,n){var r=y.parseHelloMessage(e,t,n);if(e.fail)return;var i=r.session_id.bytes(),s=null;if(e.sessionCache){if(s=e.sessionCache.getSession(i),s===null)i="";else if(s.version.major!==r.version.major||s.version.minor>r.version.minor)s=null,i=""}if(i.length===0)i=O.random.getBytes(32);if(e.session.id=i,e.session.clientHelloVersion=r.version,e.session.sp={},s)e.version=e.session.version=s.version,e.session.sp=s.sp;else{var a;for(var o=1;o<y.SupportedVersions.length;++o)if(a=y.SupportedVersions[o],a.minor<=r.version.minor)break;e.version={major:a.major,minor:a.minor},e.session.version=e.version}if(s!==null)e.expect=qo,e.session.resuming=!0,e.session.sp.client_random=r.random.bytes();else e.expect=e.verifyClient!==!1?Ay:Ko,e.session.resuming=!1,y.createSecurityParameters(e,r);if(e.open=!0,y.queue(e,y.createRecord(e,{type:y.ContentType.handshake,data:y.createServerHello(e)})),e.session.resuming)y.queue(e,y.createRecord(e,{type:y.ContentType.change_cipher_spec,data:y.createChangeCipherSpec()})),e.state.pending=y.createConnectionState(e),e.state.current.write=e.state.pending.write,y.queue(e,y.createRecord(e,{type:y.ContentType.handshake,data:y.createFinished(e)}));else if(y.queue(e,y.createRecord(e,{type:y.ContentType.handshake,data:y.createCertificate(e)})),!e.fail){if(y.queue(e,y.createRecord(e,{type:y.ContentType.handshake,data:y.createServerKeyExchange(e)})),e.verifyClient!==!1)y.queue(e,y.createRecord(e,{type:y.ContentType.handshake,data:y.createCertificateRequest(e)}));y.queue(e,y.createRecord(e,{type:y.ContentType.handshake,data:y.createServerHelloDone(e)}))}y.flush(e),e.process()};y.handleCertificate=function(e,t,n){if(n<3)return e.error(e,{message:"Invalid Certificate message. Message too short.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.illegal_parameter}});var r=t.fragment,i={certificate_list:Rt(r,3)},s,a,o=[];try{while(i.certificate_list.length()>0)s=Rt(i.certificate_list,3),a=O.asn1.fromDer(s),s=O.pki.certificateFromAsn1(a,!0),o.push(s)}catch(c){return e.error(e,{message:"Could not parse certificate list.",cause:c,send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.bad_certificate}})}var l=e.entity===y.ConnectionEnd.client;if((l||e.verifyClient===!0)&&o.length===0)e.error(e,{message:l?"No server certificate provided.":"No client certificate provided.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.illegal_parameter}});else if(o.length===0)e.expect=l?yd:Ko;else{if(l)e.session.serverCertificate=o[0];else e.session.clientCertificate=o[0];if(y.verifyCertificateChain(e,o))e.expect=l?yd:Ko}e.process()};y.handleServerKeyExchange=function(e,t,n){if(n>0)return e.error(e,{message:"Invalid key parameters. Only RSA is supported.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.unsupported_certificate}});e.expect=Sy,e.process()};y.handleClientKeyExchange=function(e,t,n){if(n<48)return e.error(e,{message:"Invalid key parameters. Only RSA is supported.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.unsupported_certificate}});var r=t.fragment,i={enc_pre_master_secret:Rt(r,2).getBytes()},s=null;if(e.getPrivateKey)try{s=e.getPrivateKey(e,e.session.serverCertificate),s=O.pki.privateKeyFromPem(s)}catch(l){e.error(e,{message:"Could not get private key.",cause:l,send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.internal_error}})}if(s===null)return e.error(e,{message:"No private key set.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.internal_error}});try{var a=e.session.sp;a.pre_master_secret=s.decrypt(i.enc_pre_master_secret);var o=e.session.clientHelloVersion;if(o.major!==a.pre_master_secret.charCodeAt(0)||o.minor!==a.pre_master_secret.charCodeAt(1))throw Error("TLS version rollback attack detected.")}catch(l){a.pre_master_secret=O.random.getBytes(48)}if(e.expect=qo,e.session.clientCertificate!==null)e.expect=_y;e.process()};y.handleCertificateRequest=function(e,t,n){if(n<3)return e.error(e,{message:"Invalid CertificateRequest. Message too short.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.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=by,e.process()};y.handleCertificateVerify=function(e,t,n){if(n<2)return e.error(e,{message:"Invalid CertificateVerify. Message too short.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.illegal_parameter}});var r=t.fragment;r.read-=4;var i=r.bytes();r.read+=4;var s={signature:Rt(r,2).getBytes()},a=O.util.createBuffer();a.putBuffer(e.session.md5.digest()),a.putBuffer(e.session.sha1.digest()),a=a.getBytes();try{var o=e.session.clientCertificate;if(!o.publicKey.verify(a,s.signature,"NONE"))throw Error("CertificateVerify signature does not match.");e.session.md5.update(i),e.session.sha1.update(i)}catch(l){return e.error(e,{message:"Bad signature in CertificateVerify.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.handshake_failure}})}e.expect=qo,e.process()};y.handleServerHelloDone=function(e,t,n){if(n>0)return e.error(e,{message:"Invalid ServerHelloDone message. Invalid length.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.record_overflow}});if(e.session.serverCertificate===null){var r={message:"No server certificate provided. Not enough security.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.insufficient_security}},i=0,s=e.verify(e,r.alert.description,i,[]);if(s!==!0){if(s||s===0){if(typeof s==="object"&&!O.util.isArray(s)){if(s.message)r.message=s.message;if(s.alert)r.alert.description=s.alert}else if(typeof s==="number")r.alert.description=s}}return e.error(e,r)}if(e.session.certificateRequest!==null)t=y.createRecord(e,{type:y.ContentType.handshake,data:y.createCertificate(e)}),y.queue(e,t);t=y.createRecord(e,{type:y.ContentType.handshake,data:y.createClientKeyExchange(e)}),y.queue(e,t),e.expect=Ey;var a=function(o,l){if(o.session.certificateRequest!==null&&o.session.clientCertificate!==null)y.queue(o,y.createRecord(o,{type:y.ContentType.handshake,data:y.createCertificateVerify(o,l)}));y.queue(o,y.createRecord(o,{type:y.ContentType.change_cipher_spec,data:y.createChangeCipherSpec()})),o.state.pending=y.createConnectionState(o),o.state.current.write=o.state.pending.write,y.queue(o,y.createRecord(o,{type:y.ContentType.handshake,data:y.createFinished(o)})),o.expect=xd,y.flush(o),o.process()};if(e.session.certificateRequest===null||e.session.clientCertificate===null)return a(e,null);y.getClientSignature(e,a)};y.handleChangeCipherSpec=function(e,t){if(t.fragment.getByte()!==1)return e.error(e,{message:"Invalid ChangeCipherSpec message received.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.illegal_parameter}});var n=e.entity===y.ConnectionEnd.client;if(e.session.resuming&&n||!e.session.resuming&&!n)e.state.pending=y.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?Cy:ky,e.process()};y.handleFinished=function(e,t,n){var r=t.fragment;r.read-=4;var i=r.bytes();r.read+=4;var s=t.fragment.getBytes();r=O.util.createBuffer(),r.putBuffer(e.session.md5.digest()),r.putBuffer(e.session.sha1.digest());var a=e.entity===y.ConnectionEnd.client,o=a?"server finished":"client finished",l=e.session.sp,c=12,u=Js;if(r=u(l.master_secret,o,r.getBytes(),c),r.getBytes()!==s)return e.error(e,{message:"Invalid verify_data in Finished message.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.decrypt_error}});if(e.session.md5.update(i),e.session.sha1.update(i),e.session.resuming&&a||!e.session.resuming&&!a)y.queue(e,y.createRecord(e,{type:y.ContentType.change_cipher_spec,data:y.createChangeCipherSpec()})),e.state.current.write=e.state.pending.write,e.state.pending=null,y.queue(e,y.createRecord(e,{type:y.ContentType.handshake,data:y.createFinished(e)}));e.expect=a?wy:Iy,e.handshaking=!1,++e.handshakes,e.peerCertificate=a?e.session.serverCertificate:e.session.clientCertificate,y.flush(e),e.isConnected=!0,e.connected(e),e.process()};y.handleAlert=function(e,t){var n=t.fragment,r={level:n.getByte(),description:n.getByte()},i;switch(r.description){case y.Alert.Description.close_notify:i="Connection closed.";break;case y.Alert.Description.unexpected_message:i="Unexpected message.";break;case y.Alert.Description.bad_record_mac:i="Bad record MAC.";break;case y.Alert.Description.decryption_failed:i="Decryption failed.";break;case y.Alert.Description.record_overflow:i="Record overflow.";break;case y.Alert.Description.decompression_failure:i="Decompression failed.";break;case y.Alert.Description.handshake_failure:i="Handshake failure.";break;case y.Alert.Description.bad_certificate:i="Bad certificate.";break;case y.Alert.Description.unsupported_certificate:i="Unsupported certificate.";break;case y.Alert.Description.certificate_revoked:i="Certificate revoked.";break;case y.Alert.Description.certificate_expired:i="Certificate expired.";break;case y.Alert.Description.certificate_unknown:i="Certificate unknown.";break;case y.Alert.Description.illegal_parameter:i="Illegal parameter.";break;case y.Alert.Description.unknown_ca:i="Unknown certificate authority.";break;case y.Alert.Description.access_denied:i="Access denied.";break;case y.Alert.Description.decode_error:i="Decode error.";break;case y.Alert.Description.decrypt_error:i="Decrypt error.";break;case y.Alert.Description.export_restriction:i="Export restriction.";break;case y.Alert.Description.protocol_version:i="Unsupported protocol version.";break;case y.Alert.Description.insufficient_security:i="Insufficient security.";break;case y.Alert.Description.internal_error:i="Internal error.";break;case y.Alert.Description.user_canceled:i="User canceled.";break;case y.Alert.Description.no_renegotiation:i="Renegotiation not supported.";break;default:i="Unknown error.";break}if(r.description===y.Alert.Description.close_notify)return e.close();e.error(e,{message:i,send:!1,origin:e.entity===y.ConnectionEnd.client?"server":"client",alert:r}),e.process()};y.handleHandshake=function(e,t){var n=t.fragment,r=n.getByte(),i=n.getInt24();if(i>n.length())return e.fragmented=t,t.fragment=O.util.createBuffer(),n.read-=4,e.process();e.fragmented=null,n.read-=4;var s=n.bytes(i+4);if(n.read+=4,r in Ys[e.entity][e.expect]){if(e.entity===y.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:O.md.md5.create(),sha1:O.md.sha1.create()};if(r!==y.HandshakeType.hello_request&&r!==y.HandshakeType.certificate_verify&&r!==y.HandshakeType.finished)e.session.md5.update(s),e.session.sha1.update(s);Ys[e.entity][e.expect][r](e,t,i)}else y.handleUnexpected(e,t)};y.handleApplicationData=function(e,t){e.data.putBuffer(t.fragment),e.dataReady(e),e.process()};y.handleHeartbeat=function(e,t){var n=t.fragment,r=n.getByte(),i=n.getInt16(),s=n.getBytes(i);if(r===y.HeartbeatMessageType.heartbeat_request){if(e.handshakes===0||e.handshaking||i>s.length)return e.process();y.queue(e,y.createRecord(e,{type:y.ContentType.heartbeat,data:y.createHeartbeat(y.HeartbeatMessageType.heartbeat_response,s)})),y.flush(e)}else if(r===y.HeartbeatMessageType.heartbeat_response){if(s!==e.expectedHeartbeatPayload)return e.process();if(e.heartbeatReceived)e.heartbeatReceived(e,O.util.createBuffer(s))}e.process()};var vy=0,xy=1,yd=2,Sy=3,by=4,xd=5,Cy=6,wy=7,Ey=8,Ty=0,Ay=1,Ko=2,_y=3,qo=4,ky=5,Iy=6,{handleUnexpected:m,handleChangeCipherSpec:Sd,handleAlert:gt,handleHandshake:wt,handleApplicationData:bd,handleHeartbeat:mt}=y,Go=[];Go[y.ConnectionEnd.client]=[[m,gt,wt,m,mt],[m,gt,wt,m,mt],[m,gt,wt,m,mt],[m,gt,wt,m,mt],[m,gt,wt,m,mt],[Sd,gt,m,m,mt],[m,gt,wt,m,mt],[m,gt,wt,bd,mt],[m,gt,wt,m,mt]];Go[y.ConnectionEnd.server]=[[m,gt,wt,m,mt],[m,gt,wt,m,mt],[m,gt,wt,m,mt],[m,gt,wt,m,mt],[Sd,gt,m,m,mt],[m,gt,wt,m,mt],[m,gt,wt,bd,mt],[m,gt,wt,m,mt]];var{handleHelloRequest:$r,handleServerHello:Ry,handleCertificate:Cd,handleServerKeyExchange:vd,handleCertificateRequest:Wo,handleServerHelloDone:Qs,handleFinished:wd}=y,Ys=[];Ys[y.ConnectionEnd.client]=[[m,m,Ry,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m],[$r,m,m,m,m,m,m,m,m,m,m,Cd,vd,Wo,Qs,m,m,m,m,m,m],[$r,m,m,m,m,m,m,m,m,m,m,m,vd,Wo,Qs,m,m,m,m,m,m],[$r,m,m,m,m,m,m,m,m,m,m,m,m,Wo,Qs,m,m,m,m,m,m],[$r,m,m,m,m,m,m,m,m,m,m,m,m,m,Qs,m,m,m,m,m,m],[$r,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m],[$r,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,wd],[$r,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m],[$r,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m]];var{handleClientHello:By,handleClientKeyExchange:Py,handleCertificateVerify:Ny}=y;Ys[y.ConnectionEnd.server]=[[m,By,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m],[m,m,m,m,m,m,m,m,m,m,m,Cd,m,m,m,m,m,m,m,m,m],[m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,Py,m,m,m,m],[m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,Ny,m,m,m,m,m],[m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m],[m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,wd],[m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m],[m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m]];y.generateKeys=function(e,t){var n=Js,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,s=e.version.major===y.Versions.TLS_1_0.major&&e.version.minor===y.Versions.TLS_1_0.minor;if(s)i+=2*t.fixed_iv_length;var a=n(t.master_secret,"key expansion",r,i),o={client_write_MAC_key:a.getBytes(t.mac_key_length),server_write_MAC_key:a.getBytes(t.mac_key_length),client_write_key:a.getBytes(t.enc_key_length),server_write_key:a.getBytes(t.enc_key_length)};if(s)o.client_write_IV=a.getBytes(t.fixed_iv_length),o.server_write_IV=a.getBytes(t.fixed_iv_length);return o};y.createConnectionState=function(e){var t=e.entity===y.ConnectionEnd.client,n=function(){var s={sequenceNumber:[0,0],macKey:null,macLength:0,macFunction:null,cipherState:null,cipherFunction:function(a){return!0},compressionState:null,compressFunction:function(a){return!0},updateSequenceNumber:function(){if(s.sequenceNumber[1]===4294967295)s.sequenceNumber[1]=0,++s.sequenceNumber[0];else++s.sequenceNumber[1]}};return s},r={read:n(),write:n()};if(r.read.update=function(s,a){if(!r.read.cipherFunction(a,r.read))s.error(s,{message:"Could not decrypt record or bad MAC.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.bad_record_mac}});else if(!r.read.compressFunction(s,a,r.read))s.error(s,{message:"Could not decompress record.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.decompression_failure}});return!s.fail},r.write.update=function(s,a){if(!r.write.compressFunction(s,a,r.write))s.error(s,{message:"Could not compress record.",send:!1,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.internal_error}});else if(!r.write.cipherFunction(a,r.write))s.error(s,{message:"Could not encrypt record.",send:!1,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.internal_error}});return!s.fail},e.session){var i=e.session.sp;switch(e.session.cipherSuite.initSecurityParameters(i),i.keys=y.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 y.CompressionMethod.none:break;case y.CompressionMethod.deflate:r.read.compressFunction=yy,r.write.compressFunction=my;break;default:throw Error("Unsupported compression algorithm.")}}return r};y.createRandom=function(){var e=new Date,t=+e+e.getTimezoneOffset()*60000,n=O.util.createBuffer();return n.putInt32(t),n.putBytes(O.random.getBytes(28)),n};y.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};y.createAlert=function(e,t){var n=O.util.createBuffer();return n.putByte(t.level),n.putByte(t.description),y.createRecord(e,{type:y.ContentType.alert,data:n})};y.createClientHello=function(e){e.session.clientHelloVersion={major:e.version.major,minor:e.version.minor};var t=O.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(),s=O.util.createBuffer();s.putByte(y.CompressionMethod.none);var a=s.length(),o=O.util.createBuffer();if(e.virtualHost){var l=O.util.createBuffer();l.putByte(0),l.putByte(0);var c=O.util.createBuffer();c.putByte(0),Ft(c,2,O.util.createBuffer(e.virtualHost));var u=O.util.createBuffer();Ft(u,2,c),Ft(l,2,u),o.putBuffer(l)}var d=o.length();if(d>0)d+=2;var p=e.session.id,h=p.length+1+2+4+28+2+i+1+a+d,f=O.util.createBuffer();if(f.putByte(y.HandshakeType.client_hello),f.putInt24(h),f.putByte(e.version.major),f.putByte(e.version.minor),f.putBytes(e.session.sp.client_random),Ft(f,1,O.util.createBuffer(p)),Ft(f,2,t),Ft(f,1,s),d>0)Ft(f,2,o);return f};y.createServerHello=function(e){var t=e.session.id,n=t.length+1+2+4+28+2+1,r=O.util.createBuffer();return r.putByte(y.HandshakeType.server_hello),r.putInt24(n),r.putByte(e.version.major),r.putByte(e.version.minor),r.putBytes(e.session.sp.server_random),Ft(r,1,O.util.createBuffer(t)),r.putByte(e.session.cipherSuite.id[0]),r.putByte(e.session.cipherSuite.id[1]),r.putByte(e.session.compressionMethod),r};y.createCertificate=function(e){var t=e.entity===y.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=O.util.createBuffer();if(n!==null)try{if(!O.util.isArray(n))n=[n];var s=null;for(var a=0;a<n.length;++a){var o=O.pem.decode(n[a])[0];if(o.type!=="CERTIFICATE"&&o.type!=="X509 CERTIFICATE"&&o.type!=="TRUSTED CERTIFICATE"){var l=Error('Could not convert certificate from PEM; PEM header type is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".');throw l.headerType=o.type,l}if(o.procType&&o.procType.type==="ENCRYPTED")throw Error("Could not convert certificate from PEM; PEM is encrypted.");var c=O.util.createBuffer(o.body);if(s===null)s=O.asn1.fromDer(c.bytes(),!1);var u=O.util.createBuffer();Ft(u,3,c),i.putBuffer(u)}if(n=O.pki.certificateFromAsn1(s),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:y.Alert.Level.fatal,description:y.Alert.Description.bad_certificate}})}var d=3+i.length(),p=O.util.createBuffer();return p.putByte(y.HandshakeType.certificate),p.putInt24(d),Ft(p,3,i),p};y.createClientKeyExchange=function(e){var t=O.util.createBuffer();t.putByte(e.session.clientHelloVersion.major),t.putByte(e.session.clientHelloVersion.minor),t.putBytes(O.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,s=O.util.createBuffer();return s.putByte(y.HandshakeType.client_key_exchange),s.putInt24(i),s.putInt16(t.length),s.putBytes(t),s};y.createServerKeyExchange=function(e){var t=0,n=O.util.createBuffer();if(t>0)n.putByte(y.HandshakeType.server_key_exchange),n.putInt24(t);return n};y.getClientSignature=function(e,t){var n=O.util.createBuffer();n.putBuffer(e.session.md5.digest()),n.putBuffer(e.session.sha1.digest()),n=n.getBytes(),e.getSignature=e.getSignature||function(r,i,s){var a=null;if(r.getPrivateKey)try{a=r.getPrivateKey(r,r.session.clientCertificate),a=O.pki.privateKeyFromPem(a)}catch(o){r.error(r,{message:"Could not get private key.",cause:o,send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.internal_error}})}if(a===null)r.error(r,{message:"No private key set.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.internal_error}});else i=a.sign(i,null);s(r,i)},e.getSignature(e,n,t)};y.createCertificateVerify=function(e,t){var n=t.length+2,r=O.util.createBuffer();return r.putByte(y.HandshakeType.certificate_verify),r.putInt24(n),r.putInt16(t.length),r.putBytes(t),r};y.createCertificateRequest=function(e){var t=O.util.createBuffer();t.putByte(1);var n=O.util.createBuffer();for(var r in e.caStore.certs){var i=e.caStore.certs[r],s=O.pki.distinguishedNameToAsn1(i.subject),a=O.asn1.toDer(s);n.putInt16(a.length()),n.putBuffer(a)}var o=1+t.length()+2+n.length(),l=O.util.createBuffer();return l.putByte(y.HandshakeType.certificate_request),l.putInt24(o),Ft(l,1,t),Ft(l,2,n),l};y.createServerHelloDone=function(e){var t=O.util.createBuffer();return t.putByte(y.HandshakeType.server_hello_done),t.putInt24(0),t};y.createChangeCipherSpec=function(){var e=O.util.createBuffer();return e.putByte(1),e};y.createFinished=function(e){var t=O.util.createBuffer();t.putBuffer(e.session.md5.digest()),t.putBuffer(e.session.sha1.digest());var n=e.entity===y.ConnectionEnd.client,r=e.session.sp,i=12,s=Js,a=n?"client finished":"server finished";t=s(r.master_secret,a,t.getBytes(),i);var o=O.util.createBuffer();return o.putByte(y.HandshakeType.finished),o.putInt24(t.length()),o.putBuffer(t),o};y.createHeartbeat=function(e,t,n){if(typeof n>"u")n=t.length;var r=O.util.createBuffer();r.putByte(e),r.putInt16(n),r.putBytes(t);var i=r.length(),s=Math.max(16,i-n-3);return r.putBytes(O.random.getBytes(s)),r};y.queue=function(e,t){if(!t)return;if(t.fragment.length()===0){if(t.type===y.ContentType.handshake||t.type===y.ContentType.alert||t.type===y.ContentType.change_cipher_spec)return}if(t.type===y.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()<=y.MaxFragment)r=[t];else{r=[];var i=t.fragment.bytes();while(i.length>y.MaxFragment)r.push(y.createRecord(e,{type:t.type,data:O.util.createBuffer(i.slice(0,y.MaxFragment))})),i=i.slice(y.MaxFragment);if(i.length>0)r.push(y.createRecord(e,{type:t.type,data:O.util.createBuffer(i)}))}for(var s=0;s<r.length&&!e.fail;++s){var a=r[s],o=e.state.current.write;if(o.update(e,a))e.records.push(a)}};y.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 Ho=function(e){switch(e){case!0:return!0;case O.pki.certificateError.bad_certificate:return y.Alert.Description.bad_certificate;case O.pki.certificateError.unsupported_certificate:return y.Alert.Description.unsupported_certificate;case O.pki.certificateError.certificate_revoked:return y.Alert.Description.certificate_revoked;case O.pki.certificateError.certificate_expired:return y.Alert.Description.certificate_expired;case O.pki.certificateError.certificate_unknown:return y.Alert.Description.certificate_unknown;case O.pki.certificateError.unknown_ca:return y.Alert.Description.unknown_ca;default:return y.Alert.Description.bad_certificate}},Dy=function(e){switch(e){case!0:return!0;case y.Alert.Description.bad_certificate:return O.pki.certificateError.bad_certificate;case y.Alert.Description.unsupported_certificate:return O.pki.certificateError.unsupported_certificate;case y.Alert.Description.certificate_revoked:return O.pki.certificateError.certificate_revoked;case y.Alert.Description.certificate_expired:return O.pki.certificateError.certificate_expired;case y.Alert.Description.certificate_unknown:return O.pki.certificateError.certificate_unknown;case y.Alert.Description.unknown_ca:return O.pki.certificateError.unknown_ca;default:return O.pki.certificateError.bad_certificate}};y.verifyCertificateChain=function(e,t){try{var n={};for(var r in e.verifyOptions)n[r]=e.verifyOptions[r];n.verify=function(s,a,o){var l=Ho(s),c=e.verify(e,s,a,o);if(c!==!0){if(typeof c==="object"&&!O.util.isArray(c)){var u=Error("The application rejected the certificate.");if(u.send=!0,u.alert={level:y.Alert.Level.fatal,description:y.Alert.Description.bad_certificate},c.message)u.message=c.message;if(c.alert)u.alert.description=c.alert;throw u}if(c!==s)c=Dy(c)}return c},O.pki.verifyCertificateChain(e.caStore,t,n)}catch(s){var i=s;if(typeof i!=="object"||O.util.isArray(i))i={send:!0,alert:{level:y.Alert.Level.fatal,description:Ho(s)}};if(!("send"in i))i.send=!0;if(!("alert"in i))i.alert={level:y.Alert.Level.fatal,description:Ho(i.error)};e.error(e,i)}return!e.fail};y.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 s=null,a=null;if(i)a=O.util.bytesToHex(i);else if(n.order.length>0)a=n.order[0];if(a!==null&&a in n.cache){s=n.cache[a],delete n.cache[a];for(var o in n.order)if(n.order[o]===a){n.order.splice(o,1);break}}return s},n.setSession=function(i,s){if(n.order.length===n.capacity){var a=n.order.shift();delete n.cache[a]}var a=O.util.bytesToHex(i);n.order.push(a),n.cache[a]=s}}return n};y.createConnection=function(e){var t=null;if(e.caStore)if(O.util.isArray(e.caStore))t=O.pki.createCaStore(e.caStore);else t=e.caStore;else t=O.pki.createCaStore();var n=e.cipherSuites||null;if(n===null){n=[];for(var r in y.CipherSuites)n.push(y.CipherSuites[r])}var i=e.server?y.ConnectionEnd.server:y.ConnectionEnd.client,s=e.sessionCache?y.createSessionCache(e.sessionCache):null,a={version:{major:y.Version.major,minor:y.Version.minor},entity:i,sessionId:e.sessionId,caStore:t,sessionCache:s,cipherSuites:n,connected:e.connected,virtualHost:e.virtualHost||null,verifyClient:e.verifyClient||!1,verify:e.verify||function(h,f,v,x){return f},verifyOptions:e.verifyOptions||{},getCertificate:e.getCertificate||null,getPrivateKey:e.getPrivateKey||null,getSignature:e.getSignature||null,input:O.util.createBuffer(),tlsData:O.util.createBuffer(),data:O.util.createBuffer(),tlsDataReady:e.tlsDataReady,dataReady:e.dataReady,heartbeatReceived:e.heartbeatReceived,closed:e.closed,error:function(h,f){if(f.origin=f.origin||(h.entity===y.ConnectionEnd.client?"client":"server"),f.send)y.queue(h,y.createAlert(h,f.alert)),y.flush(h);var v=f.fatal!==!1;if(v)h.fail=!0;if(e.error(h,f),v)h.close(!1)},deflate:e.deflate||null,inflate:e.inflate||null};a.reset=function(h){a.version={major:y.Version.major,minor:y.Version.minor},a.record=null,a.session=null,a.peerCertificate=null,a.state={pending:null,current:null},a.expect=a.entity===y.ConnectionEnd.client?vy:Ty,a.fragmented=null,a.records=[],a.open=!1,a.handshakes=0,a.handshaking=!1,a.isConnected=!1,a.fail=!(h||typeof h>"u"),a.input.clear(),a.tlsData.clear(),a.data.clear(),a.state.current=y.createConnectionState(a)},a.reset();var o=function(h,f){var v=f.type-y.ContentType.change_cipher_spec,x=Go[h.entity][h.expect];if(v in x)x[v](h,f);else y.handleUnexpected(h,f)},l=function(h){var f=0,v=h.input,x=v.length();if(x<5)f=5-x;else{h.record={type:v.getByte(),version:{major:v.getByte(),minor:v.getByte()},length:v.getInt16(),fragment:O.util.createBuffer(),ready:!1};var S=h.record.version.major===h.version.major;if(S&&h.session&&h.session.version)S=h.record.version.minor===h.version.minor;if(!S)h.error(h,{message:"Incompatible TLS version.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.protocol_version}})}return f},c=function(h){var f=0,v=h.input,x=v.length();if(x<h.record.length)f=h.record.length-x;else{h.record.fragment.putBytes(v.getBytes(h.record.length)),v.compact();var S=h.state.current.read;if(S.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:y.Alert.Level.fatal,description:y.Alert.Description.unexpected_message}}),f;h.record.ready=!0}}return f};a.handshake=function(h){if(a.entity!==y.ConnectionEnd.client)a.error(a,{message:"Cannot initiate handshake as a server.",fatal:!1});else if(a.handshaking)a.error(a,{message:"Handshake already in progress.",fatal:!1});else{if(a.fail&&!a.open&&a.handshakes===0)a.fail=!1;a.handshaking=!0,h=h||"";var f=null;if(h.length>0){if(a.sessionCache)f=a.sessionCache.getSession(h);if(f===null)h=""}if(h.length===0&&a.sessionCache){if(f=a.sessionCache.getSession(),f!==null)h=f.id}if(a.session={id:h,version:null,cipherSuite:null,compressionMethod:null,serverCertificate:null,certificateRequest:null,clientCertificate:null,sp:{},md5:O.md.md5.create(),sha1:O.md.sha1.create()},f)a.version=f.version,a.session.sp=f.sp;a.session.sp.client_random=y.createRandom().getBytes(),a.open=!0,y.queue(a,y.createRecord(a,{type:y.ContentType.handshake,data:y.createClientHello(a)})),y.flush(a)}};var u=!1,d=!1,p=function(h){var f=0;if(!h.fail){if(h.record!==null&&h.record.ready&&h.record.fragment.isEmpty())h.record=null;if(h.record===null)f=l(h);if(!h.fail&&h.record!==null&&!h.record.ready)f=c(h);if(!h.fail&&h.record!==null&&h.record.ready)o(h,h.record)}return f};return a.process=function(h){var f=0;if(h)a.input.putBytes(h);if(u&&typeof h>"u")return d=!0,f;var v=u,x=d;u=!0,d=!1;try{f=p(a);while(d)d=!1,p(a)}finally{u=v,d=x}return f},a.prepare=function(h){return y.queue(a,y.createRecord(a,{type:y.ContentType.application_data,data:O.util.createBuffer(h)})),y.flush(a)},a.prepareHeartbeatRequest=function(h,f){if(h instanceof O.util.ByteBuffer)h=h.bytes();if(typeof f>"u")f=h.length;return a.expectedHeartbeatPayload=h,y.queue(a,y.createRecord(a,{type:y.ContentType.heartbeat,data:y.createHeartbeat(y.HeartbeatMessageType.heartbeat_request,h,f)})),y.flush(a)},a.close=function(h){if(!a.fail&&a.sessionCache&&a.session){var f={id:a.session.id,version:a.session.version,sp:a.session.sp};f.sp.keys=null,a.sessionCache.setSession(f.id,f)}if(a.open){if(a.open=!1,a.input.clear(),a.isConnected||a.handshaking)a.isConnected=a.handshaking=!1,y.queue(a,y.createAlert(a,{level:y.Alert.Level.warning,description:y.Alert.Description.close_notify})),y.flush(a);a.closed(a)}a.reset(h)},a};Ed.exports=O.tls=O.tls||{};for(Ai in y)if(typeof y[Ai]!=="function")O.tls[Ai]=y[Ai];var Ai;O.tls.prf_tls1=Js;O.tls.hmac_sha1=gy;O.tls.createSessionCache=y.createSessionCache;O.tls.createConnection=y.createConnection});var _d=de(function(U1,Ad){var Wr=ve();Lr();jo();var Mt=Ad.exports=Wr.tls;Mt.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=Mt.BulkCipherAlgorithm.aes,e.cipher_type=Mt.CipherType.block,e.enc_key_length=16,e.block_length=16,e.fixed_iv_length=16,e.record_iv_length=16,e.mac_algorithm=Mt.MACAlgorithm.hmac_sha1,e.mac_length=20,e.mac_key_length=20},initConnectionState:Td};Mt.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=Mt.BulkCipherAlgorithm.aes,e.cipher_type=Mt.CipherType.block,e.enc_key_length=32,e.block_length=16,e.fixed_iv_length=16,e.record_iv_length=16,e.mac_algorithm=Mt.MACAlgorithm.hmac_sha1,e.mac_length=20,e.mac_key_length=20},initConnectionState:Td};function Td(e,t,n){var r=t.entity===Wr.tls.ConnectionEnd.client;e.read.cipherState={init:!1,cipher:Wr.cipher.createDecipher("AES-CBC",r?n.keys.server_write_key:n.keys.client_write_key),iv:r?n.keys.server_write_IV:n.keys.client_write_IV},e.write.cipherState={init:!1,cipher:Wr.cipher.createCipher("AES-CBC",r?n.keys.client_write_key:n.keys.server_write_key),iv:r?n.keys.client_write_IV:n.keys.server_write_IV},e.read.cipherFunction=Vy,e.write.cipherFunction=Ly,e.read.macLength=e.write.macLength=n.mac_length,e.read.macFunction=e.write.macFunction=Mt.hmac_sha1}function Ly(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===Mt.Versions.TLS_1_0.minor)i=t.cipherState.init?null:t.cipherState.iv;else i=Wr.random.getBytesSync(16);t.cipherState.init=!0;var s=t.cipherState.cipher;if(s.start({iv:i}),e.version.minor>=Mt.Versions.TLS_1_1.minor)s.output.putBytes(i);if(s.update(e.fragment),s.finish(Oy))e.fragment=s.output,e.length=e.fragment.length(),n=!0;return n}function Oy(e,t,n){if(!n){var r=e-t.length()%e;t.fillWithByte(r-1,r)}return!0}function Uy(e,t,n){var r=!0;if(n){var i=t.length(),s=t.last();for(var a=i-1-s;a<i-1;++a)r=r&&t.at(a)==s;if(r)t.truncate(s+1)}return r}function Vy(e,t){var n=!1,r;if(e.version.minor===Mt.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(Uy);var s=t.macLength,a=Wr.random.getBytesSync(s),o=i.output.length();if(o>=s)e.fragment=i.output.getBytes(o-s),a=i.output.getBytes(s);else e.fragment=i.output.getBytes();e.fragment=Wr.util.createBuffer(e.fragment),e.length=e.fragment.length();var l=t.macFunction(t.macKey,t.sequenceNumber,e);return t.updateSequenceNumber(),n=Fy(t.macKey,a,l)&&n,n}function Fy(e,t,n){var r=Wr.hmac.create();return r.start("SHA1",e),r.update(t),t=r.digest().getBytes(),r.start(null,null),r.update(n),n=r.digest().getBytes(),t===n}});var Qo=de(function(V1,Bd){var Ge=ve();rr();Pe();var _i=Bd.exports=Ge.sha512=Ge.sha512||{};Ge.md.sha512=Ge.md.algorithms.sha512=_i;var Id=Ge.sha384=Ge.sha512.sha384=Ge.sha512.sha384||{};Id.create=function(){return _i.create("SHA-384")};Ge.md.sha384=Ge.md.algorithms.sha384=Id;Ge.sha512.sha256=Ge.sha512.sha256||{create:function(){return _i.create("SHA-512/256")}};Ge.md["sha512/256"]=Ge.md.algorithms["sha512/256"]=Ge.sha512.sha256;Ge.sha512.sha224=Ge.sha512.sha224||{create:function(){return _i.create("SHA-512/224")}};Ge.md["sha512/224"]=Ge.md.algorithms["sha512/224"]=Ge.sha512.sha224;_i.create=function(e){if(!Rd)My();if(typeof e>"u")e="SHA-512";if(!(e in dn))throw Error("Invalid SHA-512 algorithm: "+e);var t=dn[e],n=null,r=Ge.util.createBuffer(),i=Array(80);for(var s=0;s<80;++s)i[s]=[,,];var a=64;switch(e){case"SHA-384":a=48;break;case"SHA-512/256":a=32;break;case"SHA-512/224":a=28;break}var o={algorithm:e.replace("-","").toLowerCase(),blockLength:128,digestLength:a,messageLength:0,fullMessageLength:null,messageLengthSize:16};return o.start=function(){o.messageLength=0,o.fullMessageLength=o.messageLength128=[];var l=o.messageLengthSize/4;for(var c=0;c<l;++c)o.fullMessageLength.push(0);r=Ge.util.createBuffer(),n=Array(t.length);for(var c=0;c<t.length;++c)n[c]=t[c].slice(0);return o},o.start(),o.update=function(l,c){if(c==="utf8")l=Ge.util.encodeUtf8(l);var u=l.length;o.messageLength+=u,u=[u/4294967296>>>0,u>>>0];for(var d=o.fullMessageLength.length-1;d>=0;--d)o.fullMessageLength[d]+=u[1],u[1]=u[0]+(o.fullMessageLength[d]/4294967296>>>0),o.fullMessageLength[d]=o.fullMessageLength[d]>>>0,u[0]=u[1]/4294967296>>>0;if(r.putBytes(l),kd(n,i,r),r.read>2048||r.length()===0)r.compact();return o},o.digest=function(){var l=Ge.util.createBuffer();l.putBytes(r.bytes());var c=o.fullMessageLength[o.fullMessageLength.length-1]+o.messageLengthSize,u=c&o.blockLength-1;l.putBytes(zo.substr(0,o.blockLength-u));var d,p,h=o.fullMessageLength[0]*8;for(var f=0;f<o.fullMessageLength.length-1;++f)d=o.fullMessageLength[f+1]*8,p=d/4294967296>>>0,h+=p,l.putInt32(h>>>0),h=d>>>0;l.putInt32(h);var v=Array(n.length);for(var f=0;f<n.length;++f)v[f]=n[f].slice(0);kd(v,i,l);var x=Ge.util.createBuffer(),S;if(e==="SHA-512")S=v.length;else if(e==="SHA-384")S=v.length-2;else S=v.length-4;for(var f=0;f<S;++f)if(x.putInt32(v[f][0]),f!==S-1||e!=="SHA-512/224")x.putInt32(v[f][1]);return x},o};var zo=null,Rd=!1,Xo=null,dn=null;function My(){zo=String.fromCharCode(128),zo+=Ge.util.fillString(String.fromCharCode(0),128),Xo=[[1116352408,3609767458],[1899447441,602891725],[3049323471,3964484399],[3921009573,2173295548],[961987163,4081628472],[1508970993,3053834265],[2453635748,2937671579],[2870763221,3664609560],[3624381080,2734883394],[310598401,1164996542],[607225278,1323610764],[1426881987,3590304994],[1925078388,4068182383],[2162078206,991336113],[2614888103,633803317],[3248222580,3479774868],[3835390401,2666613458],[4022224774,944711139],[264347078,2341262773],[604807628,2007800933],[770255983,1495990901],[1249150122,1856431235],[1555081692,3175218132],[1996064986,2198950837],[2554220882,3999719339],[2821834349,766784016],[2952996808,2566594879],[3210313671,3203337956],[3336571891,1034457026],[3584528711,2466948901],[113926993,3758326383],[338241895,168717936],[666307205,1188179964],[773529912,1546045734],[1294757372,1522805485],[1396182291,2643833823],[1695183700,2343527390],[1986661051,1014477480],[2177026350,1206759142],[2456956037,344077627],[2730485921,1290863460],[2820302411,3158454273],[3259730800,3505952657],[3345764771,106217008],[3516065817,3606008344],[3600352804,1432725776],[4094571909,1467031594],[275423344,851169720],[430227734,3100823752],[506948616,1363258195],[659060556,3750685593],[883997877,3785050280],[958139571,3318307427],[1322822218,3812723403],[1537002063,2003034995],[1747873779,3602036899],[1955562222,1575990012],[2024104815,1125592928],[2227730452,2716904306],[2361852424,442776044],[2428436474,593698344],[2756734187,3733110249],[3204031479,2999351573],[3329325298,3815920427],[3391569614,3928383900],[3515267271,566280711],[3940187606,3454069534],[4118630271,4000239992],[116418474,1914138554],[174292421,2731055270],[289380356,3203993006],[460393269,320620315],[685471733,587496836],[852142971,1086792851],[1017036298,365543100],[1126000580,2618297676],[1288033470,3409855158],[1501505948,4234509866],[1607167915,987167468],[1816402316,1246189591]],dn={},dn["SHA-512"]=[[1779033703,4089235720],[3144134277,2227873595],[1013904242,4271175723],[2773480762,1595750129],[1359893119,2917565137],[2600822924,725511199],[528734635,4215389547],[1541459225,327033209]],dn["SHA-384"]=[[3418070365,3238371032],[1654270250,914150663],[2438529370,812702999],[355462360,4144912697],[1731405415,4290775857],[2394180231,1750603025],[3675008525,1694076839],[1203062813,3204075428]],dn["SHA-512/256"]=[[573645204,4230739756],[2673172387,3360449730],[596883563,1867755857],[2520282905,1497426621],[2519219938,2827943907],[3193839141,1401305490],[721525244,746961066],[246885852,2177182882]],dn["SHA-512/224"]=[[2352822216,424955298],[1944164710,2312950998],[502970286,855612546],[1738396948,1479516111],[258812777,2077511080],[2011393907,79989058],[1067287976,1780299464],[286451373,2446758561]],Rd=!0}function kd(e,t,n){var r,i,s,a,o,l,c,u,d,p,h,f,v,x,S,A,b,k,R,I,V,J,D,W,Z,pe,ge,$e,xe,Le,F,re,Q,ue,ce,te=n.length();while(te>=128){for(xe=0;xe<16;++xe)t[xe][0]=n.getInt32()>>>0,t[xe][1]=n.getInt32()>>>0;for(;xe<80;++xe)re=t[xe-2],Le=re[0],F=re[1],r=((Le>>>19|F<<13)^(F>>>29|Le<<3)^Le>>>6)>>>0,i=((Le<<13|F>>>19)^(F<<3|Le>>>29)^(Le<<26|F>>>6))>>>0,ue=t[xe-15],Le=ue[0],F=ue[1],s=((Le>>>1|F<<31)^(Le>>>8|F<<24)^Le>>>7)>>>0,a=((Le<<31|F>>>1)^(Le<<24|F>>>8)^(Le<<25|F>>>7))>>>0,Q=t[xe-7],ce=t[xe-16],F=i+Q[1]+a+ce[1],t[xe][0]=r+Q[0]+s+ce[0]+(F/4294967296>>>0)>>>0,t[xe][1]=F>>>0;v=e[0][0],x=e[0][1],S=e[1][0],A=e[1][1],b=e[2][0],k=e[2][1],R=e[3][0],I=e[3][1],V=e[4][0],J=e[4][1],D=e[5][0],W=e[5][1],Z=e[6][0],pe=e[6][1],ge=e[7][0],$e=e[7][1];for(xe=0;xe<80;++xe)c=((V>>>14|J<<18)^(V>>>18|J<<14)^(J>>>9|V<<23))>>>0,u=((V<<18|J>>>14)^(V<<14|J>>>18)^(J<<23|V>>>9))>>>0,d=(Z^V&(D^Z))>>>0,p=(pe^J&(W^pe))>>>0,o=((v>>>28|x<<4)^(x>>>2|v<<30)^(x>>>7|v<<25))>>>0,l=((v<<4|x>>>28)^(x<<30|v>>>2)^(x<<25|v>>>7))>>>0,h=(v&S|b&(v^S))>>>0,f=(x&A|k&(x^A))>>>0,F=$e+u+p+Xo[xe][1]+t[xe][1],r=ge+c+d+Xo[xe][0]+t[xe][0]+(F/4294967296>>>0)>>>0,i=F>>>0,F=l+f,s=o+h+(F/4294967296>>>0)>>>0,a=F>>>0,ge=Z,$e=pe,Z=D,pe=W,D=V,W=J,F=I+i,V=R+r+(F/4294967296>>>0)>>>0,J=F>>>0,R=b,I=k,b=S,k=A,S=v,A=x,F=i+a,v=r+s+(F/4294967296>>>0)>>>0,x=F>>>0;F=e[0][1]+x,e[0][0]=e[0][0]+v+(F/4294967296>>>0)>>>0,e[0][1]=F>>>0,F=e[1][1]+A,e[1][0]=e[1][0]+S+(F/4294967296>>>0)>>>0,e[1][1]=F>>>0,F=e[2][1]+k,e[2][0]=e[2][0]+b+(F/4294967296>>>0)>>>0,e[2][1]=F>>>0,F=e[3][1]+I,e[3][0]=e[3][0]+R+(F/4294967296>>>0)>>>0,e[3][1]=F>>>0,F=e[4][1]+J,e[4][0]=e[4][0]+V+(F/4294967296>>>0)>>>0,e[4][1]=F>>>0,F=e[5][1]+W,e[5][0]=e[5][0]+D+(F/4294967296>>>0)>>>0,e[5][1]=F>>>0,F=e[6][1]+pe,e[6][0]=e[6][0]+Z+(F/4294967296>>>0)>>>0,e[6][1]=F>>>0,F=e[7][1]+$e,e[7][0]=e[7][0]+ge+(F/4294967296>>>0)>>>0,e[7][1]=F>>>0,te-=128}}});var Pd=de(function(Wy){var $y=ve();Gt();var pt=$y.asn1;Wy.privateKeyValidator={name:"PrivateKeyInfo",tagClass:pt.Class.UNIVERSAL,type:pt.Type.SEQUENCE,constructed:!0,value:[{name:"PrivateKeyInfo.version",tagClass:pt.Class.UNIVERSAL,type:pt.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:pt.Class.UNIVERSAL,type:pt.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:pt.Class.UNIVERSAL,type:pt.Type.OID,constructed:!1,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:pt.Class.UNIVERSAL,type:pt.Type.OCTETSTRING,constructed:!1,capture:"privateKey"}]};Wy.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:pt.Class.UNIVERSAL,type:pt.Type.SEQUENCE,constructed:!0,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:pt.Class.UNIVERSAL,type:pt.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:pt.Class.UNIVERSAL,type:pt.Type.OID,constructed:!1,capture:"publicKeyOid"}]},{tagClass:pt.Class.UNIVERSAL,type:pt.Type.BITSTRING,constructed:!1,composed:!0,captureBitStringValue:"ed25519PublicKey"}]}});var Kd=de(function(M1,Hd){var yt=ve();Ci();Lt();Qo();Pe();var Ud=Pd(),{publicKeyValidator:qy,privateKeyValidator:Gy}=Ud;if(typeof Jo>"u")Jo=yt.jsbn.BigInteger;var Jo,Zo=yt.util.ByteBuffer,kt=typeof Buffer>"u"?Uint8Array:Buffer;yt.pki=yt.pki||{};Hd.exports=yt.pki.ed25519=yt.ed25519=yt.ed25519||{};var Te=yt.ed25519;Te.constants={};Te.constants.PUBLIC_KEY_BYTE_LENGTH=32;Te.constants.PRIVATE_KEY_BYTE_LENGTH=64;Te.constants.SEED_BYTE_LENGTH=32;Te.constants.SIGN_BYTE_LENGTH=64;Te.constants.HASH_BYTE_LENGTH=64;Te.generateKeyPair=function(e){e=e||{};var t=e.seed;if(t===void 0)t=yt.random.getBytesSync(Te.constants.SEED_BYTE_LENGTH);else if(typeof t==="string"){if(t.length!==Te.constants.SEED_BYTE_LENGTH)throw TypeError('"seed" must be '+Te.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=Cr({message:t,encoding:"binary"});var n=new kt(Te.constants.PUBLIC_KEY_BYTE_LENGTH),r=new kt(Te.constants.PRIVATE_KEY_BYTE_LENGTH);for(var i=0;i<32;++i)r[i]=t[i];return Qy(n,r),{publicKey:n,privateKey:r}};Te.privateKeyFromAsn1=function(e){var t={},n=[],r=yt.asn1.validate(e,Gy,t,n);if(!r){var i=Error("Invalid Key.");throw i.errors=n,i}var s=yt.asn1.derToOid(t.privateKeyOid),a=yt.oids.EdDSA25519;if(s!==a)throw Error('Invalid OID "'+s+'"; OID must be "'+a+'".');var o=t.privateKey,l=Cr({message:yt.asn1.fromDer(o).value,encoding:"binary"});return{privateKeyBytes:l}};Te.publicKeyFromAsn1=function(e){var t={},n=[],r=yt.asn1.validate(e,qy,t,n);if(!r){var i=Error("Invalid Key.");throw i.errors=n,i}var s=yt.asn1.derToOid(t.publicKeyOid),a=yt.oids.EdDSA25519;if(s!==a)throw Error('Invalid OID "'+s+'"; OID must be "'+a+'".');var o=t.ed25519PublicKey;if(o.length!==Te.constants.PUBLIC_KEY_BYTE_LENGTH)throw Error("Key length is invalid.");return Cr({message:o,encoding:"binary"})};Te.publicKeyFromPrivateKey=function(e){e=e||{};var t=Cr({message:e.privateKey,encoding:"binary"});if(t.length!==Te.constants.PRIVATE_KEY_BYTE_LENGTH)throw TypeError('"options.privateKey" must have a byte length of '+Te.constants.PRIVATE_KEY_BYTE_LENGTH);var n=new kt(Te.constants.PUBLIC_KEY_BYTE_LENGTH);for(var r=0;r<n.length;++r)n[r]=t[32+r];return n};Te.sign=function(e){e=e||{};var t=Cr(e),n=Cr({message:e.privateKey,encoding:"binary"});if(n.length===Te.constants.SEED_BYTE_LENGTH){var r=Te.generateKeyPair({seed:n});n=r.privateKey}else if(n.length!==Te.constants.PRIVATE_KEY_BYTE_LENGTH)throw TypeError('"options.privateKey" must have a byte length of '+Te.constants.SEED_BYTE_LENGTH+" or "+Te.constants.PRIVATE_KEY_BYTE_LENGTH);var i=new kt(Te.constants.SIGN_BYTE_LENGTH+t.length);Yy(i,t,t.length,n);var s=new kt(Te.constants.SIGN_BYTE_LENGTH);for(var a=0;a<s.length;++a)s[a]=i[a];return s};Te.verify=function(e){e=e||{};var t=Cr(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=Cr({message:e.signature,encoding:"binary"});if(n.length!==Te.constants.SIGN_BYTE_LENGTH)throw TypeError('"options.signature" must have a byte length of '+Te.constants.SIGN_BYTE_LENGTH);var r=Cr({message:e.publicKey,encoding:"binary"});if(r.length!==Te.constants.PUBLIC_KEY_BYTE_LENGTH)throw TypeError('"options.publicKey" must have a byte length of '+Te.constants.PUBLIC_KEY_BYTE_LENGTH);var i=new kt(Te.constants.SIGN_BYTE_LENGTH+t.length),s=new kt(Te.constants.SIGN_BYTE_LENGTH+t.length),a;for(a=0;a<Te.constants.SIGN_BYTE_LENGTH;++a)i[a]=n[a];for(a=0;a<t.length;++a)i[a+Te.constants.SIGN_BYTE_LENGTH]=t[a];return Jy(s,i,i.length,r)>=0};function Cr(e){var t=e.message;if(t instanceof Uint8Array||t instanceof kt)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 Zo(t,n)}else if(!(t instanceof Zo))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 kt(t.length());for(var i=0;i<r.length;++i)r[i]=t.at(i);return r}var el=ae(),Zs=ae([1]),jy=ae([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),zy=ae([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),Nd=ae([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),Dd=ae([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),ki=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]),Xy=ae([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function Ii(e,t){var n=yt.md.sha512.create(),r=new Zo(e);n.update(r.getBytes(t),"binary");var i=n.digest().getBytes();if(typeof Buffer<"u")return Buffer.from(i,"binary");var s=new kt(Te.constants.HASH_BYTE_LENGTH);for(var a=0;a<64;++a)s[a]=i.charCodeAt(a);return s}function Qy(e,t){var n=[ae(),ae(),ae(),ae()],r,i=Ii(t,32);i[0]&=248,i[31]&=127,i[31]|=64,il(n,i),nl(e,n);for(r=0;r<32;++r)t[r+32]=e[r];return 0}function Yy(e,t,n,r){var i,s,a=new Float64Array(64),o=[ae(),ae(),ae(),ae()],l=Ii(r,32);l[0]&=248,l[31]&=127,l[31]|=64;var c=n+64;for(i=0;i<n;++i)e[64+i]=t[i];for(i=0;i<32;++i)e[32+i]=l[32+i];var u=Ii(e.subarray(32),n+32);tl(u),il(o,u),nl(e,o);for(i=32;i<64;++i)e[i]=r[i];var d=Ii(e,n+64);tl(d);for(i=32;i<64;++i)a[i]=0;for(i=0;i<32;++i)a[i]=u[i];for(i=0;i<32;++i)for(s=0;s<32;s++)a[i+s]+=d[i]*l[s];return Vd(e.subarray(32),a),c}function Jy(e,t,n,r){var i,s,a=new kt(32),o=[ae(),ae(),ae(),ae()],l=[ae(),ae(),ae(),ae()];if(s=-1,n<64)return-1;if(ev(l,r))return-1;if(!Zy(t,32))return-1;for(i=0;i<n;++i)e[i]=t[i];for(i=0;i<32;++i)e[i+32]=r[i];var c=Ii(e,n);if(tl(c),$d(o,l,c),il(l,t.subarray(32)),rl(o,l),nl(a,o),n-=64,Fd(t,0,a,0)){for(i=0;i<n;++i)e[i]=0;return-1}for(i=0;i<n;++i)e[i]=t[i+64];return s=n,s}function Zy(e,t){var n;for(n=31;n>=0;--n){if(e[t+n]<ki[n])return!0;if(e[t+n]>ki[n])return!1}return!1}function Vd(e,t){var n,r,i,s;for(r=63;r>=32;--r){n=0;for(i=r-32,s=r-12;i<s;++i)t[i]+=n-16*t[r]*ki[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)*ki[i],n=t[i]>>8,t[i]&=255;for(i=0;i<32;++i)t[i]-=n*ki[i];for(r=0;r<32;++r)t[r+1]+=t[r]>>8,e[r]=t[r]&255}function tl(e){var t=new Float64Array(64);for(var n=0;n<64;++n)t[n]=e[n],e[n]=0;Vd(e,t)}function rl(e,t){var n=ae(),r=ae(),i=ae(),s=ae(),a=ae(),o=ae(),l=ae(),c=ae(),u=ae();On(n,e[1],e[0]),On(u,t[1],t[0]),Fe(n,n,u),Ln(r,e[0],e[1]),Ln(u,t[0],t[1]),Fe(r,r,u),Fe(i,e[3],t[3]),Fe(i,i,zy),Fe(s,e[2],t[2]),Ln(s,s,s),On(a,r,n),On(o,s,i),Ln(l,s,i),Ln(c,r,n),Fe(e[0],a,o),Fe(e[1],c,l),Fe(e[2],l,o),Fe(e[3],a,c)}function Ld(e,t,n){for(var r=0;r<4;++r)Wd(e[r],t[r],n)}function nl(e,t){var n=ae(),r=ae(),i=ae();iv(i,t[2]),Fe(n,t[0],i),Fe(r,t[1],i),ea(e,r),e[31]^=Md(n)<<7}function ea(e,t){var n,r,i,s=ae(),a=ae();for(n=0;n<16;++n)a[n]=t[n];Yo(a),Yo(a),Yo(a);for(r=0;r<2;++r){s[0]=a[0]-65517;for(n=1;n<15;++n)s[n]=a[n]-65535-(s[n-1]>>16&1),s[n-1]&=65535;s[15]=a[15]-32767-(s[14]>>16&1),i=s[15]>>16&1,s[14]&=65535,Wd(a,s,1-i)}for(n=0;n<16;n++)e[2*n]=a[n]&255,e[2*n+1]=a[n]>>8}function ev(e,t){var n=ae(),r=ae(),i=ae(),s=ae(),a=ae(),o=ae(),l=ae();if(Hr(e[2],Zs),tv(e[1],t),fn(i,e[1]),Fe(s,i,jy),On(i,i,e[2]),Ln(s,e[2],s),fn(a,s),fn(o,a),Fe(l,o,a),Fe(n,l,i),Fe(n,n,s),rv(n,n),Fe(n,n,i),Fe(n,n,s),Fe(n,n,s),Fe(e[0],n,s),fn(r,e[0]),Fe(r,r,s),Od(r,i))Fe(e[0],e[0],Xy);if(fn(r,e[0]),Fe(r,r,s),Od(r,i))return-1;if(Md(e[0])===t[31]>>7)On(e[0],el,e[0]);return Fe(e[3],e[0],e[1]),0}function tv(e,t){var n;for(n=0;n<16;++n)e[n]=t[2*n]+(t[2*n+1]<<8);e[15]&=32767}function rv(e,t){var n=ae(),r;for(r=0;r<16;++r)n[r]=t[r];for(r=250;r>=0;--r)if(fn(n,n),r!==1)Fe(n,n,t);for(r=0;r<16;++r)e[r]=n[r]}function Od(e,t){var n=new kt(32),r=new kt(32);return ea(n,e),ea(r,t),Fd(n,0,r,0)}function Fd(e,t,n,r){return nv(e,t,n,r,32)}function nv(e,t,n,r,i){var s,a=0;for(s=0;s<i;++s)a|=e[t+s]^n[r+s];return(1&a-1>>>8)-1}function Md(e){var t=new kt(32);return ea(t,e),t[0]&1}function $d(e,t,n){var r,i;Hr(e[0],el),Hr(e[1],Zs),Hr(e[2],Zs),Hr(e[3],el);for(i=255;i>=0;--i)r=n[i/8|0]>>(i&7)&1,Ld(e,t,r),rl(t,e),rl(e,e),Ld(e,t,r)}function il(e,t){var n=[ae(),ae(),ae(),ae()];Hr(n[0],Nd),Hr(n[1],Dd),Hr(n[2],Zs),Fe(n[3],Nd,Dd),$d(e,n,t)}function Hr(e,t){var n;for(n=0;n<16;n++)e[n]=t[n]|0}function iv(e,t){var n=ae(),r;for(r=0;r<16;++r)n[r]=t[r];for(r=253;r>=0;--r)if(fn(n,n),r!==2&&r!==4)Fe(n,n,t);for(r=0;r<16;++r)e[r]=n[r]}function Yo(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 Wd(e,t,n){var r,i=~(n-1);for(var s=0;s<16;++s)r=i&(e[s]^t[s]),e[s]^=r,t[s]^=r}function ae(e){var t,n=new Float64Array(16);if(e)for(t=0;t<e.length;++t)n[t]=e[t];return n}function Ln(e,t,n){for(var r=0;r<16;++r)e[r]=t[r]+n[r]}function On(e,t,n){for(var r=0;r<16;++r)e[r]=t[r]-n[r]}function fn(e,t){Fe(e,t,t)}function Fe(e,t,n){var r,i,s=0,a=0,o=0,l=0,c=0,u=0,d=0,p=0,h=0,f=0,v=0,x=0,S=0,A=0,b=0,k=0,R=0,I=0,V=0,J=0,D=0,W=0,Z=0,pe=0,ge=0,$e=0,xe=0,Le=0,F=0,re=0,Q=0,ue=n[0],ce=n[1],te=n[2],Ie=n[3],We=n[4],Xe=n[5],se=n[6],me=n[7],Oe=n[8],Ve=n[9],nt=n[10],st=n[11],at=n[12],Qe=n[13],ot=n[14],lt=n[15];r=t[0],s+=r*ue,a+=r*ce,o+=r*te,l+=r*Ie,c+=r*We,u+=r*Xe,d+=r*se,p+=r*me,h+=r*Oe,f+=r*Ve,v+=r*nt,x+=r*st,S+=r*at,A+=r*Qe,b+=r*ot,k+=r*lt,r=t[1],a+=r*ue,o+=r*ce,l+=r*te,c+=r*Ie,u+=r*We,d+=r*Xe,p+=r*se,h+=r*me,f+=r*Oe,v+=r*Ve,x+=r*nt,S+=r*st,A+=r*at,b+=r*Qe,k+=r*ot,R+=r*lt,r=t[2],o+=r*ue,l+=r*ce,c+=r*te,u+=r*Ie,d+=r*We,p+=r*Xe,h+=r*se,f+=r*me,v+=r*Oe,x+=r*Ve,S+=r*nt,A+=r*st,b+=r*at,k+=r*Qe,R+=r*ot,I+=r*lt,r=t[3],l+=r*ue,c+=r*ce,u+=r*te,d+=r*Ie,p+=r*We,h+=r*Xe,f+=r*se,v+=r*me,x+=r*Oe,S+=r*Ve,A+=r*nt,b+=r*st,k+=r*at,R+=r*Qe,I+=r*ot,V+=r*lt,r=t[4],c+=r*ue,u+=r*ce,d+=r*te,p+=r*Ie,h+=r*We,f+=r*Xe,v+=r*se,x+=r*me,S+=r*Oe,A+=r*Ve,b+=r*nt,k+=r*st,R+=r*at,I+=r*Qe,V+=r*ot,J+=r*lt,r=t[5],u+=r*ue,d+=r*ce,p+=r*te,h+=r*Ie,f+=r*We,v+=r*Xe,x+=r*se,S+=r*me,A+=r*Oe,b+=r*Ve,k+=r*nt,R+=r*st,I+=r*at,V+=r*Qe,J+=r*ot,D+=r*lt,r=t[6],d+=r*ue,p+=r*ce,h+=r*te,f+=r*Ie,v+=r*We,x+=r*Xe,S+=r*se,A+=r*me,b+=r*Oe,k+=r*Ve,R+=r*nt,I+=r*st,V+=r*at,J+=r*Qe,D+=r*ot,W+=r*lt,r=t[7],p+=r*ue,h+=r*ce,f+=r*te,v+=r*Ie,x+=r*We,S+=r*Xe,A+=r*se,b+=r*me,k+=r*Oe,R+=r*Ve,I+=r*nt,V+=r*st,J+=r*at,D+=r*Qe,W+=r*ot,Z+=r*lt,r=t[8],h+=r*ue,f+=r*ce,v+=r*te,x+=r*Ie,S+=r*We,A+=r*Xe,b+=r*se,k+=r*me,R+=r*Oe,I+=r*Ve,V+=r*nt,J+=r*st,D+=r*at,W+=r*Qe,Z+=r*ot,pe+=r*lt,r=t[9],f+=r*ue,v+=r*ce,x+=r*te,S+=r*Ie,A+=r*We,b+=r*Xe,k+=r*se,R+=r*me,I+=r*Oe,V+=r*Ve,J+=r*nt,D+=r*st,W+=r*at,Z+=r*Qe,pe+=r*ot,ge+=r*lt,r=t[10],v+=r*ue,x+=r*ce,S+=r*te,A+=r*Ie,b+=r*We,k+=r*Xe,R+=r*se,I+=r*me,V+=r*Oe,J+=r*Ve,D+=r*nt,W+=r*st,Z+=r*at,pe+=r*Qe,ge+=r*ot,$e+=r*lt,r=t[11],x+=r*ue,S+=r*ce,A+=r*te,b+=r*Ie,k+=r*We,R+=r*Xe,I+=r*se,V+=r*me,J+=r*Oe,D+=r*Ve,W+=r*nt,Z+=r*st,pe+=r*at,ge+=r*Qe,$e+=r*ot,xe+=r*lt,r=t[12],S+=r*ue,A+=r*ce,b+=r*te,k+=r*Ie,R+=r*We,I+=r*Xe,V+=r*se,J+=r*me,D+=r*Oe,W+=r*Ve,Z+=r*nt,pe+=r*st,ge+=r*at,$e+=r*Qe,xe+=r*ot,Le+=r*lt,r=t[13],A+=r*ue,b+=r*ce,k+=r*te,R+=r*Ie,I+=r*We,V+=r*Xe,J+=r*se,D+=r*me,W+=r*Oe,Z+=r*Ve,pe+=r*nt,ge+=r*st,$e+=r*at,xe+=r*Qe,Le+=r*ot,F+=r*lt,r=t[14],b+=r*ue,k+=r*ce,R+=r*te,I+=r*Ie,V+=r*We,J+=r*Xe,D+=r*se,W+=r*me,Z+=r*Oe,pe+=r*Ve,ge+=r*nt,$e+=r*st,xe+=r*at,Le+=r*Qe,F+=r*ot,re+=r*lt,r=t[15],k+=r*ue,R+=r*ce,I+=r*te,V+=r*Ie,J+=r*We,D+=r*Xe,W+=r*se,Z+=r*me,pe+=r*Oe,ge+=r*Ve,$e+=r*nt,xe+=r*st,Le+=r*at,F+=r*Qe,re+=r*ot,Q+=r*lt,s+=38*R,a+=38*I,o+=38*V,l+=38*J,c+=38*D,u+=38*W,d+=38*Z,p+=38*pe,h+=38*ge,f+=38*$e,v+=38*xe,x+=38*Le,S+=38*F,A+=38*re,b+=38*Q,i=1,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=o+i+65535,i=Math.floor(r/65536),o=r-i*65536,r=l+i+65535,i=Math.floor(r/65536),l=r-i*65536,r=c+i+65535,i=Math.floor(r/65536),c=r-i*65536,r=u+i+65535,i=Math.floor(r/65536),u=r-i*65536,r=d+i+65535,i=Math.floor(r/65536),d=r-i*65536,r=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=f+i+65535,i=Math.floor(r/65536),f=r-i*65536,r=v+i+65535,i=Math.floor(r/65536),v=r-i*65536,r=x+i+65535,i=Math.floor(r/65536),x=r-i*65536,r=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=b+i+65535,i=Math.floor(r/65536),b=r-i*65536,r=k+i+65535,i=Math.floor(r/65536),k=r-i*65536,s+=i-1+37*(i-1),i=1,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=o+i+65535,i=Math.floor(r/65536),o=r-i*65536,r=l+i+65535,i=Math.floor(r/65536),l=r-i*65536,r=c+i+65535,i=Math.floor(r/65536),c=r-i*65536,r=u+i+65535,i=Math.floor(r/65536),u=r-i*65536,r=d+i+65535,i=Math.floor(r/65536),d=r-i*65536,r=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=f+i+65535,i=Math.floor(r/65536),f=r-i*65536,r=v+i+65535,i=Math.floor(r/65536),v=r-i*65536,r=x+i+65535,i=Math.floor(r/65536),x=r-i*65536,r=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=b+i+65535,i=Math.floor(r/65536),b=r-i*65536,r=k+i+65535,i=Math.floor(r/65536),k=r-i*65536,s+=i-1+37*(i-1),e[0]=s,e[1]=a,e[2]=o,e[3]=l,e[4]=c,e[5]=u,e[6]=d,e[7]=p,e[8]=h,e[9]=f,e[10]=v,e[11]=x,e[12]=S,e[13]=A,e[14]=b,e[15]=k}});var zd=de(function($1,jd){var Bt=ve();Pe();Lt();Ci();jd.exports=Bt.kem=Bt.kem||{};var qd=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,s){var a=Math.ceil(i.n.bitLength()/8),o;do o=new qd(Bt.util.bytesToHex(n.getBytesSync(a)),16).mod(i.n);while(o.compareTo(qd.ONE)<=0);o=Bt.util.hexToBytes(o.toString(16));var l=a-o.length;if(l>0)o=Bt.util.fillString(String.fromCharCode(0),l)+o;var c=i.encrypt(o,"NONE"),u=e.generate(o,s);return{encapsulation:c,key:u}},r.decrypt=function(i,s,a){var o=i.decrypt(s,"NONE");return e.generate(o,a)},r};Bt.kem.kdf1=function(e,t){Gd(this,e,0,t||e.digestLength)};Bt.kem.kdf2=function(e,t){Gd(this,e,1,t||e.digestLength)};function Gd(e,t,n,r){e.generate=function(i,s){var a=new Bt.util.ByteBuffer,o=Math.ceil(s/r)+n,l=new Bt.util.ByteBuffer;for(var c=n;c<o;++c){l.putInt32(c),t.start(),t.update(i+l.getBytes());var u=t.digest();a.putBytes(u.getBytes(r))}return a.truncate(a.length()-s),a.getBytes()}}});var Qd=de(function(W1,Xd){var Ae=ve();Pe();Xd.exports=Ae.log=Ae.log||{};Ae.log.levels=["none","error","warning","info","debug","verbose","max"];var na={},sl=[],Ri=null;Ae.log.LEVEL_LOCKED=2;Ae.log.NO_LEVEL_CHECK=4;Ae.log.INTERPOLATE=8;for($t=0;$t<Ae.log.levels.length;++$t)ta=Ae.log.levels[$t],na[ta]={index:$t,name:ta.toUpperCase()};var ta,$t;Ae.log.logMessage=function(e){var t=na[e.level].index;for(var n=0;n<sl.length;++n){var r=sl[n];if(r.flags&Ae.log.NO_LEVEL_CHECK)r.f(e);else{var i=na[r.level].index;if(t<=i)r.f(r,e)}}};Ae.log.prepareStandard=function(e){if(!("standard"in e))e.standard=na[e.level].name+" ["+e.category+"] "+e.message};Ae.log.prepareFull=function(e){if(!("full"in e)){var t=[e.message];t=t.concat([]),e.full=Ae.util.format.apply(this,t)}};Ae.log.prepareStandardFull=function(e){if(!("standardFull"in e))Ae.log.prepareStandard(e),e.standardFull=e.standard};ra=["error","warning","info","debug","verbose"];for($t=0;$t<ra.length;++$t)(function(t){Ae.log[t]=function(n,r){var i=Array.prototype.slice.call(arguments).slice(2),s={timestamp:new Date,level:t,category:n,message:r,arguments:i};Ae.log.logMessage(s)}})(ra[$t]);var ra,$t;Ae.log.makeLogger=function(e){var t={flags:0,f:e};return Ae.log.setLevel(t,"none"),t};Ae.log.setLevel=function(e,t){var n=!1;if(e&&!(e.flags&Ae.log.LEVEL_LOCKED))for(var r=0;r<Ae.log.levels.length;++r){var i=Ae.log.levels[r];if(t==i){e.level=t,n=!0;break}}return n};Ae.log.lock=function(e,t){if(typeof t>"u"||t)e.flags|=Ae.log.LEVEL_LOCKED;else e.flags&=~Ae.log.LEVEL_LOCKED};Ae.log.addLogger=function(e){sl.push(e)};if(typeof console<"u"&&"log"in console){if(console.error&&console.warn&&console.info&&console.debug)al={error:console.error,warning:console.warn,info:console.info,debug:console.debug,verbose:console.debug},Vn=function(e,t){Ae.log.prepareStandard(t);var n=al[t.level],r=[t.standard];r=r.concat(t.arguments.slice()),n.apply(console,r)},pn=Ae.log.makeLogger(Vn);else Vn=function(t,n){Ae.log.prepareStandardFull(n),console.log(n.standardFull)},pn=Ae.log.makeLogger(Vn);Ae.log.setLevel(pn,"debug"),Ae.log.addLogger(pn),Ri=pn}else console={log:function(){}};var pn,al,Vn;if(Ri!==null&&typeof window<"u"&&window.location){if(Un=new URL(window.location.href).searchParams,Un.has("console.level"))Ae.log.setLevel(Ri,Un.get("console.level").slice(-1)[0]);if(Un.has("console.lock")){if(ol=Un.get("console.lock").slice(-1)[0],ol=="true")Ae.log.lock(Ri)}}var Un,ol;Ae.log.consoleLogger=Ri});var Jd=de(function(H1,Yd){Yd.exports=rr();Ls();Rn();So();Qo()});var tf=de(function(K1,ef){var H=ve();Lr();Gt();Si();Or();sn();Lo();Lt();Pe();Xs();var E=H.asn1,Et=ef.exports=H.pkcs7=H.pkcs7||{};Et.messageFromPem=function(e){var t=H.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=E.fromDer(t.body);return Et.messageFromAsn1(r)};Et.messageToPem=function(e,t){var n={type:"PKCS7",body:E.toDer(e.toAsn1()).getBytes()};return H.pem.encode(n,{maxline:t})};Et.messageFromAsn1=function(e){var t={},n=[];if(!E.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=E.derToOid(t.contentType),s;switch(i){case H.pki.oids.envelopedData:s=Et.createEnvelopedData();break;case H.pki.oids.encryptedData:s=Et.createEncryptedData();break;case H.pki.oids.signedData:s=Et.createSignedData();break;default:throw Error("Cannot read PKCS#7 message. ContentType with OID "+i+" is not (yet) supported.")}return s.fromAsn1(t.content.value[0]),s};Et.createSignedData=function(){var e=null;return e={type:H.pki.oids.signedData,version:1,certificates:[],crls:[],signers:[],digestAlgorithmIdentifiers:[],contentInfo:null,signerInfos:[],fromAsn1:function(r){if(cl(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 s=0;s<i.length;++s)e.certificates.push(H.pki.certificateFromAsn1(i[s]))}},toAsn1:function(){if(!e.contentInfo)e.sign();var r=[];for(var i=0;i<e.certificates.length;++i)r.push(H.pki.certificateToAsn1(e.certificates[i]));var s=[],a=E.create(E.Class.CONTEXT_SPECIFIC,0,!0,[E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.INTEGER,!1,E.integerToDer(e.version).getBytes()),E.create(E.Class.UNIVERSAL,E.Type.SET,!0,e.digestAlgorithmIdentifiers),e.contentInfo])]);if(r.length>0)a.value[0].value.push(E.create(E.Class.CONTEXT_SPECIFIC,0,!0,r));if(s.length>0)a.value[0].value.push(E.create(E.Class.CONTEXT_SPECIFIC,1,!0,s));return a.value[0].value.push(E.create(E.Class.UNIVERSAL,E.Type.SET,!0,e.signerInfos)),E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.OID,!1,E.oidToDer(e.type).getBytes()),a])},addSigner:function(r){var{issuer:i,serialNumber:s}=r;if(r.certificate){var a=r.certificate;if(typeof a==="string")a=H.pki.certificateFromPem(a);i=a.issuer.attributes,s=a.serialNumber}var o=r.key;if(!o)throw Error("Could not add PKCS#7 signer; no private key specified.");if(typeof o==="string")o=H.pki.privateKeyFromPem(o);var l=r.digestAlgorithm||H.pki.oids.sha1;switch(l){case H.pki.oids.sha1:case H.pki.oids.sha256:case H.pki.oids.sha384:case H.pki.oids.sha512:case H.pki.oids.md5:break;default:throw Error("Could not add PKCS#7 signer; unknown message digest algorithm: "+l)}var c=r.authenticatedAttributes||[];if(c.length>0){var u=!1,d=!1;for(var p=0;p<c.length;++p){var h=c[p];if(!u&&h.type===H.pki.oids.contentType){if(u=!0,d)break;continue}if(!d&&h.type===H.pki.oids.messageDigest){if(d=!0,u)break;continue}}if(!u||!d)throw Error("Invalid signer.authenticatedAttributes. If signer.authenticatedAttributes is specified, then it must contain at least two attributes, PKCS #9 content-type and PKCS #9 message-digest.")}e.signers.push({key:o,version:1,issuer:i,serialNumber:s,digestAlgorithm:l,signatureAlgorithm:H.pki.oids.rsaEncryption,signature:null,authenticatedAttributes:c,unauthenticatedAttributes:[]})},sign:function(r){if(r=r||{},typeof e.content!=="object"||e.contentInfo===null){if(e.contentInfo=E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.OID,!1,E.oidToDer(H.pki.oids.data).getBytes())]),"content"in e){var i;if(e.content instanceof H.util.ByteBuffer)i=e.content.bytes();else if(typeof e.content==="string")i=H.util.encodeUtf8(e.content);if(r.detached)e.detachedContent=E.create(E.Class.UNIVERSAL,E.Type.OCTETSTRING,!1,i);else e.contentInfo.value.push(E.create(E.Class.CONTEXT_SPECIFIC,0,!0,[E.create(E.Class.UNIVERSAL,E.Type.OCTETSTRING,!1,i)]))}}if(e.signers.length===0)return;var s=t();n(s)},verify:function(){throw Error("PKCS#7 signature verification not yet implemented.")},addCertificate:function(r){if(typeof r==="string")r=H.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 s=e.signers[i],a=s.digestAlgorithm;if(!(a in r))r[a]=H.md[H.pki.oids[a]].create();if(s.authenticatedAttributes.length===0)s.md=r[a];else s.md=H.md[H.pki.oids[a]].create()}e.digestAlgorithmIdentifiers=[];for(var a in r)e.digestAlgorithmIdentifiers.push(E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.OID,!1,E.oidToDer(a).getBytes()),E.create(E.Class.UNIVERSAL,E.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 s=E.derToOid(e.contentInfo.value[0].value),a=E.toDer(i);a.getByte(),E.getBerValueLength(a),a=a.getBytes();for(var o in r)r[o].start().update(a);var l=new Date;for(var c=0;c<e.signers.length;++c){var u=e.signers[c];if(u.authenticatedAttributes.length===0){if(s!==H.pki.oids.data)throw Error("Invalid signer; authenticatedAttributes must be present when the ContentInfo content type is not PKCS#7 Data.")}else{u.authenticatedAttributesAsn1=E.create(E.Class.CONTEXT_SPECIFIC,0,!0,[]);var d=E.create(E.Class.UNIVERSAL,E.Type.SET,!0,[]);for(var p=0;p<u.authenticatedAttributes.length;++p){var h=u.authenticatedAttributes[p];if(h.type===H.pki.oids.messageDigest)h.value=r[u.digestAlgorithm].digest();else if(h.type===H.pki.oids.signingTime){if(!h.value)h.value=l}d.value.push(ll(h)),u.authenticatedAttributesAsn1.value.push(ll(h))}a=E.toDer(d).getBytes(),u.md.start().update(a)}u.signature=u.key.sign(u.md,"RSASSA-PKCS1-V1_5")}e.signerInfos=uv(e.signers)}};Et.createEncryptedData=function(){var e=null;return e={type:H.pki.oids.encryptedData,version:0,encryptedContent:{algorithm:H.pki.oids["aes256-CBC"]},fromAsn1:function(t){cl(e,t,Et.asn1.encryptedDataValidator)},decrypt:function(t){if(t!==void 0)e.encryptedContent.key=t;Zd(e)}},e};Et.createEnvelopedData=function(){var e=null;return e={type:H.pki.oids.envelopedData,version:0,recipients:[],encryptedContent:{algorithm:H.pki.oids["aes256-CBC"]},fromAsn1:function(t){var n=cl(e,t,Et.asn1.envelopedDataValidator);e.recipients=ov(n.recipientInfos.value)},toAsn1:function(){return E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.OID,!1,E.oidToDer(e.type).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.INTEGER,!1,E.integerToDer(e.version).getBytes()),E.create(E.Class.UNIVERSAL,E.Type.SET,!0,lv(e.recipients)),E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,dv(e.encryptedContent))])])])},findRecipient:function(t){var n=t.issuer.attributes;for(var r=0;r<e.recipients.length;++r){var i=e.recipients[r],s=i.issuer;if(i.serialNumber!==t.serialNumber)continue;if(s.length!==n.length)continue;var a=!0;for(var o=0;o<n.length;++o)if(s[o].type!==n[o].type||s[o].value!==n[o].value){a=!1;break}if(a)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 H.pki.oids.rsaEncryption:case H.pki.oids.desCBC:var r=n.decrypt(t.encryptedContent.content);e.encryptedContent.key=H.util.createBuffer(r);break;default:throw Error("Unsupported asymmetric cipher, OID "+t.encryptedContent.algorithm)}Zd(e)},addRecipient:function(t){e.recipients.push({version:0,issuer:t.issuer.attributes,serialNumber:t.serialNumber,encryptedContent:{algorithm:H.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,s;switch(n){case H.pki.oids["aes128-CBC"]:r=16,i=16,s=H.aes.createEncryptionCipher;break;case H.pki.oids["aes192-CBC"]:r=24,i=16,s=H.aes.createEncryptionCipher;break;case H.pki.oids["aes256-CBC"]:r=32,i=16,s=H.aes.createEncryptionCipher;break;case H.pki.oids["des-EDE3-CBC"]:r=24,i=8,s=H.des.createEncryptionCipher;break;default:throw Error("Unsupported symmetric cipher, OID "+n)}if(t===void 0)t=H.util.createBuffer(H.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=H.util.createBuffer(H.random.getBytes(i));var a=s(t);if(a.start(e.encryptedContent.parameter.copy()),a.update(e.content),!a.finish())throw Error("Symmetric encryption failed.");e.encryptedContent.content=a.output}for(var o=0;o<e.recipients.length;++o){var l=e.recipients[o];if(l.encryptedContent.content!==void 0)continue;switch(l.encryptedContent.algorithm){case H.pki.oids.rsaEncryption:l.encryptedContent.content=l.encryptedContent.key.encrypt(e.encryptedContent.key.data);break;default:throw Error("Unsupported asymmetric cipher, OID "+l.encryptedContent.algorithm)}}}},e};function sv(e){var t={},n=[];if(!E.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:H.pki.RDNAttributesAsArray(t.issuer),serialNumber:H.util.createBuffer(t.serial).toHex(),encryptedContent:{algorithm:E.derToOid(t.encAlgorithm),parameter:t.encParameter?t.encParameter.value:void 0,content:t.encKey}}}function av(e){return E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.INTEGER,!1,E.integerToDer(e.version).getBytes()),E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[H.pki.distinguishedNameToAsn1({attributes:e.issuer}),E.create(E.Class.UNIVERSAL,E.Type.INTEGER,!1,H.util.hexToBytes(e.serialNumber))]),E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.OID,!1,E.oidToDer(e.encryptedContent.algorithm).getBytes()),E.create(E.Class.UNIVERSAL,E.Type.NULL,!1,"")]),E.create(E.Class.UNIVERSAL,E.Type.OCTETSTRING,!1,e.encryptedContent.content)])}function ov(e){var t=[];for(var n=0;n<e.length;++n)t.push(sv(e[n]));return t}function lv(e){var t=[];for(var n=0;n<e.length;++n)t.push(av(e[n]));return t}function cv(e){var t=E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.INTEGER,!1,E.integerToDer(e.version).getBytes()),E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[H.pki.distinguishedNameToAsn1({attributes:e.issuer}),E.create(E.Class.UNIVERSAL,E.Type.INTEGER,!1,H.util.hexToBytes(e.serialNumber))]),E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.OID,!1,E.oidToDer(e.digestAlgorithm).getBytes()),E.create(E.Class.UNIVERSAL,E.Type.NULL,!1,"")])]);if(e.authenticatedAttributesAsn1)t.value.push(e.authenticatedAttributesAsn1);if(t.value.push(E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.OID,!1,E.oidToDer(e.signatureAlgorithm).getBytes()),E.create(E.Class.UNIVERSAL,E.Type.NULL,!1,"")])),t.value.push(E.create(E.Class.UNIVERSAL,E.Type.OCTETSTRING,!1,e.signature)),e.unauthenticatedAttributes.length>0){var n=E.create(E.Class.CONTEXT_SPECIFIC,1,!0,[]);for(var r=0;r<e.unauthenticatedAttributes.length;++r){var i=e.unauthenticatedAttributes[r];n.values.push(ll(i))}t.value.push(n)}return t}function uv(e){var t=[];for(var n=0;n<e.length;++n)t.push(cv(e[n]));return t}function ll(e){var t;if(e.type===H.pki.oids.contentType)t=E.create(E.Class.UNIVERSAL,E.Type.OID,!1,E.oidToDer(e.value).getBytes());else if(e.type===H.pki.oids.messageDigest)t=E.create(E.Class.UNIVERSAL,E.Type.OCTETSTRING,!1,e.value.bytes());else if(e.type===H.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 s=Date.parse(i);if(!isNaN(s))i=new Date(s);else if(i.length===13)i=E.utcTimeToDate(i);else i=E.generalizedTimeToDate(i)}if(i>=n&&i<r)t=E.create(E.Class.UNIVERSAL,E.Type.UTCTIME,!1,E.dateToUtcTime(i));else t=E.create(E.Class.UNIVERSAL,E.Type.GENERALIZEDTIME,!1,E.dateToGeneralizedTime(i))}return E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.OID,!1,E.oidToDer(e.type).getBytes()),E.create(E.Class.UNIVERSAL,E.Type.SET,!0,[t])])}function dv(e){return[E.create(E.Class.UNIVERSAL,E.Type.OID,!1,E.oidToDer(H.pki.oids.data).getBytes()),E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.OID,!1,E.oidToDer(e.algorithm).getBytes()),!e.parameter?void 0:E.create(E.Class.UNIVERSAL,E.Type.OCTETSTRING,!1,e.parameter.getBytes())]),E.create(E.Class.CONTEXT_SPECIFIC,0,!0,[E.create(E.Class.UNIVERSAL,E.Type.OCTETSTRING,!1,e.content.getBytes())])]}function cl(e,t,n){var r={},i=[];if(!E.validate(t,n,r,i)){var s=Error("Cannot read PKCS#7 message. ASN.1 object is not a supported PKCS#7 message.");throw s.errors=s,s}var a=E.derToOid(r.contentType);if(a!==H.pki.oids.data)throw Error("Unsupported PKCS#7 message. Only wrapped ContentType Data supported.");if(r.encryptedContent){var o="";if(H.util.isArray(r.encryptedContent))for(var l=0;l<r.encryptedContent.length;++l){if(r.encryptedContent[l].type!==E.Type.OCTETSTRING)throw Error("Malformed PKCS#7 message, expecting encrypted content constructed of only OCTET STRING objects.");o+=r.encryptedContent[l].value}else o=r.encryptedContent;e.encryptedContent={algorithm:E.derToOid(r.encAlgorithm),parameter:H.util.createBuffer(r.encParameter.value),content:H.util.createBuffer(o)}}if(r.content){var o="";if(H.util.isArray(r.content))for(var l=0;l<r.content.length;++l){if(r.content[l].type!==E.Type.OCTETSTRING)throw Error("Malformed PKCS#7 message, expecting content constructed of only OCTET STRING objects.");o+=r.content[l].value}else o=r.content;e.content=H.util.createBuffer(o)}return e.version=r.version.charCodeAt(0),e.rawCapture=r,r}function Zd(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 H.pki.oids["aes128-CBC"]:case H.pki.oids["aes192-CBC"]:case H.pki.oids["aes256-CBC"]:t=H.aes.createDecryptionCipher(e.encryptedContent.key);break;case H.pki.oids.desCBC:case H.pki.oids["des-EDE3-CBC"]:t=H.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 nf=de(function(q1,rf){var it=ve();Lr();An();Ls();Rn();Pe();var sa=rf.exports=it.ssh=it.ssh||{};sa.privateKeyToPutty=function(e,t,n){n=n||"",t=t||"";var r="ssh-rsa",i=t===""?"none":"aes256-cbc",s="PuTTY-User-Key-File-2: "+r+`\r
19
+ `)Z.push(b+1);Z.push(b);for(var pe=0;pe<Z.length;++pe){var ge=Z[pe],Me=R?l(ge+1,k):-1,ve=k;if(Me===-1&&I)Me=I.blank,ve=I.end;if(Me!==-1&&Me<=x){var Oe=o(Me);return v=ve+14+A.length,[e.substring(S,v),A,e.substring(ge,Oe),e.substring(Oe,ve)]}if(R&&ge<k)return v=k+14+A.length,[e.substring(S,v),A,void 0,e.substring(ge,k)]}}return null}}}});var Si=de(function(m1,xu){var je=ye();ks();po();Ne();xu.exports=je.des=je.des||{};je.des.startEncrypting=function(e,t,n,r){var i=Vs({key:e,output:n,decrypt:!1,mode:r||(t===null?"ECB":"CBC")});return i.start(t),i};je.des.createEncryptionCipher=function(e,t){return Vs({key:e,output:null,decrypt:!1,mode:t})};je.des.startDecrypting=function(e,t,n,r){var i=Vs({key:e,output:n,decrypt:!0,mode:r||(t===null?"ECB":"CBC")});return i.start(t),i};je.des.createDecryptionCipher=function(e,t){return Vs({key:e,output:null,decrypt:!0,mode:t})};je.des.Algorithm=function(e,t){var n=this;n.name=e,n.mode=new t({blockSize:8,cipher:{encrypt:function(r,i){return vu(n._keys,r,i,!1)},decrypt:function(r,i){return vu(n._keys,r,i,!0)}}}),n._init=!1};je.des.Algorithm.prototype.initialize=function(e){if(this._init)return;var t=je.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=H0(t),this._init=!0};ir("DES-ECB",je.cipher.modes.ecb);ir("DES-CBC",je.cipher.modes.cbc);ir("DES-CFB",je.cipher.modes.cfb);ir("DES-OFB",je.cipher.modes.ofb);ir("DES-CTR",je.cipher.modes.ctr);ir("3DES-ECB",je.cipher.modes.ecb);ir("3DES-CBC",je.cipher.modes.cbc);ir("3DES-CFB",je.cipher.modes.cfb);ir("3DES-OFB",je.cipher.modes.ofb);ir("3DES-CTR",je.cipher.modes.ctr);function ir(e,t){var n=function(){return new je.des.Algorithm(e,t)};je.cipher.registerAlgorithm(e,n)}var L0=[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],O0=[-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],U0=[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],V0=[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],F0=[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],M0=[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],$0=[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],W0=[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 H0(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],s=[0,262144,16,262160,0,262144,16,262160,4096,266240,4112,266256,4096,266240,4112,266256],a=[0,1024,32,1056,0,1024,32,1056,33554432,33555456,33554464,33555488,33554432,33555456,33554464,33555488],o=[0,268435456,524288,268959744,2,268435458,524290,268959746,0,268435456,524288,268959744,2,268435458,524290,268959746],l=[0,65536,2048,67584,536870912,536936448,536872960,536938496,131072,196608,133120,198656,537001984,537067520,537004032,537069568],c=[0,262144,0,262144,2,262146,2,262146,33554432,33816576,33554432,33816576,33554434,33816578,33554434,33816578],u=[0,268435456,8,268435464,0,268435456,8,268435464,1024,268436480,1032,268436488,1024,268436480,1032,268436488],d=[0,32,0,32,1048576,1048608,1048576,1048608,8192,8224,8192,8224,1056768,1056800,1056768,1056800],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],f=[0,4,256,260,0,4,256,260,1,5,257,261,1,5,257,261],v=e.length()>8?3:1,x=[],S=[0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0],A=0,b;for(var k=0;k<v;k++){var R=e.getInt32(),I=e.getInt32();b=(R>>>4^I)&252645135,I^=b,R^=b<<4,b=(I>>>-16^R)&65535,R^=b,I^=b<<-16,b=(R>>>2^I)&858993459,I^=b,R^=b<<2,b=(I>>>-16^R)&65535,R^=b,I^=b<<-16,b=(R>>>1^I)&1431655765,I^=b,R^=b<<1,b=(I>>>8^R)&16711935,R^=b,I^=b<<8,b=(R>>>1^I)&1431655765,I^=b,R^=b<<1,b=R<<8|I>>>20&240,R=I<<24|I<<8&16711680|I>>>8&65280|I>>>24&240,I=b;for(var V=0;V<S.length;++V){if(S[V])R=R<<2|R>>>26,I=I<<2|I>>>26;else R=R<<1|R>>>27,I=I<<1|I>>>27;R&=-15,I&=-15;var J=t[R>>>28]|n[R>>>24&15]|r[R>>>20&15]|i[R>>>16&15]|s[R>>>12&15]|a[R>>>8&15]|o[R>>>4&15],D=l[I>>>28]|c[I>>>24&15]|u[I>>>20&15]|d[I>>>16&15]|p[I>>>12&15]|h[I>>>8&15]|f[I>>>4&15];b=(D>>>16^J)&65535,x[A++]=J^b,x[A++]=D^b<<16}}return x}function vu(e,t,n,r){var i=e.length===32?3:9,s;if(i===3)s=r?[30,-2,-2]:[0,32,2];else s=r?[94,62,-2,32,64,2,30,-2,-2]:[0,32,2,62,30,-2,64,96,2];var a,o=t[0],l=t[1];a=(o>>>4^l)&252645135,l^=a,o^=a<<4,a=(o>>>16^l)&65535,l^=a,o^=a<<16,a=(l>>>2^o)&858993459,o^=a,l^=a<<2,a=(l>>>8^o)&16711935,o^=a,l^=a<<8,a=(o>>>1^l)&1431655765,l^=a,o^=a<<1,o=o<<1|o>>>31,l=l<<1|l>>>31;for(var c=0;c<i;c+=3){var u=s[c+1],d=s[c+2];for(var p=s[c];p!=u;p+=d){var h=l^e[p],f=(l>>>4|l<<28)^e[p+1];a=o,o=l,l=a^(O0[h>>>24&63]|V0[h>>>16&63]|M0[h>>>8&63]|W0[h&63]|L0[f>>>24&63]|U0[f>>>16&63]|F0[f>>>8&63]|$0[f&63])}a=o,o=l,l=a}o=o>>>1|o<<31,l=l>>>1|l<<31,a=(o>>>1^l)&1431655765,l^=a,o^=a<<1,a=(l>>>8^o)&16711935,o^=a,l^=a<<8,a=(l>>>2^o)&858993459,o^=a,l^=a<<2,a=(o>>>16^l)&65535,l^=a,o^=a<<16,a=(o>>>4^l)&252645135,l^=a,o^=a<<4,n[0]=o,n[1]=l}function Vs(e){e=e||{};var t=(e.mode||"CBC").toUpperCase(),n="DES-"+t,r;if(e.decrypt)r=je.cipher.createDecipher(n,e.key);else r=je.cipher.createCipher(n,e.key);var i=r.start;return r.start=function(s,a){var o=null;if(a instanceof je.util.ByteBuffer)o=a,a={};a=a||{},a.output=o,a.iv=s,i.call(r,a)},r}});var Fs=de(function(y1,Su){var Ct=ye();An();rr();Ne();var K0=Ct.pkcs5=Ct.pkcs5||{},Sr;if(Ct.util.isNodejs&&!Ct.options.usePureJavaScript)Sr=ui("crypto");Su.exports=Ct.pbkdf2=K0.pbkdf2=function(e,t,n,r,i,s){if(typeof i==="function")s=i,i=null;if(Ct.util.isNodejs&&!Ct.options.usePureJavaScript&&Sr.pbkdf2&&(i===null||typeof i!=="object")&&(Sr.pbkdf2Sync.length>4||(!i||i==="sha1"))){if(typeof i!=="string")i="sha1";if(e=Buffer.from(e,"binary"),t=Buffer.from(t,"binary"),!s){if(Sr.pbkdf2Sync.length===4)return Sr.pbkdf2Sync(e,t,n,r).toString("binary");return Sr.pbkdf2Sync(e,t,n,r,i).toString("binary")}if(Sr.pbkdf2Sync.length===4)return Sr.pbkdf2(e,t,n,r,function(b,k){if(b)return s(b);s(null,k.toString("binary"))});return Sr.pbkdf2(e,t,n,r,i,function(b,k){if(b)return s(b);s(null,k.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 a=i.digestLength;if(r>4294967295*a){var o=Error("Derived key is too long.");if(s)return s(o);throw o}var l=Math.ceil(r/a),c=r-(l-1)*a,u=Ct.hmac.create();u.start(i,e);var d="",p,h,f;if(!s){for(var v=1;v<=l;++v){u.start(null,null),u.update(t),u.update(Ct.util.int32ToBytes(v)),p=f=u.digest().getBytes();for(var x=2;x<=n;++x)u.start(null,null),u.update(f),h=u.digest().getBytes(),p=Ct.util.xorBytes(p,h,a),f=h;d+=v<l?p:p.substr(0,c)}return d}var v=1,x;function S(){if(v>l)return s(null,d);u.start(null,null),u.update(t),u.update(Ct.util.int32ToBytes(v)),p=f=u.digest().getBytes(),x=2,A()}function A(){if(x<=n)return u.start(null,null),u.update(f),h=u.digest().getBytes(),p=Ct.util.xorBytes(p,h,a),f=h,++x,Ct.util.setImmediate(A);d+=v<l?p:p.substr(0,c),++v,S()}S()}});var So=de(function(v1,Tu){var sr=ye();rr();Ne();var Cu=Tu.exports=sr.sha256=sr.sha256||{};sr.md.sha256=sr.md.algorithms.sha256=Cu;Cu.create=function(){if(!wu)q0();var e=null,t=sr.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 s=0;s<i;++s)r.fullMessageLength.push(0);return t=sr.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,s){if(s==="utf8")i=sr.util.encodeUtf8(i);var a=i.length;r.messageLength+=a,a=[a/4294967296>>>0,a>>>0];for(var o=r.fullMessageLength.length-1;o>=0;--o)r.fullMessageLength[o]+=a[1],a[1]=a[0]+(r.fullMessageLength[o]/4294967296>>>0),r.fullMessageLength[o]=r.fullMessageLength[o]>>>0,a[0]=a[1]/4294967296>>>0;if(t.putBytes(i),bu(e,n,t),t.read>2048||t.length()===0)t.compact();return r},r.digest=function(){var i=sr.util.createBuffer();i.putBytes(t.bytes());var s=r.fullMessageLength[r.fullMessageLength.length-1]+r.messageLengthSize,a=s&r.blockLength-1;i.putBytes(xo.substr(0,r.blockLength-a));var o,l,c=r.fullMessageLength[0]*8;for(var u=0;u<r.fullMessageLength.length-1;++u)o=r.fullMessageLength[u+1]*8,l=o/4294967296>>>0,c+=l,i.putInt32(c>>>0),c=o>>>0;i.putInt32(c);var d={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3,h4:e.h4,h5:e.h5,h6:e.h6,h7:e.h7};bu(d,n,i);var p=sr.util.createBuffer();return p.putInt32(d.h0),p.putInt32(d.h1),p.putInt32(d.h2),p.putInt32(d.h3),p.putInt32(d.h4),p.putInt32(d.h5),p.putInt32(d.h6),p.putInt32(d.h7),p},r};var xo=null,wu=!1,Eu=null;function q0(){xo=String.fromCharCode(128),xo+=sr.util.fillString(String.fromCharCode(0),64),Eu=[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],wu=!0}function bu(e,t,n){var r,i,s,a,o,l,c,u,d,p,h,f,v,x,S,A=n.length();while(A>=64){for(c=0;c<16;++c)t[c]=n.getInt32();for(;c<64;++c)r=t[c-2],r=(r>>>17|r<<15)^(r>>>19|r<<13)^r>>>10,i=t[c-15],i=(i>>>7|i<<25)^(i>>>18|i<<14)^i>>>3,t[c]=r+t[c-7]+i+t[c-16]|0;u=e.h0,d=e.h1,p=e.h2,h=e.h3,f=e.h4,v=e.h5,x=e.h6,S=e.h7;for(c=0;c<64;++c)a=(f>>>6|f<<26)^(f>>>11|f<<21)^(f>>>25|f<<7),o=x^f&(v^x),s=(u>>>2|u<<30)^(u>>>13|u<<19)^(u>>>22|u<<10),l=u&d|p&(u^d),r=S+a+o+Eu[c]+t[c],i=s+l,S=x,x=v,v=f,f=h+r>>>0,h=p,p=d,d=u,u=r+i>>>0;e.h0=e.h0+u|0,e.h1=e.h1+d|0,e.h2=e.h2+p|0,e.h3=e.h3+h|0,e.h4=e.h4+f|0,e.h5=e.h5+v|0,e.h6=e.h6+x|0,e.h7=e.h7+S|0,A-=64}}});var bo=de(function(x1,Au){var ar=ye();Ne();var Ms=null;if(ar.util.isNodejs&&!ar.options.usePureJavaScript&&!process.versions["node-webkit"])Ms=ui("crypto");var G0=Au.exports=ar.prng=ar.prng||{};G0.create=function(e){var t={plugin:e,key:null,seed:null,time:null,reseeds:0,generated:0,keyBytes:""},n=e.md,r=Array(32);for(var i=0;i<32;++i)r[i]=n.create();t.pools=r,t.pool=0,t.generate=function(c,u){if(!u)return t.generateSync(c);var d=t.plugin.cipher,p=t.plugin.increment,h=t.plugin.formatKey,f=t.plugin.formatSeed,v=ar.util.createBuffer();t.key=null,x();function x(S){if(S)return u(S);if(v.length()>=c)return u(null,v.getBytes(c));if(t.generated>1048575)t.key=null;if(t.key===null)return ar.util.nextTick(function(){s(x)});var A=d(t.key,t.seed);t.generated+=A.length,v.putBytes(A),t.key=h(d(t.key,p(t.seed))),t.seed=f(d(t.key,t.seed)),ar.util.setImmediate(x)}},t.generateSync=function(c){var u=t.plugin.cipher,d=t.plugin.increment,p=t.plugin.formatKey,h=t.plugin.formatSeed;t.key=null;var f=ar.util.createBuffer();while(f.length()<c){if(t.generated>1048575)t.key=null;if(t.key===null)a();var v=u(t.key,t.seed);t.generated+=v.length,f.putBytes(v),t.key=p(u(t.key,d(t.seed))),t.seed=h(u(t.key,t.seed))}return f.getBytes(c)};function s(c){if(t.pools[0].messageLength>=32)return o(),c();var u=32-t.pools[0].messageLength<<5;t.seedFile(u,function(d,p){if(d)return c(d);t.collect(p),o(),c()})}function a(){if(t.pools[0].messageLength>=32)return o();var c=32-t.pools[0].messageLength<<5;t.collect(t.seedFileSync(c)),o()}function o(){t.reseeds=t.reseeds===4294967295?0:t.reseeds+1;var c=t.plugin.md.create();c.update(t.keyBytes);var u=1;for(var d=0;d<32;++d){if(t.reseeds%u===0)c.update(t.pools[d].digest().getBytes()),t.pools[d].start();u=u<<1}t.keyBytes=c.digest().getBytes(),c.start(),c.update(t.keyBytes);var p=c.digest().getBytes();t.key=t.plugin.formatKey(t.keyBytes),t.seed=t.plugin.formatSeed(p),t.generated=0}function l(c){var u=null,d=ar.util.globalScope,p=d.crypto||d.msCrypto;if(p&&p.getRandomValues)u=function(R){return p.getRandomValues(R)};var h=ar.util.createBuffer();if(u)while(h.length()<c){var f=Math.max(1,Math.min(c-h.length(),65536)/4),v=new Uint32Array(Math.floor(f));try{u(v);for(var x=0;x<v.length;++x)h.putInt32(v[x])}catch(R){if(!(typeof QuotaExceededError<"u"&&R instanceof QuotaExceededError))throw R}}if(h.length()<c){var S,A,b,k=Math.floor(Math.random()*65536);while(h.length()<c){A=16807*(k&65535),S=16807*(k>>16),A+=(S&32767)<<16,A+=S>>15,A=(A&2147483647)+(A>>31),k=A&4294967295;for(var x=0;x<3;++x)b=k>>>(x<<3),b^=Math.floor(Math.random()*256),h.putByte(b&255)}}return h.getBytes(c)}if(Ms)t.seedFile=function(c,u){Ms.randomBytes(c,function(d,p){if(d)return u(d);u(null,p.toString())})},t.seedFileSync=function(c){return Ms.randomBytes(c).toString()};else t.seedFile=function(c,u){try{u(null,l(c))}catch(d){u(d)}},t.seedFileSync=l;return t.collect=function(c){var u=c.length;for(var d=0;d<u;++d)t.pools[t.pool].update(c.substr(d,1)),t.pool=t.pool===31?0:t.pool+1},t.collectInt=function(c,u){var d="";for(var p=0;p<u;p+=8)d+=String.fromCharCode(c>>p&255);t.collect(d)},t.registerWorker=function(c){if(c===self)t.seedFile=function(d,p){function h(f){var v=f.data;if(v.forge&&v.forge.prng)self.removeEventListener("message",h),p(v.forge.prng.err,v.forge.prng.bytes)}self.addEventListener("message",h),self.postMessage({forge:{prng:{needed:d}}})};else{var u=function(d){var p=d.data;if(p.forge&&p.forge.prng)t.seedFile(p.forge.prng.needed,function(h,f){c.postMessage({forge:{prng:{err:h,bytes:f}}})})};c.addEventListener("message",u)}},t}});var Lt=de(function(S1,Co){var ft=ye();Lr();So();bo();Ne();(function(){if(ft.random&&ft.random.getBytes){Co.exports=ft.random;return}(function(e){var t={},n=[,,,,],r=ft.util.createBuffer();t.formatKey=function(d){var p=ft.util.createBuffer(d);return d=[,,,,],d[0]=p.getInt32(),d[1]=p.getInt32(),d[2]=p.getInt32(),d[3]=p.getInt32(),ft.aes._expandKey(d,!1)},t.formatSeed=function(d){var p=ft.util.createBuffer(d);return d=[,,,,],d[0]=p.getInt32(),d[1]=p.getInt32(),d[2]=p.getInt32(),d[3]=p.getInt32(),d},t.cipher=function(d,p){return ft.aes._updateBlock(d,p,n,!1),r.putInt32(n[0]),r.putInt32(n[1]),r.putInt32(n[2]),r.putInt32(n[3]),r.getBytes()},t.increment=function(d){return++d[3],d},t.md=ft.md.sha256;function i(){var d=ft.prng.create(t);return d.getBytes=function(p,h){return d.generate(p,h)},d.getBytesSync=function(p){return d.generate(p)},d}var s=i(),a=null,o=ft.util.globalScope,l=o.crypto||o.msCrypto;if(l&&l.getRandomValues)a=function(d){return l.getRandomValues(d)};if(ft.options.usePureJavaScript||!ft.util.isNodejs&&!a){if(typeof window>"u"||window.document===void 0);if(s.collectInt(+new Date,32),typeof navigator<"u"){var c="";for(var u in navigator)try{if(typeof navigator[u]=="string")c+=navigator[u]}catch(d){}s.collect(c),c=null}if(e)e().mousemove(function(d){s.collectInt(d.clientX,16),s.collectInt(d.clientY,16)}),e().keypress(function(d){s.collectInt(d.charCode,8)})}if(!ft.random)ft.random=s;else for(var u in s)ft.random[u]=s[u];ft.random.createInstance=i,Co.exports=ft.random})(typeof jQuery<"u"?jQuery:null)})()});var Eo=de(function(b1,Iu){var At=ye();Ne();var wo=[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],_u=[1,2,3,5],j0=function(e,t){return e<<t&65535|(e&65535)>>16-t},z0=function(e,t){return(e&65535)>>t|e<<16-t&65535};Iu.exports=At.rc2=At.rc2||{};At.rc2.expandKey=function(e,t){if(typeof e==="string")e=At.util.createBuffer(e);t=t||128;var n=e,r=e.length(),i=t,s=Math.ceil(i/8),a=255>>(i&7),o;for(o=r;o<128;o++)n.putByte(wo[n.at(o-1)+n.at(o-r)&255]);n.setAt(128-s,wo[n.at(128-s)&a]);for(o=127-s;o>=0;o--)n.setAt(o,wo[n.at(o+1)^n.at(o+s)]);return n};var ku=function(e,t,n){var r=!1,i=null,s=null,a=null,o,l,c,u,d=[];e=At.rc2.expandKey(e,t);for(c=0;c<64;c++)d.push(e.getInt16Le());if(n)o=function(f){for(c=0;c<4;c++)f[c]+=d[u]+(f[(c+3)%4]&f[(c+2)%4])+(~f[(c+3)%4]&f[(c+1)%4]),f[c]=j0(f[c],_u[c]),u++},l=function(f){for(c=0;c<4;c++)f[c]+=d[f[(c+3)%4]&63]};else o=function(f){for(c=3;c>=0;c--)f[c]=z0(f[c],_u[c]),f[c]-=d[u]+(f[(c+3)%4]&f[(c+2)%4])+(~f[(c+3)%4]&f[(c+1)%4]),u--},l=function(f){for(c=3;c>=0;c--)f[c]-=d[f[(c+3)%4]&63]};var p=function(f){var v=[];for(c=0;c<4;c++){var x=i.getInt16Le();if(a!==null)if(n)x^=a.getInt16Le();else a.putInt16Le(x);v.push(x&65535)}u=n?0:63;for(var S=0;S<f.length;S++)for(var A=0;A<f[S][0];A++)f[S][1](v);for(c=0;c<4;c++){if(a!==null)if(n)a.putInt16Le(v[c]);else v[c]^=a.getInt16Le();s.putInt16Le(v[c])}},h=null;return h={start:function(f,v){if(f){if(typeof f==="string")f=At.util.createBuffer(f)}r=!1,i=At.util.createBuffer(),s=v||new At.util.createBuffer,a=f,h.output=s},update:function(f){if(!r)i.putBuffer(f);while(i.length()>=8)p([[5,o],[1,l],[6,o],[1,l],[5,o]])},finish:function(f){var v=!0;if(n)if(f)v=f(8,i,!n);else{var x=i.length()===8?8:8-i.length();i.fillWithByte(x,x)}if(v)r=!0,h.update();if(!n){if(v=i.length()===0,v)if(f)v=f(8,s,!n);else{var S=s.length(),A=s.at(S-1);if(A>S)v=!1;else s.truncate(A)}}return v}},h};At.rc2.startEncrypting=function(e,t,n){var r=At.rc2.createEncryptionCipher(e,128);return r.start(t,n),r};At.rc2.createEncryptionCipher=function(e,t){return ku(e,t,!0)};At.rc2.startDecrypting=function(e,t,n){var r=At.rc2.createDecryptionCipher(e,128);return r.start(t,n),r};At.rc2.createDecryptionCipher=function(e,t){return ku(e,t,!1)}});var Ci=de(function(C1,Uu){var To=ye();Uu.exports=To.jsbn=To.jsbn||{};var br,X0=244837814094590,Ru=(X0&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)}To.jsbn.BigInteger=L;function Be(){return new L(null)}function Q0(e,t,n,r,i,s){while(--s>=0){var a=t*this.data[e++]+n.data[r]+i;i=Math.floor(a/67108864),n.data[r++]=a&67108863}return i}function Y0(e,t,n,r,i,s){var a=t&32767,o=t>>15;while(--s>=0){var l=this.data[e]&32767,c=this.data[e++]>>15,u=o*l+c*a;l=a*l+((u&32767)<<15)+n.data[r]+(i&1073741823),i=(l>>>30)+(u>>>15)+o*c+(i>>>30),n.data[r++]=l&1073741823}return i}function Bu(e,t,n,r,i,s){var a=t&16383,o=t>>14;while(--s>=0){var l=this.data[e]&16383,c=this.data[e++]>>14,u=o*l+c*a;l=a*l+((u&16383)<<14)+n.data[r]+i,i=(l>>28)+(u>>14)+o*c,n.data[r++]=l&268435455}return i}if(typeof navigator>"u")L.prototype.am=Bu,br=28;else if(Ru&&navigator.appName=="Microsoft Internet Explorer")L.prototype.am=Y0,br=30;else if(Ru&&navigator.appName!="Netscape")L.prototype.am=Q0,br=26;else L.prototype.am=Bu,br=28;L.prototype.DB=br;L.prototype.DM=(1<<br)-1;L.prototype.DV=1<<br;var Ao=52;L.prototype.FV=Math.pow(2,Ao);L.prototype.F1=Ao-br;L.prototype.F2=2*br-Ao;var J0="0123456789abcdefghijklmnopqrstuvwxyz",$s=[],kn,Ot;kn=48;for(Ot=0;Ot<=9;++Ot)$s[kn++]=Ot;kn=97;for(Ot=10;Ot<36;++Ot)$s[kn++]=Ot;kn=65;for(Ot=10;Ot<36;++Ot)$s[kn++]=Ot;function Pu(e){return J0.charAt(e)}function Nu(e,t){var n=$s[e.charCodeAt(t)];return n==null?-1:n}function Z0(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 eg(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 Ur(e){var t=Be();return t.fromInt(e),t}function tg(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,s=0;while(--r>=0){var a=n==8?e[r]&255:Nu(e,r);if(a<0){if(e.charAt(r)=="-")i=!0;continue}if(i=!1,s==0)this.data[this.t++]=a;else if(s+n>this.DB)this.data[this.t-1]|=(a&(1<<this.DB-s)-1)<<s,this.data[this.t++]=a>>this.DB-s;else this.data[this.t-1]|=a<<s;if(s+=n,s>=this.DB)s-=this.DB}if(n==8&&(e[0]&128)!=0){if(this.s=-1,s>0)this.data[this.t-1]|=(1<<this.DB-s)-1<<s}if(this.clamp(),i)L.ZERO.subTo(this,this)}function rg(){var e=this.s&this.DM;while(this.t>0&&this.data[this.t-1]==e)--this.t}function ng(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,s="",a=this.t,o=this.DB-a*this.DB%t;if(a-- >0){if(o<this.DB&&(r=this.data[a]>>o)>0)i=!0,s=Pu(r);while(a>=0){if(o<t)r=(this.data[a]&(1<<o)-1)<<t-o,r|=this.data[--a]>>(o+=this.DB-t);else if(r=this.data[a]>>(o-=t)&n,o<=0)o+=this.DB,--a;if(r>0)i=!0;if(i)s+=Pu(r)}}return i?s:"0"}function ig(){var e=Be();return L.ZERO.subTo(this,e),e}function sg(){return this.s<0?this.negate():this}function ag(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 Ws(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 og(){if(this.t<=0)return 0;return this.DB*(this.t-1)+Ws(this.data[this.t-1]^this.s&this.DM)}function lg(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 cg(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 ug(e,t){var n=e%this.DB,r=this.DB-n,i=(1<<r)-1,s=Math.floor(e/this.DB),a=this.s<<n&this.DM,o;for(o=this.t-1;o>=0;--o)t.data[o+s+1]=this.data[o]>>r|a,a=(this.data[o]&i)<<n;for(o=s-1;o>=0;--o)t.data[o]=0;t.data[s]=a,t.t=this.t+s+1,t.s=this.s,t.clamp()}function dg(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,s=(1<<r)-1;t.data[0]=this.data[n]>>r;for(var a=n+1;a<this.t;++a)t.data[a-n-1]|=(this.data[a]&s)<<i,t.data[a-n]=this.data[a]>>r;if(r>0)t.data[this.t-n-1]|=(this.s&s)<<i;t.t=this.t-n,t.clamp()}function fg(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 pg(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 hg(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 gg(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=Be();var s=Be(),a=this.s,o=e.s,l=this.DB-Ws(r.data[r.t-1]);if(l>0)r.lShiftTo(l,s),i.lShiftTo(l,n);else r.copyTo(s),i.copyTo(n);var c=s.t,u=s.data[c-1];if(u==0)return;var d=u*(1<<this.F1)+(c>1?s.data[c-2]>>this.F2:0),p=this.FV/d,h=(1<<this.F1)/d,f=1<<this.F2,v=n.t,x=v-c,S=t==null?Be():t;if(s.dlShiftTo(x,S),n.compareTo(S)>=0)n.data[n.t++]=1,n.subTo(S,n);L.ONE.dlShiftTo(c,S),S.subTo(s,s);while(s.t<c)s.data[s.t++]=0;while(--x>=0){var A=n.data[--v]==u?this.DM:Math.floor(n.data[v]*p+(n.data[v-1]+f)*h);if((n.data[v]+=s.am(0,A,n,x,0,c))<A){s.dlShiftTo(x,S),n.subTo(S,n);while(n.data[v]<--A)n.subTo(S,n)}}if(t!=null){if(n.drShiftTo(c,t),a!=o)L.ZERO.subTo(t,t)}if(n.t=c,n.clamp(),l>0)n.rShiftTo(l,n);if(a<0)L.ZERO.subTo(n,n)}function mg(e){var t=Be();if(this.abs().divRemTo(e,null,t),this.s<0&&t.compareTo(L.ZERO)>0)e.subTo(t,t);return t}function an(e){this.m=e}function yg(e){if(e.s<0||e.compareTo(this.m)>=0)return e.mod(this.m);else return e}function vg(e){return e}function xg(e){e.divRemTo(this.m,null,e)}function Sg(e,t,n){e.multiplyTo(t,n),this.reduce(n)}function bg(e,t){e.squareTo(t),this.reduce(t)}an.prototype.convert=yg;an.prototype.revert=vg;an.prototype.reduce=xg;an.prototype.mulTo=Sg;an.prototype.sqrTo=bg;function Cg(){if(this.t<1)return 0;var e=this.data[0];if((e&1)==0)return 0;var t=e&3;return t=t*(2-(e&15)*t)&15,t=t*(2-(e&255)*t)&255,t=t*(2-((e&65535)*t&65535))&65535,t=t*(2-e*t%this.DV)%this.DV,t>0?this.DV-t:-t}function on(e){this.m=e,this.mp=e.invDigit(),this.mpl=this.mp&32767,this.mph=this.mp>>15,this.um=(1<<e.DB-15)-1,this.mt2=2*e.t}function wg(e){var t=Be();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 Eg(e){var t=Be();return e.copyTo(t),this.reduce(t),t}function Tg(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 Ag(e,t){e.squareTo(t),this.reduce(t)}function _g(e,t,n){e.multiplyTo(t,n),this.reduce(n)}on.prototype.convert=wg;on.prototype.revert=Eg;on.prototype.reduce=Tg;on.prototype.mulTo=_g;on.prototype.sqrTo=Ag;function kg(){return(this.t>0?this.data[0]&1:this.s)==0}function Ig(e,t){if(e>4294967295||e<1)return L.ONE;var n=Be(),r=Be(),i=t.convert(this),s=Ws(e)-1;i.copyTo(n);while(--s>=0)if(t.sqrTo(n,r),(e&1<<s)>0)t.mulTo(r,i,n);else{var a=n;n=r,r=a}return t.revert(n)}function Rg(e,t){var n;if(e<256||t.isEven())n=new an(t);else n=new on(t);return this.exp(e,n)}L.prototype.copyTo=Z0;L.prototype.fromInt=eg;L.prototype.fromString=tg;L.prototype.clamp=rg;L.prototype.dlShiftTo=lg;L.prototype.drShiftTo=cg;L.prototype.lShiftTo=ug;L.prototype.rShiftTo=dg;L.prototype.subTo=fg;L.prototype.multiplyTo=pg;L.prototype.squareTo=hg;L.prototype.divRemTo=gg;L.prototype.invDigit=Cg;L.prototype.isEven=kg;L.prototype.exp=Ig;L.prototype.toString=ng;L.prototype.negate=ig;L.prototype.abs=sg;L.prototype.compareTo=ag;L.prototype.bitLength=og;L.prototype.mod=mg;L.prototype.modPowInt=Rg;L.ZERO=Ur(0);L.ONE=Ur(1);function Bg(){var e=Be();return this.copyTo(e),e}function Pg(){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 Ng(){return this.t==0?this.s:this.data[0]<<24>>24}function Dg(){return this.t==0?this.s:this.data[0]<<16>>16}function Lg(e){return Math.floor(Math.LN2*this.DB/Math.log(e))}function Og(){if(this.s<0)return-1;else if(this.t<=0||this.t==1&&this.data[0]<=0)return 0;else return 1}function Ug(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=Ur(n),i=Be(),s=Be(),a="";this.divRemTo(r,i,s);while(i.signum()>0)a=(n+s.intValue()).toString(e).substr(1)+a,i.divRemTo(r,i,s);return s.intValue().toString(e)+a}function Vg(e,t){if(this.fromInt(0),t==null)t=10;var n=this.chunkSize(t),r=Math.pow(t,n),i=!1,s=0,a=0;for(var o=0;o<e.length;++o){var l=Nu(e,o);if(l<0){if(e.charAt(o)=="-"&&this.signum()==0)i=!0;continue}if(a=t*a+l,++s>=n)this.dMultiply(r),this.dAddOffset(a,0),s=0,a=0}if(s>0)this.dMultiply(Math.pow(t,s)),this.dAddOffset(a,0);if(i)L.ZERO.subTo(this,this)}function Fg(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),_o,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 Mg(){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 $g(e){return this.compareTo(e)==0}function Wg(e){return this.compareTo(e)<0?this:e}function Hg(e){return this.compareTo(e)>0?this:e}function Kg(e,t,n){var r,i,s=Math.min(e.t,this.t);for(r=0;r<s;++r)n.data[r]=t(this.data[r],e.data[r]);if(e.t<this.t){i=e.s&this.DM;for(r=s;r<this.t;++r)n.data[r]=t(this.data[r],i);n.t=this.t}else{i=this.s&this.DM;for(r=s;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 qg(e,t){return e&t}function Gg(e){var t=Be();return this.bitwiseTo(e,qg,t),t}function _o(e,t){return e|t}function jg(e){var t=Be();return this.bitwiseTo(e,_o,t),t}function Du(e,t){return e^t}function zg(e){var t=Be();return this.bitwiseTo(e,Du,t),t}function Lu(e,t){return e&~t}function Xg(e){var t=Be();return this.bitwiseTo(e,Lu,t),t}function Qg(){var e=Be();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 Yg(e){var t=Be();if(e<0)this.rShiftTo(-e,t);else this.lShiftTo(e,t);return t}function Jg(e){var t=Be();if(e<0)this.lShiftTo(-e,t);else this.rShiftTo(e,t);return t}function Zg(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 em(){for(var e=0;e<this.t;++e)if(this.data[e]!=0)return e*this.DB+Zg(this.data[e]);if(this.s<0)return this.t*this.DB;return-1}function tm(e){var t=0;while(e!=0)e&=e-1,++t;return t}function rm(){var e=0,t=this.s&this.DM;for(var n=0;n<this.t;++n)e+=tm(this.data[n]^t);return e}function nm(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 im(e,t){var n=L.ONE.shiftLeft(e);return this.bitwiseTo(n,t,n),n}function sm(e){return this.changeBit(e,_o)}function am(e){return this.changeBit(e,Lu)}function om(e){return this.changeBit(e,Du)}function lm(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 cm(e){var t=Be();return this.addTo(e,t),t}function um(e){var t=Be();return this.subTo(e,t),t}function dm(e){var t=Be();return this.multiplyTo(e,t),t}function fm(){var e=Be();return this.squareTo(e),e}function pm(e){var t=Be();return this.divRemTo(e,t,null),t}function hm(e){var t=Be();return this.divRemTo(e,null,t),t}function gm(e){var t=Be(),n=Be();return this.divRemTo(e,t,n),[t,n]}function mm(e){this.data[this.t]=this.am(0,e-1,this,0,0,this.t),++this.t,this.clamp()}function ym(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 bi(){}function Ou(e){return e}function vm(e,t,n){e.multiplyTo(t,n)}function xm(e,t){e.squareTo(t)}bi.prototype.convert=Ou;bi.prototype.revert=Ou;bi.prototype.mulTo=vm;bi.prototype.sqrTo=xm;function Sm(e){return this.exp(e,new bi)}function bm(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 Cm(e,t,n){--t;var r=n.t=this.t+e.t-t;n.s=0;while(--r>=0)n.data[r]=0;for(r=Math.max(t-this.t,0);r<e.t;++r)n.data[this.t+r-t]=this.am(t-r,e.data[r],n,0,0,this.t+r-t);n.clamp(),n.drShiftTo(1,n)}function In(e){this.r2=Be(),this.q3=Be(),L.ONE.dlShiftTo(2*e.t,this.r2),this.mu=this.r2.divide(e),this.m=e}function wm(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=Be();return e.copyTo(t),this.reduce(t),t}}function Em(e){return e}function Tm(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 Am(e,t){e.squareTo(t),this.reduce(t)}function _m(e,t,n){e.multiplyTo(t,n),this.reduce(n)}In.prototype.convert=wm;In.prototype.revert=Em;In.prototype.reduce=Tm;In.prototype.mulTo=_m;In.prototype.sqrTo=Am;function km(e,t){var n=e.bitLength(),r,i=Ur(1),s;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)s=new an(t);else if(t.isEven())s=new In(t);else s=new on(t);var a=[],o=3,l=r-1,c=(1<<r)-1;if(a[1]=s.convert(this),r>1){var u=Be();s.sqrTo(a[1],u);while(o<=c)a[o]=Be(),s.mulTo(u,a[o-2],a[o]),o+=2}var d=e.t-1,p,h=!0,f=Be(),v;n=Ws(e.data[d])-1;while(d>=0){if(n>=l)p=e.data[d]>>n-l&c;else if(p=(e.data[d]&(1<<n+1)-1)<<l-n,d>0)p|=e.data[d-1]>>this.DB+n-l;o=r;while((p&1)==0)p>>=1,--o;if((n-=o)<0)n+=this.DB,--d;if(h)a[p].copyTo(i),h=!1;else{while(o>1)s.sqrTo(i,f),s.sqrTo(f,i),o-=2;if(o>0)s.sqrTo(i,f);else v=i,i=f,f=v;s.mulTo(f,a[p],i)}while(d>=0&&(e.data[d]&1<<n)==0)if(s.sqrTo(i,f),v=i,i=f,f=v,--n<0)n=this.DB-1,--d}return s.revert(i)}function Im(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(),s=n.getLowestSetBit();if(s<0)return t;if(i<s)s=i;if(s>0)t.rShiftTo(s,t),n.rShiftTo(s,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(s>0)n.lShiftTo(s,n);return n}function Rm(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 Bm(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=Ur(1),s=Ur(0),a=Ur(0),o=Ur(1);while(n.signum()!=0){while(n.isEven()){if(n.rShiftTo(1,n),t){if(!i.isEven()||!s.isEven())i.addTo(this,i),s.subTo(e,s);i.rShiftTo(1,i)}else if(!s.isEven())s.subTo(e,s);s.rShiftTo(1,s)}while(r.isEven()){if(r.rShiftTo(1,r),t){if(!a.isEven()||!o.isEven())a.addTo(this,a),o.subTo(e,o);a.rShiftTo(1,a)}else if(!o.isEven())o.subTo(e,o);o.rShiftTo(1,o)}if(n.compareTo(r)>=0){if(n.subTo(r,n),t)i.subTo(a,i);s.subTo(o,s)}else{if(r.subTo(n,r),t)a.subTo(i,a);o.subTo(s,o)}}if(r.compareTo(L.ONE)!=0)return L.ZERO;if(o.compareTo(e)>=0)return o.subtract(e);if(o.signum()<0)o.addTo(e,o);else return o;if(o.signum()<0)return o.add(e);else return o}var jt=[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],Pm=67108864/jt[jt.length-1];function Nm(e){var t,n=this.abs();if(n.t==1&&n.data[0]<=jt[jt.length-1]){for(t=0;t<jt.length;++t)if(n.data[0]==jt[t])return!0;return!1}if(n.isEven())return!1;t=1;while(t<jt.length){var r=jt[t],i=t+1;while(i<jt.length&&r<Pm)r*=jt[i++];r=n.modInt(r);while(t<i)if(r%jt[t++]==0)return!1}return n.millerRabin(e)}function Dm(e){var t=this.subtract(L.ONE),n=t.getLowestSetBit();if(n<=0)return!1;var r=t.shiftRight(n),i=Lm(),s;for(var a=0;a<e;++a){do s=new L(this.bitLength(),i);while(s.compareTo(L.ONE)<=0||s.compareTo(t)>=0);var o=s.modPow(r,this);if(o.compareTo(L.ONE)!=0&&o.compareTo(t)!=0){var l=1;while(l++<n&&o.compareTo(t)!=0)if(o=o.modPowInt(2,this),o.compareTo(L.ONE)==0)return!1;if(o.compareTo(t)!=0)return!1}}return!0}function Lm(){return{nextBytes:function(e){for(var t=0;t<e.length;++t)e[t]=Math.floor(Math.random()*256)}}}L.prototype.chunkSize=Lg;L.prototype.toRadix=Ug;L.prototype.fromRadix=Vg;L.prototype.fromNumber=Fg;L.prototype.bitwiseTo=Kg;L.prototype.changeBit=im;L.prototype.addTo=lm;L.prototype.dMultiply=mm;L.prototype.dAddOffset=ym;L.prototype.multiplyLowerTo=bm;L.prototype.multiplyUpperTo=Cm;L.prototype.modInt=Rm;L.prototype.millerRabin=Dm;L.prototype.clone=Bg;L.prototype.intValue=Pg;L.prototype.byteValue=Ng;L.prototype.shortValue=Dg;L.prototype.signum=Og;L.prototype.toByteArray=Mg;L.prototype.equals=$g;L.prototype.min=Wg;L.prototype.max=Hg;L.prototype.and=Gg;L.prototype.or=jg;L.prototype.xor=zg;L.prototype.andNot=Xg;L.prototype.not=Qg;L.prototype.shiftLeft=Yg;L.prototype.shiftRight=Jg;L.prototype.getLowestSetBit=em;L.prototype.bitCount=rm;L.prototype.testBit=nm;L.prototype.setBit=sm;L.prototype.clearBit=am;L.prototype.flipBit=om;L.prototype.add=cm;L.prototype.subtract=um;L.prototype.multiply=dm;L.prototype.divide=pm;L.prototype.remainder=hm;L.prototype.divideAndRemainder=gm;L.prototype.modPow=km;L.prototype.modInverse=Bm;L.prototype.pow=Sm;L.prototype.gcd=Im;L.prototype.isProbablePrime=Nm;L.prototype.square=fm});var Rn=de(function(w1,$u){var or=ye();rr();Ne();var Fu=$u.exports=or.sha1=or.sha1||{};or.md.sha1=or.md.algorithms.sha1=Fu;Fu.create=function(){if(!Mu)Om();var e=null,t=or.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 s=0;s<i;++s)r.fullMessageLength.push(0);return t=or.util.createBuffer(),e={h0:1732584193,h1:4023233417,h2:2562383102,h3:271733878,h4:3285377520},r},r.start(),r.update=function(i,s){if(s==="utf8")i=or.util.encodeUtf8(i);var a=i.length;r.messageLength+=a,a=[a/4294967296>>>0,a>>>0];for(var o=r.fullMessageLength.length-1;o>=0;--o)r.fullMessageLength[o]+=a[1],a[1]=a[0]+(r.fullMessageLength[o]/4294967296>>>0),r.fullMessageLength[o]=r.fullMessageLength[o]>>>0,a[0]=a[1]/4294967296>>>0;if(t.putBytes(i),Vu(e,n,t),t.read>2048||t.length()===0)t.compact();return r},r.digest=function(){var i=or.util.createBuffer();i.putBytes(t.bytes());var s=r.fullMessageLength[r.fullMessageLength.length-1]+r.messageLengthSize,a=s&r.blockLength-1;i.putBytes(ko.substr(0,r.blockLength-a));var o,l,c=r.fullMessageLength[0]*8;for(var u=0;u<r.fullMessageLength.length-1;++u)o=r.fullMessageLength[u+1]*8,l=o/4294967296>>>0,c+=l,i.putInt32(c>>>0),c=o>>>0;i.putInt32(c);var d={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3,h4:e.h4};Vu(d,n,i);var p=or.util.createBuffer();return p.putInt32(d.h0),p.putInt32(d.h1),p.putInt32(d.h2),p.putInt32(d.h3),p.putInt32(d.h4),p},r};var ko=null,Mu=!1;function Om(){ko=String.fromCharCode(128),ko+=or.util.fillString(String.fromCharCode(0),64),Mu=!0}function Vu(e,t,n){var r,i,s,a,o,l,c,u,d=n.length();while(d>=64){i=e.h0,s=e.h1,a=e.h2,o=e.h3,l=e.h4;for(u=0;u<16;++u)r=n.getInt32(),t[u]=r,c=o^s&(a^o),r=(i<<5|i>>>27)+c+l+1518500249+r,l=o,o=a,a=(s<<30|s>>>2)>>>0,s=i,i=r;for(;u<20;++u)r=t[u-3]^t[u-8]^t[u-14]^t[u-16],r=r<<1|r>>>31,t[u]=r,c=o^s&(a^o),r=(i<<5|i>>>27)+c+l+1518500249+r,l=o,o=a,a=(s<<30|s>>>2)>>>0,s=i,i=r;for(;u<32;++u)r=t[u-3]^t[u-8]^t[u-14]^t[u-16],r=r<<1|r>>>31,t[u]=r,c=s^a^o,r=(i<<5|i>>>27)+c+l+1859775393+r,l=o,o=a,a=(s<<30|s>>>2)>>>0,s=i,i=r;for(;u<40;++u)r=t[u-6]^t[u-16]^t[u-28]^t[u-32],r=r<<2|r>>>30,t[u]=r,c=s^a^o,r=(i<<5|i>>>27)+c+l+1859775393+r,l=o,o=a,a=(s<<30|s>>>2)>>>0,s=i,i=r;for(;u<60;++u)r=t[u-6]^t[u-16]^t[u-28]^t[u-32],r=r<<2|r>>>30,t[u]=r,c=s&a|o&(s^a),r=(i<<5|i>>>27)+c+l+2400959708+r,l=o,o=a,a=(s<<30|s>>>2)>>>0,s=i,i=r;for(;u<80;++u)r=t[u-6]^t[u-16]^t[u-28]^t[u-32],r=r<<2|r>>>30,t[u]=r,c=s^a^o,r=(i<<5|i>>>27)+c+l+3395469782+r,l=o,o=a,a=(s<<30|s>>>2)>>>0,s=i,i=r;e.h0=e.h0+i|0,e.h1=e.h1+s|0,e.h2=e.h2+a|0,e.h3=e.h3+o|0,e.h4=e.h4+l|0,d-=64}}});var Io=de(function(E1,Hu){var lr=ye();Ne();Lt();Rn();var Wu=Hu.exports=lr.pkcs1=lr.pkcs1||{};Wu.encode_rsa_oaep=function(e,t,n){var r,i,s,a;if(typeof n==="string")r=n,i=arguments[3]||void 0,s=arguments[4]||void 0;else if(n){if(r=n.label||void 0,i=n.seed||void 0,s=n.md||void 0,n.mgf1&&n.mgf1.md)a=n.mgf1.md}if(!s)s=lr.md.sha1.create();else s.start();if(!a)a=s;var o=Math.ceil(e.n.bitLength()/8),l=o-2*s.digestLength-2;if(t.length>l){var c=Error("RSAES-OAEP input message length is too long.");throw c.length=t.length,c.maxLength=l,c}if(!r)r="";s.update(r,"raw");var u=s.digest(),d="",p=l-t.length;for(var h=0;h<p;h++)d+="\x00";var f=u.getBytes()+d+"\x01"+t;if(!i)i=lr.random.getBytes(s.digestLength);else if(i.length!==s.digestLength){var c=Error("Invalid RSAES-OAEP seed. The seed length must match the digest length.");throw c.seedLength=i.length,c.digestLength=s.digestLength,c}var v=Hs(i,o-s.digestLength-1,a),x=lr.util.xorBytes(f,v,f.length),S=Hs(x,s.digestLength,a),A=lr.util.xorBytes(i,S,i.length);return"\x00"+A+x};Wu.decode_rsa_oaep=function(e,t,n){var r,i,s;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)s=n.mgf1.md}var a=Math.ceil(e.n.bitLength()/8);if(t.length!==a){var x=Error("RSAES-OAEP encoded message length is invalid.");throw x.length=t.length,x.expectedLength=a,x}if(i===void 0)i=lr.md.sha1.create();else i.start();if(!s)s=i;if(a<2*i.digestLength+2)throw Error("RSAES-OAEP key is too short for the hash function.");if(!r)r="";i.update(r,"raw");var o=i.digest().getBytes(),l=t.charAt(0),c=t.substring(1,i.digestLength+1),u=t.substring(1+i.digestLength),d=Hs(u,i.digestLength,s),p=lr.util.xorBytes(c,d,c.length),h=Hs(p,a-i.digestLength-1,s),f=lr.util.xorBytes(u,h,u.length),v=f.substring(0,i.digestLength),x=l!=="\x00";for(var S=0;S<i.digestLength;++S)x|=o.charAt(S)!==v.charAt(S);var A=1,b=i.digestLength;for(var k=i.digestLength;k<f.length;k++){var R=f.charCodeAt(k),I=R&1^1,V=A?65534:0;x|=R&V,A=A&I,b+=A}if(x||f.charCodeAt(b)!==1)throw Error("Invalid RSAES-OAEP padding.");return f.substring(b+1)};function Hs(e,t,n){if(!n)n=lr.md.sha1.create();var r="",i=Math.ceil(t/n.digestLength);for(var s=0;s<i;++s){var a=String.fromCharCode(s>>24&255,s>>16&255,s>>8&255,s&255);n.start(),n.update(e+a),r+=n.digest().getBytes()}return r.substring(0,t)}});var Bo=de(function(T1,Ro){var Vr=ye();Ne();Ci();Lt();(function(){if(Vr.prime){Ro.exports=Vr.prime;return}var e=Ro.exports=Vr.prime=Vr.prime||{},t=Vr.jsbn.BigInteger,n=[6,4,2,4,2,4,6,2],r=new t(null);r.fromInt(30);var i=function(d,p){return d|p};e.generateProbablePrime=function(d,p,h){if(typeof p==="function")h=p,p={};p=p||{};var f=p.algorithm||"PRIMEINC";if(typeof f==="string")f={name:f};f.options=f.options||{};var v=p.prng||Vr.random,x={nextBytes:function(S){var A=v.getBytesSync(S.length);for(var b=0;b<S.length;++b)S[b]=A.charCodeAt(b)}};if(f.name==="PRIMEINC")return s(d,x,f.options,h);throw Error("Invalid prime generation algorithm: "+f.name)};function s(d,p,h,f){if("workers"in h)return l(d,p,h,f);return a(d,p,h,f)}function a(d,p,h,f){var v=c(d,p),x=0,S=u(v.bitLength());if("millerRabinTests"in h)S=h.millerRabinTests;var A=10;if("maxBlockTime"in h)A=h.maxBlockTime;o(v,d,p,x,S,A,f)}function o(d,p,h,f,v,x,S){var A=+new Date;do{if(d.bitLength()>p)d=c(p,h);if(d.isProbablePrime(v))return S(null,d);d.dAddOffset(n[f++%8],0)}while(x<0||+new Date-A<x);Vr.util.setImmediate(function(){o(d,p,h,f,v,x,S)})}function l(d,p,h,f){if(typeof Worker>"u")return a(d,p,h,f);var v=c(d,p),x=h.workers,S=h.workLoad||100,A=S*30/8,b=h.workerScript||"forge/prime.worker.js";if(x===-1)return Vr.util.estimateCores(function(R,I){if(R)I=2;x=I-1,k()});k();function k(){x=Math.max(1,x);var R=[];for(var I=0;I<x;++I)R[I]=new Worker(b);var V=x;for(var I=0;I<x;++I)R[I].addEventListener("message",D);var J=!1;function D(W){if(J)return;--V;var Z=W.data;if(Z.found){for(var pe=0;pe<R.length;++pe)R[pe].terminate();return J=!0,f(null,new t(Z.prime,16))}if(v.bitLength()>d)v=c(d,p);var ge=v.toString(16);W.target.postMessage({hex:ge,workLoad:S}),v.dAddOffset(A,0)}}}function c(d,p){var h=new t(d,p),f=d-1;if(!h.testBit(f))h.bitwiseTo(t.ONE.shiftLeft(f),i,h);return h.dAddOffset(31-h.mod(r).byteValue(),0),h}function u(d){if(d<=100)return 27;if(d<=150)return 18;if(d<=200)return 15;if(d<=250)return 12;if(d<=300)return 9;if(d<=350)return 8;if(d<=400)return 7;if(d<=500)return 6;if(d<=600)return 5;if(d<=800)return 4;if(d<=1250)return 3;return 2}})()});var wi=de(function(A1,Yu){var ne=ye();Gt();Ci();Or();Io();Bo();Lt();Ne();if(typeof ke>"u")ke=ne.jsbn.BigInteger;var ke,Po=ne.util.isNodejs?ui("crypto"):null,{asn1:_,util:Ut}=ne;ne.pki=ne.pki||{};Yu.exports=ne.pki.rsa=ne.rsa=ne.rsa||{};var fe=ne.pki,Um=[6,4,2,4,2,4,6,2],Vm={name:"PrivateKeyInfo",tagClass:_.Class.UNIVERSAL,type:_.Type.SEQUENCE,constructed:!0,value:[{name:"PrivateKeyInfo.version",tagClass:_.Class.UNIVERSAL,type:_.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:_.Class.UNIVERSAL,type:_.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:_.Class.UNIVERSAL,type:_.Type.OID,constructed:!1,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:_.Class.UNIVERSAL,type:_.Type.OCTETSTRING,constructed:!1,capture:"privateKey"}]},Fm={name:"RSAPrivateKey",tagClass:_.Class.UNIVERSAL,type:_.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPrivateKey.version",tagClass:_.Class.UNIVERSAL,type:_.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"RSAPrivateKey.modulus",tagClass:_.Class.UNIVERSAL,type:_.Type.INTEGER,constructed:!1,capture:"privateKeyModulus"},{name:"RSAPrivateKey.publicExponent",tagClass:_.Class.UNIVERSAL,type:_.Type.INTEGER,constructed:!1,capture:"privateKeyPublicExponent"},{name:"RSAPrivateKey.privateExponent",tagClass:_.Class.UNIVERSAL,type:_.Type.INTEGER,constructed:!1,capture:"privateKeyPrivateExponent"},{name:"RSAPrivateKey.prime1",tagClass:_.Class.UNIVERSAL,type:_.Type.INTEGER,constructed:!1,capture:"privateKeyPrime1"},{name:"RSAPrivateKey.prime2",tagClass:_.Class.UNIVERSAL,type:_.Type.INTEGER,constructed:!1,capture:"privateKeyPrime2"},{name:"RSAPrivateKey.exponent1",tagClass:_.Class.UNIVERSAL,type:_.Type.INTEGER,constructed:!1,capture:"privateKeyExponent1"},{name:"RSAPrivateKey.exponent2",tagClass:_.Class.UNIVERSAL,type:_.Type.INTEGER,constructed:!1,capture:"privateKeyExponent2"},{name:"RSAPrivateKey.coefficient",tagClass:_.Class.UNIVERSAL,type:_.Type.INTEGER,constructed:!1,capture:"privateKeyCoefficient"}]},Mm={name:"RSAPublicKey",tagClass:_.Class.UNIVERSAL,type:_.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPublicKey.modulus",tagClass:_.Class.UNIVERSAL,type:_.Type.INTEGER,constructed:!1,capture:"publicKeyModulus"},{name:"RSAPublicKey.exponent",tagClass:_.Class.UNIVERSAL,type:_.Type.INTEGER,constructed:!1,capture:"publicKeyExponent"}]},$m=ne.pki.rsa.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:_.Class.UNIVERSAL,type:_.Type.SEQUENCE,constructed:!0,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:_.Class.UNIVERSAL,type:_.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:_.Class.UNIVERSAL,type:_.Type.OID,constructed:!1,capture:"publicKeyOid"}]},{name:"SubjectPublicKeyInfo.subjectPublicKey",tagClass:_.Class.UNIVERSAL,type:_.Type.BITSTRING,constructed:!1,value:[{name:"SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey",tagClass:_.Class.UNIVERSAL,type:_.Type.SEQUENCE,constructed:!0,optional:!0,captureAsn1:"rsaPublicKey"}]}]},Wm={name:"DigestInfo",tagClass:_.Class.UNIVERSAL,type:_.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm",tagClass:_.Class.UNIVERSAL,type:_.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm.algorithmIdentifier",tagClass:_.Class.UNIVERSAL,type:_.Type.OID,constructed:!1,capture:"algorithmIdentifier"},{name:"DigestInfo.DigestAlgorithm.parameters",tagClass:_.Class.UNIVERSAL,type:_.Type.NULL,capture:"parameters",optional:!0,constructed:!1}]},{name:"DigestInfo.digest",tagClass:_.Class.UNIVERSAL,type:_.Type.OCTETSTRING,constructed:!1,capture:"digest"}]},Ku=function(e,t,n){var r=[_.create(_.Class.UNIVERSAL,_.Type.OID,!1,_.oidToDer(e).getBytes())];if(n)r.push(_.create(_.Class.UNIVERSAL,_.Type.NULL,!1,""));return _.toDer(_.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[_.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,r),_.create(_.Class.UNIVERSAL,_.Type.OCTETSTRING,!1,t)])).getBytes()},Hm=function(e){var t;if(e.algorithm in fe.oids)t=fe.oids[e.algorithm];else{var n=Error("Unknown message digest algorithm.");throw n.algorithm=e.algorithm,n}var r=_.oidToDer(t).getBytes(),i=_.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[]),s=_.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[]);s.value.push(_.create(_.Class.UNIVERSAL,_.Type.OID,!1,r)),s.value.push(_.create(_.Class.UNIVERSAL,_.Type.NULL,!1,""));var a=_.create(_.Class.UNIVERSAL,_.Type.OCTETSTRING,!1,e.digest().getBytes());return i.value.push(s),i.value.push(a),_.toDer(i).getBytes()},Xu=function(e,t,n){if(n)return e.modPow(t.e,t.n);if(!t.p||!t.q)return e.modPow(t.d,t.n);if(!t.dP)t.dP=t.d.mod(t.p.subtract(ke.ONE));if(!t.dQ)t.dQ=t.d.mod(t.q.subtract(ke.ONE));if(!t.qInv)t.qInv=t.q.modInverse(t.p);var r;do r=new ke(ne.util.bytesToHex(ne.random.getBytes(t.n.bitLength()/8)),16);while(r.compareTo(t.n)>=0||!r.gcd(t.n).equals(ke.ONE));e=e.multiply(r.modPow(t.e,t.n)).mod(t.n);var i=e.mod(t.p).modPow(t.dP,t.p),s=e.mod(t.q).modPow(t.dQ,t.q);while(i.compareTo(s)<0)i=i.add(t.p);var a=i.subtract(s).multiply(t.qInv).mod(t.p).multiply(t.q).add(s);return a=a.multiply(r.modInverse(t.n)).mod(t.n),a};fe.rsa.encrypt=function(e,t,n){var r=n,i,s=Math.ceil(t.n.bitLength()/8);if(n!==!1&&n!==!0)r=n===2,i=Qu(e,t,n);else i=ne.util.createBuffer(),i.putBytes(e);var a=new ke(i.toHex(),16),o=Xu(a,t,r),l=o.toString(16),c=ne.util.createBuffer(),u=s-Math.ceil(l.length/2);while(u>0)c.putByte(0),--u;return c.putBytes(ne.util.hexToBytes(l)),c.getBytes()};fe.rsa.decrypt=function(e,t,n,r){var i=Math.ceil(t.n.bitLength()/8);if(e.length!==i){var s=Error("Encrypted message length is invalid.");throw s.length=e.length,s.expected=i,s}var a=new ke(ne.util.createBuffer(e).toHex(),16);if(a.compareTo(t.n)>=0)throw Error("Encrypted message is invalid.");var o=Xu(a,t,n),l=o.toString(16),c=ne.util.createBuffer(),u=i-Math.ceil(l.length/2);while(u>0)c.putByte(0),--u;if(c.putBytes(ne.util.hexToBytes(l)),r!==!1)return Ks(c.getBytes(),t,n);return c.getBytes()};fe.rsa.createKeyPairGenerationState=function(e,t,n){if(typeof e==="string")e=parseInt(e,10);e=e||2048,n=n||{};var r=n.prng||ne.random,i={nextBytes:function(o){var l=r.getBytesSync(o.length);for(var c=0;c<o.length;++c)o[c]=l.charCodeAt(c)}},s=n.algorithm||"PRIMEINC",a;if(s==="PRIMEINC")a={algorithm:s,state:0,bits:e,rng:i,eInt:t||65537,e:new ke(null),p:null,q:null,qBits:e>>1,pBits:e-(e>>1),pqState:0,num:null,keys:null},a.e.fromInt(a.eInt);else throw Error("Invalid key generation algorithm: "+s);return a};fe.rsa.stepKeyPairGenerationState=function(e,t){if(!("algorithm"in e))e.algorithm="PRIMEINC";var n=new ke(null);n.fromInt(30);var r=0,i=function(d,p){return d|p},s=+new Date,a,o=0;while(e.keys===null&&(t<=0||o<t)){if(e.state===0){var l=e.p===null?e.pBits:e.qBits,c=l-1;if(e.pqState===0){if(e.num=new ke(l,e.rng),!e.num.testBit(c))e.num.bitwiseTo(ke.ONE.shiftLeft(c),i,e.num);e.num.dAddOffset(31-e.num.mod(n).byteValue(),0),r=0,++e.pqState}else if(e.pqState===1)if(e.num.bitLength()>l)e.pqState=0;else if(e.num.isProbablePrime(qm(e.num.bitLength())))++e.pqState;else e.num.dAddOffset(Um[r++%8],0);else if(e.pqState===2)e.pqState=e.num.subtract(ke.ONE).gcd(e.e).compareTo(ke.ONE)===0?3:0;else if(e.pqState===3){if(e.pqState=0,e.p===null)e.p=e.num;else e.q=e.num;if(e.p!==null&&e.q!==null)++e.state;e.num=null}}else if(e.state===1){if(e.p.compareTo(e.q)<0)e.num=e.p,e.p=e.q,e.q=e.num;++e.state}else if(e.state===2)e.p1=e.p.subtract(ke.ONE),e.q1=e.q.subtract(ke.ONE),e.phi=e.p1.multiply(e.q1),++e.state;else if(e.state===3)if(e.phi.gcd(e.e).compareTo(ke.ONE)===0)++e.state;else e.p=null,e.q=null,e.state=0;else if(e.state===4)if(e.n=e.p.multiply(e.q),e.n.bitLength()===e.bits)++e.state;else e.q=null,e.state=0;else if(e.state===5){var u=e.e.modInverse(e.phi);e.keys={privateKey:fe.rsa.setPrivateKey(e.n,e.e,u,e.p,e.q,u.mod(e.p1),u.mod(e.q1),e.q.modInverse(e.p)),publicKey:fe.rsa.setPublicKey(e.n,e.e)}}a=+new Date,o+=a-s,s=a}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(qu("generateKeyPair"))return Po.generateKeyPair("rsa",{modulusLength:e,publicExponent:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}},function(o,l,c){if(o)return r(o);r(null,{privateKey:fe.privateKeyFromPem(c),publicKey:fe.publicKeyFromPem(l)})});if(Gu("generateKey")&&Gu("exportKey"))return Ut.globalScope.crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:zu(t),hash:{name:"SHA-256"}},!0,["sign","verify"]).then(function(o){return Ut.globalScope.crypto.subtle.exportKey("pkcs8",o.privateKey)}).then(void 0,function(o){r(o)}).then(function(o){if(o){var l=fe.privateKeyFromAsn1(_.fromDer(ne.util.createBuffer(o)));r(null,{privateKey:l,publicKey:fe.setRsaPublicKey(l.n,l.e)})}});if(ju("generateKey")&&ju("exportKey")){var i=Ut.globalScope.msCrypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:zu(t),hash:{name:"SHA-256"}},!0,["sign","verify"]);i.oncomplete=function(o){var l=o.target.result,c=Ut.globalScope.msCrypto.subtle.exportKey("pkcs8",l.privateKey);c.oncomplete=function(u){var d=u.target.result,p=fe.privateKeyFromAsn1(_.fromDer(ne.util.createBuffer(d)));r(null,{privateKey:p,publicKey:fe.setRsaPublicKey(p.n,p.e)})},c.onerror=function(u){r(u)}},i.onerror=function(o){r(o)};return}}else if(qu("generateKeyPairSync")){var s=Po.generateKeyPairSync("rsa",{modulusLength:e,publicExponent:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{privateKey:fe.privateKeyFromPem(s.privateKey),publicKey:fe.publicKeyFromPem(s.publicKey)}}}var a=fe.rsa.createKeyPairGenerationState(e,t,n);if(!r)return fe.rsa.stepKeyPairGenerationState(a,0),a.keys;Km(a,n,r)};fe.setRsaPublicKey=fe.rsa.setPublicKey=function(e,t){var n={n:e,e:t};return n.encrypt=function(r,i,s){if(typeof i==="string")i=i.toUpperCase();else if(i===void 0)i="RSAES-PKCS1-V1_5";if(i==="RSAES-PKCS1-V1_5")i={encode:function(o,l,c){return Qu(o,l,2).getBytes()}};else if(i==="RSA-OAEP"||i==="RSAES-OAEP")i={encode:function(o,l){return ne.pkcs1.encode_rsa_oaep(l,o,s)}};else if(["RAW","NONE","NULL",null].indexOf(i)!==-1)i={encode:function(o){return o}};else if(typeof i==="string")throw Error('Unsupported encryption scheme: "'+i+'".');var a=i.encode(r,n,!0);return fe.rsa.encrypt(a,n,!0)},n.verify=function(r,i,s,a){if(typeof s==="string")s=s.toUpperCase();else if(s===void 0)s="RSASSA-PKCS1-V1_5";if(a===void 0)a={_parseAllDigestBytes:!0,_skipPaddingChecks:!1};if(!("_parseAllDigestBytes"in a))a._parseAllDigestBytes=!0;if(!("_skipPaddingChecks"in a))a._skipPaddingChecks=!1;if(s==="RSASSA-PKCS1-V1_5")s={verify:function(l,c){c=Ks(c,n,!0,void 0,a);var u=_.fromDer(c,{parseAllBytes:a._parseAllDigestBytes}),d={},p=[];if(!_.validate(u,Wm,d,p)||u.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 f=_.derToOid(d.algorithmIdentifier);if(!(f===ne.oids.md2||f===ne.oids.md5||f===ne.oids.sha1||f===ne.oids.sha224||f===ne.oids.sha256||f===ne.oids.sha384||f===ne.oids.sha512||f===ne.oids["sha512-224"]||f===ne.oids["sha512-256"])){var h=Error("Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.");throw h.oid=f,h}if(f===ne.oids.md2||f===ne.oids.md5){if(!("parameters"in d))throw Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value. Missing algorithm identifier NULL parameters.")}var v=Ku(f,d.digest,!0),x=Ku(f,d.digest,!1);if(c.substring(0,v.length)!==v&&c.substring(0,x.length)!==x)throw Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value.");return l===d.digest}};else if(s==="NONE"||s==="NULL"||s===null)s={verify:function(l,c){return c=Ks(c,n,!0,void 0,a),l===c}};var o=fe.rsa.decrypt(i,n,!0,!1);return s.verify(r,o,n.n.bitLength())},n};fe.setRsaPrivateKey=fe.rsa.setPrivateKey=function(e,t,n,r,i,s,a,o){var l={n:e,e:t,d:n,p:r,q:i,dP:s,dQ:a,qInv:o};return l.decrypt=function(c,u,d){if(typeof u==="string")u=u.toUpperCase();else if(u===void 0)u="RSAES-PKCS1-V1_5";var p=fe.rsa.decrypt(c,l,!1,!1);if(u==="RSAES-PKCS1-V1_5")u={decode:Ks};else if(u==="RSA-OAEP"||u==="RSAES-OAEP")u={decode:function(h,f){return ne.pkcs1.decode_rsa_oaep(f,h,d)}};else if(["RAW","NONE","NULL",null].indexOf(u)!==-1)u={decode:function(h){return h}};else throw Error('Unsupported encryption scheme: "'+u+'".');return u.decode(p,l,!1)},l.sign=function(c,u){var d=!1;if(typeof u==="string")u=u.toUpperCase();if(u===void 0||u==="RSASSA-PKCS1-V1_5")u={encode:Hm},d=1;else if(u==="NONE"||u==="NULL"||u===null)u={encode:function(){return c}},d=1;var p=u.encode(c,l.n.bitLength());return fe.rsa.encrypt(p,l,d)},l};fe.wrapRsaPrivateKey=function(e){return _.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[_.create(_.Class.UNIVERSAL,_.Type.INTEGER,!1,_.integerToDer(0).getBytes()),_.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[_.create(_.Class.UNIVERSAL,_.Type.OID,!1,_.oidToDer(fe.oids.rsaEncryption).getBytes()),_.create(_.Class.UNIVERSAL,_.Type.NULL,!1,"")]),_.create(_.Class.UNIVERSAL,_.Type.OCTETSTRING,!1,_.toDer(e).getBytes())])};fe.privateKeyFromAsn1=function(e){var t={},n=[];if(_.validate(e,Vm,t,n))e=_.fromDer(ne.util.createBuffer(t.privateKey));if(t={},n=[],!_.validate(e,Fm,t,n)){var r=Error("Cannot read private key. ASN.1 object does not contain an RSAPrivateKey.");throw r.errors=n,r}var i,s,a,o,l,c,u,d;return i=ne.util.createBuffer(t.privateKeyModulus).toHex(),s=ne.util.createBuffer(t.privateKeyPublicExponent).toHex(),a=ne.util.createBuffer(t.privateKeyPrivateExponent).toHex(),o=ne.util.createBuffer(t.privateKeyPrime1).toHex(),l=ne.util.createBuffer(t.privateKeyPrime2).toHex(),c=ne.util.createBuffer(t.privateKeyExponent1).toHex(),u=ne.util.createBuffer(t.privateKeyExponent2).toHex(),d=ne.util.createBuffer(t.privateKeyCoefficient).toHex(),fe.setRsaPrivateKey(new ke(i,16),new ke(s,16),new ke(a,16),new ke(o,16),new ke(l,16),new ke(c,16),new ke(u,16),new ke(d,16))};fe.privateKeyToAsn1=fe.privateKeyToRSAPrivateKey=function(e){return _.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[_.create(_.Class.UNIVERSAL,_.Type.INTEGER,!1,_.integerToDer(0).getBytes()),_.create(_.Class.UNIVERSAL,_.Type.INTEGER,!1,cr(e.n)),_.create(_.Class.UNIVERSAL,_.Type.INTEGER,!1,cr(e.e)),_.create(_.Class.UNIVERSAL,_.Type.INTEGER,!1,cr(e.d)),_.create(_.Class.UNIVERSAL,_.Type.INTEGER,!1,cr(e.p)),_.create(_.Class.UNIVERSAL,_.Type.INTEGER,!1,cr(e.q)),_.create(_.Class.UNIVERSAL,_.Type.INTEGER,!1,cr(e.dP)),_.create(_.Class.UNIVERSAL,_.Type.INTEGER,!1,cr(e.dQ)),_.create(_.Class.UNIVERSAL,_.Type.INTEGER,!1,cr(e.qInv))])};fe.publicKeyFromAsn1=function(e){var t={},n=[];if(_.validate(e,$m,t,n)){var r=_.derToOid(t.publicKeyOid);if(r!==fe.oids.rsaEncryption){var i=Error("Cannot read public key. Unknown OID.");throw i.oid=r,i}e=t.rsaPublicKey}if(n=[],!_.validate(e,Mm,t,n)){var i=Error("Cannot read public key. ASN.1 object does not contain an RSAPublicKey.");throw i.errors=n,i}var s=ne.util.createBuffer(t.publicKeyModulus).toHex(),a=ne.util.createBuffer(t.publicKeyExponent).toHex();return fe.setRsaPublicKey(new ke(s,16),new ke(a,16))};fe.publicKeyToAsn1=fe.publicKeyToSubjectPublicKeyInfo=function(e){return _.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[_.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[_.create(_.Class.UNIVERSAL,_.Type.OID,!1,_.oidToDer(fe.oids.rsaEncryption).getBytes()),_.create(_.Class.UNIVERSAL,_.Type.NULL,!1,"")]),_.create(_.Class.UNIVERSAL,_.Type.BITSTRING,!1,[fe.publicKeyToRSAPublicKey(e)])])};fe.publicKeyToRSAPublicKey=function(e){return _.create(_.Class.UNIVERSAL,_.Type.SEQUENCE,!0,[_.create(_.Class.UNIVERSAL,_.Type.INTEGER,!1,cr(e.n)),_.create(_.Class.UNIVERSAL,_.Type.INTEGER,!1,cr(e.e))])};function Qu(e,t,n){var r=ne.util.createBuffer(),i=Math.ceil(t.n.bitLength()/8);if(e.length>i-11){var s=Error("Message is too long for PKCS#1 v1.5 padding.");throw s.length=e.length,s.max=i-11,s}r.putByte(0),r.putByte(n);var a=i-3-e.length,o;if(n===0||n===1){o=n===0?0:255;for(var l=0;l<a;++l)r.putByte(o)}else while(a>0){var c=0,u=ne.random.getBytes(a);for(var l=0;l<a;++l)if(o=u.charCodeAt(l),o===0)++c;else r.putByte(o);a=c}return r.putByte(0),r.putBytes(e),r}function Ks(e,t,n,r,i){var s=Math.ceil(t.n.bitLength()/8),a=ne.util.createBuffer(e),o=a.getByte(),l=a.getByte();if(o!==0||n&&l!==0&&l!==1||!n&&l!==2||n&&l===0&&typeof r>"u")throw Error("Encryption block is invalid.");var c=0;if(l===0){c=s-3-r;for(var u=0;u<c;++u)if(a.getByte()!==0)throw Error("Encryption block is invalid.")}else if(l===1){c=0;while(a.length()>1){if(a.getByte()!==255){--a.read;break}++c}if(c<8&&!(i?i._skipPaddingChecks:!1))throw Error("Encryption block is invalid.")}else if(l===2){c=0;while(a.length()>1){if(a.getByte()===0){--a.read;break}++c}if(c<8&&!(i?i._skipPaddingChecks:!1))throw Error("Encryption block is invalid.")}var d=a.getByte();if(d!==0||c!==s-3-a.length())throw Error("Encryption block is invalid.");return a.getBytes()}function Km(e,t,n){if(typeof t==="function")n=t,t={};t=t||{};var r={algorithm:{name:t.algorithm||"PRIMEINC",options:{workers:t.workers||2,workLoad:t.workLoad||100,workerScript:t.workerScript}}};if("prng"in t)r.prng=t.prng;i();function i(){s(e.pBits,function(o,l){if(o)return n(o);if(e.p=l,e.q!==null)return a(o,e.q);s(e.qBits,a)})}function s(o,l){ne.prime.generateProbablePrime(o,r,l)}function a(o,l){if(o)return n(o);if(e.q=l,e.p.compareTo(e.q)<0){var c=e.p;e.p=e.q,e.q=c}if(e.p.subtract(ke.ONE).gcd(e.e).compareTo(ke.ONE)!==0){e.p=null,i();return}if(e.q.subtract(ke.ONE).gcd(e.e).compareTo(ke.ONE)!==0){e.q=null,s(e.qBits,a);return}if(e.p1=e.p.subtract(ke.ONE),e.q1=e.q.subtract(ke.ONE),e.phi=e.p1.multiply(e.q1),e.phi.gcd(e.e).compareTo(ke.ONE)!==0){e.p=e.q=null,i();return}if(e.n=e.p.multiply(e.q),e.n.bitLength()!==e.bits){e.q=null,s(e.qBits,a);return}var u=e.e.modInverse(e.phi);e.keys={privateKey:fe.rsa.setPrivateKey(e.n,e.e,u,e.p,e.q,u.mod(e.p1),u.mod(e.q1),e.q.modInverse(e.p)),publicKey:fe.rsa.setPublicKey(e.n,e.e)},n(null,e.keys)}}function cr(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 qm(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 qu(e){return ne.util.isNodejs&&typeof Po[e]==="function"}function Gu(e){return typeof Ut.globalScope<"u"&&typeof Ut.globalScope.crypto==="object"&&typeof Ut.globalScope.crypto.subtle==="object"&&typeof Ut.globalScope.crypto.subtle[e]==="function"}function ju(e){return typeof Ut.globalScope<"u"&&typeof Ut.globalScope.msCrypto==="object"&&typeof Ut.globalScope.msCrypto.subtle==="object"&&typeof Ut.globalScope.msCrypto.subtle[e]==="function"}function zu(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 Do=de(function(_1,td){var z=ye();Lr();Gt();Si();rr();Or();Fs();sn();Lt();Eo();wi();Ne();if(typeof No>"u")No=z.jsbn.BigInteger;var No,B=z.asn1,me=z.pki=z.pki||{};td.exports=me.pbe=z.pbe=z.pbe||{};var ln=me.oids,Gm={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"}]},jm={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"}]}]},zm={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"}]};me.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=z.random.getBytesSync(n.saltSize),i=n.count,s=B.integerToDer(i),a,o,l;if(n.algorithm.indexOf("aes")===0||n.algorithm==="des"){var c,u,d;switch(n.algorithm){case"aes128":a=16,c=16,u=ln["aes128-CBC"],d=z.aes.createEncryptionCipher;break;case"aes192":a=24,c=16,u=ln["aes192-CBC"],d=z.aes.createEncryptionCipher;break;case"aes256":a=32,c=16,u=ln["aes256-CBC"],d=z.aes.createEncryptionCipher;break;case"des":a=8,c=8,u=ln.desCBC,d=z.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(),f=ed(h),v=z.pkcs5.pbkdf2(t,r,i,a,f),x=z.random.getBytesSync(c),S=d(v);S.start(x),S.update(B.toDer(e)),S.finish(),l=S.output.getBytes();var A=Xm(r,s,a,h);o=B.create(B.Class.UNIVERSAL,B.Type.SEQUENCE,!0,[B.create(B.Class.UNIVERSAL,B.Type.OID,!1,B.oidToDer(ln.pkcs5PBES2).getBytes()),B.create(B.Class.UNIVERSAL,B.Type.SEQUENCE,!0,[B.create(B.Class.UNIVERSAL,B.Type.SEQUENCE,!0,[B.create(B.Class.UNIVERSAL,B.Type.OID,!1,B.oidToDer(ln.pkcs5PBKDF2).getBytes()),A]),B.create(B.Class.UNIVERSAL,B.Type.SEQUENCE,!0,[B.create(B.Class.UNIVERSAL,B.Type.OID,!1,B.oidToDer(u).getBytes()),B.create(B.Class.UNIVERSAL,B.Type.OCTETSTRING,!1,x)])])])}else if(n.algorithm==="3des"){a=24;var b=new z.util.ByteBuffer(r),v=me.pbe.generatePkcs12Key(t,b,1,i,a),x=me.pbe.generatePkcs12Key(t,b,2,i,a),S=z.des.createEncryptionCipher(v);S.start(x),S.update(B.toDer(e)),S.finish(),l=S.output.getBytes(),o=B.create(B.Class.UNIVERSAL,B.Type.SEQUENCE,!0,[B.create(B.Class.UNIVERSAL,B.Type.OID,!1,B.oidToDer(ln["pbeWithSHAAnd3-KeyTripleDES-CBC"]).getBytes()),B.create(B.Class.UNIVERSAL,B.Type.SEQUENCE,!0,[B.create(B.Class.UNIVERSAL,B.Type.OCTETSTRING,!1,r),B.create(B.Class.UNIVERSAL,B.Type.INTEGER,!1,s.getBytes())])])}else{var p=Error("Cannot encrypt private key. Unknown encryption algorithm.");throw p.algorithm=n.algorithm,p}var k=B.create(B.Class.UNIVERSAL,B.Type.SEQUENCE,!0,[o,B.create(B.Class.UNIVERSAL,B.Type.OCTETSTRING,!1,l)]);return k};me.decryptPrivateKeyInfo=function(e,t){var n=null,r={},i=[];if(!B.validate(e,Gm,r,i)){var s=Error("Cannot read encrypted private key. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw s.errors=i,s}var a=B.derToOid(r.encryptionOid),o=me.pbe.getCipher(a,r.encryptionParams,t),l=z.util.createBuffer(r.encryptedData);if(o.update(l),o.finish())n=B.fromDer(o.output);return n};me.encryptedPrivateKeyToPem=function(e,t){var n={type:"ENCRYPTED PRIVATE KEY",body:B.toDer(e).getBytes()};return z.pem.encode(n,{maxline:t})};me.encryptedPrivateKeyFromPem=function(e){var t=z.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)};me.encryptRsaPrivateKey=function(e,t,n){if(n=n||{},!n.legacy){var r=me.wrapRsaPrivateKey(me.privateKeyToAsn1(e));return r=me.encryptPrivateKeyInfo(r,t,n),me.encryptedPrivateKeyToPem(r)}var i,s,a,o;switch(n.algorithm){case"aes128":i="AES-128-CBC",a=16,s=z.random.getBytesSync(16),o=z.aes.createEncryptionCipher;break;case"aes192":i="AES-192-CBC",a=24,s=z.random.getBytesSync(16),o=z.aes.createEncryptionCipher;break;case"aes256":i="AES-256-CBC",a=32,s=z.random.getBytesSync(16),o=z.aes.createEncryptionCipher;break;case"3des":i="DES-EDE3-CBC",a=24,s=z.random.getBytesSync(8),o=z.des.createEncryptionCipher;break;case"des":i="DES-CBC",a=8,s=z.random.getBytesSync(8),o=z.des.createEncryptionCipher;break;default:var l=Error('Could not encrypt RSA private key; unsupported encryption algorithm "'+n.algorithm+'".');throw l.algorithm=n.algorithm,l}var c=z.pbe.opensslDeriveBytes(t,s.substr(0,8),a),u=o(c);u.start(s),u.update(B.toDer(me.privateKeyToAsn1(e))),u.finish();var d={type:"RSA PRIVATE KEY",procType:{version:"4",type:"ENCRYPTED"},dekInfo:{algorithm:i,parameters:z.util.bytesToHex(s).toUpperCase()},body:u.output.getBytes()};return z.pem.encode(d)};me.decryptRsaPrivateKey=function(e,t){var n=null,r=z.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 s,a;switch(r.dekInfo.algorithm){case"DES-CBC":s=8,a=z.des.createDecryptionCipher;break;case"DES-EDE3-CBC":s=24,a=z.des.createDecryptionCipher;break;case"AES-128-CBC":s=16,a=z.aes.createDecryptionCipher;break;case"AES-192-CBC":s=24,a=z.aes.createDecryptionCipher;break;case"AES-256-CBC":s=32,a=z.aes.createDecryptionCipher;break;case"RC2-40-CBC":s=5,a=function(d){return z.rc2.createDecryptionCipher(d,40)};break;case"RC2-64-CBC":s=8,a=function(d){return z.rc2.createDecryptionCipher(d,64)};break;case"RC2-128-CBC":s=16,a=function(d){return z.rc2.createDecryptionCipher(d,128)};break;default:var i=Error('Could not decrypt private key; unsupported encryption algorithm "'+r.dekInfo.algorithm+'".');throw i.algorithm=r.dekInfo.algorithm,i}var o=z.util.hexToBytes(r.dekInfo.parameters),l=z.pbe.opensslDeriveBytes(t,o.substr(0,8),s),c=a(l);if(c.start(o),c.update(z.util.createBuffer(r.body)),c.finish())n=c.output.getBytes();else return n}else n=r.body;if(r.type==="ENCRYPTED PRIVATE KEY")n=me.decryptPrivateKeyInfo(B.fromDer(n),t);else n=B.fromDer(n);if(n!==null)n=me.privateKeyFromAsn1(n);return n};me.pbe.generatePkcs12Key=function(e,t,n,r,i,s){var a,o;if(!(r>=1))throw Error("PKCS#12 key derivation iteration count must be >= 1.");if(typeof s>"u"||s===null){if(!("sha1"in z.md))throw Error('"sha1" hash algorithm unavailable.');s=z.md.sha1.create()}var l=s.digestLength,c=s.blockLength,u=new z.util.ByteBuffer,d=new z.util.ByteBuffer;if(e!==null&&e!==void 0){for(o=0;o<e.length;o++)d.putInt16(e.charCodeAt(o));d.putInt16(0)}var p=d.length(),h=t.length(),f=new z.util.ByteBuffer;f.fillWithByte(n,c);var v=c*Math.ceil(h/c),x=new z.util.ByteBuffer;for(o=0;o<v;o++)x.putByte(t.at(o%h));var S=c*Math.ceil(p/c),A=new z.util.ByteBuffer;for(o=0;o<S;o++)A.putByte(d.at(o%p));var b=x;b.putBuffer(A);var k=Math.ceil(i/l);for(var R=1;R<=k;R++){var I=new z.util.ByteBuffer;I.putBytes(f.bytes()),I.putBytes(b.bytes());for(var V=0;V<r;V++)s.start(),s.update(I.getBytes()),I=s.digest();var J=new z.util.ByteBuffer;for(o=0;o<c;o++)J.putByte(I.at(o%l));var D=Math.ceil(h/c)+Math.ceil(p/c),W=new z.util.ByteBuffer;for(a=0;a<D;a++){var Z=new z.util.ByteBuffer(b.getBytes(c)),pe=511;for(o=J.length()-1;o>=0;o--)pe=pe>>8,pe+=J.at(o)+Z.at(o),Z.setAt(o,pe&255);W.putBuffer(Z)}b=W,u.putBuffer(I)}return u.truncate(u.length()-i),u};me.pbe.getCipher=function(e,t,n){switch(e){case me.oids.pkcs5PBES2:return me.pbe.getCipherForPBES2(e,t,n);case me.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:case me.oids["pbewithSHAAnd40BitRC2-CBC"]:return me.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}};me.pbe.getCipherForPBES2=function(e,t,n){var r={},i=[];if(!B.validate(t,jm,r,i)){var s=Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw s.errors=i,s}if(e=B.derToOid(r.kdfOid),e!==me.oids.pkcs5PBKDF2){var s=Error("Cannot read encrypted private key. Unsupported key derivation function OID.");throw s.oid=e,s.supportedOids=["pkcs5PBKDF2"],s}if(e=B.derToOid(r.encOid),e!==me.oids["aes128-CBC"]&&e!==me.oids["aes192-CBC"]&&e!==me.oids["aes256-CBC"]&&e!==me.oids["des-EDE3-CBC"]&&e!==me.oids.desCBC){var s=Error("Cannot read encrypted private key. Unsupported encryption scheme OID.");throw s.oid=e,s.supportedOids=["aes128-CBC","aes192-CBC","aes256-CBC","des-EDE3-CBC","desCBC"],s}var a=r.kdfSalt,o=z.util.createBuffer(r.kdfIterationCount);o=o.getInt(o.length()<<3);var l,c;switch(me.oids[e]){case"aes128-CBC":l=16,c=z.aes.createDecryptionCipher;break;case"aes192-CBC":l=24,c=z.aes.createDecryptionCipher;break;case"aes256-CBC":l=32,c=z.aes.createDecryptionCipher;break;case"des-EDE3-CBC":l=24,c=z.des.createDecryptionCipher;break;case"desCBC":l=8,c=z.des.createDecryptionCipher;break}var u=Zu(r.prfOid),d=z.pkcs5.pbkdf2(n,a,o,l,u),p=r.encIv,h=c(d);return h.start(p),h};me.pbe.getCipherForPKCS12PBE=function(e,t,n){var r={},i=[];if(!B.validate(t,zm,r,i)){var s=Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw s.errors=i,s}var a=z.util.createBuffer(r.salt),o=z.util.createBuffer(r.iterations);o=o.getInt(o.length()<<3);var l,c,u;switch(e){case me.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:l=24,c=8,u=z.des.startDecrypting;break;case me.oids["pbewithSHAAnd40BitRC2-CBC"]:l=5,c=8,u=function(v,x){var S=z.rc2.createDecryptionCipher(v,40);return S.start(x,null),S};break;default:var s=Error("Cannot read PKCS #12 PBE data block. Unsupported OID.");throw s.oid=e,s}var d=Zu(r.prfOid),p=me.pbe.generatePkcs12Key(n,a,1,o,l,d);d.start();var h=me.pbe.generatePkcs12Key(n,a,2,o,c,d);return u(p,h)};me.pbe.opensslDeriveBytes=function(e,t,n,r){if(typeof r>"u"||r===null){if(!("md5"in z.md))throw Error('"md5" hash algorithm unavailable.');r=z.md.md5.create()}if(t===null)t="";var i=[Ju(r,e+t)];for(var s=16,a=1;s<n;++a,s+=16)i.push(Ju(r,i[a-1]+e+t));return i.join("").substr(0,n)};function Ju(e,t){return e.start().update(t).digest().getBytes()}function Zu(e){var t;if(!e)t="hmacWithSHA1";else if(t=me.oids[B.derToOid(e)],!t){var n=Error("Unsupported PRF OID.");throw n.oid=e,n.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"],n}return ed(t)}function ed(e){var t=z.md;switch(e){case"hmacWithSHA224":t=z.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 Xm(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,z.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(me.oids[r]).getBytes()),B.create(B.Class.UNIVERSAL,B.Type.NULL,!1,"")]));return i}});var Lo=de(function(k1,id){var Bn=ye();Gt();Ne();var G=Bn.asn1,Pn=id.exports=Bn.pkcs7asn1=Bn.pkcs7asn1||{};Bn.pkcs7=Bn.pkcs7||{};Bn.pkcs7.asn1=Pn;var rd={name:"ContentInfo",tagClass:G.Class.UNIVERSAL,type:G.Type.SEQUENCE,constructed:!0,value:[{name:"ContentInfo.ContentType",tagClass:G.Class.UNIVERSAL,type:G.Type.OID,constructed:!1,capture:"contentType"},{name:"ContentInfo.content",tagClass:G.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,captureAsn1:"content"}]};Pn.contentInfoValidator=rd;var nd={name:"EncryptedContentInfo",tagClass:G.Class.UNIVERSAL,type:G.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedContentInfo.contentType",tagClass:G.Class.UNIVERSAL,type:G.Type.OID,constructed:!1,capture:"contentType"},{name:"EncryptedContentInfo.contentEncryptionAlgorithm",tagClass:G.Class.UNIVERSAL,type:G.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedContentInfo.contentEncryptionAlgorithm.algorithm",tagClass:G.Class.UNIVERSAL,type:G.Type.OID,constructed:!1,capture:"encAlgorithm"},{name:"EncryptedContentInfo.contentEncryptionAlgorithm.parameter",tagClass:G.Class.UNIVERSAL,captureAsn1:"encParameter"}]},{name:"EncryptedContentInfo.encryptedContent",tagClass:G.Class.CONTEXT_SPECIFIC,type:0,capture:"encryptedContent",captureAsn1:"encryptedContentAsn1"}]};Pn.envelopedDataValidator={name:"EnvelopedData",tagClass:G.Class.UNIVERSAL,type:G.Type.SEQUENCE,constructed:!0,value:[{name:"EnvelopedData.Version",tagClass:G.Class.UNIVERSAL,type:G.Type.INTEGER,constructed:!1,capture:"version"},{name:"EnvelopedData.RecipientInfos",tagClass:G.Class.UNIVERSAL,type:G.Type.SET,constructed:!0,captureAsn1:"recipientInfos"}].concat(nd)};Pn.encryptedDataValidator={name:"EncryptedData",tagClass:G.Class.UNIVERSAL,type:G.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedData.Version",tagClass:G.Class.UNIVERSAL,type:G.Type.INTEGER,constructed:!1,capture:"version"}].concat(nd)};var Qm={name:"SignerInfo",tagClass:G.Class.UNIVERSAL,type:G.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.version",tagClass:G.Class.UNIVERSAL,type:G.Type.INTEGER,constructed:!1},{name:"SignerInfo.issuerAndSerialNumber",tagClass:G.Class.UNIVERSAL,type:G.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.issuerAndSerialNumber.issuer",tagClass:G.Class.UNIVERSAL,type:G.Type.SEQUENCE,constructed:!0,captureAsn1:"issuer"},{name:"SignerInfo.issuerAndSerialNumber.serialNumber",tagClass:G.Class.UNIVERSAL,type:G.Type.INTEGER,constructed:!1,capture:"serial"}]},{name:"SignerInfo.digestAlgorithm",tagClass:G.Class.UNIVERSAL,type:G.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.digestAlgorithm.algorithm",tagClass:G.Class.UNIVERSAL,type:G.Type.OID,constructed:!1,capture:"digestAlgorithm"},{name:"SignerInfo.digestAlgorithm.parameter",tagClass:G.Class.UNIVERSAL,constructed:!1,captureAsn1:"digestParameter",optional:!0}]},{name:"SignerInfo.authenticatedAttributes",tagClass:G.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,capture:"authenticatedAttributes"},{name:"SignerInfo.digestEncryptionAlgorithm",tagClass:G.Class.UNIVERSAL,type:G.Type.SEQUENCE,constructed:!0,capture:"signatureAlgorithm"},{name:"SignerInfo.encryptedDigest",tagClass:G.Class.UNIVERSAL,type:G.Type.OCTETSTRING,constructed:!1,capture:"signature"},{name:"SignerInfo.unauthenticatedAttributes",tagClass:G.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,optional:!0,capture:"unauthenticatedAttributes"}]};Pn.signedDataValidator={name:"SignedData",tagClass:G.Class.UNIVERSAL,type:G.Type.SEQUENCE,constructed:!0,value:[{name:"SignedData.Version",tagClass:G.Class.UNIVERSAL,type:G.Type.INTEGER,constructed:!1,capture:"version"},{name:"SignedData.DigestAlgorithms",tagClass:G.Class.UNIVERSAL,type:G.Type.SET,constructed:!0,captureAsn1:"digestAlgorithms"},rd,{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:[Qm]}]};Pn.recipientInfoValidator={name:"RecipientInfo",tagClass:G.Class.UNIVERSAL,type:G.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.version",tagClass:G.Class.UNIVERSAL,type:G.Type.INTEGER,constructed:!1,capture:"version"},{name:"RecipientInfo.issuerAndSerial",tagClass:G.Class.UNIVERSAL,type:G.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.issuerAndSerial.issuer",tagClass:G.Class.UNIVERSAL,type:G.Type.SEQUENCE,constructed:!0,captureAsn1:"issuer"},{name:"RecipientInfo.issuerAndSerial.serialNumber",tagClass:G.Class.UNIVERSAL,type:G.Type.INTEGER,constructed:!1,capture:"serial"}]},{name:"RecipientInfo.keyEncryptionAlgorithm",tagClass:G.Class.UNIVERSAL,type:G.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.keyEncryptionAlgorithm.algorithm",tagClass:G.Class.UNIVERSAL,type:G.Type.OID,constructed:!1,capture:"encAlgorithm"},{name:"RecipientInfo.keyEncryptionAlgorithm.parameter",tagClass:G.Class.UNIVERSAL,constructed:!1,captureAsn1:"encParameter",optional:!0}]},{name:"RecipientInfo.encryptedKey",tagClass:G.Class.UNIVERSAL,type:G.Type.OCTETSTRING,constructed:!1,capture:"encKey"}]}});var Oo=de(function(I1,sd){var cn=ye();Ne();cn.mgf=cn.mgf||{};var Ym=sd.exports=cn.mgf.mgf1=cn.mgf1=cn.mgf1||{};Ym.create=function(e){var t={generate:function(n,r){var i=new cn.util.ByteBuffer,s=Math.ceil(r/e.digestLength);for(var a=0;a<s;a++){var o=new cn.util.ByteBuffer;o.putInt32(a),e.start(),e.update(n+o.getBytes()),i.putBuffer(e.digest())}return i.truncate(i.length()-r),i.getBytes()}};return t}});var od=de(function(R1,ad){var qs=ye();Oo();ad.exports=qs.mgf=qs.mgf||{};qs.mgf.mgf1=qs.mgf1});var Gs=de(function(B1,ld){var un=ye();Lt();Ne();var Jm=ld.exports=un.pss=un.pss||{};Jm.create=function(e){if(arguments.length===3)e={md:arguments[0],mgf:arguments[1],saltLength:arguments[2]};var t=e.md,n=e.mgf,r=t.digestLength,i=e.salt||null;if(typeof i==="string")i=un.util.createBuffer(i);var s;if("saltLength"in e)s=e.saltLength;else if(i!==null)s=i.length();else throw Error("Salt length not specified or specific salt not given.");if(i!==null&&i.length()!==s)throw Error("Given salt length does not match length of given salt.");var a=e.prng||un.random,o={};return o.encode=function(l,c){var u,d=c-1,p=Math.ceil(d/8),h=l.digest().getBytes();if(p<r+s+2)throw Error("Message is too long to encrypt.");var f;if(i===null)f=a.getBytesSync(s);else f=i.bytes();var v=new un.util.ByteBuffer;v.fillWithByte(0,8),v.putBytes(h),v.putBytes(f),t.start(),t.update(v.getBytes());var x=t.digest().getBytes(),S=new un.util.ByteBuffer;S.fillWithByte(0,p-s-r-2),S.putByte(1),S.putBytes(f);var A=S.getBytes(),b=p-r-1,k=n.generate(x,b),R="";for(u=0;u<b;u++)R+=String.fromCharCode(A.charCodeAt(u)^k.charCodeAt(u));var I=65280>>8*p-d&255;return R=String.fromCharCode(R.charCodeAt(0)&~I)+R.substr(1),R+x+String.fromCharCode(188)},o.verify=function(l,c,u){var d,p=u-1,h=Math.ceil(p/8);if(c=c.substr(-h),h<r+s+2)throw Error("Inconsistent parameters to PSS signature verification.");if(c.charCodeAt(h-1)!==188)throw Error("Encoded message does not end in 0xBC.");var f=h-r-1,v=c.substr(0,f),x=c.substr(f,r),S=65280>>8*h-p&255;if((v.charCodeAt(0)&S)!==0)throw Error("Bits beyond keysize not zero as expected.");var A=n.generate(x,f),b="";for(d=0;d<f;d++)b+=String.fromCharCode(v.charCodeAt(d)^A.charCodeAt(d));b=String.fromCharCode(b.charCodeAt(0)&~S)+b.substr(1);var k=h-r-s-2;for(d=0;d<k;d++)if(b.charCodeAt(d)!==0)throw Error("Leftmost octets not zero as expected");if(b.charCodeAt(k)!==1)throw Error("Inconsistent PSS signature, 0x01 marker not found");var R=b.substr(-s),I=new un.util.ByteBuffer;I.fillWithByte(0,8),I.putBytes(l),I.putBytes(R),t.start(),t.update(I.getBytes());var V=t.digest().getBytes();return x===V},o}});var Xs=de(function(P1,pd){var ie=ye();Lr();Gt();Si();rr();od();Or();sn();Gs();wi();Ne();var g=ie.asn1,M=pd.exports=ie.pki=ie.pki||{},Pe=M.oids,Ye={};Ye.CN=Pe.commonName;Ye.commonName="CN";Ye.C=Pe.countryName;Ye.countryName="C";Ye.L=Pe.localityName;Ye.localityName="L";Ye.ST=Pe.stateOrProvinceName;Ye.stateOrProvinceName="ST";Ye.O=Pe.organizationName;Ye.organizationName="O";Ye.OU=Pe.organizationalUnitName;Ye.organizationalUnitName="OU";Ye.E=Pe.emailAddress;Ye.emailAddress="E";var ud=ie.pki.rsa.publicKeyValidator,Zm={name:"Certificate",tagClass:g.Class.UNIVERSAL,type:g.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate",tagClass:g.Class.UNIVERSAL,type:g.Type.SEQUENCE,constructed:!0,captureAsn1:"tbsCertificate",value:[{name:"Certificate.TBSCertificate.version",tagClass:g.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.version.integer",tagClass:g.Class.UNIVERSAL,type:g.Type.INTEGER,constructed:!1,capture:"certVersion"}]},{name:"Certificate.TBSCertificate.serialNumber",tagClass:g.Class.UNIVERSAL,type:g.Type.INTEGER,constructed:!1,capture:"certSerialNumber"},{name:"Certificate.TBSCertificate.signature",tagClass:g.Class.UNIVERSAL,type:g.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate.signature.algorithm",tagClass:g.Class.UNIVERSAL,type:g.Type.OID,constructed:!1,capture:"certinfoSignatureOid"},{name:"Certificate.TBSCertificate.signature.parameters",tagClass:g.Class.UNIVERSAL,optional:!0,captureAsn1:"certinfoSignatureParams"}]},{name:"Certificate.TBSCertificate.issuer",tagClass:g.Class.UNIVERSAL,type:g.Type.SEQUENCE,constructed:!0,captureAsn1:"certIssuer"},{name:"Certificate.TBSCertificate.validity",tagClass:g.Class.UNIVERSAL,type:g.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate.validity.notBefore (utc)",tagClass:g.Class.UNIVERSAL,type:g.Type.UTCTIME,constructed:!1,optional:!0,capture:"certValidity1UTCTime"},{name:"Certificate.TBSCertificate.validity.notBefore (generalized)",tagClass:g.Class.UNIVERSAL,type:g.Type.GENERALIZEDTIME,constructed:!1,optional:!0,capture:"certValidity2GeneralizedTime"},{name:"Certificate.TBSCertificate.validity.notAfter (utc)",tagClass:g.Class.UNIVERSAL,type:g.Type.UTCTIME,constructed:!1,optional:!0,capture:"certValidity3UTCTime"},{name:"Certificate.TBSCertificate.validity.notAfter (generalized)",tagClass:g.Class.UNIVERSAL,type:g.Type.GENERALIZEDTIME,constructed:!1,optional:!0,capture:"certValidity4GeneralizedTime"}]},{name:"Certificate.TBSCertificate.subject",tagClass:g.Class.UNIVERSAL,type:g.Type.SEQUENCE,constructed:!0,captureAsn1:"certSubject"},ud,{name:"Certificate.TBSCertificate.issuerUniqueID",tagClass:g.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.issuerUniqueID.id",tagClass:g.Class.UNIVERSAL,type:g.Type.BITSTRING,constructed:!1,captureBitStringValue:"certIssuerUniqueId"}]},{name:"Certificate.TBSCertificate.subjectUniqueID",tagClass:g.Class.CONTEXT_SPECIFIC,type:2,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.subjectUniqueID.id",tagClass:g.Class.UNIVERSAL,type:g.Type.BITSTRING,constructed:!1,captureBitStringValue:"certSubjectUniqueId"}]},{name:"Certificate.TBSCertificate.extensions",tagClass:g.Class.CONTEXT_SPECIFIC,type:3,constructed:!0,captureAsn1:"certExtensions",optional:!0}]},{name:"Certificate.signatureAlgorithm",tagClass:g.Class.UNIVERSAL,type:g.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.signatureAlgorithm.algorithm",tagClass:g.Class.UNIVERSAL,type:g.Type.OID,constructed:!1,capture:"certSignatureOid"},{name:"Certificate.TBSCertificate.signature.parameters",tagClass:g.Class.UNIVERSAL,optional:!0,captureAsn1:"certSignatureParams"}]},{name:"Certificate.signatureValue",tagClass:g.Class.UNIVERSAL,type:g.Type.BITSTRING,constructed:!1,captureBitStringValue:"certSignature"}]},ey={name:"rsapss",tagClass:g.Class.UNIVERSAL,type:g.Type.SEQUENCE,constructed:!0,value:[{name:"rsapss.hashAlgorithm",tagClass:g.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,value:[{name:"rsapss.hashAlgorithm.AlgorithmIdentifier",tagClass:g.Class.UNIVERSAL,type:g.Class.SEQUENCE,constructed:!0,optional:!0,value:[{name:"rsapss.hashAlgorithm.AlgorithmIdentifier.algorithm",tagClass:g.Class.UNIVERSAL,type:g.Type.OID,constructed:!1,capture:"hashOid"}]}]},{name:"rsapss.maskGenAlgorithm",tagClass:g.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier",tagClass:g.Class.UNIVERSAL,type:g.Class.SEQUENCE,constructed:!0,optional:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.algorithm",tagClass:g.Class.UNIVERSAL,type:g.Type.OID,constructed:!1,capture:"maskGenOid"},{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.params",tagClass:g.Class.UNIVERSAL,type:g.Type.SEQUENCE,constructed:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.params.algorithm",tagClass:g.Class.UNIVERSAL,type:g.Type.OID,constructed:!1,capture:"maskGenHashOid"}]}]}]},{name:"rsapss.saltLength",tagClass:g.Class.CONTEXT_SPECIFIC,type:2,optional:!0,value:[{name:"rsapss.saltLength.saltLength",tagClass:g.Class.UNIVERSAL,type:g.Class.INTEGER,constructed:!1,capture:"saltLength"}]},{name:"rsapss.trailerField",tagClass:g.Class.CONTEXT_SPECIFIC,type:3,optional:!0,value:[{name:"rsapss.trailer.trailer",tagClass:g.Class.UNIVERSAL,type:g.Class.INTEGER,constructed:!1,capture:"trailer"}]}]},ty={name:"CertificationRequestInfo",tagClass:g.Class.UNIVERSAL,type:g.Type.SEQUENCE,constructed:!0,captureAsn1:"certificationRequestInfo",value:[{name:"CertificationRequestInfo.integer",tagClass:g.Class.UNIVERSAL,type:g.Type.INTEGER,constructed:!1,capture:"certificationRequestInfoVersion"},{name:"CertificationRequestInfo.subject",tagClass:g.Class.UNIVERSAL,type:g.Type.SEQUENCE,constructed:!0,captureAsn1:"certificationRequestInfoSubject"},ud,{name:"CertificationRequestInfo.attributes",tagClass:g.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,capture:"certificationRequestInfoAttributes",value:[{name:"CertificationRequestInfo.attributes",tagClass:g.Class.UNIVERSAL,type:g.Type.SEQUENCE,constructed:!0,value:[{name:"CertificationRequestInfo.attributes.type",tagClass:g.Class.UNIVERSAL,type:g.Type.OID,constructed:!1},{name:"CertificationRequestInfo.attributes.value",tagClass:g.Class.UNIVERSAL,type:g.Type.SET,constructed:!0}]}]}]},ry={name:"CertificationRequest",tagClass:g.Class.UNIVERSAL,type:g.Type.SEQUENCE,constructed:!0,captureAsn1:"csr",value:[ty,{name:"CertificationRequest.signatureAlgorithm",tagClass:g.Class.UNIVERSAL,type:g.Type.SEQUENCE,constructed:!0,value:[{name:"CertificationRequest.signatureAlgorithm.algorithm",tagClass:g.Class.UNIVERSAL,type:g.Type.OID,constructed:!1,capture:"csrSignatureOid"},{name:"CertificationRequest.signatureAlgorithm.parameters",tagClass:g.Class.UNIVERSAL,optional:!0,captureAsn1:"csrSignatureParams"}]},{name:"CertificationRequest.signature",tagClass:g.Class.UNIVERSAL,type:g.Type.BITSTRING,constructed:!1,captureBitStringValue:"csrSignature"}]};M.RDNAttributesAsArray=function(e,t){var n=[],r,i,s;for(var a=0;a<e.value.length;++a){r=e.value[a];for(var o=0;o<r.value.length;++o){if(s={},i=r.value[o],s.type=g.derToOid(i.value[0].value),s.value=i.value[1].value,s.valueTagClass=i.value[1].type,s.type in Pe){if(s.name=Pe[s.type],s.name in Ye)s.shortName=Ye[s.name]}if(t)t.update(s.type),t.update(s.value);n.push(s)}}return n};M.CRIAttributesAsArray=function(e){var t=[];for(var n=0;n<e.length;++n){var r=e[n],i=g.derToOid(r.value[0].value),s=r.value[1].value;for(var a=0;a<s.length;++a){var o={};if(o.type=i,o.value=s[a].value,o.valueTagClass=s[a].type,o.type in Pe){if(o.name=Pe[o.type],o.name in Ye)o.shortName=Ye[o.name]}if(o.type===Pe.extensionRequest){o.extensions=[];for(var l=0;l<o.value.length;++l)o.extensions.push(M.certificateExtensionFromAsn1(o.value[l]))}t.push(o)}}return t};function Fr(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 js=function(e,t,n){var r={};if(e!==Pe["RSASSA-PSS"])return r;if(n)r={hash:{algorithmOid:Pe.sha1},mgf:{algorithmOid:Pe.mgf1,hash:{algorithmOid:Pe.sha1}},saltLength:20};var i={},s=[];if(!g.validate(t,ey,i,s)){var a=Error("Cannot read RSASSA-PSS parameter block.");throw a.errors=s,a}if(i.hashOid!==void 0)r.hash=r.hash||{},r.hash.algorithmOid=g.derToOid(i.hashOid);if(i.maskGenOid!==void 0)r.mgf=r.mgf||{},r.mgf.algorithmOid=g.derToOid(i.maskGenOid),r.mgf.hash=r.mgf.hash||{},r.mgf.hash.algorithmOid=g.derToOid(i.maskGenHashOid);if(i.saltLength!==void 0)r.saltLength=i.saltLength.charCodeAt(0);return r},zs=function(e){switch(Pe[e.signatureOid]){case"sha1WithRSAEncryption":case"sha1WithRSASignature":return ie.md.sha1.create();case"md5WithRSAEncryption":return ie.md.md5.create();case"sha256WithRSAEncryption":return ie.md.sha256.create();case"sha384WithRSAEncryption":return ie.md.sha384.create();case"sha512WithRSAEncryption":return ie.md.sha512.create();case"RSASSA-PSS":return ie.md.sha256.create();default:var t=Error("Could not compute "+e.type+" digest. Unknown signature OID.");throw t.signatureOid=e.signatureOid,t}},dd=function(e){var t=e.certificate,n=e.publicKey||t.publicKey,r;switch(t.signatureOid){case Pe.sha1WithRSAEncryption:case Pe.sha1WithRSASignature:break;case Pe["RSASSA-PSS"]:var i,s;if(i=Pe[t.signatureParameters.mgf.hash.algorithmOid],i===void 0||ie.md[i]===void 0){var a=Error("Unsupported MGF hash function.");throw a.oid=t.signatureParameters.mgf.hash.algorithmOid,a.name=i,a}if(s=Pe[t.signatureParameters.mgf.algorithmOid],s===void 0||ie.mgf[s]===void 0){var a=Error("Unsupported MGF function.");throw a.oid=t.signatureParameters.mgf.algorithmOid,a.name=s,a}if(s=ie.mgf[s].create(ie.md[i].create()),i=Pe[t.signatureParameters.hash.algorithmOid],i===void 0||ie.md[i]===void 0){var a=Error("Unsupported RSASSA-PSS hash function.");throw a.oid=t.signatureParameters.hash.algorithmOid,a.name=i,a}r=ie.pss.create(ie.md[i].create(),s,t.signatureParameters.saltLength);break}return n.verify(e.md.digest().getBytes(),e.signature,r)};M.certificateFromPem=function(e,t,n){var r=ie.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 s=g.fromDer(r.body,n);return M.certificateFromAsn1(s,t)};M.certificateToPem=function(e,t){var n={type:"CERTIFICATE",body:g.toDer(M.certificateToAsn1(e)).getBytes()};return ie.pem.encode(n,{maxline:t})};M.publicKeyFromPem=function(e){var t=ie.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=g.fromDer(t.body);return M.publicKeyFromAsn1(r)};M.publicKeyToPem=function(e,t){var n={type:"PUBLIC KEY",body:g.toDer(M.publicKeyToAsn1(e)).getBytes()};return ie.pem.encode(n,{maxline:t})};M.publicKeyToRSAPublicKeyPem=function(e,t){var n={type:"RSA PUBLIC KEY",body:g.toDer(M.publicKeyToRSAPublicKey(e)).getBytes()};return ie.pem.encode(n,{maxline:t})};M.getPublicKeyFingerprint=function(e,t){t=t||{};var n=t.md||ie.md.sha1.create(),r=t.type||"RSAPublicKey",i;switch(r){case"RSAPublicKey":i=g.toDer(M.publicKeyToRSAPublicKey(e)).getBytes();break;case"SubjectPublicKeyInfo":i=g.toDer(M.publicKeyToAsn1(e)).getBytes();break;default:throw Error('Unknown fingerprint type "'+t.type+'".')}n.start(),n.update(i);var s=n.digest();if(t.encoding==="hex"){var a=s.toHex();if(t.delimiter)return a.match(/.{2}/g).join(t.delimiter);return a}else if(t.encoding==="binary")return s.getBytes();else if(t.encoding)throw Error('Unknown encoding "'+t.encoding+'".');return s};M.certificationRequestFromPem=function(e,t,n){var r=ie.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 s=g.fromDer(r.body,n);return M.certificationRequestFromAsn1(s,t)};M.certificationRequestToPem=function(e,t){var n={type:"CERTIFICATE REQUEST",body:g.toDer(M.certificationRequestToAsn1(e)).getBytes()};return ie.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 Fr(e.issuer,t)},e.issuer.addField=function(t){Vt([t]),e.issuer.attributes.push(t)},e.issuer.attributes=[],e.issuer.hash=null,e.subject={},e.subject.getField=function(t){return Fr(e.subject,t)},e.subject.addField=function(t){Vt([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(Vt(t),e.subject.attributes=t,delete e.subject.uniqueId,n)e.subject.uniqueId=n;e.subject.hash=null},e.setIssuer=function(t,n){if(Vt(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)fd(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||ie.md.sha1.create();var r=Pe[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 s=g.toDer(e.tbsCertificate);e.md.update(s.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,s=Error("The parent certificate did not issue the given child certificate; the child certificate's issuer does not match the parent's subject.");throw s.expectedIssuer=i.attributes,s.actualIssuer=r.attributes,s}var a=t.md;if(a===null){a=zs({signatureOid:t.signatureOid,type:"certificate"});var o=t.tbsCertificate||M.getTBSCertificate(t),l=g.toDer(o);a.update(l.getBytes())}if(a!==null)n=dd({certificate:t,publicKey:e.publicKey,md:a,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 s,a;for(var o=0;n&&o<r.attributes.length;++o)if(s=r.attributes[o],a=i.attributes[o],s.type!==a.type||s.value!==a.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=Pe.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 ie.util.hexToBytes(r.subjectKeyIdentifier)===i}}return!1},e};M.certificateFromAsn1=function(e,t){var n={},r=[];if(!g.validate(e,Zm,n,r)){var i=Error("Cannot read X.509 certificate. ASN.1 object is not an X509v3 Certificate.");throw i.errors=r,i}var s=g.derToOid(n.publicKeyOid);if(s!==M.oids.rsaEncryption)throw Error("Cannot read public key. OID is not RSA.");var a=M.createCertificate();a.version=n.certVersion?n.certVersion.charCodeAt(0):0;var o=ie.util.createBuffer(n.certSerialNumber);a.serialNumber=o.toHex(),a.signatureOid=ie.asn1.derToOid(n.certSignatureOid),a.signatureParameters=js(a.signatureOid,n.certSignatureParams,!0),a.siginfo.algorithmOid=ie.asn1.derToOid(n.certinfoSignatureOid),a.siginfo.parameters=js(a.siginfo.algorithmOid,n.certinfoSignatureParams,!1),a.signature=n.certSignature;var l=[];if(n.certValidity1UTCTime!==void 0)l.push(g.utcTimeToDate(n.certValidity1UTCTime));if(n.certValidity2GeneralizedTime!==void 0)l.push(g.generalizedTimeToDate(n.certValidity2GeneralizedTime));if(n.certValidity3UTCTime!==void 0)l.push(g.utcTimeToDate(n.certValidity3UTCTime));if(n.certValidity4GeneralizedTime!==void 0)l.push(g.generalizedTimeToDate(n.certValidity4GeneralizedTime));if(l.length>2)throw Error("Cannot read notBefore/notAfter validity times; more than two times were provided in the certificate.");if(l.length<2)throw Error("Cannot read notBefore/notAfter validity times; they were not provided as either UTCTime or GeneralizedTime.");if(a.validity.notBefore=l[0],a.validity.notAfter=l[1],a.tbsCertificate=n.tbsCertificate,t){a.md=zs({signatureOid:a.signatureOid,type:"certificate"});var c=g.toDer(a.tbsCertificate);a.md.update(c.getBytes())}var u=ie.md.sha1.create(),d=g.toDer(n.certIssuer);if(u.update(d.getBytes()),a.issuer.getField=function(f){return Fr(a.issuer,f)},a.issuer.addField=function(f){Vt([f]),a.issuer.attributes.push(f)},a.issuer.attributes=M.RDNAttributesAsArray(n.certIssuer),n.certIssuerUniqueId)a.issuer.uniqueId=n.certIssuerUniqueId;a.issuer.hash=u.digest().toHex();var p=ie.md.sha1.create(),h=g.toDer(n.certSubject);if(p.update(h.getBytes()),a.subject.getField=function(f){return Fr(a.subject,f)},a.subject.addField=function(f){Vt([f]),a.subject.attributes.push(f)},a.subject.attributes=M.RDNAttributesAsArray(n.certSubject),n.certSubjectUniqueId)a.subject.uniqueId=n.certSubjectUniqueId;if(a.subject.hash=p.digest().toHex(),n.certExtensions)a.extensions=M.certificateExtensionsFromAsn1(n.certExtensions);else a.extensions=[];return a.publicKey=M.publicKeyFromAsn1(n.subjectPublicKeyInfo),a};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=g.derToOid(e.value[0].value),t.critical=!1,e.value[1].type===g.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 Pe){if(t.name=Pe[t.id],t.name==="keyUsage"){var n=g.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=g.fromDer(t.value);if(n.value.length>0&&n.value[0].type===g.Type.BOOLEAN)t.cA=n.value[0].value.charCodeAt(0)!==0;else t.cA=!1;var s=null;if(n.value.length>0&&n.value[0].type===g.Type.INTEGER)s=n.value[0].value;else if(n.value.length>1)s=n.value[1].value;if(s!==null)t.pathLenConstraint=g.derToInteger(s)}else if(t.name==="extKeyUsage"){var n=g.fromDer(t.value);for(var a=0;a<n.value.length;++a){var o=g.derToOid(n.value[a].value);if(o in Pe)t[Pe[o]]=!0;else t[o]=!0}}else if(t.name==="nsCertType"){var n=g.fromDer(t.value),r=0;if(n.value.length>1)r=n.value.charCodeAt(1);t.client=(r&128)===128,t.server=(r&64)===64,t.email=(r&32)===32,t.objsign=(r&16)===16,t.reserved=(r&8)===8,t.sslCA=(r&4)===4,t.emailCA=(r&2)===2,t.objCA=(r&1)===1}else if(t.name==="subjectAltName"||t.name==="issuerAltName"){t.altNames=[];var l,n=g.fromDer(t.value);for(var c=0;c<n.value.length;++c){l=n.value[c];var u={type:l.type,value:l.value};switch(t.altNames.push(u),l.type){case 1:case 2:case 6:break;case 7:u.ip=ie.util.bytesToIP(l.value);break;case 8:u.oid=g.derToOid(l.value);break;default:}}}else if(t.name==="subjectKeyIdentifier"){var n=g.fromDer(t.value);t.subjectKeyIdentifier=ie.util.bytesToHex(n.value)}}return t};M.certificationRequestFromAsn1=function(e,t){var n={},r=[];if(!g.validate(e,ry,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 s=g.derToOid(n.publicKeyOid);if(s!==M.oids.rsaEncryption)throw Error("Cannot read public key. OID is not RSA.");var a=M.createCertificationRequest();if(a.version=n.csrVersion?n.csrVersion.charCodeAt(0):0,a.signatureOid=ie.asn1.derToOid(n.csrSignatureOid),a.signatureParameters=js(a.signatureOid,n.csrSignatureParams,!0),a.siginfo.algorithmOid=ie.asn1.derToOid(n.csrSignatureOid),a.siginfo.parameters=js(a.siginfo.algorithmOid,n.csrSignatureParams,!1),a.signature=n.csrSignature,a.certificationRequestInfo=n.certificationRequestInfo,t){a.md=zs({signatureOid:a.signatureOid,type:"certification request"});var o=g.toDer(a.certificationRequestInfo);a.md.update(o.getBytes())}var l=ie.md.sha1.create();return a.subject.getField=function(c){return Fr(a.subject,c)},a.subject.addField=function(c){Vt([c]),a.subject.attributes.push(c)},a.subject.attributes=M.RDNAttributesAsArray(n.certificationRequestInfoSubject,l),a.subject.hash=l.digest().toHex(),a.publicKey=M.publicKeyFromAsn1(n.subjectPublicKeyInfo),a.getAttribute=function(c){return Fr(a,c)},a.addAttribute=function(c){Vt([c]),a.attributes.push(c)},a.attributes=M.CRIAttributesAsArray(n.certificationRequestInfoAttributes||[]),a};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 Fr(e.subject,t)},e.subject.addField=function(t){Vt([t]),e.subject.attributes.push(t)},e.subject.attributes=[],e.subject.hash=null,e.publicKey=null,e.attributes=[],e.getAttribute=function(t){return Fr(e,t)},e.addAttribute=function(t){Vt([t]),e.attributes.push(t)},e.md=null,e.setSubject=function(t){Vt(t),e.subject.attributes=t,e.subject.hash=null},e.setAttributes=function(t){Vt(t),e.attributes=t},e.sign=function(t,n){e.md=n||ie.md.sha1.create();var r=Pe[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 s=g.toDer(e.certificationRequestInfo);e.md.update(s.getBytes()),e.signature=t.sign(e.md)},e.verify=function(){var t=!1,n=e.md;if(n===null){n=zs({signatureOid:e.signatureOid,type:"certification request"});var r=e.certificationRequestInfo||M.getCertificationRequestInfo(e),i=g.toDer(r);n.update(i.getBytes())}if(n!==null)t=dd({certificate:e,md:n,signature:e.signature});return t},e};function Nn(e){var t=g.create(g.Class.UNIVERSAL,g.Type.SEQUENCE,!0,[]),n,r,i=e.attributes;for(var s=0;s<i.length;++s){n=i[s];var a=n.value,o=g.Type.PRINTABLESTRING;if("valueTagClass"in n){if(o=n.valueTagClass,o===g.Type.UTF8)a=ie.util.encodeUtf8(a)}r=g.create(g.Class.UNIVERSAL,g.Type.SET,!0,[g.create(g.Class.UNIVERSAL,g.Type.SEQUENCE,!0,[g.create(g.Class.UNIVERSAL,g.Type.OID,!1,g.oidToDer(n.type).getBytes()),g.create(g.Class.UNIVERSAL,o,!1,a)])]),t.value.push(r)}return t}function Vt(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 Ye)t.name=M.oids[Ye[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 Ye)t.shortName=Ye[t.name]}if(t.type===Pe.extensionRequest){if(t.valueConstructed=!0,t.valueTagClass=g.Type.SEQUENCE,!t.value&&t.extensions){t.value=[];for(var i=0;i<t.extensions.length;++i)t.value.push(M.certificateExtensionToAsn1(fd(t.extensions[i])))}}if(typeof t.value>"u"){var r=Error("Attribute value not specified.");throw r.attribute=t,r}}}function fd(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,s=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)s|=128,r=7;var a=String.fromCharCode(r);if(s!==0)a+=String.fromCharCode(i)+String.fromCharCode(s);else if(i!==0)a+=String.fromCharCode(i);e.value=g.create(g.Class.UNIVERSAL,g.Type.BITSTRING,!1,a)}else if(e.name==="basicConstraints"){if(e.value=g.create(g.Class.UNIVERSAL,g.Type.SEQUENCE,!0,[]),e.cA)e.value.value.push(g.create(g.Class.UNIVERSAL,g.Type.BOOLEAN,!1,String.fromCharCode(255)));if("pathLenConstraint"in e)e.value.value.push(g.create(g.Class.UNIVERSAL,g.Type.INTEGER,!1,g.integerToDer(e.pathLenConstraint).getBytes()))}else if(e.name==="extKeyUsage"){e.value=g.create(g.Class.UNIVERSAL,g.Type.SEQUENCE,!0,[]);var o=e.value.value;for(var l in e){if(e[l]!==!0)continue;if(l in Pe)o.push(g.create(g.Class.UNIVERSAL,g.Type.OID,!1,g.oidToDer(Pe[l]).getBytes()));else if(l.indexOf(".")!==-1)o.push(g.create(g.Class.UNIVERSAL,g.Type.OID,!1,g.oidToDer(l).getBytes()))}}else if(e.name==="nsCertType"){var r=0,i=0;if(e.client)i|=128,r=7;if(e.server)i|=64,r=6;if(e.email)i|=32,r=5;if(e.objsign)i|=16,r=4;if(e.reserved)i|=8,r=3;if(e.sslCA)i|=4,r=2;if(e.emailCA)i|=2,r=1;if(e.objCA)i|=1,r=0;var a=String.fromCharCode(r);if(i!==0)a+=String.fromCharCode(i);e.value=g.create(g.Class.UNIVERSAL,g.Type.BITSTRING,!1,a)}else if(e.name==="subjectAltName"||e.name==="issuerAltName"){e.value=g.create(g.Class.UNIVERSAL,g.Type.SEQUENCE,!0,[]);var c;for(var u=0;u<e.altNames.length;++u){c=e.altNames[u];var a=c.value;if(c.type===7&&c.ip){if(a=ie.util.bytesFromIP(c.ip),a===null){var n=Error('Extension "ip" value is not a valid IPv4 or IPv6 address.');throw n.extension=e,n}}else if(c.type===8)if(c.oid)a=g.oidToDer(g.oidToDer(c.oid));else a=g.oidToDer(a);e.value.value.push(g.create(g.Class.CONTEXT_SPECIFIC,c.type,!1,a))}}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=g.create(g.Class.UNIVERSAL,g.Type.IA5STRING,!1,e.comment)}else if(e.name==="subjectKeyIdentifier"&&t.cert){var d=t.cert.generateSubjectKeyIdentifier();e.subjectKeyIdentifier=d.toHex(),e.value=g.create(g.Class.UNIVERSAL,g.Type.OCTETSTRING,!1,d.getBytes())}else if(e.name==="authorityKeyIdentifier"&&t.cert){e.value=g.create(g.Class.UNIVERSAL,g.Type.SEQUENCE,!0,[]);var o=e.value.value;if(e.keyIdentifier){var p=e.keyIdentifier===!0?t.cert.generateSubjectKeyIdentifier().getBytes():e.keyIdentifier;o.push(g.create(g.Class.CONTEXT_SPECIFIC,0,!1,p))}if(e.authorityCertIssuer){var h=[g.create(g.Class.CONTEXT_SPECIFIC,4,!0,[Nn(e.authorityCertIssuer===!0?t.cert.issuer:e.authorityCertIssuer)])];o.push(g.create(g.Class.CONTEXT_SPECIFIC,1,!0,h))}if(e.serialNumber){var f=ie.util.hexToBytes(e.serialNumber===!0?t.cert.serialNumber:e.serialNumber);o.push(g.create(g.Class.CONTEXT_SPECIFIC,2,!1,f))}}else if(e.name==="cRLDistributionPoints"){e.value=g.create(g.Class.UNIVERSAL,g.Type.SEQUENCE,!0,[]);var o=e.value.value,v=g.create(g.Class.UNIVERSAL,g.Type.SEQUENCE,!0,[]),x=g.create(g.Class.CONTEXT_SPECIFIC,0,!0,[]),c;for(var u=0;u<e.altNames.length;++u){c=e.altNames[u];var a=c.value;if(c.type===7&&c.ip){if(a=ie.util.bytesFromIP(c.ip),a===null){var n=Error('Extension "ip" value is not a valid IPv4 or IPv6 address.');throw n.extension=e,n}}else if(c.type===8)if(c.oid)a=g.oidToDer(g.oidToDer(c.oid));else a=g.oidToDer(a);x.value.push(g.create(g.Class.CONTEXT_SPECIFIC,c.type,!1,a))}v.value.push(g.create(g.Class.CONTEXT_SPECIFIC,0,!0,[x])),o.push(v)}if(typeof e.value>"u"){var n=Error("Extension value not specified.");throw n.extension=e,n}return e}function Uo(e,t){switch(e){case Pe["RSASSA-PSS"]:var n=[];if(t.hash.algorithmOid!==void 0)n.push(g.create(g.Class.CONTEXT_SPECIFIC,0,!0,[g.create(g.Class.UNIVERSAL,g.Type.SEQUENCE,!0,[g.create(g.Class.UNIVERSAL,g.Type.OID,!1,g.oidToDer(t.hash.algorithmOid).getBytes()),g.create(g.Class.UNIVERSAL,g.Type.NULL,!1,"")])]));if(t.mgf.algorithmOid!==void 0)n.push(g.create(g.Class.CONTEXT_SPECIFIC,1,!0,[g.create(g.Class.UNIVERSAL,g.Type.SEQUENCE,!0,[g.create(g.Class.UNIVERSAL,g.Type.OID,!1,g.oidToDer(t.mgf.algorithmOid).getBytes()),g.create(g.Class.UNIVERSAL,g.Type.SEQUENCE,!0,[g.create(g.Class.UNIVERSAL,g.Type.OID,!1,g.oidToDer(t.mgf.hash.algorithmOid).getBytes()),g.create(g.Class.UNIVERSAL,g.Type.NULL,!1,"")])])]));if(t.saltLength!==void 0)n.push(g.create(g.Class.CONTEXT_SPECIFIC,2,!0,[g.create(g.Class.UNIVERSAL,g.Type.INTEGER,!1,g.integerToDer(t.saltLength).getBytes())]));return g.create(g.Class.UNIVERSAL,g.Type.SEQUENCE,!0,n);default:return g.create(g.Class.UNIVERSAL,g.Type.NULL,!1,"")}}function ny(e){var t=g.create(g.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],s=i.value,a=g.Type.UTF8;if("valueTagClass"in i)a=i.valueTagClass;if(a===g.Type.UTF8)s=ie.util.encodeUtf8(s);var o=!1;if("valueConstructed"in i)o=i.valueConstructed;var l=g.create(g.Class.UNIVERSAL,g.Type.SEQUENCE,!0,[g.create(g.Class.UNIVERSAL,g.Type.OID,!1,g.oidToDer(i.type).getBytes()),g.create(g.Class.UNIVERSAL,g.Type.SET,!0,[g.create(g.Class.UNIVERSAL,a,o,s)])]);t.value.push(l)}return t}var iy=new Date("1950-01-01T00:00:00Z"),sy=new Date("2050-01-01T00:00:00Z");function cd(e){if(e>=iy&&e<sy)return g.create(g.Class.UNIVERSAL,g.Type.UTCTIME,!1,g.dateToUtcTime(e));else return g.create(g.Class.UNIVERSAL,g.Type.GENERALIZEDTIME,!1,g.dateToGeneralizedTime(e))}M.getTBSCertificate=function(e){var t=cd(e.validity.notBefore),n=cd(e.validity.notAfter),r=g.create(g.Class.UNIVERSAL,g.Type.SEQUENCE,!0,[g.create(g.Class.CONTEXT_SPECIFIC,0,!0,[g.create(g.Class.UNIVERSAL,g.Type.INTEGER,!1,g.integerToDer(e.version).getBytes())]),g.create(g.Class.UNIVERSAL,g.Type.INTEGER,!1,ie.util.hexToBytes(e.serialNumber)),g.create(g.Class.UNIVERSAL,g.Type.SEQUENCE,!0,[g.create(g.Class.UNIVERSAL,g.Type.OID,!1,g.oidToDer(e.siginfo.algorithmOid).getBytes()),Uo(e.siginfo.algorithmOid,e.siginfo.parameters)]),Nn(e.issuer),g.create(g.Class.UNIVERSAL,g.Type.SEQUENCE,!0,[t,n]),Nn(e.subject),M.publicKeyToAsn1(e.publicKey)]);if(e.issuer.uniqueId)r.value.push(g.create(g.Class.CONTEXT_SPECIFIC,1,!0,[g.create(g.Class.UNIVERSAL,g.Type.BITSTRING,!1,String.fromCharCode(0)+e.issuer.uniqueId)]));if(e.subject.uniqueId)r.value.push(g.create(g.Class.CONTEXT_SPECIFIC,2,!0,[g.create(g.Class.UNIVERSAL,g.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=g.create(g.Class.UNIVERSAL,g.Type.SEQUENCE,!0,[g.create(g.Class.UNIVERSAL,g.Type.INTEGER,!1,g.integerToDer(e.version).getBytes()),Nn(e.subject),M.publicKeyToAsn1(e.publicKey),ny(e)]);return t};M.distinguishedNameToAsn1=function(e){return Nn(e)};M.certificateToAsn1=function(e){var t=e.tbsCertificate||M.getTBSCertificate(e);return g.create(g.Class.UNIVERSAL,g.Type.SEQUENCE,!0,[t,g.create(g.Class.UNIVERSAL,g.Type.SEQUENCE,!0,[g.create(g.Class.UNIVERSAL,g.Type.OID,!1,g.oidToDer(e.signatureOid).getBytes()),Uo(e.signatureOid,e.signatureParameters)]),g.create(g.Class.UNIVERSAL,g.Type.BITSTRING,!1,String.fromCharCode(0)+e.signature)])};M.certificateExtensionsToAsn1=function(e){var t=g.create(g.Class.CONTEXT_SPECIFIC,3,!0,[]),n=g.create(g.Class.UNIVERSAL,g.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=g.create(g.Class.UNIVERSAL,g.Type.SEQUENCE,!0,[]);if(t.value.push(g.create(g.Class.UNIVERSAL,g.Type.OID,!1,g.oidToDer(e.id).getBytes())),e.critical)t.value.push(g.create(g.Class.UNIVERSAL,g.Type.BOOLEAN,!1,String.fromCharCode(255)));var n=e.value;if(typeof e.value!=="string")n=g.toDer(n).getBytes();return t.value.push(g.create(g.Class.UNIVERSAL,g.Type.OCTETSTRING,!1,n)),t};M.certificationRequestToAsn1=function(e){var t=e.certificationRequestInfo||M.getCertificationRequestInfo(e);return g.create(g.Class.UNIVERSAL,g.Type.SEQUENCE,!0,[t,g.create(g.Class.UNIVERSAL,g.Type.SEQUENCE,!0,[g.create(g.Class.UNIVERSAL,g.Type.OID,!1,g.oidToDer(e.signatureOid).getBytes()),Uo(e.signatureOid,e.signatureParameters)]),g.create(g.Class.UNIVERSAL,g.Type.BITSTRING,!1,String.fromCharCode(0)+e.signature)])};M.createCaStore=function(e){var t={certs:{}};t.getIssuer=function(a){var o=n(a.issuer);return o},t.addCertificate=function(a){if(typeof a==="string")a=ie.pki.certificateFromPem(a);if(r(a.subject),!t.hasCertificate(a))if(a.subject.hash in t.certs){var o=t.certs[a.subject.hash];if(!ie.util.isArray(o))o=[o];o.push(a),t.certs[a.subject.hash]=o}else t.certs[a.subject.hash]=a},t.hasCertificate=function(a){if(typeof a==="string")a=ie.pki.certificateFromPem(a);var o=n(a.subject);if(!o)return!1;if(!ie.util.isArray(o))o=[o];var l=g.toDer(M.certificateToAsn1(a)).getBytes();for(var c=0;c<o.length;++c){var u=g.toDer(M.certificateToAsn1(o[c])).getBytes();if(l===u)return!0}return!1},t.listAllCertificates=function(){var a=[];for(var o in t.certs)if(t.certs.hasOwnProperty(o)){var l=t.certs[o];if(!ie.util.isArray(l))a.push(l);else for(var c=0;c<l.length;++c)a.push(l[c])}return a},t.removeCertificate=function(a){var o;if(typeof a==="string")a=ie.pki.certificateFromPem(a);if(r(a.subject),!t.hasCertificate(a))return null;var l=n(a.subject);if(!ie.util.isArray(l))return o=t.certs[a.subject.hash],delete t.certs[a.subject.hash],o;var c=g.toDer(M.certificateToAsn1(a)).getBytes();for(var u=0;u<l.length;++u){var d=g.toDer(M.certificateToAsn1(l[u])).getBytes();if(c===d)o=l[u],l.splice(u,1)}if(l.length===0)delete t.certs[a.subject.hash];return o};function n(a){return r(a),t.certs[a.hash]||null}function r(a){if(!a.hash){var o=ie.md.sha1.create();a.attributes=M.RDNAttributesAsArray(Nn(a),o),a.hash=o.digest().toHex()}}if(e)for(var i=0;i<e.length;++i){var s=e[i];t.addCertificate(s)}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"};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 s=!0,a=null,o=0;do{var l=t.shift(),c=null,u=!1;if(i){if(i<l.validity.notBefore||i>l.validity.notAfter)a={message:"Certificate is not valid yet or has expired.",error:M.certificateError.certificate_expired,notBefore:l.validity.notBefore,notAfter:l.validity.notAfter,now:i}}if(a===null){if(c=t[0]||e.getIssuer(l),c===null){if(l.isIssuer(l))u=!0,c=l}if(c){var d=ie.util.isArray(c)?c.slice():[c],p=!1;while(!p&&d.length>0){c=d.shift();try{p=c.verify(l)}catch(R){}}if(!p)a={message:"Certificate signature is invalid.",error:M.certificateError.bad_certificate}}if(a===null&&(!c||u)&&!e.hasCertificate(l))a={message:"Certificate is not trusted.",error:M.certificateError.unknown_ca}}if(a===null&&c&&!l.isIssuer(c))a={message:"Certificate issuer is invalid.",error:M.certificateError.bad_certificate};if(a===null){var h={keyUsage:!0,basicConstraints:!0};for(var f=0;a===null&&f<l.extensions.length;++f){var v=l.extensions[f];if(v.critical&&!(v.name in h))a={message:"Certificate has an unsupported critical extension.",error:M.certificateError.unsupported_certificate}}}if(a===null&&(!s||t.length===0&&(!c||u))){var x=l.getExtension({id:"2.5.29.19"}),S=l.getExtension("keyUsage");if(S!==null){if(!S.keyCertSign||x===null)a={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(a===null&&x===null)a={message:"Certificate is missing basicConstraints extension and cannot be used as a CA.",error:M.certificateError.bad_certificate};if(a===null&&x!==null&&!x.cA)a={message:"Certificate basicConstraints indicates the certificate is not a CA.",error:M.certificateError.bad_certificate};if(a===null&&x!==null&&"pathLenConstraint"in x){var A=o-1;if(A>x.pathLenConstraint)a={message:"Certificate basicConstraints pathLenConstraint violated.",error:M.certificateError.bad_certificate}}}var b=a===null?!0:a.error,k=n.verify?n.verify(b,o,r):b;if(k===!0)a=null;else{if(b===!0)a={message:"The application rejected the certificate.",error:M.certificateError.bad_certificate};if(k||k===0){if(typeof k==="object"&&!ie.util.isArray(k)){if(k.message)a.message=k.message;if(k.error)a.error=k.error}else if(typeof k==="string")a.error=k}throw a}s=!1,++o}while(t.length>0);return!0}});var Fo=de(function(N1,gd){var Ke=ye();Gt();An();Or();Lo();Do();Lt();wi();Rn();Ne();Xs();var{asn1:C,pki:Ee}=Ke,Ti=gd.exports=Ke.pkcs12=Ke.pkcs12||{},hd={name:"ContentInfo",tagClass:C.Class.UNIVERSAL,type:C.Type.SEQUENCE,constructed:!0,value:[{name:"ContentInfo.contentType",tagClass:C.Class.UNIVERSAL,type:C.Type.OID,constructed:!1,capture:"contentType"},{name:"ContentInfo.content",tagClass:C.Class.CONTEXT_SPECIFIC,constructed:!0,captureAsn1:"content"}]},ay={name:"PFX",tagClass:C.Class.UNIVERSAL,type:C.Type.SEQUENCE,constructed:!0,value:[{name:"PFX.version",tagClass:C.Class.UNIVERSAL,type:C.Type.INTEGER,constructed:!1,capture:"version"},hd,{name:"PFX.macData",tagClass:C.Class.UNIVERSAL,type:C.Type.SEQUENCE,constructed:!0,optional:!0,captureAsn1:"mac",value:[{name:"PFX.macData.mac",tagClass:C.Class.UNIVERSAL,type:C.Type.SEQUENCE,constructed:!0,value:[{name:"PFX.macData.mac.digestAlgorithm",tagClass:C.Class.UNIVERSAL,type:C.Type.SEQUENCE,constructed:!0,value:[{name:"PFX.macData.mac.digestAlgorithm.algorithm",tagClass:C.Class.UNIVERSAL,type:C.Type.OID,constructed:!1,capture:"macAlgorithm"},{name:"PFX.macData.mac.digestAlgorithm.parameters",optional:!0,tagClass:C.Class.UNIVERSAL,captureAsn1:"macAlgorithmParameters"}]},{name:"PFX.macData.mac.digest",tagClass:C.Class.UNIVERSAL,type:C.Type.OCTETSTRING,constructed:!1,capture:"macDigest"}]},{name:"PFX.macData.macSalt",tagClass:C.Class.UNIVERSAL,type:C.Type.OCTETSTRING,constructed:!1,capture:"macSalt"},{name:"PFX.macData.iterations",tagClass:C.Class.UNIVERSAL,type:C.Type.INTEGER,constructed:!1,optional:!0,capture:"macIterations"}]}]},oy={name:"SafeBag",tagClass:C.Class.UNIVERSAL,type:C.Type.SEQUENCE,constructed:!0,value:[{name:"SafeBag.bagId",tagClass:C.Class.UNIVERSAL,type:C.Type.OID,constructed:!1,capture:"bagId"},{name:"SafeBag.bagValue",tagClass:C.Class.CONTEXT_SPECIFIC,constructed:!0,captureAsn1:"bagValue"},{name:"SafeBag.bagAttributes",tagClass:C.Class.UNIVERSAL,type:C.Type.SET,constructed:!0,optional:!0,capture:"bagAttributes"}]},ly={name:"Attribute",tagClass:C.Class.UNIVERSAL,type:C.Type.SEQUENCE,constructed:!0,value:[{name:"Attribute.attrId",tagClass:C.Class.UNIVERSAL,type:C.Type.OID,constructed:!1,capture:"oid"},{name:"Attribute.attrValues",tagClass:C.Class.UNIVERSAL,type:C.Type.SET,constructed:!0,capture:"values"}]},cy={name:"CertBag",tagClass:C.Class.UNIVERSAL,type:C.Type.SEQUENCE,constructed:!0,value:[{name:"CertBag.certId",tagClass:C.Class.UNIVERSAL,type:C.Type.OID,constructed:!1,capture:"certId"},{name:"CertBag.certValue",tagClass:C.Class.CONTEXT_SPECIFIC,constructed:!0,value:[{name:"CertBag.certValue[0]",tagClass:C.Class.UNIVERSAL,type:C.Class.OCTETSTRING,constructed:!1,capture:"cert"}]}]};function Ei(e,t,n,r){var i=[];for(var s=0;s<e.length;s++)for(var a=0;a<e[s].safeBags.length;a++){var o=e[s].safeBags[a];if(r!==void 0&&o.type!==r)continue;if(t===null){i.push(o);continue}if(o.attributes[t]!==void 0&&o.attributes[t].indexOf(n)>=0)i.push(o)}return i}Ti.pkcs12FromAsn1=function(e,t,n){if(typeof t==="string")n=t,t=!0;else if(t===void 0)t=!0;var r={},i=[];if(!C.validate(e,ay,r,i)){var s=Error("Cannot read PKCS#12 PFX. ASN.1 object is not an PKCS#12 PFX.");throw s.errors=s,s}var a={version:r.version.charCodeAt(0),safeContents:[],getBags:function(x){var S={},A;if("localKeyId"in x)A=x.localKeyId;else if("localKeyIdHex"in x)A=Ke.util.hexToBytes(x.localKeyIdHex);if(A===void 0&&!("friendlyName"in x)&&"bagType"in x)S[x.bagType]=Ei(a.safeContents,null,null,x.bagType);if(A!==void 0)S.localKeyId=Ei(a.safeContents,"localKeyId",A,x.bagType);if("friendlyName"in x)S.friendlyName=Ei(a.safeContents,"friendlyName",x.friendlyName,x.bagType);return S},getBagsByFriendlyName:function(x,S){return Ei(a.safeContents,"friendlyName",x,S)},getBagsByLocalKeyId:function(x,S){return Ei(a.safeContents,"localKeyId",x,S)}};if(r.version.charCodeAt(0)!==3){var s=Error("PKCS#12 PFX of version other than 3 not supported.");throw s.version=r.version.charCodeAt(0),s}if(C.derToOid(r.contentType)!==Ee.oids.data){var s=Error("Only PKCS#12 PFX in password integrity mode supported.");throw s.oid=C.derToOid(r.contentType),s}var o=r.content.value[0];if(o.tagClass!==C.Class.UNIVERSAL||o.type!==C.Type.OCTETSTRING)throw Error("PKCS#12 authSafe content data is not an OCTET STRING.");if(o=Vo(o),r.mac){var l=null,c=0,u=C.derToOid(r.macAlgorithm);switch(u){case Ee.oids.sha1:l=Ke.md.sha1.create(),c=20;break;case Ee.oids.sha256:l=Ke.md.sha256.create(),c=32;break;case Ee.oids.sha384:l=Ke.md.sha384.create(),c=48;break;case Ee.oids.sha512:l=Ke.md.sha512.create(),c=64;break;case Ee.oids.md5:l=Ke.md.md5.create(),c=16;break}if(l===null)throw Error("PKCS#12 uses unsupported MAC algorithm: "+u);var d=new Ke.util.ByteBuffer(r.macSalt),p="macIterations"in r?parseInt(Ke.util.bytesToHex(r.macIterations),16):1;if(!(p>=1))throw Error("PKCS#12 MAC iteration count must be >= 1.");var h=Ti.generateKey(n,d,3,p,c,l),f=Ke.hmac.create();f.start(l,h),f.update(o.value);var v=f.getMac();if(v.getBytes()!==r.macDigest)throw Error("PKCS#12 MAC could not be verified. Invalid password?")}else if(Array.isArray(e.value)&&e.value.length>2)throw Error("Invalid PKCS#12. macData field present but MAC was not validated.");return uy(a,o.value,t,n),a};function Vo(e){if(e.composed||e.constructed){var t=Ke.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 uy(e,t,n,r){if(t=C.fromDer(t,n),t.tagClass!==C.Class.UNIVERSAL||t.type!==C.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 s=t.value[i],a={},o=[];if(!C.validate(s,hd,a,o)){var l=Error("Cannot read ContentInfo.");throw l.errors=o,l}var c={encrypted:!1},u=null,d=a.content.value[0];switch(C.derToOid(a.contentType)){case Ee.oids.data:if(d.tagClass!==C.Class.UNIVERSAL||d.type!==C.Type.OCTETSTRING)throw Error("PKCS#12 SafeContents Data is not an OCTET STRING.");u=Vo(d).value;break;case Ee.oids.encryptedData:u=dy(d,r),c.encrypted=!0;break;default:var l=Error("Unsupported PKCS#12 contentType.");throw l.contentType=C.derToOid(a.contentType),l}c.safeBags=fy(u,n,r),e.safeContents.push(c)}}function dy(e,t){var n={},r=[];if(!C.validate(e,Ke.pkcs7.asn1.encryptedDataValidator,n,r)){var i=Error("Cannot read EncryptedContentInfo.");throw i.errors=r,i}var s=C.derToOid(n.contentType);if(s!==Ee.oids.data){var i=Error("PKCS#12 EncryptedContentInfo ContentType is not Data.");throw i.oid=s,i}s=C.derToOid(n.encAlgorithm);var a=Ee.pbe.getCipher(s,n.encParameter,t),o=Vo(n.encryptedContentAsn1),l=Ke.util.createBuffer(o.value);if(a.update(l),!a.finish())throw Error("Failed to decrypt PKCS#12 SafeContents.");return a.output.getBytes()}function fy(e,t,n){if(!t&&e.length===0)return[];if(e=C.fromDer(e,t),e.tagClass!==C.Class.UNIVERSAL||e.type!==C.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 s=e.value[i],a={},o=[];if(!C.validate(s,oy,a,o)){var l=Error("Cannot read SafeBag.");throw l.errors=o,l}var c={type:C.derToOid(a.bagId),attributes:py(a.bagAttributes)};r.push(c);var u,d,p=a.bagValue.value[0];switch(c.type){case Ee.oids.pkcs8ShroudedKeyBag:if(p=Ee.decryptPrivateKeyInfo(p,n),p===null)throw Error("Unable to decrypt PKCS#8 ShroudedKeyBag, wrong password?");case Ee.oids.keyBag:try{c.key=Ee.privateKeyFromAsn1(p)}catch(f){c.key=null,c.asn1=p}continue;case Ee.oids.certBag:u=cy,d=function(){if(C.derToOid(a.certId)!==Ee.oids.x509Certificate){var f=Error("Unsupported certificate type, only X.509 supported.");throw f.oid=C.derToOid(a.certId),f}var v=C.fromDer(a.cert,t);try{c.cert=Ee.certificateFromAsn1(v,!0)}catch(x){c.cert=null,c.asn1=v}};break;default:var l=Error("Unsupported PKCS#12 SafeBag type.");throw l.oid=c.type,l}if(u!==void 0&&!C.validate(p,u,a,o)){var l=Error("Cannot read PKCS#12 "+u.name);throw l.errors=o,l}d()}return r}function py(e){var t={};if(e!==void 0)for(var n=0;n<e.length;++n){var r={},i=[];if(!C.validate(e[n],ly,r,i)){var s=Error("Cannot read PKCS#12 BagAttribute.");throw s.errors=i,s}var a=C.derToOid(r.oid);if(Ee.oids[a]===void 0)continue;t[Ee.oids[a]]=[];for(var o=0;o<r.values.length;++o)t[Ee.oids[a]].push(r.values[o].value)}return t}Ti.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,s;if(i!==null)i=Ke.util.hexToBytes(i);else if(r.generateLocalKeyId)if(t){var a=Ke.util.isArray(t)?t[0]:t;if(typeof a==="string")a=Ee.certificateFromPem(a);var o=Ke.md.sha1.create();o.update(C.toDer(Ee.certificateToAsn1(a)).getBytes()),i=o.digest().getBytes()}else i=Ke.random.getBytes(20);var l=[];if(i!==null)l.push(C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,[C.create(C.Class.UNIVERSAL,C.Type.OID,!1,C.oidToDer(Ee.oids.localKeyId).getBytes()),C.create(C.Class.UNIVERSAL,C.Type.SET,!0,[C.create(C.Class.UNIVERSAL,C.Type.OCTETSTRING,!1,i)])]));if("friendlyName"in r)l.push(C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,[C.create(C.Class.UNIVERSAL,C.Type.OID,!1,C.oidToDer(Ee.oids.friendlyName).getBytes()),C.create(C.Class.UNIVERSAL,C.Type.SET,!0,[C.create(C.Class.UNIVERSAL,C.Type.BMPSTRING,!1,r.friendlyName)])]));if(l.length>0)s=C.create(C.Class.UNIVERSAL,C.Type.SET,!0,l);var c=[],u=[];if(t!==null)if(Ke.util.isArray(t))u=t;else u=[t];var d=[];for(var p=0;p<u.length;++p){if(t=u[p],typeof t==="string")t=Ee.certificateFromPem(t);var h=p===0?s:void 0,f=Ee.certificateToAsn1(t),v=C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,[C.create(C.Class.UNIVERSAL,C.Type.OID,!1,C.oidToDer(Ee.oids.certBag).getBytes()),C.create(C.Class.CONTEXT_SPECIFIC,0,!0,[C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,[C.create(C.Class.UNIVERSAL,C.Type.OID,!1,C.oidToDer(Ee.oids.x509Certificate).getBytes()),C.create(C.Class.CONTEXT_SPECIFIC,0,!0,[C.create(C.Class.UNIVERSAL,C.Type.OCTETSTRING,!1,C.toDer(f).getBytes())])])]),h]);d.push(v)}if(d.length>0){var x=C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,d),S=C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,[C.create(C.Class.UNIVERSAL,C.Type.OID,!1,C.oidToDer(Ee.oids.data).getBytes()),C.create(C.Class.CONTEXT_SPECIFIC,0,!0,[C.create(C.Class.UNIVERSAL,C.Type.OCTETSTRING,!1,C.toDer(x).getBytes())])]);c.push(S)}var A=null;if(e!==null){var b=Ee.wrapRsaPrivateKey(Ee.privateKeyToAsn1(e));if(n===null)A=C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,[C.create(C.Class.UNIVERSAL,C.Type.OID,!1,C.oidToDer(Ee.oids.keyBag).getBytes()),C.create(C.Class.CONTEXT_SPECIFIC,0,!0,[b]),s]);else A=C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,[C.create(C.Class.UNIVERSAL,C.Type.OID,!1,C.oidToDer(Ee.oids.pkcs8ShroudedKeyBag).getBytes()),C.create(C.Class.CONTEXT_SPECIFIC,0,!0,[Ee.encryptPrivateKeyInfo(b,n,r)]),s]);var k=C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,[A]),R=C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,[C.create(C.Class.UNIVERSAL,C.Type.OID,!1,C.oidToDer(Ee.oids.data).getBytes()),C.create(C.Class.CONTEXT_SPECIFIC,0,!0,[C.create(C.Class.UNIVERSAL,C.Type.OCTETSTRING,!1,C.toDer(k).getBytes())])]);c.push(R)}var I=C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,c),V;if(r.useMac){var o=Ke.md.sha1.create(),J=new Ke.util.ByteBuffer(Ke.random.getBytes(r.saltSize)),D=r.count,e=Ti.generateKey(n,J,3,D,20),W=Ke.hmac.create();W.start(o,e),W.update(C.toDer(I).getBytes());var Z=W.getMac();V=C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,[C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,[C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,[C.create(C.Class.UNIVERSAL,C.Type.OID,!1,C.oidToDer(Ee.oids.sha1).getBytes()),C.create(C.Class.UNIVERSAL,C.Type.NULL,!1,"")]),C.create(C.Class.UNIVERSAL,C.Type.OCTETSTRING,!1,Z.getBytes())]),C.create(C.Class.UNIVERSAL,C.Type.OCTETSTRING,!1,J.getBytes()),C.create(C.Class.UNIVERSAL,C.Type.INTEGER,!1,C.integerToDer(D).getBytes())])}return C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,[C.create(C.Class.UNIVERSAL,C.Type.INTEGER,!1,C.integerToDer(3).getBytes()),C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,[C.create(C.Class.UNIVERSAL,C.Type.OID,!1,C.oidToDer(Ee.oids.data).getBytes()),C.create(C.Class.CONTEXT_SPECIFIC,0,!0,[C.create(C.Class.UNIVERSAL,C.Type.OCTETSTRING,!1,C.toDer(I).getBytes())])]),V])};Ti.generateKey=Ke.pbe.generatePkcs12Key});var $o=de(function(D1,md){var Mr=ye();Gt();Or();Do();sn();Fs();Fo();Gs();wi();Ne();Xs();var Mo=Mr.asn1,Dn=md.exports=Mr.pki=Mr.pki||{};Dn.pemToDer=function(e){var t=Mr.pem.decode(e)[0];if(t.procType&&t.procType.type==="ENCRYPTED")throw Error("Could not convert PEM to DER; PEM is encrypted.");return Mr.util.createBuffer(t.body)};Dn.privateKeyFromPem=function(e){var t=Mr.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=Mo.fromDer(t.body);return Dn.privateKeyFromAsn1(r)};Dn.privateKeyToPem=function(e,t){var n={type:"RSA PRIVATE KEY",body:Mo.toDer(Dn.privateKeyToAsn1(e)).getBytes()};return Mr.pem.encode(n,{maxline:t})};Dn.privateKeyInfoToPem=function(e,t){var n={type:"PRIVATE KEY",body:Mo.toDer(e).getBytes()};return Mr.pem.encode(n,{maxline:t})}});var jo=de(function(L1,Ed){var O=ye();Gt();An();Ls();sn();$o();Lt();Rn();Ne();var Js=function(e,t,n,r){var i=O.util.createBuffer(),s=e.length>>1,a=s+(e.length&1),o=e.substr(0,a),l=e.substr(s,a),c=O.util.createBuffer(),u=O.hmac.create();n=t+n;var d=Math.ceil(r/16),p=Math.ceil(r/20);u.start("MD5",o);var h=O.util.createBuffer();c.putBytes(n);for(var f=0;f<d;++f)u.start(null,null),u.update(c.getBytes()),c.putBuffer(u.digest()),u.start(null,null),u.update(c.bytes()+n),h.putBuffer(u.digest());u.start("SHA1",l);var v=O.util.createBuffer();c.clear(),c.putBytes(n);for(var f=0;f<p;++f)u.start(null,null),u.update(c.getBytes()),c.putBuffer(u.digest()),u.start(null,null),u.update(c.bytes()+n),v.putBuffer(u.digest());return i.putBytes(O.util.xorBytes(h.getBytes(),v.getBytes(),r)),i},hy=function(e,t,n){var r=O.hmac.create();r.start("SHA1",e);var i=O.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()},gy=function(e,t,n){var r=!1;try{var i=e.deflate(t.fragment.getBytes());t.fragment=O.util.createBuffer(i),t.length=i.length,r=!0}catch(s){}return r},my=function(e,t,n){var r=!1;try{var i=e.inflate(t.fragment.getBytes());t.fragment=O.util.createBuffer(i),t.length=i.length,r=!0}catch(s){}return r},It=function(e,t){var n=0;switch(t){case 1:n=e.getByte();break;case 2:n=e.getInt16();break;case 3:n=e.getInt24();break;case 4:n=e.getInt32();break}return O.util.createBuffer(e.getBytes(n))},Ft=function(e,t,n){e.putInt(n.length(),t<<3),e.putBuffer(n)},y={};y.Versions={TLS_1_0:{major:3,minor:1},TLS_1_1:{major:3,minor:2},TLS_1_2:{major:3,minor:3}};y.SupportedVersions=[y.Versions.TLS_1_1,y.Versions.TLS_1_0];y.Version=y.SupportedVersions[0];y.MaxFragment=15360;y.ConnectionEnd={server:0,client:1};y.PRFAlgorithm={tls_prf_sha256:0};y.BulkCipherAlgorithm={none:null,rc4:0,des3:1,aes:2};y.CipherType={stream:0,block:1,aead:2};y.MACAlgorithm={none:null,hmac_md5:0,hmac_sha1:1,hmac_sha256:2,hmac_sha384:3,hmac_sha512:4};y.CompressionMethod={none:0,deflate:1};y.ContentType={change_cipher_spec:20,alert:21,handshake:22,application_data:23,heartbeat:24};y.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};y.Alert={};y.Alert.Level={warning:1,fatal:2};y.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};y.HeartbeatMessageType={heartbeat_request:1,heartbeat_response:2};y.CipherSuites={};y.getCipherSuite=function(e){var t=null;for(var n in y.CipherSuites){var r=y.CipherSuites[n];if(r.id[0]===e.charCodeAt(0)&&r.id[1]===e.charCodeAt(1)){t=r;break}}return t};y.handleUnexpected=function(e,t){var n=!e.open&&e.entity===y.ConnectionEnd.client;if(!n)e.error(e,{message:"Unexpected message. Received TLS record out of order.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.unexpected_message}})};y.handleHelloRequest=function(e,t,n){if(!e.handshaking&&e.handshakes>0)y.queue(e,y.createAlert(e,{level:y.Alert.Level.warning,description:y.Alert.Description.no_renegotiation})),y.flush(e);e.process()};y.parseHelloMessage=function(e,t,n){var r=null,i=e.entity===y.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:y.Alert.Level.fatal,description:y.Alert.Description.illegal_parameter}});else{var s=t.fragment,a=s.length();if(r={version:{major:s.getByte(),minor:s.getByte()},random:O.util.createBuffer(s.getBytes(32)),session_id:It(s,1),extensions:[]},i)r.cipher_suite=s.getBytes(2),r.compression_method=s.getByte();else r.cipher_suites=It(s,2),r.compression_methods=It(s,1);if(a=n-(a-s.length()),a>0){var o=It(s,2);while(o.length()>0)r.extensions.push({type:[o.getByte(),o.getByte()],data:It(o,2)});if(!i)for(var l=0;l<r.extensions.length;++l){var c=r.extensions[l];if(c.type[0]===0&&c.type[1]===0){var u=It(c.data,2);while(u.length()>0){var d=u.getByte();if(d!==0)break;e.session.extensions.server_name.serverNameList.push(It(u,2).getBytes())}}}}if(e.session.version){if(r.version.major!==e.session.version.major||r.version.minor!==e.session.version.minor)return e.error(e,{message:"TLS version change is disallowed during renegotiation.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.protocol_version}})}if(i)e.session.cipherSuite=y.getCipherSuite(r.cipher_suite);else{var p=O.util.createBuffer(r.cipher_suites.bytes());while(p.length()>0)if(e.session.cipherSuite=y.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:y.Alert.Level.fatal,description:y.Alert.Description.handshake_failure},cipherSuite:O.util.bytesToHex(r.cipher_suite)});if(i)e.session.compressionMethod=r.compression_method;else e.session.compressionMethod=y.CompressionMethod.none}return r};y.createSecurityParameters=function(e,t){var n=e.entity===y.ConnectionEnd.client,r=t.random.bytes(),i=n?e.session.sp.client_random:r,s=n?r:y.createRandom().getBytes();e.session.sp={entity:e.entity,prf_algorithm:y.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:s}};y.handleServerHello=function(e,t,n){var r=y.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:y.Alert.Level.fatal,description:y.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=xd,e.session.resuming=!0,e.session.sp.server_random=r.random.bytes();else e.expect=vy,e.session.resuming=!1,y.createSecurityParameters(e,r);e.session.id=i,e.process()};y.handleClientHello=function(e,t,n){var r=y.parseHelloMessage(e,t,n);if(e.fail)return;var i=r.session_id.bytes(),s=null;if(e.sessionCache){if(s=e.sessionCache.getSession(i),s===null)i="";else if(s.version.major!==r.version.major||s.version.minor>r.version.minor)s=null,i=""}if(i.length===0)i=O.random.getBytes(32);if(e.session.id=i,e.session.clientHelloVersion=r.version,e.session.sp={},s)e.version=e.session.version=s.version,e.session.sp=s.sp;else{var a;for(var o=1;o<y.SupportedVersions.length;++o)if(a=y.SupportedVersions[o],a.minor<=r.version.minor)break;e.version={major:a.major,minor:a.minor},e.session.version=e.version}if(s!==null)e.expect=qo,e.session.resuming=!0,e.session.sp.client_random=r.random.bytes();else e.expect=e.verifyClient!==!1?Ty:Ko,e.session.resuming=!1,y.createSecurityParameters(e,r);if(e.open=!0,y.queue(e,y.createRecord(e,{type:y.ContentType.handshake,data:y.createServerHello(e)})),e.session.resuming)y.queue(e,y.createRecord(e,{type:y.ContentType.change_cipher_spec,data:y.createChangeCipherSpec()})),e.state.pending=y.createConnectionState(e),e.state.current.write=e.state.pending.write,y.queue(e,y.createRecord(e,{type:y.ContentType.handshake,data:y.createFinished(e)}));else if(y.queue(e,y.createRecord(e,{type:y.ContentType.handshake,data:y.createCertificate(e)})),!e.fail){if(y.queue(e,y.createRecord(e,{type:y.ContentType.handshake,data:y.createServerKeyExchange(e)})),e.verifyClient!==!1)y.queue(e,y.createRecord(e,{type:y.ContentType.handshake,data:y.createCertificateRequest(e)}));y.queue(e,y.createRecord(e,{type:y.ContentType.handshake,data:y.createServerHelloDone(e)}))}y.flush(e),e.process()};y.handleCertificate=function(e,t,n){if(n<3)return e.error(e,{message:"Invalid Certificate message. Message too short.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.illegal_parameter}});var r=t.fragment,i={certificate_list:It(r,3)},s,a,o=[];try{while(i.certificate_list.length()>0)s=It(i.certificate_list,3),a=O.asn1.fromDer(s),s=O.pki.certificateFromAsn1(a,!0),o.push(s)}catch(c){return e.error(e,{message:"Could not parse certificate list.",cause:c,send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.bad_certificate}})}var l=e.entity===y.ConnectionEnd.client;if((l||e.verifyClient===!0)&&o.length===0)e.error(e,{message:l?"No server certificate provided.":"No client certificate provided.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.illegal_parameter}});else if(o.length===0)e.expect=l?yd:Ko;else{if(l)e.session.serverCertificate=o[0];else e.session.clientCertificate=o[0];if(y.verifyCertificateChain(e,o))e.expect=l?yd:Ko}e.process()};y.handleServerKeyExchange=function(e,t,n){if(n>0)return e.error(e,{message:"Invalid key parameters. Only RSA is supported.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.unsupported_certificate}});e.expect=xy,e.process()};y.handleClientKeyExchange=function(e,t,n){if(n<48)return e.error(e,{message:"Invalid key parameters. Only RSA is supported.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.unsupported_certificate}});var r=t.fragment,i={enc_pre_master_secret:It(r,2).getBytes()},s=null;if(e.getPrivateKey)try{s=e.getPrivateKey(e,e.session.serverCertificate),s=O.pki.privateKeyFromPem(s)}catch(l){e.error(e,{message:"Could not get private key.",cause:l,send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.internal_error}})}if(s===null)return e.error(e,{message:"No private key set.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.internal_error}});try{var a=e.session.sp;a.pre_master_secret=s.decrypt(i.enc_pre_master_secret);var o=e.session.clientHelloVersion;if(o.major!==a.pre_master_secret.charCodeAt(0)||o.minor!==a.pre_master_secret.charCodeAt(1))throw Error("TLS version rollback attack detected.")}catch(l){a.pre_master_secret=O.random.getBytes(48)}if(e.expect=qo,e.session.clientCertificate!==null)e.expect=Ay;e.process()};y.handleCertificateRequest=function(e,t,n){if(n<3)return e.error(e,{message:"Invalid CertificateRequest. Message too short.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.illegal_parameter}});var r=t.fragment,i={certificate_types:It(r,1),certificate_authorities:It(r,2)};e.session.certificateRequest=i,e.expect=Sy,e.process()};y.handleCertificateVerify=function(e,t,n){if(n<2)return e.error(e,{message:"Invalid CertificateVerify. Message too short.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.illegal_parameter}});var r=t.fragment;r.read-=4;var i=r.bytes();r.read+=4;var s={signature:It(r,2).getBytes()},a=O.util.createBuffer();a.putBuffer(e.session.md5.digest()),a.putBuffer(e.session.sha1.digest()),a=a.getBytes();try{var o=e.session.clientCertificate;if(!o.publicKey.verify(a,s.signature,"NONE"))throw Error("CertificateVerify signature does not match.");e.session.md5.update(i),e.session.sha1.update(i)}catch(l){return e.error(e,{message:"Bad signature in CertificateVerify.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.handshake_failure}})}e.expect=qo,e.process()};y.handleServerHelloDone=function(e,t,n){if(n>0)return e.error(e,{message:"Invalid ServerHelloDone message. Invalid length.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.record_overflow}});if(e.session.serverCertificate===null){var r={message:"No server certificate provided. Not enough security.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.insufficient_security}},i=0,s=e.verify(e,r.alert.description,i,[]);if(s!==!0){if(s||s===0){if(typeof s==="object"&&!O.util.isArray(s)){if(s.message)r.message=s.message;if(s.alert)r.alert.description=s.alert}else if(typeof s==="number")r.alert.description=s}}return e.error(e,r)}if(e.session.certificateRequest!==null)t=y.createRecord(e,{type:y.ContentType.handshake,data:y.createCertificate(e)}),y.queue(e,t);t=y.createRecord(e,{type:y.ContentType.handshake,data:y.createClientKeyExchange(e)}),y.queue(e,t),e.expect=wy;var a=function(o,l){if(o.session.certificateRequest!==null&&o.session.clientCertificate!==null)y.queue(o,y.createRecord(o,{type:y.ContentType.handshake,data:y.createCertificateVerify(o,l)}));y.queue(o,y.createRecord(o,{type:y.ContentType.change_cipher_spec,data:y.createChangeCipherSpec()})),o.state.pending=y.createConnectionState(o),o.state.current.write=o.state.pending.write,y.queue(o,y.createRecord(o,{type:y.ContentType.handshake,data:y.createFinished(o)})),o.expect=xd,y.flush(o),o.process()};if(e.session.certificateRequest===null||e.session.clientCertificate===null)return a(e,null);y.getClientSignature(e,a)};y.handleChangeCipherSpec=function(e,t){if(t.fragment.getByte()!==1)return e.error(e,{message:"Invalid ChangeCipherSpec message received.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.illegal_parameter}});var n=e.entity===y.ConnectionEnd.client;if(e.session.resuming&&n||!e.session.resuming&&!n)e.state.pending=y.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?by:_y,e.process()};y.handleFinished=function(e,t,n){var r=t.fragment;r.read-=4;var i=r.bytes();r.read+=4;var s=t.fragment.getBytes();r=O.util.createBuffer(),r.putBuffer(e.session.md5.digest()),r.putBuffer(e.session.sha1.digest());var a=e.entity===y.ConnectionEnd.client,o=a?"server finished":"client finished",l=e.session.sp,c=12,u=Js;if(r=u(l.master_secret,o,r.getBytes(),c),r.getBytes()!==s)return e.error(e,{message:"Invalid verify_data in Finished message.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.decrypt_error}});if(e.session.md5.update(i),e.session.sha1.update(i),e.session.resuming&&a||!e.session.resuming&&!a)y.queue(e,y.createRecord(e,{type:y.ContentType.change_cipher_spec,data:y.createChangeCipherSpec()})),e.state.current.write=e.state.pending.write,e.state.pending=null,y.queue(e,y.createRecord(e,{type:y.ContentType.handshake,data:y.createFinished(e)}));e.expect=a?Cy:ky,e.handshaking=!1,++e.handshakes,e.peerCertificate=a?e.session.serverCertificate:e.session.clientCertificate,y.flush(e),e.isConnected=!0,e.connected(e),e.process()};y.handleAlert=function(e,t){var n=t.fragment,r={level:n.getByte(),description:n.getByte()},i;switch(r.description){case y.Alert.Description.close_notify:i="Connection closed.";break;case y.Alert.Description.unexpected_message:i="Unexpected message.";break;case y.Alert.Description.bad_record_mac:i="Bad record MAC.";break;case y.Alert.Description.decryption_failed:i="Decryption failed.";break;case y.Alert.Description.record_overflow:i="Record overflow.";break;case y.Alert.Description.decompression_failure:i="Decompression failed.";break;case y.Alert.Description.handshake_failure:i="Handshake failure.";break;case y.Alert.Description.bad_certificate:i="Bad certificate.";break;case y.Alert.Description.unsupported_certificate:i="Unsupported certificate.";break;case y.Alert.Description.certificate_revoked:i="Certificate revoked.";break;case y.Alert.Description.certificate_expired:i="Certificate expired.";break;case y.Alert.Description.certificate_unknown:i="Certificate unknown.";break;case y.Alert.Description.illegal_parameter:i="Illegal parameter.";break;case y.Alert.Description.unknown_ca:i="Unknown certificate authority.";break;case y.Alert.Description.access_denied:i="Access denied.";break;case y.Alert.Description.decode_error:i="Decode error.";break;case y.Alert.Description.decrypt_error:i="Decrypt error.";break;case y.Alert.Description.export_restriction:i="Export restriction.";break;case y.Alert.Description.protocol_version:i="Unsupported protocol version.";break;case y.Alert.Description.insufficient_security:i="Insufficient security.";break;case y.Alert.Description.internal_error:i="Internal error.";break;case y.Alert.Description.user_canceled:i="User canceled.";break;case y.Alert.Description.no_renegotiation:i="Renegotiation not supported.";break;default:i="Unknown error.";break}if(r.description===y.Alert.Description.close_notify)return e.close();e.error(e,{message:i,send:!1,origin:e.entity===y.ConnectionEnd.client?"server":"client",alert:r}),e.process()};y.handleHandshake=function(e,t){var n=t.fragment,r=n.getByte(),i=n.getInt24();if(i>n.length())return e.fragmented=t,t.fragment=O.util.createBuffer(),n.read-=4,e.process();e.fragmented=null,n.read-=4;var s=n.bytes(i+4);if(n.read+=4,r in Ys[e.entity][e.expect]){if(e.entity===y.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:O.md.md5.create(),sha1:O.md.sha1.create()};if(r!==y.HandshakeType.hello_request&&r!==y.HandshakeType.certificate_verify&&r!==y.HandshakeType.finished)e.session.md5.update(s),e.session.sha1.update(s);Ys[e.entity][e.expect][r](e,t,i)}else y.handleUnexpected(e,t)};y.handleApplicationData=function(e,t){e.data.putBuffer(t.fragment),e.dataReady(e),e.process()};y.handleHeartbeat=function(e,t){var n=t.fragment,r=n.getByte(),i=n.getInt16(),s=n.getBytes(i);if(r===y.HeartbeatMessageType.heartbeat_request){if(e.handshakes===0||e.handshaking||i>s.length)return e.process();y.queue(e,y.createRecord(e,{type:y.ContentType.heartbeat,data:y.createHeartbeat(y.HeartbeatMessageType.heartbeat_response,s)})),y.flush(e)}else if(r===y.HeartbeatMessageType.heartbeat_response){if(s!==e.expectedHeartbeatPayload)return e.process();if(e.heartbeatReceived)e.heartbeatReceived(e,O.util.createBuffer(s))}e.process()};var yy=0,vy=1,yd=2,xy=3,Sy=4,xd=5,by=6,Cy=7,wy=8,Ey=0,Ty=1,Ko=2,Ay=3,qo=4,_y=5,ky=6,{handleUnexpected:m,handleChangeCipherSpec:Sd,handleAlert:gt,handleHandshake:wt,handleApplicationData:bd,handleHeartbeat:mt}=y,Go=[];Go[y.ConnectionEnd.client]=[[m,gt,wt,m,mt],[m,gt,wt,m,mt],[m,gt,wt,m,mt],[m,gt,wt,m,mt],[m,gt,wt,m,mt],[Sd,gt,m,m,mt],[m,gt,wt,m,mt],[m,gt,wt,bd,mt],[m,gt,wt,m,mt]];Go[y.ConnectionEnd.server]=[[m,gt,wt,m,mt],[m,gt,wt,m,mt],[m,gt,wt,m,mt],[m,gt,wt,m,mt],[Sd,gt,m,m,mt],[m,gt,wt,m,mt],[m,gt,wt,bd,mt],[m,gt,wt,m,mt]];var{handleHelloRequest:$r,handleServerHello:Iy,handleCertificate:Cd,handleServerKeyExchange:vd,handleCertificateRequest:Wo,handleServerHelloDone:Qs,handleFinished:wd}=y,Ys=[];Ys[y.ConnectionEnd.client]=[[m,m,Iy,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m],[$r,m,m,m,m,m,m,m,m,m,m,Cd,vd,Wo,Qs,m,m,m,m,m,m],[$r,m,m,m,m,m,m,m,m,m,m,m,vd,Wo,Qs,m,m,m,m,m,m],[$r,m,m,m,m,m,m,m,m,m,m,m,m,Wo,Qs,m,m,m,m,m,m],[$r,m,m,m,m,m,m,m,m,m,m,m,m,m,Qs,m,m,m,m,m,m],[$r,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m],[$r,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,wd],[$r,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m],[$r,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m]];var{handleClientHello:Ry,handleClientKeyExchange:By,handleCertificateVerify:Py}=y;Ys[y.ConnectionEnd.server]=[[m,Ry,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m],[m,m,m,m,m,m,m,m,m,m,m,Cd,m,m,m,m,m,m,m,m,m],[m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,By,m,m,m,m],[m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,Py,m,m,m,m,m],[m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m],[m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,wd],[m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m],[m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m,m]];y.generateKeys=function(e,t){var n=Js,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,s=e.version.major===y.Versions.TLS_1_0.major&&e.version.minor===y.Versions.TLS_1_0.minor;if(s)i+=2*t.fixed_iv_length;var a=n(t.master_secret,"key expansion",r,i),o={client_write_MAC_key:a.getBytes(t.mac_key_length),server_write_MAC_key:a.getBytes(t.mac_key_length),client_write_key:a.getBytes(t.enc_key_length),server_write_key:a.getBytes(t.enc_key_length)};if(s)o.client_write_IV=a.getBytes(t.fixed_iv_length),o.server_write_IV=a.getBytes(t.fixed_iv_length);return o};y.createConnectionState=function(e){var t=e.entity===y.ConnectionEnd.client,n=function(){var s={sequenceNumber:[0,0],macKey:null,macLength:0,macFunction:null,cipherState:null,cipherFunction:function(a){return!0},compressionState:null,compressFunction:function(a){return!0},updateSequenceNumber:function(){if(s.sequenceNumber[1]===4294967295)s.sequenceNumber[1]=0,++s.sequenceNumber[0];else++s.sequenceNumber[1]}};return s},r={read:n(),write:n()};if(r.read.update=function(s,a){if(!r.read.cipherFunction(a,r.read))s.error(s,{message:"Could not decrypt record or bad MAC.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.bad_record_mac}});else if(!r.read.compressFunction(s,a,r.read))s.error(s,{message:"Could not decompress record.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.decompression_failure}});return!s.fail},r.write.update=function(s,a){if(!r.write.compressFunction(s,a,r.write))s.error(s,{message:"Could not compress record.",send:!1,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.internal_error}});else if(!r.write.cipherFunction(a,r.write))s.error(s,{message:"Could not encrypt record.",send:!1,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.internal_error}});return!s.fail},e.session){var i=e.session.sp;switch(e.session.cipherSuite.initSecurityParameters(i),i.keys=y.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 y.CompressionMethod.none:break;case y.CompressionMethod.deflate:r.read.compressFunction=my,r.write.compressFunction=gy;break;default:throw Error("Unsupported compression algorithm.")}}return r};y.createRandom=function(){var e=new Date,t=+e+e.getTimezoneOffset()*60000,n=O.util.createBuffer();return n.putInt32(t),n.putBytes(O.random.getBytes(28)),n};y.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};y.createAlert=function(e,t){var n=O.util.createBuffer();return n.putByte(t.level),n.putByte(t.description),y.createRecord(e,{type:y.ContentType.alert,data:n})};y.createClientHello=function(e){e.session.clientHelloVersion={major:e.version.major,minor:e.version.minor};var t=O.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(),s=O.util.createBuffer();s.putByte(y.CompressionMethod.none);var a=s.length(),o=O.util.createBuffer();if(e.virtualHost){var l=O.util.createBuffer();l.putByte(0),l.putByte(0);var c=O.util.createBuffer();c.putByte(0),Ft(c,2,O.util.createBuffer(e.virtualHost));var u=O.util.createBuffer();Ft(u,2,c),Ft(l,2,u),o.putBuffer(l)}var d=o.length();if(d>0)d+=2;var p=e.session.id,h=p.length+1+2+4+28+2+i+1+a+d,f=O.util.createBuffer();if(f.putByte(y.HandshakeType.client_hello),f.putInt24(h),f.putByte(e.version.major),f.putByte(e.version.minor),f.putBytes(e.session.sp.client_random),Ft(f,1,O.util.createBuffer(p)),Ft(f,2,t),Ft(f,1,s),d>0)Ft(f,2,o);return f};y.createServerHello=function(e){var t=e.session.id,n=t.length+1+2+4+28+2+1,r=O.util.createBuffer();return r.putByte(y.HandshakeType.server_hello),r.putInt24(n),r.putByte(e.version.major),r.putByte(e.version.minor),r.putBytes(e.session.sp.server_random),Ft(r,1,O.util.createBuffer(t)),r.putByte(e.session.cipherSuite.id[0]),r.putByte(e.session.cipherSuite.id[1]),r.putByte(e.session.compressionMethod),r};y.createCertificate=function(e){var t=e.entity===y.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=O.util.createBuffer();if(n!==null)try{if(!O.util.isArray(n))n=[n];var s=null;for(var a=0;a<n.length;++a){var o=O.pem.decode(n[a])[0];if(o.type!=="CERTIFICATE"&&o.type!=="X509 CERTIFICATE"&&o.type!=="TRUSTED CERTIFICATE"){var l=Error('Could not convert certificate from PEM; PEM header type is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".');throw l.headerType=o.type,l}if(o.procType&&o.procType.type==="ENCRYPTED")throw Error("Could not convert certificate from PEM; PEM is encrypted.");var c=O.util.createBuffer(o.body);if(s===null)s=O.asn1.fromDer(c.bytes(),!1);var u=O.util.createBuffer();Ft(u,3,c),i.putBuffer(u)}if(n=O.pki.certificateFromAsn1(s),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:y.Alert.Level.fatal,description:y.Alert.Description.bad_certificate}})}var d=3+i.length(),p=O.util.createBuffer();return p.putByte(y.HandshakeType.certificate),p.putInt24(d),Ft(p,3,i),p};y.createClientKeyExchange=function(e){var t=O.util.createBuffer();t.putByte(e.session.clientHelloVersion.major),t.putByte(e.session.clientHelloVersion.minor),t.putBytes(O.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,s=O.util.createBuffer();return s.putByte(y.HandshakeType.client_key_exchange),s.putInt24(i),s.putInt16(t.length),s.putBytes(t),s};y.createServerKeyExchange=function(e){var t=0,n=O.util.createBuffer();if(t>0)n.putByte(y.HandshakeType.server_key_exchange),n.putInt24(t);return n};y.getClientSignature=function(e,t){var n=O.util.createBuffer();n.putBuffer(e.session.md5.digest()),n.putBuffer(e.session.sha1.digest()),n=n.getBytes(),e.getSignature=e.getSignature||function(r,i,s){var a=null;if(r.getPrivateKey)try{a=r.getPrivateKey(r,r.session.clientCertificate),a=O.pki.privateKeyFromPem(a)}catch(o){r.error(r,{message:"Could not get private key.",cause:o,send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.internal_error}})}if(a===null)r.error(r,{message:"No private key set.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.internal_error}});else i=a.sign(i,null);s(r,i)},e.getSignature(e,n,t)};y.createCertificateVerify=function(e,t){var n=t.length+2,r=O.util.createBuffer();return r.putByte(y.HandshakeType.certificate_verify),r.putInt24(n),r.putInt16(t.length),r.putBytes(t),r};y.createCertificateRequest=function(e){var t=O.util.createBuffer();t.putByte(1);var n=O.util.createBuffer();for(var r in e.caStore.certs){var i=e.caStore.certs[r],s=O.pki.distinguishedNameToAsn1(i.subject),a=O.asn1.toDer(s);n.putInt16(a.length()),n.putBuffer(a)}var o=1+t.length()+2+n.length(),l=O.util.createBuffer();return l.putByte(y.HandshakeType.certificate_request),l.putInt24(o),Ft(l,1,t),Ft(l,2,n),l};y.createServerHelloDone=function(e){var t=O.util.createBuffer();return t.putByte(y.HandshakeType.server_hello_done),t.putInt24(0),t};y.createChangeCipherSpec=function(){var e=O.util.createBuffer();return e.putByte(1),e};y.createFinished=function(e){var t=O.util.createBuffer();t.putBuffer(e.session.md5.digest()),t.putBuffer(e.session.sha1.digest());var n=e.entity===y.ConnectionEnd.client,r=e.session.sp,i=12,s=Js,a=n?"client finished":"server finished";t=s(r.master_secret,a,t.getBytes(),i);var o=O.util.createBuffer();return o.putByte(y.HandshakeType.finished),o.putInt24(t.length()),o.putBuffer(t),o};y.createHeartbeat=function(e,t,n){if(typeof n>"u")n=t.length;var r=O.util.createBuffer();r.putByte(e),r.putInt16(n),r.putBytes(t);var i=r.length(),s=Math.max(16,i-n-3);return r.putBytes(O.random.getBytes(s)),r};y.queue=function(e,t){if(!t)return;if(t.fragment.length()===0){if(t.type===y.ContentType.handshake||t.type===y.ContentType.alert||t.type===y.ContentType.change_cipher_spec)return}if(t.type===y.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()<=y.MaxFragment)r=[t];else{r=[];var i=t.fragment.bytes();while(i.length>y.MaxFragment)r.push(y.createRecord(e,{type:t.type,data:O.util.createBuffer(i.slice(0,y.MaxFragment))})),i=i.slice(y.MaxFragment);if(i.length>0)r.push(y.createRecord(e,{type:t.type,data:O.util.createBuffer(i)}))}for(var s=0;s<r.length&&!e.fail;++s){var a=r[s],o=e.state.current.write;if(o.update(e,a))e.records.push(a)}};y.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 Ho=function(e){switch(e){case!0:return!0;case O.pki.certificateError.bad_certificate:return y.Alert.Description.bad_certificate;case O.pki.certificateError.unsupported_certificate:return y.Alert.Description.unsupported_certificate;case O.pki.certificateError.certificate_revoked:return y.Alert.Description.certificate_revoked;case O.pki.certificateError.certificate_expired:return y.Alert.Description.certificate_expired;case O.pki.certificateError.certificate_unknown:return y.Alert.Description.certificate_unknown;case O.pki.certificateError.unknown_ca:return y.Alert.Description.unknown_ca;default:return y.Alert.Description.bad_certificate}},Ny=function(e){switch(e){case!0:return!0;case y.Alert.Description.bad_certificate:return O.pki.certificateError.bad_certificate;case y.Alert.Description.unsupported_certificate:return O.pki.certificateError.unsupported_certificate;case y.Alert.Description.certificate_revoked:return O.pki.certificateError.certificate_revoked;case y.Alert.Description.certificate_expired:return O.pki.certificateError.certificate_expired;case y.Alert.Description.certificate_unknown:return O.pki.certificateError.certificate_unknown;case y.Alert.Description.unknown_ca:return O.pki.certificateError.unknown_ca;default:return O.pki.certificateError.bad_certificate}};y.verifyCertificateChain=function(e,t){try{var n={};for(var r in e.verifyOptions)n[r]=e.verifyOptions[r];n.verify=function(s,a,o){var l=Ho(s),c=e.verify(e,s,a,o);if(c!==!0){if(typeof c==="object"&&!O.util.isArray(c)){var u=Error("The application rejected the certificate.");if(u.send=!0,u.alert={level:y.Alert.Level.fatal,description:y.Alert.Description.bad_certificate},c.message)u.message=c.message;if(c.alert)u.alert.description=c.alert;throw u}if(c!==s)c=Ny(c)}return c},O.pki.verifyCertificateChain(e.caStore,t,n)}catch(s){var i=s;if(typeof i!=="object"||O.util.isArray(i))i={send:!0,alert:{level:y.Alert.Level.fatal,description:Ho(s)}};if(!("send"in i))i.send=!0;if(!("alert"in i))i.alert={level:y.Alert.Level.fatal,description:Ho(i.error)};e.error(e,i)}return!e.fail};y.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 s=null,a=null;if(i)a=O.util.bytesToHex(i);else if(n.order.length>0)a=n.order[0];if(a!==null&&a in n.cache){s=n.cache[a],delete n.cache[a];for(var o in n.order)if(n.order[o]===a){n.order.splice(o,1);break}}return s},n.setSession=function(i,s){if(n.order.length===n.capacity){var a=n.order.shift();delete n.cache[a]}var a=O.util.bytesToHex(i);n.order.push(a),n.cache[a]=s}}return n};y.createConnection=function(e){var t=null;if(e.caStore)if(O.util.isArray(e.caStore))t=O.pki.createCaStore(e.caStore);else t=e.caStore;else t=O.pki.createCaStore();var n=e.cipherSuites||null;if(n===null){n=[];for(var r in y.CipherSuites)n.push(y.CipherSuites[r])}var i=e.server?y.ConnectionEnd.server:y.ConnectionEnd.client,s=e.sessionCache?y.createSessionCache(e.sessionCache):null,a={version:{major:y.Version.major,minor:y.Version.minor},entity:i,sessionId:e.sessionId,caStore:t,sessionCache:s,cipherSuites:n,connected:e.connected,virtualHost:e.virtualHost||null,verifyClient:e.verifyClient||!1,verify:e.verify||function(h,f,v,x){return f},verifyOptions:e.verifyOptions||{},getCertificate:e.getCertificate||null,getPrivateKey:e.getPrivateKey||null,getSignature:e.getSignature||null,input:O.util.createBuffer(),tlsData:O.util.createBuffer(),data:O.util.createBuffer(),tlsDataReady:e.tlsDataReady,dataReady:e.dataReady,heartbeatReceived:e.heartbeatReceived,closed:e.closed,error:function(h,f){if(f.origin=f.origin||(h.entity===y.ConnectionEnd.client?"client":"server"),f.send)y.queue(h,y.createAlert(h,f.alert)),y.flush(h);var v=f.fatal!==!1;if(v)h.fail=!0;if(e.error(h,f),v)h.close(!1)},deflate:e.deflate||null,inflate:e.inflate||null};a.reset=function(h){a.version={major:y.Version.major,minor:y.Version.minor},a.record=null,a.session=null,a.peerCertificate=null,a.state={pending:null,current:null},a.expect=a.entity===y.ConnectionEnd.client?yy:Ey,a.fragmented=null,a.records=[],a.open=!1,a.handshakes=0,a.handshaking=!1,a.isConnected=!1,a.fail=!(h||typeof h>"u"),a.input.clear(),a.tlsData.clear(),a.data.clear(),a.state.current=y.createConnectionState(a)},a.reset();var o=function(h,f){var v=f.type-y.ContentType.change_cipher_spec,x=Go[h.entity][h.expect];if(v in x)x[v](h,f);else y.handleUnexpected(h,f)},l=function(h){var f=0,v=h.input,x=v.length();if(x<5)f=5-x;else{h.record={type:v.getByte(),version:{major:v.getByte(),minor:v.getByte()},length:v.getInt16(),fragment:O.util.createBuffer(),ready:!1};var S=h.record.version.major===h.version.major;if(S&&h.session&&h.session.version)S=h.record.version.minor===h.version.minor;if(!S)h.error(h,{message:"Incompatible TLS version.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.protocol_version}})}return f},c=function(h){var f=0,v=h.input,x=v.length();if(x<h.record.length)f=h.record.length-x;else{h.record.fragment.putBytes(v.getBytes(h.record.length)),v.compact();var S=h.state.current.read;if(S.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:y.Alert.Level.fatal,description:y.Alert.Description.unexpected_message}}),f;h.record.ready=!0}}return f};a.handshake=function(h){if(a.entity!==y.ConnectionEnd.client)a.error(a,{message:"Cannot initiate handshake as a server.",fatal:!1});else if(a.handshaking)a.error(a,{message:"Handshake already in progress.",fatal:!1});else{if(a.fail&&!a.open&&a.handshakes===0)a.fail=!1;a.handshaking=!0,h=h||"";var f=null;if(h.length>0){if(a.sessionCache)f=a.sessionCache.getSession(h);if(f===null)h=""}if(h.length===0&&a.sessionCache){if(f=a.sessionCache.getSession(),f!==null)h=f.id}if(a.session={id:h,version:null,cipherSuite:null,compressionMethod:null,serverCertificate:null,certificateRequest:null,clientCertificate:null,sp:{},md5:O.md.md5.create(),sha1:O.md.sha1.create()},f)a.version=f.version,a.session.sp=f.sp;a.session.sp.client_random=y.createRandom().getBytes(),a.open=!0,y.queue(a,y.createRecord(a,{type:y.ContentType.handshake,data:y.createClientHello(a)})),y.flush(a)}};var u=!1,d=!1,p=function(h){var f=0;if(!h.fail){if(h.record!==null&&h.record.ready&&h.record.fragment.isEmpty())h.record=null;if(h.record===null)f=l(h);if(!h.fail&&h.record!==null&&!h.record.ready)f=c(h);if(!h.fail&&h.record!==null&&h.record.ready)o(h,h.record)}return f};return a.process=function(h){var f=0;if(h)a.input.putBytes(h);if(u&&typeof h>"u")return d=!0,f;var v=u,x=d;u=!0,d=!1;try{f=p(a);while(d)d=!1,p(a)}finally{u=v,d=x}return f},a.prepare=function(h){return y.queue(a,y.createRecord(a,{type:y.ContentType.application_data,data:O.util.createBuffer(h)})),y.flush(a)},a.prepareHeartbeatRequest=function(h,f){if(h instanceof O.util.ByteBuffer)h=h.bytes();if(typeof f>"u")f=h.length;return a.expectedHeartbeatPayload=h,y.queue(a,y.createRecord(a,{type:y.ContentType.heartbeat,data:y.createHeartbeat(y.HeartbeatMessageType.heartbeat_request,h,f)})),y.flush(a)},a.close=function(h){if(!a.fail&&a.sessionCache&&a.session){var f={id:a.session.id,version:a.session.version,sp:a.session.sp};f.sp.keys=null,a.sessionCache.setSession(f.id,f)}if(a.open){if(a.open=!1,a.input.clear(),a.isConnected||a.handshaking)a.isConnected=a.handshaking=!1,y.queue(a,y.createAlert(a,{level:y.Alert.Level.warning,description:y.Alert.Description.close_notify})),y.flush(a);a.closed(a)}a.reset(h)},a};Ed.exports=O.tls=O.tls||{};for(Ai in y)if(typeof y[Ai]!=="function")O.tls[Ai]=y[Ai];var Ai;O.tls.prf_tls1=Js;O.tls.hmac_sha1=hy;O.tls.createSessionCache=y.createSessionCache;O.tls.createConnection=y.createConnection});var _d=de(function(O1,Ad){var Wr=ye();Lr();jo();var Mt=Ad.exports=Wr.tls;Mt.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=Mt.BulkCipherAlgorithm.aes,e.cipher_type=Mt.CipherType.block,e.enc_key_length=16,e.block_length=16,e.fixed_iv_length=16,e.record_iv_length=16,e.mac_algorithm=Mt.MACAlgorithm.hmac_sha1,e.mac_length=20,e.mac_key_length=20},initConnectionState:Td};Mt.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=Mt.BulkCipherAlgorithm.aes,e.cipher_type=Mt.CipherType.block,e.enc_key_length=32,e.block_length=16,e.fixed_iv_length=16,e.record_iv_length=16,e.mac_algorithm=Mt.MACAlgorithm.hmac_sha1,e.mac_length=20,e.mac_key_length=20},initConnectionState:Td};function Td(e,t,n){var r=t.entity===Wr.tls.ConnectionEnd.client;e.read.cipherState={init:!1,cipher:Wr.cipher.createDecipher("AES-CBC",r?n.keys.server_write_key:n.keys.client_write_key),iv:r?n.keys.server_write_IV:n.keys.client_write_IV},e.write.cipherState={init:!1,cipher:Wr.cipher.createCipher("AES-CBC",r?n.keys.client_write_key:n.keys.server_write_key),iv:r?n.keys.client_write_IV:n.keys.server_write_IV},e.read.cipherFunction=Uy,e.write.cipherFunction=Dy,e.read.macLength=e.write.macLength=n.mac_length,e.read.macFunction=e.write.macFunction=Mt.hmac_sha1}function Dy(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===Mt.Versions.TLS_1_0.minor)i=t.cipherState.init?null:t.cipherState.iv;else i=Wr.random.getBytesSync(16);t.cipherState.init=!0;var s=t.cipherState.cipher;if(s.start({iv:i}),e.version.minor>=Mt.Versions.TLS_1_1.minor)s.output.putBytes(i);if(s.update(e.fragment),s.finish(Ly))e.fragment=s.output,e.length=e.fragment.length(),n=!0;return n}function Ly(e,t,n){if(!n){var r=e-t.length()%e;t.fillWithByte(r-1,r)}return!0}function Oy(e,t,n){var r=!0;if(n){var i=t.length(),s=t.last();for(var a=i-1-s;a<i-1;++a)r=r&&t.at(a)==s;if(r)t.truncate(s+1)}return r}function Uy(e,t){var n=!1,r;if(e.version.minor===Mt.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(Oy);var s=t.macLength,a=Wr.random.getBytesSync(s),o=i.output.length();if(o>=s)e.fragment=i.output.getBytes(o-s),a=i.output.getBytes(s);else e.fragment=i.output.getBytes();e.fragment=Wr.util.createBuffer(e.fragment),e.length=e.fragment.length();var l=t.macFunction(t.macKey,t.sequenceNumber,e);return t.updateSequenceNumber(),n=Vy(t.macKey,a,l)&&n,n}function Vy(e,t,n){var r=Wr.hmac.create();return r.start("SHA1",e),r.update(t),t=r.digest().getBytes(),r.start(null,null),r.update(n),n=r.digest().getBytes(),t===n}});var Qo=de(function(U1,Bd){var Ge=ye();rr();Ne();var _i=Bd.exports=Ge.sha512=Ge.sha512||{};Ge.md.sha512=Ge.md.algorithms.sha512=_i;var Id=Ge.sha384=Ge.sha512.sha384=Ge.sha512.sha384||{};Id.create=function(){return _i.create("SHA-384")};Ge.md.sha384=Ge.md.algorithms.sha384=Id;Ge.sha512.sha256=Ge.sha512.sha256||{create:function(){return _i.create("SHA-512/256")}};Ge.md["sha512/256"]=Ge.md.algorithms["sha512/256"]=Ge.sha512.sha256;Ge.sha512.sha224=Ge.sha512.sha224||{create:function(){return _i.create("SHA-512/224")}};Ge.md["sha512/224"]=Ge.md.algorithms["sha512/224"]=Ge.sha512.sha224;_i.create=function(e){if(!Rd)Fy();if(typeof e>"u")e="SHA-512";if(!(e in dn))throw Error("Invalid SHA-512 algorithm: "+e);var t=dn[e],n=null,r=Ge.util.createBuffer(),i=Array(80);for(var s=0;s<80;++s)i[s]=[,,];var a=64;switch(e){case"SHA-384":a=48;break;case"SHA-512/256":a=32;break;case"SHA-512/224":a=28;break}var o={algorithm:e.replace("-","").toLowerCase(),blockLength:128,digestLength:a,messageLength:0,fullMessageLength:null,messageLengthSize:16};return o.start=function(){o.messageLength=0,o.fullMessageLength=o.messageLength128=[];var l=o.messageLengthSize/4;for(var c=0;c<l;++c)o.fullMessageLength.push(0);r=Ge.util.createBuffer(),n=Array(t.length);for(var c=0;c<t.length;++c)n[c]=t[c].slice(0);return o},o.start(),o.update=function(l,c){if(c==="utf8")l=Ge.util.encodeUtf8(l);var u=l.length;o.messageLength+=u,u=[u/4294967296>>>0,u>>>0];for(var d=o.fullMessageLength.length-1;d>=0;--d)o.fullMessageLength[d]+=u[1],u[1]=u[0]+(o.fullMessageLength[d]/4294967296>>>0),o.fullMessageLength[d]=o.fullMessageLength[d]>>>0,u[0]=u[1]/4294967296>>>0;if(r.putBytes(l),kd(n,i,r),r.read>2048||r.length()===0)r.compact();return o},o.digest=function(){var l=Ge.util.createBuffer();l.putBytes(r.bytes());var c=o.fullMessageLength[o.fullMessageLength.length-1]+o.messageLengthSize,u=c&o.blockLength-1;l.putBytes(zo.substr(0,o.blockLength-u));var d,p,h=o.fullMessageLength[0]*8;for(var f=0;f<o.fullMessageLength.length-1;++f)d=o.fullMessageLength[f+1]*8,p=d/4294967296>>>0,h+=p,l.putInt32(h>>>0),h=d>>>0;l.putInt32(h);var v=Array(n.length);for(var f=0;f<n.length;++f)v[f]=n[f].slice(0);kd(v,i,l);var x=Ge.util.createBuffer(),S;if(e==="SHA-512")S=v.length;else if(e==="SHA-384")S=v.length-2;else S=v.length-4;for(var f=0;f<S;++f)if(x.putInt32(v[f][0]),f!==S-1||e!=="SHA-512/224")x.putInt32(v[f][1]);return x},o};var zo=null,Rd=!1,Xo=null,dn=null;function Fy(){zo=String.fromCharCode(128),zo+=Ge.util.fillString(String.fromCharCode(0),128),Xo=[[1116352408,3609767458],[1899447441,602891725],[3049323471,3964484399],[3921009573,2173295548],[961987163,4081628472],[1508970993,3053834265],[2453635748,2937671579],[2870763221,3664609560],[3624381080,2734883394],[310598401,1164996542],[607225278,1323610764],[1426881987,3590304994],[1925078388,4068182383],[2162078206,991336113],[2614888103,633803317],[3248222580,3479774868],[3835390401,2666613458],[4022224774,944711139],[264347078,2341262773],[604807628,2007800933],[770255983,1495990901],[1249150122,1856431235],[1555081692,3175218132],[1996064986,2198950837],[2554220882,3999719339],[2821834349,766784016],[2952996808,2566594879],[3210313671,3203337956],[3336571891,1034457026],[3584528711,2466948901],[113926993,3758326383],[338241895,168717936],[666307205,1188179964],[773529912,1546045734],[1294757372,1522805485],[1396182291,2643833823],[1695183700,2343527390],[1986661051,1014477480],[2177026350,1206759142],[2456956037,344077627],[2730485921,1290863460],[2820302411,3158454273],[3259730800,3505952657],[3345764771,106217008],[3516065817,3606008344],[3600352804,1432725776],[4094571909,1467031594],[275423344,851169720],[430227734,3100823752],[506948616,1363258195],[659060556,3750685593],[883997877,3785050280],[958139571,3318307427],[1322822218,3812723403],[1537002063,2003034995],[1747873779,3602036899],[1955562222,1575990012],[2024104815,1125592928],[2227730452,2716904306],[2361852424,442776044],[2428436474,593698344],[2756734187,3733110249],[3204031479,2999351573],[3329325298,3815920427],[3391569614,3928383900],[3515267271,566280711],[3940187606,3454069534],[4118630271,4000239992],[116418474,1914138554],[174292421,2731055270],[289380356,3203993006],[460393269,320620315],[685471733,587496836],[852142971,1086792851],[1017036298,365543100],[1126000580,2618297676],[1288033470,3409855158],[1501505948,4234509866],[1607167915,987167468],[1816402316,1246189591]],dn={},dn["SHA-512"]=[[1779033703,4089235720],[3144134277,2227873595],[1013904242,4271175723],[2773480762,1595750129],[1359893119,2917565137],[2600822924,725511199],[528734635,4215389547],[1541459225,327033209]],dn["SHA-384"]=[[3418070365,3238371032],[1654270250,914150663],[2438529370,812702999],[355462360,4144912697],[1731405415,4290775857],[2394180231,1750603025],[3675008525,1694076839],[1203062813,3204075428]],dn["SHA-512/256"]=[[573645204,4230739756],[2673172387,3360449730],[596883563,1867755857],[2520282905,1497426621],[2519219938,2827943907],[3193839141,1401305490],[721525244,746961066],[246885852,2177182882]],dn["SHA-512/224"]=[[2352822216,424955298],[1944164710,2312950998],[502970286,855612546],[1738396948,1479516111],[258812777,2077511080],[2011393907,79989058],[1067287976,1780299464],[286451373,2446758561]],Rd=!0}function kd(e,t,n){var r,i,s,a,o,l,c,u,d,p,h,f,v,x,S,A,b,k,R,I,V,J,D,W,Z,pe,ge,Me,ve,Oe,F,re,Q,ue,ce,te=n.length();while(te>=128){for(ve=0;ve<16;++ve)t[ve][0]=n.getInt32()>>>0,t[ve][1]=n.getInt32()>>>0;for(;ve<80;++ve)re=t[ve-2],Oe=re[0],F=re[1],r=((Oe>>>19|F<<13)^(F>>>29|Oe<<3)^Oe>>>6)>>>0,i=((Oe<<13|F>>>19)^(F<<3|Oe>>>29)^(Oe<<26|F>>>6))>>>0,ue=t[ve-15],Oe=ue[0],F=ue[1],s=((Oe>>>1|F<<31)^(Oe>>>8|F<<24)^Oe>>>7)>>>0,a=((Oe<<31|F>>>1)^(Oe<<24|F>>>8)^(Oe<<25|F>>>7))>>>0,Q=t[ve-7],ce=t[ve-16],F=i+Q[1]+a+ce[1],t[ve][0]=r+Q[0]+s+ce[0]+(F/4294967296>>>0)>>>0,t[ve][1]=F>>>0;v=e[0][0],x=e[0][1],S=e[1][0],A=e[1][1],b=e[2][0],k=e[2][1],R=e[3][0],I=e[3][1],V=e[4][0],J=e[4][1],D=e[5][0],W=e[5][1],Z=e[6][0],pe=e[6][1],ge=e[7][0],Me=e[7][1];for(ve=0;ve<80;++ve)c=((V>>>14|J<<18)^(V>>>18|J<<14)^(J>>>9|V<<23))>>>0,u=((V<<18|J>>>14)^(V<<14|J>>>18)^(J<<23|V>>>9))>>>0,d=(Z^V&(D^Z))>>>0,p=(pe^J&(W^pe))>>>0,o=((v>>>28|x<<4)^(x>>>2|v<<30)^(x>>>7|v<<25))>>>0,l=((v<<4|x>>>28)^(x<<30|v>>>2)^(x<<25|v>>>7))>>>0,h=(v&S|b&(v^S))>>>0,f=(x&A|k&(x^A))>>>0,F=Me+u+p+Xo[ve][1]+t[ve][1],r=ge+c+d+Xo[ve][0]+t[ve][0]+(F/4294967296>>>0)>>>0,i=F>>>0,F=l+f,s=o+h+(F/4294967296>>>0)>>>0,a=F>>>0,ge=Z,Me=pe,Z=D,pe=W,D=V,W=J,F=I+i,V=R+r+(F/4294967296>>>0)>>>0,J=F>>>0,R=b,I=k,b=S,k=A,S=v,A=x,F=i+a,v=r+s+(F/4294967296>>>0)>>>0,x=F>>>0;F=e[0][1]+x,e[0][0]=e[0][0]+v+(F/4294967296>>>0)>>>0,e[0][1]=F>>>0,F=e[1][1]+A,e[1][0]=e[1][0]+S+(F/4294967296>>>0)>>>0,e[1][1]=F>>>0,F=e[2][1]+k,e[2][0]=e[2][0]+b+(F/4294967296>>>0)>>>0,e[2][1]=F>>>0,F=e[3][1]+I,e[3][0]=e[3][0]+R+(F/4294967296>>>0)>>>0,e[3][1]=F>>>0,F=e[4][1]+J,e[4][0]=e[4][0]+V+(F/4294967296>>>0)>>>0,e[4][1]=F>>>0,F=e[5][1]+W,e[5][0]=e[5][0]+D+(F/4294967296>>>0)>>>0,e[5][1]=F>>>0,F=e[6][1]+pe,e[6][0]=e[6][0]+Z+(F/4294967296>>>0)>>>0,e[6][1]=F>>>0,F=e[7][1]+Me,e[7][0]=e[7][0]+ge+(F/4294967296>>>0)>>>0,e[7][1]=F>>>0,te-=128}}});var Pd=de(function($y){var My=ye();Gt();var pt=My.asn1;$y.privateKeyValidator={name:"PrivateKeyInfo",tagClass:pt.Class.UNIVERSAL,type:pt.Type.SEQUENCE,constructed:!0,value:[{name:"PrivateKeyInfo.version",tagClass:pt.Class.UNIVERSAL,type:pt.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:pt.Class.UNIVERSAL,type:pt.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:pt.Class.UNIVERSAL,type:pt.Type.OID,constructed:!1,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:pt.Class.UNIVERSAL,type:pt.Type.OCTETSTRING,constructed:!1,capture:"privateKey"}]};$y.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:pt.Class.UNIVERSAL,type:pt.Type.SEQUENCE,constructed:!0,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:pt.Class.UNIVERSAL,type:pt.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:pt.Class.UNIVERSAL,type:pt.Type.OID,constructed:!1,capture:"publicKeyOid"}]},{tagClass:pt.Class.UNIVERSAL,type:pt.Type.BITSTRING,constructed:!1,composed:!0,captureBitStringValue:"ed25519PublicKey"}]}});var Kd=de(function(F1,Hd){var yt=ye();Ci();Lt();Qo();Ne();var Ud=Pd(),{publicKeyValidator:Ky,privateKeyValidator:qy}=Ud;if(typeof Jo>"u")Jo=yt.jsbn.BigInteger;var Jo,Zo=yt.util.ByteBuffer,_t=typeof Buffer>"u"?Uint8Array:Buffer;yt.pki=yt.pki||{};Hd.exports=yt.pki.ed25519=yt.ed25519=yt.ed25519||{};var Te=yt.ed25519;Te.constants={};Te.constants.PUBLIC_KEY_BYTE_LENGTH=32;Te.constants.PRIVATE_KEY_BYTE_LENGTH=64;Te.constants.SEED_BYTE_LENGTH=32;Te.constants.SIGN_BYTE_LENGTH=64;Te.constants.HASH_BYTE_LENGTH=64;Te.generateKeyPair=function(e){e=e||{};var t=e.seed;if(t===void 0)t=yt.random.getBytesSync(Te.constants.SEED_BYTE_LENGTH);else if(typeof t==="string"){if(t.length!==Te.constants.SEED_BYTE_LENGTH)throw TypeError('"seed" must be '+Te.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=Cr({message:t,encoding:"binary"});var n=new _t(Te.constants.PUBLIC_KEY_BYTE_LENGTH),r=new _t(Te.constants.PRIVATE_KEY_BYTE_LENGTH);for(var i=0;i<32;++i)r[i]=t[i];return Xy(n,r),{publicKey:n,privateKey:r}};Te.privateKeyFromAsn1=function(e){var t={},n=[],r=yt.asn1.validate(e,qy,t,n);if(!r){var i=Error("Invalid Key.");throw i.errors=n,i}var s=yt.asn1.derToOid(t.privateKeyOid),a=yt.oids.EdDSA25519;if(s!==a)throw Error('Invalid OID "'+s+'"; OID must be "'+a+'".');var o=t.privateKey,l=Cr({message:yt.asn1.fromDer(o).value,encoding:"binary"});return{privateKeyBytes:l}};Te.publicKeyFromAsn1=function(e){var t={},n=[],r=yt.asn1.validate(e,Ky,t,n);if(!r){var i=Error("Invalid Key.");throw i.errors=n,i}var s=yt.asn1.derToOid(t.publicKeyOid),a=yt.oids.EdDSA25519;if(s!==a)throw Error('Invalid OID "'+s+'"; OID must be "'+a+'".');var o=t.ed25519PublicKey;if(o.length!==Te.constants.PUBLIC_KEY_BYTE_LENGTH)throw Error("Key length is invalid.");return Cr({message:o,encoding:"binary"})};Te.publicKeyFromPrivateKey=function(e){e=e||{};var t=Cr({message:e.privateKey,encoding:"binary"});if(t.length!==Te.constants.PRIVATE_KEY_BYTE_LENGTH)throw TypeError('"options.privateKey" must have a byte length of '+Te.constants.PRIVATE_KEY_BYTE_LENGTH);var n=new _t(Te.constants.PUBLIC_KEY_BYTE_LENGTH);for(var r=0;r<n.length;++r)n[r]=t[32+r];return n};Te.sign=function(e){e=e||{};var t=Cr(e),n=Cr({message:e.privateKey,encoding:"binary"});if(n.length===Te.constants.SEED_BYTE_LENGTH){var r=Te.generateKeyPair({seed:n});n=r.privateKey}else if(n.length!==Te.constants.PRIVATE_KEY_BYTE_LENGTH)throw TypeError('"options.privateKey" must have a byte length of '+Te.constants.SEED_BYTE_LENGTH+" or "+Te.constants.PRIVATE_KEY_BYTE_LENGTH);var i=new _t(Te.constants.SIGN_BYTE_LENGTH+t.length);Qy(i,t,t.length,n);var s=new _t(Te.constants.SIGN_BYTE_LENGTH);for(var a=0;a<s.length;++a)s[a]=i[a];return s};Te.verify=function(e){e=e||{};var t=Cr(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=Cr({message:e.signature,encoding:"binary"});if(n.length!==Te.constants.SIGN_BYTE_LENGTH)throw TypeError('"options.signature" must have a byte length of '+Te.constants.SIGN_BYTE_LENGTH);var r=Cr({message:e.publicKey,encoding:"binary"});if(r.length!==Te.constants.PUBLIC_KEY_BYTE_LENGTH)throw TypeError('"options.publicKey" must have a byte length of '+Te.constants.PUBLIC_KEY_BYTE_LENGTH);var i=new _t(Te.constants.SIGN_BYTE_LENGTH+t.length),s=new _t(Te.constants.SIGN_BYTE_LENGTH+t.length),a;for(a=0;a<Te.constants.SIGN_BYTE_LENGTH;++a)i[a]=n[a];for(a=0;a<t.length;++a)i[a+Te.constants.SIGN_BYTE_LENGTH]=t[a];return Yy(s,i,i.length,r)>=0};function Cr(e){var t=e.message;if(t instanceof Uint8Array||t instanceof _t)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 Zo(t,n)}else if(!(t instanceof Zo))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 _t(t.length());for(var i=0;i<r.length;++i)r[i]=t.at(i);return r}var el=se(),Zs=se([1]),Gy=se([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),jy=se([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),Nd=se([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),Dd=se([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),ki=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]),zy=se([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function Ii(e,t){var n=yt.md.sha512.create(),r=new Zo(e);n.update(r.getBytes(t),"binary");var i=n.digest().getBytes();if(typeof Buffer<"u")return Buffer.from(i,"binary");var s=new _t(Te.constants.HASH_BYTE_LENGTH);for(var a=0;a<64;++a)s[a]=i.charCodeAt(a);return s}function Xy(e,t){var n=[se(),se(),se(),se()],r,i=Ii(t,32);i[0]&=248,i[31]&=127,i[31]|=64,il(n,i),nl(e,n);for(r=0;r<32;++r)t[r+32]=e[r];return 0}function Qy(e,t,n,r){var i,s,a=new Float64Array(64),o=[se(),se(),se(),se()],l=Ii(r,32);l[0]&=248,l[31]&=127,l[31]|=64;var c=n+64;for(i=0;i<n;++i)e[64+i]=t[i];for(i=0;i<32;++i)e[32+i]=l[32+i];var u=Ii(e.subarray(32),n+32);tl(u),il(o,u),nl(e,o);for(i=32;i<64;++i)e[i]=r[i];var d=Ii(e,n+64);tl(d);for(i=32;i<64;++i)a[i]=0;for(i=0;i<32;++i)a[i]=u[i];for(i=0;i<32;++i)for(s=0;s<32;s++)a[i+s]+=d[i]*l[s];return Vd(e.subarray(32),a),c}function Yy(e,t,n,r){var i,s,a=new _t(32),o=[se(),se(),se(),se()],l=[se(),se(),se(),se()];if(s=-1,n<64)return-1;if(Zy(l,r))return-1;if(!Jy(t,32))return-1;for(i=0;i<n;++i)e[i]=t[i];for(i=0;i<32;++i)e[i+32]=r[i];var c=Ii(e,n);if(tl(c),$d(o,l,c),il(l,t.subarray(32)),rl(o,l),nl(a,o),n-=64,Fd(t,0,a,0)){for(i=0;i<n;++i)e[i]=0;return-1}for(i=0;i<n;++i)e[i]=t[i+64];return s=n,s}function Jy(e,t){var n;for(n=31;n>=0;--n){if(e[t+n]<ki[n])return!0;if(e[t+n]>ki[n])return!1}return!1}function Vd(e,t){var n,r,i,s;for(r=63;r>=32;--r){n=0;for(i=r-32,s=r-12;i<s;++i)t[i]+=n-16*t[r]*ki[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)*ki[i],n=t[i]>>8,t[i]&=255;for(i=0;i<32;++i)t[i]-=n*ki[i];for(r=0;r<32;++r)t[r+1]+=t[r]>>8,e[r]=t[r]&255}function tl(e){var t=new Float64Array(64);for(var n=0;n<64;++n)t[n]=e[n],e[n]=0;Vd(e,t)}function rl(e,t){var n=se(),r=se(),i=se(),s=se(),a=se(),o=se(),l=se(),c=se(),u=se();On(n,e[1],e[0]),On(u,t[1],t[0]),Ve(n,n,u),Ln(r,e[0],e[1]),Ln(u,t[0],t[1]),Ve(r,r,u),Ve(i,e[3],t[3]),Ve(i,i,jy),Ve(s,e[2],t[2]),Ln(s,s,s),On(a,r,n),On(o,s,i),Ln(l,s,i),Ln(c,r,n),Ve(e[0],a,o),Ve(e[1],c,l),Ve(e[2],l,o),Ve(e[3],a,c)}function Ld(e,t,n){for(var r=0;r<4;++r)Wd(e[r],t[r],n)}function nl(e,t){var n=se(),r=se(),i=se();nv(i,t[2]),Ve(n,t[0],i),Ve(r,t[1],i),ea(e,r),e[31]^=Md(n)<<7}function ea(e,t){var n,r,i,s=se(),a=se();for(n=0;n<16;++n)a[n]=t[n];Yo(a),Yo(a),Yo(a);for(r=0;r<2;++r){s[0]=a[0]-65517;for(n=1;n<15;++n)s[n]=a[n]-65535-(s[n-1]>>16&1),s[n-1]&=65535;s[15]=a[15]-32767-(s[14]>>16&1),i=s[15]>>16&1,s[14]&=65535,Wd(a,s,1-i)}for(n=0;n<16;n++)e[2*n]=a[n]&255,e[2*n+1]=a[n]>>8}function Zy(e,t){var n=se(),r=se(),i=se(),s=se(),a=se(),o=se(),l=se();if(Hr(e[2],Zs),ev(e[1],t),fn(i,e[1]),Ve(s,i,Gy),On(i,i,e[2]),Ln(s,e[2],s),fn(a,s),fn(o,a),Ve(l,o,a),Ve(n,l,i),Ve(n,n,s),tv(n,n),Ve(n,n,i),Ve(n,n,s),Ve(n,n,s),Ve(e[0],n,s),fn(r,e[0]),Ve(r,r,s),Od(r,i))Ve(e[0],e[0],zy);if(fn(r,e[0]),Ve(r,r,s),Od(r,i))return-1;if(Md(e[0])===t[31]>>7)On(e[0],el,e[0]);return Ve(e[3],e[0],e[1]),0}function ev(e,t){var n;for(n=0;n<16;++n)e[n]=t[2*n]+(t[2*n+1]<<8);e[15]&=32767}function tv(e,t){var n=se(),r;for(r=0;r<16;++r)n[r]=t[r];for(r=250;r>=0;--r)if(fn(n,n),r!==1)Ve(n,n,t);for(r=0;r<16;++r)e[r]=n[r]}function Od(e,t){var n=new _t(32),r=new _t(32);return ea(n,e),ea(r,t),Fd(n,0,r,0)}function Fd(e,t,n,r){return rv(e,t,n,r,32)}function rv(e,t,n,r,i){var s,a=0;for(s=0;s<i;++s)a|=e[t+s]^n[r+s];return(1&a-1>>>8)-1}function Md(e){var t=new _t(32);return ea(t,e),t[0]&1}function $d(e,t,n){var r,i;Hr(e[0],el),Hr(e[1],Zs),Hr(e[2],Zs),Hr(e[3],el);for(i=255;i>=0;--i)r=n[i/8|0]>>(i&7)&1,Ld(e,t,r),rl(t,e),rl(e,e),Ld(e,t,r)}function il(e,t){var n=[se(),se(),se(),se()];Hr(n[0],Nd),Hr(n[1],Dd),Hr(n[2],Zs),Ve(n[3],Nd,Dd),$d(e,n,t)}function Hr(e,t){var n;for(n=0;n<16;n++)e[n]=t[n]|0}function nv(e,t){var n=se(),r;for(r=0;r<16;++r)n[r]=t[r];for(r=253;r>=0;--r)if(fn(n,n),r!==2&&r!==4)Ve(n,n,t);for(r=0;r<16;++r)e[r]=n[r]}function Yo(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 Wd(e,t,n){var r,i=~(n-1);for(var s=0;s<16;++s)r=i&(e[s]^t[s]),e[s]^=r,t[s]^=r}function se(e){var t,n=new Float64Array(16);if(e)for(t=0;t<e.length;++t)n[t]=e[t];return n}function Ln(e,t,n){for(var r=0;r<16;++r)e[r]=t[r]+n[r]}function On(e,t,n){for(var r=0;r<16;++r)e[r]=t[r]-n[r]}function fn(e,t){Ve(e,t,t)}function Ve(e,t,n){var r,i,s=0,a=0,o=0,l=0,c=0,u=0,d=0,p=0,h=0,f=0,v=0,x=0,S=0,A=0,b=0,k=0,R=0,I=0,V=0,J=0,D=0,W=0,Z=0,pe=0,ge=0,Me=0,ve=0,Oe=0,F=0,re=0,Q=0,ue=n[0],ce=n[1],te=n[2],Ie=n[3],$e=n[4],Xe=n[5],xe=n[6],ae=n[7],We=n[8],Re=n[9],st=n[10],nt=n[11],at=n[12],ot=n[13],Qe=n[14],lt=n[15];r=t[0],s+=r*ue,a+=r*ce,o+=r*te,l+=r*Ie,c+=r*$e,u+=r*Xe,d+=r*xe,p+=r*ae,h+=r*We,f+=r*Re,v+=r*st,x+=r*nt,S+=r*at,A+=r*ot,b+=r*Qe,k+=r*lt,r=t[1],a+=r*ue,o+=r*ce,l+=r*te,c+=r*Ie,u+=r*$e,d+=r*Xe,p+=r*xe,h+=r*ae,f+=r*We,v+=r*Re,x+=r*st,S+=r*nt,A+=r*at,b+=r*ot,k+=r*Qe,R+=r*lt,r=t[2],o+=r*ue,l+=r*ce,c+=r*te,u+=r*Ie,d+=r*$e,p+=r*Xe,h+=r*xe,f+=r*ae,v+=r*We,x+=r*Re,S+=r*st,A+=r*nt,b+=r*at,k+=r*ot,R+=r*Qe,I+=r*lt,r=t[3],l+=r*ue,c+=r*ce,u+=r*te,d+=r*Ie,p+=r*$e,h+=r*Xe,f+=r*xe,v+=r*ae,x+=r*We,S+=r*Re,A+=r*st,b+=r*nt,k+=r*at,R+=r*ot,I+=r*Qe,V+=r*lt,r=t[4],c+=r*ue,u+=r*ce,d+=r*te,p+=r*Ie,h+=r*$e,f+=r*Xe,v+=r*xe,x+=r*ae,S+=r*We,A+=r*Re,b+=r*st,k+=r*nt,R+=r*at,I+=r*ot,V+=r*Qe,J+=r*lt,r=t[5],u+=r*ue,d+=r*ce,p+=r*te,h+=r*Ie,f+=r*$e,v+=r*Xe,x+=r*xe,S+=r*ae,A+=r*We,b+=r*Re,k+=r*st,R+=r*nt,I+=r*at,V+=r*ot,J+=r*Qe,D+=r*lt,r=t[6],d+=r*ue,p+=r*ce,h+=r*te,f+=r*Ie,v+=r*$e,x+=r*Xe,S+=r*xe,A+=r*ae,b+=r*We,k+=r*Re,R+=r*st,I+=r*nt,V+=r*at,J+=r*ot,D+=r*Qe,W+=r*lt,r=t[7],p+=r*ue,h+=r*ce,f+=r*te,v+=r*Ie,x+=r*$e,S+=r*Xe,A+=r*xe,b+=r*ae,k+=r*We,R+=r*Re,I+=r*st,V+=r*nt,J+=r*at,D+=r*ot,W+=r*Qe,Z+=r*lt,r=t[8],h+=r*ue,f+=r*ce,v+=r*te,x+=r*Ie,S+=r*$e,A+=r*Xe,b+=r*xe,k+=r*ae,R+=r*We,I+=r*Re,V+=r*st,J+=r*nt,D+=r*at,W+=r*ot,Z+=r*Qe,pe+=r*lt,r=t[9],f+=r*ue,v+=r*ce,x+=r*te,S+=r*Ie,A+=r*$e,b+=r*Xe,k+=r*xe,R+=r*ae,I+=r*We,V+=r*Re,J+=r*st,D+=r*nt,W+=r*at,Z+=r*ot,pe+=r*Qe,ge+=r*lt,r=t[10],v+=r*ue,x+=r*ce,S+=r*te,A+=r*Ie,b+=r*$e,k+=r*Xe,R+=r*xe,I+=r*ae,V+=r*We,J+=r*Re,D+=r*st,W+=r*nt,Z+=r*at,pe+=r*ot,ge+=r*Qe,Me+=r*lt,r=t[11],x+=r*ue,S+=r*ce,A+=r*te,b+=r*Ie,k+=r*$e,R+=r*Xe,I+=r*xe,V+=r*ae,J+=r*We,D+=r*Re,W+=r*st,Z+=r*nt,pe+=r*at,ge+=r*ot,Me+=r*Qe,ve+=r*lt,r=t[12],S+=r*ue,A+=r*ce,b+=r*te,k+=r*Ie,R+=r*$e,I+=r*Xe,V+=r*xe,J+=r*ae,D+=r*We,W+=r*Re,Z+=r*st,pe+=r*nt,ge+=r*at,Me+=r*ot,ve+=r*Qe,Oe+=r*lt,r=t[13],A+=r*ue,b+=r*ce,k+=r*te,R+=r*Ie,I+=r*$e,V+=r*Xe,J+=r*xe,D+=r*ae,W+=r*We,Z+=r*Re,pe+=r*st,ge+=r*nt,Me+=r*at,ve+=r*ot,Oe+=r*Qe,F+=r*lt,r=t[14],b+=r*ue,k+=r*ce,R+=r*te,I+=r*Ie,V+=r*$e,J+=r*Xe,D+=r*xe,W+=r*ae,Z+=r*We,pe+=r*Re,ge+=r*st,Me+=r*nt,ve+=r*at,Oe+=r*ot,F+=r*Qe,re+=r*lt,r=t[15],k+=r*ue,R+=r*ce,I+=r*te,V+=r*Ie,J+=r*$e,D+=r*Xe,W+=r*xe,Z+=r*ae,pe+=r*We,ge+=r*Re,Me+=r*st,ve+=r*nt,Oe+=r*at,F+=r*ot,re+=r*Qe,Q+=r*lt,s+=38*R,a+=38*I,o+=38*V,l+=38*J,c+=38*D,u+=38*W,d+=38*Z,p+=38*pe,h+=38*ge,f+=38*Me,v+=38*ve,x+=38*Oe,S+=38*F,A+=38*re,b+=38*Q,i=1,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=o+i+65535,i=Math.floor(r/65536),o=r-i*65536,r=l+i+65535,i=Math.floor(r/65536),l=r-i*65536,r=c+i+65535,i=Math.floor(r/65536),c=r-i*65536,r=u+i+65535,i=Math.floor(r/65536),u=r-i*65536,r=d+i+65535,i=Math.floor(r/65536),d=r-i*65536,r=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=f+i+65535,i=Math.floor(r/65536),f=r-i*65536,r=v+i+65535,i=Math.floor(r/65536),v=r-i*65536,r=x+i+65535,i=Math.floor(r/65536),x=r-i*65536,r=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=b+i+65535,i=Math.floor(r/65536),b=r-i*65536,r=k+i+65535,i=Math.floor(r/65536),k=r-i*65536,s+=i-1+37*(i-1),i=1,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=o+i+65535,i=Math.floor(r/65536),o=r-i*65536,r=l+i+65535,i=Math.floor(r/65536),l=r-i*65536,r=c+i+65535,i=Math.floor(r/65536),c=r-i*65536,r=u+i+65535,i=Math.floor(r/65536),u=r-i*65536,r=d+i+65535,i=Math.floor(r/65536),d=r-i*65536,r=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=f+i+65535,i=Math.floor(r/65536),f=r-i*65536,r=v+i+65535,i=Math.floor(r/65536),v=r-i*65536,r=x+i+65535,i=Math.floor(r/65536),x=r-i*65536,r=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=b+i+65535,i=Math.floor(r/65536),b=r-i*65536,r=k+i+65535,i=Math.floor(r/65536),k=r-i*65536,s+=i-1+37*(i-1),e[0]=s,e[1]=a,e[2]=o,e[3]=l,e[4]=c,e[5]=u,e[6]=d,e[7]=p,e[8]=h,e[9]=f,e[10]=v,e[11]=x,e[12]=S,e[13]=A,e[14]=b,e[15]=k}});var zd=de(function(M1,jd){var Rt=ye();Ne();Lt();Ci();jd.exports=Rt.kem=Rt.kem||{};var qd=Rt.jsbn.BigInteger;Rt.kem.rsa={};Rt.kem.rsa.create=function(e,t){t=t||{};var n=t.prng||Rt.random,r={};return r.encrypt=function(i,s){var a=Math.ceil(i.n.bitLength()/8),o;do o=new qd(Rt.util.bytesToHex(n.getBytesSync(a)),16).mod(i.n);while(o.compareTo(qd.ONE)<=0);o=Rt.util.hexToBytes(o.toString(16));var l=a-o.length;if(l>0)o=Rt.util.fillString(String.fromCharCode(0),l)+o;var c=i.encrypt(o,"NONE"),u=e.generate(o,s);return{encapsulation:c,key:u}},r.decrypt=function(i,s,a){var o=i.decrypt(s,"NONE");return e.generate(o,a)},r};Rt.kem.kdf1=function(e,t){Gd(this,e,0,t||e.digestLength)};Rt.kem.kdf2=function(e,t){Gd(this,e,1,t||e.digestLength)};function Gd(e,t,n,r){e.generate=function(i,s){var a=new Rt.util.ByteBuffer,o=Math.ceil(s/r)+n,l=new Rt.util.ByteBuffer;for(var c=n;c<o;++c){l.putInt32(c),t.start(),t.update(i+l.getBytes());var u=t.digest();a.putBytes(u.getBytes(r))}return a.truncate(a.length()-s),a.getBytes()}}});var Qd=de(function($1,Xd){var Ae=ye();Ne();Xd.exports=Ae.log=Ae.log||{};Ae.log.levels=["none","error","warning","info","debug","verbose","max"];var na={},sl=[],Ri=null;Ae.log.LEVEL_LOCKED=2;Ae.log.NO_LEVEL_CHECK=4;Ae.log.INTERPOLATE=8;for($t=0;$t<Ae.log.levels.length;++$t)ta=Ae.log.levels[$t],na[ta]={index:$t,name:ta.toUpperCase()};var ta,$t;Ae.log.logMessage=function(e){var t=na[e.level].index;for(var n=0;n<sl.length;++n){var r=sl[n];if(r.flags&Ae.log.NO_LEVEL_CHECK)r.f(e);else{var i=na[r.level].index;if(t<=i)r.f(r,e)}}};Ae.log.prepareStandard=function(e){if(!("standard"in e))e.standard=na[e.level].name+" ["+e.category+"] "+e.message};Ae.log.prepareFull=function(e){if(!("full"in e)){var t=[e.message];t=t.concat([]),e.full=Ae.util.format.apply(this,t)}};Ae.log.prepareStandardFull=function(e){if(!("standardFull"in e))Ae.log.prepareStandard(e),e.standardFull=e.standard};ra=["error","warning","info","debug","verbose"];for($t=0;$t<ra.length;++$t)(function(t){Ae.log[t]=function(n,r){var i=Array.prototype.slice.call(arguments).slice(2),s={timestamp:new Date,level:t,category:n,message:r,arguments:i};Ae.log.logMessage(s)}})(ra[$t]);var ra,$t;Ae.log.makeLogger=function(e){var t={flags:0,f:e};return Ae.log.setLevel(t,"none"),t};Ae.log.setLevel=function(e,t){var n=!1;if(e&&!(e.flags&Ae.log.LEVEL_LOCKED))for(var r=0;r<Ae.log.levels.length;++r){var i=Ae.log.levels[r];if(t==i){e.level=t,n=!0;break}}return n};Ae.log.lock=function(e,t){if(typeof t>"u"||t)e.flags|=Ae.log.LEVEL_LOCKED;else e.flags&=~Ae.log.LEVEL_LOCKED};Ae.log.addLogger=function(e){sl.push(e)};if(typeof console<"u"&&"log"in console){if(console.error&&console.warn&&console.info&&console.debug)al={error:console.error,warning:console.warn,info:console.info,debug:console.debug,verbose:console.debug},Vn=function(e,t){Ae.log.prepareStandard(t);var n=al[t.level],r=[t.standard];r=r.concat(t.arguments.slice()),n.apply(console,r)},pn=Ae.log.makeLogger(Vn);else Vn=function(t,n){Ae.log.prepareStandardFull(n),console.log(n.standardFull)},pn=Ae.log.makeLogger(Vn);Ae.log.setLevel(pn,"debug"),Ae.log.addLogger(pn),Ri=pn}else console={log:function(){}};var pn,al,Vn;if(Ri!==null&&typeof window<"u"&&window.location){if(Un=new URL(window.location.href).searchParams,Un.has("console.level"))Ae.log.setLevel(Ri,Un.get("console.level").slice(-1)[0]);if(Un.has("console.lock")){if(ol=Un.get("console.lock").slice(-1)[0],ol=="true")Ae.log.lock(Ri)}}var Un,ol;Ae.log.consoleLogger=Ri});var Jd=de(function(W1,Yd){Yd.exports=rr();Ls();Rn();So();Qo()});var tf=de(function(H1,ef){var H=ye();Lr();Gt();Si();Or();sn();Lo();Lt();Ne();Xs();var E=H.asn1,Et=ef.exports=H.pkcs7=H.pkcs7||{};Et.messageFromPem=function(e){var t=H.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=E.fromDer(t.body);return Et.messageFromAsn1(r)};Et.messageToPem=function(e,t){var n={type:"PKCS7",body:E.toDer(e.toAsn1()).getBytes()};return H.pem.encode(n,{maxline:t})};Et.messageFromAsn1=function(e){var t={},n=[];if(!E.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=E.derToOid(t.contentType),s;switch(i){case H.pki.oids.envelopedData:s=Et.createEnvelopedData();break;case H.pki.oids.encryptedData:s=Et.createEncryptedData();break;case H.pki.oids.signedData:s=Et.createSignedData();break;default:throw Error("Cannot read PKCS#7 message. ContentType with OID "+i+" is not (yet) supported.")}return s.fromAsn1(t.content.value[0]),s};Et.createSignedData=function(){var e=null;return e={type:H.pki.oids.signedData,version:1,certificates:[],crls:[],signers:[],digestAlgorithmIdentifiers:[],contentInfo:null,signerInfos:[],fromAsn1:function(r){if(cl(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 s=0;s<i.length;++s)e.certificates.push(H.pki.certificateFromAsn1(i[s]))}},toAsn1:function(){if(!e.contentInfo)e.sign();var r=[];for(var i=0;i<e.certificates.length;++i)r.push(H.pki.certificateToAsn1(e.certificates[i]));var s=[],a=E.create(E.Class.CONTEXT_SPECIFIC,0,!0,[E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.INTEGER,!1,E.integerToDer(e.version).getBytes()),E.create(E.Class.UNIVERSAL,E.Type.SET,!0,e.digestAlgorithmIdentifiers),e.contentInfo])]);if(r.length>0)a.value[0].value.push(E.create(E.Class.CONTEXT_SPECIFIC,0,!0,r));if(s.length>0)a.value[0].value.push(E.create(E.Class.CONTEXT_SPECIFIC,1,!0,s));return a.value[0].value.push(E.create(E.Class.UNIVERSAL,E.Type.SET,!0,e.signerInfos)),E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.OID,!1,E.oidToDer(e.type).getBytes()),a])},addSigner:function(r){var{issuer:i,serialNumber:s}=r;if(r.certificate){var a=r.certificate;if(typeof a==="string")a=H.pki.certificateFromPem(a);i=a.issuer.attributes,s=a.serialNumber}var o=r.key;if(!o)throw Error("Could not add PKCS#7 signer; no private key specified.");if(typeof o==="string")o=H.pki.privateKeyFromPem(o);var l=r.digestAlgorithm||H.pki.oids.sha1;switch(l){case H.pki.oids.sha1:case H.pki.oids.sha256:case H.pki.oids.sha384:case H.pki.oids.sha512:case H.pki.oids.md5:break;default:throw Error("Could not add PKCS#7 signer; unknown message digest algorithm: "+l)}var c=r.authenticatedAttributes||[];if(c.length>0){var u=!1,d=!1;for(var p=0;p<c.length;++p){var h=c[p];if(!u&&h.type===H.pki.oids.contentType){if(u=!0,d)break;continue}if(!d&&h.type===H.pki.oids.messageDigest){if(d=!0,u)break;continue}}if(!u||!d)throw Error("Invalid signer.authenticatedAttributes. If signer.authenticatedAttributes is specified, then it must contain at least two attributes, PKCS #9 content-type and PKCS #9 message-digest.")}e.signers.push({key:o,version:1,issuer:i,serialNumber:s,digestAlgorithm:l,signatureAlgorithm:H.pki.oids.rsaEncryption,signature:null,authenticatedAttributes:c,unauthenticatedAttributes:[]})},sign:function(r){if(r=r||{},typeof e.content!=="object"||e.contentInfo===null){if(e.contentInfo=E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.OID,!1,E.oidToDer(H.pki.oids.data).getBytes())]),"content"in e){var i;if(e.content instanceof H.util.ByteBuffer)i=e.content.bytes();else if(typeof e.content==="string")i=H.util.encodeUtf8(e.content);if(r.detached)e.detachedContent=E.create(E.Class.UNIVERSAL,E.Type.OCTETSTRING,!1,i);else e.contentInfo.value.push(E.create(E.Class.CONTEXT_SPECIFIC,0,!0,[E.create(E.Class.UNIVERSAL,E.Type.OCTETSTRING,!1,i)]))}}if(e.signers.length===0)return;var s=t();n(s)},verify:function(){throw Error("PKCS#7 signature verification not yet implemented.")},addCertificate:function(r){if(typeof r==="string")r=H.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 s=e.signers[i],a=s.digestAlgorithm;if(!(a in r))r[a]=H.md[H.pki.oids[a]].create();if(s.authenticatedAttributes.length===0)s.md=r[a];else s.md=H.md[H.pki.oids[a]].create()}e.digestAlgorithmIdentifiers=[];for(var a in r)e.digestAlgorithmIdentifiers.push(E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.OID,!1,E.oidToDer(a).getBytes()),E.create(E.Class.UNIVERSAL,E.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 s=E.derToOid(e.contentInfo.value[0].value),a=E.toDer(i);a.getByte(),E.getBerValueLength(a),a=a.getBytes();for(var o in r)r[o].start().update(a);var l=new Date;for(var c=0;c<e.signers.length;++c){var u=e.signers[c];if(u.authenticatedAttributes.length===0){if(s!==H.pki.oids.data)throw Error("Invalid signer; authenticatedAttributes must be present when the ContentInfo content type is not PKCS#7 Data.")}else{u.authenticatedAttributesAsn1=E.create(E.Class.CONTEXT_SPECIFIC,0,!0,[]);var d=E.create(E.Class.UNIVERSAL,E.Type.SET,!0,[]);for(var p=0;p<u.authenticatedAttributes.length;++p){var h=u.authenticatedAttributes[p];if(h.type===H.pki.oids.messageDigest)h.value=r[u.digestAlgorithm].digest();else if(h.type===H.pki.oids.signingTime){if(!h.value)h.value=l}d.value.push(ll(h)),u.authenticatedAttributesAsn1.value.push(ll(h))}a=E.toDer(d).getBytes(),u.md.start().update(a)}u.signature=u.key.sign(u.md,"RSASSA-PKCS1-V1_5")}e.signerInfos=cv(e.signers)}};Et.createEncryptedData=function(){var e=null;return e={type:H.pki.oids.encryptedData,version:0,encryptedContent:{algorithm:H.pki.oids["aes256-CBC"]},fromAsn1:function(t){cl(e,t,Et.asn1.encryptedDataValidator)},decrypt:function(t){if(t!==void 0)e.encryptedContent.key=t;Zd(e)}},e};Et.createEnvelopedData=function(){var e=null;return e={type:H.pki.oids.envelopedData,version:0,recipients:[],encryptedContent:{algorithm:H.pki.oids["aes256-CBC"]},fromAsn1:function(t){var n=cl(e,t,Et.asn1.envelopedDataValidator);e.recipients=av(n.recipientInfos.value)},toAsn1:function(){return E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.OID,!1,E.oidToDer(e.type).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.INTEGER,!1,E.integerToDer(e.version).getBytes()),E.create(E.Class.UNIVERSAL,E.Type.SET,!0,ov(e.recipients)),E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,uv(e.encryptedContent))])])])},findRecipient:function(t){var n=t.issuer.attributes;for(var r=0;r<e.recipients.length;++r){var i=e.recipients[r],s=i.issuer;if(i.serialNumber!==t.serialNumber)continue;if(s.length!==n.length)continue;var a=!0;for(var o=0;o<n.length;++o)if(s[o].type!==n[o].type||s[o].value!==n[o].value){a=!1;break}if(a)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 H.pki.oids.rsaEncryption:case H.pki.oids.desCBC:var r=n.decrypt(t.encryptedContent.content);e.encryptedContent.key=H.util.createBuffer(r);break;default:throw Error("Unsupported asymmetric cipher, OID "+t.encryptedContent.algorithm)}Zd(e)},addRecipient:function(t){e.recipients.push({version:0,issuer:t.issuer.attributes,serialNumber:t.serialNumber,encryptedContent:{algorithm:H.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,s;switch(n){case H.pki.oids["aes128-CBC"]:r=16,i=16,s=H.aes.createEncryptionCipher;break;case H.pki.oids["aes192-CBC"]:r=24,i=16,s=H.aes.createEncryptionCipher;break;case H.pki.oids["aes256-CBC"]:r=32,i=16,s=H.aes.createEncryptionCipher;break;case H.pki.oids["des-EDE3-CBC"]:r=24,i=8,s=H.des.createEncryptionCipher;break;default:throw Error("Unsupported symmetric cipher, OID "+n)}if(t===void 0)t=H.util.createBuffer(H.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=H.util.createBuffer(H.random.getBytes(i));var a=s(t);if(a.start(e.encryptedContent.parameter.copy()),a.update(e.content),!a.finish())throw Error("Symmetric encryption failed.");e.encryptedContent.content=a.output}for(var o=0;o<e.recipients.length;++o){var l=e.recipients[o];if(l.encryptedContent.content!==void 0)continue;switch(l.encryptedContent.algorithm){case H.pki.oids.rsaEncryption:l.encryptedContent.content=l.encryptedContent.key.encrypt(e.encryptedContent.key.data);break;default:throw Error("Unsupported asymmetric cipher, OID "+l.encryptedContent.algorithm)}}}},e};function iv(e){var t={},n=[];if(!E.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:H.pki.RDNAttributesAsArray(t.issuer),serialNumber:H.util.createBuffer(t.serial).toHex(),encryptedContent:{algorithm:E.derToOid(t.encAlgorithm),parameter:t.encParameter?t.encParameter.value:void 0,content:t.encKey}}}function sv(e){return E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.INTEGER,!1,E.integerToDer(e.version).getBytes()),E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[H.pki.distinguishedNameToAsn1({attributes:e.issuer}),E.create(E.Class.UNIVERSAL,E.Type.INTEGER,!1,H.util.hexToBytes(e.serialNumber))]),E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.OID,!1,E.oidToDer(e.encryptedContent.algorithm).getBytes()),E.create(E.Class.UNIVERSAL,E.Type.NULL,!1,"")]),E.create(E.Class.UNIVERSAL,E.Type.OCTETSTRING,!1,e.encryptedContent.content)])}function av(e){var t=[];for(var n=0;n<e.length;++n)t.push(iv(e[n]));return t}function ov(e){var t=[];for(var n=0;n<e.length;++n)t.push(sv(e[n]));return t}function lv(e){var t=E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.INTEGER,!1,E.integerToDer(e.version).getBytes()),E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[H.pki.distinguishedNameToAsn1({attributes:e.issuer}),E.create(E.Class.UNIVERSAL,E.Type.INTEGER,!1,H.util.hexToBytes(e.serialNumber))]),E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.OID,!1,E.oidToDer(e.digestAlgorithm).getBytes()),E.create(E.Class.UNIVERSAL,E.Type.NULL,!1,"")])]);if(e.authenticatedAttributesAsn1)t.value.push(e.authenticatedAttributesAsn1);if(t.value.push(E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.OID,!1,E.oidToDer(e.signatureAlgorithm).getBytes()),E.create(E.Class.UNIVERSAL,E.Type.NULL,!1,"")])),t.value.push(E.create(E.Class.UNIVERSAL,E.Type.OCTETSTRING,!1,e.signature)),e.unauthenticatedAttributes.length>0){var n=E.create(E.Class.CONTEXT_SPECIFIC,1,!0,[]);for(var r=0;r<e.unauthenticatedAttributes.length;++r){var i=e.unauthenticatedAttributes[r];n.values.push(ll(i))}t.value.push(n)}return t}function cv(e){var t=[];for(var n=0;n<e.length;++n)t.push(lv(e[n]));return t}function ll(e){var t;if(e.type===H.pki.oids.contentType)t=E.create(E.Class.UNIVERSAL,E.Type.OID,!1,E.oidToDer(e.value).getBytes());else if(e.type===H.pki.oids.messageDigest)t=E.create(E.Class.UNIVERSAL,E.Type.OCTETSTRING,!1,e.value.bytes());else if(e.type===H.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 s=Date.parse(i);if(!isNaN(s))i=new Date(s);else if(i.length===13)i=E.utcTimeToDate(i);else i=E.generalizedTimeToDate(i)}if(i>=n&&i<r)t=E.create(E.Class.UNIVERSAL,E.Type.UTCTIME,!1,E.dateToUtcTime(i));else t=E.create(E.Class.UNIVERSAL,E.Type.GENERALIZEDTIME,!1,E.dateToGeneralizedTime(i))}return E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.OID,!1,E.oidToDer(e.type).getBytes()),E.create(E.Class.UNIVERSAL,E.Type.SET,!0,[t])])}function uv(e){return[E.create(E.Class.UNIVERSAL,E.Type.OID,!1,E.oidToDer(H.pki.oids.data).getBytes()),E.create(E.Class.UNIVERSAL,E.Type.SEQUENCE,!0,[E.create(E.Class.UNIVERSAL,E.Type.OID,!1,E.oidToDer(e.algorithm).getBytes()),!e.parameter?void 0:E.create(E.Class.UNIVERSAL,E.Type.OCTETSTRING,!1,e.parameter.getBytes())]),E.create(E.Class.CONTEXT_SPECIFIC,0,!0,[E.create(E.Class.UNIVERSAL,E.Type.OCTETSTRING,!1,e.content.getBytes())])]}function cl(e,t,n){var r={},i=[];if(!E.validate(t,n,r,i)){var s=Error("Cannot read PKCS#7 message. ASN.1 object is not a supported PKCS#7 message.");throw s.errors=s,s}var a=E.derToOid(r.contentType);if(a!==H.pki.oids.data)throw Error("Unsupported PKCS#7 message. Only wrapped ContentType Data supported.");if(r.encryptedContent){var o="";if(H.util.isArray(r.encryptedContent))for(var l=0;l<r.encryptedContent.length;++l){if(r.encryptedContent[l].type!==E.Type.OCTETSTRING)throw Error("Malformed PKCS#7 message, expecting encrypted content constructed of only OCTET STRING objects.");o+=r.encryptedContent[l].value}else o=r.encryptedContent;e.encryptedContent={algorithm:E.derToOid(r.encAlgorithm),parameter:H.util.createBuffer(r.encParameter.value),content:H.util.createBuffer(o)}}if(r.content){var o="";if(H.util.isArray(r.content))for(var l=0;l<r.content.length;++l){if(r.content[l].type!==E.Type.OCTETSTRING)throw Error("Malformed PKCS#7 message, expecting content constructed of only OCTET STRING objects.");o+=r.content[l].value}else o=r.content;e.content=H.util.createBuffer(o)}return e.version=r.version.charCodeAt(0),e.rawCapture=r,r}function Zd(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 H.pki.oids["aes128-CBC"]:case H.pki.oids["aes192-CBC"]:case H.pki.oids["aes256-CBC"]:t=H.aes.createDecryptionCipher(e.encryptedContent.key);break;case H.pki.oids.desCBC:case H.pki.oids["des-EDE3-CBC"]:t=H.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 nf=de(function(K1,rf){var it=ye();Lr();An();Ls();Rn();Ne();var sa=rf.exports=it.ssh=it.ssh||{};sa.privateKeyToPutty=function(e,t,n){n=n||"",t=t||"";var r="ssh-rsa",i=t===""?"none":"aes256-cbc",s="PuTTY-User-Key-File-2: "+r+`\r
20
20
  `;s+="Encryption: "+i+`\r
21
21
  `,s+="Comment: "+n+`\r
22
22
  `;var a=it.util.createBuffer();Fn(a,r),ur(a,e.e),ur(a,e.n);var o=it.util.encode64(a.bytes(),64),l=Math.floor(o.length/66)+1;s+="Public-Lines: "+l+`\r
@@ -24,26 +24,26 @@ var c0=Object.create;var{getPrototypeOf:u0,defineProperty:$c,getOwnPropertyNames
24
24
  Private-Lines: `+l+`\r
25
25
  `,s+=u;var x=ia("putty-private-key-file-mac-key",t),S=it.util.createBuffer();Fn(S,r),Fn(S,i),Fn(S,n),S.putInt32(a.length()),S.putBuffer(a),S.putInt32(c.length()),S.putBuffer(c);var A=it.hmac.create();return A.start("sha1",x),A.update(S.bytes()),s+=`\r
26
26
  Private-MAC: `+A.digest().toHex()+`\r
27
- `,s};sa.publicKeyToOpenSSH=function(e,t){var n="ssh-rsa";t=t||"";var r=it.util.createBuffer();return Fn(r,n),ur(r,e.e),ur(r,e.n),n+" "+it.util.encode64(r.bytes())+" "+t};sa.privateKeyToOpenSSH=function(e,t){if(!t)return it.pki.privateKeyToPem(e);return it.pki.encryptRsaPrivateKey(e,t,{legacy:!0,algorithm:"aes128"})};sa.getPublicKeyFingerprint=function(e,t){t=t||{};var n=t.md||it.md.md5.create(),r="ssh-rsa",i=it.util.createBuffer();Fn(i,r),ur(i,e.e),ur(i,e.n),n.start(),n.update(i.getBytes());var s=n.digest();if(t.encoding==="hex"){var a=s.toHex();if(t.delimiter)return a.match(/.{2}/g).join(t.delimiter);return a}else if(t.encoding==="binary")return s.getBytes();else if(t.encoding)throw Error('Unknown encoding "'+t.encoding+'".');return s};function ur(e,t){var n=t.toString(16);if(n[0]>="8")n="00"+n;var r=it.util.hexToBytes(n);e.putInt32(r.length),e.putBytes(r)}function Fn(e,t){e.putInt32(t.length),e.putString(t)}function ia(){var e=it.md.sha1.create(),t=arguments.length;for(var n=0;n<t;++n)e.update(arguments[n]);return e.digest()}});var ul=de(function(G1,sf){sf.exports=ve();Lr();_d();Gt();ks();Si();Kd();An();zd();Qd();Jd();Oo();Fs();sn();Io();Fo();tf();$o();Bo();bo();Gs();Lt();Eo();nf();jo();Pe()});var qf=de(function(Zw,Kf){var{create:gx,defineProperty:ya,getOwnPropertyDescriptor:mx,getOwnPropertyNames:yx,getPrototypeOf:vx}=Object,xx=Object.prototype.hasOwnProperty,Sx=(e,t)=>{for(var n in t)ya(e,n,{get:t[n],enumerable:!0})},Ff=(e,t,n,r)=>{if(t&&typeof t==="object"||typeof t==="function"){for(let i of yx(t))if(!xx.call(e,i)&&i!==n)ya(e,i,{get:()=>t[i],enumerable:!(r=mx(t,i))||r.enumerable})}return e},Mf=(e,t,n)=>(n=e!=null?gx(vx(e)):{},Ff(t||!e||!e.__esModule?ya(n,"default",{value:e,enumerable:!0}):n,e)),bx=(e)=>Ff(ya({},"__esModule",{value:!0}),e),$f={};Sx($f,{Socks5Server:()=>Hf,createServer:()=>Tx,defaultConnectionHandler:()=>Ul});Kf.exports=bx($f);var Cx=Mf(ui("net")),Wf=((e)=>(e[e.connect=1]="connect",e[e.bind=2]="bind",e[e.udp=3]="udp",e))(Wf||{}),Ol=((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))(Ol||{}),wx=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=(s)=>{let a=Math.min(s.length,e-r);if(s.copy(n,r,0,a),r+=a,r<e)return;this.socket.removeListener("data",i),this.socket.push(s.subarray(a)),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,s=()=>{if(i)return;i=!0,this.socket.write(Buffer.from([1,0])),this.handleConnectionRequest()},a=()=>{if(i)return;i=!0,this.socket.write(Buffer.from([1,1])),this.socket.destroy()},o=await this.server.authHandler(this,s,a);if(o===!0)s();else if(o===!1)a()}async handleConnectionRequest(){await this.readBytes(1);let e=(await this.readBytes(1))[0],t=Wf[e];if(!t)return this.socket.destroy();this.command=t,await this.readBytes(1);let n=(await this.readBytes(1)).readUInt8(),r="";switch(n){case 1:r=(await this.readBytes(4)).join(".");break;case 3:let c=(await this.readBytes(1)).readUInt8();r=(await this.readBytes(c)).toString();break;case 4:let u=await this.readBytes(16);for(let d=0;d<16;d++){if(d%2===0&&d>0)r+=":";r+=`${u[d]<16?"0":""}${u[d].toString(16)}`}break;default:this.socket.destroy();return}let i=(await this.readBytes(2)).readUInt16BE();if(!this.server.supportedCommands.has(t))return this.socket.write(Buffer.from([5,7])),this.socket.destroy();this.destAddress=r,this.destPort=i;let s=!1,a=()=>{if(s)return;s=!0,this.connect()};if(!this.server.rulesetValidator)return a();let o=()=>{if(s)return;s=!0,this.socket.write(Buffer.from([5,2,0,1,0,0,0,0,0,0])),this.socket.destroy()},l=await this.server.rulesetValidator(this,a,o);if(l===!0)a();else if(l===!1)o()}connect(){this.socket.removeListener("error",this.errorHandler),this.server.connectionHandler(this,(e)=>{if(Ol[e]===void 0)throw Error(`"${e}" is not a valid status.`);if(this.socket.write(Buffer.from([5,Ol[e],0,1,0,0,0,0,0,0])),e!=="REQUEST_GRANTED")this.socket.destroy()}),this.socket.resume()}},Ex=Mf(ui("net"));function Ul(e,t){if(e.command!=="connect")return t("COMMAND_NOT_SUPPORTED");e.socket.on("error",()=>{});let n=Ex.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 Hf=class{constructor(){this.supportedCommands=new Set(["connect"]),this.connectionHandler=Ul,this.server=Cx.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=Ul,this}_handleConnection(e){return new wx(this,e),this}};function Tx(e){let t=new Hf;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 ux,createServer as dx}from"http";import{request as Ll}from"http";import{request as Lf}from"https";import{connect as fx,isIP as Of}from"net";import{URL as Uf}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 g0}from"crypto";function bs(e,t){let n=Buffer.from(e),r=Buffer.from(t);if(n.length!==r.length)return!1;return g0(n,r)}import{homedir as Cs}from"os";import*as ct from"path";import*as en from"fs";import*as Hc from"fs";function io(){if(process.platform!=="linux")return;try{let e=Hc.readFileSync("/proc/version",{encoding:"utf8"}),t=e.match(/WSL(\d+)/i);if(t&&t[1])return t[1];if(e.toLowerCase().includes("microsoft"))return"1";return}catch{return}}function Ne(){switch(process.platform){case"darwin":return"macos";case"linux":return"linux";case"win32":return"windows";default:return"unknown"}}var di=[".gitconfig",".gitmodules",".bashrc",".bash_profile",".zshrc",".zprofile",".profile",".ripgreprc",".mcp.json"],m0=[".git",".vscode",".idea"];function Es(){return[...m0.filter((e)=>e!==".git"),".claude/commands",".claude/agents"]}function so(e){return e.toLowerCase()}function St(e){return e.includes("*")||e.includes("?")||e.includes("[")||e.includes("]")}function fi(e){return e.includes("*")||e.includes("?")}function Kc(e){return Ne()==="windows"?fi(e):St(e)}function qc(e){if(/^\\\\\?\\unc\\/i.test(e))return"\\\\"+e.slice(8);if(e.startsWith("\\\\?\\"))return e.slice(4);return e}function pi(e){let t=ct.win32.toNamespacedPath(e);return/^[\\/]{2}[?.][\\/]unc[\\/]/i.test(t)}function vr(e){return e.replace(/\/\*\*$/,"")||"/"}function ws(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 s=n;if(n.startsWith("/tmp/"))s="/private"+n;else if(n.startsWith("/var/"))s="/private"+n;if(s!==n&&s.startsWith(r+"/"))return!0;let a=r.startsWith(n+"/"),o=s!==n&&r.startsWith(s+"/");if(r!==n&&!(s!==n&&r===s)&&!a&&!o)return!0;return!1}function y0(e){if(e==="~")return Cs();if(e.startsWith("~/")||process.platform==="win32"&&e.startsWith("~\\"))return Cs()+e.slice(1);return e}function v0(e){let t=Cs(),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 Gc(e){let t=e.length;while(t>0&&e.charCodeAt(t-1)===47)t--;return e.slice(0,t)}function et(e){let t=process.cwd();if(Ne()==="windows"){if(e=qc(v0(e)),/^[a-z]:/.test(e))e=e[0].toUpperCase()+e.slice(1);if(pi(e)&&!fi(e))return ct.win32.normalize(e)}if(Ne()!=="windows"&&e.endsWith("/")&&e!=="/"&&!Kc(e))e=Gc(e)||"/";let n=y0(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(Kc(n)){let r=Ne()==="windows"?/[*?]/:/[*?[\]]/,i=n.split(r)[0];if(i&&i!=="/"){let s=i.endsWith("/")?i.slice(0,-1):ct.dirname(i);try{let a=en.realpathSync(s);if(!ws(s,a)){let o=n.slice(s.length);return a+o}}catch{}}return n}try{let r=en.realpathSync(n);if(ws(n,r));else n=r}catch{}return n}function Cn(e){let t=e??Cs();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 x0=["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 wn(e,t,n,r,i,s){let a=b0(s),o=a===yr?a:encodeURIComponent(a),l=r?`${o}:${r}@`:"",c=Ne()==="linux"?"127.0.0.1":"localhost",u=["SANDBOX_RUNTIME=1"];if(!i){let h=process.env.CLAUDE_CODE_TMPDIR||process.env.CLAUDE_TMPDIR||"/tmp/claude";u.push(`TMPDIR=${h}`)}if(n)for(let h of x0)u.push(`${h}=${n}`);if(!e&&!t)return u;let d=["localhost","127.0.0.1","::1","169.254.0.0/16","10.0.0.0/8","172.16.0.0/12","192.168.0.0/16"].join(",");if(u.push(`NO_PROXY=${d}`),u.push(`no_proxy=${d}`),e){if(u.push(`HTTP_PROXY=http://${l}${c}:${e}`),u.push(`HTTPS_PROXY=http://${l}${c}:${e}`),u.push(`http_proxy=http://${l}${c}:${e}`),u.push(`https_proxy=http://${l}${c}:${e}`),r)u.push("GIT_CONFIG_PARAMETERS='http.proxyAuthMethod=basic'")}let p=e?`http://${l}${c}:${e}`:`socks5h://${l}${c}:${t}`;if(u.push(`ALL_PROXY=${p}`),u.push(`all_proxy=${p}`),u.push(`GRPC_PROXY=${p}`),u.push(`grpc_proxy=${p}`),t){let f=Ne();if(f==="macos")u.push(`GIT_SSH_COMMAND=ssh -o ControlMaster=no -o ControlPath=none -o ProxyCommand='nc -X 5 -x localhost:${t} %h %p'`);else if(f==="linux"&&e){let v=r?`,proxyauth=${a}:${r}`:"";if(u.push(`GIT_SSH_COMMAND=ssh -o ControlMaster=no -o ControlPath=none -o ProxyCommand='socat - PROXY:${c}:%h:%p,proxyport=${e}${v}'`),r)u.push(`SRT_SSH_PROXY_AUTH=${a}:${r}`)}if(u.push(`FTP_PROXY=socks5h://${l}${c}:${t}`),u.push(`ftp_proxy=socks5h://${l}${c}:${t}`),u.push(`RSYNC_PROXY=${c}:${t}`),u.push(`DOCKER_HTTP_PROXY=http://${l}${c}:${e||t}`),u.push(`DOCKER_HTTPS_PROXY=http://${l}${c}:${e||t}`),e){if(u.push("CLOUDSDK_PROXY_TYPE=http"),u.push(`CLOUDSDK_PROXY_ADDRESS=${c}`),u.push(`CLOUDSDK_PROXY_PORT=${e}`),r)u.push(`CLOUDSDK_PROXY_USERNAME=${a}`),u.push(`CLOUDSDK_PROXY_PASSWORD=${r}`)}}return u}var S0=8;function hi(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={},s=(o,l)=>{i[`GIT_CONFIG_KEY_${r}`]=o,i[`GIT_CONFIG_VALUE_${r}`]=l,r++},a=[...new Set(e.safeDirs.filter((o)=>!!o).map((o)=>{let l=o.replace(/\\/g,"/"),c=Gc(l);if(c===""||/^[A-Za-z]:$/.test(c))return`${c}/`;return c}))];if(a.length>S0)s("safe.directory","*");else for(let o of a)s("safe.directory",o),s("safe.directory",o.endsWith("/")?`${o}*`:`${o}/*`);if(e.schannelCa)s("http.schannelUseSSLCAInfo","true"),s("http.schannelCheckRevoke","false");if(r===n)return{};return i.GIT_CONFIG_COUNT=String(r),i}function Ts(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??{}),hi({safeDirs:e.safeDirs,baseEnv:t})}function Dt(e){let t=e.slice(0,100);return Buffer.from(t).toString("base64")}function tn(e){return Buffer.from(e,"base64").toString("utf8")}var yr="srt";function b0(e){if(!e)return yr;let t=`${yr}.${e}`;return Buffer.byteLength(t)<=255?t:yr}function As(e){if(!e||!e.startsWith(`${yr}.`))return;return e.slice(yr.length+1)||void 0}function C0(e){let t=e.indexOf("[",e.lastIndexOf("]")+1);return t<0?e:`${e.slice(0,t)}\\${e.slice(t)}`}function gi(e){return"^"+C0(e.replace(/[.^$+{}()|\\]/g,"\\$&")).replace(/\*\*\//g,"__GLOBSTAR_SLASH__").replace(/\*\*/g,"__GLOBSTAR__").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").replace(/__GLOBSTAR_SLASH__/g,"(.*/)?").replace(/__GLOBSTAR__/g,".*")+"$"}function rn(e,t={}){let n=(l)=>process.platform==="win32"?l.replace(/\\/g,"/"):l,r=n(et(e)),i=r.split(/[*?[\]]/)[0];if(!i||i==="/")return w(`[Sandbox] Glob pattern too broad, skipping: ${e}`),[];let s=i.endsWith("/")?i.slice(0,-1):ct.dirname(i);if(!en.existsSync(s))return w(`[Sandbox] Base directory for glob does not exist: ${s}`),[];let a=new RegExp(gi(r),t.caseInsensitive?"i":""),o=[];try{let l=en.readdirSync(s,{recursive:!0,withFileTypes:!0});for(let c of l){let u=c.parentPath??c.path??s,d=ct.join(u,c.name);if(a.test(n(d)))o.push(d)}}catch(l){w(`[Sandbox] Error expanding glob pattern ${e}: ${l}`)}return o}var lf=no(ul(),1);import{sign as fv,X509Certificate as pv}from"crypto";import{mkdtempSync as fl,readFileSync as pl,writeFileSync as hl}from"fs";import{rm as hv}from"fs/promises";import{tmpdir as gl}from"os";import{join as $n,dirname as dl}from"path";import{rootCertificates as gv}from"tls";var{asn1:Je,pki:zt,md:mv,random:yv,util:cf}=lf.default,vv=zt.getTBSCertificate,xv=/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g,aa="/srt.crl";function ml(e){let t=e.getExtension("subjectKeyIdentifier");return t?.subjectKeyIdentifier?cf.hexToBytes(t.subjectKeyIdentifier):e.generateSubjectKeyIdentifier().getBytes()}function yl(e,t){let n=zt.oids.sha256WithRSAEncryption;e.siginfo.algorithmOid=n,e.signatureOid=n,e.tbsCertificate=vv(e);let r=Je.toDer(e.tbsCertificate).getBytes();e.signature=uf(r,t),e.md=mv.sha256.create(),e.md.update(r)}function uf(e,t){return fv("sha256",Buffer.from(e,"binary"),t).toString("binary")}function vl(e){if(e.caCertPem&&e.caKeyPem){let t=Pi(e.caCertPem,e.caKeyPem);if(!t.ok)throw Error(`tlsTerminate: CA PEM pair: ${t.reason}`);return xl(e.caCertPem,e.caKeyPem,t.cert,t.key,{certPath:e.caCertPath??"",keyPath:e.caKeyPath??"",extraCaCertPaths:e.extraCaCertPaths})}if(e.caCertPath&&e.caKeyPath)return Cv(e.caCertPath,e.caKeyPath,e.extraCaCertPaths);if(e.caCertPath||e.caKeyPath)throw Error("tlsTerminate: caCertPath and caKeyPath must be provided together");return wv(e.extraCaCertPaths)}async function df(e){let t=new Set([dl(e.trustBundlePath)]);if(e.ephemeral){if(t.add(dl(e.certPath)),e.keyPath)t.add(dl(e.keyPath))}for(let n of t)try{await hv(n,{recursive:!0,force:!0})}catch(r){w(`[mitm-ca] cleanup failed: ${r.message}`,{level:"warn"})}}function Sv(e,t,n){let r=[t.trim(),...gv],i=process.env.NODE_EXTRA_CA_CERTS;if(i)try{r.push(pl(i,"utf8").trim())}catch{}for(let a of n??[]){let o;try{o=pl(a,"utf8")}catch(c){let u=c.code??String(c);w(`[mitm-ca] extraCaCertPaths: cannot read ${a} (${u}); skipping`,{level:"warn"});continue}let l=o.match(xv);if(!l){w(`[mitm-ca] extraCaCertPaths: ${a} has no PEM CERTIFICATE block; skipping`,{level:"warn"});continue}r.push(...l)}let s=$n(e,"trust-bundle.crt");return hl(s,r.join(`
27
+ `,s};sa.publicKeyToOpenSSH=function(e,t){var n="ssh-rsa";t=t||"";var r=it.util.createBuffer();return Fn(r,n),ur(r,e.e),ur(r,e.n),n+" "+it.util.encode64(r.bytes())+" "+t};sa.privateKeyToOpenSSH=function(e,t){if(!t)return it.pki.privateKeyToPem(e);return it.pki.encryptRsaPrivateKey(e,t,{legacy:!0,algorithm:"aes128"})};sa.getPublicKeyFingerprint=function(e,t){t=t||{};var n=t.md||it.md.md5.create(),r="ssh-rsa",i=it.util.createBuffer();Fn(i,r),ur(i,e.e),ur(i,e.n),n.start(),n.update(i.getBytes());var s=n.digest();if(t.encoding==="hex"){var a=s.toHex();if(t.delimiter)return a.match(/.{2}/g).join(t.delimiter);return a}else if(t.encoding==="binary")return s.getBytes();else if(t.encoding)throw Error('Unknown encoding "'+t.encoding+'".');return s};function ur(e,t){var n=t.toString(16);if(n[0]>="8")n="00"+n;var r=it.util.hexToBytes(n);e.putInt32(r.length),e.putBytes(r)}function Fn(e,t){e.putInt32(t.length),e.putString(t)}function ia(){var e=it.md.sha1.create(),t=arguments.length;for(var n=0;n<t;++n)e.update(arguments[n]);return e.digest()}});var ul=de(function(q1,sf){sf.exports=ye();Lr();_d();Gt();ks();Si();Kd();An();zd();Qd();Jd();Oo();Fs();sn();Io();Fo();tf();$o();Bo();bo();Gs();Lt();Eo();nf();jo();Ne()});var qf=de(function(Jw,Kf){var{create:hx,defineProperty:ya,getOwnPropertyDescriptor:gx,getOwnPropertyNames:mx,getPrototypeOf:yx}=Object,vx=Object.prototype.hasOwnProperty,xx=(e,t)=>{for(var n in t)ya(e,n,{get:t[n],enumerable:!0})},Ff=(e,t,n,r)=>{if(t&&typeof t==="object"||typeof t==="function"){for(let i of mx(t))if(!vx.call(e,i)&&i!==n)ya(e,i,{get:()=>t[i],enumerable:!(r=gx(t,i))||r.enumerable})}return e},Mf=(e,t,n)=>(n=e!=null?hx(yx(e)):{},Ff(t||!e||!e.__esModule?ya(n,"default",{value:e,enumerable:!0}):n,e)),Sx=(e)=>Ff(ya({},"__esModule",{value:!0}),e),$f={};xx($f,{Socks5Server:()=>Hf,createServer:()=>Ex,defaultConnectionHandler:()=>Ul});Kf.exports=Sx($f);var bx=Mf(ui("net")),Wf=((e)=>(e[e.connect=1]="connect",e[e.bind=2]="bind",e[e.udp=3]="udp",e))(Wf||{}),Ol=((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))(Ol||{}),Cx=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=(s)=>{let a=Math.min(s.length,e-r);if(s.copy(n,r,0,a),r+=a,r<e)return;this.socket.removeListener("data",i),this.socket.push(s.subarray(a)),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,s=()=>{if(i)return;i=!0,this.socket.write(Buffer.from([1,0])),this.handleConnectionRequest()},a=()=>{if(i)return;i=!0,this.socket.write(Buffer.from([1,1])),this.socket.destroy()},o=await this.server.authHandler(this,s,a);if(o===!0)s();else if(o===!1)a()}async handleConnectionRequest(){await this.readBytes(1);let e=(await this.readBytes(1))[0],t=Wf[e];if(!t)return this.socket.destroy();this.command=t,await this.readBytes(1);let n=(await this.readBytes(1)).readUInt8(),r="";switch(n){case 1:r=(await this.readBytes(4)).join(".");break;case 3:let c=(await this.readBytes(1)).readUInt8();r=(await this.readBytes(c)).toString();break;case 4:let u=await this.readBytes(16);for(let d=0;d<16;d++){if(d%2===0&&d>0)r+=":";r+=`${u[d]<16?"0":""}${u[d].toString(16)}`}break;default:this.socket.destroy();return}let i=(await this.readBytes(2)).readUInt16BE();if(!this.server.supportedCommands.has(t))return this.socket.write(Buffer.from([5,7])),this.socket.destroy();this.destAddress=r,this.destPort=i;let s=!1,a=()=>{if(s)return;s=!0,this.connect()};if(!this.server.rulesetValidator)return a();let o=()=>{if(s)return;s=!0,this.socket.write(Buffer.from([5,2,0,1,0,0,0,0,0,0])),this.socket.destroy()},l=await this.server.rulesetValidator(this,a,o);if(l===!0)a();else if(l===!1)o()}connect(){this.socket.removeListener("error",this.errorHandler),this.server.connectionHandler(this,(e)=>{if(Ol[e]===void 0)throw Error(`"${e}" is not a valid status.`);if(this.socket.write(Buffer.from([5,Ol[e],0,1,0,0,0,0,0,0])),e!=="REQUEST_GRANTED")this.socket.destroy()}),this.socket.resume()}},wx=Mf(ui("net"));function Ul(e,t){if(e.command!=="connect")return t("COMMAND_NOT_SUPPORTED");e.socket.on("error",()=>{});let n=wx.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 Hf=class{constructor(){this.supportedCommands=new Set(["connect"]),this.connectionHandler=Ul,this.server=bx.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=Ul,this}_handleConnection(e){return new Cx(this,e),this}};function Ex(e){let t=new Hf;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 cx,createServer as ux}from"http";import{request as Ll}from"http";import{request as Lf}from"https";import{connect as dx,isIP as Of}from"net";import{URL as Uf}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 h0}from"crypto";function bs(e,t){let n=Buffer.from(e),r=Buffer.from(t);if(n.length!==r.length)return!1;return h0(n,r)}import{homedir as Cs}from"os";import*as ct from"path";import*as en from"fs";import*as Hc from"fs";function io(){if(process.platform!=="linux")return;try{let e=Hc.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 De(){switch(process.platform){case"darwin":return"macos";case"linux":return"linux";case"win32":return"windows";default:return"unknown"}}var di=[".gitconfig",".gitmodules",".bashrc",".bash_profile",".zshrc",".zprofile",".profile",".ripgreprc",".mcp.json"],g0=[".git",".vscode",".idea"];function Es(){return[...g0.filter((e)=>e!==".git"),".claude/commands",".claude/agents"]}function so(e){return e.toLowerCase()}function St(e){return e.includes("*")||e.includes("?")||e.includes("[")||e.includes("]")}function fi(e){return e.includes("*")||e.includes("?")}function Kc(e){return De()==="windows"?fi(e):St(e)}function qc(e){if(/^\\\\\?\\unc\\/i.test(e))return"\\\\"+e.slice(8);if(e.startsWith("\\\\?\\"))return e.slice(4);return e}function pi(e){let t=ct.win32.toNamespacedPath(e);return/^[\\/]{2}[?.][\\/]unc[\\/]/i.test(t)}function vr(e){return e.replace(/\/\*\*$/,"")||"/"}function ws(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 s=n;if(n.startsWith("/tmp/"))s="/private"+n;else if(n.startsWith("/var/"))s="/private"+n;if(s!==n&&s.startsWith(r+"/"))return!0;let a=r.startsWith(n+"/"),o=s!==n&&r.startsWith(s+"/");if(r!==n&&!(s!==n&&r===s)&&!a&&!o)return!0;return!1}function m0(e){if(e==="~")return Cs();if(e.startsWith("~/")||process.platform==="win32"&&e.startsWith("~\\"))return Cs()+e.slice(1);return e}function y0(e){let t=Cs(),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 Gc(e){let t=e.length;while(t>0&&e.charCodeAt(t-1)===47)t--;return e.slice(0,t)}function et(e){let t=process.cwd();if(De()==="windows"){if(e=qc(y0(e)),/^[a-z]:/.test(e))e=e[0].toUpperCase()+e.slice(1);if(pi(e)&&!fi(e))return ct.win32.normalize(e)}if(De()!=="windows"&&e.endsWith("/")&&e!=="/"&&!Kc(e))e=Gc(e)||"/";let n=m0(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(Kc(n)){let r=De()==="windows"?/[*?]/:/[*?[\]]/,i=n.split(r)[0];if(i&&i!=="/"){let s=i.endsWith("/")?i.slice(0,-1):ct.dirname(i);try{let a=en.realpathSync(s);if(!ws(s,a)){let o=n.slice(s.length);return a+o}}catch{}}return n}try{let r=en.realpathSync(n);if(ws(n,r));else n=r}catch{}return n}function Cn(e){let t=e??Cs();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 v0=["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 wn(e,t,n,r,i,s){let a=S0(s),o=a===yr?a:encodeURIComponent(a),l=r?`${o}:${r}@`:"",c=De()==="linux"?"127.0.0.1":"localhost",u=["SANDBOX_RUNTIME=1"];if(!i){let h=process.env.CLAUDE_CODE_TMPDIR||process.env.CLAUDE_TMPDIR||"/tmp/claude";u.push(`TMPDIR=${h}`)}if(n)for(let h of v0)u.push(`${h}=${n}`);if(!e&&!t)return u;let d=["localhost","127.0.0.1","::1","169.254.0.0/16","10.0.0.0/8","172.16.0.0/12","192.168.0.0/16"].join(",");if(u.push(`NO_PROXY=${d}`),u.push(`no_proxy=${d}`),e){if(u.push(`HTTP_PROXY=http://${l}${c}:${e}`),u.push(`HTTPS_PROXY=http://${l}${c}:${e}`),u.push(`http_proxy=http://${l}${c}:${e}`),u.push(`https_proxy=http://${l}${c}:${e}`),r)u.push("GIT_CONFIG_PARAMETERS='http.proxyAuthMethod=basic'")}let p=e?`http://${l}${c}:${e}`:`socks5h://${l}${c}:${t}`;if(u.push(`ALL_PROXY=${p}`),u.push(`all_proxy=${p}`),u.push(`GRPC_PROXY=${p}`),u.push(`grpc_proxy=${p}`),t){let f=De();if(f==="macos")u.push(`GIT_SSH_COMMAND=ssh -o ControlMaster=no -o ControlPath=none -o ProxyCommand='nc -X 5 -x localhost:${t} %h %p'`);else if(f==="linux"&&e){let v=r?`,proxyauth=${a}:${r}`:"";if(u.push(`GIT_SSH_COMMAND=ssh -o ControlMaster=no -o ControlPath=none -o ProxyCommand='socat - PROXY:${c}:%h:%p,proxyport=${e}${v}'`),r)u.push(`SRT_SSH_PROXY_AUTH=${a}:${r}`)}if(u.push(`FTP_PROXY=socks5h://${l}${c}:${t}`),u.push(`ftp_proxy=socks5h://${l}${c}:${t}`),u.push(`RSYNC_PROXY=${c}:${t}`),u.push(`DOCKER_HTTP_PROXY=http://${l}${c}:${e||t}`),u.push(`DOCKER_HTTPS_PROXY=http://${l}${c}:${e||t}`),e){if(u.push("CLOUDSDK_PROXY_TYPE=http"),u.push(`CLOUDSDK_PROXY_ADDRESS=${c}`),u.push(`CLOUDSDK_PROXY_PORT=${e}`),r)u.push(`CLOUDSDK_PROXY_USERNAME=${a}`),u.push(`CLOUDSDK_PROXY_PASSWORD=${r}`)}}return u}var x0=8;function hi(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={},s=(o,l)=>{i[`GIT_CONFIG_KEY_${r}`]=o,i[`GIT_CONFIG_VALUE_${r}`]=l,r++},a=[...new Set(e.safeDirs.filter((o)=>!!o).map((o)=>{let l=o.replace(/\\/g,"/"),c=Gc(l);if(c===""||/^[A-Za-z]:$/.test(c))return`${c}/`;return c}))];if(a.length>x0)s("safe.directory","*");else for(let o of a)s("safe.directory",o),s("safe.directory",o.endsWith("/")?`${o}*`:`${o}/*`);if(e.schannelCa)s("http.schannelUseSSLCAInfo","true"),s("http.schannelCheckRevoke","false");if(r===n)return{};return i.GIT_CONFIG_COUNT=String(r),i}function Ts(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??{}),hi({safeDirs:e.safeDirs,baseEnv:t})}function Dt(e){let t=e.slice(0,100);return Buffer.from(t).toString("base64")}function tn(e){return Buffer.from(e,"base64").toString("utf8")}var yr="srt";function S0(e){if(!e)return yr;let t=`${yr}.${e}`;return Buffer.byteLength(t)<=255?t:yr}function As(e){if(!e||!e.startsWith(`${yr}.`))return;return e.slice(yr.length+1)||void 0}function b0(e){let t=e.indexOf("[",e.lastIndexOf("]")+1);return t<0?e:`${e.slice(0,t)}\\${e.slice(t)}`}function gi(e){return"^"+b0(e.replace(/[.^$+{}()|\\]/g,"\\$&")).replace(/\*\*\//g,"__GLOBSTAR_SLASH__").replace(/\*\*/g,"__GLOBSTAR__").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").replace(/__GLOBSTAR_SLASH__/g,"(.*/)?").replace(/__GLOBSTAR__/g,".*")+"$"}function rn(e,t={}){let n=(l)=>process.platform==="win32"?l.replace(/\\/g,"/"):l,r=n(et(e)),i=r.split(/[*?[\]]/)[0];if(!i||i==="/")return w(`[Sandbox] Glob pattern too broad, skipping: ${e}`),[];let s=i.endsWith("/")?i.slice(0,-1):ct.dirname(i);if(!en.existsSync(s))return w(`[Sandbox] Base directory for glob does not exist: ${s}`),[];let a=new RegExp(gi(r),t.caseInsensitive?"i":""),o=[];try{let l=en.readdirSync(s,{recursive:!0,withFileTypes:!0});for(let c of l){let u=c.parentPath??c.path??s,d=ct.join(u,c.name);if(a.test(n(d)))o.push(d)}}catch(l){w(`[Sandbox] Error expanding glob pattern ${e}: ${l}`)}return o}var lf=no(ul(),1);import{sign as dv,X509Certificate as fv}from"crypto";import{mkdtempSync as fl,readFileSync as pl,writeFileSync as hl}from"fs";import{rm as pv}from"fs/promises";import{tmpdir as gl}from"os";import{join as $n,dirname as dl}from"path";import{rootCertificates as hv}from"tls";var{asn1:Je,pki:zt,md:gv,random:mv,util:cf}=lf.default,yv=zt.getTBSCertificate,vv=/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g,aa="/srt.crl";function ml(e){let t=e.getExtension("subjectKeyIdentifier");return t?.subjectKeyIdentifier?cf.hexToBytes(t.subjectKeyIdentifier):e.generateSubjectKeyIdentifier().getBytes()}function yl(e,t){let n=zt.oids.sha256WithRSAEncryption;e.siginfo.algorithmOid=n,e.signatureOid=n,e.tbsCertificate=yv(e);let r=Je.toDer(e.tbsCertificate).getBytes();e.signature=uf(r,t),e.md=gv.sha256.create(),e.md.update(r)}function uf(e,t){return dv("sha256",Buffer.from(e,"binary"),t).toString("binary")}function vl(e){if(e.caCertPem&&e.caKeyPem){let t=Pi(e.caCertPem,e.caKeyPem);if(!t.ok)throw Error(`tlsTerminate: CA PEM pair: ${t.reason}`);return xl(e.caCertPem,e.caKeyPem,t.cert,t.key,{certPath:e.caCertPath??"",keyPath:e.caKeyPath??"",extraCaCertPaths:e.extraCaCertPaths})}if(e.caCertPath&&e.caKeyPath)return bv(e.caCertPath,e.caKeyPath,e.extraCaCertPaths);if(e.caCertPath||e.caKeyPath)throw Error("tlsTerminate: caCertPath and caKeyPath must be provided together");return Cv(e.extraCaCertPaths)}async function df(e){let t=new Set([dl(e.trustBundlePath)]);if(e.ephemeral){if(t.add(dl(e.certPath)),e.keyPath)t.add(dl(e.keyPath))}for(let n of t)try{await pv(n,{recursive:!0,force:!0})}catch(r){w(`[mitm-ca] cleanup failed: ${r.message}`,{level:"warn"})}}function xv(e,t,n){let r=[t.trim(),...hv],i=process.env.NODE_EXTRA_CA_CERTS;if(i)try{r.push(pl(i,"utf8").trim())}catch{}for(let a of n??[]){let o;try{o=pl(a,"utf8")}catch(c){let u=c.code??String(c);w(`[mitm-ca] extraCaCertPaths: cannot read ${a} (${u}); skipping`,{level:"warn"});continue}let l=o.match(vv);if(!l){w(`[mitm-ca] extraCaCertPaths: ${a} has no PEM CERTIFICATE block; skipping`,{level:"warn"});continue}r.push(...l)}let s=$n(e,"trust-bundle.crt");return hl(s,r.join(`
28
28
  `)+`
29
- `,{mode:420}),s}function bv(e,t){let n=zt.oids.sha256WithRSAEncryption,r=()=>Mn([Je.create(Wt.UNIVERSAL,dr.OID,!1,Je.oidToDer(n).getBytes()),Je.create(Wt.UNIVERSAL,dr.NULL,!1,"")]),i=(p,h)=>Mn([Je.create(Wt.UNIVERSAL,dr.OID,!1,Je.oidToDer(p).getBytes()),Je.create(Wt.UNIVERSAL,dr.OCTETSTRING,!1,Je.toDer(h).getBytes())]),s=Je.create(Wt.CONTEXT_SPECIFIC,0,!0,[Mn([i(zt.oids.authorityKeyIdentifier,Mn([Je.create(Wt.CONTEXT_SPECIFIC,0,!1,ml(e))])),i("2.5.29.20",Je.create(Wt.UNIVERSAL,dr.INTEGER,!1,"\x01"))])]),a=new Date,o=e.validity.notAfter,l=o>a?o:Bi(1),c=Mn([Je.create(Wt.UNIVERSAL,dr.INTEGER,!1,"\x01"),r(),zt.distinguishedNameToAsn1(e.subject),af(a),af(l),s]),u=uf(Je.toDer(c).getBytes(),t),d=Mn([c,r(),Je.create(Wt.UNIVERSAL,dr.BITSTRING,!1,"\x00"+u)]);return Buffer.from(Je.toDer(d).getBytes(),"binary")}var{Class:Wt,Type:dr}=Je;function Mn(e){return Je.create(Wt.UNIVERSAL,dr.SEQUENCE,!0,e)}function af(e){return e.getUTCFullYear()<2050?Je.create(Wt.UNIVERSAL,dr.UTCTIME,!1,Je.dateToUtcTime(e)):Je.create(Wt.UNIVERSAL,dr.GENERALIZEDTIME,!1,Je.dateToGeneralizedTime(e))}function Cv(e,t,n){let r=of(e,"CERTIFICATE","tlsTerminate.caCertPath"),i=of(t,"PRIVATE KEY","tlsTerminate.caKeyPath"),s=Pi(r,i);if(!s.ok)throw Error(`tlsTerminate: CA at ${e}: ${s.reason}`);return w(`[mitm-ca] loaded CA from ${e}`),xl(r,i,s.cert,s.key,{certPath:e,keyPath:t,extraCaCertPaths:n})}function xl(e,t,n,r,i){let s=fl($n(gl(),"srt-ca-"));return{certPath:i.certPath,keyPath:i.keyPath,trustBundlePath:Sv(s,e,i.extraCaCertPaths),certPem:e,keyPem:t,cert:n,key:r,leafCerts:new Map,secureContexts:new Map,crlDer:bv(n,t),ephemeral:i.ephemeral??!1}}function oa(e={}){let t=zt.rsa.generateKeyPair(2048),n=zt.createCertificate();n.publicKey=t.publicKey,n.serialNumber=Sl(),n.validity.notBefore=Bi(-1),n.validity.notAfter=Bi(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=zt.privateKeyToPem(t.privateKey);return yl(n,i),{certPem:zt.certificateToPem(n),keyPem:i,cert:n,key:t.privateKey}}function Wn(e){return new pv(e).fingerprint.replace(/:/g,"").toUpperCase()}function Pi(e,t){let n,r;try{n=zt.certificateFromPem(e),r=zt.privateKeyFromPem(t)}catch(a){return{ok:!1,reason:`parse: ${a.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 s;try{s=Wn(e)}catch(a){return{ok:!1,reason:`thumbprint: ${a.message}`}}return{ok:!0,thumbprint:s,notAfter:n.validity.notAfter,cert:n,key:r}}function wv(e){let{certPem:t,keyPem:n,cert:r,key:i}=oa(),s=fl($n(gl(),"srt-ca-")),a=$n(s,"ca.crt"),o=$n(fl($n(gl(),"srt-ca-key-")),"ca.key");return hl(a,t,{mode:420}),hl(o,n,{mode:384}),w(`[mitm-ca] generated ephemeral CA at ${a}`),xl(t,n,r,i,{certPath:a,keyPath:o,extraCaCertPaths:e,ephemeral:!0})}function of(e,t,n){let r;try{r=pl(e,"utf8")}catch(i){let s=i.code??String(i);throw Error(`${n}: cannot read ${e} (${s})`)}if(!new RegExp(`-----BEGIN [A-Z ]*${t}-----`).test(r))throw Error(`${n}: ${e} is not a PEM ${t}`);return r}function Sl(){let e=yv.getBytesSync(16),t=cf.bytesToHex(e);return(parseInt(t[0],16)&7).toString(16)+t.slice(1)}function Bi(e){let t=new Date;return t.setDate(t.getDate()+e),t}import{BlockList as Ev,isIP as bl}from"net";import{lookup as Tv}from"dns/promises";var Ni=new Ev;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]])Ni.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]])Ni.addSubnet(e,t,"ipv6");function Av(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 la(e){let t=e.replace(/^\[|\]$/g,""),n=bl(t);if(n===0)return!1;if(n===4)return!Ni.check(t,"ipv4");let r=Av(t);if(r!==void 0)return bl(r)===4&&!Ni.check(r,"ipv4");return!Ni.check(t,"ipv6")}function Cl(e){let t=e.toLowerCase().replace(/\.$/,"");return t==="localhost"||t.endsWith(".localhost")||t==="localhost.localdomain"}class Hn extends Error{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"}}var _v=(e)=>Tv(e,{all:!0,verbatim:!0});async function ca(e,t=_v){let n=e.replace(/^\[|\]$/g,"");if(bl(n)){if(!la(n))throw new Hn(e);return n}if(Cl(n))throw new Hn(e);let r=await t(n);if(r.length===0)throw Error(`${e} did not resolve`);for(let{address:i}of r)if(!la(i))throw new Hn(e,i);return(r.find((i)=>i.family===4)??r[0]).address}import{PassThrough as kv,Readable as ff}from"stream";var wl=new Set(["GET","HEAD","OPTIONS"]),gf="denied by sandbox policy";function pf(e,t){if(t.writableFinished||t.destroyed){e.destroy();return}t.once("finish",()=>e.destroy()),t.once("close",()=>e.destroy())}async function ua(e,t,n,r,i,s){let a=t.method??"GET",o,l=t,c=Boolean(t.headers["content-length"]||t.headers["transfer-encoding"]),u=wl.has(a);if(!u||c){let h=new kv;h.on("error",()=>{}),t.pipe(h);let f=ff.toWeb(h),[v,x]=f.tee();o=v,l=ff.fromWeb(x);let S=l;S.on("error",()=>{}),t.on("error",(A)=>{h.end(),S.destroy(A)})}let d;try{if(o&&!(o instanceof ReadableStream))throw TypeError("Unexpected request body stream");let h=o&&!u?{body:o,duplex:"half"}:{};d=new Request(r,{method:a,headers:Iv(t),signal:i,...h})}catch(h){let f=`malformed request: ${h.message}`;if(s?.(a,r,f),hf(n,{action:"deny",reason:f}),o?.cancel().catch(()=>{}),l.destroy(),l!==t)pf(t,n);return null}let p;try{p=await e(d)}catch(h){p={action:"deny",reason:`sandbox policy check failed: ${h.message}`}}if(o&&!d.bodyUsed)o.cancel().catch(()=>{});if(p.action==="allow")return w(`[request-filter] allow ${a} ${r}`),l;if(s?.(a,r,p.reason??gf),hf(n,p),l.destroy(),l!==t)pf(t,n);return null}function hf(e,t){Di(e,t.reason??gf)}function Di(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 Iv(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 Yv,request as Jv}from"https";import{connect as Zv,isIP as Nl}from"net";import{unlink as ex}from"fs";import{tmpdir as tx}from"os";import{join as rx}from"path";import{Transform as Rv}from"stream";function Bv(e){return e.every((t)=>t.sentinel.length===t.realValue.length)}function da(e,t,n,r){if(e===void 0)return;let i=t.headers["content-length"]!==void 0||t.headers["transfer-encoding"]!==void 0;if(wl.has(t.method??"GET")&&!i)return;let s=e(r);if(!s?.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(!Bv(s))delete n["content-length"];return Pv(s)}function Pv(e){let t=Math.max(...e.map((r)=>r.sentinel.length)),n;return new Rv({transform(r,i,s){let a=Buffer.isBuffer(r)?r:Buffer.from(r,i),o=n?.length?Buffer.concat([n,a]):a,{out:l,tail:c}=Nv(o,e,t);n=c,s(null,l)},flush(r){r(null,n?.length?n:void 0)}})}function Nv(e,t,n){let r=[],i=0;for(;;){let a=-1,o;for(let l of t){let c=e.indexOf(l.sentinel,i);if(c!==-1&&(a===-1||c<a))a=c,o=l}if(o===void 0)break;r.push(e.subarray(i,a),o.realValue),i=a+o.sentinel.length}let s=Math.max(i,e.length-(n-1));return r.push(e.subarray(i,s)),{out:Buffer.concat(r),tail:Buffer.from(e.subarray(s))}}var mf=no(ul(),1);import{isIP as Dv}from"net";import{createSecureContext as Lv}from"tls";var{pki:fa}=mf.default;function El(e,t){let n=e.leafCerts.get(t);if(n)return n;let r=fa.rsa.generateKeyPair(2048),i=fa.createCertificate();i.publicKey=r.publicKey,i.serialNumber=Sl();let s=Bi(-1);i.validity.notBefore=s,i.validity.notAfter=Uv(e.cert,s),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:[Ov(t)]},{name:"subjectKeyIdentifier"},{name:"authorityKeyIdentifier",keyIdentifier:ml(e.cert)},...e.crlUrl?[{name:"cRLDistributionPoints",altNames:[{type:6,value:e.crlUrl}]}]:[]]),yl(i,e.keyPem);let a={certPem:fa.certificateToPem(i)+e.certPem,keyPem:fa.privateKeyToPem(r.privateKey)};return e.leafCerts.set(t,a),w(`[mitm-leaf] minted RSA leaf for ${t}`),a}function yf(e,t){let n=e.secureContexts.get(t);if(n)return n;let{certPem:r,keyPem:i}=El(e,t),s=Lv({cert:r,key:i});return e.secureContexts.set(t,s),s}function Ov(e){return Dv(e)!==0?{type:7,ip:e}:{type:2,value:e}}function Uv(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 vf,connect as xf,isIP as hn}from"net";import{connect as Vv}from"tls";import{URL as Tl}from"url";var Sf=30000,Fv=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","proxy-connection","te","trailer","transfer-encoding","upgrade"]);function Al(e){let t=e?.http??process.env.HTTP_PROXY??process.env.http_proxy??void 0,n=e?.https??process.env.HTTPS_PROXY??process.env.https_proxy??t,r=e?.noProxy??process.env.NO_PROXY??process.env.no_proxy??"";if(!t&&!n)return;let i=(o)=>{if(!o)return;let c=/^[a-z][a-z0-9+.-]*:\/\//i.test(o)?o:`http://${o}`;try{let u=new Tl(c);if(u.protocol!=="http:"&&u.protocol!=="https:"||!u.hostname)throw Error("unsupported scheme or empty host");return u}catch{w(`Invalid parent proxy URL, ignoring: ${Wv(o)}`,{level:"error"});return}},s=i(t),a=i(n);if(!s&&!a)return;return{httpUrl:s,httpsUrl:a,noProxy:Mv(r)}}function Mv(e){let t={all:!1,suffixes:[],cidr:new vf};for(let n of e.split(",")){if(n=n.trim(),!n)continue;if(n==="*"){t.all=!0;continue}let r=n.indexOf("/");if(r!==-1){let o=n.slice(0,r),l=n.slice(r+1),c=hn(o);if(c&&l!==""&&/^\d+$/.test(l)){let u=Number(l),d=c===6?128:32;if(u>=0&&u<=d){try{t.cidr.addSubnet(o,u,c===6?"ipv6":"ipv4")}catch{}continue}}continue}let i=n.toLowerCase(),s=/^\[([^\]]+)\](?::\d+)?$/.exec(i);if(s)i=s[1];if(i.startsWith("*."))i=i.slice(1);let a=hn(i);if(!a){let o=i.lastIndexOf(":");if(o!==-1&&/^\d+$/.test(i.slice(o+1)))i=i.slice(0,o)}else try{t.cidr.addAddress(i,a===6?"ipv6":"ipv4");continue}catch{}t.suffixes.push(i)}return t}function Li(e,t){let n=Xt(t.toLowerCase().replace(/\.$/,""));if(n==="localhost")return!0;let r=hn(n);if(r){if($v.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 $v=(()=>{let e=new vf;return e.addSubnet("127.0.0.0",8,"ipv4"),e.addAddress("::1","ipv6"),e.addSubnet("::ffff:127.0.0.0",104,"ipv6"),e})();function Oi(e,t){if(t.isHttps)return e.httpsUrl??e.httpUrl;return e.httpUrl}function _l(e){let{destHost:t,destPort:n}=e,r=Xt(t);if(!Kn(r))return Promise.reject(Error(`Invalid destination host for CONNECT: ${JSON.stringify(t)}`));if(!Number.isInteger(n)||n<1||n>65535)return Promise.reject(Error(`Invalid destination port: ${n}`));let i=hn(r)===6?`[${r}]:${n}`:`${r}:${n}`;return new Promise((s,a)=>{let o=e.dial(),l=!1,c=(d)=>{if(l)return;l=!0,o.destroy(),a(d)},u=()=>c(Error("Proxy closed during CONNECT handshake"));o.setTimeout(e.timeoutMs??Sf,()=>c(Error("CONNECT handshake timed out"))),o.once("error",c),o.once("close",u),o.once(e.readyEvent,()=>{o.write(`CONNECT ${i} HTTP/1.1\r
29
+ `,{mode:420}),s}function Sv(e,t){let n=zt.oids.sha256WithRSAEncryption,r=()=>Mn([Je.create(Wt.UNIVERSAL,dr.OID,!1,Je.oidToDer(n).getBytes()),Je.create(Wt.UNIVERSAL,dr.NULL,!1,"")]),i=(p,h)=>Mn([Je.create(Wt.UNIVERSAL,dr.OID,!1,Je.oidToDer(p).getBytes()),Je.create(Wt.UNIVERSAL,dr.OCTETSTRING,!1,Je.toDer(h).getBytes())]),s=Je.create(Wt.CONTEXT_SPECIFIC,0,!0,[Mn([i(zt.oids.authorityKeyIdentifier,Mn([Je.create(Wt.CONTEXT_SPECIFIC,0,!1,ml(e))])),i("2.5.29.20",Je.create(Wt.UNIVERSAL,dr.INTEGER,!1,"\x01"))])]),a=new Date,o=e.validity.notAfter,l=o>a?o:Bi(1),c=Mn([Je.create(Wt.UNIVERSAL,dr.INTEGER,!1,"\x01"),r(),zt.distinguishedNameToAsn1(e.subject),af(a),af(l),s]),u=uf(Je.toDer(c).getBytes(),t),d=Mn([c,r(),Je.create(Wt.UNIVERSAL,dr.BITSTRING,!1,"\x00"+u)]);return Buffer.from(Je.toDer(d).getBytes(),"binary")}var{Class:Wt,Type:dr}=Je;function Mn(e){return Je.create(Wt.UNIVERSAL,dr.SEQUENCE,!0,e)}function af(e){return e.getUTCFullYear()<2050?Je.create(Wt.UNIVERSAL,dr.UTCTIME,!1,Je.dateToUtcTime(e)):Je.create(Wt.UNIVERSAL,dr.GENERALIZEDTIME,!1,Je.dateToGeneralizedTime(e))}function bv(e,t,n){let r=of(e,"CERTIFICATE","tlsTerminate.caCertPath"),i=of(t,"PRIVATE KEY","tlsTerminate.caKeyPath"),s=Pi(r,i);if(!s.ok)throw Error(`tlsTerminate: CA at ${e}: ${s.reason}`);return w(`[mitm-ca] loaded CA from ${e}`),xl(r,i,s.cert,s.key,{certPath:e,keyPath:t,extraCaCertPaths:n})}function xl(e,t,n,r,i){let s=fl($n(gl(),"srt-ca-"));return{certPath:i.certPath,keyPath:i.keyPath,trustBundlePath:xv(s,e,i.extraCaCertPaths),certPem:e,keyPem:t,cert:n,key:r,leafCerts:new Map,secureContexts:new Map,crlDer:Sv(n,t),ephemeral:i.ephemeral??!1}}function oa(e={}){let t=zt.rsa.generateKeyPair(2048),n=zt.createCertificate();n.publicKey=t.publicKey,n.serialNumber=Sl(),n.validity.notBefore=Bi(-1),n.validity.notAfter=Bi(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=zt.privateKeyToPem(t.privateKey);return yl(n,i),{certPem:zt.certificateToPem(n),keyPem:i,cert:n,key:t.privateKey}}function Wn(e){return new fv(e).fingerprint.replace(/:/g,"").toUpperCase()}function Pi(e,t){let n,r;try{n=zt.certificateFromPem(e),r=zt.privateKeyFromPem(t)}catch(a){return{ok:!1,reason:`parse: ${a.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 s;try{s=Wn(e)}catch(a){return{ok:!1,reason:`thumbprint: ${a.message}`}}return{ok:!0,thumbprint:s,notAfter:n.validity.notAfter,cert:n,key:r}}function Cv(e){let{certPem:t,keyPem:n,cert:r,key:i}=oa(),s=fl($n(gl(),"srt-ca-")),a=$n(s,"ca.crt"),o=$n(fl($n(gl(),"srt-ca-key-")),"ca.key");return hl(a,t,{mode:420}),hl(o,n,{mode:384}),w(`[mitm-ca] generated ephemeral CA at ${a}`),xl(t,n,r,i,{certPath:a,keyPath:o,extraCaCertPaths:e,ephemeral:!0})}function of(e,t,n){let r;try{r=pl(e,"utf8")}catch(i){let s=i.code??String(i);throw Error(`${n}: cannot read ${e} (${s})`)}if(!new RegExp(`-----BEGIN [A-Z ]*${t}-----`).test(r))throw Error(`${n}: ${e} is not a PEM ${t}`);return r}function Sl(){let e=mv.getBytesSync(16),t=cf.bytesToHex(e);return(parseInt(t[0],16)&7).toString(16)+t.slice(1)}function Bi(e){let t=new Date;return t.setDate(t.getDate()+e),t}import{BlockList as wv,isIP as bl}from"net";import{lookup as Ev}from"dns/promises";var Ni=new wv;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]])Ni.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]])Ni.addSubnet(e,t,"ipv6");function Tv(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 la(e){let t=e.replace(/^\[|\]$/g,""),n=bl(t);if(n===0)return!1;if(n===4)return!Ni.check(t,"ipv4");let r=Tv(t);if(r!==void 0)return bl(r)===4&&!Ni.check(r,"ipv4");return!Ni.check(t,"ipv6")}function Cl(e){let t=e.toLowerCase().replace(/\.$/,"");return t==="localhost"||t.endsWith(".localhost")||t==="localhost.localdomain"}class Hn extends Error{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"}}var Av=(e)=>Ev(e,{all:!0,verbatim:!0});async function ca(e,t=Av){let n=e.replace(/^\[|\]$/g,"");if(bl(n)){if(!la(n))throw new Hn(e);return n}if(Cl(n))throw new Hn(e);let r=await t(n);if(r.length===0)throw Error(`${e} did not resolve`);for(let{address:i}of r)if(!la(i))throw new Hn(e,i);return(r.find((i)=>i.family===4)??r[0]).address}import{PassThrough as _v,Readable as ff}from"stream";var wl=new Set(["GET","HEAD","OPTIONS"]),gf="denied by sandbox policy";function pf(e,t){if(t.writableFinished||t.destroyed){e.destroy();return}t.once("finish",()=>e.destroy()),t.once("close",()=>e.destroy())}async function ua(e,t,n,r,i,s){let a=t.method??"GET",o,l=t,c=Boolean(t.headers["content-length"]||t.headers["transfer-encoding"]),u=wl.has(a);if(!u||c){let h=new _v;h.on("error",()=>{}),t.pipe(h);let f=ff.toWeb(h),[v,x]=f.tee();o=v,l=ff.fromWeb(x);let S=l;S.on("error",()=>{}),t.on("error",(A)=>{h.end(),S.destroy(A)})}let d;try{if(o&&!(o instanceof ReadableStream))throw TypeError("Unexpected request body stream");let h=o&&!u?{body:o,duplex:"half"}:{};d=new Request(r,{method:a,headers:kv(t),signal:i,...h})}catch(h){let f=`malformed request: ${h.message}`;if(s?.(a,r,f),hf(n,{action:"deny",reason:f}),o?.cancel().catch(()=>{}),l.destroy(),l!==t)pf(t,n);return null}let p;try{p=await e(d)}catch(h){p={action:"deny",reason:`sandbox policy check failed: ${h.message}`}}if(o&&!d.bodyUsed)o.cancel().catch(()=>{});if(p.action==="allow")return w(`[request-filter] allow ${a} ${r}`),l;if(s?.(a,r,p.reason??gf),hf(n,p),l.destroy(),l!==t)pf(t,n);return null}function hf(e,t){Di(e,t.reason??gf)}function Di(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 kv(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 Qv,request as Yv}from"https";import{connect as Jv,isIP as Nl}from"net";import{unlink as Zv}from"fs";import{tmpdir as ex}from"os";import{join as tx}from"path";import{Transform as Iv}from"stream";function Rv(e){return e.every((t)=>t.sentinel.length===t.realValue.length)}function da(e,t,n,r){if(e===void 0)return;let i=t.headers["content-length"]!==void 0||t.headers["transfer-encoding"]!==void 0;if(wl.has(t.method??"GET")&&!i)return;let s=e(r);if(!s?.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(!Rv(s))delete n["content-length"];return Bv(s)}function Bv(e){let t=Math.max(...e.map((r)=>r.sentinel.length)),n;return new Iv({transform(r,i,s){let a=Buffer.isBuffer(r)?r:Buffer.from(r,i),o=n?.length?Buffer.concat([n,a]):a,{out:l,tail:c}=Pv(o,e,t);n=c,s(null,l)},flush(r){r(null,n?.length?n:void 0)}})}function Pv(e,t,n){let r=[],i=0;for(;;){let a=-1,o;for(let l of t){let c=e.indexOf(l.sentinel,i);if(c!==-1&&(a===-1||c<a))a=c,o=l}if(o===void 0)break;r.push(e.subarray(i,a),o.realValue),i=a+o.sentinel.length}let s=Math.max(i,e.length-(n-1));return r.push(e.subarray(i,s)),{out:Buffer.concat(r),tail:Buffer.from(e.subarray(s))}}var mf=no(ul(),1);import{isIP as Nv}from"net";import{createSecureContext as Dv}from"tls";var{pki:fa}=mf.default;function El(e,t){let n=e.leafCerts.get(t);if(n)return n;let r=fa.rsa.generateKeyPair(2048),i=fa.createCertificate();i.publicKey=r.publicKey,i.serialNumber=Sl();let s=Bi(-1);i.validity.notBefore=s,i.validity.notAfter=Ov(e.cert,s),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:[Lv(t)]},{name:"subjectKeyIdentifier"},{name:"authorityKeyIdentifier",keyIdentifier:ml(e.cert)},...e.crlUrl?[{name:"cRLDistributionPoints",altNames:[{type:6,value:e.crlUrl}]}]:[]]),yl(i,e.keyPem);let a={certPem:fa.certificateToPem(i)+e.certPem,keyPem:fa.privateKeyToPem(r.privateKey)};return e.leafCerts.set(t,a),w(`[mitm-leaf] minted RSA leaf for ${t}`),a}function yf(e,t){let n=e.secureContexts.get(t);if(n)return n;let{certPem:r,keyPem:i}=El(e,t),s=Dv({cert:r,key:i});return e.secureContexts.set(t,s),s}function Lv(e){return Nv(e)!==0?{type:7,ip:e}:{type:2,value:e}}function Ov(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 vf,connect as xf,isIP as hn}from"net";import{connect as Uv}from"tls";import{URL as Tl}from"url";var Sf=30000,Vv=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","proxy-connection","te","trailer","transfer-encoding","upgrade"]);function Al(e){let t=e?.http??process.env.HTTP_PROXY??process.env.http_proxy??void 0,n=e?.https??process.env.HTTPS_PROXY??process.env.https_proxy??t,r=e?.noProxy??process.env.NO_PROXY??process.env.no_proxy??"";if(!t&&!n)return;let i=(o)=>{if(!o)return;let c=/^[a-z][a-z0-9+.-]*:\/\//i.test(o)?o:`http://${o}`;try{let u=new Tl(c);if(u.protocol!=="http:"&&u.protocol!=="https:"||!u.hostname)throw Error("unsupported scheme or empty host");return u}catch{w(`Invalid parent proxy URL, ignoring: ${$v(o)}`,{level:"error"});return}},s=i(t),a=i(n);if(!s&&!a)return;return{httpUrl:s,httpsUrl:a,noProxy:Fv(r)}}function Fv(e){let t={all:!1,suffixes:[],cidr:new vf};for(let n of e.split(",")){if(n=n.trim(),!n)continue;if(n==="*"){t.all=!0;continue}let r=n.indexOf("/");if(r!==-1){let o=n.slice(0,r),l=n.slice(r+1),c=hn(o);if(c&&l!==""&&/^\d+$/.test(l)){let u=Number(l),d=c===6?128:32;if(u>=0&&u<=d){try{t.cidr.addSubnet(o,u,c===6?"ipv6":"ipv4")}catch{}continue}}continue}let i=n.toLowerCase(),s=/^\[([^\]]+)\](?::\d+)?$/.exec(i);if(s)i=s[1];if(i.startsWith("*."))i=i.slice(1);let a=hn(i);if(!a){let o=i.lastIndexOf(":");if(o!==-1&&/^\d+$/.test(i.slice(o+1)))i=i.slice(0,o)}else try{t.cidr.addAddress(i,a===6?"ipv6":"ipv4");continue}catch{}t.suffixes.push(i)}return t}function Li(e,t){let n=Xt(t.toLowerCase().replace(/\.$/,""));if(n==="localhost")return!0;let r=hn(n);if(r){if(Mv.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 Mv=(()=>{let e=new vf;return e.addSubnet("127.0.0.0",8,"ipv4"),e.addAddress("::1","ipv6"),e.addSubnet("::ffff:127.0.0.0",104,"ipv6"),e})();function Oi(e,t){if(t.isHttps)return e.httpsUrl??e.httpUrl;return e.httpUrl}function _l(e){let{destHost:t,destPort:n}=e,r=Xt(t);if(!Kn(r))return Promise.reject(Error(`Invalid destination host for CONNECT: ${JSON.stringify(t)}`));if(!Number.isInteger(n)||n<1||n>65535)return Promise.reject(Error(`Invalid destination port: ${n}`));let i=hn(r)===6?`[${r}]:${n}`:`${r}:${n}`;return new Promise((s,a)=>{let o=e.dial(),l=!1,c=(d)=>{if(l)return;l=!0,o.destroy(),a(d)},u=()=>c(Error("Proxy closed during CONNECT handshake"));o.setTimeout(e.timeoutMs??Sf,()=>c(Error("CONNECT handshake timed out"))),o.once("error",c),o.once("close",u),o.once(e.readyEvent,()=>{o.write(`CONNECT ${i} HTTP/1.1\r
31
31
  Host: ${i}\r
32
32
  `+(e.authHeader?`Proxy-Authorization: ${e.authHeader}\r
33
33
  `:"")+`\r
34
34
  `);let d="",p=(h)=>{d+=h.toString("latin1");let f=d.indexOf(`\r
35
35
  \r
36
36
  `);if(f===-1){if(d.length>16384)c(Error("CONNECT response header too large"));return}o.pause(),o.removeListener("data",p);let v=d.slice(0,d.indexOf(`\r
37
- `));if(!/^HTTP\/1\.[01] 2\d\d(?:\s|$)/.test(v))return c(Error(`Proxy refused CONNECT: ${v.trim()}`));let x=d.slice(f+4);if(x.length)o.unshift(Buffer.from(x,"latin1"));l=!0,o.setTimeout(0),o.removeListener("error",c),o.removeListener("close",u),s(o)};o.on("data",p)})})}function pa(e,t,n){let r=Xt(e.hostname),i=Number(e.port)||(e.protocol==="https:"?443:80),s=e.protocol==="https:";return _l({destHost:t,destPort:n,authHeader:kl(e),readyEvent:s?"secureConnect":"connect",dial:()=>s?Vv({host:r,port:i,...hn(r)?{}:{servername:r}}):xf(i,r)})}function kl(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 Kr(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,s]of Object.entries(e)){let a=i.toLowerCase();if(!Fv.has(a)&&!t.has(a))r[i]=s}return r}function Xt(e){return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}function Il(e){if(!e)return"-";if(!e.username&&!e.password)return e.href;let t=new Tl(e.href);return t.username="***",t.password="***",t.href}function Wv(e){return e.replace(/\/\/[^@/]*@/,"//***:***@")}function Kn(e){if(!e||e.length>255)return!1;let t=Xt(e);if(t.includes("%"))return!1;if(hn(t))return!0;return/^[A-Za-z0-9._-]+$/.test(t)}function vt(e){try{let t=Xt(e),n=hn(t)===6?`[${t}]`:t,r=new Tl(`http://${n}/`).hostname;return Xt(r).replace(/\.$/,"")}catch{return}}async function ha(e,t,n=Sf,r=!1){let i=r?await ca(e):e;return new Promise((s,a)=>{let o=xf(t,i),l=!1,c=(u)=>{if(l)return;if(l=!0,o.setTimeout(0),u)o.destroy(),a(u);else s(o)};o.setTimeout(n,()=>c(Error("connect timed out"))),o.once("connect",()=>c()),o.once("error",c),o.once("close",()=>c(Error("socket closed before connect")))})}import{createHash as Hv,createHmac as Ef}from"crypto";var Ui="AWS4-HMAC-SHA256",Kv="AWS4-ECDSA-P256-SHA256",ma="UNSIGNED-PAYLOAD";function Tf(e,t){let n=qn(e.authorization);if(n!==void 0&&n.startsWith(Kv)){let o=bf(n);if(o!==void 0)return{kind:"sigv4a",accessKeyId:o}}else if(n!==void 0&&n.startsWith(Ui)){let o=bf(n);if(o!==void 0)return{kind:qn(e["x-amz-content-sha256"])?.startsWith("STREAMING-")?"streaming":"header-sigv4",accessKeyId:o}}let r=t.indexOf("?");if(r===-1)return null;let i=new URLSearchParams(t.slice(r+1));if(i.get("X-Amz-Algorithm")!==Ui)return null;if(!i.has("X-Amz-Signature"))return null;let s=i.get("X-Amz-Credential");if(!s)return null;let a=s.split("/")[0];return a?{kind:"presigned",accessKeyId:a}:null}function bf(e){return/Credential=([^/,\s]+)\//.exec(e)?.[1]}function Af(e){if(!e.startsWith(Ui))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[s,a,o,l]=i;if(!s||!a||!o||!l)return null;return{accessKeyId:s,date:a,region:o,service:l,signedHeaders:n.split(";").map((c)=>c.toLowerCase()),signature:r}}function Rl(e){return encodeURIComponent(e).replace(/[!'()*]/g,(t)=>"%"+t.charCodeAt(0).toString(16).toUpperCase())}function qv(e,t){if(e==="")return"/";if(t==="s3")return e;let n=[];for(let s of e.split("/")){if(s===""||s===".")continue;if(s==="..")n.pop();else n.push(s)}let r=n.length>0&&e.endsWith("/")?"/":"",i=`/${n.join("/")}${r}`;return Rl(i).replace(/%2F/gi,"/")}function Gv(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),s=r===-1?"":n.slice(r+1);t.push([Rl(Cf(i)),Rl(Cf(s))])}return t.sort(([n,r],[i,s])=>n<i?-1:n>i?1:r<s?-1:r>s?1:0),t.map(([n,r])=>`${n}=${r}`).join("&")}function Cf(e){try{return decodeURIComponent(e)}catch{return e}}function wf(e){return e.trim().replace(/[ \t]+/g," ")}function jv(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((a)=>a.toLowerCase()).sort(),s=[];for(let a of i){let o=a==="host"?e.hostHeader:e.headers[a];if(o===void 0)throw Error(`signed header "${a}" is missing from the request`);let l=Array.isArray(o)?o.map(wf).join(","):wf(String(o));s.push(`${a}:${l}`)}return[e.method.toUpperCase(),qv(n,e.scope.service),Gv(r),s.join(`
37
+ `));if(!/^HTTP\/1\.[01] 2\d\d(?:\s|$)/.test(v))return c(Error(`Proxy refused CONNECT: ${v.trim()}`));let x=d.slice(f+4);if(x.length)o.unshift(Buffer.from(x,"latin1"));l=!0,o.setTimeout(0),o.removeListener("error",c),o.removeListener("close",u),s(o)};o.on("data",p)})})}function pa(e,t,n){let r=Xt(e.hostname),i=Number(e.port)||(e.protocol==="https:"?443:80),s=e.protocol==="https:";return _l({destHost:t,destPort:n,authHeader:kl(e),readyEvent:s?"secureConnect":"connect",dial:()=>s?Uv({host:r,port:i,...hn(r)?{}:{servername:r}}):xf(i,r)})}function kl(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 Kr(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,s]of Object.entries(e)){let a=i.toLowerCase();if(!Vv.has(a)&&!t.has(a))r[i]=s}return r}function Xt(e){return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}function Il(e){if(!e)return"-";if(!e.username&&!e.password)return e.href;let t=new Tl(e.href);return t.username="***",t.password="***",t.href}function $v(e){return e.replace(/\/\/[^@/]*@/,"//***:***@")}function Kn(e){if(!e||e.length>255)return!1;let t=Xt(e);if(t.includes("%"))return!1;if(hn(t))return!0;return/^[A-Za-z0-9._-]+$/.test(t)}function vt(e){try{let t=Xt(e),n=hn(t)===6?`[${t}]`:t,r=new Tl(`http://${n}/`).hostname;return Xt(r).replace(/\.$/,"")}catch{return}}async function ha(e,t,n=Sf,r=!1){let i=r?await ca(e):e;return new Promise((s,a)=>{let o=xf(t,i),l=!1,c=(u)=>{if(l)return;if(l=!0,o.setTimeout(0),u)o.destroy(),a(u);else s(o)};o.setTimeout(n,()=>c(Error("connect timed out"))),o.once("connect",()=>c()),o.once("error",c),o.once("close",()=>c(Error("socket closed before connect")))})}import{createHash as Wv,createHmac as Ef}from"crypto";var Ui="AWS4-HMAC-SHA256",Hv="AWS4-ECDSA-P256-SHA256",ma="UNSIGNED-PAYLOAD";function Tf(e,t){let n=qn(e.authorization);if(n!==void 0&&n.startsWith(Hv)){let o=bf(n);if(o!==void 0)return{kind:"sigv4a",accessKeyId:o}}else if(n!==void 0&&n.startsWith(Ui)){let o=bf(n);if(o!==void 0)return{kind:qn(e["x-amz-content-sha256"])?.startsWith("STREAMING-")?"streaming":"header-sigv4",accessKeyId:o}}let r=t.indexOf("?");if(r===-1)return null;let i=new URLSearchParams(t.slice(r+1));if(i.get("X-Amz-Algorithm")!==Ui)return null;if(!i.has("X-Amz-Signature"))return null;let s=i.get("X-Amz-Credential");if(!s)return null;let a=s.split("/")[0];return a?{kind:"presigned",accessKeyId:a}:null}function bf(e){return/Credential=([^/,\s]+)\//.exec(e)?.[1]}function Af(e){if(!e.startsWith(Ui))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[s,a,o,l]=i;if(!s||!a||!o||!l)return null;return{accessKeyId:s,date:a,region:o,service:l,signedHeaders:n.split(";").map((c)=>c.toLowerCase()),signature:r}}function Rl(e){return encodeURIComponent(e).replace(/[!'()*]/g,(t)=>"%"+t.charCodeAt(0).toString(16).toUpperCase())}function Kv(e,t){if(e==="")return"/";if(t==="s3")return e;let n=[];for(let s of e.split("/")){if(s===""||s===".")continue;if(s==="..")n.pop();else n.push(s)}let r=n.length>0&&e.endsWith("/")?"/":"",i=`/${n.join("/")}${r}`;return Rl(i).replace(/%2F/gi,"/")}function qv(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),s=r===-1?"":n.slice(r+1);t.push([Rl(Cf(i)),Rl(Cf(s))])}return t.sort(([n,r],[i,s])=>n<i?-1:n>i?1:r<s?-1:r>s?1:0),t.map(([n,r])=>`${n}=${r}`).join("&")}function Cf(e){try{return decodeURIComponent(e)}catch{return e}}function wf(e){return e.trim().replace(/[ \t]+/g," ")}function Gv(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((a)=>a.toLowerCase()).sort(),s=[];for(let a of i){let o=a==="host"?e.hostHeader:e.headers[a];if(o===void 0)throw Error(`signed header "${a}" is missing from the request`);let l=Array.isArray(o)?o.map(wf).join(","):wf(String(o));s.push(`${a}:${l}`)}return[e.method.toUpperCase(),Kv(n,e.scope.service),qv(r),s.join(`
38
38
  `)+`
39
39
  `,i.join(";"),e.payloadHash].join(`
40
- `)}function zv(e,t,n){return[Ui,t,`${n.date}/${n.region}/${n.service}/aws4_request`,Bl(e)].join(`
41
- `)}function Xv(e,t){let n=ga(`AWS4${e}`,t.date),r=ga(n,t.region),i=ga(r,t.service);return ga(i,"aws4_request")}function _f(e){let t=jv(e),n=zv(t,e.amzDate,e.scope),r=Ef("sha256",Xv(e.secretAccessKey,e.scope)).update(n,"utf8").digest("hex"),i=[...e.signedHeaders].map((a)=>a.toLowerCase()).sort(),s=`${e.scope.date}/${e.scope.region}/${e.scope.service}/aws4_request`;return{authorization:`${Ui} Credential=${e.accessKeyId}/${s}, SignedHeaders=${i.join(";")}, Signature=${r}`,signature:r,canonicalRequest:t,stringToSign:n}}function Bl(e){return Hv("sha256").update(e).digest("hex")}function ga(e,t){return Ef("sha256",e).update(t,"utf8").digest()}function qn(e){return Array.isArray(e)?e[0]:e}var kf="reason-egress-target",If="reason-egress-token";class Pl{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((s)=>s.includes(n.placeholder)||Qv(s,n.placeholder)))return{url:new URL(n.url),token:n.token}}return}}function Qv(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 Pf=67108864;class Dl extends Error{}function Rf(e){return e.length>=3&&e[0]===22&&e[1]===3&&e[2]<=3}function Nf(e,t){if(t.length>=3)return Promise.resolve({isTLS:Rf(t),head:t});return new Promise((n)=>{let r=t,i=()=>{e.removeListener("data",s),e.removeListener("close",i),n({isTLS:Rf(r),head:r})},s=(a)=>{if(e.pause(),r=r.length?Buffer.concat([r,a]):a,r.length>=3)return i();e.resume()};e.on("data",s),e.once("close",i)})}function nx(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 Df(e,t,n,r,i,s,a,o,l=Pf,c){let u=El(e,a.hostname),d=Yv({ALPNProtocols:["http/1.1"],cert:u.certPem,key:u.keyPem,SNICallback:(f,v)=>{try{v(null,yf(e,f||a.hostname))}catch(x){v(x)}}});d.on("request",(f,v)=>{f.on("error",(x)=>{w(`[tls-terminate] client request error: ${x.message}`,{level:"error"})}),v.on("error",(x)=>{w(`[tls-terminate] client response error: ${x.message}`,{level:"error"})}),ix(t,n,r,f,v,a,o,l,c)}),d.on("clientError",(f,v)=>{w(`[tls-terminate] client connection error for ${a.hostname}: ${f.message}`,{level:"error"}),v.destroy()}),d.on("tlsClientError",(f,v)=>{w(`[tls-terminate] client TLS error for ${a.hostname}: ${f.message}`,{level:"error"}),v.destroy()}),d.on("upgrade",(f,v)=>{w("[tls-terminate] upgrade request refused",{level:"warn"}),v.destroy()});let p=cx(),h=()=>{d.close(),ex(p,()=>{})};d.on("error",(f)=>{w(`[tls-terminate] inner server listen failed: ${f.message}`,{level:"error"}),i.destroy(),h()}),d.listen(p,()=>{let f=Zv({path:p});f.on("error",(v)=>{w(`[tls-terminate] inner loopback failed: ${v.message}`,{level:"error"}),i.destroy(),h()}),f.once("connect",()=>{if(s.length)f.write(s);nx(i,f),f.pipe(i)}),i.on("error",()=>f.destroy()),i.once("close",()=>{f.destroy(),h()}),f.once("close",()=>i.destroy())}),d.unref()}function Bf(e,t){if(t.writableFinished||t.destroyed){e.destroy();return}t.once("finish",()=>e.destroy()),t.once("close",()=>e.destroy())}function ix(...e){sx(...e).catch((t)=>{w(`[tls-terminate] forwardUpstream failed: ${t.message}`,{level:"error"})})}async function sx(e,t,n,r,i,s,a,o=Pf,l){let c=ox(r.url),u=r;if(e){let b=new AbortController;i.once("close",()=>b.abort());let k=s.port===443?s.hostname:`${s.hostname}:${s.port}`,R=await ua(e,r,i,`https://${k}${c}`,b.signal,s.onFilterRequestDeny);if(R===null)return;if(u=R,r.destroyed&&!r.readableEnded||i.destroyed||r.socket.destroyed||u.destroyed){u.destroy();return}}let d=Kr(r.headers);delete d.host;let p=l?.(d,s.hostname),h=a?.(r.method??"GET",c,d,s.hostname);t?.(d,s.hostname);let f=da(n,r,d,s.hostname),v;if(h?.action==="deny"){if(Di(i,h.reason),u.destroy(),u!==r)Bf(r,i);return}if(h?.action==="resign"){let b=h.payloadHash;if(b===void 0){let I=f?u.pipe(f):u;if(f)u.on("error",(V)=>f.destroy(V));try{v=await ax(I,o)}catch(V){if(V instanceof Dl){Di(i,`AWS SigV4 request uses a masked credential and signs a literal body hash, so the proxy must buffer the body to re-sign it, but the body exceeds the ${o}-byte buffering limit; denied. Sign the payload as UNSIGNED-PAYLOAD to stream it without buffering, or use an unmasked credential to have the request forwarded untouched.`),I.resume();return}w(`[tls-terminate] failed to buffer body for SigV4 re-sign: ${V.message}`,{level:"error"}),i.destroy();return}b=Bl(v),d["content-length"]=String(v.length)}let k=Nl(s.hostname)===6?`[${s.hostname}]`:s.hostname,R=s.port===443?k:`${k}:${s.port}`;try{h.apply(d,R,b)}catch(I){if(Di(i,`AWS SigV4 re-signing failed: ${I.message}`),u.destroy(),u!==r)Bf(r,i);return}}if(Boolean(r.headers["content-length"]||r.headers["transfer-encoding"])&&v===void 0&&d["content-length"]===void 0&&d["transfer-encoding"]===void 0)d["transfer-encoding"]="chunked";if(p){let b=Nl(s.hostname)===6?`[${s.hostname}]`:s.hostname;d[kf]=`https://${s.port===443?b:`${b}:${s.port}`}${c}`,d[If]=p.token}let S=p?p.url.hostname:s.hostname,A=Jv({host:S,port:p?Number(p.url.port||443):s.port,path:p?`${p.url.pathname}${p.url.search}`:c,method:r.method,headers:d,...Nl(S)?{}:{servername:S},...s.upstreamCA?{ca:s.upstreamCA}:{},agent:!1},(b)=>{b.on("error",(k)=>{w(`[tls-terminate] upstream response error: ${k.message}`,{level:"error"}),i.destroy()}),i.writeHead(b.statusCode??502,Kr(b.headers)),b.pipe(i)});if(A.on("error",(b)=>{if(w(`[tls-terminate] upstream ${s.hostname}:${s.port} failed: ${b.message}`,{level:"error"}),!i.headersSent)i.writeHead(502,{"Content-Type":"text/plain"}),i.end("Bad Gateway");else i.destroy()}),i.on("close",()=>A.destroy()),v!==void 0)A.end(v);else if(f)f.on("error",(b)=>A.destroy(b)),u.on("error",(b)=>f.destroy(b)),i.on("close",()=>f.destroy()),u.pipe(f).pipe(A);else u.on("error",(b)=>A.destroy(b)),u.pipe(A)}function ax(e,t){return new Promise((n,r)=>{let i=[],s=0,a=(o)=>{if(s+=o.length,s>t){i.length=0,e.removeListener("data",a),r(new Dl(`request body exceeds ${t} bytes`));return}i.push(o)};e.on("data",a),e.once("end",()=>n(Buffer.concat(i))),e.once("error",r)})}function ox(e){let t=e??"/";if(t.startsWith("/"))return t;try{let n=new URL(t);return`${n.pathname}${n.search}`||"/"}catch{return t}}var lx=0;function cx(){return rx(tx(),`srt-tt-${process.pid}-${(lx++).toString(36)}.sock`)}function px(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||!bs(r.slice(i+1),t))return{ok:!1};return{ok:!0,encodedCommand:As(r.slice(0,i))}}function Vf(e){let t=dx();t.on("clientError",(r,i)=>{if(w(`Client connection error: ${r.message}`,{level:"error"}),i.on("error",()=>{}),r.code!=="ECONNRESET"&&i.writable){let s=r.code==="HPE_HEADER_OVERFLOW"?"431 Request Header Fields Too Large":"400 Bad Request";i.end(`HTTP/1.1 ${s}\r
40
+ `)}function jv(e,t,n){return[Ui,t,`${n.date}/${n.region}/${n.service}/aws4_request`,Bl(e)].join(`
41
+ `)}function zv(e,t){let n=ga(`AWS4${e}`,t.date),r=ga(n,t.region),i=ga(r,t.service);return ga(i,"aws4_request")}function _f(e){let t=Gv(e),n=jv(t,e.amzDate,e.scope),r=Ef("sha256",zv(e.secretAccessKey,e.scope)).update(n,"utf8").digest("hex"),i=[...e.signedHeaders].map((a)=>a.toLowerCase()).sort(),s=`${e.scope.date}/${e.scope.region}/${e.scope.service}/aws4_request`;return{authorization:`${Ui} Credential=${e.accessKeyId}/${s}, SignedHeaders=${i.join(";")}, Signature=${r}`,signature:r,canonicalRequest:t,stringToSign:n}}function Bl(e){return Wv("sha256").update(e).digest("hex")}function ga(e,t){return Ef("sha256",e).update(t,"utf8").digest()}function qn(e){return Array.isArray(e)?e[0]:e}var kf="reason-egress-target",If="reason-egress-token";class Pl{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((s)=>s.includes(n.placeholder)||Xv(s,n.placeholder)))return{url:new URL(n.url),token:n.token}}return}}function Xv(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 Pf=67108864;class Dl extends Error{}function Rf(e){return e.length>=3&&e[0]===22&&e[1]===3&&e[2]<=3}function Nf(e,t){if(t.length>=3)return Promise.resolve({isTLS:Rf(t),head:t});return new Promise((n)=>{let r=t,i=()=>{e.removeListener("data",s),e.removeListener("close",i),n({isTLS:Rf(r),head:r})},s=(a)=>{if(e.pause(),r=r.length?Buffer.concat([r,a]):a,r.length>=3)return i();e.resume()};e.on("data",s),e.once("close",i)})}function rx(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 Df(e,t,n,r,i,s,a,o,l=Pf,c){let u=El(e,a.hostname),d=Qv({ALPNProtocols:["http/1.1"],cert:u.certPem,key:u.keyPem,SNICallback:(f,v)=>{try{v(null,yf(e,f||a.hostname))}catch(x){v(x)}}});d.on("request",(f,v)=>{f.on("error",(x)=>{w(`[tls-terminate] client request error: ${x.message}`,{level:"error"})}),v.on("error",(x)=>{w(`[tls-terminate] client response error: ${x.message}`,{level:"error"})}),nx(t,n,r,f,v,a,o,l,c)}),d.on("clientError",(f,v)=>{w(`[tls-terminate] client connection error for ${a.hostname}: ${f.message}`,{level:"error"}),v.destroy()}),d.on("tlsClientError",(f,v)=>{w(`[tls-terminate] client TLS error for ${a.hostname}: ${f.message}`,{level:"error"}),v.destroy()}),d.on("upgrade",(f,v)=>{w("[tls-terminate] upgrade request refused",{level:"warn"}),v.destroy()});let p=lx(),h=()=>{d.close(),Zv(p,()=>{})};d.on("error",(f)=>{w(`[tls-terminate] inner server listen failed: ${f.message}`,{level:"error"}),i.destroy(),h()}),d.listen(p,()=>{let f=Jv({path:p});f.on("error",(v)=>{w(`[tls-terminate] inner loopback failed: ${v.message}`,{level:"error"}),i.destroy(),h()}),f.once("connect",()=>{if(s.length)f.write(s);rx(i,f),f.pipe(i)}),i.on("error",()=>f.destroy()),i.once("close",()=>{f.destroy(),h()}),f.once("close",()=>i.destroy())}),d.unref()}function Bf(e,t){if(t.writableFinished||t.destroyed){e.destroy();return}t.once("finish",()=>e.destroy()),t.once("close",()=>e.destroy())}function nx(...e){ix(...e).catch((t)=>{w(`[tls-terminate] forwardUpstream failed: ${t.message}`,{level:"error"})})}async function ix(e,t,n,r,i,s,a,o=Pf,l){let c=ax(r.url),u=r;if(e){let b=new AbortController;i.once("close",()=>b.abort());let k=s.port===443?s.hostname:`${s.hostname}:${s.port}`,R=await ua(e,r,i,`https://${k}${c}`,b.signal,s.onFilterRequestDeny);if(R===null)return;if(u=R,r.destroyed&&!r.readableEnded||i.destroyed||r.socket.destroyed||u.destroyed){u.destroy();return}}let d=Kr(r.headers);delete d.host;let p=l?.(d,s.hostname),h=a?.(r.method??"GET",c,d,s.hostname);t?.(d,s.hostname);let f=da(n,r,d,s.hostname),v;if(h?.action==="deny"){if(Di(i,h.reason),u.destroy(),u!==r)Bf(r,i);return}if(h?.action==="resign"){let b=h.payloadHash;if(b===void 0){let I=f?u.pipe(f):u;if(f)u.on("error",(V)=>f.destroy(V));try{v=await sx(I,o)}catch(V){if(V instanceof Dl){Di(i,`AWS SigV4 request uses a masked credential and signs a literal body hash, so the proxy must buffer the body to re-sign it, but the body exceeds the ${o}-byte buffering limit; denied. Sign the payload as UNSIGNED-PAYLOAD to stream it without buffering, or use an unmasked credential to have the request forwarded untouched.`),I.resume();return}w(`[tls-terminate] failed to buffer body for SigV4 re-sign: ${V.message}`,{level:"error"}),i.destroy();return}b=Bl(v),d["content-length"]=String(v.length)}let k=Nl(s.hostname)===6?`[${s.hostname}]`:s.hostname,R=s.port===443?k:`${k}:${s.port}`;try{h.apply(d,R,b)}catch(I){if(Di(i,`AWS SigV4 re-signing failed: ${I.message}`),u.destroy(),u!==r)Bf(r,i);return}}if(Boolean(r.headers["content-length"]||r.headers["transfer-encoding"])&&v===void 0&&d["content-length"]===void 0&&d["transfer-encoding"]===void 0)d["transfer-encoding"]="chunked";if(p){let b=Nl(s.hostname)===6?`[${s.hostname}]`:s.hostname;d[kf]=`https://${s.port===443?b:`${b}:${s.port}`}${c}`,d[If]=p.token}let S=p?p.url.hostname:s.hostname,A=Yv({host:S,port:p?Number(p.url.port||443):s.port,path:p?`${p.url.pathname}${p.url.search}`:c,method:r.method,headers:d,...Nl(S)?{}:{servername:S},...s.upstreamCA?{ca:s.upstreamCA}:{},agent:!1},(b)=>{b.on("error",(k)=>{w(`[tls-terminate] upstream response error: ${k.message}`,{level:"error"}),i.destroy()}),i.writeHead(b.statusCode??502,Kr(b.headers)),b.pipe(i)});if(A.on("error",(b)=>{if(w(`[tls-terminate] upstream ${s.hostname}:${s.port} failed: ${b.message}`,{level:"error"}),!i.headersSent)i.writeHead(502,{"Content-Type":"text/plain"}),i.end("Bad Gateway");else i.destroy()}),i.on("close",()=>A.destroy()),v!==void 0)A.end(v);else if(f)f.on("error",(b)=>A.destroy(b)),u.on("error",(b)=>f.destroy(b)),i.on("close",()=>f.destroy()),u.pipe(f).pipe(A);else u.on("error",(b)=>A.destroy(b)),u.pipe(A)}function sx(e,t){return new Promise((n,r)=>{let i=[],s=0,a=(o)=>{if(s+=o.length,s>t){i.length=0,e.removeListener("data",a),r(new Dl(`request body exceeds ${t} bytes`));return}i.push(o)};e.on("data",a),e.once("end",()=>n(Buffer.concat(i))),e.once("error",r)})}function ax(e){let t=e??"/";if(t.startsWith("/"))return t;try{let n=new URL(t);return`${n.pathname}${n.search}`||"/"}catch{return t}}var ox=0;function lx(){return tx(ex(),`srt-tt-${process.pid}-${(ox++).toString(36)}.sock`)}function fx(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||!bs(r.slice(i+1),t))return{ok:!1};return{ok:!0,encodedCommand:As(r.slice(0,i))}}function Vf(e){let t=ux();t.on("clientError",(r,i)=>{if(w(`Client connection error: ${r.message}`,{level:"error"}),i.on("error",()=>{}),r.code!=="ECONNRESET"&&i.writable){let s=r.code==="HPE_HEADER_OVERFLOW"?"431 Request Header Fields Too Large":"400 Bad Request";i.end(`HTTP/1.1 ${s}\r
42
42
  \r
43
- `,()=>i.destroy()),setTimeout(()=>i.destroy(),1000).unref?.();return}i.destroy()});let n=(r)=>px(r,e.proxyAuthToken);return t.on("connect",async(r,i,s)=>{i.on("error",(S)=>{w(`Client socket error: ${S.message}`,{level:"error"}),i.destroy()});let a=!1;i.once("close",()=>{a=!0});let o=()=>{a=!0,i.destroy()},l=65536,c=0,u=!1,d=[],p=(S)=>{if(!u)return;if(c+=S.length,c>l){w("CONNECT client exceeded pre-establishment capture cap; destroying",{level:"error"}),o();return}d.push(S)};if(!e.mitmCA)u=!0,i.on("data",p);if(i.readableEnded)o();else i.once("end",o);let h=()=>{if(u=!1,d.length)s=Buffer.concat([s,...d]),d.length=0},f=()=>{i.removeListener("end",o),h()},v=(S)=>{if(a||i.destroyed||i.readableEnded||!i.writable){w("CONNECT client gone before status write; dropping verdict and destroying socket"),i.destroy();return}f(),i.end(S)};if(a||i.destroyed)return;let x=!1;try{let S=n(r.headers["proxy-authorization"]);if(!S.ok){v(`HTTP/1.1 407 Proxy Authentication Required\r
43
+ `,()=>i.destroy()),setTimeout(()=>i.destroy(),1000).unref?.();return}i.destroy()});let n=(r)=>fx(r,e.proxyAuthToken);return t.on("connect",async(r,i,s)=>{i.on("error",(S)=>{w(`Client socket error: ${S.message}`,{level:"error"}),i.destroy()});let a=!1;i.once("close",()=>{a=!0});let o=()=>{a=!0,i.destroy()},l=65536,c=0,u=!1,d=[],p=(S)=>{if(!u)return;if(c+=S.length,c>l){w("CONNECT client exceeded pre-establishment capture cap; destroying",{level:"error"}),o();return}d.push(S)};if(!e.mitmCA)u=!0,i.on("data",p);if(i.readableEnded)o();else i.once("end",o);let h=()=>{if(u=!1,d.length)s=Buffer.concat([s,...d]),d.length=0},f=()=>{i.removeListener("end",o),h()},v=(S)=>{if(a||i.destroyed||i.readableEnded||!i.writable){w("CONNECT client gone before status write; dropping verdict and destroying socket"),i.destroy();return}f(),i.end(S)};if(a||i.destroyed)return;let x=!1;try{let S=n(r.headers["proxy-authorization"]);if(!S.ok){v(`HTTP/1.1 407 Proxy Authentication Required\r
44
44
  Proxy-Authenticate: Basic realm="srt"\r
45
45
  \r
46
- `);return}let A=hx(r.url);if(!A){w(`Invalid CONNECT request: ${r.url}`,{level:"error"}),v(`HTTP/1.1 400 Bad Request\r
46
+ `);return}let A=px(r.url);if(!A){w(`Invalid CONNECT request: ${r.url}`,{level:"error"}),v(`HTTP/1.1 400 Bad Request\r
47
47
  \r
48
48
  `);return}let{hostname:b,port:k}=A;if(!await e.filter(k,b,i,S.encodedCommand)){w(`Connection blocked to ${b}:${k}`,{level:"error"}),v(`HTTP/1.1 403 Forbidden\r
49
49
  Content-Type: text/plain\r
@@ -51,7 +51,7 @@ X-Proxy-Error: blocked-by-allowlist\r
51
51
  \r
52
52
  Connection blocked by network allowlist`);return}if(a||i.destroyed){i.destroy();return}let I=vt(b)??b;if(e.mitmCA&&(e.shouldTerminateTLS?.(I,k)??!0)){i.write(`HTTP/1.1 200 Connection Established\r
53
53
  \r
54
- `),x=!0;let W=await Nf(i,s);if(a||i.destroyed){i.destroy();return}if(W.isTLS){f(),Df(e.mitmCA,e.filterRequest,e.mutateHeaders,e.getBodySubstitutions,i,W.head,{hostname:I,port:k,upstreamCA:e.tlsTerminateUpstreamCA,onFilterRequestDeny:e.onFilterRequestDenied?(Z,pe,ge)=>e.onFilterRequestDenied({method:Z,url:pe,reason:ge,encodedCommand:S.encodedCommand}):void 0},e.planSigv4,e.maxSigv4ResignBodyBytes,e.getBrokerForward);return}w(`[tls-terminate] non-TLS bytes on CONNECT ${I}:${k}; opaque-tunnelling`),s=W.head}else if(e.mitmCA)w(`[tls-terminate] policy exempts ${I}:${k}; opaque-tunnelling`);let V=e.getMitmSocketPath?.(I),J=!V&&e.parentProxy&&!Li(e.parentProxy,I)?Oi(e.parentProxy,{isHttps:!0}):void 0,D;try{if(V)w(`Routing CONNECT ${I}:${k} through MITM proxy at ${V}`),D=await _l({dial:()=>fx({path:V}),readyEvent:"connect",destHost:I,destPort:k});else if(J)D=await pa(J,I,k);else D=await ha(I,k,void 0,e.publicOnly?.(I,k)??!1)}catch(W){if(w(`CONNECT tunnel failed: ${W.message}`,{level:"error"}),x)i.destroy();else if(W instanceof Hn)v(`HTTP/1.1 403 Forbidden\r
54
+ `),x=!0;let W=await Nf(i,s);if(a||i.destroyed){i.destroy();return}if(W.isTLS){f(),Df(e.mitmCA,e.filterRequest,e.mutateHeaders,e.getBodySubstitutions,i,W.head,{hostname:I,port:k,upstreamCA:e.tlsTerminateUpstreamCA,onFilterRequestDeny:e.onFilterRequestDenied?(Z,pe,ge)=>e.onFilterRequestDenied({method:Z,url:pe,reason:ge,encodedCommand:S.encodedCommand}):void 0},e.planSigv4,e.maxSigv4ResignBodyBytes,e.getBrokerForward);return}w(`[tls-terminate] non-TLS bytes on CONNECT ${I}:${k}; opaque-tunnelling`),s=W.head}else if(e.mitmCA)w(`[tls-terminate] policy exempts ${I}:${k}; opaque-tunnelling`);let V=e.getMitmSocketPath?.(I),J=!V&&e.parentProxy&&!Li(e.parentProxy,I)?Oi(e.parentProxy,{isHttps:!0}):void 0,D;try{if(V)w(`Routing CONNECT ${I}:${k} through MITM proxy at ${V}`),D=await _l({dial:()=>dx({path:V}),readyEvent:"connect",destHost:I,destPort:k});else if(J)D=await pa(J,I,k);else D=await ha(I,k,void 0,e.publicOnly?.(I,k)??!1)}catch(W){if(w(`CONNECT tunnel failed: ${W.message}`,{level:"error"}),x)i.destroy();else if(W instanceof Hn)v(`HTTP/1.1 403 Forbidden\r
55
55
  Content-Type: text/plain\r
56
56
  X-Proxy-Error: blocked-by-allowlist\r
57
57
  \r
@@ -63,24 +63,24 @@ ${I}:${k} could not be reached (the network allowlist allowed it): ${Z}`)}return
63
63
  \r
64
64
  `);if(f(),i.allowHalfOpen=!0,s.length)D.write(s);D.pipe(i),i.pipe(D),D.on("error",(W)=>{w(`CONNECT tunnel failed: ${W.message}`,{level:"error"}),i.destroy()}),i.on("close",()=>D.destroy()),D.on("close",()=>i.destroy())}catch(S){if(w(`Error handling CONNECT: ${S}`,{level:"error"}),x)i.destroy();else v(`HTTP/1.1 500 Internal Server Error\r
65
65
  \r
66
- `)}}),t.on("request",async(r,i)=>{r.on("error",(s)=>{w(`Client request error: ${s.message}`,{level:"error"})}),i.on("error",(s)=>{w(`Client response error: ${s.message}`,{level:"error"}),i.socket?.destroy()});try{if(e.mitmCA&&r.method==="GET"&&new Uf(r.url??"","http://x").pathname===aa){i.writeHead(200,{"Content-Type":"application/pkix-crl","Content-Length":e.mitmCA.crlDer.length}),i.end(e.mitmCA.crlDer);return}let s=n(r.headers["proxy-authorization"]);if(!s.ok){i.writeHead(407,{"Proxy-Authenticate":'Basic realm="srt"'}),i.end();return}let a=new Uf(r.url),o=Xt(a.hostname),l=a.port?parseInt(a.port,10):a.protocol==="https:"?443:80;if(!await e.filter(l,o,r.socket,s.encodedCommand)){if(w(`HTTP request blocked to ${o}:${l}`,{level:"error"}),r.socket.destroyed||i.destroyed){i.destroy();return}i.writeHead(403,{"Content-Type":"text/plain","X-Proxy-Error":"blocked-by-allowlist"}),i.end("Connection blocked by network allowlist");return}if(r.socket.destroyed)return;let u=vt(o)??o,d=(Of(u)===6?`[${u}]`:u)+(a.port?`:${a.port}`:""),p={...Kr(r.headers),host:d};e.mutateHeadersPlaintext?.(p,u);let h=da(e.getBodySubstitutionsPlaintext,r,p,u),f=e.getMitmSocketPath?.(u),v=!f&&e.parentProxy&&!Li(e.parentProxy,u)?Oi(e.parentProxy,{isHttps:a.protocol==="https:"}):void 0,x=`${a.protocol}//${d}${a.pathname}${a.search}`,S=r;if(e.filterRequest){let k=new AbortController;i.once("close",()=>k.abort());let R=await ua(e.filterRequest,r,i,x,k.signal,e.onFilterRequestDenied?(I,V,J)=>e.onFilterRequestDenied({method:I,url:V,reason:J,encodedCommand:s.encodedCommand}):void 0);if(R===null)return;if(S=R,r.destroyed&&!r.readableEnded||i.destroyed||r.socket.destroyed||S.destroyed){S.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 b;if(f){w(`Routing HTTP ${r.method} ${u}:${l} through MITM proxy at ${f}`);let k=new ux({socketPath:f});b=Ll({agent:k,path:x,method:r.method,headers:p},(R)=>{R.on("error",(I)=>{w(`Upstream response error: ${I.message}`,{level:"error"}),i.destroy()}),i.writeHead(R.statusCode,Kr(R.headers)),R.pipe(i)})}else if(v){let k=Xt(v.hostname),R=Number(v.port)||(v.protocol==="https:"?443:80),I=kl(v);b=(v.protocol==="https:"?Lf:Ll)({hostname:k,port:R,path:x,method:r.method,headers:I?{...p,"proxy-authorization":I}:p},(J)=>{J.on("error",(D)=>{w(`Upstream response error: ${D.message}`,{level:"error"}),i.destroy()}),i.writeHead(J.statusCode,Kr(J.headers)),J.pipe(i)})}else{let k=a.protocol==="https:"?Lf:Ll,R=u;if(e.publicOnly?.(u,l))try{R=await ca(u)}catch(I){w(`Open egress refused ${u}:${l}: ${I.message}`,{level:"error"}),i.writeHead(403,{"Content-Type":"text/plain","X-Proxy-Error":"blocked-by-allowlist"}),i.end("Connection blocked: destination is not on the public internet");return}b=k({hostname:R,...R!==u&&a.protocol==="https:"&&!Of(u)?{servername:u}:{},port:l,path:a.pathname+a.search,method:r.method,headers:p},(I)=>{I.on("error",(V)=>{w(`Upstream response error: ${V.message}`,{level:"error"}),i.destroy()}),i.writeHead(I.statusCode,Kr(I.headers)),I.pipe(i)})}if(b.on("error",(k)=>{if(w(`Proxy request failed: ${k.message}`,{level:"error"}),!i.headersSent)i.writeHead(502,{"Content-Type":"text/plain"}),i.end("Bad Gateway");else i.destroy()}),i.on("close",()=>b.destroy()),h)h.on("error",(k)=>b.destroy(k)),S.on("error",(k)=>h.destroy(k)),i.on("close",()=>h.destroy()),S.pipe(h).pipe(b);else S.on("error",(k)=>b.destroy(k)),S.pipe(b)}catch(s){if(w(`Error handling HTTP request: ${s}`,{level:"error"}),!i.headersSent)i.writeHead(500,{"Content-Type":"text/plain"}),i.end("Internal Server Error");else i.destroy()}}),t}function hx(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 Gf=no(qf(),1);function Ax(e,t,n){if(!n||t===void 0)return!1;return e!==void 0&&(e===yr||e.startsWith(`${yr}.`))&&bs(t,n)}function jf(e){let t=Gf.createServer();if(e.proxyAuthToken)t.setAuthHandler((r,i,s)=>{if(Ax(r.username,r.password,e.proxyAuthToken))i();else w("SOCKS auth rejected",{level:"error"}),s()});t.setRulesetValidator(async(r)=>{try{let{destAddress:i,destPort:s}=r;if(!Kn(i))return w(`Rejecting malformed SOCKS host: ${JSON.stringify(i)}`,{level:"error"}),!1;if(w(`Connection request to ${i}:${s}`),!await e.filter(s,i,As(r.username)))return w(`Connection blocked to ${i}:${s}`,{level:"error"}),!1;return w(`Connection allowed to ${i}:${s}`),!0}catch(i){return w(`Error validating connection: ${i}`,{level:"error"}),!1}}),t.setConnectionHandler((r,i)=>{let s=vt(r.destAddress)??r.destAddress,a=r.destPort,o=!1,l;r.socket.once("close",()=>{o=!0,l?.destroy()}),r.socket.on("error",()=>l?.destroy());let c=e.parentProxy&&!Li(e.parentProxy,s)?Oi(e.parentProxy,{isHttps:!0}):void 0;(c?pa(c,s,a):ha(s,a,void 0,e.publicOnly?.(s,a)??!1)).then((d)=>{if(l=d,d.on("error",()=>r.socket.destroy()),o){d.destroy();return}i("REQUEST_GRANTED"),d.pipe(r.socket),r.socket.pipe(d),d.on("close",()=>r.socket.destroy())}).catch((d)=>{if(w(`SOCKS connect to ${s}:${a} failed: ${d.message}`,{level:"error"}),!o)try{i("HOST_UNREACHABLE")}catch{}})});let n=new Set;return{handleConnection(r){if(r.setNoDelay(),n.add(r),r.once("close",()=>n.delete(r)),!e.proxyAuthToken){t._handleConnection(r);return}Ix(r,(i)=>{if(i){t._handleConnection(r);return}Rx(r,e).catch(()=>r.destroy())})},async close(){for(let r of n)r.destroy();n.clear()}}}var _x=0,kx=2;function Ix(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 s=n[1];if(n.length<2+s)return;e.off("data",r),e.pause();let o=n.subarray(2,2+s).includes(kx),l=o?n:n.subarray(2+s);if(l.length>0)e.unshift(l);t(o)};e.on("data",r),e.once("error",()=>e.off("data",r))}async function Rx(e,t){e.write(Buffer.from([5,_x]));let n=await Bx(e);if(n===void 0){e.destroy();return}let{host:r,port:i}=n;if(!Kn(r)){e.end(Vl(2));return}let s=t.probeUnauthenticated?await t.probeUnauthenticated(i,r):{};if(w(`SOCKS unauthenticated client refused for ${r}:${i}`+(s.deniedReason!==void 0?" (denied by policy)":"")),i!==22){e.end(Vl(2));return}let a=s.deniedReason??"This proxy requires authentication, and this client did not offer an authentication method, so the connection was refused.";e.write(Vl(0)),e.write(Buffer.from(`SSH-2.0-policy_refusal\r
67
- `)),e.end(Px(a))}function Vl(e){return Buffer.from([5,e,0,1,0,0,0,0,0,0])}function Bx(e){return new Promise((t)=>{let n=Buffer.alloc(0),r=(a)=>{e.off("data",s),clearTimeout(i),t(a)},i=setTimeout(()=>r(void 0),5000),s=(a)=>{if(n=Buffer.concat([n,a]),n.length<4)return;if(n[0]!==5||n[1]!==1){r(void 0);return}let o=n[3];if(o===1){if(n.length<10)return;let l=Array.from(n.subarray(4,8)).join(".");r({host:l,port:n.readUInt16BE(8)})}else if(o===3){if(n.length<5)return;let l=n[4];if(n.length<5+l+2)return;r({host:n.subarray(5,5+l).toString("utf8"),port:n.readUInt16BE(5+l)})}else if(o===4){if(n.length<22)return;let l=[];for(let c=0;c<16;c+=2)l.push(n.readUInt16BE(4+c).toString(16));r({host:l.join(":"),port:n.readUInt16BE(20)})}else r(void 0)};e.on("data",s),e.resume(),e.once("error",()=>r(void 0)),e.once("close",()=>r(void 0))})}function Px(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]),va(1),va(n.length),n,va(r.length),r]),s=8-(5+i.length)%8;if(s<4)s+=8;return Buffer.concat([va(1+i.length+s),Buffer.from([s]),i,Buffer.alloc(s)])}function va(e){let t=Buffer.alloc(4);return t.writeUInt32BE(e,0),t}import{createServer as Nx,connect as zf}from"net";import{join as Dx}from"path";import{tmpdir as Lx}from"os";import{unlink as Xf}from"fs/promises";function xa(e,t,n,r){return new Promise((i,s)=>{let[a,o]=n??[0,0],l=a,c=()=>{while(r.has(l)&&l<=o)l++;if(l>o){s(Error(`No free port in range ${a}-${o} (excluding ${[...r].join(",")})`));return}let u=()=>{e.removeListener("error",d),i()},d=(p)=>{if(e.removeListener("listening",u),n&&p?.code==="EADDRINUSE"&&l<o){l++,c();return}s(p??Error("listen error"))};e.once("error",d),e.once("listening",u),t(n?l:0)};c()})}var Ox=new Set([4,5]),Ux=1e4,Vx=0;function Fx(){return Dx(Lx(),`srt-mux-${process.pid}-${(Vx++).toString(36)}.sock`)}function Qf(e){let t=e.firstByteTimeoutMs??Ux,n=Ne()==="windows",r,i,s=new Set;function a(l){if(r===void 0&&i===void 0){w("mux: HTTP dispatch before backend bound; dropping",{level:"error"}),l.destroy();return}let c=r?zf(r):zf(i,"127.0.0.1");c.on("error",(u)=>{let d=u.code??"ERR";if(w(`mux: HTTP backend dial failed: ${u.message}`,{level:"error"}),!l.destroyed)l.end(`HTTP/1.1 502 Bad Gateway\r
66
+ `)}}),t.on("request",async(r,i)=>{r.on("error",(s)=>{w(`Client request error: ${s.message}`,{level:"error"})}),i.on("error",(s)=>{w(`Client response error: ${s.message}`,{level:"error"}),i.socket?.destroy()});try{if(e.mitmCA&&r.method==="GET"&&new Uf(r.url??"","http://x").pathname===aa){i.writeHead(200,{"Content-Type":"application/pkix-crl","Content-Length":e.mitmCA.crlDer.length}),i.end(e.mitmCA.crlDer);return}let s=n(r.headers["proxy-authorization"]);if(!s.ok){i.writeHead(407,{"Proxy-Authenticate":'Basic realm="srt"'}),i.end();return}let a=new Uf(r.url),o=Xt(a.hostname),l=a.port?parseInt(a.port,10):a.protocol==="https:"?443:80;if(!await e.filter(l,o,r.socket,s.encodedCommand)){if(w(`HTTP request blocked to ${o}:${l}`,{level:"error"}),r.socket.destroyed||i.destroyed){i.destroy();return}i.writeHead(403,{"Content-Type":"text/plain","X-Proxy-Error":"blocked-by-allowlist"}),i.end("Connection blocked by network allowlist");return}if(r.socket.destroyed)return;let u=vt(o)??o,d=(Of(u)===6?`[${u}]`:u)+(a.port?`:${a.port}`:""),p={...Kr(r.headers),host:d};e.mutateHeadersPlaintext?.(p,u);let h=da(e.getBodySubstitutionsPlaintext,r,p,u),f=e.getMitmSocketPath?.(u),v=!f&&e.parentProxy&&!Li(e.parentProxy,u)?Oi(e.parentProxy,{isHttps:a.protocol==="https:"}):void 0,x=`${a.protocol}//${d}${a.pathname}${a.search}`,S=r;if(e.filterRequest){let k=new AbortController;i.once("close",()=>k.abort());let R=await ua(e.filterRequest,r,i,x,k.signal,e.onFilterRequestDenied?(I,V,J)=>e.onFilterRequestDenied({method:I,url:V,reason:J,encodedCommand:s.encodedCommand}):void 0);if(R===null)return;if(S=R,r.destroyed&&!r.readableEnded||i.destroyed||r.socket.destroyed||S.destroyed){S.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 b;if(f){w(`Routing HTTP ${r.method} ${u}:${l} through MITM proxy at ${f}`);let k=new cx({socketPath:f});b=Ll({agent:k,path:x,method:r.method,headers:p},(R)=>{R.on("error",(I)=>{w(`Upstream response error: ${I.message}`,{level:"error"}),i.destroy()}),i.writeHead(R.statusCode,Kr(R.headers)),R.pipe(i)})}else if(v){let k=Xt(v.hostname),R=Number(v.port)||(v.protocol==="https:"?443:80),I=kl(v);b=(v.protocol==="https:"?Lf:Ll)({hostname:k,port:R,path:x,method:r.method,headers:I?{...p,"proxy-authorization":I}:p},(J)=>{J.on("error",(D)=>{w(`Upstream response error: ${D.message}`,{level:"error"}),i.destroy()}),i.writeHead(J.statusCode,Kr(J.headers)),J.pipe(i)})}else{let k=a.protocol==="https:"?Lf:Ll,R=u;if(e.publicOnly?.(u,l))try{R=await ca(u)}catch(I){w(`Open egress refused ${u}:${l}: ${I.message}`,{level:"error"}),i.writeHead(403,{"Content-Type":"text/plain","X-Proxy-Error":"blocked-by-allowlist"}),i.end("Connection blocked: destination is not on the public internet");return}b=k({hostname:R,...R!==u&&a.protocol==="https:"&&!Of(u)?{servername:u}:{},port:l,path:a.pathname+a.search,method:r.method,headers:p},(I)=>{I.on("error",(V)=>{w(`Upstream response error: ${V.message}`,{level:"error"}),i.destroy()}),i.writeHead(I.statusCode,Kr(I.headers)),I.pipe(i)})}if(b.on("error",(k)=>{if(w(`Proxy request failed: ${k.message}`,{level:"error"}),!i.headersSent)i.writeHead(502,{"Content-Type":"text/plain"}),i.end("Bad Gateway");else i.destroy()}),i.on("close",()=>b.destroy()),h)h.on("error",(k)=>b.destroy(k)),S.on("error",(k)=>h.destroy(k)),i.on("close",()=>h.destroy()),S.pipe(h).pipe(b);else S.on("error",(k)=>b.destroy(k)),S.pipe(b)}catch(s){if(w(`Error handling HTTP request: ${s}`,{level:"error"}),!i.headersSent)i.writeHead(500,{"Content-Type":"text/plain"}),i.end("Internal Server Error");else i.destroy()}}),t}function px(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 Gf=no(qf(),1);function Tx(e,t,n){if(!n||t===void 0)return!1;return e!==void 0&&(e===yr||e.startsWith(`${yr}.`))&&bs(t,n)}function jf(e){let t=Gf.createServer();if(e.proxyAuthToken)t.setAuthHandler((r,i,s)=>{if(Tx(r.username,r.password,e.proxyAuthToken))i();else w("SOCKS auth rejected",{level:"error"}),s()});t.setRulesetValidator(async(r)=>{try{let{destAddress:i,destPort:s}=r;if(!Kn(i))return w(`Rejecting malformed SOCKS host: ${JSON.stringify(i)}`,{level:"error"}),!1;if(w(`Connection request to ${i}:${s}`),!await e.filter(s,i,As(r.username)))return w(`Connection blocked to ${i}:${s}`,{level:"error"}),!1;return w(`Connection allowed to ${i}:${s}`),!0}catch(i){return w(`Error validating connection: ${i}`,{level:"error"}),!1}}),t.setConnectionHandler((r,i)=>{let s=vt(r.destAddress)??r.destAddress,a=r.destPort,o=!1,l;r.socket.once("close",()=>{o=!0,l?.destroy()}),r.socket.on("error",()=>l?.destroy());let c=e.parentProxy&&!Li(e.parentProxy,s)?Oi(e.parentProxy,{isHttps:!0}):void 0;(c?pa(c,s,a):ha(s,a,void 0,e.publicOnly?.(s,a)??!1)).then((d)=>{if(l=d,d.on("error",()=>r.socket.destroy()),o){d.destroy();return}i("REQUEST_GRANTED"),d.pipe(r.socket),r.socket.pipe(d),d.on("close",()=>r.socket.destroy())}).catch((d)=>{if(w(`SOCKS connect to ${s}:${a} failed: ${d.message}`,{level:"error"}),!o)try{i("HOST_UNREACHABLE")}catch{}})});let n=new Set;return{handleConnection(r){if(r.setNoDelay(),n.add(r),r.once("close",()=>n.delete(r)),!e.proxyAuthToken){t._handleConnection(r);return}kx(r,(i)=>{if(i){t._handleConnection(r);return}Ix(r,e).catch(()=>r.destroy())})},async close(){for(let r of n)r.destroy();n.clear()}}}var Ax=0,_x=2;function kx(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 s=n[1];if(n.length<2+s)return;e.off("data",r),e.pause();let o=n.subarray(2,2+s).includes(_x),l=o?n:n.subarray(2+s);if(l.length>0)e.unshift(l);t(o)};e.on("data",r),e.once("error",()=>e.off("data",r))}async function Ix(e,t){e.write(Buffer.from([5,Ax]));let n=await Rx(e);if(n===void 0){e.destroy();return}let{host:r,port:i}=n;if(!Kn(r)){e.end(Vl(2));return}let s=t.probeUnauthenticated?await t.probeUnauthenticated(i,r):{};if(w(`SOCKS unauthenticated client refused for ${r}:${i}`+(s.deniedReason!==void 0?" (denied by policy)":"")),i!==22){e.end(Vl(2));return}let a=s.deniedReason??"This proxy requires authentication, and this client did not offer an authentication method, so the connection was refused.";e.write(Vl(0)),e.write(Buffer.from(`SSH-2.0-policy_refusal\r
67
+ `)),e.end(Bx(a))}function Vl(e){return Buffer.from([5,e,0,1,0,0,0,0,0,0])}function Rx(e){return new Promise((t)=>{let n=Buffer.alloc(0),r=(a)=>{e.off("data",s),clearTimeout(i),t(a)},i=setTimeout(()=>r(void 0),5000),s=(a)=>{if(n=Buffer.concat([n,a]),n.length<4)return;if(n[0]!==5||n[1]!==1){r(void 0);return}let o=n[3];if(o===1){if(n.length<10)return;let l=Array.from(n.subarray(4,8)).join(".");r({host:l,port:n.readUInt16BE(8)})}else if(o===3){if(n.length<5)return;let l=n[4];if(n.length<5+l+2)return;r({host:n.subarray(5,5+l).toString("utf8"),port:n.readUInt16BE(5+l)})}else if(o===4){if(n.length<22)return;let l=[];for(let c=0;c<16;c+=2)l.push(n.readUInt16BE(4+c).toString(16));r({host:l.join(":"),port:n.readUInt16BE(20)})}else r(void 0)};e.on("data",s),e.resume(),e.once("error",()=>r(void 0)),e.once("close",()=>r(void 0))})}function Bx(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]),va(1),va(n.length),n,va(r.length),r]),s=8-(5+i.length)%8;if(s<4)s+=8;return Buffer.concat([va(1+i.length+s),Buffer.from([s]),i,Buffer.alloc(s)])}function va(e){let t=Buffer.alloc(4);return t.writeUInt32BE(e,0),t}import{createServer as Px,connect as zf}from"net";import{join as Nx}from"path";import{tmpdir as Dx}from"os";import{unlink as Xf}from"fs/promises";function xa(e,t,n,r){return new Promise((i,s)=>{let[a,o]=n??[0,0],l=a,c=()=>{while(r.has(l)&&l<=o)l++;if(l>o){s(Error(`No free port in range ${a}-${o} (excluding ${[...r].join(",")})`));return}let u=()=>{e.removeListener("error",d),i()},d=(p)=>{if(e.removeListener("listening",u),n&&p?.code==="EADDRINUSE"&&l<o){l++,c();return}s(p??Error("listen error"))};e.once("error",d),e.once("listening",u),t(n?l:0)};c()})}var Lx=new Set([4,5]),Ox=1e4,Ux=0;function Vx(){return Nx(Dx(),`srt-mux-${process.pid}-${(Ux++).toString(36)}.sock`)}function Qf(e){let t=e.firstByteTimeoutMs??Ox,n=De()==="windows",r,i,s=new Set;function a(l){if(r===void 0&&i===void 0){w("mux: HTTP dispatch before backend bound; dropping",{level:"error"}),l.destroy();return}let c=r?zf(r):zf(i,"127.0.0.1");c.on("error",(u)=>{let d=u.code??"ERR";if(w(`mux: HTTP backend dial failed: ${u.message}`,{level:"error"}),!l.destroyed)l.end(`HTTP/1.1 502 Bad Gateway\r
68
68
  Connection: close\r
69
69
  \r
70
70
  mux backend dial failed (${d})
71
- `)}),l.on("error",()=>c.destroy()),l.once("close",()=>c.destroy()),c.once("close",()=>l.destroy()),l.pipe(c),c.pipe(l)}let o=Nx((l)=>{s.add(l),l.once("close",()=>s.delete(l)),l.on("error",(u)=>w(`mux: client socket error: ${u.message}`));let c=setTimeout(()=>{w("mux: first-byte timeout; destroying connection"),l.destroy()},t);if(typeof c.unref==="function")c.unref();l.once("readable",()=>{clearTimeout(c);let u=l.read(1);if(!u||u.length===0){l.destroy();return}if(l.unshift(u),Ox.has(u[0]))e.handleSocksConnection(l);else a(l)})});return{server:o,getPort(){let l=o.address();return l&&typeof l==="object"?l.port:void 0},async listenHttpBackend(){if(!n){let c=Fx();await Xf(c).catch(()=>{}),await new Promise((u,d)=>{e.httpServer.once("error",d),e.httpServer.listen(c,()=>{e.httpServer.removeListener("error",d),u()})}),r=c,w(`mux: HTTP backend listening on ${c}`);return}await xa(e.httpServer,(c)=>e.httpServer.listen(c,"127.0.0.1"),e.httpBackendPortRange,new Set);let l=e.httpServer.address();return i=l&&typeof l==="object"?l.port:void 0,w(`mux: HTTP backend listening on 127.0.0.1:${i}`),i},async close(){for(let l of s)l.destroy();if(s.clear(),await new Promise((l)=>o.close(()=>l())),await new Promise((l)=>e.httpServer.close(()=>l())),r)await Xf(r).catch(()=>{}),r=void 0;i=void 0},unref(){o.unref(),e.httpServer.unref()}}}import{randomInt as Mx,randomUUID as $x}from"crypto";var Gn="fake_value_",Yf="abcdefghijklmnopqrstuvwxyz0123456789_-";function Wx(e){let t=Gn+$x(),n=Buffer.byteLength(e)-t.length;if(n<=0)return t;let r=t;for(let i=0;i<n;i++)r+=Yf[Mx(Yf.length)];return r}class Fl{byName=new Map;bySentinel=new Map;allSentinelsPrefixed=!0;refs=new Map;lease=null;register(e,t,n,r){return this.registerWithSentinel(e,Wx(t),t,n,r)}registerWithSentinel(e,t,n,r,i){let s=this.byName.get(e);if(s!==void 0&&s.realValue===n)return s.injectHosts=r,s.injectHeaders=i,this.lease?.add(s),s.sentinel;if(this.bySentinel.has(t))throw Error("credential sentinel collision");if(!t.startsWith(Gn))this.allSentinelsPrefixed=!1;let a={name:e,sentinel:t,realValue:n,injectHosts:r,injectHeaders:i};return this.byName.set(e,a),this.bySentinel.set(t,a),this.lease?.add(a),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(Gn));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 s=0;s<i.length;s++)i[s]=this.substituteInHeaderValue(r,i[s],t,n);else e[r]=this.substituteInHeaderValue(r,i,t,n)}}substituteInHeaderValue(e,t,n,r){let i=e.toLowerCase(),s=this.substituteInString(t,n,r,i);if(i!=="authorization")return s;let a=/^(\s*basic\s+)([a-z0-9+/]+={0,2})(\s*)$/i.exec(s);if(a===null)return s;let o=a[2],l=Buffer.from(o,"base64");if(o.length%4!==0||l.toString("base64")!==o)return s;let c=l.toString("utf8");if(!Buffer.from(c,"utf8").equals(l))return s;let u=this.substituteInString(c,n,r,i);if(u===c)return s;return`${a[1]}${Buffer.from(u,"utf8").toString("base64")}${a[3]}`}substituteInString(e,t,n,r){if(this.allSentinelsPrefixed&&!e.includes(Gn))return e;let i=e;for(let s of this.bySentinel.values()){if(!i.includes(s.sentinel))continue;if(!s.injectHosts.some((a)=>n(t,a)))continue;if(s.injectHeaders!==void 0&&!s.injectHeaders.includes(r))continue;i=i.split(s.sentinel).join(s.realValue)}return i}}import{randomUUID as Qx}from"crypto";import*as Qt from"fs";import{tmpdir as Yx}from"os";import{join as tp}from"path";function Hx(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 Kx(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 Jf(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 qx(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 Gx(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 s=Number(e.slice(i,r)),a=s,o=!1;if(e[r]===","){r++;let l=r;while(/[0-9]/.test(e[r]??""))r++;if(r===l)o=!0,a=void 0;else a=Number(e.slice(l,r))}if(e[r]!=="}")return null;if(!Number.isFinite(s)||s>4096||a!==void 0&&(!Number.isFinite(a)||a>4096))return{next:r+1,unbounded:o,error:"finite repetitions must be at most 4096"};if(r++,e[r]==="?")r++;return{next:r,unbounded:o}}function jx(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=(s)=>{let a=r();if(a.lastAtom?.hasUnboundedQuantifier&&s.hasUnboundedQuantifier&&a.lastAtom.repeatClass!==null&&s.repeatClass!==null&&Jf(a.lastAtom.repeatClass,s.repeatClass))a.error="adjacent unbounded repetition with overlapping input is not supported";if(a.previousAtom=a.lastAtom,a.lastAtom=s,a.atomCount===0)a.simpleClass=s.repeatClass;else a.simpleClass=null;if(a.atomCount++,s.kind==="group")a.containsQuantifier||=s.containsQuantifier,a.containsAlternation||=s.containsAlternation;a.hasUnboundedQuantifier||=s.hasUnboundedQuantifier};for(let s=0;s<e.length;){if(r().error!==void 0)return{groupCount:n,error:r().error};let a=e[s];if(a==="\\"){let l=e[s+1];if(l!==void 0&&/[1-9]/.test(l)||l==="k"&&e[s+2]==="<")return{groupCount:n,error:"backreferences are not supported by the safe extractor"};let c=l==="b"||l==="B";if(i({kind:"token",containsQuantifier:!1,containsAlternation:!1,hasUnboundedQuantifier:!1,repeatClass:Kx(l)}),s+=l===void 0?1:2,c)r().previousAtom=null,r().lastAtom=null;continue}if(a==="["){i({kind:"token",containsQuantifier:!1,containsAlternation:!1,hasUnboundedQuantifier:!1,repeatClass:{kind:"unknown"}}),s=Hx(e,s);continue}if(a==="("){let l=qx(e,s);if(l.capturing)n++;t.push({previousAtom:null,lastAtom:null,atomCount:0,simpleClass:null,containsQuantifier:!1,containsAlternation:!1,hasUnboundedQuantifier:!1}),s=l.next;continue}if(a===")"){if(t.length>1){let l=t.pop();if(l.error!==void 0)return{groupCount:n,error:l.error};i({kind:"group",containsQuantifier:l.containsQuantifier,containsAlternation:l.containsAlternation,hasUnboundedQuantifier:l.hasUnboundedQuantifier,repeatClass:l.atomCount===1&&!l.containsAlternation?l.simpleClass:null})}s++;continue}if(a==="|"){r().containsAlternation=!0,r().previousAtom=null,r().lastAtom=null,s++;continue}let o=Gx(e,s);if(o!==null){if(o.error)return{groupCount:n,error:o.error};let l=r(),c=l.lastAtom;if(o.unbounded&&c?.kind==="group"&&(c.containsQuantifier||c.containsAlternation))return{groupCount:n,error:"nested unbounded repetition or unbounded alternation is not supported"};if(o.unbounded&&l.previousAtom?.hasUnboundedQuantifier&&c!==null&&l.previousAtom.repeatClass!==null&&c.repeatClass!==null&&Jf(l.previousAtom.repeatClass,c.repeatClass))return{groupCount:n,error:"adjacent unbounded repetition with overlapping input is not supported"};if(l.containsQuantifier=!0,c!==null)l.lastAtom={...c,containsQuantifier:!0,hasUnboundedQuantifier:c.hasUnboundedQuantifier||o.unbounded};l.hasUnboundedQuantifier||=o.unbounded,s=o.next;continue}if(a!=="^"&&a!=="$")i({kind:"token",containsQuantifier:!1,containsAlternation:!1,hasUnboundedQuantifier:!1,repeatClass:a==="."?{kind:"any"}:{kind:"literal",value:a}});else r().previousAtom=null,r().lastAtom=null;s++}return{groupCount:n,error:r().error}}function Ml(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=jx(e);if(n.error!==void 0)throw Error(`Credential extract pattern rejected: ${n.error}`);return{regex:t,groupCount:n.groupCount}}function zx(e,t=""){Ml(e);try{return new RegExp(e,t)}catch{throw Error("Credential extract pattern is not supported by this runtime")}}function Sa(e,t,n,r={}){if(e.length>1048576)throw Error("Credential extraction input exceeds the 1048576-character limit");let i=zx(t,"gd"),s=new Map,a=new Map,o=[],l=0;for(let d of e.matchAll(i)){if(l++,l>4096)throw Error("Credential extraction exceeds the 4096-match limit");let p=d[1];if(p===void 0)throw Error(`Credential extraction matched at offset ${d.index} without a group-1 capture; group 1 must capture the credential value on every match.`);if(p.length===0)continue;let h=s.get(p);if(h===void 0)s.set(p,h=s.size);let[f,v]=d.indices[1],x=n(p,h);if(!a.has(p))a.set(p,x);o.push({start:f,end:v,sentinel:x})}if(s.size===0)return null;if(r.maskDuplicates){let d=[...s.keys()].sort((p,h)=>h.length-p.length);for(let p of d){let h=a.get(p);if(h===p)continue;for(let f=e.indexOf(p);f!==-1;f=e.indexOf(p,f+1)){let v=f+p.length;if(o.some((x)=>f<x.end&&x.start<v))continue;o.push({start:f,end:v,sentinel:h})}}o.sort((p,h)=>p.start-h.start)}let c="",u=0;for(let d of o)c+=e.slice(u,d.start)+d.sentinel,u=d.end;return{fakeContent:c+e.slice(u),captures:[...s.keys()]}}var Zf="(eyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+)";function $l(e){try{return JSON.parse(Buffer.from(e,"base64url").toString("utf8"))}catch{return}}function ba(e){let t=e.split(".");if(t.length!==3)return!1;let n=$l(t[0]);if(typeof n!=="object"||n===null||!("alg"in n))return!1;return $l(t[1])!==void 0}var Xx=9999999999,ep="c3J0LWZha2U";function Wl(e){return Buffer.from(e,"utf8").toString("base64url")}function Ca(e){let t=Wl(JSON.stringify({alg:"HS256",typ:"JWT"})),n=Wl(JSON.stringify({sub:Gn+e,exp:Xx}));return`${t}.${n}.${ep}`}function wa(e,t,n){let[r,i]=e.split("."),s=$l(i??"");if(typeof s!=="object"||s===null||Array.isArray(s))return null;let a=s,o=[];for(let c of t){let u=a[c];if(typeof u==="string")o.push([c,u])}if(o.length===0)return null;let l=new Map;for(let[c,u]of o){let d=n(c,u);a[c]=d,l.set(c,d)}return{fakeToken:`${r}.${Wl(JSON.stringify(a))}.${ep}`,claimSentinels:l}}var Jx="file:";class Hl{dir;byKey=new Map;write(e,t){if(this.dir===void 0)this.dir=Qt.mkdtempSync(tp(Yx(),"srt-credmask-"));let n=this.byKey.get(e);if(n===void 0)n=tp(this.dir,`${this.byKey.size}.fake`),this.byKey.set(e,n);return Qt.rmSync(n,{force:!0}),Qt.writeFileSync(n,t,{mode:384}),n}dispose(){if(this.dir!==void 0)try{Qt.rmSync(this.dir,{recursive:!0,force:!0})}catch(e){w(`MaskedFileStore cleanup failed: ${e}`,{level:"error"})}this.dir=void 0,this.byKey.clear()}get dirPath(){return this.dir}}function rp(e,t,n,r){let i=[],s=[];for(let a of e){if(a.mode!=="mask")continue;let o=et(a.path),l;try{if(Qt.statSync(o).isDirectory()){w(`[credential-mask] Skipping masked file entry that resolves to a directory: ${a.path} \u2014 use mode "deny" for directories.`,{level:"warn"});continue}let f=Qt.readFileSync(o);if(l=f.toString("utf8"),Buffer.byteLength(l,"utf8")!==f.length){w(`[credential-mask] Skipping masked file with non-UTF-8 content (binary credential files are not supported in mask mode): ${a.path}`,{level:"warn"});continue}}catch(h){w(`[credential-mask] Skipping masked file (unreadable on host): ${a.path} \u2014 ${h.message}`);continue}let c=a.injectHosts??t,u=Jx+o,d;if(a.extract===void 0&&a.decode===void 0)d=n.register(u,l,c);else{let h=a.extract??Zf,f=0,v=Sa(l,h,(x,S)=>{if(a.decode==="jwt"&&!ba(x))return x;let A=`${u}#${S}`;if(a.decode==="jwt"&&a.maskClaims?.length){let b=wa(x,a.maskClaims,(R,I)=>n.register(`${u}#jwt${S}.${R}`,I,c));if(b===null)return w(`[credential-mask] ${a.path}: verified JWT candidate has none of maskClaims ${JSON.stringify(a.maskClaims)} as `+"string claims \u2014 left unmasked."),x;let k=a.maskClaims.filter((R)=>!b.claimSentinels.has(R));if(k.length>0)w(`[credential-mask] ${a.path}: maskClaims ${JSON.stringify(k)} absent or non-string in a `+"verified JWT \u2014 skipped.");return f++,n.registerWithSentinel(A,b.fakeToken,x,c)}return f++,a.decode==="jwt"?n.registerWithSentinel(A,Ca(Qx()),x,c):n.register(A,x,c)},{maskDuplicates:a.maskDuplicates??!1});if(v===null||f===0){let x=a.decode==="jwt"?a.maskClaims?.length?`decode "jwt" with pattern "${h}" that matched no verified JWT with maskable claims (maskClaims: ${JSON.stringify(a.maskClaims)})`:`decode "jwt" with pattern "${h}" that matched no verified JWT`:`extract pattern "${h}" that matched nothing`,S=a.onExtractNoMatch??"warn";if(S==="error")throw Error(`credentials.files entry "${a.path}": ${x} (onExtractNoMatch: "error"). Fix the config, change to "warn"/"deny", or remove the entry.`);if(S==="deny"){w(`[credential-mask] ${a.path} has ${x} \u2014 degrading to `+'mode "deny".',{level:"warn"}),s.push(o);continue}let A=`[sandbox-runtime] WARNING: credentials.files entry "${a.path}" has ${x} in the file. The file is left UNPROTECTED (readable as-is inside the sandbox). Fix the config, set onExtractNoMatch to "deny" or "error", or remove the entry.`;console.warn(A),w(A,{level:"warn"});continue}d=v.fakeContent}let p=r.write(u,d);i.push({realPath:o,fakePath:p})}return{binds:i,degradeToDenyPaths:s}}import{randomUUID as Zx}from"crypto";var Ea="env:";function np(e,t,n,r=process.env){let i={},s=[];for(let a of e){if(a.mode!=="mask")continue;let o=r[a.name];if(o===void 0)continue;let l=a.injectHosts??t;if(a.decode==="jwt"){if(!ba(o)){let u=`[sandbox-runtime] WARNING: credentials.envVars entry "${a.name}" has decode "jwt" but its value did not verify as a JWT. The variable is left UNPROTECTED (real value visible as-is inside the sandbox). Fix the config or remove the entry.`;console.warn(u),w(u,{level:"warn"});continue}if(a.maskClaims?.length){let u=wa(o,a.maskClaims,(p,h)=>n.register(`${Ea}${a.name}#${p}`,h,l,a.injectHeaders));if(u===null){let p=`[sandbox-runtime] WARNING: credentials.envVars entry "${a.name}" has maskClaims ${JSON.stringify(a.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 d=a.maskClaims.filter((p)=>!u.claimSentinels.has(p));if(d.length>0)w(`[credential-mask] env var "${a.name}": maskClaims ${JSON.stringify(d)} absent or non-string in the `+"JWT \u2014 skipped.");i[a.name]=n.registerWithSentinel(`${Ea}${a.name}`,u.fakeToken,o,l,a.injectHeaders);continue}i[a.name]=n.registerWithSentinel(`${Ea}${a.name}`,Ca(Zx()),o,l,a.injectHeaders);continue}if(a.extract===void 0){i[a.name]=n.register(a.name,o,l,a.injectHeaders);continue}let c=Sa(o,a.extract,(u,d)=>n.register(`${Ea}${a.name}#${d}`,u,l,a.injectHeaders));if(c===null){let u=a.onExtractNoMatch??"warn";if(u==="error")throw Error(`credentials.envVars entry "${a.name}": extract pattern "${a.extract}" matched nothing (onExtractNoMatch: "error"). Fix the regex, change to "warn"/"deny", or remove the entry.`);if(u==="deny"){w(`[credential-mask] extract pattern /${a.extract}/ matched nothing in the value of ${a.name} \u2014 unsetting the variable.`,{level:"warn"}),s.push(a.name);continue}let d=`[sandbox-runtime] WARNING: credentials.envVars entry "${a.name}" has extract pattern "${a.extract}" that matched nothing in the variable's value. The variable is left UNPROTECTED (visible as-is inside the sandbox). Fix the regex, set onExtractNoMatch to "deny" or "error", or remove the entry.`;console.warn(d),w(d,{level:"warn"});continue}i[a.name]=c.fakeContent}return{setEnvVars:i,degradeToUnsetNames:s}}var ip="AWS_ACCESS_KEY_ID",sp="AWS_SECRET_ACCESS_KEY",ap="AWS_SESSION_TOKEN";class Kl{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 op(e,t,n,r,i,s=process.env){let a=[...t??[]],o=new Set(a.flatMap((d)=>[d.accessKeyIdVar,d.secretAccessKeyVar,...d.sessionTokenVar?[d.sessionTokenVar]:[]]));if(![ip,sp,ap].some((d)=>o.has(d)))a.push({accessKeyIdVar:ip,secretAccessKeyVar:sp,sessionTokenVar:ap});let c=(d)=>e.find((p)=>p.name===d&&p.mode==="mask"&&p.extract===void 0&&p.decode===void 0),u=(d)=>c(d)!==void 0?r[d]:void 0;for(let d of a){let p=u(d.accessKeyIdVar),h=u(d.secretAccessKeyVar)!==void 0,f=s[d.accessKeyIdVar],v=s[d.secretAccessKeyVar];if(p===void 0||!h||f===void 0||v===void 0){if(h&&p===void 0){let b=`[sandbox-runtime] WARNING: "${d.secretAccessKeyVar}" is masked but "${d.accessKeyIdVar}" is not, so no AWS credential pair was registered. SigV4 requests will be signed with the masked placeholder secret and the proxy cannot `+"detect or re-sign them \u2014 they will fail upstream. Mask both "+"variables (whole-value) to enable re-signing.";console.warn(b),w(b,{level:"warn"})}continue}let x=c(d.accessKeyIdVar),A=(d.sessionTokenVar!==void 0?u(d.sessionTokenVar):void 0)!==void 0&&d.sessionTokenVar!==void 0?s[d.sessionTokenVar]:void 0;i.register({accessKeyIdSentinel:p,realAccessKeyId:f,realSecretAccessKey:v,...A!==void 0?{realSessionToken:A}:{},injectHosts:x.injectHosts??n}),w(`[credential-aws] registered SigV4 pair for ${d.accessKeyIdVar}/${d.secretAccessKeyVar}`+(A!==void 0?" (+session token)":""))}}function eS(e){return{streaming:e?.streaming??"deny",presigned:e?.presigned??"deny",sigv4a:e?.sigv4a??"deny"}}function lp(e,t,n){let r=eS(t);return(i,s,a,o)=>{if(e.size===0)return;let l=Tf(a,s);if(l===null)return;let c=e.lookup(l.accessKeyId);if(c===void 0)return;if(!c.injectHosts.some((f)=>n(o,f)))return;if(l.kind!=="header-sigv4"){if(r[l.kind]==="passthrough"){w(`[credential-aws] ${l.kind} request with masked credential passed through un-resigned per credentials.sigv4.${l.kind} (its signature covers the placeholder secret and will fail upstream)`);return}return{action:"deny",reason:`AWS SigV4 ${l.kind} request uses a masked credential but cannot be re-signed by the sandbox proxy; denied by policy. Set credentials.sigv4.${l.kind} to "passthrough" to forward it unmodified (it will fail upstream: the signature covers the masked placeholder).`}}let u=Af(qn(a.authorization));if(u===null)return{action:"deny",reason:"AWS SigV4 request uses a masked credential but its Authorization header is malformed; the proxy cannot re-sign it."};let d=qn(a["x-amz-date"]);if(d===void 0)return{action:"deny",reason:"AWS SigV4 request uses a masked credential but carries no x-amz-date header; the proxy cannot re-sign it."};let p=[...u.signedHeaders];for(let f of p){if(f==="host")continue;if(f==="x-amz-security-token"&&c.realSessionToken!==void 0)continue;if(a[f]===void 0)return{action:"deny",reason:`AWS SigV4 request uses a masked credential but signed header "${f}" is missing; the proxy cannot re-sign it.`}}if(c.realSessionToken!==void 0&&!p.includes("x-amz-security-token"))p.push("x-amz-security-token");let h=qn(a["x-amz-content-sha256"]);return{action:"resign",payloadHash:h===ma?ma:void 0,apply(f,v,x){if(c.realSessionToken!==void 0)f["x-amz-security-token"]=c.realSessionToken;if(f["x-amz-content-sha256"]!==void 0&&h!==ma)f["x-amz-content-sha256"]=x;let{authorization:S}=_f({method:i,requestTarget:s,headers:f,hostHeader:v,signedHeaders:p,payloadHash:x,amzDate:d,scope:{date:u.date,region:u.region,service:u.service},accessKeyId:c.realAccessKeyId,secretAccessKey:c.realSecretAccessKey});f.authorization=S}}}}import{spawnSync as tS}from"child_process";import*as jn from"fs";function wr(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(!jn.statSync(i).isFile())return!1;return jn.accessSync(i,jn.constants.X_OK),!0}catch{return!1}};if(e.includes("/"))return r(e)?e.trim():null;for(let i of t.split(":")){let s=`${i||"."}/${e}`;if(r(s))return s.trim()}return null}let n=tS("which",[e],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1000});if(n.status===0&&n.stdout)return n.stdout.trim();return null}import*as Xr from"fs";import{randomBytes as xb}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{randomBytes as AS}from"crypto";import*as j from"fs";import{spawn as _p}from"child_process";import{tmpdir as Gi}from"os";import De,{join as kp}from"path";import{spawn as rS}from"child_process";import{text as cp}from"stream/consumers";var nS={ms:1e4};class Ta extends Error{constructor(e){super(`ripgrep timed out after ${e} ms`);this.name="RipgrepTimeoutError"}}async function ql(e,t,n,r={command:"rg"}){let{command:i,args:s=[],argv0:a}=r,o=rS(i,[...s,...e,t],{argv0:a,env:{PATH:process.env.PATH??"/usr/bin:/bin"},signal:n,windowsHide:!0}),l=nS.ms,c=!1,u=setTimeout(()=>{c=!0,o.kill("SIGKILL")},l),d,p,h;try{[d,p,h]=await Promise.all([cp(o.stdout),cp(o.stderr),new Promise((f,v)=>{o.on("close",f),o.on("error",v)})])}finally{clearTimeout(u)}if(c)throw new Ta(l);if(h===0)return d.trim().split(`
72
- `).filter(Boolean);if(h===1)return[];throw Error(`ripgrep failed with exit code ${h}: ${p}`)}import{join as fr,dirname as iS}from"path";import{fileURLToPath as sS}from"url";import*as Aa from"fs";import{homedir as aS}from"os";var Gl=new Map,jl=null;function oS(){if(jl)return jl;let e=[],t=aS();return e.push(fr("/usr","lib","node_modules","@anthropic-ai","sandbox-runtime"),fr("/usr","local","lib","node_modules","@anthropic-ai","sandbox-runtime"),fr("/opt","homebrew","lib","node_modules","@anthropic-ai","sandbox-runtime"),fr(t,".npm","lib","node_modules","@anthropic-ai","sandbox-runtime"),fr(t,".npm-global","lib","node_modules","@anthropic-ai","sandbox-runtime")),jl=e,e}function up(){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 lS(e){let t=up();if(!t)return[];let n=iS(sS(import.meta.url)),r=fr("vendor","seccomp",t,e);return[fr(n,r),fr(n,"..","..",r),fr(n,"..",r)]}function zl(e){let t=e??"";if(Gl.has(t))return Gl.get(t);let n=cS(e);return Gl.set(t,n),n}function cS(e){if(e){if(Aa.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=up();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 lS("apply-seccomp"))if(Aa.existsSync(n))return w(`[SeccompFilter] Found apply-seccomp binary: ${n} (${t})`),n;for(let n of oS()){let r=fr(n,"vendor","seccomp",t,"apply-seccomp");if(Aa.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 uS}from"child_process";import{createHash as dS}from"crypto";import*as Y from"fs";import Yt from"path";class Fi extends Error{}var fS={dir:"/run/srt-stubs",uid:0,lockWaitMs:2000,flockPath:"/usr/bin/flock"},zn=fS,pS,pp;var _a=Y.constants.O_CLOEXEC??524288,Xl={kind:"masked"},dp={kind:"real"},Vi={kind:"unregistered"},hS=new Set(["ENOENT","EACCES"]),gS=new Set(["ENOENT","ENOTDIR","EROFS"]),pr=null,gn=null,mS=0;function Mi(e){return e?.code}function Yl(e){return dS("sha256").update(e).digest("hex")}function Jl(){if(process.platform!=="linux")return"off";let{dir:e,uid:t,flockPath:n}=zn;if(process.geteuid?.()!==t)return"off";try{Y.accessSync(n,Y.constants.X_OK)}catch(i){return hS.has(Mi(i)??"")?"off":"error"}try{Y.mkdirSync(e,{mode:448}),Y.chmodSync(e,448)}catch(i){let s=Mi(i)??"";if(s!=="EEXIST")return gS.has(s)?"off":"error"}let r;try{r=Y.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 hp(e,t){try{return Y.openSync(Yt.join(e,t),Y.constants.O_RDONLY|Y.constants.O_CREAT|Y.constants.O_NOFOLLOW|_a,384)}catch{return null}}function gp(e,t){try{return uS(zn.flockPath,[...t,"3"],{stdio:["ignore","ignore","ignore",e],timeout:zn.lockWaitMs+5000}).status===0}catch{return!1}}function fp(e,t,n){let r=hp(e,t);if(r===null)return null;let i=(zn.lockWaitMs/1000).toFixed(3);if(gp(r,[n,"-w",i]))return r;return Y.closeSync(r),null}function mp(e){try{Y.closeSync(e)}catch{}}function yp(){let e=Jl();if(e==="off")return!1;if(e==="error")throw new Fi(`srt: cannot read the mask stub registry ${zn.dir}; refusing to start the sandbox`);if(pr===null)pr=fp(e,"lock","-s");if(pr!==null&&gn===null)gn=fp(e,"claims","-x");if(pr===null||gn===null)throw new Fi(`srt: mask stub registry ${e} is busy (no ${pr===null?"shared":"claims"} lock within ${zn.lockWaitMs} ms); refusing to start the sandbox rather than risk a mask another call removes`);return!0}function ka(){if(gn===null)return;mp(gn),gn=null}function yS(){if(pr===null)return;mp(pr),pr=null}function vp(){let e=Jl();if(e==="off")return null;if(e==="error"||pr===null||gn===null)throw new Fi("srt: mask stub claimed without holding the registry; refusing to start the sandbox");return e}function $i(e){try{return Y.lstatSync(e,{bigint:!0})}catch(t){return Mi(t)==="ENOENT"?"absent":"unknown"}}function xp(e){try{let t=JSON.parse(Y.readFileSync(e,"utf8")),{v:n,type:r,uid:i,dev:s,ino:a,ctimeNs:o,path:l}=t,c=(u)=>typeof u==="string"&&/^\d+$/.test(u);if(n!==1||r!=="f"&&r!=="d"||typeof i!=="number"||!c(s)||!c(a)||!c(o)||typeof l!=="string"||!l.startsWith("/"))return null;return{type:r,uid:i,dev:BigInt(s),ino:BigInt(a),ctimeNs:BigInt(o),dest:l}}catch{return null}}function Sp(e,t){return Yt.join(e,`${Yl(t)}.stub`)}function vS(e,t){let n=Yl(t.dest),r=Yt.join(e,`${n}.stub.${process.pid}-${++mS}`),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});Y.writeFileSync(r,i+`
73
- `,{flag:"wx",mode:384}),Y.renameSync(r,Yt.join(e,`${n}.stub`))}function bp(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 Zl(e){let t=Yt.dirname(e),n;try{n=Y.openSync(t,Y.constants.O_RDONLY|Y.constants.O_DIRECTORY|Y.constants.O_NOFOLLOW|_a)}catch{return null}try{if(Y.readlinkSync(`/proc/self/fd/${n}`)===t)return n}catch{}return Y.closeSync(n),null}function Cp(e,t,n){return{type:e,uid:Number(t.uid),dev:t.dev,ino:t.ino,ctimeNs:t.ctimeNs,dest:n}}function xS(e){let t=Zl(e);if(t===null)return null;try{let n;try{n=Y.openSync(`/proc/self/fd/${t}/${Yt.basename(e)}`,Y.constants.O_RDONLY|Y.constants.O_CREAT|Y.constants.O_EXCL|Y.constants.O_NOFOLLOW|_a,292)}catch(r){return Mi(r)==="EEXIST"?"exists":null}try{return pp?.(e),Cp("f",Y.fstatSync(n,{bigint:!0}),e)}finally{Y.closeSync(n)}}finally{Y.closeSync(t)}}function SS(e,t){let n=Zl(e);if(n===null)return null;try{let r=`/proc/self/fd/${n}/${Yt.basename(e)}`;try{Y.mkdirSync(r,{mode:493})}catch(s){return Mi(s)==="EEXIST"?"exists":null}pp?.(e);let i;try{i=Y.openSync(r,Y.constants.O_RDONLY|Y.constants.O_DIRECTORY|Y.constants.O_NOFOLLOW|_a)}catch{return null}try{let s=Y.fstatSync(i,{bigint:!0});if(!s.isDirectory()||s.uid!==BigInt(process.geteuid?.()??-1)||s.nlink>BigInt(2)||Y.readdirSync(`/proc/self/fd/${i}`).length!==0)return null;if(t)Y.fchownSync(i,t.uid,t.gid);return Cp("d",Y.fstatSync(i,{bigint:!0}),e)}catch{return null}finally{Y.closeSync(i)}}finally{Y.closeSync(n)}}function bS(e){let t=Zl(e.dest);if(t===null)return;try{let n=`/proc/self/fd/${t}/${Yt.basename(e.dest)}`,r=$i(n);if(typeof r==="object"&&bp(r,e)){if(e.type==="d")Y.rmdirSync(n);else Y.unlinkSync(n);w(`[Sandbox Linux] Removed shared mask stub: ${e.dest}`)}}catch{}finally{Y.closeSync(t)}}function CS(e){try{Y.unlinkSync(e)}catch{}}function Ql(e,t,n,r){let i=xp(Sp(e,t));return i!==null&&i.type===r&&i.dest===t&&bp(n,i)}function wp(e,t,n){let r=vp();if(r===null)return Vi;if(pS?.(e)==="unregistered")return Vi;let i=$i(e);if(i==="unknown")return Vi;if(i!=="absent")return Ql(r,e,i,t)?Xl:dp;let s=n();if(s==="exists"){let a=$i(e);return typeof a==="object"&&Ql(r,e,a,t)?Xl:dp}if(s===null)return Vi;try{vS(r,s)}catch(a){w(`[Sandbox Linux] mask stub marker not written for ${e}: ${a}`,{level:"warn"})}return Xl}function wS(e){return wp(e,"f",()=>xS(e))}function ES(e,t){return wp(e,"d",()=>SS(e,t))}function Ep(e,t){let n=vp();if(n===null)return null;let r=(s)=>t.some((a)=>s.startsWith(a+"/")),i=[];for(let s=Yt.dirname(e);r(s);s=Yt.dirname(s))i.unshift(s);for(let s of i){let a=$i(s);if(typeof a==="object"&&Ql(n,s,a,"d"))return s}return null}function Tp(e,t){try{return e()}catch(n){if(n instanceof Fi)throw n;return w(`[Sandbox Linux] mask stub not recorded for ${t}: ${n}`,{level:"warn"}),Vi}}function ec(e){return Tp(()=>wS(e),e)}function Ap(e,t){return Tp(()=>ES(e,t),e)}function TS(e){let t;try{t=Y.readdirSync(e)}catch{return}let n=[],r=[];for(let s of t){let a=/^([0-9a-f]{64})\.stub(\..*)?$/.exec(s);if(a===null)continue;let o=Yt.join(e,s);if(r.push(o),a[2]===void 0){let l=xp(o);if(l!==null&&Yl(l.dest)===a[1])n.push(l)}}let i=(s)=>s.dest.split("/").length;n.sort((s,a)=>s.type===a.type?i(a)-i(s):s.type==="f"?-1:1);for(let s of n)bS(s);for(let s of r)CS(s)}function tc(e,t){let n=Jl(),r=pr!==null;if(ka(),yS(),n==="off"){for(let s of e)t(s);return[]}if(n==="error")return[...e];if(!r&&e.length===0)return[];let i=hp(n,"lock");if(i===null)return[...e];try{if(!gp(i,["-x","-n"]))return[...e];for(let s of e)if($i(Sp(n,s))==="absent")t(s);return TS(n),[]}catch(s){return w(`[Sandbox Linux] mask stub sweep failed: ${s}`,{level:"warn"}),[...e]}finally{Y.closeSync(i)}}var ic=3;function _S(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,s])=>`${i}=${s}`),...t]}function rc(e,t){let n=e.split(De.sep),r="";for(let i of n){if(!i)continue;let s=r+De.sep+i;try{if(j.lstatSync(s).isSymbolicLink()){if(t.some((l)=>s.startsWith(l+"/")||s===l))return s}}catch{break}r=s}return null}var kS=40;function Ip(e){let t=e;for(let n=0;n<kS;n++){try{return j.realpathSync(t)}catch{}let r=t,i=[],s=null;while(s===null){let l=De.dirname(r);if(l===r)return null;i.unshift(De.basename(r)),r=l;try{s=j.realpathSync(r)}catch{}}let a=De.join(s,i[0]),o=null;try{o=j.readlinkSync(a)}catch{}if(o===null)return De.join(s,...i);t=De.join(De.resolve(De.dirname(a),o),...i.slice(1))}return null}function IS(e){let t=e.split(De.sep),n="";for(let r of t){if(!r)continue;let i=n+De.sep+r;try{let s=j.statSync(i);if(s.isFile()||s.isSymbolicLink())return!0}catch{break}n=i}return!1}function RS(e){let t=e.split(De.sep),n="";for(let r of t){if(!r)continue;let i=n+De.sep+r;if(!j.existsSync(i))return i;n=i}return e}async function BS(e={command:"rg"},t=ic,n=!1,r){let i=process.cwd(),s=new AbortController,a=r??s.signal,o=Es(),l=[...di.map((f)=>De.resolve(i,f)),...o.map((f)=>De.resolve(i,f))],c=De.resolve(i,".git"),u=!1;try{u=j.statSync(c).isDirectory()}catch{}if(u){if(l.push(De.resolve(i,".git/hooks")),!n)l.push(De.resolve(i,".git/config"))}let d=[];for(let f of di)d.push("--iglob",f);for(let f of o)d.push("--iglob",`**/${f}/**`);if(d.push("--iglob","**/.git/hooks/**"),!n)d.push("--iglob","**/.git/config");let p=["--files","--hidden","--no-ignore","--max-depth",String(t),...d,"-g","!**/node_modules/**"],h;try{h=await ql(p,i,a,e)}catch(f){if(f instanceof Ta)throw Error(`mandatory deny scan failed: ${f}`);w(`[Sandbox] ripgrep scan failed, retrying once: ${f}`);try{h=await ql(p,i,a,e)}catch(v){throw Error(`mandatory deny scan failed: ${v}`)}}for(let f of h){let v=De.resolve(i,f),x=!1;for(let S of[...o,".git"]){let A=so(S),b=v.split(De.sep),k=b.findIndex((R)=>so(R)===A);if(k!==-1){if(S===".git"){let R=b.slice(0,k+1).join(De.sep);if(f.includes(".git/hooks"))l.push(De.join(R,"hooks"));else if(f.includes(".git/config"))l.push(De.join(R,"config"))}else l.push(b.slice(0,k+1).join(De.sep));x=!0;break}}if(!x)l.push(v)}return[...new Set(l)]}var Wi;function PS(){if(process.getuid?.()!==0||process.env.ARA_SRT_FILE_MASK!=="empty")return"/dev/null";if(Wi)try{let n=j.lstatSync(Wi);if(n.isFile()&&n.size===0&&n.uid===0&&(n.mode&146)===0)return Wi}catch{}let e=j.mkdtempSync(De.join(Gi(),"claude-empty-file-"));ji.add(e),j.chmodSync(e,493);let t=De.join(e,"empty");return j.writeFileSync(t,"",{flag:"wx",mode:292}),j.chmodSync(t,292),Wi=t,t}var Hi="/etc/ssh/ssh_config";function NS(e){return`# Added by the sandbox: this sandbox reaches the network only through its proxy.
71
+ `)}),l.on("error",()=>c.destroy()),l.once("close",()=>c.destroy()),c.once("close",()=>l.destroy()),l.pipe(c),c.pipe(l)}let o=Px((l)=>{s.add(l),l.once("close",()=>s.delete(l)),l.on("error",(u)=>w(`mux: client socket error: ${u.message}`));let c=setTimeout(()=>{w("mux: first-byte timeout; destroying connection"),l.destroy()},t);if(typeof c.unref==="function")c.unref();l.once("readable",()=>{clearTimeout(c);let u=l.read(1);if(!u||u.length===0){l.destroy();return}if(l.unshift(u),Lx.has(u[0]))e.handleSocksConnection(l);else a(l)})});return{server:o,getPort(){let l=o.address();return l&&typeof l==="object"?l.port:void 0},async listenHttpBackend(){if(!n){let c=Vx();await Xf(c).catch(()=>{}),await new Promise((u,d)=>{e.httpServer.once("error",d),e.httpServer.listen(c,()=>{e.httpServer.removeListener("error",d),u()})}),r=c,w(`mux: HTTP backend listening on ${c}`);return}await xa(e.httpServer,(c)=>e.httpServer.listen(c,"127.0.0.1"),e.httpBackendPortRange,new Set);let l=e.httpServer.address();return i=l&&typeof l==="object"?l.port:void 0,w(`mux: HTTP backend listening on 127.0.0.1:${i}`),i},async close(){for(let l of s)l.destroy();if(s.clear(),await new Promise((l)=>o.close(()=>l())),await new Promise((l)=>e.httpServer.close(()=>l())),r)await Xf(r).catch(()=>{}),r=void 0;i=void 0},unref(){o.unref(),e.httpServer.unref()}}}import{randomInt as Fx,randomUUID as Mx}from"crypto";var Gn="fake_value_",Yf="abcdefghijklmnopqrstuvwxyz0123456789_-";function $x(e){let t=Gn+Mx(),n=Buffer.byteLength(e)-t.length;if(n<=0)return t;let r=t;for(let i=0;i<n;i++)r+=Yf[Fx(Yf.length)];return r}class Fl{byName=new Map;bySentinel=new Map;allSentinelsPrefixed=!0;refs=new Map;lease=null;register(e,t,n,r){return this.registerWithSentinel(e,$x(t),t,n,r)}registerWithSentinel(e,t,n,r,i){let s=this.byName.get(e);if(s!==void 0&&s.realValue===n)return s.injectHosts=r,s.injectHeaders=i,this.lease?.add(s),s.sentinel;if(this.bySentinel.has(t))throw Error("credential sentinel collision");if(!t.startsWith(Gn))this.allSentinelsPrefixed=!1;let a={name:e,sentinel:t,realValue:n,injectHosts:r,injectHeaders:i};return this.byName.set(e,a),this.bySentinel.set(t,a),this.lease?.add(a),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(Gn));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 s=0;s<i.length;s++)i[s]=this.substituteInHeaderValue(r,i[s],t,n);else e[r]=this.substituteInHeaderValue(r,i,t,n)}}substituteInHeaderValue(e,t,n,r){let i=e.toLowerCase(),s=this.substituteInString(t,n,r,i);if(i!=="authorization")return s;let a=/^(\s*basic\s+)([a-z0-9+/]+={0,2})(\s*)$/i.exec(s);if(a===null)return s;let o=a[2],l=Buffer.from(o,"base64");if(o.length%4!==0||l.toString("base64")!==o)return s;let c=l.toString("utf8");if(!Buffer.from(c,"utf8").equals(l))return s;let u=this.substituteInString(c,n,r,i);if(u===c)return s;return`${a[1]}${Buffer.from(u,"utf8").toString("base64")}${a[3]}`}substituteInString(e,t,n,r){if(this.allSentinelsPrefixed&&!e.includes(Gn))return e;let i=e;for(let s of this.bySentinel.values()){if(!i.includes(s.sentinel))continue;if(!s.injectHosts.some((a)=>n(t,a)))continue;if(s.injectHeaders!==void 0&&!s.injectHeaders.includes(r))continue;i=i.split(s.sentinel).join(s.realValue)}return i}}import{randomUUID as Xx}from"crypto";import*as Qt from"fs";import{tmpdir as Qx}from"os";import{join as tp}from"path";function Wx(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 Hx(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 Jf(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 Kx(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 qx(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 s=Number(e.slice(i,r)),a=s,o=!1;if(e[r]===","){r++;let l=r;while(/[0-9]/.test(e[r]??""))r++;if(r===l)o=!0,a=void 0;else a=Number(e.slice(l,r))}if(e[r]!=="}")return null;if(!Number.isFinite(s)||s>4096||a!==void 0&&(!Number.isFinite(a)||a>4096))return{next:r+1,unbounded:o,error:"finite repetitions must be at most 4096"};if(r++,e[r]==="?")r++;return{next:r,unbounded:o}}function Gx(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=(s)=>{let a=r();if(a.lastAtom?.hasUnboundedQuantifier&&s.hasUnboundedQuantifier&&a.lastAtom.repeatClass!==null&&s.repeatClass!==null&&Jf(a.lastAtom.repeatClass,s.repeatClass))a.error="adjacent unbounded repetition with overlapping input is not supported";if(a.previousAtom=a.lastAtom,a.lastAtom=s,a.atomCount===0)a.simpleClass=s.repeatClass;else a.simpleClass=null;if(a.atomCount++,s.kind==="group")a.containsQuantifier||=s.containsQuantifier,a.containsAlternation||=s.containsAlternation;a.hasUnboundedQuantifier||=s.hasUnboundedQuantifier};for(let s=0;s<e.length;){if(r().error!==void 0)return{groupCount:n,error:r().error};let a=e[s];if(a==="\\"){let l=e[s+1];if(l!==void 0&&/[1-9]/.test(l)||l==="k"&&e[s+2]==="<")return{groupCount:n,error:"backreferences are not supported by the safe extractor"};let c=l==="b"||l==="B";if(i({kind:"token",containsQuantifier:!1,containsAlternation:!1,hasUnboundedQuantifier:!1,repeatClass:Hx(l)}),s+=l===void 0?1:2,c)r().previousAtom=null,r().lastAtom=null;continue}if(a==="["){i({kind:"token",containsQuantifier:!1,containsAlternation:!1,hasUnboundedQuantifier:!1,repeatClass:{kind:"unknown"}}),s=Wx(e,s);continue}if(a==="("){let l=Kx(e,s);if(l.capturing)n++;t.push({previousAtom:null,lastAtom:null,atomCount:0,simpleClass:null,containsQuantifier:!1,containsAlternation:!1,hasUnboundedQuantifier:!1}),s=l.next;continue}if(a===")"){if(t.length>1){let l=t.pop();if(l.error!==void 0)return{groupCount:n,error:l.error};i({kind:"group",containsQuantifier:l.containsQuantifier,containsAlternation:l.containsAlternation,hasUnboundedQuantifier:l.hasUnboundedQuantifier,repeatClass:l.atomCount===1&&!l.containsAlternation?l.simpleClass:null})}s++;continue}if(a==="|"){r().containsAlternation=!0,r().previousAtom=null,r().lastAtom=null,s++;continue}let o=qx(e,s);if(o!==null){if(o.error)return{groupCount:n,error:o.error};let l=r(),c=l.lastAtom;if(o.unbounded&&c?.kind==="group"&&(c.containsQuantifier||c.containsAlternation))return{groupCount:n,error:"nested unbounded repetition or unbounded alternation is not supported"};if(o.unbounded&&l.previousAtom?.hasUnboundedQuantifier&&c!==null&&l.previousAtom.repeatClass!==null&&c.repeatClass!==null&&Jf(l.previousAtom.repeatClass,c.repeatClass))return{groupCount:n,error:"adjacent unbounded repetition with overlapping input is not supported"};if(l.containsQuantifier=!0,c!==null)l.lastAtom={...c,containsQuantifier:!0,hasUnboundedQuantifier:c.hasUnboundedQuantifier||o.unbounded};l.hasUnboundedQuantifier||=o.unbounded,s=o.next;continue}if(a!=="^"&&a!=="$")i({kind:"token",containsQuantifier:!1,containsAlternation:!1,hasUnboundedQuantifier:!1,repeatClass:a==="."?{kind:"any"}:{kind:"literal",value:a}});else r().previousAtom=null,r().lastAtom=null;s++}return{groupCount:n,error:r().error}}function Ml(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=Gx(e);if(n.error!==void 0)throw Error(`Credential extract pattern rejected: ${n.error}`);return{regex:t,groupCount:n.groupCount}}function jx(e,t=""){Ml(e);try{return new RegExp(e,t)}catch{throw Error("Credential extract pattern is not supported by this runtime")}}function Sa(e,t,n,r={}){if(e.length>1048576)throw Error("Credential extraction input exceeds the 1048576-character limit");let i=jx(t,"gd"),s=new Map,a=new Map,o=[],l=0;for(let d of e.matchAll(i)){if(l++,l>4096)throw Error("Credential extraction exceeds the 4096-match limit");let p=d[1];if(p===void 0)throw Error(`Credential extraction matched at offset ${d.index} without a group-1 capture; group 1 must capture the credential value on every match.`);if(p.length===0)continue;let h=s.get(p);if(h===void 0)s.set(p,h=s.size);let[f,v]=d.indices[1],x=n(p,h);if(!a.has(p))a.set(p,x);o.push({start:f,end:v,sentinel:x})}if(s.size===0)return null;if(r.maskDuplicates){let d=[...s.keys()].sort((p,h)=>h.length-p.length);for(let p of d){let h=a.get(p);if(h===p)continue;for(let f=e.indexOf(p);f!==-1;f=e.indexOf(p,f+1)){let v=f+p.length;if(o.some((x)=>f<x.end&&x.start<v))continue;o.push({start:f,end:v,sentinel:h})}}o.sort((p,h)=>p.start-h.start)}let c="",u=0;for(let d of o)c+=e.slice(u,d.start)+d.sentinel,u=d.end;return{fakeContent:c+e.slice(u),captures:[...s.keys()]}}var Zf="(eyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+)";function $l(e){try{return JSON.parse(Buffer.from(e,"base64url").toString("utf8"))}catch{return}}function ba(e){let t=e.split(".");if(t.length!==3)return!1;let n=$l(t[0]);if(typeof n!=="object"||n===null||!("alg"in n))return!1;return $l(t[1])!==void 0}var zx=9999999999,ep="c3J0LWZha2U";function Wl(e){return Buffer.from(e,"utf8").toString("base64url")}function Ca(e){let t=Wl(JSON.stringify({alg:"HS256",typ:"JWT"})),n=Wl(JSON.stringify({sub:Gn+e,exp:zx}));return`${t}.${n}.${ep}`}function wa(e,t,n){let[r,i]=e.split("."),s=$l(i??"");if(typeof s!=="object"||s===null||Array.isArray(s))return null;let a=s,o=[];for(let c of t){let u=a[c];if(typeof u==="string")o.push([c,u])}if(o.length===0)return null;let l=new Map;for(let[c,u]of o){let d=n(c,u);a[c]=d,l.set(c,d)}return{fakeToken:`${r}.${Wl(JSON.stringify(a))}.${ep}`,claimSentinels:l}}var Yx="file:";class Hl{dir;byKey=new Map;write(e,t){if(this.dir===void 0)this.dir=Qt.mkdtempSync(tp(Qx(),"srt-credmask-"));let n=this.byKey.get(e);if(n===void 0)n=tp(this.dir,`${this.byKey.size}.fake`),this.byKey.set(e,n);return Qt.rmSync(n,{force:!0}),Qt.writeFileSync(n,t,{mode:384}),n}dispose(){if(this.dir!==void 0)try{Qt.rmSync(this.dir,{recursive:!0,force:!0})}catch(e){w(`MaskedFileStore cleanup failed: ${e}`,{level:"error"})}this.dir=void 0,this.byKey.clear()}get dirPath(){return this.dir}}function rp(e,t,n,r){let i=[],s=[];for(let a of e){if(a.mode!=="mask")continue;let o=et(a.path),l;try{if(Qt.statSync(o).isDirectory()){w(`[credential-mask] Skipping masked file entry that resolves to a directory: ${a.path} \u2014 use mode "deny" for directories.`,{level:"warn"});continue}let f=Qt.readFileSync(o);if(l=f.toString("utf8"),Buffer.byteLength(l,"utf8")!==f.length){w(`[credential-mask] Skipping masked file with non-UTF-8 content (binary credential files are not supported in mask mode): ${a.path}`,{level:"warn"});continue}}catch(h){w(`[credential-mask] Skipping masked file (unreadable on host): ${a.path} \u2014 ${h.message}`);continue}let c=a.injectHosts??t,u=Yx+o,d;if(a.extract===void 0&&a.decode===void 0)d=n.register(u,l,c);else{let h=a.extract??Zf,f=0,v=Sa(l,h,(x,S)=>{if(a.decode==="jwt"&&!ba(x))return x;let A=`${u}#${S}`;if(a.decode==="jwt"&&a.maskClaims?.length){let b=wa(x,a.maskClaims,(R,I)=>n.register(`${u}#jwt${S}.${R}`,I,c));if(b===null)return w(`[credential-mask] ${a.path}: verified JWT candidate has none of maskClaims ${JSON.stringify(a.maskClaims)} as `+"string claims \u2014 left unmasked."),x;let k=a.maskClaims.filter((R)=>!b.claimSentinels.has(R));if(k.length>0)w(`[credential-mask] ${a.path}: maskClaims ${JSON.stringify(k)} absent or non-string in a `+"verified JWT \u2014 skipped.");return f++,n.registerWithSentinel(A,b.fakeToken,x,c)}return f++,a.decode==="jwt"?n.registerWithSentinel(A,Ca(Xx()),x,c):n.register(A,x,c)},{maskDuplicates:a.maskDuplicates??!1});if(v===null||f===0){let x=a.decode==="jwt"?a.maskClaims?.length?`decode "jwt" with pattern "${h}" that matched no verified JWT with maskable claims (maskClaims: ${JSON.stringify(a.maskClaims)})`:`decode "jwt" with pattern "${h}" that matched no verified JWT`:`extract pattern "${h}" that matched nothing`,S=a.onExtractNoMatch??"warn";if(S==="error")throw Error(`credentials.files entry "${a.path}": ${x} (onExtractNoMatch: "error"). Fix the config, change to "warn"/"deny", or remove the entry.`);if(S==="deny"){w(`[credential-mask] ${a.path} has ${x} \u2014 degrading to `+'mode "deny".',{level:"warn"}),s.push(o);continue}let A=`[sandbox-runtime] WARNING: credentials.files entry "${a.path}" has ${x} in the file. The file is left UNPROTECTED (readable as-is inside the sandbox). Fix the config, set onExtractNoMatch to "deny" or "error", or remove the entry.`;console.warn(A),w(A,{level:"warn"});continue}d=v.fakeContent}let p=r.write(u,d);i.push({realPath:o,fakePath:p})}return{binds:i,degradeToDenyPaths:s}}import{randomUUID as Jx}from"crypto";var Ea="env:";function np(e,t,n,r=process.env){let i={},s=[];for(let a of e){if(a.mode!=="mask")continue;let o=r[a.name];if(o===void 0)continue;let l=a.injectHosts??t;if(a.decode==="jwt"){if(!ba(o)){let u=`[sandbox-runtime] WARNING: credentials.envVars entry "${a.name}" has decode "jwt" but its value did not verify as a JWT. The variable is left UNPROTECTED (real value visible as-is inside the sandbox). Fix the config or remove the entry.`;console.warn(u),w(u,{level:"warn"});continue}if(a.maskClaims?.length){let u=wa(o,a.maskClaims,(p,h)=>n.register(`${Ea}${a.name}#${p}`,h,l,a.injectHeaders));if(u===null){let p=`[sandbox-runtime] WARNING: credentials.envVars entry "${a.name}" has maskClaims ${JSON.stringify(a.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 d=a.maskClaims.filter((p)=>!u.claimSentinels.has(p));if(d.length>0)w(`[credential-mask] env var "${a.name}": maskClaims ${JSON.stringify(d)} absent or non-string in the `+"JWT \u2014 skipped.");i[a.name]=n.registerWithSentinel(`${Ea}${a.name}`,u.fakeToken,o,l,a.injectHeaders);continue}i[a.name]=n.registerWithSentinel(`${Ea}${a.name}`,Ca(Jx()),o,l,a.injectHeaders);continue}if(a.extract===void 0){i[a.name]=n.register(a.name,o,l,a.injectHeaders);continue}let c=Sa(o,a.extract,(u,d)=>n.register(`${Ea}${a.name}#${d}`,u,l,a.injectHeaders));if(c===null){let u=a.onExtractNoMatch??"warn";if(u==="error")throw Error(`credentials.envVars entry "${a.name}": extract pattern "${a.extract}" matched nothing (onExtractNoMatch: "error"). Fix the regex, change to "warn"/"deny", or remove the entry.`);if(u==="deny"){w(`[credential-mask] extract pattern /${a.extract}/ matched nothing in the value of ${a.name} \u2014 unsetting the variable.`,{level:"warn"}),s.push(a.name);continue}let d=`[sandbox-runtime] WARNING: credentials.envVars entry "${a.name}" has extract pattern "${a.extract}" that matched nothing in the variable's value. The variable is left UNPROTECTED (visible as-is inside the sandbox). Fix the regex, set onExtractNoMatch to "deny" or "error", or remove the entry.`;console.warn(d),w(d,{level:"warn"});continue}i[a.name]=c.fakeContent}return{setEnvVars:i,degradeToUnsetNames:s}}var ip="AWS_ACCESS_KEY_ID",sp="AWS_SECRET_ACCESS_KEY",ap="AWS_SESSION_TOKEN";class Kl{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 op(e,t,n,r,i,s=process.env){let a=[...t??[]],o=new Set(a.flatMap((d)=>[d.accessKeyIdVar,d.secretAccessKeyVar,...d.sessionTokenVar?[d.sessionTokenVar]:[]]));if(![ip,sp,ap].some((d)=>o.has(d)))a.push({accessKeyIdVar:ip,secretAccessKeyVar:sp,sessionTokenVar:ap});let c=(d)=>e.find((p)=>p.name===d&&p.mode==="mask"&&p.extract===void 0&&p.decode===void 0),u=(d)=>c(d)!==void 0?r[d]:void 0;for(let d of a){let p=u(d.accessKeyIdVar),h=u(d.secretAccessKeyVar)!==void 0,f=s[d.accessKeyIdVar],v=s[d.secretAccessKeyVar];if(p===void 0||!h||f===void 0||v===void 0){if(h&&p===void 0){let b=`[sandbox-runtime] WARNING: "${d.secretAccessKeyVar}" is masked but "${d.accessKeyIdVar}" is not, so no AWS credential pair was registered. SigV4 requests will be signed with the masked placeholder secret and the proxy cannot `+"detect or re-sign them \u2014 they will fail upstream. Mask both "+"variables (whole-value) to enable re-signing.";console.warn(b),w(b,{level:"warn"})}continue}let x=c(d.accessKeyIdVar),A=(d.sessionTokenVar!==void 0?u(d.sessionTokenVar):void 0)!==void 0&&d.sessionTokenVar!==void 0?s[d.sessionTokenVar]:void 0;i.register({accessKeyIdSentinel:p,realAccessKeyId:f,realSecretAccessKey:v,...A!==void 0?{realSessionToken:A}:{},injectHosts:x.injectHosts??n}),w(`[credential-aws] registered SigV4 pair for ${d.accessKeyIdVar}/${d.secretAccessKeyVar}`+(A!==void 0?" (+session token)":""))}}function Zx(e){return{streaming:e?.streaming??"deny",presigned:e?.presigned??"deny",sigv4a:e?.sigv4a??"deny"}}function lp(e,t,n){let r=Zx(t);return(i,s,a,o)=>{if(e.size===0)return;let l=Tf(a,s);if(l===null)return;let c=e.lookup(l.accessKeyId);if(c===void 0)return;if(!c.injectHosts.some((f)=>n(o,f)))return;if(l.kind!=="header-sigv4"){if(r[l.kind]==="passthrough"){w(`[credential-aws] ${l.kind} request with masked credential passed through un-resigned per credentials.sigv4.${l.kind} (its signature covers the placeholder secret and will fail upstream)`);return}return{action:"deny",reason:`AWS SigV4 ${l.kind} request uses a masked credential but cannot be re-signed by the sandbox proxy; denied by policy. Set credentials.sigv4.${l.kind} to "passthrough" to forward it unmodified (it will fail upstream: the signature covers the masked placeholder).`}}let u=Af(qn(a.authorization));if(u===null)return{action:"deny",reason:"AWS SigV4 request uses a masked credential but its Authorization header is malformed; the proxy cannot re-sign it."};let d=qn(a["x-amz-date"]);if(d===void 0)return{action:"deny",reason:"AWS SigV4 request uses a masked credential but carries no x-amz-date header; the proxy cannot re-sign it."};let p=[...u.signedHeaders];for(let f of p){if(f==="host")continue;if(f==="x-amz-security-token"&&c.realSessionToken!==void 0)continue;if(a[f]===void 0)return{action:"deny",reason:`AWS SigV4 request uses a masked credential but signed header "${f}" is missing; the proxy cannot re-sign it.`}}if(c.realSessionToken!==void 0&&!p.includes("x-amz-security-token"))p.push("x-amz-security-token");let h=qn(a["x-amz-content-sha256"]);return{action:"resign",payloadHash:h===ma?ma:void 0,apply(f,v,x){if(c.realSessionToken!==void 0)f["x-amz-security-token"]=c.realSessionToken;if(f["x-amz-content-sha256"]!==void 0&&h!==ma)f["x-amz-content-sha256"]=x;let{authorization:S}=_f({method:i,requestTarget:s,headers:f,hostHeader:v,signedHeaders:p,payloadHash:x,amzDate:d,scope:{date:u.date,region:u.region,service:u.service},accessKeyId:c.realAccessKeyId,secretAccessKey:c.realSecretAccessKey});f.authorization=S}}}}import{spawnSync as eS}from"child_process";import*as jn from"fs";function wr(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(!jn.statSync(i).isFile())return!1;return jn.accessSync(i,jn.constants.X_OK),!0}catch{return!1}};if(e.includes("/"))return r(e)?e.trim():null;for(let i of t.split(":")){let s=`${i||"."}/${e}`;if(r(s))return s.trim()}return null}let n=eS("which",[e],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1000});if(n.status===0&&n.stdout)return n.stdout.trim();return null}import*as Xr from"fs";import{randomBytes as vb}from"crypto";function kt(e){return e.map((t)=>{if(t==="")return"''";if(/^[A-Za-z0-9_./:@+,-][A-Za-z0-9_./:=@+,-]*$/.test(t))return t;return"'"+t.replace(/'/g,`'"'"'`)+"'"}).join(" ")}import{randomBytes as TS}from"crypto";import*as j from"fs";import{spawn as _p}from"child_process";import{tmpdir as Gi}from"os";import Le,{join as kp}from"path";import{spawn as tS}from"child_process";import{text as cp}from"stream/consumers";var rS={ms:1e4};class Ta extends Error{constructor(e){super(`ripgrep timed out after ${e} ms`);this.name="RipgrepTimeoutError"}}async function ql(e,t,n,r={command:"rg"}){let{command:i,args:s=[],argv0:a}=r,o=tS(i,[...s,...e,t],{argv0:a,env:{PATH:process.env.PATH??"/usr/bin:/bin"},signal:n,windowsHide:!0}),l=rS.ms,c=!1,u=setTimeout(()=>{c=!0,o.kill("SIGKILL")},l),d,p,h;try{[d,p,h]=await Promise.all([cp(o.stdout),cp(o.stderr),new Promise((f,v)=>{o.on("close",f),o.on("error",v)})])}finally{clearTimeout(u)}if(c)throw new Ta(l);if(h===0)return d.trim().split(`
72
+ `).filter(Boolean);if(h===1)return[];throw Error(`ripgrep failed with exit code ${h}: ${p}`)}import{join as fr,dirname as nS}from"path";import{fileURLToPath as iS}from"url";import*as Aa from"fs";import{homedir as sS}from"os";var Gl=new Map,jl=null;function aS(){if(jl)return jl;let e=[],t=sS();return e.push(fr("/usr","lib","node_modules","@anthropic-ai","sandbox-runtime"),fr("/usr","local","lib","node_modules","@anthropic-ai","sandbox-runtime"),fr("/opt","homebrew","lib","node_modules","@anthropic-ai","sandbox-runtime"),fr(t,".npm","lib","node_modules","@anthropic-ai","sandbox-runtime"),fr(t,".npm-global","lib","node_modules","@anthropic-ai","sandbox-runtime")),jl=e,e}function up(){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 oS(e){let t=up();if(!t)return[];let n=nS(iS(import.meta.url)),r=fr("vendor","seccomp",t,e);return[fr(n,r),fr(n,"..","..",r),fr(n,"..",r)]}function zl(e){let t=e??"";if(Gl.has(t))return Gl.get(t);let n=lS(e);return Gl.set(t,n),n}function lS(e){if(e){if(Aa.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=up();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 oS("apply-seccomp"))if(Aa.existsSync(n))return w(`[SeccompFilter] Found apply-seccomp binary: ${n} (${t})`),n;for(let n of aS()){let r=fr(n,"vendor","seccomp",t,"apply-seccomp");if(Aa.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 cS}from"child_process";import{createHash as uS}from"crypto";import*as Y from"fs";import Yt from"path";class Fi extends Error{}var dS={dir:"/run/srt-stubs",uid:0,lockWaitMs:2000,flockPath:"/usr/bin/flock"},zn=dS,fS,pp;var _a=Y.constants.O_CLOEXEC??524288,Xl={kind:"masked"},dp={kind:"real"},Vi={kind:"unregistered"},pS=new Set(["ENOENT","EACCES"]),hS=new Set(["ENOENT","ENOTDIR","EROFS"]),pr=null,gn=null,gS=0;function Mi(e){return e?.code}function Yl(e){return uS("sha256").update(e).digest("hex")}function Jl(){if(process.platform!=="linux")return"off";let{dir:e,uid:t,flockPath:n}=zn;if(process.geteuid?.()!==t)return"off";try{Y.accessSync(n,Y.constants.X_OK)}catch(i){return pS.has(Mi(i)??"")?"off":"error"}try{Y.mkdirSync(e,{mode:448}),Y.chmodSync(e,448)}catch(i){let s=Mi(i)??"";if(s!=="EEXIST")return hS.has(s)?"off":"error"}let r;try{r=Y.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 hp(e,t){try{return Y.openSync(Yt.join(e,t),Y.constants.O_RDONLY|Y.constants.O_CREAT|Y.constants.O_NOFOLLOW|_a,384)}catch{return null}}function gp(e,t){try{return cS(zn.flockPath,[...t,"3"],{stdio:["ignore","ignore","ignore",e],timeout:zn.lockWaitMs+5000}).status===0}catch{return!1}}function fp(e,t,n){let r=hp(e,t);if(r===null)return null;let i=(zn.lockWaitMs/1000).toFixed(3);if(gp(r,[n,"-w",i]))return r;return Y.closeSync(r),null}function mp(e){try{Y.closeSync(e)}catch{}}function yp(){let e=Jl();if(e==="off")return!1;if(e==="error")throw new Fi(`srt: cannot read the mask stub registry ${zn.dir}; refusing to start the sandbox`);if(pr===null)pr=fp(e,"lock","-s");if(pr!==null&&gn===null)gn=fp(e,"claims","-x");if(pr===null||gn===null)throw new Fi(`srt: mask stub registry ${e} is busy (no ${pr===null?"shared":"claims"} lock within ${zn.lockWaitMs} ms); refusing to start the sandbox rather than risk a mask another call removes`);return!0}function ka(){if(gn===null)return;mp(gn),gn=null}function mS(){if(pr===null)return;mp(pr),pr=null}function vp(){let e=Jl();if(e==="off")return null;if(e==="error"||pr===null||gn===null)throw new Fi("srt: mask stub claimed without holding the registry; refusing to start the sandbox");return e}function $i(e){try{return Y.lstatSync(e,{bigint:!0})}catch(t){return Mi(t)==="ENOENT"?"absent":"unknown"}}function xp(e){try{let t=JSON.parse(Y.readFileSync(e,"utf8")),{v:n,type:r,uid:i,dev:s,ino:a,ctimeNs:o,path:l}=t,c=(u)=>typeof u==="string"&&/^\d+$/.test(u);if(n!==1||r!=="f"&&r!=="d"||typeof i!=="number"||!c(s)||!c(a)||!c(o)||typeof l!=="string"||!l.startsWith("/"))return null;return{type:r,uid:i,dev:BigInt(s),ino:BigInt(a),ctimeNs:BigInt(o),dest:l}}catch{return null}}function Sp(e,t){return Yt.join(e,`${Yl(t)}.stub`)}function yS(e,t){let n=Yl(t.dest),r=Yt.join(e,`${n}.stub.${process.pid}-${++gS}`),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});Y.writeFileSync(r,i+`
73
+ `,{flag:"wx",mode:384}),Y.renameSync(r,Yt.join(e,`${n}.stub`))}function bp(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 Zl(e){let t=Yt.dirname(e),n;try{n=Y.openSync(t,Y.constants.O_RDONLY|Y.constants.O_DIRECTORY|Y.constants.O_NOFOLLOW|_a)}catch{return null}try{if(Y.readlinkSync(`/proc/self/fd/${n}`)===t)return n}catch{}return Y.closeSync(n),null}function Cp(e,t,n){return{type:e,uid:Number(t.uid),dev:t.dev,ino:t.ino,ctimeNs:t.ctimeNs,dest:n}}function vS(e){let t=Zl(e);if(t===null)return null;try{let n;try{n=Y.openSync(`/proc/self/fd/${t}/${Yt.basename(e)}`,Y.constants.O_RDONLY|Y.constants.O_CREAT|Y.constants.O_EXCL|Y.constants.O_NOFOLLOW|_a,292)}catch(r){return Mi(r)==="EEXIST"?"exists":null}try{return pp?.(e),Cp("f",Y.fstatSync(n,{bigint:!0}),e)}finally{Y.closeSync(n)}}finally{Y.closeSync(t)}}function xS(e,t){let n=Zl(e);if(n===null)return null;try{let r=`/proc/self/fd/${n}/${Yt.basename(e)}`;try{Y.mkdirSync(r,{mode:493})}catch(s){return Mi(s)==="EEXIST"?"exists":null}pp?.(e);let i;try{i=Y.openSync(r,Y.constants.O_RDONLY|Y.constants.O_DIRECTORY|Y.constants.O_NOFOLLOW|_a)}catch{return null}try{let s=Y.fstatSync(i,{bigint:!0});if(!s.isDirectory()||s.uid!==BigInt(process.geteuid?.()??-1)||s.nlink>BigInt(2)||Y.readdirSync(`/proc/self/fd/${i}`).length!==0)return null;if(t)Y.fchownSync(i,t.uid,t.gid);return Cp("d",Y.fstatSync(i,{bigint:!0}),e)}catch{return null}finally{Y.closeSync(i)}}finally{Y.closeSync(n)}}function SS(e){let t=Zl(e.dest);if(t===null)return;try{let n=`/proc/self/fd/${t}/${Yt.basename(e.dest)}`,r=$i(n);if(typeof r==="object"&&bp(r,e)){if(e.type==="d")Y.rmdirSync(n);else Y.unlinkSync(n);w(`[Sandbox Linux] Removed shared mask stub: ${e.dest}`)}}catch{}finally{Y.closeSync(t)}}function bS(e){try{Y.unlinkSync(e)}catch{}}function Ql(e,t,n,r){let i=xp(Sp(e,t));return i!==null&&i.type===r&&i.dest===t&&bp(n,i)}function wp(e,t,n){let r=vp();if(r===null)return Vi;if(fS?.(e)==="unregistered")return Vi;let i=$i(e);if(i==="unknown")return Vi;if(i!=="absent")return Ql(r,e,i,t)?Xl:dp;let s=n();if(s==="exists"){let a=$i(e);return typeof a==="object"&&Ql(r,e,a,t)?Xl:dp}if(s===null)return Vi;try{yS(r,s)}catch(a){w(`[Sandbox Linux] mask stub marker not written for ${e}: ${a}`,{level:"warn"})}return Xl}function CS(e){return wp(e,"f",()=>vS(e))}function wS(e,t){return wp(e,"d",()=>xS(e,t))}function Ep(e,t){let n=vp();if(n===null)return null;let r=(s)=>t.some((a)=>s.startsWith(a+"/")),i=[];for(let s=Yt.dirname(e);r(s);s=Yt.dirname(s))i.unshift(s);for(let s of i){let a=$i(s);if(typeof a==="object"&&Ql(n,s,a,"d"))return s}return null}function Tp(e,t){try{return e()}catch(n){if(n instanceof Fi)throw n;return w(`[Sandbox Linux] mask stub not recorded for ${t}: ${n}`,{level:"warn"}),Vi}}function ec(e){return Tp(()=>CS(e),e)}function Ap(e,t){return Tp(()=>wS(e,t),e)}function ES(e){let t;try{t=Y.readdirSync(e)}catch{return}let n=[],r=[];for(let s of t){let a=/^([0-9a-f]{64})\.stub(\..*)?$/.exec(s);if(a===null)continue;let o=Yt.join(e,s);if(r.push(o),a[2]===void 0){let l=xp(o);if(l!==null&&Yl(l.dest)===a[1])n.push(l)}}let i=(s)=>s.dest.split("/").length;n.sort((s,a)=>s.type===a.type?i(a)-i(s):s.type==="f"?-1:1);for(let s of n)SS(s);for(let s of r)bS(s)}function tc(e,t){let n=Jl(),r=pr!==null;if(ka(),mS(),n==="off"){for(let s of e)t(s);return[]}if(n==="error")return[...e];if(!r&&e.length===0)return[];let i=hp(n,"lock");if(i===null)return[...e];try{if(!gp(i,["-x","-n"]))return[...e];for(let s of e)if($i(Sp(n,s))==="absent")t(s);return ES(n),[]}catch(s){return w(`[Sandbox Linux] mask stub sweep failed: ${s}`,{level:"warn"}),[...e]}finally{Y.closeSync(i)}}var ic=3;function AS(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,s])=>`${i}=${s}`),...t]}function rc(e,t){let n=e.split(Le.sep),r="";for(let i of n){if(!i)continue;let s=r+Le.sep+i;try{if(j.lstatSync(s).isSymbolicLink()){if(t.some((l)=>s.startsWith(l+"/")||s===l))return s}}catch{break}r=s}return null}var _S=40;function Ip(e){let t=e;for(let n=0;n<_S;n++){try{return j.realpathSync(t)}catch{}let r=t,i=[],s=null;while(s===null){let l=Le.dirname(r);if(l===r)return null;i.unshift(Le.basename(r)),r=l;try{s=j.realpathSync(r)}catch{}}let a=Le.join(s,i[0]),o=null;try{o=j.readlinkSync(a)}catch{}if(o===null)return Le.join(s,...i);t=Le.join(Le.resolve(Le.dirname(a),o),...i.slice(1))}return null}function kS(e){let t=e.split(Le.sep),n="";for(let r of t){if(!r)continue;let i=n+Le.sep+r;try{let s=j.statSync(i);if(s.isFile()||s.isSymbolicLink())return!0}catch{break}n=i}return!1}function IS(e){let t=e.split(Le.sep),n="";for(let r of t){if(!r)continue;let i=n+Le.sep+r;if(!j.existsSync(i))return i;n=i}return e}async function RS(e={command:"rg"},t=ic,n=!1,r){let i=process.cwd(),s=new AbortController,a=r??s.signal,o=Es(),l=[...di.map((f)=>Le.resolve(i,f)),...o.map((f)=>Le.resolve(i,f))],c=Le.resolve(i,".git"),u=!1;try{u=j.statSync(c).isDirectory()}catch{}if(u){if(l.push(Le.resolve(i,".git/hooks")),!n)l.push(Le.resolve(i,".git/config"))}let d=[];for(let f of di)d.push("--iglob",f);for(let f of o)d.push("--iglob",`**/${f}/**`);if(d.push("--iglob","**/.git/hooks/**"),!n)d.push("--iglob","**/.git/config");let p=["--files","--hidden","--no-ignore","--max-depth",String(t),...d,"-g","!**/node_modules/**"],h;try{h=await ql(p,i,a,e)}catch(f){if(f instanceof Ta)throw Error(`mandatory deny scan failed: ${f}`);w(`[Sandbox] ripgrep scan failed, retrying once: ${f}`);try{h=await ql(p,i,a,e)}catch(v){throw Error(`mandatory deny scan failed: ${v}`)}}for(let f of h){let v=Le.resolve(i,f),x=!1;for(let S of[...o,".git"]){let A=so(S),b=v.split(Le.sep),k=b.findIndex((R)=>so(R)===A);if(k!==-1){if(S===".git"){let R=b.slice(0,k+1).join(Le.sep);if(f.includes(".git/hooks"))l.push(Le.join(R,"hooks"));else if(f.includes(".git/config"))l.push(Le.join(R,"config"))}else l.push(b.slice(0,k+1).join(Le.sep));x=!0;break}}if(!x)l.push(v)}return[...new Set(l)]}var Wi;function BS(){if(process.getuid?.()!==0||process.env.ARA_SRT_FILE_MASK!=="empty")return"/dev/null";if(Wi)try{let n=j.lstatSync(Wi);if(n.isFile()&&n.size===0&&n.uid===0&&(n.mode&146)===0)return Wi}catch{}let e=j.mkdtempSync(Le.join(Gi(),"claude-empty-file-"));ji.add(e),j.chmodSync(e,493);let t=Le.join(e,"empty");return j.writeFileSync(t,"",{flag:"wx",mode:292}),j.chmodSync(t,292),Wi=t,t}var Hi="/etc/ssh/ssh_config";function PS(e){return`# Added by the sandbox: this sandbox reaches the network only through its proxy.
74
74
  Host * !localhost !127.0.0.1 !::1
75
75
  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
76
76
 
77
77
  Host *
78
- `+e}var Ki;function DS(e,t){let n;try{if(!j.statSync(Hi).isFile())return;n=j.realpathSync(Hi)}catch{return}let r=[Hi,n],i=(s)=>r.some((a)=>a===s||a.startsWith(`${s}/`));for(let s of t){let a=s;try{a=j.realpathSync(s)}catch{}if(i(s)||i(a))return}for(let s of e){let a=et(s).replace(/\/+$/,"");if(a===""||/[*?[{]/.test(a)||i(a))return}if(Ki&&j.existsSync(Ki))return Ki;try{let s=NS(j.readFileSync(Hi,"utf8")),a=j.mkdtempSync(De.join(Gi(),"srt-ssh-config-"));ji.add(a),j.chmodSync(a,493);let o=De.join(a,"ssh_config");return j.writeFileSync(o,s,{flag:"wx",mode:292}),j.chmodSync(o,292),Ki=o,o}catch(s){w(`[Sandbox Linux] ssh_config through the proxy unavailable: ${s.message}`);return}}var qi=new Set,ji=new Set;function Rp(e,t){return e===t?PS():"/dev/null"}var LS="ARA_SRT_MASKED_PATHS",OS=16384;function US(e,t,n=OS){let r=[],i=0;for(let s of new Set(e)){if(s.includes(`
78
+ `+e}var Ki;function NS(e,t){let n;try{if(!j.statSync(Hi).isFile())return;n=j.realpathSync(Hi)}catch{return}let r=[Hi,n],i=(s)=>r.some((a)=>a===s||a.startsWith(`${s}/`));for(let s of t){let a=s;try{a=j.realpathSync(s)}catch{}if(i(s)||i(a))return}for(let s of e){let a=et(s).replace(/\/+$/,"");if(a===""||/[*?[{]/.test(a)||i(a))return}if(Ki&&j.existsSync(Ki))return Ki;try{let s=PS(j.readFileSync(Hi,"utf8")),a=j.mkdtempSync(Le.join(Gi(),"srt-ssh-config-"));ji.add(a),j.chmodSync(a,493);let o=Le.join(a,"ssh_config");return j.writeFileSync(o,s,{flag:"wx",mode:292}),j.chmodSync(o,292),Ki=o,o}catch(s){w(`[Sandbox Linux] ssh_config through the proxy unavailable: ${s.message}`);return}}var qi=new Set,ji=new Set;function Rp(e,t){return e===t?BS():"/dev/null"}var DS="ARA_SRT_MASKED_PATHS",LS=16384;function OS(e,t,n=LS){let r=[],i=0;for(let s of new Set(e)){if(s.includes(`
79
79
  `))continue;if(s!==t&&!s.startsWith(t==="/"?"/":t+"/"))continue;let a=s.split("'").length-1,o=Buffer.byteLength(s)+4*a+(r.length>0?1:0);if(i+o>n)break;r.push(s),i+=o}return r.length>0?r.join(`
80
- `):void 0}function VS(e){try{let t=j.lstatSync(e);return t.isFile()&&t.size===0}catch{return!1}}var Er=0,Bp=!1;function Ia(){if(Bp)return;process.on("exit",()=>{Ba({force:!0})}),Bp=!0}function Ba(e){if(!e?.force){if(Er>0)Er--;if(Er>0){w(`[Sandbox Linux] Deferring mount point cleanup \u2014 ${Er} sandbox(es) still active`);return}}else Er=0;let t=[],n=[];for(let s of qi)try{let a=j.statSync(s);if(a.isFile()&&a.size===0)t.push(s);else if(a.isDirectory())n.push(s)}catch{}let r=(s)=>s.split("/").length;n.sort((s,a)=>r(a)-r(s));let i=tc([...t,...n],(s)=>{try{let a=j.statSync(s);if(a.isFile()&&a.size===0)j.unlinkSync(s),w(`[Sandbox Linux] Cleaned up bwrap mount point (file): ${s}`);else if(a.isDirectory()){if(j.readdirSync(s).length!==0)return;j.rmdirSync(s),w(`[Sandbox Linux] Cleaned up bwrap mount point (dir): ${s}`)}}catch{}});qi.clear();for(let s of i)qi.add(s);for(let s of ji)try{j.rmSync(s,{recursive:!0,force:!0})}catch{}ji.clear(),Wi=void 0,Ki=void 0}function Pp(e){try{return j.accessSync(e,j.constants.X_OK),!0}catch{return!1}}function Dp(e){let{seccompConfig:t,bwrapPath:n,socatPath:r}=e??{},i=[],s=[];if(n){if(!Pp(n))i.push(`bubblewrap (bwrap) not executable at ${n}`)}else if(wr("bwrap")===null)i.push("bubblewrap (bwrap) not installed");if(r){if(!Pp(r))i.push(`socat not executable at ${r}`)}else if(wr("socat")===null)i.push("socat not installed");if(!t?.argv0&&zl(t?.applyPath)===null)s.push("seccomp not available - unix socket access not restricted");return{warnings:s,errors:i}}async function Lp(e,t,n,r,i){let s=n??"socat",a=AS(8).toString("hex"),o=kp(Gi(),`claude-http-${a}.sock`),l=kp(Gi(),`claude-socks-${a}.sock`),c=[`UNIX-LISTEN:${o},fork,reuseaddr`,`TCP:localhost:${e},keepalive,keepidle=10,keepintvl=5,keepcnt=3`];w(`Starting HTTP bridge: ${s} ${c.join(" ")}`);let u=_p(s,c,{stdio:"ignore"});if(u.on("error",(f)=>{w(`HTTP bridge process error: ${f}`,{level:"error"})}),u.on("exit",(f,v)=>{w(`HTTP bridge process exited with code ${f}, signal ${v}`,{level:f===0?"info":"error"})}),!u.pid)throw Error("Failed to start HTTP bridge process");let d,p;if(t===e)d=u,p=o;else{p=l;let f=[`UNIX-LISTEN:${l},fork,reuseaddr`,`TCP:localhost:${t},keepalive,keepidle=10,keepintvl=5,keepcnt=3`];if(w(`Starting SOCKS bridge: ${s} ${f.join(" ")}`),d=_p(s,f,{stdio:"ignore"}),d.on("error",(v)=>{w(`SOCKS bridge process error: ${v}`,{level:"error"})}),d.on("exit",(v,x)=>{w(`SOCKS bridge process exited with code ${v}, signal ${x}`,{level:v===0?"info":"error"})}),!d.pid){if(u.pid)try{process.kill(u.pid,"SIGTERM")}catch{}throw Error("Failed to start SOCKS bridge process")}}let h=200;for(let f=0;f<h;f++){if(!u.pid||u.killed||!d.pid||d.killed)throw Error("Linux bridge process died unexpectedly");try{if(j.existsSync(o)&&j.existsSync(p)){if(r!==void 0){let v=i??r;for(let x of new Set([o,p]))j.chownSync(x,r,v),j.chmodSync(x,384)}w(`Linux bridges ready after ${f+1} attempts`);break}}catch(v){w(`Error checking sockets (attempt ${f+1}): ${v}`,{level:"error"})}if(f===h-1){if(u.pid)try{process.kill(u.pid,"SIGTERM")}catch{}if(d.pid)try{process.kill(d.pid,"SIGTERM")}catch{}throw Error(`Failed to create bridge sockets after ${h} attempts`)}await new Promise((v)=>setTimeout(v,5))}return{httpSocketPath:o,socksSocketPath:p,httpBridgeProcess:u,socksBridgeProcess:d,httpProxyPort:e,socksProxyPort:t}}function FS(e,t){if(t){if(!e)throw Error("seccompConfig.argv0 requires seccompConfig.applyPath");return`ARGV0=${It([t])} ${It([e])} `}let n=zl(e);return n?`${It([n])} `:void 0}function nc(e,t,n){if(n===void 0)return[e,"-c",t];return[e,"-c",`${Op(n)}; exec "$0" "$@"`,e,"-c",t]}function Op(e){if(!Number.isSafeInteger(e)||e<3||e>9)throw Error("bad_start_fd");return`printf . >&${e}; exec ${e}>&-`}function MS(e,t,n,r,i,s,a,o){let l=i||"bash",c=It([s??"socat"]),u=a===void 0?"":` ${a}>&-`,d=["srt_payload_pid=",`${c} TCP4-LISTEN:3128,bind=127.0.0.1,fork,reuseaddr ${It([`UNIX-CONNECT:${e}`])} >/dev/null 2>&1${u} &`,"srt_http_proxy_pid=$!",`${c} TCP4-LISTEN:1080,bind=127.0.0.1,fork,reuseaddr ${It([`UNIX-CONNECT:${t}`])} >/dev/null 2>&1${u} &`,"srt_socks_proxy_pid=$!","srt_cleanup_command() {"," srt_status=$?"," trap - EXIT INT TERM",' if [ -n "$srt_payload_pid" ]; then',' kill -KILL "$srt_payload_pid" 2>/dev/null',' wait "$srt_payload_pid" 2>/dev/null'," fi",' kill -KILL "$srt_http_proxy_pid" "$srt_socks_proxy_pid" 2>/dev/null',' wait "$srt_http_proxy_pid" "$srt_socks_proxy_pid" 2>/dev/null',' exit "$srt_status"',"}","trap srt_cleanup_command EXIT","trap 'exit 143' TERM","trap 'exit 130' INT",...[3128,1080].map((f)=>`{ true <>/dev/tcp/127.0.0.1/${f}; } 2>/dev/null || { ${c} -u OPEN:/dev/null TCP4:127.0.0.1:${f},connect-timeout=0.1,retry=480,interval=0.005 >/dev/null 2>&1${u} & wait "$!"; } || { printf '%s\\n' 'Sandbox proxy listener readiness failed' >&2; exit 1; }`),`kill -0 "$srt_http_proxy_pid" "$srt_socks_proxy_pid" 2>/dev/null || { printf '%s\\n' 'Sandbox proxy listener exited before command' >&2; exit 1; }`],p=r===void 0&&a!==void 0?`{ ${Op(a)}; trap '' INT QUIT; exec ${o?n:It([l,"-c",n])}; }`:(r??"")+It(nc(l,n,a));return[...d,`${p} <&0 &`,"srt_payload_pid=$!",'wait "$srt_payload_pid"',"srt_payload_status=$?","srt_payload_pid=",'exit "$srt_payload_status"'].join(`
81
- `)}function Ra(e){try{if(j.lstatSync(e).isSymbolicLink())return j.realpathSync(e)}catch{}return e}function Np(e,t,n,r){let i=t==="/"?"/":t+"/";e.push("--tmpfs",t);for(let s of n)if(s.startsWith(i)||s===t)e.push("--bind",s,s),w(`[Sandbox Linux] Re-bound write path wiped by denyRead tmpfs: ${s}`);for(let s of r)if(s.startsWith(i)||s===t){if(!j.existsSync(s)){w(`[Sandbox Linux] Skipping non-existent read allow path: ${s}`);continue}if(n.some((a)=>(a.startsWith(i)||a===t)&&(s===a||s.startsWith(a+"/"))))continue;e.push("--ro-bind",s,s),w(`[Sandbox Linux] Re-allowed read access within denied region: ${s}`)}}async function $S(e,t,n,r,i={command:"rg"},s=ic,a=!1,o,l,c=[]){let u=[],d=[],p=[],h=new Set,f=new Map,v=new Map;if(t){u.push("--ro-bind","/","/");for(let F of t.allowOnly||[]){let re=et(F).replace(/\/+$/,"")||"/";if(w(`[Sandbox Linux] Processing write path: ${F} -> ${re}`),re.startsWith("/dev/")){w(`[Sandbox Linux] Skipping /dev path: ${re}`);continue}if(!j.existsSync(re)){w(`[Sandbox Linux] Skipping non-existent write path: ${re}`);continue}try{let Q=j.realpathSync(re),ue=re.replace(/\/+$/,"");if(Q!==ue&&ws(re,Q)){w(`[Sandbox Linux] Skipping symlink write path pointing outside expected location: ${F} -> ${Q}`);continue}}catch{w(`[Sandbox Linux] Skipping write path that could not be resolved: ${re}`);continue}u.push("--bind",re,re),d.push(re)}let D,W=()=>{if(D!==void 0)return D;let F=[];for(let Q of d){F.push(Q);try{let ue=j.realpathSync(Q);if(ue!==Q)F.push(ue)}catch{}}let re=[];if(e){let Q=[],ue=new Set(["proc","dev","sys"]);for(let ce of e.denyOnly||[])if(et(ce)==="/")try{for(let te of j.readdirSync("/"))if(!ue.has(te))Q.push("/"+te)}catch{}else Q.push(ce);if(j.existsSync("/etc/ssh/ssh_config.d"))Q.push("/etc/ssh/ssh_config.d");for(let ce of Q){let te=et(ce),Ie=!1;try{Ie=j.statSync(te).isDirectory()}catch{continue}if(!Ie)continue;re.push(te);try{let We=j.realpathSync(te);if(We!==te)re.push(We)}catch{}}}return D={allowedWritePathsBothForms:F,prospectiveReadDenyTmpfsDirsBothForms:re},D},Z=(F)=>d.some((re)=>F.startsWith(re+"/")||F===re),pe=[...t.denyWithinAllow||[],...await BS(i,s,a,o)];yp();let ge=new Set;for(let F of pe){let re=et(F);if(re.startsWith("/dev/"))continue;let Q=Ip(re);if(Q===null||Q.startsWith("/dev/"))continue;if(rc(Q,d))continue;let ue=!1;try{ue=j.statSync(Q).isDirectory()}catch{continue}if(!ue)continue;if(Z(Q)){let ce=f.get(Q);if(ce===void 0)ce=new Set,f.set(Q,ce);ce.add(re)}}let $e=new Map,xe=(F)=>{let re=$e.get(F);if(re!==void 0)return re;let{allowedWritePathsBothForms:Q,prospectiveReadDenyTmpfsDirsBothForms:ue}=W(),ce=Q.some((te)=>te.startsWith(F+"/"))||ue.some((te)=>te===F||te.startsWith(F+"/"))||ue.some((te)=>[F,...f.get(F)??[]].some((Ie)=>Ie===te||Ie.startsWith(te+"/")));return $e.set(F,ce),ce},Le=[...f.keys()];for(let F of pe){let re=et(F);if(re.startsWith("/dev/"))continue;let Q=Ip(re);if(Q===null){let te=rc(re,d);if(te&&!ge.has(te))ge.add(te),p.push("--ro-bind","/dev/null",te),v.set(te,re);w(`[Sandbox Linux] Deny path could not be resolved through symlinks, failing closed: ${re}`);continue}if(Q!==re)w(`[Sandbox Linux] Resolved symlinked deny path: ${re} -> ${Q}`);if(Q.startsWith("/dev/"))continue;if(ge.has(Q))continue;ge.add(Q);let ue=rc(Q,d);if(ue){if(!ge.has(ue))ge.add(ue),p.push("--ro-bind","/dev/null",ue),v.set(ue,re);w(`[Sandbox Linux] Mounted /dev/null at symlink ${ue} to prevent symlink replacement attack`);continue}if(!j.existsSync(Q)){if(IS(Q)){w(`[Sandbox Linux] Skipping deny path with file ancestor (cannot create paths under a file): ${Q}`);continue}let te=De.dirname(Q);while(te!=="/"&&!j.existsSync(te))te=De.dirname(te);let Ie=Z(te)||Z(Q),We=Le.filter((se)=>te===se||te.startsWith(se+"/")),Xe=We.length>0&&!We.some(xe);if(Ie&&!Xe){let se=RS(Q),me=Ep(se,d)??se;if(me!==Q){if(!h.has(me)){let Oe=Ap(me,l),Ve=j.mkdtempSync(De.join(Gi(),"claude-empty-"));if(j.chmodSync(Ve,365),ji.add(Ve),p.push("--ro-bind",Ve,me),v.set(me,re),h.add(me),Oe.kind==="unregistered")qi.add(me);Ia(),w(`[Sandbox Linux] Mounted empty dir at ${me} to block creation of ${Q}`)}}else{let Oe=ec(me),Ve=Rp(Q,re);if(Oe.kind==="masked")p.push("--ro-bind",Ve,me),v.set(me,re),Ia(),w(`[Sandbox Linux] Masked shared stub at ${me} with ${Ve} to block creation of ${Q}`);else if(Oe.kind==="real")p.push("--ro-bind",me,me),v.set(me,re);else p.push("--ro-bind",Ve,me),v.set(me,re),qi.add(me),Ia(),w(`[Sandbox Linux] Mounted ${Ve} at ${me} to block creation of ${Q}`)}}else if(Xe)w(`[Sandbox Linux] Skipping non-existent deny path inside a read-only denied directory (already uncreatable): ${Q}`);else w(`[Sandbox Linux] Skipping non-existent deny path not within allowed paths: ${Q}`);continue}if(Z(Q)){if((VS(Q)?ec(Q):void 0)?.kind==="masked")p.push("--ro-bind",Rp(Q,re),Q),Ia();else p.push("--ro-bind",Q,Q);v.set(Q,re)}else w(`[Sandbox Linux] Skipping deny path not within allowed paths: ${Q}`)}}else u.push("--bind","/","/");let x=[],S=(e?.allowWithinDeny||[]).map((D)=>et(D)),A=new Map,b=[],k=new Set(["proc","dev","sys"]);for(let D of e?.denyOnly||[])if(et(D)==="/"){for(let W of j.readdirSync("/"))if(!k.has(W))x.push("/"+W)}else x.push(D);if(e&&j.existsSync("/etc/ssh/ssh_config.d"))x.push("/etc/ssh/ssh_config.d");let R=x.map((D)=>et(D)).sort((D,W)=>D.split("/").length-W.split("/").length);for(let D of R){if(!j.existsSync(D)){w(`[Sandbox Linux] Skipping non-existent read deny path: ${D}`);continue}if(j.statSync(D).isDirectory())b.push(D),Np(u,D,d,S);else{if(S.includes(D)){w(`[Sandbox Linux] Skipping read deny for re-allowed path: ${D}`);continue}let Z=Ra(D);u.push("--ro-bind","/dev/null",Z),A.set(Z,"/dev/null"),A.set(D,"/dev/null")}}for(let{realPath:D,fakePath:W}of n??[]){let Z=Ra(D);u.push("--ro-bind",W,Z),A.set(Z,W),A.set(D,W)}let I=(D)=>b.some((W)=>{if(!(D===W||D.startsWith(W+"/")))return!1;return!d.some((ge)=>(ge===W||ge.startsWith(W+"/"))&&(D===ge||D.startsWith(ge+"/")))}),V=[...h].filter((D)=>{let W=v.get(D)??D;return!A.has(D)&&!I(D)&&!I(W)&&!d.some((Z)=>Z===D||Z.startsWith(D+"/"))}),J=[];for(let D=0;D<p.length;D+=3){let W=p[D+2],Z=v.get(W)??W;if(A.has(W))continue;if(I(W)||I(Z)){w(`[Sandbox Linux] Skipping denyWrite bind already hidden by denyRead tmpfs: ${W}`);continue}if(V.some((pe)=>W.startsWith(pe+"/"))){w(`[Sandbox Linux] Skipping denyWrite bind under an empty-directory mask: ${W}`);continue}if(u.push(p[D],p[D+1],W),J.push(W),p[D+1]!==W)c.push(W);if(Z!==W)J.push(Z)}for(let D of b)if(J.some((W)=>D.startsWith(W+"/")))w(`[Sandbox Linux] Re-applying denyRead tmpfs re-exposed by denyWrite bind: ${D}`),Np(u,D,d,S);for(let[D,W]of A)if(J.some((Z)=>D.startsWith(Z+"/"))){if(Ra(D)!==D)continue;w(`[Sandbox Linux] Re-applying file mask re-exposed by denyWrite bind: ${D}`),u.push("--ro-bind",W,D)}if(r!==void 0)u.push("--ro-bind",r,r);return u}async function Up(e){let{command:t,commandId:n,needsNetworkRestriction:r,httpSocketPath:i,socksSocketPath:s,httpProxyPort:a,socksProxyPort:o,proxyAuthToken:l,caCertPath:c,readConfig:u,writeConfig:d,unsetEnvVars:p,setEnvVars:h,maskedFileBinds:f,maskedFileStoreDir:v,enableWeakerNestedSandbox:x,runAsUid:S,runAsGid:A,runAsHostUid:b,runAsHostGid:k,runAsHostHome:R,runAsHostUser:I,setprivPath:V,allowAllUnixSockets:J,binShell:D,ripgrepConfig:W={command:"rg"},mandatoryDenySearchDepth:Z=ic,allowGitConfig:pe=!1,gitSafeDirectories:ge,seccompConfig:$e,bwrapPath:xe,socatPath:Le,observeSocketPath:F,startFd:re,argvCommand:Q,abortSignal:ue}=e,ce=u&&u.denyOnly.length>0||f!==void 0&&f.length>0,te=d!==void 0,Ie=p!==void 0&&p.length>0||h!==void 0&&Object.keys(h).length>0,We=(ge?.length??0)>0;if(!r&&!ce&&!te&&!Ie&&!We)return t;Er++;let Xe=[],se=["--new-session","--die-with-parent"],me=[],Oe,Ve=!1;try{if(!J)if(Oe=FS($e?.applyPath,$e?.argv0),!Oe)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(F&&Oe)if(j.existsSync(F))me.push("--bind",F,F),se.push("--setenv","SRT_OBSERVE_SOCK",F),se.push("--setenv","SRT_ENCODED_CMD",Dt(n??t));else w("[Sandbox Linux] observe socket missing \u2014 supervisor not running; "+"continuing without violation monitoring");if(Ie){for(let At of p??[])se.push("--unsetenv",At);for(let[At,tr]of Object.entries(h??{}))se.push("--setenv",At,tr)}if(ge&&ge.length>0){let At=Ts({safeDirs:ge,unsetEnvVars:p,setEnvVars:h});for(let[tr,Ss]of Object.entries(At))se.push("--setenv",tr,Ss)}if(r){if(se.push("--unshare-net"),i&&s){if(!j.existsSync(i))throw Error(`Linux HTTP bridge socket does not exist: ${i}. The bridge process may have died. Try reinitializing the sandbox.`);if(!j.existsSync(s))throw Error(`Linux SOCKS bridge socket does not exist: ${s}. The bridge process may have died. Try reinitializing the sandbox.`);if(me.push("--bind",i,i),s!==i)me.push("--bind",s,s);Ve=!0;let At=wn(3128,1080,c,l,d===void 0,Dt(n??t));if(se.push(...At.flatMap((tr)=>{let Ss=tr.indexOf("="),o0=tr.slice(0,Ss),l0=tr.slice(Ss+1);return["--setenv",o0,l0]})),a!==void 0)se.push("--setenv","CLAUDE_CODE_HOST_HTTP_PROXY_PORT",String(a));if(o!==void 0)se.push("--setenv","CLAUDE_CODE_HOST_SOCKS_PROXY_PORT",String(o))}}let nt=await $S(u,d,f,v,W,Z,pe,ue,b===void 0?void 0:{uid:b,gid:k??b},Xe);ka(),se.push(...nt);let st=US(Xe,process.cwd());if(st!==void 0)se.push("--setenv",LS,st);if(se.push(...me),Ve){let At=DS(u?.denyOnly??[],(f??[]).flatMap(({realPath:tr})=>[tr,Ra(tr)]));if(At)se.push("--ro-bind",At,Hi)}if(se.push("--dev","/dev"),se.push("--unshare-pid"),!x){if(se.push("--unshare-user","--cap-drop","ALL","--proc","/proc"),!Oe)se.push("--ro-bind","/dev/null","/proc/sysrq-trigger")}else se.push("--unshare-user","--bind","/proc","/proc");if(S!==void 0)se.push("--uid",String(S)),se.push("--gid",String(A??S));if(b!==void 0){if(R)se.push("--setenv","HOME",R);if(I)se.push("--setenv","USER",I),se.push("--setenv","LOGNAME",I)}let at=D||"bash",Qe=wr(at);if(!Qe)throw Error(`Shell '${at}' not found in PATH`);if(se.push("--",Qe,"-c"),r&&i&&s){let At=MS(i,s,t,Oe,Qe,Le,re,Q);se.push(At)}else if(Oe){let At=Oe+It(nc(Qe,t,re));se.push(At)}else se.push(re===void 0?t:`exec ${It(nc(Qe,t,re))}`);let ot=[xe??"bwrap",...se],lt=It(_S({bwrapCommand:ot,uid:b,gid:k,setprivPath:V,unsetEnvVars:p,setEnvVars:h})),ci=[];if(r)ci.push("network");if(ce||te)ci.push("filesystem");if(Ie)ci.push("env");if(Oe)ci.push("seccomp(unix-block)");return w(`[Sandbox Linux] Wrapped command with bwrap (${ci.join(", ")} restrictions)`),lt}catch(nt){if(Er>0)Er--;if(ka(),Er===0)tc([],()=>{});throw nt}}import{spawn as WS}from"child_process";import*as Tr from"path";class Pa{violations=[];totalCount=0;maxSize=100;listeners=new Set;addViolation(e){if(this.violations.push({...e,line:sc(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=Dt(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 Xn(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,s]of Object.entries(n))if(i!=="*"&&t.includes(i)&&s.some((a)=>e.includes(a)))return!0;return!1}function sc(e){return e.replace(/[\x00-\x1f\x7f-\x9f]+/g," ").trim()}function HS(e=!1){let t=process.cwd(),n=[];for(let r of di)n.push(Tr.resolve(t,r)),n.push(`**/${r}`);for(let r of Es())n.push(Tr.resolve(t,r)),n.push(`**/${r}/**`);if(n.push(Tr.resolve(t,".git/hooks")),n.push("**/.git/hooks/**"),!e)n.push(Tr.resolve(t,".git/config")),n.push("**/.git/config");return[...new Set(n)]}var Vp=`_${Math.random().toString(36).slice(2,11)}_SBX`;function KS(e){return`CMD64_${Dt(e)}_END_${Vp}`}function Qn(e){return St(e)?`(regex ${Jt(gi(e))})`:`(subpath ${Jt(e)})`}function cc(e){return gi(e).slice(0,-1)+"(/.*)?$"}function mn(e){return St(e)?`(regex ${Jt(cc(e))})`:`(subpath ${Jt(e)})`}function Fp(e){return e.replace(/\[[^\]]*\]|[*?]+/g,"x")}function oc(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 ac(e){let t=et(e);return{path:t,glob:St(t)}}function Mp(e,t){return e.test(t.glob?Fp(t.path):t.path)}function Na(e,t){let n=e.glob?Fp(e.path):e.path;return n.startsWith(t==="/"?"/":t+"/")&&n!==t}function qS(e,t){return{denies:(e.denyOnly||[]).map(ac),allows:(e.allowWithinDeny||[]).map(ac),writeRoots:(t||[]).map(ac)}}function GS(e){let t=[],n=!1,r=e.allows.filter((i)=>!i.glob).map((i)=>i.path);for(let i of e.denies){if(!i.glob){if(r.some((o)=>i.path.startsWith(o+"/")))t.push(mn(i.path));continue}let s=new RegExp(cc(i.path));if(s.test("/"))n=!0;let a=e.allows.filter((o)=>Mp(s,o)).map((o)=>Qn(o.path));t.push(oc(mn(i.path),a))}return{filters:t,coversRoot:n}}function $p(e){let t=e.split(/[*?[\]]/)[0];if(!t||t==="/")return"/";return t.endsWith("/")?t.slice(0,-1):Tr.dirname(t)}function jS(e,t){let{denies:n,allows:r,writeRoots:i}=e;if(i.length===0)return[];let s=i.filter((d)=>d.glob).map((d)=>new RegExp(gi(d.path))),a=i.filter((d)=>!d.glob).map((d)=>d.path),o=(d)=>a.some((p)=>Na({path:d,glob:!1},p))||s.some((p)=>p.test(d)),l=(d)=>[...r,...i].filter((p)=>Na(p,d)).map((p)=>Qn(p.path)),c=new Set,u=(d)=>{for(let p of d)if(o(p))c.add(`(literal ${Jt(p)})`)};for(let d of n)if(d.glob){let p=$p(d.path);if(!(s.length>0||a.some((x)=>p===x||Na({path:p,glob:!1},x)||Na({path:x,glob:!1},p))))continue;let f=new RegExp(cc(d.path)),v=[...r,...i].filter((x)=>Mp(f,x)).map((x)=>Qn(x.path));if(c.add(oc(mn(d.path),v)),p!=="/")u([p,...lc(p)])}else{if(!o(d.path))continue;c.add(oc(mn(d.path),l(d.path))),u(lc(d.path))}return qr("deny",["file-write-unlink"],c,t)}function qr(e,t,n,r){if(n.size===0)return[];return[`(${e} ${t.join(" ")}`,...[...n].map((i)=>` ${i}`),` (with message "${r}"))`]}function lc(e){let t=[],n=Tr.dirname(e);while(n!=="/"&&n!=="."){t.push(n);let r=Tr.dirname(n);if(r===n)break;n=r}return t}function Wp(e,t){let n=new Set;for(let r of e){let i=et(r);n.add(mn(i));let s;if(St(i)){if(s=$p(i),s==="/")continue;n.add(`(literal ${Jt(s)})`)}else s=i;for(let a of lc(s))n.add(`(literal ${Jt(a)})`)}return qr("deny",["file-write-unlink","file-write-create"],n,t)}function zS(e,t){if(!e)return["(allow file-read*)"];let n=[];n.push("(allow file-read*)");let r=e.denies.some((l)=>l.path==="/"),i=new Set(e.denies.map((l)=>mn(l.path)));n.push(...qr("deny",["file-read*"],i,t));let s=new Set(e.allows.map((l)=>Qn(l.path)));n.push(...qr("allow",["file-read*"],s,t));let a=GS(e);if(n.push(...qr("deny",["file-read*"],new Set(a.filters),t)),r||a.coversRoot)n.push('(allow file-read* (literal "/"))');if(e.denies.length>0)n.push("(allow file-read-metadata"," (vnode-type DIRECTORY))");n.push(...Wp(e.denies.map((l)=>l.path),t));let o=new Set(e.writeRoots.map((l)=>Qn(l.path)));return n.push(...qr("allow",["file-write-unlink","file-write-create"],o,t)),n}function XS(e,t,n=!1){if(!e)return["(allow file-write*)"];let r=[],i=new Set;for(let o of e.allowOnly||[])i.add(Qn(et(o)));r.push(...qr("allow",["file-write*"],i,t));let s=[...e.denyWithinAllow||[],...HS(n)],a=new Set;for(let o of s)a.add(mn(et(o)));return r.push(...qr("deny",["file-write*"],a,t)),r.push(...Wp(s,t)),r}function QS({readConfig:e,writeConfig:t,httpProxyPort:n,socksProxyPort:r,needsNetworkRestriction:i,allowUnixSockets:s,allowAllUnixSockets:a,allowLocalBinding:o,allowMachLookup:l,allowPty:c,allowGitConfig:u=!1,enableWeakerNetworkIsolation:d=!1,allowAppleEvents:p=!1,logTag:h}){let f=["(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")',")","",...d?["; 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"))']:[],...l&&l.length>0?["; User-specified XPC/Mach services",...l.map((x)=>x.endsWith("*")?`(allow mach-lookup (global-name-prefix ${Jt(x.slice(0,-1))}))`:`(allow mach-lookup (global-name ${Jt(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(f.push("; Network"),!i)f.push("(allow network*)");else{if(o)f.push('(allow network-bind (local ip "*:*"))'),f.push('(allow network-inbound (local ip "*:*"))'),f.push('(allow network-outbound (remote ip "localhost:*"))');if(a)f.push("(allow system-socket (socket-domain AF_UNIX))"),f.push('(allow network-bind (local unix-socket (path-regex #"^/")))'),f.push('(allow network-outbound (remote unix-socket (path-regex #"^/")))');else if(s&&s.length>0){f.push("(allow system-socket (socket-domain AF_UNIX))");for(let x of s){let S=et(x);f.push(`(allow network-bind (local unix-socket (subpath ${Jt(S)})))`),f.push(`(allow network-outbound (remote unix-socket (subpath ${Jt(S)})))`)}}if(n!==void 0)f.push(`(allow network-bind (local ip "localhost:${n}"))`),f.push(`(allow network-inbound (local ip "localhost:${n}"))`),f.push(`(allow network-outbound (remote ip "localhost:${n}"))`);if(r!==void 0&&r!==n)f.push(`(allow network-bind (local ip "localhost:${r}"))`),f.push(`(allow network-inbound (local ip "localhost:${r}"))`),f.push(`(allow network-outbound (remote ip "localhost:${r}"))`)}f.push("");let v=e?qS(e,t?.allowOnly):void 0;if(f.push("; File read"),f.push(...zS(v,h)),f.push(""),f.push("; File write"),f.push(...XS(t,h,u)),v){let x=jS(v,h);if(x.length>0)f.push(""),f.push("; File read: keep read-denied paths inside write roots in place"),f.push(...x)}if(c)f.push(""),f.push("; Pseudo-terminal (pty) support"),f.push("(allow pseudo-tty)"),f.push("(allow file-ioctl"),f.push(' (literal "/dev/ptmx")'),f.push(' (regex #"^/dev/ttys")'),f.push(")"),f.push("(allow file-read* file-write*"),f.push(' (literal "/dev/ptmx")'),f.push(' (regex #"^/dev/ttys")'),f.push(")");return f.join(`
82
- `)}function Jt(e){return JSON.stringify(e)}function Hp(e){let{command:t,commandId:n,needsNetworkRestriction:r,httpProxyPort:i,socksProxyPort:s,proxyAuthToken:a,caCertPath:o,allowUnixSockets:l,allowAllUnixSockets:c,allowLocalBinding:u,allowMachLookup:d,readConfig:p,writeConfig:h,unsetEnvVars:f,setEnvVars:v,maskedFileBinds:x,allowPty:S,allowGitConfig:A=!1,gitSafeDirectories:b,enableWeakerNetworkIsolation:k=!1,allowAppleEvents:R=!1,binShell:I}=e,V=p;if(x&&x.length>0)w("[Sandbox macOS] file mask degrades to deny on macOS until the interposer lands"),V={denyOnly:[...p?.denyOnly??[],...x.map((ce)=>ce.realPath)],allowWithinDeny:p?.allowWithinDeny};let J=V&&V.denyOnly.length>0,D=h!==void 0,W=f!==void 0&&f.length>0||v!==void 0&&Object.keys(v).length>0,Z=(b?.length??0)>0;if(!r&&!J&&!D&&!W&&!Z)return t;let pe=n??t,ge=KS(pe),$e=QS({readConfig:V,writeConfig:h,httpProxyPort:i,socksProxyPort:s,needsNetworkRestriction:r,allowUnixSockets:l,allowAllUnixSockets:c,allowLocalBinding:u,allowMachLookup:d,allowPty:S,allowGitConfig:A,enableWeakerNetworkIsolation:k,allowAppleEvents:R,logTag:ge}),xe=wn(i,s,o,a,h===void 0,Dt(pe));if(u&&r){let Ie=(f??[]).includes("JAVA_TOOL_OPTIONS")?"":process.env.JAVA_TOOL_OPTIONS??"",We=Ie.includes("-Djava.net.preferIPv4Stack=true")?Ie:[Ie,"-Djava.net.preferIPv4Stack=true"].filter(Boolean).join(" ");xe.push(`JAVA_TOOL_OPTIONS=${We}`)}if(b&&b.length>0){let ce=Ts({safeDirs:b,unsetEnvVars:f,setEnvVars:v});for(let[te,Ie]of Object.entries(ce))xe.push(`${te}=${Ie}`)}let Le=I||"bash",F=wr(Le);if(!F)throw Error(`Shell '${Le}' not found in PATH`);let re=(f??[]).flatMap((ce)=>["-u",ce]),Q=Object.entries(v??{}).map(([ce,te])=>`${ce}=${te}`),ue=It(["env",...re,...Q,...xe,"/usr/bin/sandbox-exec","-p",$e,F,"-c",t]);return w(`[Sandbox macOS] Applied restrictions - network: ${!!(i||s)}, read: ${V?"allowAllExcept"in V?"allowAllExcept":"denyAllExcept":"none"}, write: ${h?"allowAllExcept"in h?"allowAllExcept":"denyAllExcept":"none"}`),ue}function Kp(e,t,n=(r)=>r){let r=/CMD64_(.+?)_END/,i=/Sandbox:\s+(.+)$/,s=WS("log",["stream","--predicate",`(eventMessage ENDSWITH "${Vp}")`,"--style","compact"]);return s.stdout?.on("data",(a)=>{let o=a.toString().split(`
83
- `),l=o.find((f)=>f.includes("Sandbox:")&&f.includes("deny")),c=o.find((f)=>f.startsWith("CMD64_"));if(!l)return;let u=l.match(i);if(!u?.[1])return;let d=u[1],p,h;if(c){if(h=c.match(r)?.[1],h)try{p=n(tn(h))}catch{}}if(d.includes("mDNSResponder")||d.includes("mach-lookup com.apple.diagnosticd")||d.includes("mach-lookup com.apple.analyticsd"))return;if(Xn(d,p,t))return;e({line:d,command:p,encodedCommand:h,timestamp:new Date})}),s.stderr?.on("data",(a)=>{w(`[Sandbox Monitor] Log stream stderr: ${a.toString()}`)}),s.on("error",(a)=>{w(`[Sandbox Monitor] Failed to start log stream: ${a.message}`)}),s.on("exit",(a)=>{w(`[Sandbox Monitor] Log stream exited with code: ${a}`)}),()=>{w("[Sandbox Monitor] Stopping log monitor"),s.kill("SIGTERM")}}import{randomBytes as YS}from"crypto";import{chmodSync as qp,chownSync as JS,mkdtempSync as ZS,rmSync as eb}from"fs";import{createServer as tb}from"net";import{tmpdir as rb}from"os";import{join as Gp,posix as nb}from"path";import{createInterface as ib}from"readline";function jp(e,t){let{allowWritePaths:n,denyWritePaths:r,ignoreViolations:i,resolveCommandText:s=(b)=>b,consumerUid:a,consumerGid:o}=t,l=ZS(Gp(rb(),"srt-obs-")),c=Gp(l,`s${YS(4).toString("hex")}.sock`),u=(b,k)=>b===k||b.startsWith(k.endsWith("/")?k:k+"/"),d=(b)=>{let k=nb.normalize(b);if(r.some((R)=>u(k,R)))return!0;return!n.some((R)=>u(k,R))},p=(b,k)=>{if(b.observe_init_error){w(`[Sandbox Linux Monitor] observe filter not installed: ${b.observe_init_error}`);return}if(typeof b.path!=="string")return;if(!b.path.startsWith("/"))return;if(!d(b.path))return;let R;if(k)try{R=s(tn(k))}catch{}if(Xn(b.path,R,i))return;let I={line:`deny ${b.syscall??"syscall"} ${b.path}`,command:R,encodedCommand:k,timestamp:new Date};e(I)},h,f=new Promise((b)=>{h=b}),v=c,x=tb((b)=>{let k,R=ib({input:b});R.on("line",(I)=>{if(!I)return;let V;try{V=JSON.parse(I)}catch{return}if(V.encodedCommand&&k===void 0)k=V.encodedCommand;p(V,k??V.encodedCommand)}),b.on("error",()=>R.close()),b.on("close",()=>R.close())});x.on("error",(b)=>{w(`[Sandbox Linux Monitor] listen failed: ${b.message} - violation monitoring disabled`,{level:"warn"}),v=void 0,h()}),x.listen(c,()=>{if(a!==void 0)qp(l,457),JS(c,a,o??a),qp(c,384);h()});let S=new Set;return x.on("connection",(b)=>{S.add(b),b.on("close",()=>S.delete(b))}),{get observeSocketPath(){return v},ready:f,stop:()=>{w("[Sandbox Linux Monitor] stopping");for(let b of S)b.destroy();x.close();try{eb(l,{recursive:!0,force:!0})}catch{}}}}import*as rt from"fs";import*as Qp from"net";import*as tt from"path";import{spawn as sb,spawnSync as ab}from"child_process";import{once as ob}from"events";import{fileURLToPath as lb}from"url";class be extends Error{code;subcommand;constructor(e,t,n){super(t);this.name="WindowsSandboxError",this.code=e,this.subcommand=n}}var Da=[60080,60089],zp=["-NoProfile","-Command"];function La(e){let t=process.env.SystemRoot??"C:\\Windows",n={exe:tt.win32.join(t,"System32","cmd.exe"),args:["/d","/s","/c"]};if(e===void 0||e===null)return n;if(typeof e==="object"){if(!tt.win32.isAbsolute(e.exe))throw new be("bin_shell_invalid",`binShell.exe must be an absolute path (got ${JSON.stringify(e.exe)})`);if(!Array.isArray(e.args))throw new be("bin_shell_invalid",`binShell.args must be an array (got ${JSON.stringify(e.args)})`);return e}let r=tt.win32.basename(e),i=r.toLowerCase(),s=tt.win32.isAbsolute(e);if(!s&&e!==r)throw new be("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(!s)throw new be("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:s?e:"pwsh.exe",args:zp};case"powershell":case"powershell.exe":return{exe:s?e:tt.win32.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe"),args:zp};case"cmd":case"cmd.exe":return s?{exe:e,args:n.args}:n;default:throw new be("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 Yp(){let e=tt.dirname(lb(import.meta.url));return tt.resolve(e,"..","..")}var Jp={x64:"x64",arm64:"arm64"},cb=tt.join(Yp(),"vendor","srt-win",Jp[process.arch]??process.arch,"srt-win.exe");function ub(){let e=Yp(),t=Jp[process.arch],n=[];if(t)n.push(tt.join(e,"vendor","srt-win",t,"srt-win.exe"));n.push(tt.join(e,"vendor","srt-win-src","target","release","srt-win.exe"));for(let r of n)if(rt.existsSync(r))return r;throw new be("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 Zp="--srt-win";function Pt(e){if(e?.path===void 0)throw new be("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(!rt.existsSync(e.path))throw new be("srt_win_not_found",`windows.srtWin.path is set to '${e.path}' but the file does not exist`);return{exe:e.path,prependArgs:[Zp]}}function Gr(e,t={}){let{exe:n,prependArgs:r}=t.srtWin??Pt(),i=ab(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 be("srt_win_timeout",`srt-win ${e.join(" ")} timed out after ${t.timeoutMs??15000}ms`+(i.signal?` (killed by ${i.signal})`:""),e[0]);throw new be("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 dc(e,t={}){let{exe:n,prependArgs:r}=t.srtWin??Pt(),i=t.timeoutMs??15000;return new Promise((s,a)=>{let o=sb(n,[...r,...e],{windowsHide:!0}),l=!1,c=i>0?setTimeout(()=>{l=!0,o.kill()},i):void 0,u="",d="";o.stdout?.setEncoding("utf8").on("data",(p)=>u+=p),o.stderr?.setEncoding("utf8").on("data",(p)=>d+=p),o.stdin?.on("error",()=>{}).end(t.stdin),o.once("error",(p)=>{clearTimeout(c),a(new be("spawn_failed",`srt-win ${e[0]}: spawn failed: ${p.message}`,e[0]))}),o.once("close",(p,h)=>{if(clearTimeout(c),l){a(new be("srt_win_timeout",`srt-win ${e.join(" ")} timed out after ${i}ms`+(h?` (killed by ${h})`:""),e[0]));return}s({status:p,signal:h,stdout:u.trim(),stderr:d.trim()})})})}function eh(e,t){if(t.status!==0)throw new be("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 be("srt_win_bad_json",`srt-win ${e.join(" ")}: unparseable JSON output ${JSON.stringify(t.stdout)}: ${n.message}`,e[0])}}function fc(e,t){return eh(e,Gr(e,t))}async function pc(e,t){return eh(e,await dc(e,t))}function th(e,t){let n=Gr(e,t),r;try{r=JSON.parse(n.stdout)}catch(i){throw new be("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 rh(e){let t=["wfp","status"];if(e)t.push("--sublayer-guid",e);return t}function Oa(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 Ua(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 nh(e={}){let t=["status"];if(e.sublayerGuid)t.push("--sublayer-guid",e.sublayerGuid);let n=fc(t,{srtWin:e.srtWin});return{user:Ua(n.user),wfp:Oa(n.wfp)}}async function ih(e={}){let t=["status"];if(e.sublayerGuid)t.push("--sublayer-guid",e.sublayerGuid);let n=await pc(t,{srtWin:e.srtWin});return{user:Ua(n.user),wfp:Oa(n.wfp)}}function sh(e={}){return Oa(fc(rh(e.sublayerGuid),{srtWin:e.srtWin}))}async function ah(e={}){return Oa(await pc(rh(e.sublayerGuid),{srtWin:e.srtWin}))}async function hc(e={}){let t=e.target,n;if(!t){let[r,i]=e.proxyPortRange??Da;for(let s=0;s<5;s++){let a=Qp.createServer();a.listen(0,"127.0.0.1"),await ob(a,"listening");let o=a.address().port;if(o<r||o>i){n=a,t=`127.0.0.1:${o}`;break}a.close()}if(!t)throw new be("wfp_verify_bind_failed",`verifyWindowsWfpEgress: could not bind a loopback listener outside the WFP permit range [${r},${i}] in 5 attempts`)}try{let r=Gr(["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 be("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 be("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 be("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 gc(e={}){return Ua(fc(["user","status"],{srtWin:e.srtWin}))}async function zi(e={}){return Ua(await pc(["user","status"],{srtWin:e.srtWin}))}function mc(e,t={}){let n=e??gc(t);if(!n.caCertThumb||!n.caCertPem)return null;return{pem:n.caCertPem,thumb:n.caCertThumb}}function db(e,t={}){let n=Gr(["user","trust-ca",e],{timeoutMs:60000,srtWin:t.srtWin});lh(e,n)}async function oh(e,t={}){let n=await dc(["user","trust-ca",e],{timeoutMs:60000,srtWin:t.srtWin});lh(e,n)}function lh(e,t){if(w(`[Sandbox Windows] user trust-ca exit=${t.status}: ${t.stderr||t.stdout}`),t.status!==0)throw new be("trust_ca_failed",`srt-win user trust-ca '${e}' failed (exit ${t.status}): ${t.stderr||t.stdout}`)}function ch(){let e=process.env.ProgramData;if(!e)throw Error("ProgramData is not set");return tt.win32.join(e,"sandbox-runtime")}async function yc(e={}){let t=e.status??await zi({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:ch();if(n&&!rt.existsSync(n))throw Error(`ensurePersistentWindowsCa: state directory ${n} does not exist. Run \`npx sandbox-runtime windows-install\` first.`);let r=e.dir??tt.win32.join(n,"ca"),i=tt.join(r,"ca.json"),s=tt.join(r,"cert.pem"),a=tt.join(r,"key.pem"),o=(e.regenerateWithinDays??30)*24*60*60*1000,l=(x,S)=>{let A=`${x}.tmp.${process.pid}`;rt.writeFileSync(A,S),rt.renameSync(A,x)},c=async(x,S,A,b)=>{l(s,x),l(a,S);let k=b||t.caCertThumb!==A;if(k){let R=tt.join(r,`.trust.${process.pid}.${Date.now()}.pem`);rt.writeFileSync(R,x);try{await oh(R,{srtWin:e.srtWin})}finally{rt.rmSync(R,{force:!0})}}return w(`[Sandbox Windows] persistent CA ${b?"generated":"reused"} (thumb=${A}${k&&!b?", trust reconciled":""})`),{certPem:x,keyPem:S,certPath:s,keyPath:a,thumbprint:A,generated:b,trusted:k}},u=()=>{let x;try{x=JSON.parse(rt.readFileSync(i,"utf8"))}catch(A){w(`[Sandbox Windows] persistent CA ca.json unreadable (${A.message})`,{level:"warn"});return}if(typeof x.certPem!=="string"||typeof x.keyPem!=="string")return;let S=Pi(x.certPem,x.keyPem);if(!S.ok){w(`[Sandbox Windows] persistent CA invalid (${S.reason})`,{level:"warn"});return}return{certPem:x.certPem,keyPem:x.keyPem,thumbprint:S.thumbprint,notAfter:S.notAfter}};if(!e.force){let x=u();if(x&&x.notAfter.getTime()-Date.now()>o)return await c(x.certPem,x.keyPem,x.thumbprint,!1);if(x)w(`[Sandbox Windows] persistent CA expiring ${x.notAfter.toISOString()}; regenerating`,{level:"warn"})}rt.mkdirSync(r,{recursive:!0});try{let x=Date.now()-300000;for(let S of rt.readdirSync(r)){if(!S.includes(".tmp.")&&!S.startsWith(".trust."))continue;let A=tt.join(r,S);if(rt.statSync(A).mtimeMs<x)rt.rmSync(A,{force:!0})}}catch{}let d=oa({cn:"sandbox-runtime persistent CA"});l(i,JSON.stringify({certPem:d.certPem,keyPem:d.keyPem}));let p=u(),{certPem:h,keyPem:f,thumbprint:v}=p??{certPem:d.certPem,keyPem:d.keyPem,thumbprint:Wn(d.certPem)};return await c(h,f,v,!0)}function vc(e){return e.timeoutMs??120000}function uh(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 dh(e){if(e instanceof be&&e.code==="srt_win_timeout")throw new be("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 fh(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 be("install_wfp_failed",`srt-win install: WFP filter install failed: ${t}`);case 14:throw new be("install_user_failed",`srt-win install: sandbox user provisioning failed: ${t}`);case 13:throw new be("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 be("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 be("install_failed",`srt-win install failed (exit ${e.status}): ${t}`)}}function fb(e={}){let t=e.srtWin??Pt(),n;try{n=Gr(uh(e),{timeoutMs:vc(e),srtWin:t})}catch(i){dh(i)}fh(n);let r=nh({sublayerGuid:e.sublayerGuid,srtWin:t});return n.status===10?{...r,cancelled:!0}:r}async function pb(e={}){let t=e.srtWin??Pt(),n;try{n=await dc(uh(e),{timeoutMs:vc(e),srtWin:t})}catch(i){dh(i)}fh(n);let r=await ih({sublayerGuid:e.sublayerGuid,srtWin:t});return n.status===10?{...r,cancelled:!0}:r}function hb(e={}){let t=["uninstall"];if(e.sublayerGuid)t.push("--sublayer-guid",e.sublayerGuid);if(e.keepUser)t.push("--keep-user");let n=Gr(t,{timeoutMs:vc(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 be("uninstall_failed",`srt-win uninstall failed (exit ${n.status}): ${n.stderr||n.stdout}`);return{}}function Va(e,t){let n=new Set;for(let r of e){let i=et(r),s=fi(i);if(pi(i)&&!s){n.add(i);continue}let a=s?rn(i,{caseInsensitive:!0}):[i];for(let o of a){if(!rt.statSync(o,{throwIfNoEntry:!1})){if(t?.mode==="deny"&&!s)n.add(/[\\/]$/.test(r)&&!/[\\/]$/.test(o)?o+"\\":o);continue}n.add(o)}}return[...n]}function gb(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 be("mapped_drive_cwd",r.message??"mapped/network-drive working directory","exec"),{drive:r.drive})}catch{}}return}function xc(e){let t=e.holderPid??process.pid,n=JSON.stringify({denyRead:e.denyRead,denyWrite:e.denyWrite}),r=Gr(["acl","stamp","--holder-pid",`${t}`,"--sandbox-user-sid",e.sandboxUserSid],{timeoutMs:60000,stdin:n,srtWin:e.srtWin});if(w(`[Sandbox Windows] acl stamp exit=${r.status}: ${r.stderr||r.stdout}`),r.status!==0)throw new be("acl_stamp_failed",`srt-win acl stamp exited ${r.status} `+(r.status===2?"(partial \u2014 some inputs skipped)":"(failed)")+`: ${r.stderr||r.stdout}`)}function Fa(e){let t=e.holderPid??process.pid;try{let n=th(["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}}function Sc(e){let t=e.holderPid??process.pid,n=JSON.stringify({read:e.read,write:e.write}),r=Gr(["acl","grant","--holder-pid",`${t}`,"--sandbox-user-sid",e.sandboxUserSid],{timeoutMs:60000,stdin:n,srtWin:e.srtWin});if(w(`[Sandbox Windows] acl grant exit=${r.status}: ${r.stderr||r.stdout}`),r.status!==0)throw new be("acl_grant_failed",`srt-win acl grant exited ${r.status}: ${r.stderr||r.stdout}`)}function Ma(e){let t=e.holderPid??process.pid;try{let n=th(["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 ph(e){let{exe:t,prependArgs:n}=e.srtWin??Pt(),r=mb(wn(e.httpProxyPort,e.socksProxyPort,e.caCertPath?.replace(/\\/g,"/"),e.proxyAuthToken,void 0,Dt(e.commandId??e.command)));delete r.TMPDIR,delete r.NO_PROXY,delete r.no_proxy;let i=hi({safeDirs:[e.cwd??process.cwd(),...e.allowWrite??[],...e.gitSafeDirectories??[]],schannelCa:e.caCertPath!==void 0,baseEnv:e.setEnvVars}),s=[t,...n,"exec"];if(e.quiet!==!1)s.push("--quiet");for(let u of e.denyRead??[])s.push("--deny-read",u);for(let u of e.denyWrite??[])s.push("--deny-write",u);let a={PATH:process.env.PATH,PATHEXT:process.env.PATHEXT,...e.setEnvVars??{},...r,...i};for(let[u,d]of Object.entries(a))if(d!==void 0)s.push("--env",`${u}=${d}`);s.push("--");let o=e.binShell??La(void 0);s.push(o.exe,...o.args,e.command);let l=s.reduce((u,d)=>u+d.length+3,0);if(l>30000)throw new be("argv_too_long",`Windows sandbox argv is ~${l} chars (CreateProcessW limit is 32 767).`);let c={...process.env,...r};return{argv:s,env:c}}function mb(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 uc(e){let t=e?` --sublayer-guid ${e}`:"";return`Windows sandbox needs a one-time install (one UAC prompt):
80
+ `):void 0}function US(e){try{let t=j.lstatSync(e);return t.isFile()&&t.size===0}catch{return!1}}var Er=0,Bp=!1;function Ia(){if(Bp)return;process.on("exit",()=>{Ba({force:!0})}),Bp=!0}function Ba(e){if(!e?.force){if(Er>0)Er--;if(Er>0){w(`[Sandbox Linux] Deferring mount point cleanup \u2014 ${Er} sandbox(es) still active`);return}}else Er=0;let t=[],n=[];for(let s of qi)try{let a=j.statSync(s);if(a.isFile()&&a.size===0)t.push(s);else if(a.isDirectory())n.push(s)}catch{}let r=(s)=>s.split("/").length;n.sort((s,a)=>r(a)-r(s));let i=tc([...t,...n],(s)=>{try{let a=j.statSync(s);if(a.isFile()&&a.size===0)j.unlinkSync(s),w(`[Sandbox Linux] Cleaned up bwrap mount point (file): ${s}`);else if(a.isDirectory()){if(j.readdirSync(s).length!==0)return;j.rmdirSync(s),w(`[Sandbox Linux] Cleaned up bwrap mount point (dir): ${s}`)}}catch{}});qi.clear();for(let s of i)qi.add(s);for(let s of ji)try{j.rmSync(s,{recursive:!0,force:!0})}catch{}ji.clear(),Wi=void 0,Ki=void 0}function Pp(e){try{return j.accessSync(e,j.constants.X_OK),!0}catch{return!1}}function Dp(e){let{seccompConfig:t,bwrapPath:n,socatPath:r}=e??{},i=[],s=[];if(n){if(!Pp(n))i.push(`bubblewrap (bwrap) not executable at ${n}`)}else if(wr("bwrap")===null)i.push("bubblewrap (bwrap) not installed");if(r){if(!Pp(r))i.push(`socat not executable at ${r}`)}else if(wr("socat")===null)i.push("socat not installed");if(!t?.argv0&&zl(t?.applyPath)===null)s.push("seccomp not available - unix socket access not restricted");return{warnings:s,errors:i}}async function Lp(e,t,n,r,i){let s=n??"socat",a=TS(8).toString("hex"),o=kp(Gi(),`claude-http-${a}.sock`),l=kp(Gi(),`claude-socks-${a}.sock`),c=[`UNIX-LISTEN:${o},fork,reuseaddr`,`TCP:localhost:${e},keepalive,keepidle=10,keepintvl=5,keepcnt=3`];w(`Starting HTTP bridge: ${s} ${c.join(" ")}`);let u=_p(s,c,{stdio:"ignore"});if(u.on("error",(f)=>{w(`HTTP bridge process error: ${f}`,{level:"error"})}),u.on("exit",(f,v)=>{w(`HTTP bridge process exited with code ${f}, signal ${v}`,{level:f===0?"info":"error"})}),!u.pid)throw Error("Failed to start HTTP bridge process");let d,p;if(t===e)d=u,p=o;else{p=l;let f=[`UNIX-LISTEN:${l},fork,reuseaddr`,`TCP:localhost:${t},keepalive,keepidle=10,keepintvl=5,keepcnt=3`];if(w(`Starting SOCKS bridge: ${s} ${f.join(" ")}`),d=_p(s,f,{stdio:"ignore"}),d.on("error",(v)=>{w(`SOCKS bridge process error: ${v}`,{level:"error"})}),d.on("exit",(v,x)=>{w(`SOCKS bridge process exited with code ${v}, signal ${x}`,{level:v===0?"info":"error"})}),!d.pid){if(u.pid)try{process.kill(u.pid,"SIGTERM")}catch{}throw Error("Failed to start SOCKS bridge process")}}let h=200;for(let f=0;f<h;f++){if(!u.pid||u.killed||!d.pid||d.killed)throw Error("Linux bridge process died unexpectedly");try{if(j.existsSync(o)&&j.existsSync(p)){if(r!==void 0){let v=i??r;for(let x of new Set([o,p]))j.chownSync(x,r,v),j.chmodSync(x,384)}w(`Linux bridges ready after ${f+1} attempts`);break}}catch(v){w(`Error checking sockets (attempt ${f+1}): ${v}`,{level:"error"})}if(f===h-1){if(u.pid)try{process.kill(u.pid,"SIGTERM")}catch{}if(d.pid)try{process.kill(d.pid,"SIGTERM")}catch{}throw Error(`Failed to create bridge sockets after ${h} attempts`)}await new Promise((v)=>setTimeout(v,5))}return{httpSocketPath:o,socksSocketPath:p,httpBridgeProcess:u,socksBridgeProcess:d,httpProxyPort:e,socksProxyPort:t}}function VS(e,t){if(t){if(!e)throw Error("seccompConfig.argv0 requires seccompConfig.applyPath");return`ARGV0=${kt([t])} ${kt([e])} `}let n=zl(e);return n?`${kt([n])} `:void 0}function nc(e,t,n){if(n===void 0)return[e,"-c",t];return[e,"-c",`${Op(n)}; exec "$0" "$@"`,e,"-c",t]}function Op(e){if(!Number.isSafeInteger(e)||e<3||e>9)throw Error("bad_start_fd");return`printf . >&${e}; exec ${e}>&-`}function FS(e,t,n,r,i,s,a,o){let l=i||"bash",c=kt([s??"socat"]),u=a===void 0?"":` ${a}>&-`,d=["srt_payload_pid=",`${c} TCP4-LISTEN:3128,bind=127.0.0.1,fork,reuseaddr ${kt([`UNIX-CONNECT:${e}`])} >/dev/null 2>&1${u} &`,"srt_http_proxy_pid=$!",`${c} TCP4-LISTEN:1080,bind=127.0.0.1,fork,reuseaddr ${kt([`UNIX-CONNECT:${t}`])} >/dev/null 2>&1${u} &`,"srt_socks_proxy_pid=$!","srt_cleanup_command() {"," srt_status=$?"," trap - EXIT INT TERM",' if [ -n "$srt_payload_pid" ]; then',' kill -KILL "$srt_payload_pid" 2>/dev/null',' wait "$srt_payload_pid" 2>/dev/null'," fi",' kill -KILL "$srt_http_proxy_pid" "$srt_socks_proxy_pid" 2>/dev/null',' wait "$srt_http_proxy_pid" "$srt_socks_proxy_pid" 2>/dev/null',' exit "$srt_status"',"}","trap srt_cleanup_command EXIT","trap 'exit 143' TERM","trap 'exit 130' INT",...[3128,1080].map((f)=>`{ true <>/dev/tcp/127.0.0.1/${f}; } 2>/dev/null || { ${c} -u OPEN:/dev/null TCP4:127.0.0.1:${f},connect-timeout=0.1,retry=480,interval=0.005 >/dev/null 2>&1${u} & wait "$!"; } || { printf '%s\\n' 'Sandbox proxy listener readiness failed' >&2; exit 1; }`),`kill -0 "$srt_http_proxy_pid" "$srt_socks_proxy_pid" 2>/dev/null || { printf '%s\\n' 'Sandbox proxy listener exited before command' >&2; exit 1; }`],p=r===void 0&&a!==void 0?`{ ${Op(a)}; trap '' INT QUIT; exec ${o?n:kt([l,"-c",n])}; }`:(r??"")+kt(nc(l,n,a));return[...d,`${p} <&0 &`,"srt_payload_pid=$!",'wait "$srt_payload_pid"',"srt_payload_status=$?","srt_payload_pid=",'exit "$srt_payload_status"'].join(`
81
+ `)}function Ra(e){try{if(j.lstatSync(e).isSymbolicLink())return j.realpathSync(e)}catch{}return e}function Np(e,t,n,r){let i=t==="/"?"/":t+"/";e.push("--tmpfs",t);for(let s of n)if(s.startsWith(i)||s===t)e.push("--bind",s,s),w(`[Sandbox Linux] Re-bound write path wiped by denyRead tmpfs: ${s}`);for(let s of r)if(s.startsWith(i)||s===t){if(!j.existsSync(s)){w(`[Sandbox Linux] Skipping non-existent read allow path: ${s}`);continue}if(n.some((a)=>(a.startsWith(i)||a===t)&&(s===a||s.startsWith(a+"/"))))continue;e.push("--ro-bind",s,s),w(`[Sandbox Linux] Re-allowed read access within denied region: ${s}`)}}async function MS(e,t,n,r,i={command:"rg"},s=ic,a=!1,o,l,c=[]){let u=[],d=[],p=[],h=new Set,f=new Map,v=new Map;if(t){u.push("--ro-bind","/","/");for(let F of t.allowOnly||[]){let re=et(F).replace(/\/+$/,"")||"/";if(w(`[Sandbox Linux] Processing write path: ${F} -> ${re}`),re.startsWith("/dev/")){w(`[Sandbox Linux] Skipping /dev path: ${re}`);continue}if(!j.existsSync(re)){w(`[Sandbox Linux] Skipping non-existent write path: ${re}`);continue}try{let Q=j.realpathSync(re),ue=re.replace(/\/+$/,"");if(Q!==ue&&ws(re,Q)){w(`[Sandbox Linux] Skipping symlink write path pointing outside expected location: ${F} -> ${Q}`);continue}}catch{w(`[Sandbox Linux] Skipping write path that could not be resolved: ${re}`);continue}u.push("--bind",re,re),d.push(re)}let D,W=()=>{if(D!==void 0)return D;let F=[];for(let Q of d){F.push(Q);try{let ue=j.realpathSync(Q);if(ue!==Q)F.push(ue)}catch{}}let re=[];if(e){let Q=[],ue=new Set(["proc","dev","sys"]);for(let ce of e.denyOnly||[])if(et(ce)==="/")try{for(let te of j.readdirSync("/"))if(!ue.has(te))Q.push("/"+te)}catch{}else Q.push(ce);if(j.existsSync("/etc/ssh/ssh_config.d"))Q.push("/etc/ssh/ssh_config.d");for(let ce of Q){let te=et(ce),Ie=!1;try{Ie=j.statSync(te).isDirectory()}catch{continue}if(!Ie)continue;re.push(te);try{let $e=j.realpathSync(te);if($e!==te)re.push($e)}catch{}}}return D={allowedWritePathsBothForms:F,prospectiveReadDenyTmpfsDirsBothForms:re},D},Z=(F)=>d.some((re)=>F.startsWith(re+"/")||F===re),pe=[...t.denyWithinAllow||[],...await RS(i,s,a,o)];yp();let ge=new Set;for(let F of pe){let re=et(F);if(re.startsWith("/dev/"))continue;let Q=Ip(re);if(Q===null||Q.startsWith("/dev/"))continue;if(rc(Q,d))continue;let ue=!1;try{ue=j.statSync(Q).isDirectory()}catch{continue}if(!ue)continue;if(Z(Q)){let ce=f.get(Q);if(ce===void 0)ce=new Set,f.set(Q,ce);ce.add(re)}}let Me=new Map,ve=(F)=>{let re=Me.get(F);if(re!==void 0)return re;let{allowedWritePathsBothForms:Q,prospectiveReadDenyTmpfsDirsBothForms:ue}=W(),ce=Q.some((te)=>te.startsWith(F+"/"))||ue.some((te)=>te===F||te.startsWith(F+"/"))||ue.some((te)=>[F,...f.get(F)??[]].some((Ie)=>Ie===te||Ie.startsWith(te+"/")));return Me.set(F,ce),ce},Oe=[...f.keys()];for(let F of pe){let re=et(F);if(re.startsWith("/dev/"))continue;let Q=Ip(re);if(Q===null){let te=rc(re,d);if(te&&!ge.has(te))ge.add(te),p.push("--ro-bind","/dev/null",te),v.set(te,re);w(`[Sandbox Linux] Deny path could not be resolved through symlinks, failing closed: ${re}`);continue}if(Q!==re)w(`[Sandbox Linux] Resolved symlinked deny path: ${re} -> ${Q}`);if(Q.startsWith("/dev/"))continue;if(ge.has(Q))continue;ge.add(Q);let ue=rc(Q,d);if(ue){if(!ge.has(ue))ge.add(ue),p.push("--ro-bind","/dev/null",ue),v.set(ue,re);w(`[Sandbox Linux] Mounted /dev/null at symlink ${ue} to prevent symlink replacement attack`);continue}if(!j.existsSync(Q)){if(kS(Q)){w(`[Sandbox Linux] Skipping deny path with file ancestor (cannot create paths under a file): ${Q}`);continue}let te=Le.dirname(Q);while(te!=="/"&&!j.existsSync(te))te=Le.dirname(te);let Ie=Z(te)||Z(Q),$e=Oe.filter((xe)=>te===xe||te.startsWith(xe+"/")),Xe=$e.length>0&&!$e.some(ve);if(Ie&&!Xe){let xe=IS(Q),ae=Ep(xe,d)??xe;if(ae!==Q){if(!h.has(ae)){let We=Ap(ae,l),Re=j.mkdtempSync(Le.join(Gi(),"claude-empty-"));if(j.chmodSync(Re,365),ji.add(Re),p.push("--ro-bind",Re,ae),v.set(ae,re),h.add(ae),We.kind==="unregistered")qi.add(ae);Ia(),w(`[Sandbox Linux] Mounted empty dir at ${ae} to block creation of ${Q}`)}}else{let We=ec(ae),Re=Rp(Q,re);if(We.kind==="masked")p.push("--ro-bind",Re,ae),v.set(ae,re),Ia(),w(`[Sandbox Linux] Masked shared stub at ${ae} with ${Re} to block creation of ${Q}`);else if(We.kind==="real")p.push("--ro-bind",ae,ae),v.set(ae,re);else p.push("--ro-bind",Re,ae),v.set(ae,re),qi.add(ae),Ia(),w(`[Sandbox Linux] Mounted ${Re} at ${ae} to block creation of ${Q}`)}}else if(Xe)w(`[Sandbox Linux] Skipping non-existent deny path inside a read-only denied directory (already uncreatable): ${Q}`);else w(`[Sandbox Linux] Skipping non-existent deny path not within allowed paths: ${Q}`);continue}if(Z(Q)){if((US(Q)?ec(Q):void 0)?.kind==="masked")p.push("--ro-bind",Rp(Q,re),Q),Ia();else p.push("--ro-bind",Q,Q);v.set(Q,re)}else w(`[Sandbox Linux] Skipping deny path not within allowed paths: ${Q}`)}}else u.push("--bind","/","/");let x=[],S=(e?.allowWithinDeny||[]).map((D)=>et(D)),A=new Map,b=[],k=new Set(["proc","dev","sys"]);for(let D of e?.denyOnly||[])if(et(D)==="/"){for(let W of j.readdirSync("/"))if(!k.has(W))x.push("/"+W)}else x.push(D);if(e&&j.existsSync("/etc/ssh/ssh_config.d"))x.push("/etc/ssh/ssh_config.d");let R=x.map((D)=>et(D)).sort((D,W)=>D.split("/").length-W.split("/").length);for(let D of R){if(!j.existsSync(D)){w(`[Sandbox Linux] Skipping non-existent read deny path: ${D}`);continue}if(j.statSync(D).isDirectory())b.push(D),Np(u,D,d,S);else{if(S.includes(D)){w(`[Sandbox Linux] Skipping read deny for re-allowed path: ${D}`);continue}let Z=Ra(D);u.push("--ro-bind","/dev/null",Z),A.set(Z,"/dev/null"),A.set(D,"/dev/null")}}for(let{realPath:D,fakePath:W}of n??[]){let Z=Ra(D);u.push("--ro-bind",W,Z),A.set(Z,W),A.set(D,W)}let I=(D)=>b.some((W)=>{if(!(D===W||D.startsWith(W+"/")))return!1;return!d.some((ge)=>(ge===W||ge.startsWith(W+"/"))&&(D===ge||D.startsWith(ge+"/")))}),V=[...h].filter((D)=>{let W=v.get(D)??D;return!A.has(D)&&!I(D)&&!I(W)&&!d.some((Z)=>Z===D||Z.startsWith(D+"/"))}),J=[];for(let D=0;D<p.length;D+=3){let W=p[D+2],Z=v.get(W)??W;if(A.has(W))continue;if(I(W)||I(Z)){w(`[Sandbox Linux] Skipping denyWrite bind already hidden by denyRead tmpfs: ${W}`);continue}if(V.some((pe)=>W.startsWith(pe+"/"))){w(`[Sandbox Linux] Skipping denyWrite bind under an empty-directory mask: ${W}`);continue}if(u.push(p[D],p[D+1],W),J.push(W),p[D+1]!==W)c.push(W);if(Z!==W)J.push(Z)}for(let D of b)if(J.some((W)=>D.startsWith(W+"/")))w(`[Sandbox Linux] Re-applying denyRead tmpfs re-exposed by denyWrite bind: ${D}`),Np(u,D,d,S);for(let[D,W]of A)if(J.some((Z)=>D.startsWith(Z+"/"))){if(Ra(D)!==D)continue;w(`[Sandbox Linux] Re-applying file mask re-exposed by denyWrite bind: ${D}`),u.push("--ro-bind",W,D)}if(r!==void 0)u.push("--ro-bind",r,r);return u}async function Up(e){let{command:t,commandId:n,needsNetworkRestriction:r,httpSocketPath:i,socksSocketPath:s,httpProxyPort:a,socksProxyPort:o,proxyAuthToken:l,caCertPath:c,readConfig:u,writeConfig:d,unsetEnvVars:p,setEnvVars:h,maskedFileBinds:f,maskedFileStoreDir:v,enableWeakerNestedSandbox:x,runAsUid:S,runAsGid:A,runAsHostUid:b,runAsHostGid:k,runAsHostHome:R,runAsHostUser:I,setprivPath:V,allowAllUnixSockets:J,binShell:D,ripgrepConfig:W={command:"rg"},mandatoryDenySearchDepth:Z=ic,allowGitConfig:pe=!1,gitSafeDirectories:ge,seccompConfig:Me,bwrapPath:ve,socatPath:Oe,observeSocketPath:F,startFd:re,argvCommand:Q,abortSignal:ue}=e,ce=u&&u.denyOnly.length>0||f!==void 0&&f.length>0,te=d!==void 0,Ie=p!==void 0&&p.length>0||h!==void 0&&Object.keys(h).length>0,$e=(ge?.length??0)>0;if(!r&&!ce&&!te&&!Ie&&!$e)return t;Er++;let Xe=[],xe=["--new-session","--die-with-parent"],ae=new Map,We=[],Re,st=!1;try{if(!J)if(Re=VS(Me?.applyPath,Me?.argv0),!Re)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(F&&Re)if(j.existsSync(F))We.push("--bind",F,F),ae.set("SRT_OBSERVE_SOCK",F),ae.set("SRT_ENCODED_CMD",Dt(n??t));else w("[Sandbox Linux] observe socket missing \u2014 supervisor not running; "+"continuing without violation monitoring");if(Ie)for(let[Nt,tr]of Object.entries(h??{}))ae.set(Nt,tr);if(ge&&ge.length>0){let Nt=Ts({safeDirs:ge,unsetEnvVars:p,setEnvVars:h});for(let[tr,Ss]of Object.entries(Nt))ae.set(tr,Ss)}if(r){if(xe.push("--unshare-net"),i&&s){if(!j.existsSync(i))throw Error(`Linux HTTP bridge socket does not exist: ${i}. The bridge process may have died. Try reinitializing the sandbox.`);if(!j.existsSync(s))throw Error(`Linux SOCKS bridge socket does not exist: ${s}. The bridge process may have died. Try reinitializing the sandbox.`);if(We.push("--bind",i,i),s!==i)We.push("--bind",s,s);st=!0;let Nt=wn(3128,1080,c,l,d===void 0,Dt(n??t));for(let tr of Nt){let Ss=tr.indexOf("=");ae.set(tr.slice(0,Ss),tr.slice(Ss+1))}if(a!==void 0)ae.set("CLAUDE_CODE_HOST_HTTP_PROXY_PORT",String(a));if(o!==void 0)ae.set("CLAUDE_CODE_HOST_SOCKS_PROXY_PORT",String(o))}}let nt=await MS(u,d,f,v,W,Z,pe,ue,b===void 0?void 0:{uid:b,gid:k??b},Xe);ka(),xe.push(...nt);let at=OS(Xe,process.cwd());if(at!==void 0)ae.set(DS,at);if(xe.push(...We),st){let Nt=NS(u?.denyOnly??[],(f??[]).flatMap(({realPath:tr})=>[tr,Ra(tr)]));if(Nt)xe.push("--ro-bind",Nt,Hi)}if(xe.push("--dev","/dev"),xe.push("--unshare-pid"),!x){if(xe.push("--unshare-user","--cap-drop","ALL","--proc","/proc"),!Re)xe.push("--ro-bind","/dev/null","/proc/sysrq-trigger")}else xe.push("--unshare-user","--bind","/proc","/proc");if(S!==void 0)xe.push("--uid",String(S)),xe.push("--gid",String(A??S));if(b!==void 0){if(R)ae.set("HOME",R);if(I)ae.set("USER",I),ae.set("LOGNAME",I)}let ot=D||"bash",Qe=wr(ot);if(!Qe)throw Error(`Shell '${ot}' not found in PATH`);if(xe.push("--",Qe,"-c"),r&&i&&s){let Nt=FS(i,s,t,Re,Qe,Oe,re,Q);xe.push(Nt)}else if(Re){let Nt=Re+kt(nc(Qe,t,re));xe.push(Nt)}else xe.push(re===void 0?t:`exec ${kt(nc(Qe,t,re))}`);let lt=[ve??"bwrap",...xe],o0=kt(AS({bwrapCommand:lt,uid:b,gid:k,setprivPath:V,unsetEnvVars:p,setEnvVars:Object.fromEntries(ae)})),ci=[];if(r)ci.push("network");if(ce||te)ci.push("filesystem");if(Ie)ci.push("env");if(Re)ci.push("seccomp(unix-block)");return w(`[Sandbox Linux] Wrapped command with bwrap (${ci.join(", ")} restrictions)`),o0}catch(nt){if(Er>0)Er--;if(ka(),Er===0)tc([],()=>{});throw nt}}import{spawn as $S}from"child_process";import*as Tr from"path";class Pa{violations=[];totalCount=0;maxSize=100;listeners=new Set;addViolation(e){if(this.violations.push({...e,line:sc(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=Dt(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 Xn(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,s]of Object.entries(n))if(i!=="*"&&t.includes(i)&&s.some((a)=>e.includes(a)))return!0;return!1}function sc(e){return e.replace(/[\x00-\x1f\x7f-\x9f]+/g," ").trim()}function WS(e=!1){let t=process.cwd(),n=[];for(let r of di)n.push(Tr.resolve(t,r)),n.push(`**/${r}`);for(let r of Es())n.push(Tr.resolve(t,r)),n.push(`**/${r}/**`);if(n.push(Tr.resolve(t,".git/hooks")),n.push("**/.git/hooks/**"),!e)n.push(Tr.resolve(t,".git/config")),n.push("**/.git/config");return[...new Set(n)]}var Vp=`_${Math.random().toString(36).slice(2,11)}_SBX`;function HS(e){return`CMD64_${Dt(e)}_END_${Vp}`}function Qn(e){return St(e)?`(regex ${Jt(gi(e))})`:`(subpath ${Jt(e)})`}function cc(e){return gi(e).slice(0,-1)+"(/.*)?$"}function mn(e){return St(e)?`(regex ${Jt(cc(e))})`:`(subpath ${Jt(e)})`}function Fp(e){return e.replace(/\[[^\]]*\]|[*?]+/g,"x")}function oc(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 ac(e){let t=et(e);return{path:t,glob:St(t)}}function Mp(e,t){return e.test(t.glob?Fp(t.path):t.path)}function Na(e,t){let n=e.glob?Fp(e.path):e.path;return n.startsWith(t==="/"?"/":t+"/")&&n!==t}function KS(e,t){return{denies:(e.denyOnly||[]).map(ac),allows:(e.allowWithinDeny||[]).map(ac),writeRoots:(t||[]).map(ac)}}function qS(e){let t=[],n=!1,r=e.allows.filter((i)=>!i.glob).map((i)=>i.path);for(let i of e.denies){if(!i.glob){if(r.some((o)=>i.path.startsWith(o+"/")))t.push(mn(i.path));continue}let s=new RegExp(cc(i.path));if(s.test("/"))n=!0;let a=e.allows.filter((o)=>Mp(s,o)).map((o)=>Qn(o.path));t.push(oc(mn(i.path),a))}return{filters:t,coversRoot:n}}function $p(e){let t=e.split(/[*?[\]]/)[0];if(!t||t==="/")return"/";return t.endsWith("/")?t.slice(0,-1):Tr.dirname(t)}function GS(e,t){let{denies:n,allows:r,writeRoots:i}=e;if(i.length===0)return[];let s=i.filter((d)=>d.glob).map((d)=>new RegExp(gi(d.path))),a=i.filter((d)=>!d.glob).map((d)=>d.path),o=(d)=>a.some((p)=>Na({path:d,glob:!1},p))||s.some((p)=>p.test(d)),l=(d)=>[...r,...i].filter((p)=>Na(p,d)).map((p)=>Qn(p.path)),c=new Set,u=(d)=>{for(let p of d)if(o(p))c.add(`(literal ${Jt(p)})`)};for(let d of n)if(d.glob){let p=$p(d.path);if(!(s.length>0||a.some((x)=>p===x||Na({path:p,glob:!1},x)||Na({path:x,glob:!1},p))))continue;let f=new RegExp(cc(d.path)),v=[...r,...i].filter((x)=>Mp(f,x)).map((x)=>Qn(x.path));if(c.add(oc(mn(d.path),v)),p!=="/")u([p,...lc(p)])}else{if(!o(d.path))continue;c.add(oc(mn(d.path),l(d.path))),u(lc(d.path))}return qr("deny",["file-write-unlink"],c,t)}function qr(e,t,n,r){if(n.size===0)return[];return[`(${e} ${t.join(" ")}`,...[...n].map((i)=>` ${i}`),` (with message "${r}"))`]}function lc(e){let t=[],n=Tr.dirname(e);while(n!=="/"&&n!=="."){t.push(n);let r=Tr.dirname(n);if(r===n)break;n=r}return t}function Wp(e,t){let n=new Set;for(let r of e){let i=et(r);n.add(mn(i));let s;if(St(i)){if(s=$p(i),s==="/")continue;n.add(`(literal ${Jt(s)})`)}else s=i;for(let a of lc(s))n.add(`(literal ${Jt(a)})`)}return qr("deny",["file-write-unlink","file-write-create"],n,t)}function jS(e,t){if(!e)return["(allow file-read*)"];let n=[];n.push("(allow file-read*)");let r=e.denies.some((l)=>l.path==="/"),i=new Set(e.denies.map((l)=>mn(l.path)));n.push(...qr("deny",["file-read*"],i,t));let s=new Set(e.allows.map((l)=>Qn(l.path)));n.push(...qr("allow",["file-read*"],s,t));let a=qS(e);if(n.push(...qr("deny",["file-read*"],new Set(a.filters),t)),r||a.coversRoot)n.push('(allow file-read* (literal "/"))');if(e.denies.length>0)n.push("(allow file-read-metadata"," (vnode-type DIRECTORY))");n.push(...Wp(e.denies.map((l)=>l.path),t));let o=new Set(e.writeRoots.map((l)=>Qn(l.path)));return n.push(...qr("allow",["file-write-unlink","file-write-create"],o,t)),n}function zS(e,t,n=!1){if(!e)return["(allow file-write*)"];let r=[],i=new Set;for(let o of e.allowOnly||[])i.add(Qn(et(o)));r.push(...qr("allow",["file-write*"],i,t));let s=[...e.denyWithinAllow||[],...WS(n)],a=new Set;for(let o of s)a.add(mn(et(o)));return r.push(...qr("deny",["file-write*"],a,t)),r.push(...Wp(s,t)),r}function XS({readConfig:e,writeConfig:t,httpProxyPort:n,socksProxyPort:r,needsNetworkRestriction:i,allowUnixSockets:s,allowAllUnixSockets:a,allowLocalBinding:o,allowMachLookup:l,allowPty:c,allowGitConfig:u=!1,enableWeakerNetworkIsolation:d=!1,allowAppleEvents:p=!1,logTag:h}){let f=["(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")',")","",...d?["; 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"))']:[],...l&&l.length>0?["; User-specified XPC/Mach services",...l.map((x)=>x.endsWith("*")?`(allow mach-lookup (global-name-prefix ${Jt(x.slice(0,-1))}))`:`(allow mach-lookup (global-name ${Jt(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(f.push("; Network"),!i)f.push("(allow network*)");else{if(o)f.push('(allow network-bind (local ip "*:*"))'),f.push('(allow network-inbound (local ip "*:*"))'),f.push('(allow network-outbound (remote ip "localhost:*"))');if(a)f.push("(allow system-socket (socket-domain AF_UNIX))"),f.push('(allow network-bind (local unix-socket (path-regex #"^/")))'),f.push('(allow network-outbound (remote unix-socket (path-regex #"^/")))');else if(s&&s.length>0){f.push("(allow system-socket (socket-domain AF_UNIX))");for(let x of s){let S=et(x);f.push(`(allow network-bind (local unix-socket (subpath ${Jt(S)})))`),f.push(`(allow network-outbound (remote unix-socket (subpath ${Jt(S)})))`)}}if(n!==void 0)f.push(`(allow network-bind (local ip "localhost:${n}"))`),f.push(`(allow network-inbound (local ip "localhost:${n}"))`),f.push(`(allow network-outbound (remote ip "localhost:${n}"))`);if(r!==void 0&&r!==n)f.push(`(allow network-bind (local ip "localhost:${r}"))`),f.push(`(allow network-inbound (local ip "localhost:${r}"))`),f.push(`(allow network-outbound (remote ip "localhost:${r}"))`)}f.push("");let v=e?KS(e,t?.allowOnly):void 0;if(f.push("; File read"),f.push(...jS(v,h)),f.push(""),f.push("; File write"),f.push(...zS(t,h,u)),v){let x=GS(v,h);if(x.length>0)f.push(""),f.push("; File read: keep read-denied paths inside write roots in place"),f.push(...x)}if(c)f.push(""),f.push("; Pseudo-terminal (pty) support"),f.push("(allow pseudo-tty)"),f.push("(allow file-ioctl"),f.push(' (literal "/dev/ptmx")'),f.push(' (regex #"^/dev/ttys")'),f.push(")"),f.push("(allow file-read* file-write*"),f.push(' (literal "/dev/ptmx")'),f.push(' (regex #"^/dev/ttys")'),f.push(")");return f.join(`
82
+ `)}function Jt(e){return JSON.stringify(e)}function Hp(e){let{command:t,commandId:n,needsNetworkRestriction:r,httpProxyPort:i,socksProxyPort:s,proxyAuthToken:a,caCertPath:o,allowUnixSockets:l,allowAllUnixSockets:c,allowLocalBinding:u,allowMachLookup:d,readConfig:p,writeConfig:h,unsetEnvVars:f,setEnvVars:v,maskedFileBinds:x,allowPty:S,allowGitConfig:A=!1,gitSafeDirectories:b,enableWeakerNetworkIsolation:k=!1,allowAppleEvents:R=!1,binShell:I}=e,V=p;if(x&&x.length>0)w("[Sandbox macOS] file mask degrades to deny on macOS until the interposer lands"),V={denyOnly:[...p?.denyOnly??[],...x.map((ce)=>ce.realPath)],allowWithinDeny:p?.allowWithinDeny};let J=V&&V.denyOnly.length>0,D=h!==void 0,W=f!==void 0&&f.length>0||v!==void 0&&Object.keys(v).length>0,Z=(b?.length??0)>0;if(!r&&!J&&!D&&!W&&!Z)return t;let pe=n??t,ge=HS(pe),Me=XS({readConfig:V,writeConfig:h,httpProxyPort:i,socksProxyPort:s,needsNetworkRestriction:r,allowUnixSockets:l,allowAllUnixSockets:c,allowLocalBinding:u,allowMachLookup:d,allowPty:S,allowGitConfig:A,enableWeakerNetworkIsolation:k,allowAppleEvents:R,logTag:ge}),ve=wn(i,s,o,a,h===void 0,Dt(pe));if(u&&r){let Ie=(f??[]).includes("JAVA_TOOL_OPTIONS")?"":process.env.JAVA_TOOL_OPTIONS??"",$e=Ie.includes("-Djava.net.preferIPv4Stack=true")?Ie:[Ie,"-Djava.net.preferIPv4Stack=true"].filter(Boolean).join(" ");ve.push(`JAVA_TOOL_OPTIONS=${$e}`)}if(b&&b.length>0){let ce=Ts({safeDirs:b,unsetEnvVars:f,setEnvVars:v});for(let[te,Ie]of Object.entries(ce))ve.push(`${te}=${Ie}`)}let Oe=I||"bash",F=wr(Oe);if(!F)throw Error(`Shell '${Oe}' not found in PATH`);let re=(f??[]).flatMap((ce)=>["-u",ce]),Q=Object.entries(v??{}).map(([ce,te])=>`${ce}=${te}`),ue=kt(["env",...re,...Q,...ve,"/usr/bin/sandbox-exec","-p",Me,F,"-c",t]);return w(`[Sandbox macOS] Applied restrictions - network: ${!!(i||s)}, read: ${V?"allowAllExcept"in V?"allowAllExcept":"denyAllExcept":"none"}, write: ${h?"allowAllExcept"in h?"allowAllExcept":"denyAllExcept":"none"}`),ue}function Kp(e,t,n=(r)=>r){let r=/CMD64_(.+?)_END/,i=/Sandbox:\s+(.+)$/,s=$S("log",["stream","--predicate",`(eventMessage ENDSWITH "${Vp}")`,"--style","compact"]);return s.stdout?.on("data",(a)=>{let o=a.toString().split(`
83
+ `),l=o.find((f)=>f.includes("Sandbox:")&&f.includes("deny")),c=o.find((f)=>f.startsWith("CMD64_"));if(!l)return;let u=l.match(i);if(!u?.[1])return;let d=u[1],p,h;if(c){if(h=c.match(r)?.[1],h)try{p=n(tn(h))}catch{}}if(d.includes("mDNSResponder")||d.includes("mach-lookup com.apple.diagnosticd")||d.includes("mach-lookup com.apple.analyticsd"))return;if(Xn(d,p,t))return;e({line:d,command:p,encodedCommand:h,timestamp:new Date})}),s.stderr?.on("data",(a)=>{w(`[Sandbox Monitor] Log stream stderr: ${a.toString()}`)}),s.on("error",(a)=>{w(`[Sandbox Monitor] Failed to start log stream: ${a.message}`)}),s.on("exit",(a)=>{w(`[Sandbox Monitor] Log stream exited with code: ${a}`)}),()=>{w("[Sandbox Monitor] Stopping log monitor"),s.kill("SIGTERM")}}import{randomBytes as QS}from"crypto";import{chmodSync as qp,chownSync as YS,mkdtempSync as JS,rmSync as ZS}from"fs";import{createServer as eb}from"net";import{tmpdir as tb}from"os";import{join as Gp,posix as rb}from"path";import{createInterface as nb}from"readline";function jp(e,t){let{allowWritePaths:n,denyWritePaths:r,ignoreViolations:i,resolveCommandText:s=(b)=>b,consumerUid:a,consumerGid:o}=t,l=JS(Gp(tb(),"srt-obs-")),c=Gp(l,`s${QS(4).toString("hex")}.sock`),u=(b,k)=>b===k||b.startsWith(k.endsWith("/")?k:k+"/"),d=(b)=>{let k=rb.normalize(b);if(r.some((R)=>u(k,R)))return!0;return!n.some((R)=>u(k,R))},p=(b,k)=>{if(b.observe_init_error){w(`[Sandbox Linux Monitor] observe filter not installed: ${b.observe_init_error}`);return}if(typeof b.path!=="string")return;if(!b.path.startsWith("/"))return;if(!d(b.path))return;let R;if(k)try{R=s(tn(k))}catch{}if(Xn(b.path,R,i))return;let I={line:`deny ${b.syscall??"syscall"} ${b.path}`,command:R,encodedCommand:k,timestamp:new Date};e(I)},h,f=new Promise((b)=>{h=b}),v=c,x=eb((b)=>{let k,R=nb({input:b});R.on("line",(I)=>{if(!I)return;let V;try{V=JSON.parse(I)}catch{return}if(V.encodedCommand&&k===void 0)k=V.encodedCommand;p(V,k??V.encodedCommand)}),b.on("error",()=>R.close()),b.on("close",()=>R.close())});x.on("error",(b)=>{w(`[Sandbox Linux Monitor] listen failed: ${b.message} - violation monitoring disabled`,{level:"warn"}),v=void 0,h()}),x.listen(c,()=>{if(a!==void 0)qp(l,457),YS(c,a,o??a),qp(c,384);h()});let S=new Set;return x.on("connection",(b)=>{S.add(b),b.on("close",()=>S.delete(b))}),{get observeSocketPath(){return v},ready:f,stop:()=>{w("[Sandbox Linux Monitor] stopping");for(let b of S)b.destroy();x.close();try{ZS(l,{recursive:!0,force:!0})}catch{}}}}import*as rt from"fs";import*as Qp from"net";import*as tt from"path";import{spawn as ib,spawnSync as sb}from"child_process";import{once as ab}from"events";import{fileURLToPath as ob}from"url";class be extends Error{code;subcommand;constructor(e,t,n){super(t);this.name="WindowsSandboxError",this.code=e,this.subcommand=n}}var Da=[60080,60089],zp=["-NoProfile","-Command"];function La(e){let t=process.env.SystemRoot??"C:\\Windows",n={exe:tt.win32.join(t,"System32","cmd.exe"),args:["/d","/s","/c"]};if(e===void 0||e===null)return n;if(typeof e==="object"){if(!tt.win32.isAbsolute(e.exe))throw new be("bin_shell_invalid",`binShell.exe must be an absolute path (got ${JSON.stringify(e.exe)})`);if(!Array.isArray(e.args))throw new be("bin_shell_invalid",`binShell.args must be an array (got ${JSON.stringify(e.args)})`);return e}let r=tt.win32.basename(e),i=r.toLowerCase(),s=tt.win32.isAbsolute(e);if(!s&&e!==r)throw new be("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(!s)throw new be("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:s?e:"pwsh.exe",args:zp};case"powershell":case"powershell.exe":return{exe:s?e:tt.win32.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe"),args:zp};case"cmd":case"cmd.exe":return s?{exe:e,args:n.args}:n;default:throw new be("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 Yp(){let e=tt.dirname(ob(import.meta.url));return tt.resolve(e,"..","..")}var Jp={x64:"x64",arm64:"arm64"},lb=tt.join(Yp(),"vendor","srt-win",Jp[process.arch]??process.arch,"srt-win.exe");function cb(){let e=Yp(),t=Jp[process.arch],n=[];if(t)n.push(tt.join(e,"vendor","srt-win",t,"srt-win.exe"));n.push(tt.join(e,"vendor","srt-win-src","target","release","srt-win.exe"));for(let r of n)if(rt.existsSync(r))return r;throw new be("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 Zp="--srt-win";function Bt(e){if(e?.path===void 0)throw new be("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(!rt.existsSync(e.path))throw new be("srt_win_not_found",`windows.srtWin.path is set to '${e.path}' but the file does not exist`);return{exe:e.path,prependArgs:[Zp]}}function Gr(e,t={}){let{exe:n,prependArgs:r}=t.srtWin??Bt(),i=sb(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 be("srt_win_timeout",`srt-win ${e.join(" ")} timed out after ${t.timeoutMs??15000}ms`+(i.signal?` (killed by ${i.signal})`:""),e[0]);throw new be("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 dc(e,t={}){let{exe:n,prependArgs:r}=t.srtWin??Bt(),i=t.timeoutMs??15000;return new Promise((s,a)=>{let o=ib(n,[...r,...e],{windowsHide:!0}),l=!1,c=i>0?setTimeout(()=>{l=!0,o.kill()},i):void 0,u="",d="";o.stdout?.setEncoding("utf8").on("data",(p)=>u+=p),o.stderr?.setEncoding("utf8").on("data",(p)=>d+=p),o.stdin?.on("error",()=>{}).end(t.stdin),o.once("error",(p)=>{clearTimeout(c),a(new be("spawn_failed",`srt-win ${e[0]}: spawn failed: ${p.message}`,e[0]))}),o.once("close",(p,h)=>{if(clearTimeout(c),l){a(new be("srt_win_timeout",`srt-win ${e.join(" ")} timed out after ${i}ms`+(h?` (killed by ${h})`:""),e[0]));return}s({status:p,signal:h,stdout:u.trim(),stderr:d.trim()})})})}function eh(e,t){if(t.status!==0)throw new be("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 be("srt_win_bad_json",`srt-win ${e.join(" ")}: unparseable JSON output ${JSON.stringify(t.stdout)}: ${n.message}`,e[0])}}function fc(e,t){return eh(e,Gr(e,t))}async function pc(e,t){return eh(e,await dc(e,t))}function th(e,t){let n=Gr(e,t),r;try{r=JSON.parse(n.stdout)}catch(i){throw new be("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 rh(e){let t=["wfp","status"];if(e)t.push("--sublayer-guid",e);return t}function Oa(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 Ua(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 nh(e={}){let t=["status"];if(e.sublayerGuid)t.push("--sublayer-guid",e.sublayerGuid);let n=fc(t,{srtWin:e.srtWin});return{user:Ua(n.user),wfp:Oa(n.wfp)}}async function ih(e={}){let t=["status"];if(e.sublayerGuid)t.push("--sublayer-guid",e.sublayerGuid);let n=await pc(t,{srtWin:e.srtWin});return{user:Ua(n.user),wfp:Oa(n.wfp)}}function sh(e={}){return Oa(fc(rh(e.sublayerGuid),{srtWin:e.srtWin}))}async function ah(e={}){return Oa(await pc(rh(e.sublayerGuid),{srtWin:e.srtWin}))}async function hc(e={}){let t=e.target,n;if(!t){let[r,i]=e.proxyPortRange??Da;for(let s=0;s<5;s++){let a=Qp.createServer();a.listen(0,"127.0.0.1"),await ab(a,"listening");let o=a.address().port;if(o<r||o>i){n=a,t=`127.0.0.1:${o}`;break}a.close()}if(!t)throw new be("wfp_verify_bind_failed",`verifyWindowsWfpEgress: could not bind a loopback listener outside the WFP permit range [${r},${i}] in 5 attempts`)}try{let r=Gr(["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 be("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 be("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 be("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 gc(e={}){return Ua(fc(["user","status"],{srtWin:e.srtWin}))}async function zi(e={}){return Ua(await pc(["user","status"],{srtWin:e.srtWin}))}function mc(e,t={}){let n=e??gc(t);if(!n.caCertThumb||!n.caCertPem)return null;return{pem:n.caCertPem,thumb:n.caCertThumb}}function ub(e,t={}){let n=Gr(["user","trust-ca",e],{timeoutMs:60000,srtWin:t.srtWin});lh(e,n)}async function oh(e,t={}){let n=await dc(["user","trust-ca",e],{timeoutMs:60000,srtWin:t.srtWin});lh(e,n)}function lh(e,t){if(w(`[Sandbox Windows] user trust-ca exit=${t.status}: ${t.stderr||t.stdout}`),t.status!==0)throw new be("trust_ca_failed",`srt-win user trust-ca '${e}' failed (exit ${t.status}): ${t.stderr||t.stdout}`)}function ch(){let e=process.env.ProgramData;if(!e)throw Error("ProgramData is not set");return tt.win32.join(e,"sandbox-runtime")}async function yc(e={}){let t=e.status??await zi({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:ch();if(n&&!rt.existsSync(n))throw Error(`ensurePersistentWindowsCa: state directory ${n} does not exist. Run \`npx sandbox-runtime windows-install\` first.`);let r=e.dir??tt.win32.join(n,"ca"),i=tt.join(r,"ca.json"),s=tt.join(r,"cert.pem"),a=tt.join(r,"key.pem"),o=(e.regenerateWithinDays??30)*24*60*60*1000,l=(x,S)=>{let A=`${x}.tmp.${process.pid}`;rt.writeFileSync(A,S),rt.renameSync(A,x)},c=async(x,S,A,b)=>{l(s,x),l(a,S);let k=b||t.caCertThumb!==A;if(k){let R=tt.join(r,`.trust.${process.pid}.${Date.now()}.pem`);rt.writeFileSync(R,x);try{await oh(R,{srtWin:e.srtWin})}finally{rt.rmSync(R,{force:!0})}}return w(`[Sandbox Windows] persistent CA ${b?"generated":"reused"} (thumb=${A}${k&&!b?", trust reconciled":""})`),{certPem:x,keyPem:S,certPath:s,keyPath:a,thumbprint:A,generated:b,trusted:k}},u=()=>{let x;try{x=JSON.parse(rt.readFileSync(i,"utf8"))}catch(A){w(`[Sandbox Windows] persistent CA ca.json unreadable (${A.message})`,{level:"warn"});return}if(typeof x.certPem!=="string"||typeof x.keyPem!=="string")return;let S=Pi(x.certPem,x.keyPem);if(!S.ok){w(`[Sandbox Windows] persistent CA invalid (${S.reason})`,{level:"warn"});return}return{certPem:x.certPem,keyPem:x.keyPem,thumbprint:S.thumbprint,notAfter:S.notAfter}};if(!e.force){let x=u();if(x&&x.notAfter.getTime()-Date.now()>o)return await c(x.certPem,x.keyPem,x.thumbprint,!1);if(x)w(`[Sandbox Windows] persistent CA expiring ${x.notAfter.toISOString()}; regenerating`,{level:"warn"})}rt.mkdirSync(r,{recursive:!0});try{let x=Date.now()-300000;for(let S of rt.readdirSync(r)){if(!S.includes(".tmp.")&&!S.startsWith(".trust."))continue;let A=tt.join(r,S);if(rt.statSync(A).mtimeMs<x)rt.rmSync(A,{force:!0})}}catch{}let d=oa({cn:"sandbox-runtime persistent CA"});l(i,JSON.stringify({certPem:d.certPem,keyPem:d.keyPem}));let p=u(),{certPem:h,keyPem:f,thumbprint:v}=p??{certPem:d.certPem,keyPem:d.keyPem,thumbprint:Wn(d.certPem)};return await c(h,f,v,!0)}function vc(e){return e.timeoutMs??120000}function uh(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 dh(e){if(e instanceof be&&e.code==="srt_win_timeout")throw new be("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 fh(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 be("install_wfp_failed",`srt-win install: WFP filter install failed: ${t}`);case 14:throw new be("install_user_failed",`srt-win install: sandbox user provisioning failed: ${t}`);case 13:throw new be("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 be("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 be("install_failed",`srt-win install failed (exit ${e.status}): ${t}`)}}function db(e={}){let t=e.srtWin??Bt(),n;try{n=Gr(uh(e),{timeoutMs:vc(e),srtWin:t})}catch(i){dh(i)}fh(n);let r=nh({sublayerGuid:e.sublayerGuid,srtWin:t});return n.status===10?{...r,cancelled:!0}:r}async function fb(e={}){let t=e.srtWin??Bt(),n;try{n=await dc(uh(e),{timeoutMs:vc(e),srtWin:t})}catch(i){dh(i)}fh(n);let r=await ih({sublayerGuid:e.sublayerGuid,srtWin:t});return n.status===10?{...r,cancelled:!0}:r}function pb(e={}){let t=["uninstall"];if(e.sublayerGuid)t.push("--sublayer-guid",e.sublayerGuid);if(e.keepUser)t.push("--keep-user");let n=Gr(t,{timeoutMs:vc(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 be("uninstall_failed",`srt-win uninstall failed (exit ${n.status}): ${n.stderr||n.stdout}`);return{}}function Va(e,t){let n=new Set;for(let r of e){let i=et(r),s=fi(i);if(pi(i)&&!s){n.add(i);continue}let a=s?rn(i,{caseInsensitive:!0}):[i];for(let o of a){if(!rt.statSync(o,{throwIfNoEntry:!1})){if(t?.mode==="deny"&&!s)n.add(/[\\/]$/.test(r)&&!/[\\/]$/.test(o)?o+"\\":o);continue}n.add(o)}}return[...n]}function hb(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 be("mapped_drive_cwd",r.message??"mapped/network-drive working directory","exec"),{drive:r.drive})}catch{}}return}function xc(e){let t=e.holderPid??process.pid,n=JSON.stringify({denyRead:e.denyRead,denyWrite:e.denyWrite}),r=Gr(["acl","stamp","--holder-pid",`${t}`,"--sandbox-user-sid",e.sandboxUserSid],{timeoutMs:60000,stdin:n,srtWin:e.srtWin});if(w(`[Sandbox Windows] acl stamp exit=${r.status}: ${r.stderr||r.stdout}`),r.status!==0)throw new be("acl_stamp_failed",`srt-win acl stamp exited ${r.status} `+(r.status===2?"(partial \u2014 some inputs skipped)":"(failed)")+`: ${r.stderr||r.stdout}`)}function Fa(e){let t=e.holderPid??process.pid;try{let n=th(["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}}function Sc(e){let t=e.holderPid??process.pid,n=JSON.stringify({read:e.read,write:e.write}),r=Gr(["acl","grant","--holder-pid",`${t}`,"--sandbox-user-sid",e.sandboxUserSid],{timeoutMs:60000,stdin:n,srtWin:e.srtWin});if(w(`[Sandbox Windows] acl grant exit=${r.status}: ${r.stderr||r.stdout}`),r.status!==0)throw new be("acl_grant_failed",`srt-win acl grant exited ${r.status}: ${r.stderr||r.stdout}`)}function Ma(e){let t=e.holderPid??process.pid;try{let n=th(["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 ph(e){let{exe:t,prependArgs:n}=e.srtWin??Bt(),r=gb(wn(e.httpProxyPort,e.socksProxyPort,e.caCertPath?.replace(/\\/g,"/"),e.proxyAuthToken,void 0,Dt(e.commandId??e.command)));delete r.TMPDIR,delete r.NO_PROXY,delete r.no_proxy;let i=hi({safeDirs:[e.cwd??process.cwd(),...e.allowWrite??[],...e.gitSafeDirectories??[]],schannelCa:e.caCertPath!==void 0,baseEnv:e.setEnvVars}),s=[t,...n,"exec"];if(e.quiet!==!1)s.push("--quiet");for(let u of e.denyRead??[])s.push("--deny-read",u);for(let u of e.denyWrite??[])s.push("--deny-write",u);let a={PATH:process.env.PATH,PATHEXT:process.env.PATHEXT,...e.setEnvVars??{},...r,...i};for(let[u,d]of Object.entries(a))if(d!==void 0)s.push("--env",`${u}=${d}`);s.push("--");let o=e.binShell??La(void 0);s.push(o.exe,...o.args,e.command);let l=s.reduce((u,d)=>u+d.length+3,0);if(l>30000)throw new be("argv_too_long",`Windows sandbox argv is ~${l} chars (CreateProcessW limit is 32 767).`);let c={...process.env,...r};return{argv:s,env:c}}function gb(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 uc(e){let t=e?` --sublayer-guid ${e}`:"";return`Windows sandbox needs a one-time install (one UAC prompt):
84
84
  npx sandbox-runtime windows-install
85
85
  `+" \u2014 or call installWindowsSandbox(), or run "+`\`srt-win.exe install${t}\` directly.
86
- No logout is needed: the WFP filter keys on the dedicated \`srt-sandbox\` user's SID, so your network is unaffected.`}function Xp(e){try{return{status:"fulfilled",value:e()}}catch(t){return{status:"rejected",reason:t}}}function hh(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 s=t.value;if(!s.provisioned||!s.credPresent)r.push(`Sandbox user is not provisioned (user=${s.provisioned}, cred=${s.credPresent}). `+uc(e));let a=n();if(a.status==="rejected")return r.push(`srt-win wfp status failed: ${a.reason.message}`),{errors:r,warnings:i};let o=a.value;if(o.state==="cannot-read")w(`[Sandbox Windows] wfp status cannot-read (non-elevated): ${o.hint}`);else if(o.state!=="installed"){if(s.provisioned&&s.credPresent)r.push(`WFP filters not installed under sublayer ${e??"(default)"}. `+uc(e))}else if(o.portRange)w(`[Sandbox Windows] WFP installed: ${o.filters} filters, proxy port range ${o.portRange[0]}-${o.portRange[1]}`);return{errors:r,warnings:i}}function gh(e={}){let t;try{t=e.srtWin??Pt()}catch(n){return{errors:[n.message],warnings:[]}}return w(`[Sandbox Windows] using srt-win at ${t.exe}`),hh(e.sublayerGuid,Xp(()=>gc({srtWin:t})),()=>Xp(()=>sh({sublayerGuid:e.sublayerGuid,srtWin:t})))}async function bc(e={}){let t;try{t=e.srtWin??Pt()}catch(i){return{errors:[i.message],warnings:[]}}w(`[Sandbox Windows] using srt-win at ${t.exe}`);let[n,r]=await Promise.allSettled([zi({srtWin:t}),ah({sublayerGuid:e.sublayerGuid,srtWin:t})]);return hh(e.sublayerGuid,n,()=>r)}import{isIP as yb}from"net";function Xi(e){if(e.startsWith("[")){let r=e.indexOf("]");if(r===-1)return{hostPattern:e,port:void 0};let i=e.slice(1,r),s=vt(i)??i,a=e.slice(r+1);if(a==="")return{hostPattern:s,port:void 0};let o=mh(a.startsWith(":")?a.slice(1):"");return o===void 0?{hostPattern:e,port:void 0}:{hostPattern:s,port:o}}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=mh(e.slice(t+1));if(n===void 0)return{hostPattern:e,port:void 0};return{hostPattern:e.slice(0,t),port:n}}function mh(e){if(!/^[1-9][0-9]{0,4}$/.test(e))return;let t=Number(e);return t>65535?void 0:t}function Qi(e){return Xi(e).hostPattern}function Ar(e,t){let n=e.toLowerCase();if(t==="*")return!0;if(t.startsWith("*.")){if(yb(Xt(n)))return!1;let r=t.substring(2).toLowerCase();return n.endsWith("."+r)}return n===t.toLowerCase()}function Yi(e,t,n){let{hostPattern:r,port:i}=Xi(n);if(i!==void 0&&i!==t)return!1;return Ar(e,r)}function $a(e,t){let n=t.map(Qi);if(!e.startsWith("*."))return n.some((i)=>Ar(e,i));let r=e.slice(2).toLowerCase();return n.some((i)=>{if(!i.startsWith("*."))return!1;let s=i.slice(2).toLowerCase();return r===s||r.endsWith("."+s)})}import{isIP as vb}from"net";var yh="<allowAllDomains>";function Cc(e,t,n,r){if(!Kn(t))return{verdict:"deny",reason:"malformed host"};let i=vt(t)??t;for(let s of e.deniedDomains)if(Yi(i,n,s))return{verdict:"deny",reason:e.deniedDomainReasons?.[s]??"host is on the deny list",rule:s};for(let s of e.allowedDomains)if(Yi(i,n,s))return{verdict:"allow",rule:s};if(e.allowAllDomains){if(Cl(i)||vb(i)!==0&&!la(i))return{verdict:"deny",reason:"host is not on the public internet"};return{verdict:"allow",rule:yh}}if(!r||e.strictAllowlist)return{verdict:"deny",reason:"host is not on the allow list"};return{verdict:"ask"}}function Wa(e,t,n){if(!e.allowAllDomains)return!1;let r=Cc(e,t,n,!1);return r.verdict==="allow"&&r.rule===yh}import{EOL as wc}from"os";import{dirname as Ec}from"path";var P,es,ts,rs,Ht,jr,Ji,vh=!1,Ha,Yn,Qr,Me,Yr,Jn,zr,Ka,xh=!1,ns,vn=new Pa,Zt=new Fl,ei=new Kl,Zn=new Pl;function Th(){let e=P?.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)Zn.register(r,t,n.hosts,e.url)}return[e.tokenEnvVar]}function Sb(e){return P?.network.brokerForward?.rules.some((t)=>t.hosts.includes(e))??!1}var is=new Hl;function bb(){if(vh)return;let e=()=>Bc().catch((t)=>{w(`Cleanup failed in registerCleanup ${t}`,{level:"error"})});process.once("exit",e),process.once("SIGINT",e),process.once("SIGTERM",e),vh=!0}var Cb=1024,yn=new Map;function Ah(e,t){let n=t?.commandId,r=t?.commandText??e;if(n===void 0||n===r)return;let i=tn(Dt(n));yn.delete(i),yn.set(i,r);while(yn.size>Cb){let s=yn.keys().next().value;if(s===void 0)break;yn.delete(s)}}function Sh(e){return yn.get(e)??e}function Tc(e,t){let n=t?(()=>{let r=tn(t);return yn.get(r)??sc(r)})():void 0;if(Xn(e,n,P?.ignoreViolations))return;vn.addViolation({line:e,encodedCommand:t,command:n,timestamp:new Date})}function wb(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 bh(e,t,n,r){let i=(a)=>(Tc(`deny network-outbound ${t}:${e} (${a})`,r),!1);if(!P)return w("No config available, denying network request"),i("sandbox policy unavailable");let s=Cc(P.network,t,e,n!==void 0);if(s.verdict==="allow")return w(`Allowed by config rule: ${t}:${e}`),!0;if(s.verdict==="deny"){if(s.reason==="malformed host")w(`Denying malformed host: ${JSON.stringify(t)}:${e}`,{level:"error"});else if(s.rule!==void 0)w(`Denied by config rule: ${t}:${e}`);else w(`No matching config rule, denying: ${t}:${e}`);return i(s.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(a){return w(`Error in permission callback: ${a}`,{level:"error"}),i("permission prompt failed")}}var qa=!1;function Eb(e){qa=e}function Tb(){if(!qa&&!P?.credentials)return;return(e,t)=>{if(!P?.credentials)return;Zt.substituteInHeaders(e,t,Ar)}}function Ab(){if(!qa&&!P?.credentials)return;return(e)=>P?.credentials?Zt.sentinelsForHost(e,Ar):void 0}function _b(){if(!qa&&!P?.credentials)return;return(e,t,n,r)=>!P?.credentials?void 0:lp(ei,P?.credentials?.sigv4,Ar)(e,t,n,r)}function kb(e){if(!P?.network.mitmProxy)return;let{socketPath:t,domains:n}=P.network.mitmProxy,r=vt(e)??e;for(let i of n)if(Ar(r,i))return w(`Host ${e} matches MITM pattern ${i}`),t;return}function Ib(e,t=443){if(P&&Wa(P.network,vt(e)??e,t))return!1;let n=P?.network.tlsTerminate?.excludeDomains;if(!n?.length)return!0;let r=vt(e)??e;if(Sb(r))return!0;for(let i of n){if(!Ar(r,i))continue;w(`Host ${e} matches tlsTerminate.excludeDomains pattern ${i}; skipping TLS termination`);let s=Zt.namesInjectableAt(r,Ar);if(s.length>0)w(`tlsTerminate.excludeDomains: masked credential(s) ${s.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 Rb(e,t){let n=Tb(),r=Ab();es=Vf({filter:(o,l,c,u)=>bh(o,l,e,u),getMitmSocketPath:kb,mitmCA:Me,shouldTerminateTLS:Ib,publicOnly:(o,l)=>P!==void 0&&Wa(P.network,vt(o)??o,l),filterRequest:P?.network.filterRequest,onFilterRequestDenied:({method:o,url:l,reason:c,encodedCommand:u})=>{Tc(`deny http-request ${o} ${wb(l)} (${c})`,u)},mutateHeaders:n,mutateHeadersPlaintext:P?.credentials?.allowPlaintextInject?n:void 0,getBrokerForward:(o,l)=>P?.network.brokerForward?Zn.forwardFor(o,l):void 0,getBodySubstitutions:r,getBodySubstitutionsPlaintext:P?.credentials?.allowPlaintextInject?r:void 0,planSigv4:_b(),parentProxy:Qr,proxyAuthToken:Yr}),ts=jf({filter:(o,l,c)=>bh(o,l,e,c),publicOnly:(o,l)=>P!==void 0&&Wa(P.network,vt(o)??o,l),parentProxy:Qr,proxyAuthToken:Yr,probeUnauthenticated:async(o,l)=>{if(!P)return{};let c=vt(l)??l;for(let u of P.network.deniedDomains)if(Yi(c,o,u)){let d=P.network.deniedDomainReasons?.[u]??"host is on the deny list";return Tc(`deny network-outbound ${l}:${o} (${d})`,void 0),{deniedReason:d}}return{}}}),rs=Qf({httpServer:es,handleSocksConnection:(o)=>ts.handleConnection(o),httpBackendPortRange:t});let i=rs,s=await i.listenHttpBackend();await xa(i.server,(o)=>i.server.listen(o,"127.0.0.1"),t,s!==void 0?new Set([s]):new Set);let a=i.getPort();if(a===void 0)throw Error("Failed to get mux proxy server port");return i.unref(),w(`Mux proxy (HTTP+SOCKS) listening on localhost:${a}`),a}async function Bb(e,t,n=!1){if(jr){await jr;return}if(P=e,Qr=Al(e.network.parentProxy),Qr)w(`Parent proxy configured: http=${Il(Qr.httpUrl)} https=${Il(Qr.httpsUrl)}`);if(e.network.tlsTerminate&&e.network.mitmProxy)throw Error("network.tlsTerminate and network.mitmProxy are mutually exclusive");let r=e.network.tlsTerminate,i=Ne()==="windows"&&r!==void 0&&!r.caCertPath&&!r.caKeyPath;if(Me=r&&!i?vl(r):void 0,Me&&e.runAsHostUid!==void 0&&Ne()==="linux"){if(Xr.chmodSync(Ec(Me.trustBundlePath),457),Xr.chmodSync(Me.trustBundlePath,420),Me.ephemeral)Xr.chmodSync(Ec(Me.certPath),457),Xr.chmodSync(Me.certPath,420)}let s=await Ih();if(s.errors.length>0)throw Error(`Sandbox dependencies not available: ${s.errors.join(", ")}`);if(n&&Ne()==="macos")Ha=Kp(vn.addViolation.bind(vn),P.ignoreViolations,Sh),w("Started macOS sandbox log monitor");if(n&&Ne()==="linux")Yn=jp(vn.addViolation.bind(vn),{allowWritePaths:[...Cn(e.runAsHostHome),...P.filesystem.allowWrite],denyWritePaths:P.filesystem.denyWrite,ignoreViolations:P.ignoreViolations,resolveCommandText:Sh,consumerUid:e.runAsHostUid,consumerGid:e.runAsHostGid}),Yn.ready,w("Started Linux seccomp violation monitor");if(bb(),Ne()==="windows"){ns=Pt(e.windows?.srtWin);let a=ns,o=await zi({srtWin:a});if(!o.provisioned||!o.credPresent)throw P=void 0,new be("not_provisioned",`Windows sandbox user is not provisioned (user=${o.provisioned}, cred=${o.credPresent}). Run \`npx sandbox-runtime windows-install\` (one UAC prompt) to provision it.`);if(!xh){try{await hc({proxyPortRange:e.windows?.proxyPortRange,srtWin:a})}catch(l){throw P=void 0,l}xh=!0}if(i&&r)try{let l=await yc({status:o,srtWin:a});Me=vl({caCertPem:l.certPem,caKeyPem:l.keyPem,caCertPath:l.certPath,caKeyPath:l.keyPath,extraCaCertPaths:r.extraCaCertPaths})}catch(l){throw P=void 0,l}if(r&&Me&&!i){let l=mc(o),c=Wn(Me.certPem);if(!l)throw P=void 0,new be("trust_ca_not_installed",`tlsTerminate on Windows requires the sandbox to be installed with this CA (thumb=${c}): run \`srt-win user trust-ca ${Me.certPath}\`. Per-exec installs into the sandbox user's Root store are not supported.`);if(l.thumb!==c)throw P=void 0,new be("trust_ca_thumbprint_mismatch",`tlsTerminate on Windows: the sandbox's installed CA (thumb=${l.thumb}) doesn't match this session's CA (thumb=${c}). Run \`srt-win user trust-ca ${Me.certPath}\` to update it.`)}try{let l=Ob(e);if(Me)l.grantRead.push(Ec(Me.trustBundlePath));if(!o.sid)throw Error("sandbox user SID missing from `srt-win user status` (provisioned but in an inconsistent state)");let c=o.sid;if(zr=c,l.grantRead.length>0||l.grantWrite.length>0)Sc({sandboxUserSid:c,read:l.grantRead,write:l.grantWrite,srtWin:a});if(l.denyRead.length>0||l.denyWrite.length>0)xc({sandboxUserSid:c,denyRead:l.denyRead,denyWrite:l.denyWrite,srtWin:a});if(l.grantRead.length>0||l.grantWrite.length>0||l.denyRead.length>0||l.denyWrite.length>0)Jn=l,w(`[Sandbox Windows] fs applied: ${l.grantWrite.length} grantWrite, ${l.grantRead.length} grantRead, ${l.denyRead.length} denyRead, ${l.denyWrite.length} denyWrite`);Ka=Bh(e)}catch(l){if(zr)Ma({sandboxUserSid:zr,srtWin:a}),Fa({sandboxUserSid:zr,srtWin:a});throw zr=void 0,P=void 0,l}}jr=(async()=>{try{let a=Ne()==="windows"?P.windows?.proxyPortRange??Da:void 0;Yr=P.network.httpProxyPort!==void 0?void 0:xb(16).toString("hex");let l=P.network.httpProxyPort===void 0||P.network.socksProxyPort===void 0?await Rb(t,a):void 0,c=P.network.httpProxyPort??l,u=P.network.socksProxyPort??l;if(Me&&l!==void 0&&Ne()==="windows")Me.crlUrl=`http://127.0.0.1:${l}${aa}`;if(P.network.httpProxyPort!==void 0)w(`Using external HTTP proxy on port ${c}`);if(P.network.socksProxyPort!==void 0)w(`Using external SOCKS proxy on port ${u}`);let d;if(Ne()==="linux")d=await Lp(c,u,P.socatPath,P.runAsHostUid,P.runAsHostGid);let p={httpProxyPort:c,socksProxyPort:u,linuxBridge:d};return Ht=p,w("Network infrastructure initialized"),p}catch(a){throw jr=void 0,Ht=void 0,Bc().catch((o)=>{w(`Cleanup failed in initializationPromise ${o}`,{level:"error"})}),a}})(),await jr}function _h(){let e=Ne();if(e==="linux")return io()!=="1";return e==="macos"||e==="windows"}function Pb(){return P!==void 0}function kh(e){if(!_h())return{done:{errors:["Unsupported platform"],warnings:[]}};let t=[],n=[],r=Ne();if(r==="linux"){let i=e??P?.ripgrep??{command:"rg"};if(wr(i.command)===null)t.push(`ripgrep (${i.command}) not found`);let s=Dp({seccompConfig:P?.seccomp,bwrapPath:P?.bwrapPath,socatPath:P?.socatPath});t.push(...s.errors),n.push(...s.warnings)}else if(r==="windows"){let i;try{i=Pt(P?.windows?.srtWin)}catch(s){return t.push(s.message),{done:{errors:t,warnings:n}}}return{windows:{sublayerGuid:P?.windows?.sublayerGuid??P?.windows?.wfpSublayerGuid,srtWin:i}}}return{done:{errors:t,warnings:n}}}function Nb(e){let t=kh(e);if("done"in t)return t.done;return gh(t.windows)}async function Ih(e){let t=kh(e);if("done"in t)return t.done;return bc(t.windows)}function _c(e,t){if(!e)return{denyReadPaths:[],unsetEnvVars:[],setEnvVars:{},maskedFileBinds:[],maskedFileStoreDir:void 0};let n=Ga(e),r=[...new Set((t??[]).map(Qi))],i=[];for(let u of e.envVars??[])if(u.mode==="deny")i.push(u.name);let{setEnvVars:s,degradeToUnsetNames:a}=np(e.envVars??[],r,Zt);i.push(...a),op(e.envVars??[],e.awsPairs,r,s,ei);let o=e.files??[],{binds:l,degradeToDenyPaths:c}=rp(o,r,Zt,is);return{denyReadPaths:[...new Set([...n,...c])],unsetEnvVars:[...new Set(i)],setEnvVars:s,maskedFileBinds:l,maskedFileStoreDir:is.dirPath}}function Ga(e){let t=e?.files??[];return[...new Set(t.filter((n)=>n.mode==="deny").map((n)=>n.path))]}function Rh(e,t){return[...new Set([...e,...t.denyReadPaths])]}function Db(){if(!P||P.filesystem.disabled)return{denyOnly:[],allowWithinDeny:[]};let e=Rh(P.filesystem.denyRead,_c(P.credentials,P.network.allowedDomains)),t=[];for(let r of e){let i=vr(r);if(Ne()==="linux"&&St(i)){let s=rn(r);w(`[Sandbox] Expanded glob pattern "${r}" to ${s.length} paths on Linux`),t.push(...s)}else t.push(i)}let n=[];for(let r of P.filesystem.allowRead??[]){let i=vr(r);if(Ne()==="linux"&&St(i)){let s=rn(r);w(`[Sandbox] Expanded allowRead glob pattern "${r}" to ${s.length} paths on Linux`),n.push(...s)}else n.push(i)}return{denyOnly:t,allowWithinDeny:n}}function Lb(){if(!P)return{allowOnly:Cn(),denyWithinAllow:[]};if(P.filesystem.disabled)return{allowOnly:["/"],denyWithinAllow:[]};let e=P.filesystem.allowWrite.map((r)=>vr(r)).filter((r)=>{if(Ne()==="linux"&&St(r))return w(`Skipping glob pattern on Linux/WSL: ${r}`),!1;return!0}),t=P.filesystem.denyWrite.map((r)=>vr(r)).filter((r)=>{if(Ne()==="linux"&&St(r))return w(`Skipping glob pattern on Linux/WSL: ${r}`),!1;return!0});return{allowOnly:[...Cn(Ac()),...e],denyWithinAllow:t}}function Ob(e){let t=e.filesystem;if(t?.disabled)return{grantRead:[],grantWrite:[],denyRead:[],denyWrite:[]};let n=Va,r=n([...new Set([...t?.denyRead??[],...Ga(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 Bh(e){return{disabled:e.filesystem.disabled??!1,denyRead:[...e.filesystem.denyRead],denyWrite:[...e.filesystem.denyWrite],allowRead:[...e.filesystem.allowRead??[]],allowWrite:[...e.filesystem.allowWrite],credFiles:Ga(e.credentials)}}function Zi(e,t){if(e.length!==t.length)return!1;let n=new Set(e);return t.every((r)=>n.has(r))}function Ub(e,t){return e.disabled===t.disabled&&Zi(e.denyRead,t.denyRead)&&Zi(e.denyWrite,t.denyWrite)&&Zi(e.allowRead,t.allowRead)&&Zi(e.allowWrite,t.allowWrite)&&Zi(e.credFiles,t.credFiles)}function Vb(e){return Ka!==void 0&&Ub(Ka,Bh(e))}function Fb(){if(!P)return{};let e=P.network.allowedDomains,t=P.network.deniedDomains;return{allowedHosts:e,...t.length>0&&{deniedHosts:t}}}function Ph(){return P?.network?.allowUnixSockets}function Ch(){return P?.network?.allowAllUnixSockets}function Nh(){return P?.network?.allowLocalBinding}function Dh(){return P?.network?.allowMachLookup}function Lh(){return P?.ignoreViolations}function Oh(){return P?.enableWeakerNestedSandbox}function Mb(){return P?.runAsUid}function $b(){return P?.runAsGid}function Wb(){return P?.runAsHostUid}function Hb(){return P?.runAsHostGid}function Ac(){return P?.runAsHostHome}function Kb(){return P?.runAsHostUser}function qb(){return P?.enableWeakerNetworkIsolation}function Gb(){return P?.allowAppleEvents}function jb(){return P?.ripgrep??{command:"rg"}}function zb(){return P?.mandatoryDenySearchDepth??3}function wh(){return P?.filesystem?.allowGitConfig??!1}function Uh(e){return[...P?.git?.safeDirectories??[],...e?.git?.safeDirectories??[]]}function Xb(){return P?.seccomp}function Qb(){return Yr}function kc(){return Ht?.httpProxyPort}function Ic(){return Ht?.socksProxyPort}function Vh(){return Ht?.linuxBridge?.httpSocketPath}function Fh(){return Ht?.linuxBridge?.socksSocketPath}async function Rc(){if(!P)return!1;if(jr)try{return await jr,!0}catch{return!1}return Ht!==void 0}async function Mh(e,t,n,r,i){let s=Ne(),a=i?.commandId;Ah(e,i);let o=n?.filesystem!==void 0?n.filesystem.disabled??!1:P?.filesystem.disabled??!1,l=_c(n?.credentials??P?.credentials,n?.network?.allowedDomains??P?.network?.allowedDomains);l.unsetEnvVars.push(...Th());let c,u;if(!o){let x=(I)=>I.map((V)=>vr(V)).filter((V)=>{if(Ne()==="linux"&&St(V))return w(`[Sandbox] Skipping glob write pattern on Linux: ${V}`),!1;return!0}),S=x(n?.filesystem?.allowWrite??P?.filesystem.allowWrite??[]);c={allowOnly:[...Cn(n?.runAsHostHome??Ac()),...S],denyWithinAllow:x(n?.filesystem?.denyWrite??P?.filesystem.denyWrite??[])};let A=Rh(n?.filesystem?.denyRead??P?.filesystem.denyRead??[],l),b=[];for(let I of A){let V=vr(I);if(Ne()==="linux"&&St(V))b.push(...rn(I));else b.push(V)}let k=n?.filesystem?.allowRead??P?.filesystem.allowRead??[],R=[];for(let I of k){let V=vr(I);if(Ne()==="linux"&&St(V))R.push(...rn(I));else R.push(V)}if(Me)R.push(Me.certPath,Me.trustBundlePath);u={denyOnly:b,allowWithinDeny:R}}let d=n?.network?.allowedDomains!==void 0||P?.network?.allowedDomains!==void 0,p=d,h=d;if(h)await Rc();let f=n?.allowPty??P?.allowPty,v=Uh(n);switch(s){case"macos":return Hp({command:e,commandId:a,needsNetworkRestriction:p,httpProxyPort:h?kc():void 0,socksProxyPort:h?Ic():void 0,proxyAuthToken:h?Yr:void 0,caCertPath:Me?.trustBundlePath,readConfig:u,writeConfig:c,unsetEnvVars:l.unsetEnvVars,setEnvVars:l.setEnvVars,maskedFileBinds:l.maskedFileBinds,allowUnixSockets:Ph(),allowAllUnixSockets:Ch(),allowLocalBinding:Nh(),allowMachLookup:Dh(),ignoreViolations:Lh(),allowPty:f,allowGitConfig:wh(),gitSafeDirectories:v,enableWeakerNetworkIsolation:qb(),allowAppleEvents:Gb(),binShell:t});case"linux":return Up({command:e,commandId:a,needsNetworkRestriction:p,httpSocketPath:h?Vh():void 0,socksSocketPath:h?Fh():void 0,httpProxyPort:h?Ht?.httpProxyPort:void 0,socksProxyPort:h?Ht?.socksProxyPort:void 0,proxyAuthToken:h?Yr:void 0,caCertPath:Me?.trustBundlePath,readConfig:u,writeConfig:c,unsetEnvVars:l.unsetEnvVars,setEnvVars:l.setEnvVars,maskedFileBinds:l.maskedFileBinds,maskedFileStoreDir:l.maskedFileStoreDir,enableWeakerNestedSandbox:Oh(),runAsUid:Mb(),runAsGid:$b(),runAsHostUid:Wb(),runAsHostGid:Hb(),runAsHostHome:Ac(),runAsHostUser:Kb(),setprivPath:"/usr/bin/setpriv",allowAllUnixSockets:Ch(),binShell:t,ripgrepConfig:jb(),mandatoryDenySearchDepth:zb(),allowGitConfig:wh(),gitSafeDirectories:v,seccompConfig:Xb(),bwrapPath:P?.bwrapPath,socatPath:P?.socatPath,observeSocketPath:Yn?.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: ${s}`)}}async function Yb(e,t,n,r,i,s){if(Ne()==="windows"){let c=n?.network?.allowedDomains!==void 0||P?.network?.allowedDomains!==void 0;if(c)await Rc();let u=_c(n?.credentials??P?.credentials,n?.network?.allowedDomains??P?.network?.allowedDomains);u.unsetEnvVars.push(...Th());let d=n?.filesystem,p=[],h=[];if(!d?.disabled){if(d?.allowRead?.length||d?.allowWrite?.length)throw Error("Per-exec filesystem.allowRead/allowWrite is not supported "+"on Windows \u2014 `srt-win exec` only exposes per-exec "+"denies. Set them at the session level (initialize()).");let f=[...d?.denyRead??[],...Ga(n?.credentials)],v=d?.denyWrite??[];if(f.length>0||v.length>0){let x=new Set(Jn?.denyRead??[]),S=new Set(Jn?.denyWrite??[]),A=Va;p=A(f,{mode:"deny"}).filter((b)=>!x.has(b)),h=A(v,{mode:"deny"}).filter((b)=>!x.has(b)&&!S.has(b))}}return Ah(e,s),ph({command:e,commandId:s?.commandId,httpProxyPort:c?kc():void 0,socksProxyPort:c?Ic():void 0,proxyAuthToken:c?Yr:void 0,setEnvVars:u.setEnvVars,denyRead:p,denyWrite:h,cwd:i,allowWrite:Jn?.grantWrite,gitSafeDirectories:Uh(n),caCertPath:Me?.trustBundlePath,binShell:La(t),srtWin:n?.windows?.srtWin?Pt(n.windows.srtWin):ns??Pt(P?.windows?.srtWin)})}if(typeof t==="object")throw Error("binShell object form is Windows-only; pass a shell path string on macOS/Linux");let o=await Mh(e,t,n,r,s);return{argv:[t??"/bin/bash","-c",o],env:process.env}}function Jb(){return P}function Zb(){Zt.clear(),ei.clear(),Zn.clear(),is.dispose()}function eC(e){if(Ne()==="windows"&&P&&!Vb(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;P=structuredClone({...e,network:n}),P.network.filterRequest=t,Qr=Al(e.network.parentProxy),w("Sandbox configuration updated")}function tC(){Ba()}var rC=1500;function Eh(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(s),n()};e.once("exit",()=>{w(`${t} bridge process exited`),i()});let s=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()},rC);s.unref?.()})}function nC(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 iC(){if(Jn&&zr){let t=zr,n=ns,r=new Set(["revoked","stillHeld","restored","alreadyOriginal"]),i=(s,a)=>{if(!r.has(a.status))w(`[Sandbox Windows] ${s}: '${a.path}' ${a.status} \u2014 `+"ACE may be left in place; resolve and run `srt-win acl recover` to clear",{level:"warn"})};for(let s of Ma({sandboxUserSid:t,srtWin:n})??[])i("grant revoke",s);for(let s of Fa({sandboxUserSid:t,srtWin:n})??[])i("deny restore",s)}if(Jn=void 0,zr=void 0,Ka=void 0,ns=void 0,Ba({force:!0}),Ha)Ha(),Ha=void 0;if(Yn)Yn.stop(),Yn=void 0;if(Ht?.linuxBridge){let{httpSocketPath:t,socksSocketPath:n,httpBridgeProcess:r,socksBridgeProcess:i}=Ht.linuxBridge;if(await Promise.all([Eh(r,"HTTP"),Eh(i,"SOCKS")]),t)try{Xr.rmSync(t,{force:!0}),w("Cleaned up HTTP socket")}catch(s){w(`HTTP socket cleanup error: ${s}`,{level:"error"})}if(n)try{Xr.rmSync(n,{force:!0}),w("Cleaned up SOCKS socket")}catch(s){w(`SOCKS socket cleanup error: ${s}`,{level:"error"})}}let e=[];if(Me)e.push(df(Me));if(rs)e.push(rs.close().catch((t)=>{w(`Error closing mux proxy server: ${t.message}`,{level:"error"})}));if(es)e.push(nC(es));if(ts){let t=ts.close().catch((n)=>{w(`Error closing SOCKS proxy server: ${n.message}`,{level:"error"})});e.push(t)}await Promise.all(e),rs=void 0,es=void 0,Yr=void 0,ts=void 0,Ht=void 0,jr=void 0,Qr=void 0,Me=void 0,Zt.clear(),ei.clear(),is.dispose()}async function Bc(){if(Ji)return Ji;Ji=iC();try{await Ji}finally{Ji=void 0}}function sC(){return vn}function aC(e,t){if(!P)return t;let n=vn.getViolationsForCommand(e);if(n.length===0)return t;let r=t;r+=wc+"<sandbox_violations>"+wc;for(let i of n)r+=i.line+wc;return r+="</sandbox_violations>",r}function oC(){if(Ne()!=="linux"||!P||P.filesystem.disabled)return[];let e=[],t=[...P.filesystem.allowWrite,...P.filesystem.denyWrite];for(let n of t){let r=vr(n);if(St(r))e.push(n)}return e}var lC={initialize:Bb,isSupportedPlatform:_h,isSandboxingEnabled:Pb,checkDependencies:Nb,checkDependenciesAsync:Ih,getFsReadConfig:Db,getFsWriteConfig:Lb,getNetworkRestrictionConfig:Fb,getAllowUnixSockets:Ph,getAllowLocalBinding:Nh,getAllowMachLookup:Dh,getIgnoreViolations:Lh,getEnableWeakerNestedSandbox:Oh,getProxyPort:kc,getProxyAuthToken:Qb,getSocksProxyPort:Ic,getLinuxHttpSocketPath:Vh,getLinuxSocksSocketPath:Fh,waitForNetworkInitialization:Rc,wrapWithSandbox:Mh,wrapWithSandboxArgv:Yb,cleanupAfterCommand:tC,beginCredentialLease:()=>{Zt.beginLease(),Zn.beginLease()},endCredentialLease:()=>Object.assign(Zt.endLease(),{brokerForward:Zn.endLease()}),releaseCredentialLease:(e)=>{Zn.release(e.brokerForward??[]),ei.forget(Zt.release(e))},reset:Bc,getMitmCA:()=>Me,getSentinelRegistry:()=>Zt,getAwsPairRegistry:()=>ei,getMaskedFileStore:()=>is,getSandboxViolationStore:sC,annotateStderrWithSandboxFailures:aC,getLinuxGlobPatternWarnings:oC,getConfig:Jb,updateConfig:eC,clearMaskedCredentials:Zb,setLiveCredentialInjectors:Eb};import{isIP as OC}from"net";import{isAbsolute as UC}from"path";var _e;(function(e){e.assertEqual=(i)=>{};function t(i){}e.assertIs=t;function n(i){throw Error()}e.assertNever=n,e.arrayToEnum=(i)=>{let s={};for(let a of i)s[a]=a;return s},e.getValidEnumValues=(i)=>{let s=e.objectKeys(i).filter((o)=>typeof i[i[o]]!=="number"),a={};for(let o of s)a[o]=i[o];return e.objectValues(a)},e.objectValues=(i)=>e.objectKeys(i).map(function(s){return i[s]}),e.objectKeys=typeof Object.keys==="function"?(i)=>Object.keys(i):(i)=>{let s=[];for(let a in i)if(Object.prototype.hasOwnProperty.call(i,a))s.push(a);return s},e.find=(i,s)=>{for(let a of i)if(s(a))return a;return},e.isInteger=typeof Number.isInteger==="function"?(i)=>Number.isInteger(i):(i)=>typeof i==="number"&&Number.isFinite(i)&&Math.floor(i)===i;function r(i,s=" | "){return i.map((a)=>typeof a==="string"?`'${a}'`:a).join(s)}e.joinValues=r,e.jsonStringifyReplacer=(i,s)=>{if(typeof s==="bigint")return s.toString();return s}})(_e||(_e={}));var $h;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})($h||($h={}));var X=_e.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),_r=(e)=>{switch(typeof e){case"undefined":return X.undefined;case"string":return X.string;case"number":return Number.isNaN(e)?X.nan:X.number;case"boolean":return X.boolean;case"function":return X.function;case"bigint":return X.bigint;case"symbol":return X.symbol;case"object":if(Array.isArray(e))return X.array;if(e===null)return X.null;if(e.then&&typeof e.then==="function"&&e.catch&&typeof e.catch==="function")return X.promise;if(typeof Map<"u"&&e instanceof Map)return X.map;if(typeof Set<"u"&&e instanceof Set)return X.set;if(typeof Date<"u"&&e instanceof Date)return X.date;return X.object;default:return X.unknown}};var N=_e.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class Nt extends Error{get errors(){return this.issues}constructor(e){super();this.issues=[],this.addIssue=(n)=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let t=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,t);else this.__proto__=t;this.name="ZodError",this.issues=e}format(e){let t=e||function(i){return i.message},n={_errors:[]},r=(i)=>{for(let s of i.issues)if(s.code==="invalid_union")s.unionErrors.map(r);else if(s.code==="invalid_return_type")r(s.returnTypeError);else if(s.code==="invalid_arguments")r(s.argumentsError);else if(s.path.length===0)n._errors.push(t(s));else{let a=n,o=0;while(o<s.path.length){let l=s.path[o];if(o!==s.path.length-1)a[l]=a[l]||{_errors:[]};else a[l]=a[l]||{_errors:[]},a[l]._errors.push(t(s));a=a[l],o++}}};return r(this),n}static assert(e){if(!(e instanceof Nt))throw Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,_e.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=(t)=>t.message){let t={},n=[];for(let r of this.issues)if(r.path.length>0){let i=r.path[0];t[i]=t[i]||[],t[i].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}}Nt.create=(e)=>new Nt(e);var cC=(e,t)=>{let n;switch(e.code){case N.invalid_type:if(e.received===X.undefined)n="Required";else n=`Expected ${e.expected}, received ${e.received}`;break;case N.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,_e.jsonStringifyReplacer)}`;break;case N.unrecognized_keys:n=`Unrecognized key(s) in object: ${_e.joinValues(e.keys,", ")}`;break;case N.invalid_union:n="Invalid input";break;case N.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${_e.joinValues(e.options)}`;break;case N.invalid_enum_value:n=`Invalid enum value. Expected ${_e.joinValues(e.options)}, received '${e.received}'`;break;case N.invalid_arguments:n="Invalid function arguments";break;case N.invalid_return_type:n="Invalid function return type";break;case N.invalid_date:n="Invalid date";break;case N.invalid_string:if(typeof e.validation==="object")if("includes"in e.validation){if(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==="number")n=`${n} at one or more positions greater than or equal to ${e.validation.position}`}else if("startsWith"in e.validation)n=`Invalid input: must start with "${e.validation.startsWith}"`;else if("endsWith"in e.validation)n=`Invalid input: must end with "${e.validation.endsWith}"`;else _e.assertNever(e.validation);else if(e.validation!=="regex")n=`Invalid ${e.validation}`;else n="Invalid";break;case N.too_small:if(e.type==="array")n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`;else if(e.type==="string")n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`;else if(e.type==="number")n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`;else if(e.type==="bigint")n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`;else if(e.type==="date")n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`;else n="Invalid input";break;case N.too_big:if(e.type==="array")n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`;else if(e.type==="string")n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`;else if(e.type==="number")n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`;else if(e.type==="bigint")n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`;else if(e.type==="date")n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`;else n="Invalid input";break;case N.custom:n="Invalid input";break;case N.invalid_intersection_types:n="Intersection results could not be merged";break;case N.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case N.not_finite:n="Number must be finite";break;default:n=t.defaultError,_e.assertNever(e)}return{message:n}},Jr=cC;var uC=Jr;function ss(){return uC}var ja=(e)=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,s=[...n,...i.path||[]],a={...i,path:s};if(i.message!==void 0)return{...i,path:s,message:i.message};let o="",l=r.filter((c)=>!!c).slice().reverse();for(let c of l)o=c(a,{data:t,defaultError:o}).message;return{...i,path:s,message:o}};function q(e,t){let n=ss(),r=ja({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Jr?void 0:Jr].filter((i)=>!!i)});e.common.issues.push(r)}class xt{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(e,t){let n=[];for(let r of t){if(r.status==="aborted")return oe;if(r.status==="dirty")e.dirty();n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){let n=[];for(let r of t){let i=await r.key,s=await r.value;n.push({key:i,value:s})}return xt.mergeObjectSync(e,n)}static mergeObjectSync(e,t){let n={};for(let r of t){let{key:i,value:s}=r;if(i.status==="aborted")return oe;if(s.status==="aborted")return oe;if(i.status==="dirty")e.dirty();if(s.status==="dirty")e.dirty();if(i.value!=="__proto__"&&(typeof s.value<"u"||r.alwaysSet))n[i.value]=s.value}return{status:e.value,value:n}}}var oe=Object.freeze({status:"aborted"}),ti=(e)=>({status:"dirty",value:e}),Tt=(e)=>({status:"valid",value:e}),Pc=(e)=>e.status==="aborted",Nc=(e)=>e.status==="dirty",xn=(e)=>e.status==="valid",as=(e)=>typeof Promise<"u"&&e instanceof Promise;var ee;(function(e){e.errToObj=(t)=>typeof t==="string"?{message:t}:t||{},e.toString=(t)=>typeof t==="string"?t:t?.message})(ee||(ee={}));class er{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var Wh=(e,t)=>{if(xn(t))return{success:!0,data:t.value};else{if(!e.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new Nt(e.common.issues);return this._error=n,this._error}}}};function he(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(t)return{errorMap:t,description:i};return{errorMap:(a,o)=>{let{message:l}=e;if(a.code==="invalid_enum_value")return{message:l??o.defaultError};if(typeof o.data>"u")return{message:l??r??o.defaultError};if(a.code!=="invalid_type")return{message:o.defaultError};return{message:l??n??o.defaultError}},description:i}}class Ce{get description(){return this._def.description}_getType(e){return _r(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:_r(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new xt,ctx:{common:e.parent.common,data:e.data,parsedType:_r(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(as(t))throw Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:_r(e)},r=this._parseSync({data:e,path:n.path,parent:n});return Wh(n,r)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:_r(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:t});return xn(n)?{value:n.value}:{issues:t.common.issues}}catch(n){if(n?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then((n)=>xn(n)?{value:n.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:_r(e)},r=this._parse({data:e,path:n.path,parent:n}),i=await(as(r)?r:Promise.resolve(r));return Wh(n,i)}refine(e,t){let n=(r)=>{if(typeof t==="string"||typeof t>"u")return{message:t};else if(typeof t==="function")return t(r);else return t};return this._refinement((r,i)=>{let s=e(r),a=()=>i.addIssue({code:N.custom,...n(r)});if(typeof Promise<"u"&&s instanceof Promise)return s.then((o)=>{if(!o)return a(),!1;else return!0});if(!s)return a(),!1;else return!0})}refinement(e,t){return this._refinement((n,r)=>{if(!e(n))return r.addIssue(typeof t==="function"?t(n,r):t),!1;else return!0})}_refinement(e){return new mr({schema:this,typeName:le.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:(t)=>this["~validate"](t)}}optional(){return gr.create(this,this._def)}nullable(){return Zr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return hr.create(this)}promise(){return oi.create(this,this._def)}or(e){return ds.create([this,e],this._def)}and(e){return fs.create(this,e,this._def)}transform(e){return new mr({...he(this._def),schema:this,typeName:le.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e==="function"?e:()=>e;return new ms({...he(this._def),innerType:this,defaultValue:t,typeName:le.ZodDefault})}brand(){return new Uc({typeName:le.ZodBranded,type:this,...he(this._def)})}catch(e){let t=typeof e==="function"?e:()=>e;return new ys({...he(this._def),innerType:this,catchValue:t,typeName:le.ZodCatch})}describe(e){return new this.constructor({...this._def,description:e})}pipe(e){return eo.create(this,e)}readonly(){return vs.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var dC=/^c[^\s-]{8,}$/i,fC=/^[0-9a-z]+$/,pC=/^[0-9A-HJKMNP-TV-Z]{26}$/i,hC=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,gC=/^[a-z0-9_-]{21}$/i,mC=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,yC=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,vC=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,xC="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Dc,SC=/^(?:(?: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])$/,bC=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,CC=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,wC=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,EC=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,TC=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Kh="((\\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])))",AC=new RegExp(`^${Kh}$`);function qh(e){let t="[0-5]\\d";if(e.precision)t=`${t}\\.\\d{${e.precision}}`;else if(e.precision==null)t=`${t}(\\.\\d+)?`;let n=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function _C(e){return new RegExp(`^${qh(e)}$`)}function kC(e){let t=`${Kh}T${qh(e)}`,n=[];if(n.push(e.local?"Z?":"Z"),e.offset)n.push("([+-]\\d{2}:?\\d{2})");return t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function IC(e,t){if((t==="v4"||!t)&&SC.test(e))return!0;if((t==="v6"||!t)&&CC.test(e))return!0;return!1}function RC(e,t){if(!mC.test(e))return!1;try{let[n]=e.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),i=JSON.parse(atob(r));if(typeof i!=="object"||i===null)return!1;if("typ"in i&&i?.typ!=="JWT")return!1;if(!i.alg)return!1;if(t&&i.alg!==t)return!1;return!0}catch{return!1}}function BC(e,t){if((t==="v4"||!t)&&bC.test(e))return!0;if((t==="v6"||!t)&&wC.test(e))return!0;return!1}class Ir extends Ce{_parse(e){if(this._def.coerce)e.data=String(e.data);if(this._getType(e)!==X.string){let i=this._getOrReturnCtx(e);return q(i,{code:N.invalid_type,expected:X.string,received:i.parsedType}),oe}let n=new xt,r=void 0;for(let i of this._def.checks)if(i.kind==="min"){if(e.data.length<i.value)r=this._getOrReturnCtx(e,r),q(r,{code:N.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty()}else if(i.kind==="max"){if(e.data.length>i.value)r=this._getOrReturnCtx(e,r),q(r,{code:N.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty()}else if(i.kind==="length"){let s=e.data.length>i.value,a=e.data.length<i.value;if(s||a){if(r=this._getOrReturnCtx(e,r),s)q(r,{code:N.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message});else if(a)q(r,{code:N.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message});n.dirty()}}else if(i.kind==="email"){if(!vC.test(e.data))r=this._getOrReturnCtx(e,r),q(r,{validation:"email",code:N.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="emoji"){if(!Dc)Dc=new RegExp(xC,"u");if(!Dc.test(e.data))r=this._getOrReturnCtx(e,r),q(r,{validation:"emoji",code:N.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="uuid"){if(!hC.test(e.data))r=this._getOrReturnCtx(e,r),q(r,{validation:"uuid",code:N.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="nanoid"){if(!gC.test(e.data))r=this._getOrReturnCtx(e,r),q(r,{validation:"nanoid",code:N.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="cuid"){if(!dC.test(e.data))r=this._getOrReturnCtx(e,r),q(r,{validation:"cuid",code:N.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="cuid2"){if(!fC.test(e.data))r=this._getOrReturnCtx(e,r),q(r,{validation:"cuid2",code:N.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="ulid"){if(!pC.test(e.data))r=this._getOrReturnCtx(e,r),q(r,{validation:"ulid",code:N.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="url")try{new URL(e.data)}catch{r=this._getOrReturnCtx(e,r),q(r,{validation:"url",code:N.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="regex"){if(i.regex.lastIndex=0,!i.regex.test(e.data))r=this._getOrReturnCtx(e,r),q(r,{validation:"regex",code:N.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="trim")e.data=e.data.trim();else if(i.kind==="includes"){if(!e.data.includes(i.value,i.position))r=this._getOrReturnCtx(e,r),q(r,{code:N.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),n.dirty()}else if(i.kind==="toLowerCase")e.data=e.data.toLowerCase();else if(i.kind==="toUpperCase")e.data=e.data.toUpperCase();else if(i.kind==="startsWith"){if(!e.data.startsWith(i.value))r=this._getOrReturnCtx(e,r),q(r,{code:N.invalid_string,validation:{startsWith:i.value},message:i.message}),n.dirty()}else if(i.kind==="endsWith"){if(!e.data.endsWith(i.value))r=this._getOrReturnCtx(e,r),q(r,{code:N.invalid_string,validation:{endsWith:i.value},message:i.message}),n.dirty()}else if(i.kind==="datetime"){if(!kC(i).test(e.data))r=this._getOrReturnCtx(e,r),q(r,{code:N.invalid_string,validation:"datetime",message:i.message}),n.dirty()}else if(i.kind==="date"){if(!AC.test(e.data))r=this._getOrReturnCtx(e,r),q(r,{code:N.invalid_string,validation:"date",message:i.message}),n.dirty()}else if(i.kind==="time"){if(!_C(i).test(e.data))r=this._getOrReturnCtx(e,r),q(r,{code:N.invalid_string,validation:"time",message:i.message}),n.dirty()}else if(i.kind==="duration"){if(!yC.test(e.data))r=this._getOrReturnCtx(e,r),q(r,{validation:"duration",code:N.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="ip"){if(!IC(e.data,i.version))r=this._getOrReturnCtx(e,r),q(r,{validation:"ip",code:N.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="jwt"){if(!RC(e.data,i.alg))r=this._getOrReturnCtx(e,r),q(r,{validation:"jwt",code:N.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="cidr"){if(!BC(e.data,i.version))r=this._getOrReturnCtx(e,r),q(r,{validation:"cidr",code:N.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="base64"){if(!EC.test(e.data))r=this._getOrReturnCtx(e,r),q(r,{validation:"base64",code:N.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="base64url"){if(!TC.test(e.data))r=this._getOrReturnCtx(e,r),q(r,{validation:"base64url",code:N.invalid_string,message:i.message}),n.dirty()}else _e.assertNever(i);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement((r)=>e.test(r),{validation:t,code:N.invalid_string,...ee.errToObj(n)})}_addCheck(e){return new Ir({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...ee.errToObj(e)})}url(e){return this._addCheck({kind:"url",...ee.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...ee.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...ee.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...ee.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...ee.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...ee.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...ee.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...ee.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...ee.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...ee.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...ee.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...ee.errToObj(e)})}datetime(e){if(typeof e==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e});return this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...ee.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){if(typeof e==="string")return this._addCheck({kind:"time",precision:null,message:e});return this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...ee.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...ee.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...ee.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...ee.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...ee.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...ee.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...ee.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...ee.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...ee.errToObj(t)})}nonempty(e){return this.min(1,ee.errToObj(e))}trim(){return new Ir({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Ir({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Ir({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((e)=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find((e)=>e.kind==="date")}get isTime(){return!!this._def.checks.find((e)=>e.kind==="time")}get isDuration(){return!!this._def.checks.find((e)=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find((e)=>e.kind==="email")}get isURL(){return!!this._def.checks.find((e)=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find((e)=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find((e)=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((e)=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((e)=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((e)=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find((e)=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find((e)=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find((e)=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find((e)=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find((e)=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e}get maxLength(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e}}Ir.create=(e)=>new Ir({checks:[],typeName:le.ZodString,coerce:e?.coerce??!1,...he(e)});function PC(e,t){let n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,i=n>r?n:r,s=Number.parseInt(e.toFixed(i).replace(".","")),a=Number.parseInt(t.toFixed(i).replace(".",""));return s%a/10**i}class ni extends Ce{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce)e.data=Number(e.data);if(this._getType(e)!==X.number){let i=this._getOrReturnCtx(e);return q(i,{code:N.invalid_type,expected:X.number,received:i.parsedType}),oe}let n=void 0,r=new xt;for(let i of this._def.checks)if(i.kind==="int"){if(!_e.isInteger(e.data))n=this._getOrReturnCtx(e,n),q(n,{code:N.invalid_type,expected:"integer",received:"float",message:i.message}),r.dirty()}else if(i.kind==="min"){if(i.inclusive?e.data<i.value:e.data<=i.value)n=this._getOrReturnCtx(e,n),q(n,{code:N.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()}else if(i.kind==="max"){if(i.inclusive?e.data>i.value:e.data>=i.value)n=this._getOrReturnCtx(e,n),q(n,{code:N.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()}else if(i.kind==="multipleOf"){if(PC(e.data,i.value)!==0)n=this._getOrReturnCtx(e,n),q(n,{code:N.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()}else if(i.kind==="finite"){if(!Number.isFinite(e.data))n=this._getOrReturnCtx(e,n),q(n,{code:N.not_finite,message:i.message}),r.dirty()}else _e.assertNever(i);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,ee.toString(t))}gt(e,t){return this.setLimit("min",e,!1,ee.toString(t))}lte(e,t){return this.setLimit("max",e,!0,ee.toString(t))}lt(e,t){return this.setLimit("max",e,!1,ee.toString(t))}setLimit(e,t,n,r){return new ni({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:ee.toString(r)}]})}_addCheck(e){return new ni({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:ee.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:ee.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:ee.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:ee.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:ee.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:ee.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:ee.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:ee.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:ee.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e}get maxValue(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e}get isInt(){return!!this._def.checks.find((e)=>e.kind==="int"||e.kind==="multipleOf"&&_e.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks)if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;else if(n.kind==="min"){if(t===null||n.value>t)t=n.value}else if(n.kind==="max"){if(e===null||n.value<e)e=n.value}return Number.isFinite(t)&&Number.isFinite(e)}}ni.create=(e)=>new ni({checks:[],typeName:le.ZodNumber,coerce:e?.coerce||!1,...he(e)});class ii extends Ce{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==X.bigint)return this._getInvalidInput(e);let n=void 0,r=new xt;for(let i of this._def.checks)if(i.kind==="min"){if(i.inclusive?e.data<i.value:e.data<=i.value)n=this._getOrReturnCtx(e,n),q(n,{code:N.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),r.dirty()}else if(i.kind==="max"){if(i.inclusive?e.data>i.value:e.data>=i.value)n=this._getOrReturnCtx(e,n),q(n,{code:N.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),r.dirty()}else if(i.kind==="multipleOf"){if(e.data%i.value!==BigInt(0))n=this._getOrReturnCtx(e,n),q(n,{code:N.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()}else _e.assertNever(i);return{status:r.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return q(t,{code:N.invalid_type,expected:X.bigint,received:t.parsedType}),oe}gte(e,t){return this.setLimit("min",e,!0,ee.toString(t))}gt(e,t){return this.setLimit("min",e,!1,ee.toString(t))}lte(e,t){return this.setLimit("max",e,!0,ee.toString(t))}lt(e,t){return this.setLimit("max",e,!1,ee.toString(t))}setLimit(e,t,n,r){return new ii({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:ee.toString(r)}]})}_addCheck(e){return new ii({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:ee.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:ee.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:ee.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:ee.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:ee.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e}get maxValue(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e}}ii.create=(e)=>new ii({checks:[],typeName:le.ZodBigInt,coerce:e?.coerce??!1,...he(e)});class za extends Ce{_parse(e){if(this._def.coerce)e.data=Boolean(e.data);if(this._getType(e)!==X.boolean){let n=this._getOrReturnCtx(e);return q(n,{code:N.invalid_type,expected:X.boolean,received:n.parsedType}),oe}return Tt(e.data)}}za.create=(e)=>new za({typeName:le.ZodBoolean,coerce:e?.coerce||!1,...he(e)});class ls extends Ce{_parse(e){if(this._def.coerce)e.data=new Date(e.data);if(this._getType(e)!==X.date){let i=this._getOrReturnCtx(e);return q(i,{code:N.invalid_type,expected:X.date,received:i.parsedType}),oe}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return q(i,{code:N.invalid_date}),oe}let n=new xt,r=void 0;for(let i of this._def.checks)if(i.kind==="min"){if(e.data.getTime()<i.value)r=this._getOrReturnCtx(e,r),q(r,{code:N.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),n.dirty()}else if(i.kind==="max"){if(e.data.getTime()>i.value)r=this._getOrReturnCtx(e,r),q(r,{code:N.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()}else _e.assertNever(i);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ls({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:ee.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:ee.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e!=null?new Date(e):null}}ls.create=(e)=>new ls({checks:[],coerce:e?.coerce||!1,typeName:le.ZodDate,...he(e)});class Xa extends Ce{_parse(e){if(this._getType(e)!==X.symbol){let n=this._getOrReturnCtx(e);return q(n,{code:N.invalid_type,expected:X.symbol,received:n.parsedType}),oe}return Tt(e.data)}}Xa.create=(e)=>new Xa({typeName:le.ZodSymbol,...he(e)});class cs extends Ce{_parse(e){if(this._getType(e)!==X.undefined){let n=this._getOrReturnCtx(e);return q(n,{code:N.invalid_type,expected:X.undefined,received:n.parsedType}),oe}return Tt(e.data)}}cs.create=(e)=>new cs({typeName:le.ZodUndefined,...he(e)});class us extends Ce{_parse(e){if(this._getType(e)!==X.null){let n=this._getOrReturnCtx(e);return q(n,{code:N.invalid_type,expected:X.null,received:n.parsedType}),oe}return Tt(e.data)}}us.create=(e)=>new us({typeName:le.ZodNull,...he(e)});class si extends Ce{constructor(){super(...arguments);this._any=!0}_parse(e){return Tt(e.data)}}si.create=(e)=>new si({typeName:le.ZodAny,...he(e)});class Sn extends Ce{constructor(){super(...arguments);this._unknown=!0}_parse(e){return Tt(e.data)}}Sn.create=(e)=>new Sn({typeName:le.ZodUnknown,...he(e)});class Rr extends Ce{_parse(e){let t=this._getOrReturnCtx(e);return q(t,{code:N.invalid_type,expected:X.never,received:t.parsedType}),oe}}Rr.create=(e)=>new Rr({typeName:le.ZodNever,...he(e)});class Qa extends Ce{_parse(e){if(this._getType(e)!==X.undefined){let n=this._getOrReturnCtx(e);return q(n,{code:N.invalid_type,expected:X.void,received:n.parsedType}),oe}return Tt(e.data)}}Qa.create=(e)=>new Qa({typeName:le.ZodVoid,...he(e)});class hr extends Ce{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==X.array)return q(t,{code:N.invalid_type,expected:X.array,received:t.parsedType}),oe;if(r.exactLength!==null){let s=t.data.length>r.exactLength.value,a=t.data.length<r.exactLength.value;if(s||a)q(t,{code:s?N.too_big:N.too_small,minimum:a?r.exactLength.value:void 0,maximum:s?r.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty()}if(r.minLength!==null){if(t.data.length<r.minLength.value)q(t,{code:N.too_small,minimum:r.minLength.value,type:"array",inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()}if(r.maxLength!==null){if(t.data.length>r.maxLength.value)q(t,{code:N.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()}if(t.common.async)return Promise.all([...t.data].map((s,a)=>r.type._parseAsync(new er(t,s,t.path,a)))).then((s)=>xt.mergeArray(n,s));let i=[...t.data].map((s,a)=>r.type._parseSync(new er(t,s,t.path,a)));return xt.mergeArray(n,i)}get element(){return this._def.type}min(e,t){return new hr({...this._def,minLength:{value:e,message:ee.toString(t)}})}max(e,t){return new hr({...this._def,maxLength:{value:e,message:ee.toString(t)}})}length(e,t){return new hr({...this._def,exactLength:{value:e,message:ee.toString(t)}})}nonempty(e){return this.min(1,e)}}hr.create=(e,t)=>new hr({type:e,minLength:null,maxLength:null,exactLength:null,typeName:le.ZodArray,...he(t)});function ri(e){if(e instanceof Ze){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=gr.create(ri(r))}return new Ze({...e._def,shape:()=>t})}else if(e instanceof hr)return new hr({...e._def,type:ri(e.element)});else if(e instanceof gr)return gr.create(ri(e.unwrap()));else if(e instanceof Zr)return Zr.create(ri(e.unwrap()));else if(e instanceof Br)return Br.create(e.items.map((t)=>ri(t)));else return e}class Ze extends Ce{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=_e.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==X.object){let l=this._getOrReturnCtx(e);return q(l,{code:N.invalid_type,expected:X.object,received:l.parsedType}),oe}let{status:n,ctx:r}=this._processInputParams(e),{shape:i,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof Rr&&this._def.unknownKeys==="strip")){for(let l in r.data)if(!s.includes(l))a.push(l)}let o=[];for(let l of s){let c=i[l],u=r.data[l];o.push({key:{status:"valid",value:l},value:c._parse(new er(r,u,r.path,l)),alwaysSet:l in r.data})}if(this._def.catchall instanceof Rr){let l=this._def.unknownKeys;if(l==="passthrough")for(let c of a)o.push({key:{status:"valid",value:c},value:{status:"valid",value:r.data[c]}});else if(l==="strict"){if(a.length>0)q(r,{code:N.unrecognized_keys,keys:a}),n.dirty()}else if(l==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let c of a){let u=r.data[c];o.push({key:{status:"valid",value:c},value:l._parse(new er(r,u,r.path,c)),alwaysSet:c in r.data})}}if(r.common.async)return Promise.resolve().then(async()=>{let l=[];for(let c of o){let u=await c.key,d=await c.value;l.push({key:u,value:d,alwaysSet:c.alwaysSet})}return l}).then((l)=>xt.mergeObjectSync(n,l));else return xt.mergeObjectSync(n,o)}get shape(){return this._def.shape()}strict(e){return ee.errToObj,new Ze({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{let r=this._def.errorMap?.(t,n).message??n.defaultError;if(t.code==="unrecognized_keys")return{message:ee.errToObj(e).message??r};return{message:r}}}:{}})}strip(){return new Ze({...this._def,unknownKeys:"strip"})}passthrough(){return new Ze({...this._def,unknownKeys:"passthrough"})}extend(e){return new Ze({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new Ze({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:le.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new Ze({...this._def,catchall:e})}pick(e){let t={};for(let n of _e.objectKeys(e))if(e[n]&&this.shape[n])t[n]=this.shape[n];return new Ze({...this._def,shape:()=>t})}omit(e){let t={};for(let n of _e.objectKeys(this.shape))if(!e[n])t[n]=this.shape[n];return new Ze({...this._def,shape:()=>t})}deepPartial(){return ri(this)}partial(e){let t={};for(let n of _e.objectKeys(this.shape)){let r=this.shape[n];if(e&&!e[n])t[n]=r;else t[n]=r.optional()}return new Ze({...this._def,shape:()=>t})}required(e){let t={};for(let n of _e.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let i=this.shape[n];while(i instanceof gr)i=i._def.innerType;t[n]=i}return new Ze({...this._def,shape:()=>t})}keyof(){return Gh(_e.objectKeys(this.shape))}}Ze.create=(e,t)=>new Ze({shape:()=>e,unknownKeys:"strip",catchall:Rr.create(),typeName:le.ZodObject,...he(t)});Ze.strictCreate=(e,t)=>new Ze({shape:()=>e,unknownKeys:"strict",catchall:Rr.create(),typeName:le.ZodObject,...he(t)});Ze.lazycreate=(e,t)=>new Ze({shape:e,unknownKeys:"strip",catchall:Rr.create(),typeName:le.ZodObject,...he(t)});class ds extends Ce{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function r(i){for(let a of i)if(a.result.status==="valid")return a.result;for(let a of i)if(a.result.status==="dirty")return t.common.issues.push(...a.ctx.common.issues),a.result;let s=i.map((a)=>new Nt(a.ctx.common.issues));return q(t,{code:N.invalid_union,unionErrors:s}),oe}if(t.common.async)return Promise.all(n.map(async(i)=>{let s={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:s}),ctx:s}})).then(r);else{let i=void 0,s=[];for(let o of n){let l={...t,common:{...t.common,issues:[]},parent:null},c=o._parseSync({data:t.data,path:t.path,parent:l});if(c.status==="valid")return c;else if(c.status==="dirty"&&!i)i={result:c,ctx:l};if(l.common.issues.length)s.push(l.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;let a=s.map((o)=>new Nt(o));return q(t,{code:N.invalid_union,unionErrors:a}),oe}}get options(){return this._def.options}}ds.create=(e,t)=>new ds({options:e,typeName:le.ZodUnion,...he(t)});var kr=(e)=>{if(e instanceof ps)return kr(e.schema);else if(e instanceof mr)return kr(e.innerType());else if(e instanceof hs)return[e.value];else if(e instanceof bn)return e.options;else if(e instanceof gs)return _e.objectValues(e.enum);else if(e instanceof ms)return kr(e._def.innerType);else if(e instanceof cs)return[void 0];else if(e instanceof us)return[null];else if(e instanceof gr)return[void 0,...kr(e.unwrap())];else if(e instanceof Zr)return[null,...kr(e.unwrap())];else if(e instanceof Uc)return kr(e.unwrap());else if(e instanceof vs)return kr(e.unwrap());else if(e instanceof ys)return kr(e._def.innerType);else return[]};class Oc extends Ce{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==X.object)return q(t,{code:N.invalid_type,expected:X.object,received:t.parsedType}),oe;let n=this.discriminator,r=t.data[n],i=this.optionsMap.get(r);if(!i)return q(t,{code:N.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),oe;if(t.common.async)return i._parseAsync({data:t.data,path:t.path,parent:t});else return i._parseSync({data:t.data,path:t.path,parent:t})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){let r=new Map;for(let i of t){let s=kr(i.shape[e]);if(!s.length)throw Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of s){if(r.has(a))throw Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);r.set(a,i)}}return new Oc({typeName:le.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:r,...he(n)})}}function Lc(e,t){let n=_r(e),r=_r(t);if(e===t)return{valid:!0,data:e};else if(n===X.object&&r===X.object){let i=_e.objectKeys(t),s=_e.objectKeys(e).filter((o)=>i.indexOf(o)!==-1),a={...e,...t};for(let o of s){let l=Lc(e[o],t[o]);if(!l.valid)return{valid:!1};a[o]=l.data}return{valid:!0,data:a}}else if(n===X.array&&r===X.array){if(e.length!==t.length)return{valid:!1};let i=[];for(let s=0;s<e.length;s++){let a=e[s],o=t[s],l=Lc(a,o);if(!l.valid)return{valid:!1};i.push(l.data)}return{valid:!0,data:i}}else if(n===X.date&&r===X.date&&+e===+t)return{valid:!0,data:e};else return{valid:!1}}class fs extends Ce{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(i,s)=>{if(Pc(i)||Pc(s))return oe;let a=Lc(i.value,s.value);if(!a.valid)return q(n,{code:N.invalid_intersection_types}),oe;if(Nc(i)||Nc(s))t.dirty();return{status:t.value,value:a.data}};if(n.common.async)return Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([i,s])=>r(i,s));else return r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}fs.create=(e,t,n)=>new fs({left:e,right:t,typeName:le.ZodIntersection,...he(n)});class Br extends Ce{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==X.array)return q(n,{code:N.invalid_type,expected:X.array,received:n.parsedType}),oe;if(n.data.length<this._def.items.length)return q(n,{code:N.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),oe;if(!this._def.rest&&n.data.length>this._def.items.length)q(n,{code:N.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty();let i=[...n.data].map((s,a)=>{let o=this._def.items[a]||this._def.rest;if(!o)return null;return o._parse(new er(n,s,n.path,a))}).filter((s)=>!!s);if(n.common.async)return Promise.all(i).then((s)=>xt.mergeArray(t,s));else return xt.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new Br({...this._def,rest:e})}}Br.create=(e,t)=>{if(!Array.isArray(e))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new Br({items:e,typeName:le.ZodTuple,rest:null,...he(t)})};class Ya extends Ce{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==X.object)return q(n,{code:N.invalid_type,expected:X.object,received:n.parsedType}),oe;let r=[],i=this._def.keyType,s=this._def.valueType;for(let a in n.data)r.push({key:i._parse(new er(n,a,n.path,a)),value:s._parse(new er(n,n.data[a],n.path,a)),alwaysSet:a in n.data});if(n.common.async)return xt.mergeObjectAsync(t,r);else return xt.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(e,t,n){if(t instanceof Ce)return new Ya({keyType:e,valueType:t,typeName:le.ZodRecord,...he(n)});return new Ya({keyType:Ir.create(),valueType:e,typeName:le.ZodRecord,...he(t)})}}class Ja extends Ce{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==X.map)return q(n,{code:N.invalid_type,expected:X.map,received:n.parsedType}),oe;let r=this._def.keyType,i=this._def.valueType,s=[...n.data.entries()].map(([a,o],l)=>({key:r._parse(new er(n,a,n.path,[l,"key"])),value:i._parse(new er(n,o,n.path,[l,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let o of s){let l=await o.key,c=await o.value;if(l.status==="aborted"||c.status==="aborted")return oe;if(l.status==="dirty"||c.status==="dirty")t.dirty();a.set(l.value,c.value)}return{status:t.value,value:a}})}else{let a=new Map;for(let o of s){let{key:l,value:c}=o;if(l.status==="aborted"||c.status==="aborted")return oe;if(l.status==="dirty"||c.status==="dirty")t.dirty();a.set(l.value,c.value)}return{status:t.value,value:a}}}}Ja.create=(e,t,n)=>new Ja({valueType:t,keyType:e,typeName:le.ZodMap,...he(n)});class ai extends Ce{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==X.set)return q(n,{code:N.invalid_type,expected:X.set,received:n.parsedType}),oe;let r=this._def;if(r.minSize!==null){if(n.data.size<r.minSize.value)q(n,{code:N.too_small,minimum:r.minSize.value,type:"set",inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()}if(r.maxSize!==null){if(n.data.size>r.maxSize.value)q(n,{code:N.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty()}let i=this._def.valueType;function s(o){let l=new Set;for(let c of o){if(c.status==="aborted")return oe;if(c.status==="dirty")t.dirty();l.add(c.value)}return{status:t.value,value:l}}let a=[...n.data.values()].map((o,l)=>i._parse(new er(n,o,n.path,l)));if(n.common.async)return Promise.all(a).then((o)=>s(o));else return s(a)}min(e,t){return new ai({...this._def,minSize:{value:e,message:ee.toString(t)}})}max(e,t){return new ai({...this._def,maxSize:{value:e,message:ee.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}ai.create=(e,t)=>new ai({valueType:e,minSize:null,maxSize:null,typeName:le.ZodSet,...he(t)});class os extends Ce{constructor(){super(...arguments);this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==X.function)return q(t,{code:N.invalid_type,expected:X.function,received:t.parsedType}),oe;function n(a,o){return ja({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ss(),Jr].filter((l)=>!!l),issueData:{code:N.invalid_arguments,argumentsError:o}})}function r(a,o){return ja({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ss(),Jr].filter((l)=>!!l),issueData:{code:N.invalid_return_type,returnTypeError:o}})}let i={errorMap:t.common.contextualErrorMap},s=t.data;if(this._def.returns instanceof oi){let a=this;return Tt(async function(...o){let l=new Nt([]),c=await a._def.args.parseAsync(o,i).catch((p)=>{throw l.addIssue(n(o,p)),l}),u=await Reflect.apply(s,this,c);return await a._def.returns._def.type.parseAsync(u,i).catch((p)=>{throw l.addIssue(r(u,p)),l})})}else{let a=this;return Tt(function(...o){let l=a._def.args.safeParse(o,i);if(!l.success)throw new Nt([n(o,l.error)]);let c=Reflect.apply(s,this,l.data),u=a._def.returns.safeParse(c,i);if(!u.success)throw new Nt([r(c,u.error)]);return u.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new os({...this._def,args:Br.create(e).rest(Sn.create())})}returns(e){return new os({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new os({args:e?e:Br.create([]).rest(Sn.create()),returns:t||Sn.create(),typeName:le.ZodFunction,...he(n)})}}class ps extends Ce{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}ps.create=(e,t)=>new ps({getter:e,typeName:le.ZodLazy,...he(t)});class hs extends Ce{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return q(t,{received:t.data,code:N.invalid_literal,expected:this._def.value}),oe}return{status:"valid",value:e.data}}get value(){return this._def.value}}hs.create=(e,t)=>new hs({value:e,typeName:le.ZodLiteral,...he(t)});function Gh(e,t){return new bn({values:e,typeName:le.ZodEnum,...he(t)})}class bn extends Ce{_parse(e){if(typeof e.data!=="string"){let t=this._getOrReturnCtx(e),n=this._def.values;return q(t,{expected:_e.joinValues(n),received:t.parsedType,code:N.invalid_type}),oe}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return q(t,{received:t.data,code:N.invalid_enum_value,options:n}),oe}return Tt(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return bn.create(e,{...this._def,...t})}exclude(e,t=this._def){return bn.create(this.options.filter((n)=>!e.includes(n)),{...this._def,...t})}}bn.create=Gh;class gs extends Ce{_parse(e){let t=_e.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==X.string&&n.parsedType!==X.number){let r=_e.objectValues(t);return q(n,{expected:_e.joinValues(r),received:n.parsedType,code:N.invalid_type}),oe}if(!this._cache)this._cache=new Set(_e.getValidEnumValues(this._def.values));if(!this._cache.has(e.data)){let r=_e.objectValues(t);return q(n,{received:n.data,code:N.invalid_enum_value,options:r}),oe}return Tt(e.data)}get enum(){return this._def.values}}gs.create=(e,t)=>new gs({values:e,typeName:le.ZodNativeEnum,...he(t)});class oi extends Ce{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==X.promise&&t.common.async===!1)return q(t,{code:N.invalid_type,expected:X.promise,received:t.parsedType}),oe;let n=t.parsedType===X.promise?t.data:Promise.resolve(t.data);return Tt(n.then((r)=>this._def.type.parseAsync(r,{path:t.path,errorMap:t.common.contextualErrorMap})))}}oi.create=(e,t)=>new oi({type:e,typeName:le.ZodPromise,...he(t)});class mr extends Ce{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===le.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:(s)=>{if(q(n,s),s.fatal)t.abort();else t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),r.type==="preprocess"){let s=r.transform(n.data,i);if(n.common.async)return Promise.resolve(s).then(async(a)=>{if(t.value==="aborted")return oe;let o=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});if(o.status==="aborted")return oe;if(o.status==="dirty")return ti(o.value);if(t.value==="dirty")return ti(o.value);return o});else{if(t.value==="aborted")return oe;let a=this._def.schema._parseSync({data:s,path:n.path,parent:n});if(a.status==="aborted")return oe;if(a.status==="dirty")return ti(a.value);if(t.value==="dirty")return ti(a.value);return a}}if(r.type==="refinement"){let s=(a)=>{let o=r.refinement(a,i);if(n.common.async)return Promise.resolve(o);if(o instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(a.status==="aborted")return oe;if(a.status==="dirty")t.dirty();return s(a.value),{status:t.value,value:a.value}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then((a)=>{if(a.status==="aborted")return oe;if(a.status==="dirty")t.dirty();return s(a.value).then(()=>({status:t.value,value:a.value}))})}if(r.type==="transform")if(n.common.async===!1){let s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!xn(s))return oe;let a=r.transform(s.value,i);if(a instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then((s)=>{if(!xn(s))return oe;return Promise.resolve(r.transform(s.value,i)).then((a)=>({status:t.value,value:a}))});_e.assertNever(r)}}mr.create=(e,t,n)=>new mr({schema:e,typeName:le.ZodEffects,effect:t,...he(n)});mr.createWithPreprocess=(e,t,n)=>new mr({schema:t,effect:{type:"preprocess",transform:e},typeName:le.ZodEffects,...he(n)});class gr extends Ce{_parse(e){if(this._getType(e)===X.undefined)return Tt(void 0);return this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}gr.create=(e,t)=>new gr({innerType:e,typeName:le.ZodOptional,...he(t)});class Zr extends Ce{_parse(e){if(this._getType(e)===X.null)return Tt(null);return this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Zr.create=(e,t)=>new Zr({innerType:e,typeName:le.ZodNullable,...he(t)});class ms extends Ce{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;if(t.parsedType===X.undefined)n=this._def.defaultValue();return this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}ms.create=(e,t)=>new ms({innerType:e,typeName:le.ZodDefault,defaultValue:typeof t.default==="function"?t.default:()=>t.default,...he(t)});class ys extends Ce{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});if(as(r))return r.then((i)=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Nt(n.common.issues)},input:n.data})}));else return{status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new Nt(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}ys.create=(e,t)=>new ys({innerType:e,typeName:le.ZodCatch,catchValue:typeof t.catch==="function"?t.catch:()=>t.catch,...he(t)});class Za extends Ce{_parse(e){if(this._getType(e)!==X.nan){let n=this._getOrReturnCtx(e);return q(n,{code:N.invalid_type,expected:X.nan,received:n.parsedType}),oe}return{status:"valid",value:e.data}}}Za.create=(e)=>new Za({typeName:le.ZodNaN,...he(e)});var OA=Symbol("zod_brand");class Uc extends Ce{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}}class eo extends Ce{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});if(i.status==="aborted")return oe;if(i.status==="dirty")return t.dirty(),ti(i.value);else return this._def.out._parseAsync({data:i.value,path:n.path,parent:n})})();else{let r=this._def.in._parseSync({data:n.data,path:n.path,parent:n});if(r.status==="aborted")return oe;if(r.status==="dirty")return t.dirty(),{status:"dirty",value:r.value};else return this._def.out._parseSync({data:r.value,path:n.path,parent:n})}}static create(e,t){return new eo({in:e,out:t,typeName:le.ZodPipeline})}}class vs extends Ce{_parse(e){let t=this._def.innerType._parse(e),n=(r)=>{if(xn(r))r.value=Object.freeze(r.value);return r};return as(t)?t.then((r)=>n(r)):n(t)}unwrap(){return this._def.innerType}}vs.create=(e,t)=>new vs({innerType:e,typeName:le.ZodReadonly,...he(t)});function Hh(e,t){let n=typeof e==="function"?e(t):typeof e==="string"?{message:e}:e;return typeof n==="string"?{message:n}:n}function NC(e,t={},n){if(e)return si.create().superRefine((r,i)=>{let s=e(r);if(s instanceof Promise)return s.then((a)=>{if(!a){let o=Hh(t,r),l=o.fatal??n??!0;i.addIssue({code:"custom",...o,fatal:l})}});if(!s){let a=Hh(t,r),o=a.fatal??n??!0;i.addIssue({code:"custom",...a,fatal:o})}return});return si.create()}var UA={object:Ze.lazycreate},le;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(le||(le={}));var Se=Ir.create,Pr=ni.create,VA=Za.create,FA=ii.create,Kt=za.create,MA=ls.create,$A=Xa.create,WA=cs.create,HA=us.create,KA=si.create,qA=Sn.create,GA=Rr.create,jA=Qa.create,ze=hr.create,{create:ht,strictCreate:zA}=Ze,XA=ds.create,QA=Oc.create,YA=fs.create,DC=Br.create,jh=Ya.create,JA=Ja.create,ZA=ai.create,e_=os.create,t_=ps.create,r_=hs.create,li=bn.create,n_=gs.create,i_=oi.create,s_=mr.create,a_=gr.create,o_=Zr.create,l_=mr.createWithPreprocess,c_=eo.create;function Fc(e){if(OC(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 Mc='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.',ro=Se().refine(Fc,{message:Mc});function Qh(e){let t=e.indexOf(":");return!(t!==-1&&e.indexOf(":",t+1)!==-1)||e.startsWith("[")}var VC=Se().refine((e)=>Qh(e)&&Fc(Xi(e).hostPattern),{message:Mc+' An optional ":port" suffix (1-65535) restricts the entry to that port.'}),FC=Se().refine((e)=>{if(!Qh(e))return!1;let{hostPattern:t}=Xi(e);return t==="*"||Fc(t)},{message:Mc+' In deniedDomains a bare "*" (deny-all) is also accepted, and an optional ":port" suffix (1-65535) restricts the entry to that port.'}),xs=Se().min(1,"Path cannot be empty"),zh=Se().min(1,"Path cannot be empty").refine((e)=>UC(e),{message:"Binary path must be absolute"}),MC=ht({socketPath:Se().min(1).describe("Unix socket path to the MITM proxy"),domains:ze(ro).min(1).describe('Domains to route through the MITM proxy (e.g., ["api.example.com", "*.internal.org"])')}),$C=ht({http:Se().url().optional().describe("Upstream proxy URL for plain HTTP traffic"),https:Se().url().optional().describe("Upstream proxy URL for HTTPS/CONNECT traffic (falls back to http if unset)"),noProxy:Se().optional().describe("Comma-separated NO_PROXY list (hostname suffixes and CIDR ranges). Matching destinations connect directly instead of via the parent proxy.")}),Yh=li(["deny","mask"]),to=Se().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"),Jh=Se().superRefine((e,t)=>{try{let{groupCount:n}=Ml(e);if(n<1)t.addIssue({code:N.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:N.custom,message:n instanceof Error?n.message:"Credential extract pattern is invalid"})}}),WC=ht({path:xs.describe("Path to a credential file or directory. Supports the same path forms as filesystem.denyRead (absolute paths and ~ expansion)."),mode:Yh.describe("Access mode for this path"),extract:Jh.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:li(["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:li(["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(Se().min(1)).optional().describe('Names of top-level payload claims to mask inside each decoded value, instead of replacing the whole token. Each named claim present with a string value gets its own sentinel; all other claims are preserved so claim-reading clients keep working. Requires decode. If no named claim matches in any verified token, behaviour is governed by onExtractNoMatch (default "warn"). Only meaningful when mode is "mask"; accepted but ignored for "deny".'),maskDuplicates:Kt().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(ro).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".')}),HC=ht({name:to.describe("Environment variable name"),mode:Yh.describe("Access mode for this environment variable"),extract:Jh.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:li(["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:li(["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(Se().min(1)).optional().describe('Names of top-level payload claims to mask inside the decoded value, instead of replacing the whole token. Each named claim present with a string value gets its own sentinel; all other claims are preserved so claim-reading clients keep working. Requires decode. If no named claim matches, the variable is left unmasked with a stderr warning (fail-open). Only meaningful when mode is "mask"; accepted but ignored for "deny".'),injectHosts:ze(ro).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(Se().regex(/^[a-z0-9-]{1,64}$/)).min(1).optional().describe('Optional narrowing of where in a request the proxy substitutes this credential: only in these headers (lower-case names), never in other headers or the body. If unset, every header and the body. Only meaningful when mode is "mask".')}),KC=ht({accessKeyIdVar:to.describe("Name of the masked env var holding the AWS access key id."),secretAccessKeyVar:to.describe("Name of the masked env var holding the AWS secret access key."),sessionTokenVar:to.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(),Vc=li(["deny","passthrough"]),qC=ht({streaming:Vc.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:Vc.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:Vc.optional().describe('Policy for SigV4A (AWS4-ECDSA-P256-SHA256) asymmetric signatures: there is no shared-key HMAC to recompute. Default "deny".')}).strict(),Zh=ht({files:ze(WC).optional().describe("Credential files or directories to protect"),envVars:ze(HC).optional().describe("Environment variables to protect"),allowPlaintextInject:Kt().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(KC).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:qC.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(),Xh=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/,GC=/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?$/,jC=ht({url:Se().url().refine((e)=>new URL(e).protocol==="https:",{message:"brokerForward.url must be https"}),tokenEnvVar:Se().regex(Xh),rules:ze(ht({envVar:Se().regex(Xh),hosts:ze(Se().regex(GC)).min(1).max(16)}).strict()).min(1).max(32)}).strict(),e0=ht({allowedDomains:ze(VC).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(FC).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:jh(Se(),Se().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:Kt().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."),strictAllowlist:Kt().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(Se()).optional().describe("macOS only: Unix socket paths to allow. Ignored on Linux (seccomp cannot filter by path)."),allowAllUnixSockets:Kt().optional().describe("If true, allow all Unix sockets (disables blocking on both platforms)."),allowLocalBinding:Kt().optional().describe("Whether to allow binding to local ports (default: false)"),allowMachLookup:ze(Se().refine((e)=>!(e.endsWith("*")?e.slice(0,-1):e).includes("*"),{message:'Wildcards are only allowed as a single trailing "*" (e.g., "com.example.*" or "*" for all services).'})).optional().describe('macOS only: Additional XPC/Mach service names to allow looking up. Supports trailing-wildcard prefix matching (e.g., "2BUA8C4S2C.com.1password.*"). Needed for tools like 1Password CLI, Playwright, or the iOS Simulator that communicate via XPC.'),httpProxyPort:Pr().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:Pr().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:MC.optional().describe("Optional MITM proxy configuration. Routes matching domains through an upstream proxy via Unix socket while SRT still handles allow/deny filtering."),filterRequest:NC((e)=>typeof e==="function",{message:"filterRequest must be a function"}).optional().describe("Per-request filter callback. Receives the parsed HTTP request (web-standard Request) and returns {action, reason?}. Denied requests get a 403 with the reason. If the callback throws, the request is denied. Applies to plain HTTP through the proxy and, when tlsTerminate is configured, to terminated HTTPS. SRT does not provide a policy language; library consumers own matching."),tlsTerminate:ht({caCertPath:Se().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:Se().min(1).optional().describe("Path to the PEM-encoded private key for caCertPath."),excludeDomains:ze(ro).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(Se().min(1)).optional().describe("Paths to PEM CA certificate files appended to the trust bundle the sandboxed child is pointed at, after the MITM CA and the host's regular roots. Use for site-local roots (e.g. an internal mTLS CA) presented by excluded/passthrough hosts, so the child can verify them itself. Only the CERTIFICATE blocks of each file are copied; files that are missing, unreadable, or contain no PEM CERTIFICATE block are skipped (with a debug log), so paths that exist on only some hosts are safe to list.")}).refine((e)=>!e.caCertPath===!e.caKeyPath,{message:"caCertPath and caKeyPath must be provided together"}).optional().describe("[EXPERIMENTAL] Enable in-process TLS termination so HTTPS request/response bodies are visible to SRT. Provide a CA cert+key, or omit both to have SRT generate an ephemeral one."),parentProxy:$C.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:jC.optional().describe("Credential placeholders a remote broker swaps (see broker-forward.ts).")}),t0=ht({disabled:Kt().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(xs).describe("Paths denied for reading"),allowRead:ze(xs).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(xs).describe("Paths allowed for writing"),denyWrite:ze(xs).describe("Paths denied for writing (takes precedence over allowWrite)"),allowGitConfig:Kt().optional().describe("Allow writes to .git/config files (default: false). Enables git remote URL updates while keeping .git/hooks protected.")}),r0=jh(Se(),ze(Se())).describe('Map of command patterns to filesystem paths to ignore violations for. Use "*" to match all commands'),n0=ht({command:Se().describe("The ripgrep command to execute"),args:ze(Se()).optional().describe("Additional arguments to pass before ripgrep args"),argv0:Se().optional().describe("Override argv[0] when spawning (for multicall binaries that dispatch on argv[0])")}),i0=ht({safeDirectories:ze(Se()).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.")}),s0=ht({path:Se().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.")}),a0=ht({sandboxUser:Se().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:Se().uuid().optional().describe("WFP sublayer GUID under which the filters were installed. Omit to use the srt-win compile-time default. Set this when filters were installed by enterprise tooling under a custom sublayer."),wfpSublayerGuid:Se().uuid().optional().describe("Deprecated alias for sublayerGuid."),proxyPortRange:DC([Pr().int().min(1),Pr().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:s0.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.")}),zC=ht({applyPath:Se().optional().describe("Path to the apply-seccomp binary"),argv0:Se().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.")}),XC=ht({network:e0.describe("Network restrictions configuration"),filesystem:t0.describe("Filesystem restrictions configuration"),credentials:Zh.optional().describe("Credential handling configuration. Only the explicitly declared files and environment variables are restricted."),ignoreViolations:r0.optional().describe("Optional configuration for ignoring specific violations"),enableWeakerNestedSandbox:Kt().optional().describe("Enable weaker nested sandbox mode (for Docker environments)"),runAsUid:Pr().int().nonnegative().optional().describe("ARA: uid to drop the sandboxed command to (bwrap --uid)"),runAsGid:Pr().int().nonnegative().optional().describe("ARA: gid to drop the sandboxed command to (bwrap --gid)"),runAsHostUid:Pr().int().positive().optional().describe("ARA: real host uid used to launch the sandboxed bwrap child"),runAsHostGid:Pr().int().positive().optional().describe("ARA: real host gid used to launch the sandboxed bwrap child"),runAsHostHome:Se().min(1).optional().describe("ARA: HOME set inside a real-host-uid sandbox child"),runAsHostUser:Se().min(1).optional().describe("ARA: USER and LOGNAME set inside a real-host-uid sandbox child"),enableWeakerNetworkIsolation:Kt().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:Kt().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:n0.optional().describe('Custom ripgrep configuration (default: { command: "rg" })'),mandatoryDenySearchDepth:Pr().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:Kt().optional().describe("Allow pseudo-terminal (pty) operations (macOS only)"),seccomp:zC.optional().describe("Custom seccomp binary paths (Linux only)."),bwrapPath:zh.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:zh.optional().describe('Linux only: absolute path to the socat binary. When set, this path is used directly instead of resolving "socat" via PATH.'),windows:a0.optional().describe("Windows-specific settings (WFP sublayer, proxy port range)."),git:i0.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(Qi),i=(l,c)=>{for(let[u,d]of l.entries())if(!$a(d,r))t.addIssue({code:N.custom,path:[...c,u],message:`injectHosts entry "${d}" is not reachable via `+`network.allowedDomains \u2014 add "${d}" (or a covering wildcard) to allowedDomains, or remove it from injectHosts.`})},s=!1,a=(l,c)=>{if(l.injectHosts)i(l.injectHosts,[...c,"injectHosts"]);if(l.mode!=="mask")return;s=!0;let u=e.network.tlsTerminate?.excludeDomains;if(u?.length){if(l.injectHosts){for(let[d,p]of l.injectHosts.entries())if($a(p,u))t.addIssue({code:N.custom,path:[...c,"injectHosts",d],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((d)=>$a(d,u)))t.addIssue({code:N.custom,path:c,message:"This masked credential has no injectHosts, so it defaults "+"to network.allowedDomains \u2014 but "+"network.tlsTerminate.excludeDomains covers every allowed domain, so it could never be injected anywhere. Credential injection only runs on TLS-terminated connections."})}if(l.injectHosts!==void 0&&l.injectHosts.length===0)t.addIssue({code:N.custom,path:c,message:"injectHosts is explicitly empty \u2014 the credential would be "+"masked but never injected. Omit injectHosts to default to network.allowedDomains, or list the intended hosts."})};for(let[l,c]of(n.envVars??[]).entries()){if(a(c,["credentials","envVars",l]),c.maskClaims!==void 0&&c.decode===void 0)t.addIssue({code:N.custom,path:["credentials","envVars",l,"maskClaims"],message:"maskClaims requires decode \u2014 it names claims inside the "+'decoded payload. Set decode (e.g. "jwt"), or remove maskClaims to mask the whole value.'});if(c.maskClaims!==void 0&&c.maskClaims.length===0)t.addIssue({code:N.custom,path:["credentials","envVars",l,"maskClaims"],message:"maskClaims is explicitly empty \u2014 no claim would ever be "+"masked. Omit maskClaims to mask the whole token, or list the claims to protect."})}for(let[l,c]of(n.files??[]).entries()){if(a(c,["credentials","files",l]),c.maskClaims!==void 0&&c.decode===void 0)t.addIssue({code:N.custom,path:["credentials","files",l,"maskClaims"],message:"maskClaims requires decode \u2014 it names claims inside the "+'decoded payload. Set decode (e.g. "jwt"), or remove maskClaims to mask the extracted value whole.'});if(c.maskClaims!==void 0&&c.maskClaims.length===0)t.addIssue({code:N.custom,path:["credentials","files",l,"maskClaims"],message:"maskClaims is explicitly empty \u2014 no claim would ever be "+"masked. Omit maskClaims to mask the whole token, or list the claims to protect."});if(c.mode==="mask"&&c.path.endsWith("/"))t.addIssue({code:N.custom,path:["credentials","files",l,"path"],message:`Credential mode "mask" applies to a single file, not a directory. Use mode "deny" for "${c.path}", or point at the credential file inside it.`})}let o=new Set;for(let[l,c]of(n.awsPairs??[]).entries()){let u=[["accessKeyIdVar",c.accessKeyIdVar],["secretAccessKeyVar",c.secretAccessKeyVar]];if(c.sessionTokenVar!==void 0)u.push(["sessionTokenVar",c.sessionTokenVar]);for(let[d,p]of u){let h=["credentials","awsPairs",l,d];if(o.has(p)){t.addIssue({code:N.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}o.add(p);let f=(n.envVars??[]).find((v)=>v.name===p);if(f===void 0||f.mode!=="mask")t.addIssue({code:N.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(f.extract!==void 0||f.decode!==void 0)t.addIssue({code:N.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(s&&e.network.tlsTerminate===void 0&&!n.allowPlaintextInject)t.addIssue({code:N.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{Zh as CredentialsConfigSchema,Da as DEFAULT_WINDOWS_PROXY_PORT_RANGE,t0 as FilesystemConfigSchema,i0 as GitConfigSchema,r0 as IgnoreViolationsConfigSchema,e0 as NetworkConfigSchema,n0 as RipgrepConfigSchema,Zp as SRT_WIN_DISPATCH_ARG1,lC as SandboxManager,XC as SandboxRuntimeConfigSchema,Pa as SandboxViolationStore,s0 as SrtWinConfigSchema,cb as VENDORED_SRT_WIN_EXE,a0 as WindowsConfigSchema,be as WindowsSandboxError,hi as buildGitConfigEnv,Wn as certThumbprint,bc as checkWindowsDependenciesAsync,nh as checkWindowsSandboxStatus,ih as checkWindowsSandboxStatusAsync,yc as ensurePersistentWindowsCa,Va as expandWindowsFsPaths,oa as generateCa,Cn as getDefaultWritePaths,ub as getSrtWinPath,mc as getWindowsSandboxCaCert,gc as getWindowsSandboxUserStatus,zi as getWindowsSandboxUserStatusAsync,sh as getWindowsWfpStatus,ah as getWindowsWfpStatusAsync,io as getWslVersion,Sc as grantWindowsAcl,fb as installWindowsSandbox,pb as installWindowsSandboxAsync,pi as isUncPath,La as parseWindowsBinShell,gb as parseWindowsSandboxError,Pt as resolveSrtWin,Fa as restoreWindowsAcl,Ma as revokeWindowsAcl,xc as stampWindowsAcl,hb as uninstallWindowsSandbox,Pi as validateCaPair,hc as verifyWindowsWfpEgress,uc as windowsInstallInstructions,ch as windowsStateDir,db as windowsTrustCa,oh as windowsTrustCaAsync};
86
+ No logout is needed: the WFP filter keys on the dedicated \`srt-sandbox\` user's SID, so your network is unaffected.`}function Xp(e){try{return{status:"fulfilled",value:e()}}catch(t){return{status:"rejected",reason:t}}}function hh(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 s=t.value;if(!s.provisioned||!s.credPresent)r.push(`Sandbox user is not provisioned (user=${s.provisioned}, cred=${s.credPresent}). `+uc(e));let a=n();if(a.status==="rejected")return r.push(`srt-win wfp status failed: ${a.reason.message}`),{errors:r,warnings:i};let o=a.value;if(o.state==="cannot-read")w(`[Sandbox Windows] wfp status cannot-read (non-elevated): ${o.hint}`);else if(o.state!=="installed"){if(s.provisioned&&s.credPresent)r.push(`WFP filters not installed under sublayer ${e??"(default)"}. `+uc(e))}else if(o.portRange)w(`[Sandbox Windows] WFP installed: ${o.filters} filters, proxy port range ${o.portRange[0]}-${o.portRange[1]}`);return{errors:r,warnings:i}}function gh(e={}){let t;try{t=e.srtWin??Bt()}catch(n){return{errors:[n.message],warnings:[]}}return w(`[Sandbox Windows] using srt-win at ${t.exe}`),hh(e.sublayerGuid,Xp(()=>gc({srtWin:t})),()=>Xp(()=>sh({sublayerGuid:e.sublayerGuid,srtWin:t})))}async function bc(e={}){let t;try{t=e.srtWin??Bt()}catch(i){return{errors:[i.message],warnings:[]}}w(`[Sandbox Windows] using srt-win at ${t.exe}`);let[n,r]=await Promise.allSettled([zi({srtWin:t}),ah({sublayerGuid:e.sublayerGuid,srtWin:t})]);return hh(e.sublayerGuid,n,()=>r)}import{isIP as mb}from"net";function Xi(e){if(e.startsWith("[")){let r=e.indexOf("]");if(r===-1)return{hostPattern:e,port:void 0};let i=e.slice(1,r),s=vt(i)??i,a=e.slice(r+1);if(a==="")return{hostPattern:s,port:void 0};let o=mh(a.startsWith(":")?a.slice(1):"");return o===void 0?{hostPattern:e,port:void 0}:{hostPattern:s,port:o}}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=mh(e.slice(t+1));if(n===void 0)return{hostPattern:e,port:void 0};return{hostPattern:e.slice(0,t),port:n}}function mh(e){if(!/^[1-9][0-9]{0,4}$/.test(e))return;let t=Number(e);return t>65535?void 0:t}function Qi(e){return Xi(e).hostPattern}function Ar(e,t){let n=e.toLowerCase();if(t==="*")return!0;if(t.startsWith("*.")){if(mb(Xt(n)))return!1;let r=t.substring(2).toLowerCase();return n.endsWith("."+r)}return n===t.toLowerCase()}function Yi(e,t,n){let{hostPattern:r,port:i}=Xi(n);if(i!==void 0&&i!==t)return!1;return Ar(e,r)}function $a(e,t){let n=t.map(Qi);if(!e.startsWith("*."))return n.some((i)=>Ar(e,i));let r=e.slice(2).toLowerCase();return n.some((i)=>{if(!i.startsWith("*."))return!1;let s=i.slice(2).toLowerCase();return r===s||r.endsWith("."+s)})}import{isIP as yb}from"net";var yh="<allowAllDomains>";function Cc(e,t,n,r){if(!Kn(t))return{verdict:"deny",reason:"malformed host"};let i=vt(t)??t;for(let s of e.deniedDomains)if(Yi(i,n,s))return{verdict:"deny",reason:e.deniedDomainReasons?.[s]??"host is on the deny list",rule:s};for(let s of e.allowedDomains)if(Yi(i,n,s))return{verdict:"allow",rule:s};if(e.allowAllDomains){if(Cl(i)||yb(i)!==0&&!la(i))return{verdict:"deny",reason:"host is not on the public internet"};return{verdict:"allow",rule:yh}}if(!r||e.strictAllowlist)return{verdict:"deny",reason:"host is not on the allow list"};return{verdict:"ask"}}function Wa(e,t,n){if(!e.allowAllDomains)return!1;let r=Cc(e,t,n,!1);return r.verdict==="allow"&&r.rule===yh}import{EOL as wc}from"os";import{dirname as Ec}from"path";var P,es,ts,rs,Ht,jr,Ji,vh=!1,Ha,Yn,Qr,Fe,Yr,Jn,zr,Ka,xh=!1,ns,vn=new Pa,Zt=new Fl,ei=new Kl,Zn=new Pl;function Th(){let e=P?.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)Zn.register(r,t,n.hosts,e.url)}return[e.tokenEnvVar]}function xb(e){return P?.network.brokerForward?.rules.some((t)=>t.hosts.includes(e))??!1}var is=new Hl;function Sb(){if(vh)return;let e=()=>Bc().catch((t)=>{w(`Cleanup failed in registerCleanup ${t}`,{level:"error"})});process.once("exit",e),process.once("SIGINT",e),process.once("SIGTERM",e),vh=!0}var bb=1024,yn=new Map;function Ah(e,t){let n=t?.commandId,r=t?.commandText??e;if(n===void 0||n===r)return;let i=tn(Dt(n));yn.delete(i),yn.set(i,r);while(yn.size>bb){let s=yn.keys().next().value;if(s===void 0)break;yn.delete(s)}}function Sh(e){return yn.get(e)??e}function Tc(e,t){let n=t?(()=>{let r=tn(t);return yn.get(r)??sc(r)})():void 0;if(Xn(e,n,P?.ignoreViolations))return;vn.addViolation({line:e,encodedCommand:t,command:n,timestamp:new Date})}function Cb(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 bh(e,t,n,r){let i=(a)=>(Tc(`deny network-outbound ${t}:${e} (${a})`,r),!1);if(!P)return w("No config available, denying network request"),i("sandbox policy unavailable");let s=Cc(P.network,t,e,n!==void 0);if(s.verdict==="allow")return w(`Allowed by config rule: ${t}:${e}`),!0;if(s.verdict==="deny"){if(s.reason==="malformed host")w(`Denying malformed host: ${JSON.stringify(t)}:${e}`,{level:"error"});else if(s.rule!==void 0)w(`Denied by config rule: ${t}:${e}`);else w(`No matching config rule, denying: ${t}:${e}`);return i(s.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(a){return w(`Error in permission callback: ${a}`,{level:"error"}),i("permission prompt failed")}}var qa=!1;function wb(e){qa=e}function Eb(){if(!qa&&!P?.credentials)return;return(e,t)=>{if(!P?.credentials)return;Zt.substituteInHeaders(e,t,Ar)}}function Tb(){if(!qa&&!P?.credentials)return;return(e)=>P?.credentials?Zt.sentinelsForHost(e,Ar):void 0}function Ab(){if(!qa&&!P?.credentials)return;return(e,t,n,r)=>!P?.credentials?void 0:lp(ei,P?.credentials?.sigv4,Ar)(e,t,n,r)}function _b(e){if(!P?.network.mitmProxy)return;let{socketPath:t,domains:n}=P.network.mitmProxy,r=vt(e)??e;for(let i of n)if(Ar(r,i))return w(`Host ${e} matches MITM pattern ${i}`),t;return}function kb(e,t=443){if(P&&Wa(P.network,vt(e)??e,t))return!1;let n=P?.network.tlsTerminate?.excludeDomains;if(!n?.length)return!0;let r=vt(e)??e;if(xb(r))return!0;for(let i of n){if(!Ar(r,i))continue;w(`Host ${e} matches tlsTerminate.excludeDomains pattern ${i}; skipping TLS termination`);let s=Zt.namesInjectableAt(r,Ar);if(s.length>0)w(`tlsTerminate.excludeDomains: masked credential(s) ${s.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 Ib(e,t){let n=Eb(),r=Tb();es=Vf({filter:(o,l,c,u)=>bh(o,l,e,u),getMitmSocketPath:_b,mitmCA:Fe,shouldTerminateTLS:kb,publicOnly:(o,l)=>P!==void 0&&Wa(P.network,vt(o)??o,l),filterRequest:P?.network.filterRequest,onFilterRequestDenied:({method:o,url:l,reason:c,encodedCommand:u})=>{Tc(`deny http-request ${o} ${Cb(l)} (${c})`,u)},mutateHeaders:n,mutateHeadersPlaintext:P?.credentials?.allowPlaintextInject?n:void 0,getBrokerForward:(o,l)=>P?.network.brokerForward?Zn.forwardFor(o,l):void 0,getBodySubstitutions:r,getBodySubstitutionsPlaintext:P?.credentials?.allowPlaintextInject?r:void 0,planSigv4:Ab(),parentProxy:Qr,proxyAuthToken:Yr}),ts=jf({filter:(o,l,c)=>bh(o,l,e,c),publicOnly:(o,l)=>P!==void 0&&Wa(P.network,vt(o)??o,l),parentProxy:Qr,proxyAuthToken:Yr,probeUnauthenticated:async(o,l)=>{if(!P)return{};let c=vt(l)??l;for(let u of P.network.deniedDomains)if(Yi(c,o,u)){let d=P.network.deniedDomainReasons?.[u]??"host is on the deny list";return Tc(`deny network-outbound ${l}:${o} (${d})`,void 0),{deniedReason:d}}return{}}}),rs=Qf({httpServer:es,handleSocksConnection:(o)=>ts.handleConnection(o),httpBackendPortRange:t});let i=rs,s=await i.listenHttpBackend();await xa(i.server,(o)=>i.server.listen(o,"127.0.0.1"),t,s!==void 0?new Set([s]):new Set);let a=i.getPort();if(a===void 0)throw Error("Failed to get mux proxy server port");return i.unref(),w(`Mux proxy (HTTP+SOCKS) listening on localhost:${a}`),a}async function Rb(e,t,n=!1){if(jr){await jr;return}if(P=e,Qr=Al(e.network.parentProxy),Qr)w(`Parent proxy configured: http=${Il(Qr.httpUrl)} https=${Il(Qr.httpsUrl)}`);if(e.network.tlsTerminate&&e.network.mitmProxy)throw Error("network.tlsTerminate and network.mitmProxy are mutually exclusive");let r=e.network.tlsTerminate,i=De()==="windows"&&r!==void 0&&!r.caCertPath&&!r.caKeyPath;if(Fe=r&&!i?vl(r):void 0,Fe&&e.runAsHostUid!==void 0&&De()==="linux"){if(Xr.chmodSync(Ec(Fe.trustBundlePath),457),Xr.chmodSync(Fe.trustBundlePath,420),Fe.ephemeral)Xr.chmodSync(Ec(Fe.certPath),457),Xr.chmodSync(Fe.certPath,420)}let s=await Ih();if(s.errors.length>0)throw Error(`Sandbox dependencies not available: ${s.errors.join(", ")}`);if(n&&De()==="macos")Ha=Kp(vn.addViolation.bind(vn),P.ignoreViolations,Sh),w("Started macOS sandbox log monitor");if(n&&De()==="linux")Yn=jp(vn.addViolation.bind(vn),{allowWritePaths:[...Cn(e.runAsHostHome),...P.filesystem.allowWrite],denyWritePaths:P.filesystem.denyWrite,ignoreViolations:P.ignoreViolations,resolveCommandText:Sh,consumerUid:e.runAsHostUid,consumerGid:e.runAsHostGid}),Yn.ready,w("Started Linux seccomp violation monitor");if(Sb(),De()==="windows"){ns=Bt(e.windows?.srtWin);let a=ns,o=await zi({srtWin:a});if(!o.provisioned||!o.credPresent)throw P=void 0,new be("not_provisioned",`Windows sandbox user is not provisioned (user=${o.provisioned}, cred=${o.credPresent}). Run \`npx sandbox-runtime windows-install\` (one UAC prompt) to provision it.`);if(!xh){try{await hc({proxyPortRange:e.windows?.proxyPortRange,srtWin:a})}catch(l){throw P=void 0,l}xh=!0}if(i&&r)try{let l=await yc({status:o,srtWin:a});Fe=vl({caCertPem:l.certPem,caKeyPem:l.keyPem,caCertPath:l.certPath,caKeyPath:l.keyPath,extraCaCertPaths:r.extraCaCertPaths})}catch(l){throw P=void 0,l}if(r&&Fe&&!i){let l=mc(o),c=Wn(Fe.certPem);if(!l)throw P=void 0,new be("trust_ca_not_installed",`tlsTerminate on Windows requires the sandbox to be installed with this CA (thumb=${c}): run \`srt-win user trust-ca ${Fe.certPath}\`. Per-exec installs into the sandbox user's Root store are not supported.`);if(l.thumb!==c)throw P=void 0,new be("trust_ca_thumbprint_mismatch",`tlsTerminate on Windows: the sandbox's installed CA (thumb=${l.thumb}) doesn't match this session's CA (thumb=${c}). Run \`srt-win user trust-ca ${Fe.certPath}\` to update it.`)}try{let l=Lb(e);if(Fe)l.grantRead.push(Ec(Fe.trustBundlePath));if(!o.sid)throw Error("sandbox user SID missing from `srt-win user status` (provisioned but in an inconsistent state)");let c=o.sid;if(zr=c,l.grantRead.length>0||l.grantWrite.length>0)Sc({sandboxUserSid:c,read:l.grantRead,write:l.grantWrite,srtWin:a});if(l.denyRead.length>0||l.denyWrite.length>0)xc({sandboxUserSid:c,denyRead:l.denyRead,denyWrite:l.denyWrite,srtWin:a});if(l.grantRead.length>0||l.grantWrite.length>0||l.denyRead.length>0||l.denyWrite.length>0)Jn=l,w(`[Sandbox Windows] fs applied: ${l.grantWrite.length} grantWrite, ${l.grantRead.length} grantRead, ${l.denyRead.length} denyRead, ${l.denyWrite.length} denyWrite`);Ka=Bh(e)}catch(l){if(zr)Ma({sandboxUserSid:zr,srtWin:a}),Fa({sandboxUserSid:zr,srtWin:a});throw zr=void 0,P=void 0,l}}jr=(async()=>{try{let a=De()==="windows"?P.windows?.proxyPortRange??Da:void 0;Yr=P.network.httpProxyPort!==void 0?void 0:vb(16).toString("hex");let l=P.network.httpProxyPort===void 0||P.network.socksProxyPort===void 0?await Ib(t,a):void 0,c=P.network.httpProxyPort??l,u=P.network.socksProxyPort??l;if(Fe&&l!==void 0&&De()==="windows")Fe.crlUrl=`http://127.0.0.1:${l}${aa}`;if(P.network.httpProxyPort!==void 0)w(`Using external HTTP proxy on port ${c}`);if(P.network.socksProxyPort!==void 0)w(`Using external SOCKS proxy on port ${u}`);let d;if(De()==="linux")d=await Lp(c,u,P.socatPath,P.runAsHostUid,P.runAsHostGid);let p={httpProxyPort:c,socksProxyPort:u,linuxBridge:d};return Ht=p,w("Network infrastructure initialized"),p}catch(a){throw jr=void 0,Ht=void 0,Bc().catch((o)=>{w(`Cleanup failed in initializationPromise ${o}`,{level:"error"})}),a}})(),await jr}function _h(){let e=De();if(e==="linux")return io()!=="1";return e==="macos"||e==="windows"}function Bb(){return P!==void 0}function kh(e){if(!_h())return{done:{errors:["Unsupported platform"],warnings:[]}};let t=[],n=[],r=De();if(r==="linux"){let i=e??P?.ripgrep??{command:"rg"};if(wr(i.command)===null)t.push(`ripgrep (${i.command}) not found`);let s=Dp({seccompConfig:P?.seccomp,bwrapPath:P?.bwrapPath,socatPath:P?.socatPath});t.push(...s.errors),n.push(...s.warnings)}else if(r==="windows"){let i;try{i=Bt(P?.windows?.srtWin)}catch(s){return t.push(s.message),{done:{errors:t,warnings:n}}}return{windows:{sublayerGuid:P?.windows?.sublayerGuid??P?.windows?.wfpSublayerGuid,srtWin:i}}}return{done:{errors:t,warnings:n}}}function Pb(e){let t=kh(e);if("done"in t)return t.done;return gh(t.windows)}async function Ih(e){let t=kh(e);if("done"in t)return t.done;return bc(t.windows)}function _c(e,t){if(!e)return{denyReadPaths:[],unsetEnvVars:[],setEnvVars:{},maskedFileBinds:[],maskedFileStoreDir:void 0};let n=Ga(e),r=[...new Set((t??[]).map(Qi))],i=[];for(let u of e.envVars??[])if(u.mode==="deny")i.push(u.name);let{setEnvVars:s,degradeToUnsetNames:a}=np(e.envVars??[],r,Zt);i.push(...a),op(e.envVars??[],e.awsPairs,r,s,ei);let o=e.files??[],{binds:l,degradeToDenyPaths:c}=rp(o,r,Zt,is);return{denyReadPaths:[...new Set([...n,...c])],unsetEnvVars:[...new Set(i)],setEnvVars:s,maskedFileBinds:l,maskedFileStoreDir:is.dirPath}}function Ga(e){let t=e?.files??[];return[...new Set(t.filter((n)=>n.mode==="deny").map((n)=>n.path))]}function Rh(e,t){return[...new Set([...e,...t.denyReadPaths])]}function Nb(){if(!P||P.filesystem.disabled)return{denyOnly:[],allowWithinDeny:[]};let e=Rh(P.filesystem.denyRead,_c(P.credentials,P.network.allowedDomains)),t=[];for(let r of e){let i=vr(r);if(De()==="linux"&&St(i)){let s=rn(r);w(`[Sandbox] Expanded glob pattern "${r}" to ${s.length} paths on Linux`),t.push(...s)}else t.push(i)}let n=[];for(let r of P.filesystem.allowRead??[]){let i=vr(r);if(De()==="linux"&&St(i)){let s=rn(r);w(`[Sandbox] Expanded allowRead glob pattern "${r}" to ${s.length} paths on Linux`),n.push(...s)}else n.push(i)}return{denyOnly:t,allowWithinDeny:n}}function Db(){if(!P)return{allowOnly:Cn(),denyWithinAllow:[]};if(P.filesystem.disabled)return{allowOnly:["/"],denyWithinAllow:[]};let e=P.filesystem.allowWrite.map((r)=>vr(r)).filter((r)=>{if(De()==="linux"&&St(r))return w(`Skipping glob pattern on Linux/WSL: ${r}`),!1;return!0}),t=P.filesystem.denyWrite.map((r)=>vr(r)).filter((r)=>{if(De()==="linux"&&St(r))return w(`Skipping glob pattern on Linux/WSL: ${r}`),!1;return!0});return{allowOnly:[...Cn(Ac()),...e],denyWithinAllow:t}}function Lb(e){let t=e.filesystem;if(t?.disabled)return{grantRead:[],grantWrite:[],denyRead:[],denyWrite:[]};let n=Va,r=n([...new Set([...t?.denyRead??[],...Ga(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 Bh(e){return{disabled:e.filesystem.disabled??!1,denyRead:[...e.filesystem.denyRead],denyWrite:[...e.filesystem.denyWrite],allowRead:[...e.filesystem.allowRead??[]],allowWrite:[...e.filesystem.allowWrite],credFiles:Ga(e.credentials)}}function Zi(e,t){if(e.length!==t.length)return!1;let n=new Set(e);return t.every((r)=>n.has(r))}function Ob(e,t){return e.disabled===t.disabled&&Zi(e.denyRead,t.denyRead)&&Zi(e.denyWrite,t.denyWrite)&&Zi(e.allowRead,t.allowRead)&&Zi(e.allowWrite,t.allowWrite)&&Zi(e.credFiles,t.credFiles)}function Ub(e){return Ka!==void 0&&Ob(Ka,Bh(e))}function Vb(){if(!P)return{};let e=P.network.allowedDomains,t=P.network.deniedDomains;return{allowedHosts:e,...t.length>0&&{deniedHosts:t}}}function Ph(){return P?.network?.allowUnixSockets}function Ch(){return P?.network?.allowAllUnixSockets}function Nh(){return P?.network?.allowLocalBinding}function Dh(){return P?.network?.allowMachLookup}function Lh(){return P?.ignoreViolations}function Oh(){return P?.enableWeakerNestedSandbox}function Fb(){return P?.runAsUid}function Mb(){return P?.runAsGid}function $b(){return P?.runAsHostUid}function Wb(){return P?.runAsHostGid}function Ac(){return P?.runAsHostHome}function Hb(){return P?.runAsHostUser}function Kb(){return P?.enableWeakerNetworkIsolation}function qb(){return P?.allowAppleEvents}function Gb(){return P?.ripgrep??{command:"rg"}}function jb(){return P?.mandatoryDenySearchDepth??3}function wh(){return P?.filesystem?.allowGitConfig??!1}function Uh(e){return[...P?.git?.safeDirectories??[],...e?.git?.safeDirectories??[]]}function zb(){return P?.seccomp}function Xb(){return Yr}function kc(){return Ht?.httpProxyPort}function Ic(){return Ht?.socksProxyPort}function Vh(){return Ht?.linuxBridge?.httpSocketPath}function Fh(){return Ht?.linuxBridge?.socksSocketPath}async function Rc(){if(!P)return!1;if(jr)try{return await jr,!0}catch{return!1}return Ht!==void 0}async function Mh(e,t,n,r,i){let s=De(),a=i?.commandId;Ah(e,i);let o=n?.filesystem!==void 0?n.filesystem.disabled??!1:P?.filesystem.disabled??!1,l=_c(n?.credentials??P?.credentials,n?.network?.allowedDomains??P?.network?.allowedDomains);l.unsetEnvVars.push(...Th());let c,u;if(!o){let x=(I)=>I.map((V)=>vr(V)).filter((V)=>{if(De()==="linux"&&St(V))return w(`[Sandbox] Skipping glob write pattern on Linux: ${V}`),!1;return!0}),S=x(n?.filesystem?.allowWrite??P?.filesystem.allowWrite??[]);c={allowOnly:[...Cn(n?.runAsHostHome??Ac()),...S],denyWithinAllow:x(n?.filesystem?.denyWrite??P?.filesystem.denyWrite??[])};let A=Rh(n?.filesystem?.denyRead??P?.filesystem.denyRead??[],l),b=[];for(let I of A){let V=vr(I);if(De()==="linux"&&St(V))b.push(...rn(I));else b.push(V)}let k=n?.filesystem?.allowRead??P?.filesystem.allowRead??[],R=[];for(let I of k){let V=vr(I);if(De()==="linux"&&St(V))R.push(...rn(I));else R.push(V)}if(Fe)R.push(Fe.certPath,Fe.trustBundlePath);u={denyOnly:b,allowWithinDeny:R}}let d=n?.network?.allowedDomains!==void 0||P?.network?.allowedDomains!==void 0,p=d,h=d;if(h)await Rc();let f=n?.allowPty??P?.allowPty,v=Uh(n);switch(s){case"macos":return Hp({command:e,commandId:a,needsNetworkRestriction:p,httpProxyPort:h?kc():void 0,socksProxyPort:h?Ic():void 0,proxyAuthToken:h?Yr:void 0,caCertPath:Fe?.trustBundlePath,readConfig:u,writeConfig:c,unsetEnvVars:l.unsetEnvVars,setEnvVars:l.setEnvVars,maskedFileBinds:l.maskedFileBinds,allowUnixSockets:Ph(),allowAllUnixSockets:Ch(),allowLocalBinding:Nh(),allowMachLookup:Dh(),ignoreViolations:Lh(),allowPty:f,allowGitConfig:wh(),gitSafeDirectories:v,enableWeakerNetworkIsolation:Kb(),allowAppleEvents:qb(),binShell:t});case"linux":return Up({command:e,commandId:a,needsNetworkRestriction:p,httpSocketPath:h?Vh():void 0,socksSocketPath:h?Fh():void 0,httpProxyPort:h?Ht?.httpProxyPort:void 0,socksProxyPort:h?Ht?.socksProxyPort:void 0,proxyAuthToken:h?Yr:void 0,caCertPath:Fe?.trustBundlePath,readConfig:u,writeConfig:c,unsetEnvVars:l.unsetEnvVars,setEnvVars:l.setEnvVars,maskedFileBinds:l.maskedFileBinds,maskedFileStoreDir:l.maskedFileStoreDir,enableWeakerNestedSandbox:Oh(),runAsUid:Fb(),runAsGid:Mb(),runAsHostUid:$b(),runAsHostGid:Wb(),runAsHostHome:Ac(),runAsHostUser:Hb(),setprivPath:"/usr/bin/setpriv",allowAllUnixSockets:Ch(),binShell:t,ripgrepConfig:Gb(),mandatoryDenySearchDepth:jb(),allowGitConfig:wh(),gitSafeDirectories:v,seccompConfig:zb(),bwrapPath:P?.bwrapPath,socatPath:P?.socatPath,observeSocketPath:Yn?.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: ${s}`)}}async function Qb(e,t,n,r,i,s){if(De()==="windows"){let c=n?.network?.allowedDomains!==void 0||P?.network?.allowedDomains!==void 0;if(c)await Rc();let u=_c(n?.credentials??P?.credentials,n?.network?.allowedDomains??P?.network?.allowedDomains);u.unsetEnvVars.push(...Th());let d=n?.filesystem,p=[],h=[];if(!d?.disabled){if(d?.allowRead?.length||d?.allowWrite?.length)throw Error("Per-exec filesystem.allowRead/allowWrite is not supported "+"on Windows \u2014 `srt-win exec` only exposes per-exec "+"denies. Set them at the session level (initialize()).");let f=[...d?.denyRead??[],...Ga(n?.credentials)],v=d?.denyWrite??[];if(f.length>0||v.length>0){let x=new Set(Jn?.denyRead??[]),S=new Set(Jn?.denyWrite??[]),A=Va;p=A(f,{mode:"deny"}).filter((b)=>!x.has(b)),h=A(v,{mode:"deny"}).filter((b)=>!x.has(b)&&!S.has(b))}}return Ah(e,s),ph({command:e,commandId:s?.commandId,httpProxyPort:c?kc():void 0,socksProxyPort:c?Ic():void 0,proxyAuthToken:c?Yr:void 0,setEnvVars:u.setEnvVars,denyRead:p,denyWrite:h,cwd:i,allowWrite:Jn?.grantWrite,gitSafeDirectories:Uh(n),caCertPath:Fe?.trustBundlePath,binShell:La(t),srtWin:n?.windows?.srtWin?Bt(n.windows.srtWin):ns??Bt(P?.windows?.srtWin)})}if(typeof t==="object")throw Error("binShell object form is Windows-only; pass a shell path string on macOS/Linux");let o=await Mh(e,t,n,r,s);return{argv:[t??"/bin/bash","-c",o],env:process.env}}function Yb(){return P}function Jb(){Zt.clear(),ei.clear(),Zn.clear(),is.dispose()}function Zb(e){if(De()==="windows"&&P&&!Ub(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;P=structuredClone({...e,network:n}),P.network.filterRequest=t,Qr=Al(e.network.parentProxy),w("Sandbox configuration updated")}function eC(){Ba()}var tC=1500;function Eh(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(s),n()};e.once("exit",()=>{w(`${t} bridge process exited`),i()});let s=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()},tC);s.unref?.()})}function rC(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 nC(){if(Jn&&zr){let t=zr,n=ns,r=new Set(["revoked","stillHeld","restored","alreadyOriginal"]),i=(s,a)=>{if(!r.has(a.status))w(`[Sandbox Windows] ${s}: '${a.path}' ${a.status} \u2014 `+"ACE may be left in place; resolve and run `srt-win acl recover` to clear",{level:"warn"})};for(let s of Ma({sandboxUserSid:t,srtWin:n})??[])i("grant revoke",s);for(let s of Fa({sandboxUserSid:t,srtWin:n})??[])i("deny restore",s)}if(Jn=void 0,zr=void 0,Ka=void 0,ns=void 0,Ba({force:!0}),Ha)Ha(),Ha=void 0;if(Yn)Yn.stop(),Yn=void 0;if(Ht?.linuxBridge){let{httpSocketPath:t,socksSocketPath:n,httpBridgeProcess:r,socksBridgeProcess:i}=Ht.linuxBridge;if(await Promise.all([Eh(r,"HTTP"),Eh(i,"SOCKS")]),t)try{Xr.rmSync(t,{force:!0}),w("Cleaned up HTTP socket")}catch(s){w(`HTTP socket cleanup error: ${s}`,{level:"error"})}if(n)try{Xr.rmSync(n,{force:!0}),w("Cleaned up SOCKS socket")}catch(s){w(`SOCKS socket cleanup error: ${s}`,{level:"error"})}}let e=[];if(Fe)e.push(df(Fe));if(rs)e.push(rs.close().catch((t)=>{w(`Error closing mux proxy server: ${t.message}`,{level:"error"})}));if(es)e.push(rC(es));if(ts){let t=ts.close().catch((n)=>{w(`Error closing SOCKS proxy server: ${n.message}`,{level:"error"})});e.push(t)}await Promise.all(e),rs=void 0,es=void 0,Yr=void 0,ts=void 0,Ht=void 0,jr=void 0,Qr=void 0,Fe=void 0,Zt.clear(),ei.clear(),is.dispose()}async function Bc(){if(Ji)return Ji;Ji=nC();try{await Ji}finally{Ji=void 0}}function iC(){return vn}function sC(e,t){if(!P)return t;let n=vn.getViolationsForCommand(e);if(n.length===0)return t;let r=t;r+=wc+"<sandbox_violations>"+wc;for(let i of n)r+=i.line+wc;return r+="</sandbox_violations>",r}function aC(){if(De()!=="linux"||!P||P.filesystem.disabled)return[];let e=[],t=[...P.filesystem.allowWrite,...P.filesystem.denyWrite];for(let n of t){let r=vr(n);if(St(r))e.push(n)}return e}var oC={initialize:Rb,isSupportedPlatform:_h,isSandboxingEnabled:Bb,checkDependencies:Pb,checkDependenciesAsync:Ih,getFsReadConfig:Nb,getFsWriteConfig:Db,getNetworkRestrictionConfig:Vb,getAllowUnixSockets:Ph,getAllowLocalBinding:Nh,getAllowMachLookup:Dh,getIgnoreViolations:Lh,getEnableWeakerNestedSandbox:Oh,getProxyPort:kc,getProxyAuthToken:Xb,getSocksProxyPort:Ic,getLinuxHttpSocketPath:Vh,getLinuxSocksSocketPath:Fh,waitForNetworkInitialization:Rc,wrapWithSandbox:Mh,wrapWithSandboxArgv:Qb,cleanupAfterCommand:eC,beginCredentialLease:()=>{Zt.beginLease(),Zn.beginLease()},endCredentialLease:()=>Object.assign(Zt.endLease(),{brokerForward:Zn.endLease()}),releaseCredentialLease:(e)=>{Zn.release(e.brokerForward??[]),ei.forget(Zt.release(e))},reset:Bc,getMitmCA:()=>Fe,getSentinelRegistry:()=>Zt,getAwsPairRegistry:()=>ei,getMaskedFileStore:()=>is,getSandboxViolationStore:iC,annotateStderrWithSandboxFailures:sC,getLinuxGlobPatternWarnings:aC,getConfig:Yb,updateConfig:Zb,clearMaskedCredentials:Jb,setLiveCredentialInjectors:wb};import{isIP as LC}from"net";import{isAbsolute as OC}from"path";var _e;(function(e){e.assertEqual=(i)=>{};function t(i){}e.assertIs=t;function n(i){throw Error()}e.assertNever=n,e.arrayToEnum=(i)=>{let s={};for(let a of i)s[a]=a;return s},e.getValidEnumValues=(i)=>{let s=e.objectKeys(i).filter((o)=>typeof i[i[o]]!=="number"),a={};for(let o of s)a[o]=i[o];return e.objectValues(a)},e.objectValues=(i)=>e.objectKeys(i).map(function(s){return i[s]}),e.objectKeys=typeof Object.keys==="function"?(i)=>Object.keys(i):(i)=>{let s=[];for(let a in i)if(Object.prototype.hasOwnProperty.call(i,a))s.push(a);return s},e.find=(i,s)=>{for(let a of i)if(s(a))return a;return},e.isInteger=typeof Number.isInteger==="function"?(i)=>Number.isInteger(i):(i)=>typeof i==="number"&&Number.isFinite(i)&&Math.floor(i)===i;function r(i,s=" | "){return i.map((a)=>typeof a==="string"?`'${a}'`:a).join(s)}e.joinValues=r,e.jsonStringifyReplacer=(i,s)=>{if(typeof s==="bigint")return s.toString();return s}})(_e||(_e={}));var $h;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})($h||($h={}));var X=_e.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),_r=(e)=>{switch(typeof e){case"undefined":return X.undefined;case"string":return X.string;case"number":return Number.isNaN(e)?X.nan:X.number;case"boolean":return X.boolean;case"function":return X.function;case"bigint":return X.bigint;case"symbol":return X.symbol;case"object":if(Array.isArray(e))return X.array;if(e===null)return X.null;if(e.then&&typeof e.then==="function"&&e.catch&&typeof e.catch==="function")return X.promise;if(typeof Map<"u"&&e instanceof Map)return X.map;if(typeof Set<"u"&&e instanceof Set)return X.set;if(typeof Date<"u"&&e instanceof Date)return X.date;return X.object;default:return X.unknown}};var N=_e.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class Pt extends Error{get errors(){return this.issues}constructor(e){super();this.issues=[],this.addIssue=(n)=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let t=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,t);else this.__proto__=t;this.name="ZodError",this.issues=e}format(e){let t=e||function(i){return i.message},n={_errors:[]},r=(i)=>{for(let s of i.issues)if(s.code==="invalid_union")s.unionErrors.map(r);else if(s.code==="invalid_return_type")r(s.returnTypeError);else if(s.code==="invalid_arguments")r(s.argumentsError);else if(s.path.length===0)n._errors.push(t(s));else{let a=n,o=0;while(o<s.path.length){let l=s.path[o];if(o!==s.path.length-1)a[l]=a[l]||{_errors:[]};else a[l]=a[l]||{_errors:[]},a[l]._errors.push(t(s));a=a[l],o++}}};return r(this),n}static assert(e){if(!(e instanceof Pt))throw Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,_e.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=(t)=>t.message){let t={},n=[];for(let r of this.issues)if(r.path.length>0){let i=r.path[0];t[i]=t[i]||[],t[i].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}}Pt.create=(e)=>new Pt(e);var lC=(e,t)=>{let n;switch(e.code){case N.invalid_type:if(e.received===X.undefined)n="Required";else n=`Expected ${e.expected}, received ${e.received}`;break;case N.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,_e.jsonStringifyReplacer)}`;break;case N.unrecognized_keys:n=`Unrecognized key(s) in object: ${_e.joinValues(e.keys,", ")}`;break;case N.invalid_union:n="Invalid input";break;case N.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${_e.joinValues(e.options)}`;break;case N.invalid_enum_value:n=`Invalid enum value. Expected ${_e.joinValues(e.options)}, received '${e.received}'`;break;case N.invalid_arguments:n="Invalid function arguments";break;case N.invalid_return_type:n="Invalid function return type";break;case N.invalid_date:n="Invalid date";break;case N.invalid_string:if(typeof e.validation==="object")if("includes"in e.validation){if(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==="number")n=`${n} at one or more positions greater than or equal to ${e.validation.position}`}else if("startsWith"in e.validation)n=`Invalid input: must start with "${e.validation.startsWith}"`;else if("endsWith"in e.validation)n=`Invalid input: must end with "${e.validation.endsWith}"`;else _e.assertNever(e.validation);else if(e.validation!=="regex")n=`Invalid ${e.validation}`;else n="Invalid";break;case N.too_small:if(e.type==="array")n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`;else if(e.type==="string")n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`;else if(e.type==="number")n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`;else if(e.type==="bigint")n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`;else if(e.type==="date")n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`;else n="Invalid input";break;case N.too_big:if(e.type==="array")n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`;else if(e.type==="string")n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`;else if(e.type==="number")n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`;else if(e.type==="bigint")n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`;else if(e.type==="date")n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`;else n="Invalid input";break;case N.custom:n="Invalid input";break;case N.invalid_intersection_types:n="Intersection results could not be merged";break;case N.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case N.not_finite:n="Number must be finite";break;default:n=t.defaultError,_e.assertNever(e)}return{message:n}},Jr=lC;var cC=Jr;function ss(){return cC}var ja=(e)=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,s=[...n,...i.path||[]],a={...i,path:s};if(i.message!==void 0)return{...i,path:s,message:i.message};let o="",l=r.filter((c)=>!!c).slice().reverse();for(let c of l)o=c(a,{data:t,defaultError:o}).message;return{...i,path:s,message:o}};function q(e,t){let n=ss(),r=ja({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Jr?void 0:Jr].filter((i)=>!!i)});e.common.issues.push(r)}class xt{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(e,t){let n=[];for(let r of t){if(r.status==="aborted")return oe;if(r.status==="dirty")e.dirty();n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){let n=[];for(let r of t){let i=await r.key,s=await r.value;n.push({key:i,value:s})}return xt.mergeObjectSync(e,n)}static mergeObjectSync(e,t){let n={};for(let r of t){let{key:i,value:s}=r;if(i.status==="aborted")return oe;if(s.status==="aborted")return oe;if(i.status==="dirty")e.dirty();if(s.status==="dirty")e.dirty();if(i.value!=="__proto__"&&(typeof s.value<"u"||r.alwaysSet))n[i.value]=s.value}return{status:e.value,value:n}}}var oe=Object.freeze({status:"aborted"}),ti=(e)=>({status:"dirty",value:e}),Tt=(e)=>({status:"valid",value:e}),Pc=(e)=>e.status==="aborted",Nc=(e)=>e.status==="dirty",xn=(e)=>e.status==="valid",as=(e)=>typeof Promise<"u"&&e instanceof Promise;var ee;(function(e){e.errToObj=(t)=>typeof t==="string"?{message:t}:t||{},e.toString=(t)=>typeof t==="string"?t:t?.message})(ee||(ee={}));class er{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var Wh=(e,t)=>{if(xn(t))return{success:!0,data:t.value};else{if(!e.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new Pt(e.common.issues);return this._error=n,this._error}}}};function he(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(t)return{errorMap:t,description:i};return{errorMap:(a,o)=>{let{message:l}=e;if(a.code==="invalid_enum_value")return{message:l??o.defaultError};if(typeof o.data>"u")return{message:l??r??o.defaultError};if(a.code!=="invalid_type")return{message:o.defaultError};return{message:l??n??o.defaultError}},description:i}}class Ce{get description(){return this._def.description}_getType(e){return _r(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:_r(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new xt,ctx:{common:e.parent.common,data:e.data,parsedType:_r(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(as(t))throw Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:_r(e)},r=this._parseSync({data:e,path:n.path,parent:n});return Wh(n,r)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:_r(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:t});return xn(n)?{value:n.value}:{issues:t.common.issues}}catch(n){if(n?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then((n)=>xn(n)?{value:n.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:_r(e)},r=this._parse({data:e,path:n.path,parent:n}),i=await(as(r)?r:Promise.resolve(r));return Wh(n,i)}refine(e,t){let n=(r)=>{if(typeof t==="string"||typeof t>"u")return{message:t};else if(typeof t==="function")return t(r);else return t};return this._refinement((r,i)=>{let s=e(r),a=()=>i.addIssue({code:N.custom,...n(r)});if(typeof Promise<"u"&&s instanceof Promise)return s.then((o)=>{if(!o)return a(),!1;else return!0});if(!s)return a(),!1;else return!0})}refinement(e,t){return this._refinement((n,r)=>{if(!e(n))return r.addIssue(typeof t==="function"?t(n,r):t),!1;else return!0})}_refinement(e){return new mr({schema:this,typeName:le.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:(t)=>this["~validate"](t)}}optional(){return gr.create(this,this._def)}nullable(){return Zr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return hr.create(this)}promise(){return oi.create(this,this._def)}or(e){return ds.create([this,e],this._def)}and(e){return fs.create(this,e,this._def)}transform(e){return new mr({...he(this._def),schema:this,typeName:le.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e==="function"?e:()=>e;return new ms({...he(this._def),innerType:this,defaultValue:t,typeName:le.ZodDefault})}brand(){return new Uc({typeName:le.ZodBranded,type:this,...he(this._def)})}catch(e){let t=typeof e==="function"?e:()=>e;return new ys({...he(this._def),innerType:this,catchValue:t,typeName:le.ZodCatch})}describe(e){return new this.constructor({...this._def,description:e})}pipe(e){return eo.create(this,e)}readonly(){return vs.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var uC=/^c[^\s-]{8,}$/i,dC=/^[0-9a-z]+$/,fC=/^[0-9A-HJKMNP-TV-Z]{26}$/i,pC=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,hC=/^[a-z0-9_-]{21}$/i,gC=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,mC=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,yC=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,vC="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Dc,xC=/^(?:(?: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])$/,SC=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,bC=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,CC=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,wC=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,EC=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Kh="((\\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])))",TC=new RegExp(`^${Kh}$`);function qh(e){let t="[0-5]\\d";if(e.precision)t=`${t}\\.\\d{${e.precision}}`;else if(e.precision==null)t=`${t}(\\.\\d+)?`;let n=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function AC(e){return new RegExp(`^${qh(e)}$`)}function _C(e){let t=`${Kh}T${qh(e)}`,n=[];if(n.push(e.local?"Z?":"Z"),e.offset)n.push("([+-]\\d{2}:?\\d{2})");return t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function kC(e,t){if((t==="v4"||!t)&&xC.test(e))return!0;if((t==="v6"||!t)&&bC.test(e))return!0;return!1}function IC(e,t){if(!gC.test(e))return!1;try{let[n]=e.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),i=JSON.parse(atob(r));if(typeof i!=="object"||i===null)return!1;if("typ"in i&&i?.typ!=="JWT")return!1;if(!i.alg)return!1;if(t&&i.alg!==t)return!1;return!0}catch{return!1}}function RC(e,t){if((t==="v4"||!t)&&SC.test(e))return!0;if((t==="v6"||!t)&&CC.test(e))return!0;return!1}class Ir extends Ce{_parse(e){if(this._def.coerce)e.data=String(e.data);if(this._getType(e)!==X.string){let i=this._getOrReturnCtx(e);return q(i,{code:N.invalid_type,expected:X.string,received:i.parsedType}),oe}let n=new xt,r=void 0;for(let i of this._def.checks)if(i.kind==="min"){if(e.data.length<i.value)r=this._getOrReturnCtx(e,r),q(r,{code:N.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty()}else if(i.kind==="max"){if(e.data.length>i.value)r=this._getOrReturnCtx(e,r),q(r,{code:N.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty()}else if(i.kind==="length"){let s=e.data.length>i.value,a=e.data.length<i.value;if(s||a){if(r=this._getOrReturnCtx(e,r),s)q(r,{code:N.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message});else if(a)q(r,{code:N.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message});n.dirty()}}else if(i.kind==="email"){if(!yC.test(e.data))r=this._getOrReturnCtx(e,r),q(r,{validation:"email",code:N.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="emoji"){if(!Dc)Dc=new RegExp(vC,"u");if(!Dc.test(e.data))r=this._getOrReturnCtx(e,r),q(r,{validation:"emoji",code:N.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="uuid"){if(!pC.test(e.data))r=this._getOrReturnCtx(e,r),q(r,{validation:"uuid",code:N.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="nanoid"){if(!hC.test(e.data))r=this._getOrReturnCtx(e,r),q(r,{validation:"nanoid",code:N.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="cuid"){if(!uC.test(e.data))r=this._getOrReturnCtx(e,r),q(r,{validation:"cuid",code:N.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="cuid2"){if(!dC.test(e.data))r=this._getOrReturnCtx(e,r),q(r,{validation:"cuid2",code:N.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="ulid"){if(!fC.test(e.data))r=this._getOrReturnCtx(e,r),q(r,{validation:"ulid",code:N.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="url")try{new URL(e.data)}catch{r=this._getOrReturnCtx(e,r),q(r,{validation:"url",code:N.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="regex"){if(i.regex.lastIndex=0,!i.regex.test(e.data))r=this._getOrReturnCtx(e,r),q(r,{validation:"regex",code:N.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="trim")e.data=e.data.trim();else if(i.kind==="includes"){if(!e.data.includes(i.value,i.position))r=this._getOrReturnCtx(e,r),q(r,{code:N.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),n.dirty()}else if(i.kind==="toLowerCase")e.data=e.data.toLowerCase();else if(i.kind==="toUpperCase")e.data=e.data.toUpperCase();else if(i.kind==="startsWith"){if(!e.data.startsWith(i.value))r=this._getOrReturnCtx(e,r),q(r,{code:N.invalid_string,validation:{startsWith:i.value},message:i.message}),n.dirty()}else if(i.kind==="endsWith"){if(!e.data.endsWith(i.value))r=this._getOrReturnCtx(e,r),q(r,{code:N.invalid_string,validation:{endsWith:i.value},message:i.message}),n.dirty()}else if(i.kind==="datetime"){if(!_C(i).test(e.data))r=this._getOrReturnCtx(e,r),q(r,{code:N.invalid_string,validation:"datetime",message:i.message}),n.dirty()}else if(i.kind==="date"){if(!TC.test(e.data))r=this._getOrReturnCtx(e,r),q(r,{code:N.invalid_string,validation:"date",message:i.message}),n.dirty()}else if(i.kind==="time"){if(!AC(i).test(e.data))r=this._getOrReturnCtx(e,r),q(r,{code:N.invalid_string,validation:"time",message:i.message}),n.dirty()}else if(i.kind==="duration"){if(!mC.test(e.data))r=this._getOrReturnCtx(e,r),q(r,{validation:"duration",code:N.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="ip"){if(!kC(e.data,i.version))r=this._getOrReturnCtx(e,r),q(r,{validation:"ip",code:N.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="jwt"){if(!IC(e.data,i.alg))r=this._getOrReturnCtx(e,r),q(r,{validation:"jwt",code:N.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="cidr"){if(!RC(e.data,i.version))r=this._getOrReturnCtx(e,r),q(r,{validation:"cidr",code:N.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="base64"){if(!wC.test(e.data))r=this._getOrReturnCtx(e,r),q(r,{validation:"base64",code:N.invalid_string,message:i.message}),n.dirty()}else if(i.kind==="base64url"){if(!EC.test(e.data))r=this._getOrReturnCtx(e,r),q(r,{validation:"base64url",code:N.invalid_string,message:i.message}),n.dirty()}else _e.assertNever(i);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement((r)=>e.test(r),{validation:t,code:N.invalid_string,...ee.errToObj(n)})}_addCheck(e){return new Ir({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...ee.errToObj(e)})}url(e){return this._addCheck({kind:"url",...ee.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...ee.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...ee.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...ee.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...ee.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...ee.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...ee.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...ee.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...ee.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...ee.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...ee.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...ee.errToObj(e)})}datetime(e){if(typeof e==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e});return this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...ee.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){if(typeof e==="string")return this._addCheck({kind:"time",precision:null,message:e});return this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...ee.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...ee.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...ee.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...ee.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...ee.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...ee.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...ee.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...ee.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...ee.errToObj(t)})}nonempty(e){return this.min(1,ee.errToObj(e))}trim(){return new Ir({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Ir({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Ir({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((e)=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find((e)=>e.kind==="date")}get isTime(){return!!this._def.checks.find((e)=>e.kind==="time")}get isDuration(){return!!this._def.checks.find((e)=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find((e)=>e.kind==="email")}get isURL(){return!!this._def.checks.find((e)=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find((e)=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find((e)=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((e)=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((e)=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((e)=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find((e)=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find((e)=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find((e)=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find((e)=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find((e)=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e}get maxLength(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e}}Ir.create=(e)=>new Ir({checks:[],typeName:le.ZodString,coerce:e?.coerce??!1,...he(e)});function BC(e,t){let n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,i=n>r?n:r,s=Number.parseInt(e.toFixed(i).replace(".","")),a=Number.parseInt(t.toFixed(i).replace(".",""));return s%a/10**i}class ni extends Ce{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce)e.data=Number(e.data);if(this._getType(e)!==X.number){let i=this._getOrReturnCtx(e);return q(i,{code:N.invalid_type,expected:X.number,received:i.parsedType}),oe}let n=void 0,r=new xt;for(let i of this._def.checks)if(i.kind==="int"){if(!_e.isInteger(e.data))n=this._getOrReturnCtx(e,n),q(n,{code:N.invalid_type,expected:"integer",received:"float",message:i.message}),r.dirty()}else if(i.kind==="min"){if(i.inclusive?e.data<i.value:e.data<=i.value)n=this._getOrReturnCtx(e,n),q(n,{code:N.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()}else if(i.kind==="max"){if(i.inclusive?e.data>i.value:e.data>=i.value)n=this._getOrReturnCtx(e,n),q(n,{code:N.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()}else if(i.kind==="multipleOf"){if(BC(e.data,i.value)!==0)n=this._getOrReturnCtx(e,n),q(n,{code:N.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()}else if(i.kind==="finite"){if(!Number.isFinite(e.data))n=this._getOrReturnCtx(e,n),q(n,{code:N.not_finite,message:i.message}),r.dirty()}else _e.assertNever(i);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,ee.toString(t))}gt(e,t){return this.setLimit("min",e,!1,ee.toString(t))}lte(e,t){return this.setLimit("max",e,!0,ee.toString(t))}lt(e,t){return this.setLimit("max",e,!1,ee.toString(t))}setLimit(e,t,n,r){return new ni({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:ee.toString(r)}]})}_addCheck(e){return new ni({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:ee.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:ee.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:ee.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:ee.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:ee.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:ee.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:ee.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:ee.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:ee.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e}get maxValue(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e}get isInt(){return!!this._def.checks.find((e)=>e.kind==="int"||e.kind==="multipleOf"&&_e.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks)if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;else if(n.kind==="min"){if(t===null||n.value>t)t=n.value}else if(n.kind==="max"){if(e===null||n.value<e)e=n.value}return Number.isFinite(t)&&Number.isFinite(e)}}ni.create=(e)=>new ni({checks:[],typeName:le.ZodNumber,coerce:e?.coerce||!1,...he(e)});class ii extends Ce{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==X.bigint)return this._getInvalidInput(e);let n=void 0,r=new xt;for(let i of this._def.checks)if(i.kind==="min"){if(i.inclusive?e.data<i.value:e.data<=i.value)n=this._getOrReturnCtx(e,n),q(n,{code:N.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),r.dirty()}else if(i.kind==="max"){if(i.inclusive?e.data>i.value:e.data>=i.value)n=this._getOrReturnCtx(e,n),q(n,{code:N.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),r.dirty()}else if(i.kind==="multipleOf"){if(e.data%i.value!==BigInt(0))n=this._getOrReturnCtx(e,n),q(n,{code:N.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()}else _e.assertNever(i);return{status:r.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return q(t,{code:N.invalid_type,expected:X.bigint,received:t.parsedType}),oe}gte(e,t){return this.setLimit("min",e,!0,ee.toString(t))}gt(e,t){return this.setLimit("min",e,!1,ee.toString(t))}lte(e,t){return this.setLimit("max",e,!0,ee.toString(t))}lt(e,t){return this.setLimit("max",e,!1,ee.toString(t))}setLimit(e,t,n,r){return new ii({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:ee.toString(r)}]})}_addCheck(e){return new ii({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:ee.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:ee.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:ee.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:ee.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:ee.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e}get maxValue(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e}}ii.create=(e)=>new ii({checks:[],typeName:le.ZodBigInt,coerce:e?.coerce??!1,...he(e)});class za extends Ce{_parse(e){if(this._def.coerce)e.data=Boolean(e.data);if(this._getType(e)!==X.boolean){let n=this._getOrReturnCtx(e);return q(n,{code:N.invalid_type,expected:X.boolean,received:n.parsedType}),oe}return Tt(e.data)}}za.create=(e)=>new za({typeName:le.ZodBoolean,coerce:e?.coerce||!1,...he(e)});class ls extends Ce{_parse(e){if(this._def.coerce)e.data=new Date(e.data);if(this._getType(e)!==X.date){let i=this._getOrReturnCtx(e);return q(i,{code:N.invalid_type,expected:X.date,received:i.parsedType}),oe}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return q(i,{code:N.invalid_date}),oe}let n=new xt,r=void 0;for(let i of this._def.checks)if(i.kind==="min"){if(e.data.getTime()<i.value)r=this._getOrReturnCtx(e,r),q(r,{code:N.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),n.dirty()}else if(i.kind==="max"){if(e.data.getTime()>i.value)r=this._getOrReturnCtx(e,r),q(r,{code:N.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()}else _e.assertNever(i);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ls({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:ee.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:ee.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e!=null?new Date(e):null}}ls.create=(e)=>new ls({checks:[],coerce:e?.coerce||!1,typeName:le.ZodDate,...he(e)});class Xa extends Ce{_parse(e){if(this._getType(e)!==X.symbol){let n=this._getOrReturnCtx(e);return q(n,{code:N.invalid_type,expected:X.symbol,received:n.parsedType}),oe}return Tt(e.data)}}Xa.create=(e)=>new Xa({typeName:le.ZodSymbol,...he(e)});class cs extends Ce{_parse(e){if(this._getType(e)!==X.undefined){let n=this._getOrReturnCtx(e);return q(n,{code:N.invalid_type,expected:X.undefined,received:n.parsedType}),oe}return Tt(e.data)}}cs.create=(e)=>new cs({typeName:le.ZodUndefined,...he(e)});class us extends Ce{_parse(e){if(this._getType(e)!==X.null){let n=this._getOrReturnCtx(e);return q(n,{code:N.invalid_type,expected:X.null,received:n.parsedType}),oe}return Tt(e.data)}}us.create=(e)=>new us({typeName:le.ZodNull,...he(e)});class si extends Ce{constructor(){super(...arguments);this._any=!0}_parse(e){return Tt(e.data)}}si.create=(e)=>new si({typeName:le.ZodAny,...he(e)});class Sn extends Ce{constructor(){super(...arguments);this._unknown=!0}_parse(e){return Tt(e.data)}}Sn.create=(e)=>new Sn({typeName:le.ZodUnknown,...he(e)});class Rr extends Ce{_parse(e){let t=this._getOrReturnCtx(e);return q(t,{code:N.invalid_type,expected:X.never,received:t.parsedType}),oe}}Rr.create=(e)=>new Rr({typeName:le.ZodNever,...he(e)});class Qa extends Ce{_parse(e){if(this._getType(e)!==X.undefined){let n=this._getOrReturnCtx(e);return q(n,{code:N.invalid_type,expected:X.void,received:n.parsedType}),oe}return Tt(e.data)}}Qa.create=(e)=>new Qa({typeName:le.ZodVoid,...he(e)});class hr extends Ce{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==X.array)return q(t,{code:N.invalid_type,expected:X.array,received:t.parsedType}),oe;if(r.exactLength!==null){let s=t.data.length>r.exactLength.value,a=t.data.length<r.exactLength.value;if(s||a)q(t,{code:s?N.too_big:N.too_small,minimum:a?r.exactLength.value:void 0,maximum:s?r.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty()}if(r.minLength!==null){if(t.data.length<r.minLength.value)q(t,{code:N.too_small,minimum:r.minLength.value,type:"array",inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()}if(r.maxLength!==null){if(t.data.length>r.maxLength.value)q(t,{code:N.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()}if(t.common.async)return Promise.all([...t.data].map((s,a)=>r.type._parseAsync(new er(t,s,t.path,a)))).then((s)=>xt.mergeArray(n,s));let i=[...t.data].map((s,a)=>r.type._parseSync(new er(t,s,t.path,a)));return xt.mergeArray(n,i)}get element(){return this._def.type}min(e,t){return new hr({...this._def,minLength:{value:e,message:ee.toString(t)}})}max(e,t){return new hr({...this._def,maxLength:{value:e,message:ee.toString(t)}})}length(e,t){return new hr({...this._def,exactLength:{value:e,message:ee.toString(t)}})}nonempty(e){return this.min(1,e)}}hr.create=(e,t)=>new hr({type:e,minLength:null,maxLength:null,exactLength:null,typeName:le.ZodArray,...he(t)});function ri(e){if(e instanceof Ze){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=gr.create(ri(r))}return new Ze({...e._def,shape:()=>t})}else if(e instanceof hr)return new hr({...e._def,type:ri(e.element)});else if(e instanceof gr)return gr.create(ri(e.unwrap()));else if(e instanceof Zr)return Zr.create(ri(e.unwrap()));else if(e instanceof Br)return Br.create(e.items.map((t)=>ri(t)));else return e}class Ze extends Ce{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=_e.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==X.object){let l=this._getOrReturnCtx(e);return q(l,{code:N.invalid_type,expected:X.object,received:l.parsedType}),oe}let{status:n,ctx:r}=this._processInputParams(e),{shape:i,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof Rr&&this._def.unknownKeys==="strip")){for(let l in r.data)if(!s.includes(l))a.push(l)}let o=[];for(let l of s){let c=i[l],u=r.data[l];o.push({key:{status:"valid",value:l},value:c._parse(new er(r,u,r.path,l)),alwaysSet:l in r.data})}if(this._def.catchall instanceof Rr){let l=this._def.unknownKeys;if(l==="passthrough")for(let c of a)o.push({key:{status:"valid",value:c},value:{status:"valid",value:r.data[c]}});else if(l==="strict"){if(a.length>0)q(r,{code:N.unrecognized_keys,keys:a}),n.dirty()}else if(l==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let c of a){let u=r.data[c];o.push({key:{status:"valid",value:c},value:l._parse(new er(r,u,r.path,c)),alwaysSet:c in r.data})}}if(r.common.async)return Promise.resolve().then(async()=>{let l=[];for(let c of o){let u=await c.key,d=await c.value;l.push({key:u,value:d,alwaysSet:c.alwaysSet})}return l}).then((l)=>xt.mergeObjectSync(n,l));else return xt.mergeObjectSync(n,o)}get shape(){return this._def.shape()}strict(e){return ee.errToObj,new Ze({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{let r=this._def.errorMap?.(t,n).message??n.defaultError;if(t.code==="unrecognized_keys")return{message:ee.errToObj(e).message??r};return{message:r}}}:{}})}strip(){return new Ze({...this._def,unknownKeys:"strip"})}passthrough(){return new Ze({...this._def,unknownKeys:"passthrough"})}extend(e){return new Ze({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new Ze({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:le.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new Ze({...this._def,catchall:e})}pick(e){let t={};for(let n of _e.objectKeys(e))if(e[n]&&this.shape[n])t[n]=this.shape[n];return new Ze({...this._def,shape:()=>t})}omit(e){let t={};for(let n of _e.objectKeys(this.shape))if(!e[n])t[n]=this.shape[n];return new Ze({...this._def,shape:()=>t})}deepPartial(){return ri(this)}partial(e){let t={};for(let n of _e.objectKeys(this.shape)){let r=this.shape[n];if(e&&!e[n])t[n]=r;else t[n]=r.optional()}return new Ze({...this._def,shape:()=>t})}required(e){let t={};for(let n of _e.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let i=this.shape[n];while(i instanceof gr)i=i._def.innerType;t[n]=i}return new Ze({...this._def,shape:()=>t})}keyof(){return Gh(_e.objectKeys(this.shape))}}Ze.create=(e,t)=>new Ze({shape:()=>e,unknownKeys:"strip",catchall:Rr.create(),typeName:le.ZodObject,...he(t)});Ze.strictCreate=(e,t)=>new Ze({shape:()=>e,unknownKeys:"strict",catchall:Rr.create(),typeName:le.ZodObject,...he(t)});Ze.lazycreate=(e,t)=>new Ze({shape:e,unknownKeys:"strip",catchall:Rr.create(),typeName:le.ZodObject,...he(t)});class ds extends Ce{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function r(i){for(let a of i)if(a.result.status==="valid")return a.result;for(let a of i)if(a.result.status==="dirty")return t.common.issues.push(...a.ctx.common.issues),a.result;let s=i.map((a)=>new Pt(a.ctx.common.issues));return q(t,{code:N.invalid_union,unionErrors:s}),oe}if(t.common.async)return Promise.all(n.map(async(i)=>{let s={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:s}),ctx:s}})).then(r);else{let i=void 0,s=[];for(let o of n){let l={...t,common:{...t.common,issues:[]},parent:null},c=o._parseSync({data:t.data,path:t.path,parent:l});if(c.status==="valid")return c;else if(c.status==="dirty"&&!i)i={result:c,ctx:l};if(l.common.issues.length)s.push(l.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;let a=s.map((o)=>new Pt(o));return q(t,{code:N.invalid_union,unionErrors:a}),oe}}get options(){return this._def.options}}ds.create=(e,t)=>new ds({options:e,typeName:le.ZodUnion,...he(t)});var kr=(e)=>{if(e instanceof ps)return kr(e.schema);else if(e instanceof mr)return kr(e.innerType());else if(e instanceof hs)return[e.value];else if(e instanceof bn)return e.options;else if(e instanceof gs)return _e.objectValues(e.enum);else if(e instanceof ms)return kr(e._def.innerType);else if(e instanceof cs)return[void 0];else if(e instanceof us)return[null];else if(e instanceof gr)return[void 0,...kr(e.unwrap())];else if(e instanceof Zr)return[null,...kr(e.unwrap())];else if(e instanceof Uc)return kr(e.unwrap());else if(e instanceof vs)return kr(e.unwrap());else if(e instanceof ys)return kr(e._def.innerType);else return[]};class Oc extends Ce{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==X.object)return q(t,{code:N.invalid_type,expected:X.object,received:t.parsedType}),oe;let n=this.discriminator,r=t.data[n],i=this.optionsMap.get(r);if(!i)return q(t,{code:N.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),oe;if(t.common.async)return i._parseAsync({data:t.data,path:t.path,parent:t});else return i._parseSync({data:t.data,path:t.path,parent:t})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){let r=new Map;for(let i of t){let s=kr(i.shape[e]);if(!s.length)throw Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of s){if(r.has(a))throw Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);r.set(a,i)}}return new Oc({typeName:le.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:r,...he(n)})}}function Lc(e,t){let n=_r(e),r=_r(t);if(e===t)return{valid:!0,data:e};else if(n===X.object&&r===X.object){let i=_e.objectKeys(t),s=_e.objectKeys(e).filter((o)=>i.indexOf(o)!==-1),a={...e,...t};for(let o of s){let l=Lc(e[o],t[o]);if(!l.valid)return{valid:!1};a[o]=l.data}return{valid:!0,data:a}}else if(n===X.array&&r===X.array){if(e.length!==t.length)return{valid:!1};let i=[];for(let s=0;s<e.length;s++){let a=e[s],o=t[s],l=Lc(a,o);if(!l.valid)return{valid:!1};i.push(l.data)}return{valid:!0,data:i}}else if(n===X.date&&r===X.date&&+e===+t)return{valid:!0,data:e};else return{valid:!1}}class fs extends Ce{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(i,s)=>{if(Pc(i)||Pc(s))return oe;let a=Lc(i.value,s.value);if(!a.valid)return q(n,{code:N.invalid_intersection_types}),oe;if(Nc(i)||Nc(s))t.dirty();return{status:t.value,value:a.data}};if(n.common.async)return Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([i,s])=>r(i,s));else return r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}fs.create=(e,t,n)=>new fs({left:e,right:t,typeName:le.ZodIntersection,...he(n)});class Br extends Ce{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==X.array)return q(n,{code:N.invalid_type,expected:X.array,received:n.parsedType}),oe;if(n.data.length<this._def.items.length)return q(n,{code:N.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),oe;if(!this._def.rest&&n.data.length>this._def.items.length)q(n,{code:N.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty();let i=[...n.data].map((s,a)=>{let o=this._def.items[a]||this._def.rest;if(!o)return null;return o._parse(new er(n,s,n.path,a))}).filter((s)=>!!s);if(n.common.async)return Promise.all(i).then((s)=>xt.mergeArray(t,s));else return xt.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new Br({...this._def,rest:e})}}Br.create=(e,t)=>{if(!Array.isArray(e))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new Br({items:e,typeName:le.ZodTuple,rest:null,...he(t)})};class Ya extends Ce{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==X.object)return q(n,{code:N.invalid_type,expected:X.object,received:n.parsedType}),oe;let r=[],i=this._def.keyType,s=this._def.valueType;for(let a in n.data)r.push({key:i._parse(new er(n,a,n.path,a)),value:s._parse(new er(n,n.data[a],n.path,a)),alwaysSet:a in n.data});if(n.common.async)return xt.mergeObjectAsync(t,r);else return xt.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(e,t,n){if(t instanceof Ce)return new Ya({keyType:e,valueType:t,typeName:le.ZodRecord,...he(n)});return new Ya({keyType:Ir.create(),valueType:e,typeName:le.ZodRecord,...he(t)})}}class Ja extends Ce{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==X.map)return q(n,{code:N.invalid_type,expected:X.map,received:n.parsedType}),oe;let r=this._def.keyType,i=this._def.valueType,s=[...n.data.entries()].map(([a,o],l)=>({key:r._parse(new er(n,a,n.path,[l,"key"])),value:i._parse(new er(n,o,n.path,[l,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let o of s){let l=await o.key,c=await o.value;if(l.status==="aborted"||c.status==="aborted")return oe;if(l.status==="dirty"||c.status==="dirty")t.dirty();a.set(l.value,c.value)}return{status:t.value,value:a}})}else{let a=new Map;for(let o of s){let{key:l,value:c}=o;if(l.status==="aborted"||c.status==="aborted")return oe;if(l.status==="dirty"||c.status==="dirty")t.dirty();a.set(l.value,c.value)}return{status:t.value,value:a}}}}Ja.create=(e,t,n)=>new Ja({valueType:t,keyType:e,typeName:le.ZodMap,...he(n)});class ai extends Ce{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==X.set)return q(n,{code:N.invalid_type,expected:X.set,received:n.parsedType}),oe;let r=this._def;if(r.minSize!==null){if(n.data.size<r.minSize.value)q(n,{code:N.too_small,minimum:r.minSize.value,type:"set",inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()}if(r.maxSize!==null){if(n.data.size>r.maxSize.value)q(n,{code:N.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty()}let i=this._def.valueType;function s(o){let l=new Set;for(let c of o){if(c.status==="aborted")return oe;if(c.status==="dirty")t.dirty();l.add(c.value)}return{status:t.value,value:l}}let a=[...n.data.values()].map((o,l)=>i._parse(new er(n,o,n.path,l)));if(n.common.async)return Promise.all(a).then((o)=>s(o));else return s(a)}min(e,t){return new ai({...this._def,minSize:{value:e,message:ee.toString(t)}})}max(e,t){return new ai({...this._def,maxSize:{value:e,message:ee.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}ai.create=(e,t)=>new ai({valueType:e,minSize:null,maxSize:null,typeName:le.ZodSet,...he(t)});class os extends Ce{constructor(){super(...arguments);this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==X.function)return q(t,{code:N.invalid_type,expected:X.function,received:t.parsedType}),oe;function n(a,o){return ja({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ss(),Jr].filter((l)=>!!l),issueData:{code:N.invalid_arguments,argumentsError:o}})}function r(a,o){return ja({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ss(),Jr].filter((l)=>!!l),issueData:{code:N.invalid_return_type,returnTypeError:o}})}let i={errorMap:t.common.contextualErrorMap},s=t.data;if(this._def.returns instanceof oi){let a=this;return Tt(async function(...o){let l=new Pt([]),c=await a._def.args.parseAsync(o,i).catch((p)=>{throw l.addIssue(n(o,p)),l}),u=await Reflect.apply(s,this,c);return await a._def.returns._def.type.parseAsync(u,i).catch((p)=>{throw l.addIssue(r(u,p)),l})})}else{let a=this;return Tt(function(...o){let l=a._def.args.safeParse(o,i);if(!l.success)throw new Pt([n(o,l.error)]);let c=Reflect.apply(s,this,l.data),u=a._def.returns.safeParse(c,i);if(!u.success)throw new Pt([r(c,u.error)]);return u.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new os({...this._def,args:Br.create(e).rest(Sn.create())})}returns(e){return new os({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new os({args:e?e:Br.create([]).rest(Sn.create()),returns:t||Sn.create(),typeName:le.ZodFunction,...he(n)})}}class ps extends Ce{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}ps.create=(e,t)=>new ps({getter:e,typeName:le.ZodLazy,...he(t)});class hs extends Ce{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return q(t,{received:t.data,code:N.invalid_literal,expected:this._def.value}),oe}return{status:"valid",value:e.data}}get value(){return this._def.value}}hs.create=(e,t)=>new hs({value:e,typeName:le.ZodLiteral,...he(t)});function Gh(e,t){return new bn({values:e,typeName:le.ZodEnum,...he(t)})}class bn extends Ce{_parse(e){if(typeof e.data!=="string"){let t=this._getOrReturnCtx(e),n=this._def.values;return q(t,{expected:_e.joinValues(n),received:t.parsedType,code:N.invalid_type}),oe}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return q(t,{received:t.data,code:N.invalid_enum_value,options:n}),oe}return Tt(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return bn.create(e,{...this._def,...t})}exclude(e,t=this._def){return bn.create(this.options.filter((n)=>!e.includes(n)),{...this._def,...t})}}bn.create=Gh;class gs extends Ce{_parse(e){let t=_e.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==X.string&&n.parsedType!==X.number){let r=_e.objectValues(t);return q(n,{expected:_e.joinValues(r),received:n.parsedType,code:N.invalid_type}),oe}if(!this._cache)this._cache=new Set(_e.getValidEnumValues(this._def.values));if(!this._cache.has(e.data)){let r=_e.objectValues(t);return q(n,{received:n.data,code:N.invalid_enum_value,options:r}),oe}return Tt(e.data)}get enum(){return this._def.values}}gs.create=(e,t)=>new gs({values:e,typeName:le.ZodNativeEnum,...he(t)});class oi extends Ce{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==X.promise&&t.common.async===!1)return q(t,{code:N.invalid_type,expected:X.promise,received:t.parsedType}),oe;let n=t.parsedType===X.promise?t.data:Promise.resolve(t.data);return Tt(n.then((r)=>this._def.type.parseAsync(r,{path:t.path,errorMap:t.common.contextualErrorMap})))}}oi.create=(e,t)=>new oi({type:e,typeName:le.ZodPromise,...he(t)});class mr extends Ce{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===le.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:(s)=>{if(q(n,s),s.fatal)t.abort();else t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),r.type==="preprocess"){let s=r.transform(n.data,i);if(n.common.async)return Promise.resolve(s).then(async(a)=>{if(t.value==="aborted")return oe;let o=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});if(o.status==="aborted")return oe;if(o.status==="dirty")return ti(o.value);if(t.value==="dirty")return ti(o.value);return o});else{if(t.value==="aborted")return oe;let a=this._def.schema._parseSync({data:s,path:n.path,parent:n});if(a.status==="aborted")return oe;if(a.status==="dirty")return ti(a.value);if(t.value==="dirty")return ti(a.value);return a}}if(r.type==="refinement"){let s=(a)=>{let o=r.refinement(a,i);if(n.common.async)return Promise.resolve(o);if(o instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(a.status==="aborted")return oe;if(a.status==="dirty")t.dirty();return s(a.value),{status:t.value,value:a.value}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then((a)=>{if(a.status==="aborted")return oe;if(a.status==="dirty")t.dirty();return s(a.value).then(()=>({status:t.value,value:a.value}))})}if(r.type==="transform")if(n.common.async===!1){let s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!xn(s))return oe;let a=r.transform(s.value,i);if(a instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then((s)=>{if(!xn(s))return oe;return Promise.resolve(r.transform(s.value,i)).then((a)=>({status:t.value,value:a}))});_e.assertNever(r)}}mr.create=(e,t,n)=>new mr({schema:e,typeName:le.ZodEffects,effect:t,...he(n)});mr.createWithPreprocess=(e,t,n)=>new mr({schema:t,effect:{type:"preprocess",transform:e},typeName:le.ZodEffects,...he(n)});class gr extends Ce{_parse(e){if(this._getType(e)===X.undefined)return Tt(void 0);return this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}gr.create=(e,t)=>new gr({innerType:e,typeName:le.ZodOptional,...he(t)});class Zr extends Ce{_parse(e){if(this._getType(e)===X.null)return Tt(null);return this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Zr.create=(e,t)=>new Zr({innerType:e,typeName:le.ZodNullable,...he(t)});class ms extends Ce{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;if(t.parsedType===X.undefined)n=this._def.defaultValue();return this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}ms.create=(e,t)=>new ms({innerType:e,typeName:le.ZodDefault,defaultValue:typeof t.default==="function"?t.default:()=>t.default,...he(t)});class ys extends Ce{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});if(as(r))return r.then((i)=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Pt(n.common.issues)},input:n.data})}));else return{status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new Pt(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}ys.create=(e,t)=>new ys({innerType:e,typeName:le.ZodCatch,catchValue:typeof t.catch==="function"?t.catch:()=>t.catch,...he(t)});class Za extends Ce{_parse(e){if(this._getType(e)!==X.nan){let n=this._getOrReturnCtx(e);return q(n,{code:N.invalid_type,expected:X.nan,received:n.parsedType}),oe}return{status:"valid",value:e.data}}}Za.create=(e)=>new Za({typeName:le.ZodNaN,...he(e)});var LA=Symbol("zod_brand");class Uc extends Ce{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}}class eo extends Ce{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});if(i.status==="aborted")return oe;if(i.status==="dirty")return t.dirty(),ti(i.value);else return this._def.out._parseAsync({data:i.value,path:n.path,parent:n})})();else{let r=this._def.in._parseSync({data:n.data,path:n.path,parent:n});if(r.status==="aborted")return oe;if(r.status==="dirty")return t.dirty(),{status:"dirty",value:r.value};else return this._def.out._parseSync({data:r.value,path:n.path,parent:n})}}static create(e,t){return new eo({in:e,out:t,typeName:le.ZodPipeline})}}class vs extends Ce{_parse(e){let t=this._def.innerType._parse(e),n=(r)=>{if(xn(r))r.value=Object.freeze(r.value);return r};return as(t)?t.then((r)=>n(r)):n(t)}unwrap(){return this._def.innerType}}vs.create=(e,t)=>new vs({innerType:e,typeName:le.ZodReadonly,...he(t)});function Hh(e,t){let n=typeof e==="function"?e(t):typeof e==="string"?{message:e}:e;return typeof n==="string"?{message:n}:n}function PC(e,t={},n){if(e)return si.create().superRefine((r,i)=>{let s=e(r);if(s instanceof Promise)return s.then((a)=>{if(!a){let o=Hh(t,r),l=o.fatal??n??!0;i.addIssue({code:"custom",...o,fatal:l})}});if(!s){let a=Hh(t,r),o=a.fatal??n??!0;i.addIssue({code:"custom",...a,fatal:o})}return});return si.create()}var OA={object:Ze.lazycreate},le;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(le||(le={}));var Se=Ir.create,Pr=ni.create,UA=Za.create,VA=ii.create,Kt=za.create,FA=ls.create,MA=Xa.create,$A=cs.create,WA=us.create,HA=si.create,KA=Sn.create,qA=Rr.create,GA=Qa.create,ze=hr.create,{create:ht,strictCreate:jA}=Ze,zA=ds.create,XA=Oc.create,QA=fs.create,NC=Br.create,jh=Ya.create,YA=Ja.create,JA=ai.create,ZA=os.create,e_=ps.create,t_=hs.create,li=bn.create,r_=gs.create,n_=oi.create,i_=mr.create,s_=gr.create,a_=Zr.create,o_=mr.createWithPreprocess,l_=eo.create;function Fc(e){if(LC(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 Mc='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.',ro=Se().refine(Fc,{message:Mc});function Qh(e){let t=e.indexOf(":");return!(t!==-1&&e.indexOf(":",t+1)!==-1)||e.startsWith("[")}var UC=Se().refine((e)=>Qh(e)&&Fc(Xi(e).hostPattern),{message:Mc+' An optional ":port" suffix (1-65535) restricts the entry to that port.'}),VC=Se().refine((e)=>{if(!Qh(e))return!1;let{hostPattern:t}=Xi(e);return t==="*"||Fc(t)},{message:Mc+' In deniedDomains a bare "*" (deny-all) is also accepted, and an optional ":port" suffix (1-65535) restricts the entry to that port.'}),xs=Se().min(1,"Path cannot be empty"),zh=Se().min(1,"Path cannot be empty").refine((e)=>OC(e),{message:"Binary path must be absolute"}),FC=ht({socketPath:Se().min(1).describe("Unix socket path to the MITM proxy"),domains:ze(ro).min(1).describe('Domains to route through the MITM proxy (e.g., ["api.example.com", "*.internal.org"])')}),MC=ht({http:Se().url().optional().describe("Upstream proxy URL for plain HTTP traffic"),https:Se().url().optional().describe("Upstream proxy URL for HTTPS/CONNECT traffic (falls back to http if unset)"),noProxy:Se().optional().describe("Comma-separated NO_PROXY list (hostname suffixes and CIDR ranges). Matching destinations connect directly instead of via the parent proxy.")}),Yh=li(["deny","mask"]),to=Se().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"),Jh=Se().superRefine((e,t)=>{try{let{groupCount:n}=Ml(e);if(n<1)t.addIssue({code:N.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:N.custom,message:n instanceof Error?n.message:"Credential extract pattern is invalid"})}}),$C=ht({path:xs.describe("Path to a credential file or directory. Supports the same path forms as filesystem.denyRead (absolute paths and ~ expansion)."),mode:Yh.describe("Access mode for this path"),extract:Jh.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:li(["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:li(["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(Se().min(1)).optional().describe('Names of top-level payload claims to mask inside each decoded value, instead of replacing the whole token. Each named claim present with a string value gets its own sentinel; all other claims are preserved so claim-reading clients keep working. Requires decode. If no named claim matches in any verified token, behaviour is governed by onExtractNoMatch (default "warn"). Only meaningful when mode is "mask"; accepted but ignored for "deny".'),maskDuplicates:Kt().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(ro).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".')}),WC=ht({name:to.describe("Environment variable name"),mode:Yh.describe("Access mode for this environment variable"),extract:Jh.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:li(["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:li(["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(Se().min(1)).optional().describe('Names of top-level payload claims to mask inside the decoded value, instead of replacing the whole token. Each named claim present with a string value gets its own sentinel; all other claims are preserved so claim-reading clients keep working. Requires decode. If no named claim matches, the variable is left unmasked with a stderr warning (fail-open). Only meaningful when mode is "mask"; accepted but ignored for "deny".'),injectHosts:ze(ro).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(Se().regex(/^[a-z0-9-]{1,64}$/)).min(1).optional().describe('Optional narrowing of where in a request the proxy substitutes this credential: only in these headers (lower-case names), never in other headers or the body. If unset, every header and the body. Only meaningful when mode is "mask".')}),HC=ht({accessKeyIdVar:to.describe("Name of the masked env var holding the AWS access key id."),secretAccessKeyVar:to.describe("Name of the masked env var holding the AWS secret access key."),sessionTokenVar:to.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(),Vc=li(["deny","passthrough"]),KC=ht({streaming:Vc.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:Vc.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:Vc.optional().describe('Policy for SigV4A (AWS4-ECDSA-P256-SHA256) asymmetric signatures: there is no shared-key HMAC to recompute. Default "deny".')}).strict(),Zh=ht({files:ze($C).optional().describe("Credential files or directories to protect"),envVars:ze(WC).optional().describe("Environment variables to protect"),allowPlaintextInject:Kt().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(HC).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:KC.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(),Xh=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/,qC=/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?$/,GC=ht({url:Se().url().refine((e)=>new URL(e).protocol==="https:",{message:"brokerForward.url must be https"}),tokenEnvVar:Se().regex(Xh),rules:ze(ht({envVar:Se().regex(Xh),hosts:ze(Se().regex(qC)).min(1).max(16)}).strict()).min(1).max(32)}).strict(),e0=ht({allowedDomains:ze(UC).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(VC).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:jh(Se(),Se().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:Kt().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."),strictAllowlist:Kt().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(Se()).optional().describe("macOS only: Unix socket paths to allow. Ignored on Linux (seccomp cannot filter by path)."),allowAllUnixSockets:Kt().optional().describe("If true, allow all Unix sockets (disables blocking on both platforms)."),allowLocalBinding:Kt().optional().describe("Whether to allow binding to local ports (default: false)"),allowMachLookup:ze(Se().refine((e)=>!(e.endsWith("*")?e.slice(0,-1):e).includes("*"),{message:'Wildcards are only allowed as a single trailing "*" (e.g., "com.example.*" or "*" for all services).'})).optional().describe('macOS only: Additional XPC/Mach service names to allow looking up. Supports trailing-wildcard prefix matching (e.g., "2BUA8C4S2C.com.1password.*"). Needed for tools like 1Password CLI, Playwright, or the iOS Simulator that communicate via XPC.'),httpProxyPort:Pr().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:Pr().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:FC.optional().describe("Optional MITM proxy configuration. Routes matching domains through an upstream proxy via Unix socket while SRT still handles allow/deny filtering."),filterRequest:PC((e)=>typeof e==="function",{message:"filterRequest must be a function"}).optional().describe("Per-request filter callback. Receives the parsed HTTP request (web-standard Request) and returns {action, reason?}. Denied requests get a 403 with the reason. If the callback throws, the request is denied. Applies to plain HTTP through the proxy and, when tlsTerminate is configured, to terminated HTTPS. SRT does not provide a policy language; library consumers own matching."),tlsTerminate:ht({caCertPath:Se().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:Se().min(1).optional().describe("Path to the PEM-encoded private key for caCertPath."),excludeDomains:ze(ro).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(Se().min(1)).optional().describe("Paths to PEM CA certificate files appended to the trust bundle the sandboxed child is pointed at, after the MITM CA and the host's regular roots. Use for site-local roots (e.g. an internal mTLS CA) presented by excluded/passthrough hosts, so the child can verify them itself. Only the CERTIFICATE blocks of each file are copied; files that are missing, unreadable, or contain no PEM CERTIFICATE block are skipped (with a debug log), so paths that exist on only some hosts are safe to list.")}).refine((e)=>!e.caCertPath===!e.caKeyPath,{message:"caCertPath and caKeyPath must be provided together"}).optional().describe("[EXPERIMENTAL] Enable in-process TLS termination so HTTPS request/response bodies are visible to SRT. Provide a CA cert+key, or omit both to have SRT generate an ephemeral one."),parentProxy:MC.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:GC.optional().describe("Credential placeholders a remote broker swaps (see broker-forward.ts).")}),t0=ht({disabled:Kt().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(xs).describe("Paths denied for reading"),allowRead:ze(xs).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(xs).describe("Paths allowed for writing"),denyWrite:ze(xs).describe("Paths denied for writing (takes precedence over allowWrite)"),allowGitConfig:Kt().optional().describe("Allow writes to .git/config files (default: false). Enables git remote URL updates while keeping .git/hooks protected.")}),r0=jh(Se(),ze(Se())).describe('Map of command patterns to filesystem paths to ignore violations for. Use "*" to match all commands'),n0=ht({command:Se().describe("The ripgrep command to execute"),args:ze(Se()).optional().describe("Additional arguments to pass before ripgrep args"),argv0:Se().optional().describe("Override argv[0] when spawning (for multicall binaries that dispatch on argv[0])")}),i0=ht({safeDirectories:ze(Se()).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.")}),s0=ht({path:Se().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.")}),a0=ht({sandboxUser:Se().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:Se().uuid().optional().describe("WFP sublayer GUID under which the filters were installed. Omit to use the srt-win compile-time default. Set this when filters were installed by enterprise tooling under a custom sublayer."),wfpSublayerGuid:Se().uuid().optional().describe("Deprecated alias for sublayerGuid."),proxyPortRange:NC([Pr().int().min(1),Pr().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:s0.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.")}),jC=ht({applyPath:Se().optional().describe("Path to the apply-seccomp binary"),argv0:Se().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.")}),zC=ht({network:e0.describe("Network restrictions configuration"),filesystem:t0.describe("Filesystem restrictions configuration"),credentials:Zh.optional().describe("Credential handling configuration. Only the explicitly declared files and environment variables are restricted."),ignoreViolations:r0.optional().describe("Optional configuration for ignoring specific violations"),enableWeakerNestedSandbox:Kt().optional().describe("Enable weaker nested sandbox mode (for Docker environments)"),runAsUid:Pr().int().nonnegative().optional().describe("ARA: uid to drop the sandboxed command to (bwrap --uid)"),runAsGid:Pr().int().nonnegative().optional().describe("ARA: gid to drop the sandboxed command to (bwrap --gid)"),runAsHostUid:Pr().int().positive().optional().describe("ARA: real host uid used to launch the sandboxed bwrap child"),runAsHostGid:Pr().int().positive().optional().describe("ARA: real host gid used to launch the sandboxed bwrap child"),runAsHostHome:Se().min(1).optional().describe("ARA: HOME set inside a real-host-uid sandbox child"),runAsHostUser:Se().min(1).optional().describe("ARA: USER and LOGNAME set inside a real-host-uid sandbox child"),enableWeakerNetworkIsolation:Kt().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:Kt().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:n0.optional().describe('Custom ripgrep configuration (default: { command: "rg" })'),mandatoryDenySearchDepth:Pr().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:Kt().optional().describe("Allow pseudo-terminal (pty) operations (macOS only)"),seccomp:jC.optional().describe("Custom seccomp binary paths (Linux only)."),bwrapPath:zh.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:zh.optional().describe('Linux only: absolute path to the socat binary. When set, this path is used directly instead of resolving "socat" via PATH.'),windows:a0.optional().describe("Windows-specific settings (WFP sublayer, proxy port range)."),git:i0.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(Qi),i=(l,c)=>{for(let[u,d]of l.entries())if(!$a(d,r))t.addIssue({code:N.custom,path:[...c,u],message:`injectHosts entry "${d}" is not reachable via `+`network.allowedDomains \u2014 add "${d}" (or a covering wildcard) to allowedDomains, or remove it from injectHosts.`})},s=!1,a=(l,c)=>{if(l.injectHosts)i(l.injectHosts,[...c,"injectHosts"]);if(l.mode!=="mask")return;s=!0;let u=e.network.tlsTerminate?.excludeDomains;if(u?.length){if(l.injectHosts){for(let[d,p]of l.injectHosts.entries())if($a(p,u))t.addIssue({code:N.custom,path:[...c,"injectHosts",d],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((d)=>$a(d,u)))t.addIssue({code:N.custom,path:c,message:"This masked credential has no injectHosts, so it defaults "+"to network.allowedDomains \u2014 but "+"network.tlsTerminate.excludeDomains covers every allowed domain, so it could never be injected anywhere. Credential injection only runs on TLS-terminated connections."})}if(l.injectHosts!==void 0&&l.injectHosts.length===0)t.addIssue({code:N.custom,path:c,message:"injectHosts is explicitly empty \u2014 the credential would be "+"masked but never injected. Omit injectHosts to default to network.allowedDomains, or list the intended hosts."})};for(let[l,c]of(n.envVars??[]).entries()){if(a(c,["credentials","envVars",l]),c.maskClaims!==void 0&&c.decode===void 0)t.addIssue({code:N.custom,path:["credentials","envVars",l,"maskClaims"],message:"maskClaims requires decode \u2014 it names claims inside the "+'decoded payload. Set decode (e.g. "jwt"), or remove maskClaims to mask the whole value.'});if(c.maskClaims!==void 0&&c.maskClaims.length===0)t.addIssue({code:N.custom,path:["credentials","envVars",l,"maskClaims"],message:"maskClaims is explicitly empty \u2014 no claim would ever be "+"masked. Omit maskClaims to mask the whole token, or list the claims to protect."})}for(let[l,c]of(n.files??[]).entries()){if(a(c,["credentials","files",l]),c.maskClaims!==void 0&&c.decode===void 0)t.addIssue({code:N.custom,path:["credentials","files",l,"maskClaims"],message:"maskClaims requires decode \u2014 it names claims inside the "+'decoded payload. Set decode (e.g. "jwt"), or remove maskClaims to mask the extracted value whole.'});if(c.maskClaims!==void 0&&c.maskClaims.length===0)t.addIssue({code:N.custom,path:["credentials","files",l,"maskClaims"],message:"maskClaims is explicitly empty \u2014 no claim would ever be "+"masked. Omit maskClaims to mask the whole token, or list the claims to protect."});if(c.mode==="mask"&&c.path.endsWith("/"))t.addIssue({code:N.custom,path:["credentials","files",l,"path"],message:`Credential mode "mask" applies to a single file, not a directory. Use mode "deny" for "${c.path}", or point at the credential file inside it.`})}let o=new Set;for(let[l,c]of(n.awsPairs??[]).entries()){let u=[["accessKeyIdVar",c.accessKeyIdVar],["secretAccessKeyVar",c.secretAccessKeyVar]];if(c.sessionTokenVar!==void 0)u.push(["sessionTokenVar",c.sessionTokenVar]);for(let[d,p]of u){let h=["credentials","awsPairs",l,d];if(o.has(p)){t.addIssue({code:N.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}o.add(p);let f=(n.envVars??[]).find((v)=>v.name===p);if(f===void 0||f.mode!=="mask")t.addIssue({code:N.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(f.extract!==void 0||f.decode!==void 0)t.addIssue({code:N.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(s&&e.network.tlsTerminate===void 0&&!n.allowPlaintextInject)t.addIssue({code:N.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{Zh as CredentialsConfigSchema,Da as DEFAULT_WINDOWS_PROXY_PORT_RANGE,t0 as FilesystemConfigSchema,i0 as GitConfigSchema,r0 as IgnoreViolationsConfigSchema,e0 as NetworkConfigSchema,n0 as RipgrepConfigSchema,Zp as SRT_WIN_DISPATCH_ARG1,oC as SandboxManager,zC as SandboxRuntimeConfigSchema,Pa as SandboxViolationStore,s0 as SrtWinConfigSchema,lb as VENDORED_SRT_WIN_EXE,a0 as WindowsConfigSchema,be as WindowsSandboxError,hi as buildGitConfigEnv,Wn as certThumbprint,bc as checkWindowsDependenciesAsync,nh as checkWindowsSandboxStatus,ih as checkWindowsSandboxStatusAsync,yc as ensurePersistentWindowsCa,Va as expandWindowsFsPaths,oa as generateCa,Cn as getDefaultWritePaths,cb as getSrtWinPath,mc as getWindowsSandboxCaCert,gc as getWindowsSandboxUserStatus,zi as getWindowsSandboxUserStatusAsync,sh as getWindowsWfpStatus,ah as getWindowsWfpStatusAsync,io as getWslVersion,Sc as grantWindowsAcl,db as installWindowsSandbox,fb as installWindowsSandboxAsync,pi as isUncPath,La as parseWindowsBinShell,hb as parseWindowsSandboxError,Bt as resolveSrtWin,Fa as restoreWindowsAcl,Ma as revokeWindowsAcl,xc as stampWindowsAcl,pb as uninstallWindowsSandbox,Pi as validateCaPair,hc as verifyWindowsWfpEgress,uc as windowsInstallInstructions,ch as windowsStateDir,ub as windowsTrustCa,oh as windowsTrustCaAsync};