ai-remote 0.4.7 → 0.4.9
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.
- package/README.md +84 -2
- package/SKILL.md +49 -1
- package/dist/apple-dh.d.ts +27 -0
- package/dist/apple-dh.js +1 -0
- package/dist/cli.mjs +2978 -210
- package/dist/index.d.ts +254 -12
- package/dist/protocols.d.ts +328 -12
- package/dist/protocols.js +13 -13
- package/package.json +6 -1
package/dist/protocols.js
CHANGED
|
@@ -1,22 +1,22 @@
|
|
|
1
|
-
function Tt(n){return new Uint8Array(n)}var p=class{bytes;view;offset=0;constructor(e=512){this.bytes=Tt(e),this.view=new DataView(this.bytes.buffer)}#e(e){if(this.offset+e<=this.bytes.length)return;let t=this.bytes.length*2;for(;t<this.offset+e;)t*=2;let s=Tt(t);s.set(this.bytes.subarray(0,this.offset)),this.bytes=s,this.view=new DataView(s.buffer)}u8(e){return this.#e(1),this.view.setUint8(this.offset,e),this.offset+=1,this}u16le(e){return this.#e(2),this.view.setUint16(this.offset,e,!0),this.offset+=2,this}u16be(e){return this.#e(2),this.view.setUint16(this.offset,e,!1),this.offset+=2,this}u32le(e){return this.#e(4),this.view.setUint32(this.offset,e>>>0,!0),this.offset+=4,this}u32be(e){return this.#e(4),this.view.setUint32(this.offset,e>>>0,!1),this.offset+=4,this}raw(e){return this.#e(e.length),this.bytes.set(e,this.offset),this.offset+=e.length,this}zeros(e){return this.#e(e),this.offset+=e,this}utf16le(e,t){let s=this.offset;for(let r of e){let i=r.codePointAt(0)??0;if(t!==void 0&&this.offset-s>=t-2)break;if(i>65535)for(let o=0;o<r.length;o++)this.u16le(r.charCodeAt(o));else this.u16le(i)}return t!==void 0&&this.zeros(t-(this.offset-s)),this}patchU16le(e,t){return this.view.setUint16(e,t,!0),this}patchU16be(e,t){return this.view.setUint16(e,t,!1),this}get length(){return this.offset}take(){return this.bytes.slice(0,this.offset)}},_=class{bytes;view;offset;constructor(e,t=0){this.bytes=e,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.offset=t}get remaining(){return this.bytes.length-this.offset}#e(e){if(this.remaining<e)throw new Error(`RDP: truncated frame (needed ${e} bytes, ${this.remaining} left)`)}u8(){return this.#e(1),this.view.getUint8(this.offset++)}u16le(){this.#e(2);let e=this.view.getUint16(this.offset,!0);return this.offset+=2,e}u16be(){this.#e(2);let e=this.view.getUint16(this.offset,!1);return this.offset+=2,e}u32le(){this.#e(4);let e=this.view.getUint32(this.offset,!0);return this.offset+=4,e}u32be(){this.#e(4);let e=this.view.getUint32(this.offset,!1);return this.offset+=4,e}raw(e){this.#e(e);let t=this.bytes.subarray(this.offset,this.offset+e);return this.offset+=e,t}skip(e){return this.#e(e),this.offset+=e,this}rest(){return this.bytes.subarray(this.offset)}};function b(...n){let e=n.reduce((r,i)=>r+i.length,0),t=Tt(e),s=0;for(let r of n)t.set(r,s),s+=r.length;return t}var fr=[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],pr=new Uint32Array(Array.from({length:64},(n,e)=>Math.floor(Math.abs(Math.sin(e+1))*4294967296)));function ze(n,e){return n<<e|n>>>32-e}function re(n){let e=n.length*8,t=Math.floor((n.length+8)/64)+1,s=new Uint8Array(t*64);s.set(n),s[n.length]=128;let r=new DataView(s.buffer,s.byteLength-8,8);r.setUint32(0,e>>>0,!0),r.setUint32(4,Math.floor(e/4294967296),!0);let i=1732584193,o=4023233417,a=2562383102,c=271733878,h=new Uint32Array(16),m=new DataView(s.buffer,s.byteOffset,s.byteLength);for(let w=0;w<t;w++){for(let T=0;T<16;T++)h[T]=m.getUint32(w*64+T*4,!0);let f=i,l=o,A=a,S=c;for(let T=0;T<64;T++){let u,d;T<16?(u=l&A|~l&S,d=T):T<32?(u=S&l|~S&A,d=(5*T+1)%16):T<48?(u=l^A^S,d=(3*T+5)%16):(u=A^(l|~S),d=7*T%16);let x=S;S=A,A=l;let R=f+u+pr[T]+h[d]|0;l=l+ze(R,fr[T])|0,f=x}i=i+f|0,o=o+l|0,a=a+A|0,c=c+S|0}let y=new Uint8Array(16),E=new DataView(y.buffer);return E.setUint32(0,i>>>0,!0),E.setUint32(4,o>>>0,!0),E.setUint32(8,a>>>0,!0),E.setUint32(12,c>>>0,!0),y}function _t(n){let e=n.length*8,t=Math.floor((n.length+8)/64)+1,s=new Uint8Array(t*64);s.set(n),s[n.length]=128;let r=new DataView(s.buffer,s.byteLength-8,8);r.setUint32(0,Math.floor(e/4294967296)),r.setUint32(4,e>>>0);let i=1732584193,o=4023233417,a=2562383102,c=271733878,h=3285377520,m=new Uint32Array(80),y=new DataView(s.buffer,s.byteOffset,s.byteLength);for(let f=0;f<t;f++){for(let d=0;d<16;d++)m[d]=y.getUint32(f*64+d*4);for(let d=16;d<80;d++)m[d]=ze(m[d-3]^m[d-8]^m[d-14]^m[d-16],1);let l=i,A=o,S=a,T=c,u=h;for(let d=0;d<80;d++){let x,R;d<20?(x=A&S|~A&T,R=1518500249):d<40?(x=A^S^T,R=1859775393):d<60?(x=A&S|A&T|S&T,R=2400959708):(x=A^S^T,R=3395469782);let C=ze(l,5)+x+u+R+m[d]|0;u=T,T=S,S=ze(A,30),A=l,l=C}i=i+l|0,o=o+A|0,a=a+S|0,c=c+T|0,h=h+u|0}let E=new Uint8Array(20),w=new DataView(E.buffer);return[i,o,a,c,h].forEach((f,l)=>w.setUint32(l*4,f>>>0)),E}function Z(n){let e=new Uint8Array(256);for(let s=0;s<256;s++)e[s]=s;let t=0;for(let s=0;s<256;s++){t=t+(e[s]??0)+(n[s%n.length]??0)&255;let r=e[s]??0;e[s]=e[t]??0,e[t]=r}return{s:e,i:0,j:0}}function X(n,e){let t=new Uint8Array(e.length),{s}=n,{i:r,j:i}=n;for(let o=0;o<e.length;o++){r=r+1&255,i=i+s[r]&255;let a=s[r];s[r]=s[i],s[i]=a,t[o]=e[o]^s[s[r]+s[i]&255]}return n.i=r,n.j=i,t}function bt(n){let e=0n;for(let t=n.length-1;t>=0;t--)e=e<<8n|BigInt(n[t]);return e}function mr(n,e){let t=new Uint8Array(e),s=n;for(let r=0;r<e;r++)t[r]=Number(s&0xffn),s>>=8n;return t}function yn(n,e,t){let s=1n,r=n%t,i=e;for(;i>0n;)i&1n&&(s=s*r%t),r=r*r%t,i>>=1n;return s}function wn(n,e,t){let s=bt(e),r=bt(t),i=bt(n);if(i>=s)throw new Error("RDP: client random is larger than the server RSA modulus");return mr(yn(i,r,s),e.length)}function gn(n,e,t){let s=w=>{let f=0n;for(let l of w)f=f<<8n|BigInt(l);return f},r=s(e),i=s(t),o=e.length;if(n.length>o-11)throw new Error("TLS: RSA message is too long for this key");let a=new Uint8Array(o);a[0]=0,a[1]=2;let c=o-n.length-3,h=new Uint8Array(c);crypto.getRandomValues(h);for(let w=0;w<c;w++){for(;h[w]===0;)h[w]=Math.max(1,crypto.getRandomValues(new Uint8Array(1))[0]);a[2+w]=h[w]}a[2+c]=0,a.set(n,3+c);let m=yn(s(a),i,r),y=new Uint8Array(o),E=m;for(let w=o-1;w>=0;w--)y[w]=Number(E&0xffn),E>>=8n;return y}var An=new Uint8Array(40).fill(54),Sn=new Uint8Array(48).fill(92),se={NONE:0,BIT_40:1,BIT_128:2,BIT_56:8,FIPS:16};function j(...n){let e=n.reduce((r,i)=>r+i.length,0),t=new Uint8Array(e),s=0;for(let r of n)t.set(r,s),s+=r.length;return t}function ye(n,e,t,s){return re(j(n,_t(j(e,n,t,s))))}function En(n,e,t){return re(j(n,e,t))}var Er=new Uint8Array([65]),yr=new Uint8Array([66,66]),wr=new Uint8Array([67,67,67]),gr=new Uint8Array([88]),Ar=new Uint8Array([89,89]),Sr=new Uint8Array([90,90,90]);function xn(n,e,t){if(e!==8)return n.slice(0,e);let s=n.slice(0,8);return s[0]=209,t&&(s[1]=38,s[2]=158),s}function xr(n){return n===se.BIT_40||n===se.BIT_56?8:16}function Tn(n,e,t){let s=j(n.subarray(0,24),e.subarray(0,24)),r=j(ye(s,Er,n,e),ye(s,yr,n,e),ye(s,wr,n,e)),i=j(ye(r,gr,n,e),ye(r,Ar,n,e),ye(r,Sr,n,e)),o=xr(t),a=t===se.BIT_40,c=E=>xn(E,o,a),h=c(i.subarray(0,16)),m=c(En(i.subarray(16,32),n,e)),y=c(En(i.subarray(32,48),n,e));return{macKey:h,keyLength:o,is40Bit:a,initialDecryptKey:m.slice(),initialEncryptKey:y.slice(),decryptKey:m,encryptKey:y}}function bn(n,e){let t=new Uint8Array(4);new DataView(t.buffer).setUint32(0,e.length,!0);let s=_t(j(n,An,t,e));return re(j(n,Sn,s)).subarray(0,8)}function Ct(n,e,t,s){let r=_t(j(n,An,e)),i=re(j(n,Sn,r)).slice(0,t),o=X(Z(i),i);return xn(o,t,s)}var Rt=3,_n=4,Tr=224,br=208,_r=240,Cr=1,Rr=2,vr=3,Cn={SSL_REQUIRED:1,SSL_NOT_ALLOWED:2,SSL_CERT_NOT_ON_SERVER:3,INCONSISTENT_FLAGS:4,HYBRID_REQUIRED:5,SSL_WITH_USER_AUTH_REQUIRED:6},D={RDP:0,SSL:1,HYBRID:2,RDSTLS:4,HYBRID_EX:8},Nr={1:"The host requires TLS. Choose the TLS security option for this target.",2:'The host does not allow TLS. Choose the "RDP (standard)" security option.',3:"The host has no certificate installed, so it cannot negotiate TLS.",4:"The host rejected the requested protocol flags as inconsistent.",5:'The host requires Network Level Authentication (NLA/CredSSP). Turn NLA off on the host, or set its security layer to "RDP".',6:"The host requires TLS with early user authentication, which this gateway does not support."};function Rn(n){let e=new p(32);return e.u8(Rt).u8(0).u16be(19),e.u8(14).u8(Tr).u16be(0).u16be(0).u8(0),e.u8(Cr).u8(0).u16le(8).u32le(n),e.take()}function vn(n){let e=new _(n);e.skip(_n),e.u8();let t=e.u8();if(t!==br)throw new Error(`RDP: expected an X.224 connection confirm, got TPDU code 0x${t.toString(16)}`);if(e.skip(5),e.remaining<8)return{selectedProtocol:D.RDP,negotiated:!1};let s=e.u8();if(e.u8(),e.u16le(),s===vr){let r=e.u32le(),i=new Error(Nr[r]||`The host refused the RDP connection (negotiation failure 0x${r.toString(16)}).`);throw i.negotiationFailure=r,i}return s!==Rr?{selectedProtocol:D.RDP,negotiated:!1}:{selectedProtocol:e.u32le(),negotiated:!0}}function we(n){let e=new p(n.length+7);return e.u8(Rt).u8(0).u16be(n.length+7),e.u8(2).u8(_r).u8(128),e.raw(n),e.take()}function Le(n){if(n.length<7)throw new Error("RDP: X.224 data frame is too short");return n.subarray(7)}function Nn(n){let e=[],t=0;for(;n.length-t>=4;){let s,r=!1;if(n[t]===Rt){if(s=n[t+2]<<8|n[t+3],s<_n)throw new Error("RDP: malformed TPKT length")}else if(r=!0,s=n[t+1]&128?(n[t+1]&127)<<8|n[t+2]:n[t+1],s<2)throw new Error("RDP: malformed fast-path length");if(n.length-t<s)break;e.push({fastPath:r,frame:n.subarray(t,t+s)}),t+=s}return{frames:e,rest:n.subarray(t)}}var Lr=1,Ir=2,Ur=826364754,Or=6,In=[42,134,72,134,247,13,1,1,1];function de(n,e){let t=e,s=n[t++],r=n[t++];if(r&128){let i=r&127;r=0;for(let o=0;o<i;o++)r=r<<8|n[t++]}return{tag:s,contentStart:t,contentEnd:t+r,next:t+r,content:n.subarray(t,t+r)}}function ge(n){let e=[],t=0;for(;t<n.length;){let s=de(n,t);if(e.push(s),s.next<=t)break;t=s.next}return e}function Un(n,e){e:for(let t=0;t+e.length<=n.length;t++){for(let s=0;s<e.length;s++)if(n[t+s]!==e[s])continue e;return!0}return!1}function Ln(n){let e=0;for(;e<n.length-1&&n[e]===0;)e++;return n.subarray(e).slice().reverse()}function kr(n){let e=de(n,0),t=de(n,e.contentStart);for(let s of ge(t.content)){if(s.tag!==48)continue;let r=ge(s.content);if(r.length<2||r[0].tag!==48||!Un(r[0].content,In)||r[1].tag!==3)continue;let i=de(r[1].content.subarray(1),0),[o,a]=ge(i.content);if(!o||!a)break;return{modulus:Ln(o.content),exponent:Ln(a.content),source:"x509"}}throw new Error("RDP: no RSA public key found in the host X.509 certificate")}function Dr(n){n.u32le(),n.u32le();let e=n.u16le(),t=n.u16le();if(e!==Or)throw new Error(`RDP: unsupported public key blob type 0x${e.toString(16)}`);let s=new _(n.raw(t));if(s.u32le()!==Ur)throw new Error("RDP: the host RSA public key blob is not in RSA1 format");let r=s.u32le();s.u32le(),s.u32le();let i=s.raw(4).slice();if(r<9)throw new Error("RDP: the host RSA modulus is too short");return{modulus:s.raw(r-8).slice(),exponent:i,source:"proprietary"}}function On(n){let e=de(n,0),t=de(n,e.contentStart);for(let s of ge(t.content)){if(s.tag!==48)continue;let r=ge(s.content);if(r.length<2||r[0].tag!==48||!Un(r[0].content,In)||r[1].tag!==3)continue;let i=r[1].content.subarray(1),o=de(i,0),[a,c]=ge(o.content);if(!a||!c)break;let h=m=>{let y=0;for(;y<m.length-1&&m[y]===0;)y++;return m.subarray(y)};return{modulus:h(a.content),exponent:h(c.content),subjectPublicKey:i}}throw new Error("TLS: no RSA public key found in the host certificate")}function kn(n){let e=new _(n),t=e.u32le()&2147483647;if(t===Lr)return Dr(e);if(t===Ir){let s=e.u32le(),r=null;for(let i=0;i<s;i++){let o=e.u32le();r=e.raw(o)}if(!r)throw new Error("RDP: the host sent an empty X.509 certificate chain");return kr(r)}throw new Error(`RDP: unsupported server certificate version ${t}`)}var Ie=771,ae={CHANGE_CIPHER_SPEC:20,ALERT:21,HANDSHAKE:22,APPLICATION_DATA:23},Y={CLIENT_HELLO:1,SERVER_HELLO:2,NEW_SESSION_TICKET:4,CERTIFICATE:11,SERVER_KEY_EXCHANGE:12,CERTIFICATE_REQUEST:13,SERVER_HELLO_DONE:14,CLIENT_KEY_EXCHANGE:16,FINISHED:20},Pr={156:{name:"TLS_RSA_WITH_AES_128_GCM_SHA256",keyLength:16,hash:"SHA-256"},157:{name:"TLS_RSA_WITH_AES_256_GCM_SHA384",keyLength:32,hash:"SHA-384"}},Mr={0:"close_notify",10:"unexpected_message",20:"bad_record_mac",40:"handshake_failure",42:"bad_certificate",46:"certificate_unknown",47:"illegal_parameter",48:"unknown_ca",50:"decode_error",51:"decrypt_error",70:"protocol_version",71:"insufficient_security",80:"internal_error",90:"user_canceled",109:"missing_extension",112:"unrecognized_name"},Hr=n=>new TextEncoder().encode(n);function K(n){return new Uint8Array([n>>8&255,n&255])}function Dn(n){return new Uint8Array([n>>16&255,n>>8&255,n&255])}function vt(n){let e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,BigInt(n)),e}async function Kr(n,e,t,s){let r=await crypto.subtle.importKey("raw",e,{name:"HMAC",hash:n},!1,["sign"]),i=async h=>new Uint8Array(await crypto.subtle.sign("HMAC",r,h)),o=[],a=0,c=await i(t);for(;a<s;){let h=await i(b(c,t));o.push(h),a+=h.length,c=await i(c)}return b(...o).subarray(0,s)}var Nt=(n,e,t,s,r)=>Kr(n,e,b(Hr(t),s),r),Qe=class{constructor({send:e,onData:t,onError:s}){this.sendRaw=e,this.onData=t,this.onError=s,this.inbound=new Uint8Array(0),this.transcript=[],this.established=!1,this.serverPublicKey=null,this.suite=null,this.certificates=[],this.readSequence=0n,this.writeSequence=0n,this.readEncrypted=!1,this.writeEncrypted=!1,this.queue=Promise.resolve(),this.handshakeDone=new Promise((r,i)=>{this.resolveHandshake=r,this.rejectHandshake=i})}async start(){this.clientRandom=new Uint8Array(32),crypto.getRandomValues(this.clientRandom);let e=b(K(13),K(10),K(8),new Uint8Array([4,1,5,1,2,1,6,1]),K(65281),K(1),new Uint8Array([0])),t=b(K(Ie),this.clientRandom,new Uint8Array([0]),K(4),K(156),K(157),new Uint8Array([1,0]),K(e.length),e);return await this.#t(Y.CLIENT_HELLO,t),this.handshakeDone}#e(e,t){return b(new Uint8Array([e]),K(Ie),K(t.length),t)}async#t(e,t){let s=b(new Uint8Array([e]),Dn(t.length),t);this.transcript.push(s),await this.#r(ae.HANDSHAKE,s)}async#r(e,t){if(!this.writeEncrypted){this.sendRaw(this.#e(e,t));return}this.sendRaw(this.#e(e,await this.#n(e,t)))}async#n(e,t){let s=this.writeSequence++,r=vt(s),i=b(this.keys.clientIv,r),o=b(vt(s),new Uint8Array([e]),K(Ie),K(t.length)),a=await crypto.subtle.encrypt({name:"AES-GCM",iv:i,additionalData:o,tagLength:128},this.keys.clientKey,t);return b(r,new Uint8Array(a))}async#s(e,t){let s=this.readSequence++,r=t.subarray(0,8),i=t.subarray(8),o=b(this.keys.serverIv,r),a=b(vt(s),new Uint8Array([e]),K(Ie),K(i.length-16)),c=await crypto.subtle.decrypt({name:"AES-GCM",iv:o,additionalData:a,tagLength:128},this.keys.serverKey,i);return new Uint8Array(c)}async#c(e){let{hash:t,keyLength:s}=this.suite;this.masterSecret=await Nt(t,e,"master secret",b(this.clientRandom,this.serverRandom),48);let r=await Nt(t,this.masterSecret,"key expansion",b(this.serverRandom,this.clientRandom),s*2+8),i=new _(r),o=i.raw(s),a=i.raw(s);this.keys={clientKey:await crypto.subtle.importKey("raw",o,"AES-GCM",!1,["encrypt"]),serverKey:await crypto.subtle.importKey("raw",a,"AES-GCM",!1,["decrypt"]),clientIv:i.raw(4).slice(),serverIv:i.raw(4).slice()}}async#i(){let e=await crypto.subtle.digest(this.suite.hash,b(...this.transcript));return new Uint8Array(e)}async#a(e){return Nt(this.suite.hash,this.masterSecret,e,await this.#i(),12)}receive(e){return this.queue=this.queue.then(()=>this.#h(e)).catch(t=>this.#o(t)),this.queue}#o(e){let t=e instanceof Error?e:new Error(String(e));this.rejectHandshake(t),this.onError&&this.onError(t)}async#h(e){for(this.inbound=this.inbound.length===0?e:b(this.inbound,e);this.inbound.length>=5;){let t=this.inbound[0],s=this.inbound[3]<<8|this.inbound[4];if(this.inbound.length<5+s)return;let r=this.inbound.subarray(5,5+s);this.inbound=this.inbound.subarray(5+s).slice();let i=this.readEncrypted&&t!==ae.CHANGE_CIPHER_SPEC?await this.#s(t,r):r;await this.#l(t,i)}}async#l(e,t){if(e===ae.ALERT){let r=t[0],i=t[1],o=Mr[i]||`alert ${i}`;if(o==="close_notify"){this.established=!1;return}throw new Error(`TLS: the host sent a fatal alert: ${o}${r===1?" (warning)":""}`)}if(e===ae.CHANGE_CIPHER_SPEC){this.readEncrypted=!0,this.readSequence=0n;return}if(e===ae.APPLICATION_DATA){this.onData&&t.length>0&&this.onData(t);return}if(e!==ae.HANDSHAKE)return;let s=0;for(;s+4<=t.length;){let r=t[s],i=t[s+1]<<16|t[s+2]<<8|t[s+3],o=t.subarray(s,s+4+i),a=t.subarray(s+4,s+4+i);s+=4+i,r!==Y.FINISHED&&this.transcript.push(o),await this.#p(r,a,o)}}async#p(e,t,s){switch(e){case Y.SERVER_HELLO:{let r=new _(t),i=r.u16be();if(i!==Ie)throw new Error(`TLS: the host chose an unsupported version 0x${i.toString(16)}`);this.serverRandom=r.raw(32).slice(),r.raw(r.u8());let o=r.u16be();if(this.suite=Pr[o],!this.suite)throw new Error(`TLS: the host chose cipher suite 0x${o.toString(16)}, which this client does not implement`);r.u8();return}case Y.CERTIFICATE:{let r=new _(t),i=r.u8()<<16|r.u16be(),o=r.offset+i;for(;r.offset<o;){let a=r.u8()<<16|r.u16be();this.certificates.push(r.raw(a).slice())}if(this.certificates.length===0)throw new Error("TLS: the host sent no certificate");this.serverPublicKey=On(this.certificates[0]);return}case Y.CERTIFICATE_REQUEST:this.certificateRequested=!0;return;case Y.SERVER_KEY_EXCHANGE:throw new Error("TLS: the host chose an ephemeral key exchange, which this client does not implement");case Y.SERVER_HELLO_DONE:await this.#E();return;case Y.NEW_SESSION_TICKET:return;case Y.FINISHED:{let r=await this.#a("server finished"),i=t.subarray(0,12);if(!(r.length===i.length&&r.every((a,c)=>a===i[c])))throw new Error("TLS: the host Finished message did not verify");this.transcript.push(s),this.established=!0,this.resolveHandshake({cipherSuite:this.suite.name,certificates:this.certificates,publicKey:this.serverPublicKey});return}default:return}}async#E(){this.certificateRequested&&await this.#t(Y.CERTIFICATE,Dn(0));let e=new Uint8Array(48);crypto.getRandomValues(e),e[0]=3,e[1]=3;let t=gn(e,this.serverPublicKey.modulus,this.serverPublicKey.exponent);await this.#t(Y.CLIENT_KEY_EXCHANGE,b(K(t.length),t)),await this.#c(e),await this.#r(ae.CHANGE_CIPHER_SPEC,new Uint8Array([1])),this.writeEncrypted=!0,this.writeSequence=0n,await this.#t(Y.FINISHED,await this.#a("client finished"))}write(e){return this.queue=this.queue.then(async()=>{if(!this.established)throw new Error("TLS: write before the handshake finished");await this.#r(ae.APPLICATION_DATA,e)}).catch(t=>this.#o(t)),this.queue}};function Fr(n,e){return n<<e|n>>>32-e}function Br(n){let e=Math.floor((n.length+8)/64)+1,t=new Uint8Array(e*64);t.set(n),t[n.length]=128;let s=new DataView(t.buffer),r=n.length*8;s.setUint32(t.length-8,r>>>0,!0),s.setUint32(t.length-4,Math.floor(r/4294967296),!0);let i=1732584193,o=4023233417,a=2562383102,c=271733878,h=new Uint32Array(16),m=[3,7,11,19],y=[0,4,8,12,1,5,9,13,2,6,10,14,3,7,11,15],E=[3,5,9,13],w=[0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15],f=[3,9,11,15];for(let S=0;S<e;S++){for(let C=0;C<16;C++)h[C]=s.getUint32(S*64+C*4,!0);let T=i,u=o,d=a,x=c,R=(C,L)=>Fr(C|0,L);for(let C=0;C<16;C++){let L=u&d|~u&x,v=m[C%4],U=R(T+L+h[C]|0,v);T=x,x=d,d=u,u=U}for(let C=0;C<16;C++){let L=u&d|u&x|d&x,v=E[C%4],U=R(T+L+h[y[C]]+1518500249|0,v);T=x,x=d,d=u,u=U}for(let C=0;C<16;C++){let L=u^d^x,v=f[C%4],U=R(T+L+h[w[C]]+1859775393|0,v);T=x,x=d,d=u,u=U}i=i+T|0,o=o+u|0,a=a+d|0,c=c+x|0}let l=new Uint8Array(16),A=new DataView(l.buffer);return A.setUint32(0,i>>>0,!0),A.setUint32(4,o>>>0,!0),A.setUint32(8,a>>>0,!0),A.setUint32(12,c>>>0,!0),l}function Ae(n,e){let s=n.length>64?re(n):n,r=new Uint8Array(64);r.set(s);let i=new Uint8Array(64),o=new Uint8Array(64);for(let a=0;a<64;a++)i[a]=r[a]^54,o[a]=r[a]^92;return re(b(o,re(b(i,e))))}var Hn=new Uint8Array([78,84,76,77,83,83,80,0]),$={UNICODE:1,REQUEST_TARGET:4,SIGN:16,SEAL:32,NTLM:512,ALWAYS_SIGN:32768,EXTENDED_SESSION_SECURITY:524288,TARGET_INFO:8388608,VERSION:33554432,KEY_128:536870912,KEY_EXCH:1073741824,KEY_56:2147483648},Kn=$.UNICODE|$.REQUEST_TARGET|$.SIGN|$.SEAL|$.NTLM|$.ALWAYS_SIGN|$.EXTENDED_SESSION_SECURITY|$.TARGET_INFO|$.VERSION|$.KEY_128|$.KEY_EXCH|$.KEY_56,Fn=0,Gr=7,Pn=6,Mn=2,It=n=>{let e=new p(n.length*2+2);return e.utf16le(n),e.take()},Bn=new Uint8Array([10,0,99,69,0,0,0,15]);function Gn(){let n=new p(40);return n.raw(Hn),n.u32le(1),n.u32le(Kn>>>0),n.u16le(0).u16le(0).u32le(0),n.u16le(0).u16le(0).u32le(0),n.raw(Bn),n.take()}function Wn(n){let e=new DataView(n.buffer,n.byteOffset,n.byteLength);if(e.getUint32(8,!0)!==2)throw new Error("NTLM: the host did not answer with a challenge message");let t=e.getUint16(12,!0),s=e.getUint32(16,!0),r=e.getUint32(20,!0),i=n.subarray(24,32).slice(),o=e.getUint16(40,!0),a=e.getUint32(44,!0);return{flags:r,serverChallenge:i,targetName:n.subarray(s,s+t).slice(),targetInfo:n.subarray(a,a+o).slice()}}function Wr(n){let e=[],t=0,s=new DataView(n.buffer,n.byteOffset,n.byteLength);for(;t+4<=n.length;){let r=s.getUint16(t,!0),i=s.getUint16(t+2,!0),o=n.subarray(t+4,t+4+i);if(t+=4+i,r===Fn)break;e.push({id:r,value:o})}return e}function Vr(n){let e=new p(256);for(let t of n)e.u16le(t.id),e.u16le(t.value.length),e.raw(t.value);return e.u16le(Fn).u16le(0),e.take()}function Yr(){let n=(BigInt(Date.now())+11644473600000n)*10000n,e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,n,!0),e}function Vn({username:n,domain:e,password:t,challenge:s,negotiateBytes:r,challengeBytes:i}){let o=Ae(Br(It(t)),It(n.toUpperCase()+e)),a=Wr(s.targetInfo),c=a.find(P=>P.id===Gr)?.value.slice()||Yr(),h=a.find(P=>P.id===Pn);if(h){let P=new DataView(h.value.buffer,h.value.byteOffset,4);P.setUint32(0,P.getUint32(0,!0)|Mn,!0)}else{let P=new Uint8Array(4);new DataView(P.buffer).setUint32(0,Mn,!0),a.push({id:Pn,value:P})}let m=Vr(a),y=new Uint8Array(8);crypto.getRandomValues(y);let E=b(new Uint8Array([1,1,0,0,0,0,0,0]),c,y,new Uint8Array(4),m,new Uint8Array(4)),w=Ae(o,b(s.serverChallenge,E)),f=b(w,E),l=Ae(o,w),A=new Uint8Array(16);crypto.getRandomValues(A);let S=X(Z(l),A),T=Lt(e),u=Lt(n),d=Lt(""),x=new Uint8Array(24),R=72,C=R,L=[],v=P=>(L.push({bytes:P,offset:C}),C+=P.length,L[L.length-1]),U=v(x),Q=v(f),me=v(T),le=v(u),Ne=v(d),ue=v(S),V=new p(C+16);V.raw(Hn),V.u32le(3);let Ee=P=>{V.u16le(P.bytes.length),V.u16le(P.bytes.length),V.u32le(P.offset+16)};Ee(U),Ee(Q),Ee(me),Ee(le),Ee(Ne),Ee(ue),V.u32le(Kn>>>0),V.raw(Bn),V.zeros(16);for(let P of L)V.raw(P.bytes);let xt=V.take(),dr=Ae(A,b(r,i,xt));return xt.set(dr,R),{message:xt,exportedSessionKey:A,keys:Qr(A)}}function Lt(n){return n?It(n).subarray(0,n.length*2).slice():new Uint8Array(0)}var $r="session key to client-to-server signing key magic constant\0",qr="session key to server-to-client signing key magic constant\0",Xr="session key to client-to-server sealing key magic constant\0",zr="session key to server-to-client sealing key magic constant\0";function Qr(n){let e=t=>re(b(n,new TextEncoder().encode(t)));return{clientSigningKey:e($r),serverSigningKey:e(qr),clientSealing:Z(e(Xr)),serverSealing:Z(e(zr))}}var je=class{keys;sendSequence;receiveSequence;constructor(e){this.keys=e,this.sendSequence=0,this.receiveSequence=0}seal(e){let t=new Uint8Array(4);new DataView(t.buffer).setUint32(0,this.sendSequence,!0);let s=Ae(this.keys.clientSigningKey,b(t,e)),r=X(this.keys.clientSealing,e),i=X(this.keys.clientSealing,s.subarray(0,8));return this.sendSequence+=1,b(new Uint8Array([1,0,0,0]),i,t,r)}unseal(e){if(e.length<16)throw new Error("NTLM: sealed message is too short");let t=e.subarray(16),s=X(this.keys.serverSealing,t),r=e.subarray(12,16),i=Ae(this.keys.serverSigningKey,b(r,s)),o=X(this.keys.serverSealing,i.subarray(0,8)),a=e.subarray(4,12);if(!o.every((c,h)=>c===a[h]))throw new Error("NTLM: the host signature did not verify");return this.receiveSequence+=1,s}};var Ut=6,jr="CredSSP Client-To-Server Binding Hash\0",Zr="CredSSP Server-To-Client Binding Hash\0",Jr={3221225581:"The host rejected the username or password (STATUS_LOGON_FAILURE).",3221225582:"The account is not allowed to sign in right now (STATUS_ACCOUNT_RESTRICTION).",3221225583:"The account is outside its permitted logon hours.",3221225584:"The account is not allowed to sign in from this machine (STATUS_INVALID_WORKSTATION).",3221225585:"The account password has expired.",3221225586:"The account is disabled.",3221225819:"The account is not allowed the Remote Desktop logon type -- add it to the Remote Desktop Users group.",3221225875:"The account has expired.",3221226020:"The account must change its password before signing in.",3221226036:"The account is locked out.",2148074252:"The host denied the logon (SEC_E_LOGON_DENIED).",2148074248:"The host rejected the authentication token (SEC_E_INVALID_TOKEN).",2148074242:"The host rejected the CredSSP exchange (SEC_E_UNSUPPORTED_FUNCTION) -- usually a public-key binding mismatch."};function ei(n){return n<128?new Uint8Array([n]):n<=255?new Uint8Array([129,n]):n<=65535?new Uint8Array([130,n>>8,n&255]):new Uint8Array([131,n>>16&255,n>>8&255,n&255])}var Je=(n,e)=>b(new Uint8Array([n]),ei(e.length),e),Ue=(...n)=>Je(48,b(...n)),ce=n=>Je(4,n),z=(n,e)=>Je(160|n,e);function Yn(n){let e=[],t=n;do e.unshift(t&255),t>>>=8;while(t>0);return e[0]&128&&e.unshift(0),Je(2,new Uint8Array(e))}function J(n,e){let t=n[e],s=e+1,r=n[s++];if(r&128){let i=r&127;r=0;for(let o=0;o<i;o++)r=r<<8|n[s++]}return{tag:t,content:n.subarray(s,s+r),end:s+r}}function ti(n,e=0){if(n.length-e<2)return 0;let t=e+1,s=n[t++];if(s&128){let i=s&127;if(n.length-t<i)return 0;s=0;for(let o=0;o<i;o++)s=s<<8|n[t++]}let r=t-e+s;return n.length-e<r?0:r}function Ot({version:n,negoToken:e,authInfo:t,pubKeyAuth:s,clientNonce:r}){let i=[z(0,Yn(n))];return e&&i.push(z(1,Ue(Ue(z(0,ce(e)))))),t&&i.push(z(2,ce(t))),s&&i.push(z(3,ce(s))),r&&i.push(z(5,ce(r))),Ue(...i)}function ni(n){let e=J(n,0),t={version:0,negoToken:null,authInfo:null,pubKeyAuth:null,errorCode:0},s=0;for(;s<e.content.length;){let r=J(e.content,s);s=r.end;let i=r.tag&31;if(i===0){t.version=J(r.content,0).content[0];continue}if(i===1){let o=J(r.content,0),a=J(o.content,0),c=J(a.content,0);t.negoToken=J(c.content,0).content;continue}if(i===2){t.authInfo=J(r.content,0).content;continue}if(i===3){t.pubKeyAuth=J(r.content,0).content;continue}if(i===4){let o=J(r.content,0).content,a=0;for(let c of o)a=(a<<8|c)>>>0;t.errorCode=a;continue}}return t}function si(n,e,t){let s=i=>{let o=new Uint8Array(i.length*2),a=new DataView(o.buffer);for(let c=0;c<i.length;c++)a.setUint16(c*2,i.charCodeAt(c),!0);return o},r=Ue(z(0,ce(s(n))),z(1,ce(s(e))),z(2,ce(s(t))));return Ue(z(0,Yn(1)),z(1,ce(r)))}var Ze=class{username;domain;password;serverPublicKey;send;log;inbound;waiters;constructor({username:e,domain:t,password:s,serverPublicKey:r,send:i,log:o}){this.username=e||"",this.domain=t||"",this.password=s||"",this.serverPublicKey=r,this.send=i,this.log=o||(()=>{}),this.inbound=new Uint8Array(0),this.waiters=[]}receive(e){for(this.inbound=this.inbound.length===0?e:b(this.inbound,e);;){let t=ti(this.inbound);if(t===0)return;let s=ni(this.inbound.subarray(0,t));this.inbound=this.inbound.subarray(t).slice();let r=this.waiters.shift();r&&r.resolve(s)}}#e(e=15e3){return new Promise((t,s)=>{let r=setTimeout(()=>s(new Error("CredSSP: the host did not answer within 15s")),e);this.waiters.push({resolve:i=>{clearTimeout(r),t(i)}})})}async#t(e,t){let s=await crypto.subtle.digest("SHA-256",b(new TextEncoder().encode(e),t,this.serverPublicKey));return new Uint8Array(s)}async authenticate(){let e=Gn();this.send(Ot({version:Ut,negoToken:e})),this.log("CredSSP","sent NTLM NEGOTIATE");let t=await this.#e();if(t.errorCode)throw new Error(this.#n(t.errorCode));if(!t.negoToken)throw new Error("CredSSP: the host sent no NTLM challenge");let s=t.negoToken.slice(),r=Wn(s),i=new TextDecoder("utf-16le").decode(r.targetName);if(this.log("CredSSP",`received NTLM CHALLENGE from "${i}" (host CredSSP version ${t.version})`),!this.username)return{authenticated:!1,reachedChallenge:!0,hostVersion:t.version,targetName:i,note:"no credentials supplied, stopping after the challenge"};let{message:o,keys:a}=Vn({username:this.username,domain:this.domain,password:this.password,challenge:r,negotiateBytes:e,challengeBytes:s}),c=new je(a),h=new Uint8Array(32);crypto.getRandomValues(h);let m=t.version<5,y=m?this.serverPublicKey:await this.#t(jr,h);this.send(Ot({version:Ut,negoToken:o,pubKeyAuth:c.seal(y),clientNonce:m?null:h})),this.log("CredSSP",`sent NTLM AUTHENTICATE with the ${m?"legacy":"hashed"} public-key binding`);let E=await this.#e();if(E.errorCode)throw new Error(this.#n(E.errorCode));if(!E.pubKeyAuth)throw new Error("CredSSP: the host returned no public-key confirmation");let w=c.unseal(E.pubKeyAuth),f=m?this.#r():await this.#t(Zr,h);if(w.length!==f.length||!f.every((l,A)=>l===w[A]))throw new Error("CredSSP: the host public-key confirmation did not match. The TLS session is not the one the host authenticated, which is what this check exists to catch.");return this.log("CredSSP","host confirmed the public-key binding"),this.send(Ot({version:Ut,authInfo:c.seal(si(this.domain,this.username,this.password))})),this.log("CredSSP","sent credentials"),{authenticated:!0,hostVersion:t.version,targetName:i}}#r(){let e=this.serverPublicKey.slice();return e[0]=e[0]+1&255,e}#n(e){return Jr[e]||`CredSSP: the host reported error 0x${e.toString(16).padStart(8,"0")}.`}};var Se=1001;var he={ERECT_DOMAIN_REQUEST:1,DISCONNECT_PROVIDER_ULTIMATUM:8,ATTACH_USER_REQUEST:10,ATTACH_USER_CONFIRM:11,CHANNEL_JOIN_REQUEST:14,CHANNEL_JOIN_CONFIRM:15,SEND_DATA_REQUEST:25,SEND_DATA_INDICATION:26},ri={0:"The host closed the RDP session (domain disconnected).",1:"The host closed the RDP session (provider initiated).",2:"The host closed the RDP session (token purged).",3:"The host closed the RDP session (user requested).",4:"The host closed the RDP session (channel purged)."};function ii(n){return n>255?new Uint8Array([130,n>>8&255,n&255]):n>127?new Uint8Array([129,n]):new Uint8Array([n])}function ke(n,e){return b(new Uint8Array(n),ii(e.length),e)}function oi(n){let e;return n<128?e=new Uint8Array([n]):n<32768?e=new Uint8Array([n>>8,n&255]):n<8388608?e=new Uint8Array([n>>16,n>>8&255,n&255]):e=new Uint8Array([n>>>24,n>>16&255,n>>8&255,n&255]),ke([2],e)}var kt=n=>ke([4],n),ai=n=>ke([1],new Uint8Array([n?255:0]));function Dt(n){return ke([48],b(...n.map(oi)))}function Pt(n,e){return e>127?n.u16be(32768|e):n.u8(e),n}function $n(n){let e=n.u8();return e&128?(e&127)<<8|n.u8():e}var ci=new Uint8Array([5,0,20,124,0,1]),hi=new Uint8Array([68,117,99,97]),et=new Uint8Array([77,99,68,110]);function li(n){let e=new p(n.length+32);return e.u8(0),e.raw(ci),Pt(e,n.length+14),e.u8(0),e.u8(8),e.u8(0),e.u8(16),e.u8(0),e.u8(1),e.u8(192),e.u8(0),e.raw(hi),Pt(e,n.length),e.raw(n),e.take()}function ui(n){for(let e=0;e+4<=n.length;e++)if(n[e]===et[0]&&n[e+1]===et[1]&&n[e+2]===et[2]&&n[e+3]===et[3]){let t=new _(n,e+4),s=$n(t),r=t.rest();return r.subarray(0,Math.min(s,r.length))}throw new Error("RDP: the host response contained no GCC server data")}var di=[34,2,0,1,0,1,65535,2],fi=[1,1,1,1,0,1,1056,2],pi=[65535,64535,65535,1,0,1,65535,2];function qn(n){let e=li(n),t=b(kt(new Uint8Array([1])),kt(new Uint8Array([1])),ai(!0),Dt(di),Dt(fi),Dt(pi),kt(e));return we(ke([127,101],t))}function Oe(n){let e=n.u8();(e&31)===31&&(e=e<<8|n.u8());let t=n.u8();if(t&128){let s=t&127;t=0;for(let r=0;r<s;r++)t=t<<8|n.u8()}return{tag:e,value:n.raw(t)}}function Xn(n){let e=new _(Le(n)),t=Oe(e);if(t.tag!==32614)throw new Error(`RDP: expected an MCS connect response, got BER tag 0x${t.tag.toString(16)}`);let s=new _(t.value),r=Oe(s);Oe(s),Oe(s);let i=Oe(s);if(r.value[0]!==0)throw new Error(`RDP: the host rejected the MCS connection (result ${r.value[0]})`);return ui(i.value)}var tt=n=>n<<2;function zn(){let n=new p(8);return n.u8(tt(he.ERECT_DOMAIN_REQUEST)),n.u8(1).u8(0),n.u8(1).u8(0),we(n.take())}function Qn(){return we(new Uint8Array([tt(he.ATTACH_USER_REQUEST)]))}function jn(n){let e=new _(Le(n)),t=e.u8();if(t>>2!==he.ATTACH_USER_CONFIRM)throw new Error(`RDP: expected an MCS attach-user confirm, got PDU ${t>>2}`);let s=e.u8();if(s!==0)throw new Error(`RDP: the host refused to attach a user (result ${s})`);return{userId:t&2?e.u16be()+Se:Se}}function Mt(n,e){let t=new p(8);return t.u8(tt(he.CHANNEL_JOIN_REQUEST)),t.u16be(n-Se),t.u16be(e),we(t.take())}function Zn(n){let e=new _(Le(n)),t=e.u8();if(t>>2!==he.CHANNEL_JOIN_CONFIRM)throw new Error(`RDP: expected an MCS channel-join confirm, got PDU ${t>>2}`);let s=e.u8();e.u16be();let r=e.u16be();if(s!==0)throw new Error(`RDP: the host refused to join channel ${r} (result ${s})`);return{channelId:(e.remaining>=2?e.u16be():r)||r}}function Ht(n,e,t){let s=new p(t.length+16);return s.u8(tt(he.SEND_DATA_REQUEST)),s.u16be(n-Se),s.u16be(e),s.u8(112),Pt(s,t.length),s.raw(t),we(s.take())}function Jn(n){let e=new _(Le(n)),t=e.u8(),s=t>>2;if(s===he.SEND_DATA_INDICATION){e.u16be();let r=e.u16be();e.u8();let i=$n(e),o=e.rest();return{type:"send-data",channelId:r,payload:o.subarray(0,Math.min(i,o.length))}}if(s===he.DISCONNECT_PROVIDER_ULTIMATUM){let r=(t&1)<<1|(e.remaining>0?e.u8()>>7:0);return{type:"disconnect",reason:r,message:ri[r]||`The host closed the RDP session (reason ${r}).`}}return{type:"other",mcsPduType:s}}var mi=49153,Ei=49154,yi=49155,wi=49156,gi=3073,Ai=3074,Si=3075,xi=524292,es=51715,Ti=43523,bi=1,nt={NONE:0,LOW:1,CLIENT_COMPATIBLE:2,HIGH:3,FIPS:4};function st(n,e){let t=new p(e.length+4);return t.u16le(n).u16le(e.length+4).raw(e),t.take()}function _i({width:n,height:e,clientName:t,keyboardLayout:s,selectedProtocol:r}){let i=new p(256);return i.u32le(xi),i.u16le(n),i.u16le(e),i.u16le(es),i.u16le(Ti),i.u32le(s),i.u32le(2600),i.utf16le(t,32),i.u32le(4),i.u32le(0),i.u32le(12),i.zeros(64),i.u16le(es),i.u16le(1),i.u32le(0),i.u16le(16),i.u16le(7),i.u16le(bi),i.zeros(64),i.u8(0),i.u8(0),i.u32le(r),st(mi,i.take())}function Ci(n){let e=new p(8);return e.u32le(n),e.u32le(0),st(Ei,e.take())}function Ri(){let n=new p(8);return n.u32le(13),n.u32le(0),st(wi,n.take())}function vi(n){if(n.length===0)return new Uint8Array(0);let e=new p(4+n.length*12);e.u32le(n.length);for(let t of n){let s=new Uint8Array(8);for(let r=0;r<Math.min(7,t.name.length);r++)s[r]=t.name.charCodeAt(r);e.raw(s),e.u32le(t.options>>>0)}return st(yi,e.take())}function ts(n){return b(_i(n),Ri(),Ci(n.encryptionMethods),vi(n.channels||[]))}function ns(n){let e=new _(n),t={version:null,encryptionMethod:0,encryptionLevel:nt.NONE,serverRandom:null,publicKey:null,ioChannelId:1003,channelIds:[]};for(;e.remaining>=4;){let s=e.u16le(),r=e.u16le();if(r<4||r-4>e.remaining)break;let i=new _(e.raw(r-4));if(s===gi){t.version=i.remaining>=4?i.u32le():null;continue}if(s===Si){t.ioChannelId=i.u16le();let o=i.u16le();for(let a=0;a<o&&i.remaining>=2;a++)t.channelIds.push(i.u16le());continue}if(s===Ai){if(t.encryptionMethod=i.u32le(),t.encryptionLevel=i.u32le(),t.encryptionMethod===0&&t.encryptionLevel===0||i.remaining<8)continue;let o=i.u32le(),a=i.u32le();t.serverRandom=i.raw(o).slice(),t.publicKey=kn(i.raw(a));continue}}return t}var W={MONITOR_READY:1,FORMAT_LIST:2,FORMAT_LIST_RESPONSE:3,FORMAT_DATA_REQUEST:4,FORMAT_DATA_RESPONSE:5,CLIP_CAPS:7},ss=1,Kt=2,Ni=4,De=1,xe=13,rs=1,Li=2,is=2,rt=32,Ii=400;function Ui(n,e,t=new Uint8Array(0)){let s=new p(t.length+8);return s.u16le(n).u16le(e).u32le(t.length).raw(t),s.take()}function Oi(n){let e=new p(n.length*2+2);return e.utf16le(n),e.u16le(0),e.take()}function ki(n){let e=new Uint16Array(n.length>>1);for(let r=0;r<e.length;r++)e[r]=n[r*2]|n[r*2+1]<<8;let t=e.indexOf(0);t===-1&&(t=e.length);let s="";for(let r=0;r<t;r+=4096)s+=String.fromCharCode(...e.subarray(r,Math.min(r+4096,t)));return s}function Di(n){let e=new p(n.length+1);for(let t of n){let s=t.codePointAt(0);e.u8(s>255?63:s)}return e.u8(0),e.take()}function Pi(n){let e=n.indexOf(0);return e===-1&&(e=n.length),String.fromCharCode(...n.subarray(0,e))}var it=class extends EventTarget{send;log;ready;longFormatNames;localText;pendingAck;constructor({send:e,log:t}){super(),this.send=e,this.log=t||(()=>{}),this.ready=!1,this.longFormatNames=!0,this.localText="",this.pendingAck=null}#e(e,t,s){this.send(Ui(e,t,s))}setLocalText(e){return this.localText=e,this.ready?(this.#e(W.FORMAT_LIST,0,this.#t(e?[xe,De]:[])),this.pendingAck&&this.pendingAck.resolve(!1),new Promise(t=>{let s=0,r=i=>{clearTimeout(s),this.pendingAck?.resolve===r&&(this.pendingAck=null),t(i)};s=setTimeout(()=>{this.log("clipboard format list was not acknowledged"),r(!1)},Ii),this.pendingAck={resolve:r}})):Promise.resolve(!1)}#t(e){let t=e.map(s=>{let r=new p(this.longFormatNames?6:4+rt);return r.u32le(s),this.longFormatNames?r.u16le(0):r.zeros(rt),r.take()});return b(...t)}receive(e){if(e.length<8)return;let t=new _(e),s=t.u16le(),r=t.u16le(),i=t.u32le(),o=t.rest(),a=o.subarray(0,Math.min(i,o.length));switch(s){case W.CLIP_CAPS:this.#r(a);return;case W.MONITOR_READY:this.#n();return;case W.FORMAT_LIST:this.#s(a,r);return;case W.FORMAT_LIST_RESPONSE:this.pendingAck?.resolve((r&Kt)===0);return;case W.FORMAT_DATA_REQUEST:this.#i(a);return;case W.FORMAT_DATA_RESPONSE:this.#a(a,r);return;default:return}}#r(e){let t=new _(e);if(t.remaining<4)return;let s=t.u16le();t.u16le();for(let r=0;r<s&&t.remaining>=4;r++){let i=t.u16le(),o=t.u16le();if(o<4||o-4>t.remaining)break;let a=new _(t.raw(o-4));if(i===rs&&a.remaining>=8){a.u32le();let c=a.u32le();this.longFormatNames=(c&is)!==0}}}#n(){let e=new p(12);e.u16le(rs).u16le(12),e.u32le(Li),e.u32le(this.longFormatNames?is:0);let t=new p(20);t.u16le(1).u16le(0),t.raw(e.take()),this.#e(W.CLIP_CAPS,0,t.take()),this.ready=!0,this.#e(W.FORMAT_LIST,0,this.#t(this.localText?[xe,De]:[])),this.log("clipboard channel ready",{longFormatNames:this.longFormatNames})}#s(e,t){let s=this.#c(e,t);this.#e(W.FORMAT_LIST_RESPONSE,ss);let r=s.includes(xe)?xe:s.includes(De)?De:null;if(r===null){this.log("host clipboard holds no text format",{formats:s});return}let i=new p(4);i.u32le(r),this.#e(W.FORMAT_DATA_REQUEST,0,i.take())}#c(e,t){let s=new _(e),r=[],i=!this.longFormatNames||(t&Ni)!==0;for(;s.remaining>=4;){if(r.push(s.u32le()),i){if(s.remaining<rt)break;s.skip(rt);continue}for(;s.remaining>=2&&s.u16le()!==0;);}return r}#i(e){let t=new _(e),s=t.remaining>=4?t.u32le():0;if(s!==xe&&s!==De){this.#e(W.FORMAT_DATA_RESPONSE,Kt);return}let r=s===xe?Oi(this.localText):Di(this.localText);this.#e(W.FORMAT_DATA_RESPONSE,ss,r),this.log("handed the host our clipboard",{formatId:s,characters:this.localText.length})}#a(e,t){if(t&Kt){this.log("the host refused to hand over its clipboard");return}let r=e.length>=2&&e.length%2===0&&e[1]===0?ki(e):Pi(e);r&&this.dispatchEvent(new CustomEvent("text",{detail:{text:r}}))}};var q={EXEC:1,ACTIVATE:2,SYSPARAM:3,SYSCOMMAND:4,HANDSHAKE:5,WINDOW_MOVE:8,CLIENT_STATUS:11,EXEC_RESULT:128,HANDSHAKE_EX:19},Mi={0:"The remote application started.",1:"The RemoteApp host could not load its application monitoring hook.",2:"The RemoteApp host could not decode the application launch request.",3:"The requested application is not in the host RemoteApp allowlist.",5:"The requested remote application was not found.",6:"The RemoteApp host could not start the requested application.",7:"The RemoteApp session is locked and cannot start the application."},as={MINIMIZE:61472,MAXIMIZE:61488,CLOSE:61536,RESTORE:61728},be={HIDDEN:0,MINIMIZED:2,MAXIMIZED:3,NORMAL:5},Pe={TYPE_WINDOW:16777216,STATE_NEW:268435456,STATE_DELETED:536870912,ICON:1073741824,CACHED_ICON:2147483648},B={OWNER:2,TITLE:4,STYLE:8,SHOW:16,WND_RECTS:256,WND_SIZE:1024,WND_OFFSET:2048,CLIENT_AREA_OFFSET:16384,CLIENT_DELTA:32768,CLIENT_AREA_SIZE:65536,RP_CONTENT:131072,ROOT_PARENT:262144,VISIBILITY:524288,VIS_OFFSET:2097152},Hi=1073741824,Ki=128,Fi=134217728,Bi=3,Gi=2,Wi=11,cs=2600,Vi=1024,Te={MOUSE_BUTTON_SWAP:33,DRAG_FULL_WINDOWS:37,WORK_AREA:47,HIGH_CONTRAST:67,KEYBOARD_PREF:69,KEYBOARD_CUES:4107};function Ft(n){let e=new p(n.length*2);return e.utf16le(n),e.take()}function ie(n,e){let t=new p(e.length+4);return t.u16le(n).u16le(e.length+4).raw(e),t.take()}function ee(n){return n|0}function Yi(n=cs){return ie(q.HANDSHAKE,new p(4).u32le(n).take())}function $i(n=Vi){return ie(q.CLIENT_STATUS,new p(4).u32le(n).take())}function ot(n,e){return ie(q.SYSPARAM,new p(5).u32le(n).u8(e?1:0).take())}function qi(){let n=new p(16);return n.u32le(Te.HIGH_CONTRAST),n.u32le(126),n.u32le(2),n.u16le(0).u16le(0),ie(q.SYSPARAM,n.take())}function hs(n,e){let t=new p(12);return t.u32le(Te.WORK_AREA),t.u16le(0).u16le(0).u16le(n).u16le(e),ie(q.SYSPARAM,t.take())}function Xi(n,e){return[qi(),ot(Te.MOUSE_BUTTON_SWAP,!1),ot(Te.KEYBOARD_PREF,!1),ot(Te.DRAG_FULL_WINDOWS,!0),ot(Te.KEYBOARD_CUES,!1),hs(n,e)]}function zi(n,e=!0){let t=new p(5);return t.u32le(n).u8(e?1:0),ie(q.ACTIVATE,t.take())}function Qi(n,e){let t=new p(6);return t.u32le(n).u16le(e),ie(q.SYSCOMMAND,t.take())}function ji(n,{left:e,top:t,right:s,bottom:r}){let i=new p(12);return i.u32le(n),i.u16le(e&65535).u16le(t&65535),i.u16le(s&65535).u16le(r&65535),ie(q.WINDOW_MOVE,i.take())}function Zi({program:n,workingDir:e="",arguments:t=""}){let s=Ft(n||""),r=Ft(e||""),i=Ft(t||"");if(s.length===0||s.length>520)throw new Error("RemoteApp program must be between 1 and 260 Unicode characters.");if(r.length>520)throw new Error("RemoteApp working directory is too long.");if(i.length>16e3)throw new Error("RemoteApp arguments are too long.");let o=new p(8+s.length+r.length+i.length);return o.u16le(0),o.u16le(s.length).u16le(r.length).u16le(i.length),o.raw(s).raw(r).raw(i),ie(q.EXEC,o.take())}function ls(n){let e="";for(let t=0;t+1<n.length;t+=2){let s=n[t]|n[t+1]<<8;if(s===0)break;e+=String.fromCharCode(s)}return e}function os(n,e){let t=[];for(let s=0;s<e&&n.remaining>=8;s++){let r=n.u16le(),i=n.u16le(),o=n.u16le(),a=n.u16le();t.push({left:r,top:i,right:o,bottom:a})}return t}function Ji(n,e){let t={};if(e&B.OWNER&&(t.ownerWindowId=n.u32le()),e&B.STYLE&&(t.style=n.u32le(),t.extendedStyle=n.u32le()),e&B.SHOW&&(t.showState=n.u8()),e&B.TITLE){let s=n.u16le();t.title=ls(n.raw(Math.min(s,n.remaining)))}return e&B.CLIENT_AREA_OFFSET&&(t.clientOffsetX=ee(n.u32le()),t.clientOffsetY=ee(n.u32le())),e&B.CLIENT_AREA_SIZE&&(t.clientWidth=ee(n.u32le()),t.clientHeight=ee(n.u32le())),e&B.RP_CONTENT&&n.u8(),e&B.ROOT_PARENT&&n.u32le(),e&B.WND_OFFSET&&(t.x=ee(n.u32le()),t.y=ee(n.u32le())),e&B.CLIENT_DELTA&&(n.u32le(),n.u32le()),e&B.WND_SIZE&&(t.width=ee(n.u32le()),t.height=ee(n.u32le())),e&B.WND_RECTS&&(t.windowRects=os(n,n.u16le())),e&B.VIS_OFFSET&&(t.visibleOffsetX=ee(n.u32le()),t.visibleOffsetY=ee(n.u32le())),e&B.VISIBILITY&&(t.visibilityRects=os(n,n.u16le())),t}function us(n){return!(!n||n.ownerWindowId||(n.style||0)&Hi||(n.extendedStyle||0)&(Ki|Fi))}function ds(n){if(n.remaining<6)throw new Error("RDP RemoteApp orders update is truncated.");n.u16le();let e=n.u16le();n.u16le();let t=[];for(let s=0;s<e&&n.remaining>0;s++){let r=n.offset,i=n.u8(),o=i&Bi,a=i>>2;if(o!==Gi||a!==Wi)break;if(n.remaining<6)throw new Error("RDP RemoteApp window-order header is truncated.");let c=n.u16le(),h=n.u32le(),m=r+c;if(c<7||m>n.bytes.length)throw new Error("RDP RemoteApp window order has an invalid size.");let y=!!(h&Pe.TYPE_WINDOW),E=!!(h&(Pe.ICON|Pe.CACHED_ICON));if(y&&!E&&m-n.offset>=4){let w=n.u32le(),f={};try{f=Ji(n,h)}catch(A){console.warn("[RDP] Dropped an unreadable RemoteApp window order",{windowId:w,fieldFlags:`0x${(h>>>0).toString(16)}`,error:A instanceof Error?A.message:String(A)})}let l="update";h&Pe.STATE_DELETED?l="deleted":h&Pe.STATE_NEW&&(l="new"),t.push({type:l,windowId:w,fieldFlags:h,...f})}if(n.offset=m,n.offset<=r)break}return t}function eo(n){let e=new _(n),t=[];for(;e.remaining>=4;){let s=e.u16le(),r=e.u16le();if(r<4||r-4>e.remaining)throw new Error("RDP RemoteApp channel delivered a malformed PDU.");let i=new _(e.raw(r-4));if(s===q.HANDSHAKE&&i.remaining>=4){t.push({type:"handshake",buildNumber:i.u32le()});continue}if(s===q.HANDSHAKE_EX&&i.remaining>=8){t.push({type:"handshake",buildNumber:i.u32le(),flags:i.u32le(),extended:!0});continue}if(s===q.EXEC_RESULT&&i.remaining>=12){let o=i.u16le(),a=i.u16le(),c=i.u32le();i.u16le();let h=i.u16le(),m=ls(i.raw(Math.min(h,i.remaining)));t.push({type:"execute-result",flags:o,result:a,rawResult:c,program:m});continue}t.push({type:"unknown",orderType:s,body:i.rest().slice()})}return t}var at=class{application;width;height;send;onReady;onResult;started;constructor({application:e,width:t,height:s,send:r,onReady:i,onResult:o}){this.application=e,this.width=t,this.height=s,this.send=r,this.onReady=i,this.onResult=o,this.started=!1}receive(e){for(let t of eo(e)){if(t.type==="handshake"){if(this.started)continue;this.started=!0,this.send(Yi(cs)),this.send($i());for(let s of Xi(this.width,this.height))this.send(s);this.send(Zi(this.application)),this.onReady?.(t);continue}t.type==="execute-result"&&this.onResult?.({...t,ok:t.result===0,message:Mi[t.result]||`The RemoteApp host returned launch result 0x${t.result.toString(16).padStart(4,"0")}.`})}}setWorkArea(e,t){return!this.started||e<=0||t<=0||e===this.width&&t===this.height?!1:(this.width=e,this.height=t,this.send(hs(e,t)),!0)}activate(e){return this.started?(this.send(zi(e,!0)),!0):!1}sysCommand(e,t){return this.started?(this.send(Qi(e,t)),!0):!1}moveWindow(e,t){return this.started?(this.send(ji(e,t)),!0):!1}};var fe={INITIALIZED:2147483648,ENCRYPT_RDP:1073741824,COMPRESS_RDP:8388608,SHOW_PROTOCOL:2097152},fs=1,ps=2,ms=16,Bt=1600;function Es(n,e=Bt,t=0){let s=[];for(let r=0;r<n.length||r===0;r+=e){let i=n.subarray(r,r+e),o=t;r===0&&(o|=fs),r+e>=n.length&&(o|=ps);let a=new p(i.length+8);if(a.u32le(n.length).u32le(o).raw(i),s.push(a.take()),n.length===0)break}return s}var ct=class{parts;expectedLength;constructor(){this.parts=[],this.expectedLength=0}push(e){if(e.length<8)return null;let t=new _(e),s=t.u32le(),r=t.u32le(),i=t.rest();if(r&fs&&(this.parts=[],this.expectedLength=s),this.parts.push(i.slice()),!((r&ps)!==0))return null;let a=b(...this.parts);return this.parts=[],this.expectedLength&&this.expectedLength<a.length?a.subarray(0,this.expectedLength):a}};var G={EXCHANGE_PKT:1,TRANSPORT_REQ:2,ENCRYPT:8,RESET_SEQNO:16,IGNORE_SEQNO:32,INFO_PKT:64,LICENSE_PKT:128,LICENSE_ENCRYPT_CS:512,REDIRECTION_PKT:1024,SECURE_CHECKSUM:2048,AUTODETECT_REQ:4096,AUTODETECT_RSP:8192,HEARTBEAT:16384},Gt=4096,Me=class{encryptionMethod;encryptionLevel;keys;encryptState;decryptState;encryptedPdus;decryptedPdus;constructor(){this.encryptionMethod=se.NONE,this.encryptionLevel=nt.NONE,this.keys=null,this.encryptState=null,this.decryptState=null,this.encryptedPdus=0,this.decryptedPdus=0}get headerPresent(){return this.encryptionLevel!==nt.NONE||this.encryptionMethod!==se.NONE}get encryptionEnabled(){return this.encryptionMethod!==se.NONE&&this.keys!==null}configure(e,t,s,r){if(this.encryptionMethod=e,this.encryptionLevel=t,e!==se.NONE){if(e&se.FIPS)throw new Error("RDP: this host requires FIPS encryption, which this client does not implement");this.keys=Tn(s,r,e),this.encryptState=Z(this.keys.encryptKey),this.decryptState=Z(this.keys.decryptKey)}}#e(){this.keys.encryptKey=Ct(this.keys.initialEncryptKey,this.keys.encryptKey,this.keys.keyLength,this.keys.is40Bit),this.encryptState=Z(this.keys.encryptKey),this.encryptedPdus=0}#t(){this.keys.decryptKey=Ct(this.keys.initialDecryptKey,this.keys.decryptKey,this.keys.keyLength,this.keys.is40Bit),this.decryptState=Z(this.keys.decryptKey),this.decryptedPdus=0}wrap(e,t=0){let s=this.encryptionEnabled;if(!s&&t===0&&!this.headerPresent)return e;let r=new p(e.length+16);return r.u16le(t|(s?G.ENCRYPT:0)),r.u16le(0),s?(r.raw(bn(this.keys.macKey,e)),r.raw(X(this.encryptState,e)),++this.encryptedPdus===Gt&&this.#e(),r.take()):(r.raw(e),r.take())}unwrap(e,t=!1){if(!this.headerPresent&&!t)return{flags:0,payload:e};if(e.length<4)return{flags:0,payload:e};let s=new _(e),r=s.u16le();if(s.u16le(),!(r&G.ENCRYPT))return{flags:r,payload:s.rest()};if(!this.encryptionEnabled)throw new Error("RDP: the host encrypted a PDU before the session keys existed");s.skip(8);let i=X(this.decryptState,s.rest());return++this.decryptedPdus===Gt&&this.#t(),{flags:r,payload:i}}decryptFastPath(e){if(!this.encryptionEnabled||e.length<=8)return e;let t=X(this.decryptState,e.subarray(8));return++this.decryptedPdus===Gt&&this.#t(),t}static securityExchange(e){let t=new p(e.length+16);return t.u16le(G.EXCHANGE_PKT),t.u16le(0),t.u32le(e.length+8),t.raw(e),t.zeros(8),t.take()}};var k={GENERAL:1,BITMAP:2,ORDER:3,BITMAPCACHE:4,CONTROL:5,ACTIVATION:7,POINTER:8,SHARE:9,COLORCACHE:10,SOUND:12,INPUT:13,FONT:14,BRUSH:15,GLYPHCACHE:16,OFFSCREENCACHE:17,VIRTUALCHANNEL:20,RAIL:23,WINDOW:24,MULTIFRAGMENTUPDATE:26,LARGE_POINTER:27,SURFACE_COMMANDS:28,BITMAP_CODECS:29},to=1,no=4,so=16,ro=1,io=4,oo=2,ao=8;function F(n,e){let t=new p(e.length+4);return t.u16le(n).u16le(e.length+4).raw(e),t.take()}function co(){let n=new p(24);return n.u16le(1),n.u16le(3),n.u16le(512),n.u16le(0),n.u16le(0),n.u16le(ro|io),n.u16le(0),n.u16le(0),n.u16le(0),n.u8(1),n.u8(1),F(k.GENERAL,n.take())}function ho(n,e){let t=new p(28);return t.u16le(16),t.u16le(1),t.u16le(1),t.u16le(1),t.u16le(n),t.u16le(e),t.u16le(0),t.u16le(1),t.u16le(1),t.u8(0),t.u8(0),t.u16le(1),t.u16le(0),F(k.BITMAP,t.take())}function lo(){let n=new p(88);return n.zeros(16),n.u32le(0),n.u16le(1),n.u16le(20),n.u16le(0),n.u16le(1),n.u16le(0),n.u16le(oo|ao),n.zeros(32),n.u16le(0),n.u16le(0),n.u32le(0),n.u32le(230400),n.u16le(0),n.u16le(0),n.u16le(0),n.u16le(0),F(k.ORDER,n.take())}function uo(){let n=new p(40);return n.zeros(24),n.u16le(0).u16le(0),n.u16le(0).u16le(0),n.u16le(0).u16le(0),F(k.BITMAPCACHE,n.take())}function fo(){let n=new p(12);return n.u16le(0),n.u16le(0),n.u16le(2),n.u16le(2),F(k.CONTROL,n.take())}function po(){let n=new p(12);return n.u16le(0).u16le(0).u16le(0).u16le(0),F(k.ACTIVATION,n.take())}function mo(){let n=new p(10);return n.u16le(1),n.u16le(20),n.u16le(20),F(k.POINTER,n.take())}function Eo(){let n=new p(8);return n.u16le(0).u16le(0),F(k.SHARE,n.take())}function yo(){let n=new p(8);return n.u16le(6).u16le(0),F(k.COLORCACHE,n.take())}function wo(){let n=new p(8);return n.u16le(0).u16le(0),F(k.SOUND,n.take())}function go(n){let e=new p(88);return e.u16le(to|no|so),e.u16le(0),e.u32le(n),e.u32le(4),e.u32le(0),e.u32le(12),e.zeros(64),F(k.INPUT,e.take())}function Ao(){let n=new p(8);return n.u16le(1).u16le(0),F(k.FONT,n.take())}function So(){let n=new p(8);return n.u32le(0),F(k.BRUSH,n.take())}function xo(){let n=new p(52);for(let e=0;e<10;e++)n.u16le(0).u16le(0);return n.u32le(0),n.u16le(0),n.u16le(0),F(k.GLYPHCACHE,n.take())}function To(){let n=new p(12);return n.u32le(0),n.u16le(0),n.u16le(0),F(k.OFFSCREENCACHE,n.take())}function bo(){let n=new p(4);return n.u32le(1),F(k.RAIL,n.take())}function _o(n=0,e=0){let t=new p(7);return t.u32le(1),t.u8(n),t.u16le(e),F(k.WINDOW,t.take())}function ys({width:n,height:e,keyboardLayout:t,remoteApp:s=!1,remoteAppCaps:r=null}){let i=[co(),ho(n,e),lo(),uo(),yo(),po(),fo(),mo(),Eo(),go(t),So(),xo(),wo(),Ao(),To()];return s&&(i.push(bo()),i.push(_o(r?.numIconCaches||0,r?.numIconCacheEntries||0))),{bytes:b(...i),count:i.length}}function ws(n){let e=new _(n),t=e.u16le();e.u16le();let s={desktopWidth:0,desktopHeight:0,preferredBitsPerPixel:16,refreshRectSupport:!1,railSupportLevel:0,windowSupportLevel:0,numIconCaches:0,numIconCacheEntries:0,types:[]};for(let r=0;r<t&&e.remaining>=4;r++){let i=e.u16le(),o=e.u16le();if(o<4||o-4>e.remaining)break;let a=new _(e.raw(o-4));if(s.types.push(i),i===k.BITMAP&&a.remaining>=20){s.preferredBitsPerPixel=a.u16le(),a.skip(6),s.desktopWidth=a.u16le(),s.desktopHeight=a.u16le();continue}if(i===k.GENERAL&&a.remaining>=20){a.skip(18),s.refreshRectSupport=a.u8()!==0;continue}if(i===k.RAIL&&a.remaining>=4){s.railSupportLevel=a.u32le();continue}if(i===k.WINDOW&&a.remaining>=7){s.windowSupportLevel=a.u32le(),s.numIconCaches=a.u8(),s.numIconCacheEntries=a.u16le();continue}}return s}var pe={DEMAND_ACTIVE:1,CONFIRM_ACTIVE:3,DEACTIVATE_ALL:6,DATA:7,SERVER_REDIRECT:10},M={UPDATE:2,CONTROL:20,POINTER:27,INPUT:28,SYNCHRONIZE:31,REFRESH_RECT:33,PLAY_SOUND:34,SUPPRESS_OUTPUT:35,SHUTDOWN_REQUEST:36,SHUTDOWN_DENIED:37,SAVE_SESSION_INFO:38,FONT_LIST:39,FONT_MAP:40,SET_ERROR_INFO:47,MONITOR_LAYOUT:55},ht={ORDERS:0,BITMAP:1,PALETTE:2,SYNCHRONIZE:3},Wt={REQUEST_CONTROL:1,GRANTED_CONTROL:2,DETACH:3,COOPERATE:4},Fe={SYNC:0,SCANCODE:4,UNICODE:5,MOUSE:32769,MOUSEX:32770},Ke={EXTENDED:256,DOWN:16384,RELEASE:32768},te={WHEEL:512,HWHEEL:1024,WHEEL_NEGATIVE:256,MOVE:2048,DOWN:32768,BUTTON1:4096,BUTTON2:8192,BUTTON3:16384};function As(n,e=!1){let t=e?Math.sign(n):-Math.sign(n);if(t===0)return 0;let s=e?te.HWHEEL:te.WHEEL,r=120;return t>0?s|r:s|te.WHEEL_NEGATIVE|-r&255}var lt={SCROLL_LOCK:1,NUM_LOCK:2,CAPS_LOCK:4,KANA_LOCK:8},_e={SYSTEM:1,POSITION:3,COLOR:6,CACHED:7,POINTER:8,LARGE:9},Co=721267,Ro=8,vo=32768,No={1:"The host disconnected the session (an administrative API call ended it).",2:"The host logged the session off.",3:"The session was disconnected after being idle too long.",4:"The session was disconnected because sign-in took too long.",5:"The session was taken over by another connection.",6:"The host ran out of memory.",7:"The host denied the connection.",9:"This account does not have permission to sign in remotely.",10:"The host requires fresh credentials.",11:"A user on the host ended the session.",12:"The remote user signed out.",256:"Remote Desktop licensing failed on the host (internal error).",257:"The host could not reach a Remote Desktop licensing server.",258:"The host has no Remote Desktop licence available for this client.",259:"The host rejected this client during licensing.",260:"The stored Remote Desktop licence does not match this client.",261:"The host rejected the client licence.",262:"Remote Desktop licensing could not be completed.",263:"The client ended the licensing exchange.",264:"The host rejected the client licence encryption.",265:"The host could not upgrade the client licence.",266:"The host does not accept remote connections.",4345:"The host rejected a malformed capability set from this client.",4346:"The host rejected the client capability exchange."};function Ss(n){return No[n]||`The host ended the session with error info 0x${n.toString(16).padStart(8,"0")}.`}function Vt(n,e,t){let s=new p(t.length+6);return s.u16le(t.length+6),s.u16le(n|16),s.u16le(e),s.raw(t),s.take()}function xs(n,e,t,s){let r=new p(s.length+12);return r.u32le(n),r.u8(0),r.u8(1),r.u16le(s.length+18),r.u8(t),r.u8(0),r.u16le(0),r.raw(s),Vt(pe.DATA,e,r.take())}function He(n,e){let t=n.length;n.utf16le(e);let s=n.length-t;return n.u16le(0),s}function Ts({domain:n,username:e,password:t,performanceFlags:s,autoLogon:r,remoteApp:i=!1}){let o=new p(512),a=He(o,n||""),c=He(o,e||""),h=He(o,t||""),m=He(o,""),y=He(o,""),E=new p(768);return E.u32le(0),E.u32le((Co|(r?Ro:0)|(i?vo:0))>>>0),E.u16le(a),E.u16le(c),E.u16le(h),E.u16le(m),E.u16le(y),E.raw(o.take()),E.u16le(2),E.u16le(2),E.u16le(0),E.u16le(2),E.u16le(0),E.zeros(172),E.u32le(0),E.u32le(s>>>0),E.u16le(0),E.take()}function bs(n){let e=new p(4);return e.u16le(1),e.u16le(n),e.take()}function Yt(n){let e=new p(8);return e.u16le(n),e.u16le(0),e.u32le(0),e.take()}function _s(){let n=new p(8);return n.u16le(0),n.u16le(0),n.u16le(3),n.u16le(50),n.take()}function Cs(n,e,t){let s=new TextEncoder().encode("MSTSC\0"),r=new p(e.length+32);return r.u32le(n),r.u16le(1002),r.u16le(s.length),r.u16le(e.length+4),r.raw(s),r.u16le(t),r.u16le(0),r.raw(e),r.take()}function Rs(n){let e=new p(n.length*12+4);e.u16le(n.length),e.u16le(0);for(let t of n)e.raw(t);return e.take()}function Be(n,e){let t=new p(12);return t.u32le(0),t.u16le(n),e(t),t.take()}function $t(n,e,t){return Be(Fe.SCANCODE,s=>{s.u16le((e?Ke.DOWN:Ke.RELEASE)|(t?Ke.EXTENDED:0)),s.u16le(n),s.u16le(0)})}function qt(n,e){return Be(Fe.UNICODE,t=>{t.u16le(e?Ke.DOWN:Ke.RELEASE),t.u16le(n),t.u16le(0)})}function ut(n,e,t){return Be(Fe.MOUSE,s=>{s.u16le(n),s.u16le(Math.max(0,Math.min(65535,Math.round(e)))),s.u16le(Math.max(0,Math.min(65535,Math.round(t))))})}function vs(n,e,t){return Be(Fe.MOUSEX,s=>{s.u16le(n),s.u16le(Math.max(0,Math.min(65535,Math.round(e)))),s.u16le(Math.max(0,Math.min(65535,Math.round(t))))})}function Xt(n){return Be(Fe.SYNC,e=>{e.u16le(0),e.u32le(n>>>0)})}function Ns(n){let e=new p(4+n.length*8);e.u8(n.length),e.zeros(3);for(let t of n)e.u16le(t.left),e.u16le(t.top),e.u16le(t.right),e.u16le(t.bottom);return e.take()}function Ls(n,e){let t=new p(12);return t.u8(n?1:0),t.zeros(3),n&&e&&(t.u16le(e.left),t.u16le(e.top),t.u16le(e.right),t.u16le(e.bottom)),t.take()}function Is(n){let e=new _(n),t=e.u16le(),s=e.u16le(),r=e.u16le();return{totalLength:t,pduType:s&15,pduSource:r,payload:e.rest().subarray(0,Math.max(0,t-6))}}function Us(n){let e=new _(n),t=e.u32le();e.u8(),e.u8(),e.u16le();let s=e.u8(),r=e.u8(),i=e.u16le();return{shareId:t,pduType2:s,compressedType:r,compressedLength:i,payload:e.rest()}}function Os(n){let e=new _(n),t=e.u32le(),s=e.u16le(),r=e.u16le();e.skip(s);let i=e.raw(Math.min(r,e.remaining));return{shareId:t,capabilities:i}}var Lo=1,Io=1024;function zt(n){let e=n.u16le(),t=[];for(let s=0;s<e&&n.remaining>=18;s++){let r=n.u16le(),i=n.u16le(),o=n.u16le(),a=n.u16le(),c=n.u16le(),h=n.u16le(),m=n.u16le(),y=n.u16le(),E=n.u16le(),w=!!(y&Lo);if(w&&!(y&Io)){n.u16le();let f=n.u16le();n.u16le(),n.u16le(),E=f}t.push({left:r,top:i,right:o,bottom:a,width:c,height:h,bitsPerPixel:m,compressed:w,data:n.raw(Math.min(E,n.remaining))})}return t}function Qt(n){n.u16le(),n.u16le();let e=n.u32le(),t=new Uint8Array(256*3);for(let s=0;s<e&&s<256&&n.remaining>=3;s++)t[s*3]=n.u8(),t[s*3+1]=n.u8(),t[s*3+2]=n.u8();return t}function gs(n,e){let t=n.u16le(),s=n.u16le(),r=n.u16le(),i=n.u16le(),o=n.u16le(),a=n.u16le(),c=n.u16le(),h=n.raw(Math.min(c,n.remaining)).slice(),m=n.raw(Math.min(a,n.remaining)).slice();return{kind:"bitmap",cacheIndex:t,hotSpotX:s,hotSpotY:r,width:i,height:o,xorBpp:e||24,xorMask:h,andMask:m}}function jt(n){let e=n.u16le();if(n.u16le(),e===_e.POSITION)return{kind:"position",x:n.u16le(),y:n.u16le()};if(e===_e.SYSTEM)return{kind:"system",hidden:n.u32le()===0};if(e===_e.CACHED)return{kind:"cached",cacheIndex:n.u16le()};if(e===_e.COLOR)return gs(n,24);if(e===_e.POINTER){let t=n.u16le();return gs(n,t)}return e===_e.LARGE?{kind:"unsupported",messageType:e}:{kind:"unsupported",messageType:e}}var ks={Escape:1,Digit1:2,Digit2:3,Digit3:4,Digit4:5,Digit5:6,Digit6:7,Digit7:8,Digit8:9,Digit9:10,Digit0:11,Minus:12,Equal:13,Backspace:14,Tab:15,KeyQ:16,KeyW:17,KeyE:18,KeyR:19,KeyT:20,KeyY:21,KeyU:22,KeyI:23,KeyO:24,KeyP:25,BracketLeft:26,BracketRight:27,Enter:28,ControlLeft:29,KeyA:30,KeyS:31,KeyD:32,KeyF:33,KeyG:34,KeyH:35,KeyJ:36,KeyK:37,KeyL:38,Semicolon:39,Quote:40,Backquote:41,ShiftLeft:42,Backslash:43,KeyZ:44,KeyX:45,KeyC:46,KeyV:47,KeyB:48,KeyN:49,KeyM:50,Comma:51,Period:52,Slash:53,ShiftRight:54,NumpadMultiply:55,AltLeft:56,Space:57,CapsLock:58,F1:59,F2:60,F3:61,F4:62,F5:63,F6:64,F7:65,F8:66,F9:67,F10:68,NumLock:69,ScrollLock:70,Numpad7:71,Numpad8:72,Numpad9:73,NumpadSubtract:74,Numpad4:75,Numpad5:76,Numpad6:77,NumpadAdd:78,Numpad1:79,Numpad2:80,Numpad3:81,Numpad0:82,NumpadDecimal:83,IntlBackslash:86,F11:87,F12:88,IntlRo:115,IntlYen:125},Ds={NumpadEnter:28,ControlRight:29,NumpadDivide:53,PrintScreen:55,AltRight:56,Home:71,ArrowUp:72,PageUp:73,ArrowLeft:75,ArrowRight:77,End:79,ArrowDown:80,PageDown:81,Insert:82,Delete:83,MetaLeft:91,MetaRight:92,ContextMenu:93};function Zt(n){return Object.prototype.hasOwnProperty.call(ks,n)?{scancode:ks[n],extended:!1}:Object.prototype.hasOwnProperty.call(Ds,n)?{scancode:Ds[n],extended:!0}:null}var Ps=[{code:"ControlLeft",pressed:!0},{code:"AltLeft",pressed:!0},{code:"Delete",pressed:!0},{code:"Delete",pressed:!1},{code:"AltLeft",pressed:!1},{code:"ControlLeft",pressed:!1}];var Ce="VNC_GATEWAY_READY_v1",Re="VNC_GATEWAY_KEEPALIVE_v1";var N={IDLE:"idle",NEGOTIATING:"negotiating",TLS_HANDSHAKE:"tls-handshake",CREDSSP:"credssp",MCS_CONNECT:"mcs-connect",ATTACH_USER:"attach-user",JOIN_CHANNELS:"join-channels",SECURE:"secure-exchange",LICENSING:"licensing",CAPABILITIES:"capabilities",CONNECTED:"connected",CLOSED:"closed"},Uo=255,Jt={name:"cliprdr",options:fe.INITIALIZED|fe.ENCRYPT_RDP|fe.SHOW_PROTOCOL},en={name:"rail",options:fe.INITIALIZED|fe.ENCRYPT_RDP|fe.SHOW_PROTOCOL},Oo=1,ko=2,Do=4,Po=1200,Mo=120,dt=2,Ho=4,Ko=12,Ms=320,ft=class extends EventTarget{constructor(e,t={}){super(),this.url=e,this.options={width:1024,height:768,username:"",password:"",domain:"",keyboardLayout:1033,clientName:"cf-gateway",security:"auto",openTransport:null,clipboard:!0,remoteApp:null,performance:Oo|ko|Do,...t},this.state=N.IDLE,this.legacyRetryUsed=!1,this.desktopWidth=this.options.width,this.desktopHeight=this.options.height,this.palette=null,this.userId=Se,this.ioChannelId=1003,this.serverChannelId=1002,this.shareId=0,this.channelsToJoin=[],this.requestedChannels=[],this.channelNamesById=new Map,this.channelReassemblers=new Map,this.clipboard=null,this.rail=null,this.remoteAppWindows=new Map,this.remoteAppHadWindow=!1,this.remoteAppCloseTimer=null,this.remoteAppFit=null,this.remoteAppFitTimer=null,this.clientRandom=null,this.serverData=null,this.fastPathFragments=[],this.receiveBuffer=new Uint8Array(0),this.keepaliveTimer=null,this.closeReported=!1,this.tls=null,this.credssp=null,this.inboundQueue=Promise.resolve(),this.requestedProtocol={auto:D.SSL|D.HYBRID,nla:D.SSL|D.HYBRID,tls:D.SSL,rdp:D.RDP}[this.options.security]??D.SSL|D.HYBRID,this.#e()}#e(){this.receiveBuffer=new Uint8Array(0),this.inboundQueue=Promise.resolve(),this.tls=null,this.credssp=null,this.security=new Me,this.replacingTransport=!1,this.channelNamesById=new Map,this.channelReassemblers=new Map,this.clipboard=null,this.rail=null,this.remoteAppWindows.clear(),this.remoteAppHadWindow=!1,clearTimeout(this.remoteAppCloseTimer),clearTimeout(this.remoteAppFitTimer),this.remoteAppFitTimer=null,this.remoteAppCloseTimer=null,this.socket=this.options.openTransport?this.options.openTransport(this.url):new WebSocket(this.url),this.socket.binaryType="arraybuffer",this.socket.addEventListener("open",()=>this.#r()),this.socket.addEventListener("message",e=>this.#a(e)),this.socket.addEventListener("close",e=>this.#c(e)),this.socket.addEventListener("error",()=>{console.warn("[RDP] WebSocket transport error",{target:this.url})})}#t(e){console.info("[RDP] Reconnecting with a different security layer",{security:e}),this.legacyRetryUsed=!0,this.options.security=e,this.requestedProtocol=e==="rdp"?D.RDP:D.SSL,this.state=N.IDLE,this.replacingTransport=!0,clearInterval(this.keepaliveTimer);try{this.socket.close(1e3,"Retrying with another security layer")}catch{}this.#e()}#r(){this.socket.send(Ce),this.state=N.NEGOTIATING,this.#n(Rn(this.requestedProtocol)),this.keepaliveTimer=setInterval(()=>{if(this.socket.readyState===WebSocket.OPEN&&(this.socket.send(Re),this.state===N.CONNECTED))try{this.#f([Xt(this.toggleFlags||0)])}catch{}},25e3)}#n(e){if(this.tls&&this.tls.established){this.tls.write(e);return}this.#s(e)}#s(e){this.socket.readyState===WebSocket.OPEN&&this.socket.send(e)}#c(e){if(clearInterval(this.keepaliveTimer),clearTimeout(this.remoteAppCloseTimer),clearTimeout(this.remoteAppFitTimer),this.remoteAppFitTimer=null,this.replacingTransport||this.state===N.CLOSED&&this.closeReported)return;let t=this.state===N.CONNECTED;this.state=N.CLOSED,this.closeReported=!0,this.dispatchEvent(new CustomEvent("close",{detail:{clean:e.wasClean&&t,code:e.code,message:e.reason||"",phase:t?"session":"handshake"}}))}#i(e){if(this.state===N.CLOSED)return;let t=e instanceof Error?e.message:String(e);console.error("[RDP] Protocol failure",{state:this.state,message:t}),this.dispatchEvent(new CustomEvent("error",{detail:{message:t,phase:this.state}})),this.state=N.CLOSED,this.closeReported=!0,clearInterval(this.keepaliveTimer),clearTimeout(this.remoteAppCloseTimer),clearTimeout(this.remoteAppFitTimer),this.remoteAppFitTimer=null;try{this.socket.close(4e3,t.slice(0,100))}catch{}this.dispatchEvent(new CustomEvent("close",{detail:{clean:!1,code:4e3,message:t,phase:"protocol"}}))}disconnect(){if(this.state!==N.CLOSED){this.state=N.CLOSED,this.closeReported=!0,clearInterval(this.keepaliveTimer),clearTimeout(this.remoteAppCloseTimer),clearTimeout(this.remoteAppFitTimer),this.remoteAppFitTimer=null;try{this.socket.close(1e3,"Client disconnected")}catch{}}}#a(e){this.state!==N.CLOSED&&(this.inboundQueue=this.inboundQueue.then(async()=>{if(this.state===N.CLOSED)return;let t=typeof e.data=="string"?new TextEncoder().encode(e.data):new Uint8Array(e.data);this.tls?await this.tls.receive(t):await this.#h(t)}).catch(t=>this.#i(t)))}#o(e){if(this.state===N.CREDSSP&&this.credssp){this.credssp.receive(e);return}return this.#h(e)}async#h(e){this.receiveBuffer=this.receiveBuffer.length===0?e:b(this.receiveBuffer,e);let{frames:t,rest:s}=Nn(this.receiveBuffer);this.receiveBuffer=s.length===this.receiveBuffer.length?this.receiveBuffer:s.slice();for(let{fastPath:r,frame:i}of t){if(this.state===N.CLOSED)return;r?this.#O(i):await this.#l(i)}}async#l(e){if(this.state===N.NEGOTIATING){let o;try{({selectedProtocol:o}=vn(e))}catch(a){if(this.options.security==="auto"&&!this.legacyRetryUsed&&a.negotiationFailure===Cn.SSL_NOT_ALLOWED){this.#t("rdp");return}throw a}if(this.selectedProtocol=o,console.info("[RDP] X.224 negotiation complete",{requested:this.requestedProtocol,selected:o,layer:o&D.HYBRID?"NLA / CredSSP":o&D.SSL?"TLS":"RDP standard"}),o&D.HYBRID_EX)throw new Error("This host selected CredSSP with early user authorization, which this client does not implement.");if(o&(D.SSL|D.HYBRID)){this.#E(o);return}this.#u(o);return}if(this.state===N.MCS_CONNECT){this.serverData=ns(Xn(e)),console.info("[RDP] MCS connect response",{encryptionMethod:this.serverData.encryptionMethod,encryptionLevel:this.serverData.encryptionLevel,ioChannelId:this.serverData.ioChannelId,certificate:this.serverData.publicKey?.source||"none",virtualChannels:this.serverData.channelIds}),this.ioChannelId=this.serverData.ioChannelId,this.channelNamesById=new Map,this.requestedChannels.forEach((o,a)=>{let c=this.serverData.channelIds[a];c!==void 0&&this.channelNamesById.set(c,o.name)}),this.security.configure(this.serverData.encryptionMethod,this.serverData.encryptionLevel,this.serverData.encryptionMethod?this.#m():new Uint8Array(32),this.serverData.serverRandom||new Uint8Array(32)),this.state=N.ATTACH_USER,this.#n(zn()),this.#n(Qn());return}if(this.state===N.ATTACH_USER){({userId:this.userId}=jn(e)),this.channelsToJoin=[this.userId,this.ioChannelId,...this.serverData.channelIds],this.joinedChannels=0,this.state=N.JOIN_CHANNELS,this.#n(Mt(this.userId,this.channelsToJoin[0]));return}if(this.state===N.JOIN_CHANNELS){if(Zn(e),this.joinedChannels+=1,this.joinedChannels<this.channelsToJoin.length){this.#n(Mt(this.userId,this.channelsToJoin[this.joinedChannels]));return}this.#g();return}let t=Jn(e);if(t.type==="disconnect"){this.#i(new Error(t.message));return}if(t.type!=="send-data")return;let s=this.channelNamesById.get(t.channelId);if(s){let o=this.security.headerPresent?this.security.unwrap(t.payload).payload:t.payload;this.#D(s,o);return}let{flags:r,payload:i}=this.#p(t.payload);if(i.length!==0){if(r&G.LICENSE_PKT){this.#y(i);return}this.#T(i)}}#p(e){if(this.security.headerPresent)return this.security.unwrap(e);let t=G.EXCHANGE_PKT|G.ENCRYPT|G.INFO_PKT|G.LICENSE_PKT|G.LICENSE_ENCRYPT_CS|G.REDIRECTION_PKT|G.AUTODETECT_REQ|G.HEARTBEAT;if(e.length>=4){let s=e[0]|e[1]<<8;if((e[2]|e[3]<<8)===0&&(s&t)!==0)return this.security.unwrap(e,!0)}return{flags:0,payload:e}}async#E(e){try{this.state=N.TLS_HANDSHAKE,this.tls=new Qe({send:s=>this.#s(s),onData:s=>this.#o(s),onError:s=>this.#i(s)});let t=await this.tls.start();if(console.info("[RDP] TLS established",{cipherSuite:t.cipherSuite,certificates:t.certificates.length,modulusBits:t.publicKey.modulus.length*8}),e&D.HYBRID){if(this.state=N.CREDSSP,this.credssp=new Ze({username:this.options.username,domain:this.options.domain,password:this.options.password,serverPublicKey:t.publicKey.subjectPublicKey,send:r=>this.tls.write(r),log:(r,i)=>console.info(`[RDP] ${r}`,i)}),!this.options.password)throw new Error("This host authenticates before the desktop appears (NLA), so it needs a username and password.");let s=await this.credssp.authenticate();console.info("[RDP] Network Level Authentication succeeded",s),this.credssp=null}this.#u(e)}catch(t){this.#i(t)}}#u(e){this.state=N.MCS_CONNECT,this.requestedChannels=[],this.options.clipboard&&this.requestedChannels.push(Jt),this.options.remoteApp?.program&&this.requestedChannels.push(en),this.#n(qn(ts({width:this.options.width,height:this.options.height,clientName:this.options.clientName,keyboardLayout:this.options.keyboardLayout,selectedProtocol:e,encryptionMethods:e===D.RDP?11:0,channels:this.requestedChannels})))}#m(){return this.clientRandom=new Uint8Array(32),crypto.getRandomValues(this.clientRandom),this.clientRandom}#g(){if(this.security.encryptionEnabled){let t=this.serverData.publicKey;if(!t)throw new Error("RDP: the host asked for encryption but sent no public key");let s=wn(this.clientRandom,t.modulus,t.exponent);this.#d(Me.securityExchange(s))}let e=Ts({domain:this.options.domain,username:this.options.username,password:this.options.password,performanceFlags:this.options.performance,autoLogon:!!this.options.password,remoteApp:!!this.options.remoteApp?.program});this.state=N.LICENSING,this.#d(this.security.wrap(e,G.INFO_PKT))}#d(e){this.#n(Ht(this.userId,this.ioChannelId,e))}#y(e){if(e.length<4)return;if(e[0]===Uo){console.info("[RDP] Licensing finished with an error alert (the normal path)"),this.state=N.CAPABILITIES;return}throw new Error("This host requires Remote Desktop licensing negotiation (per-device CAL), which this client does not implement.")}#T(e){let t=Is(e);if(t.pduSource&&(this.serverChannelId=t.pduSource),t.pduType===pe.DEMAND_ACTIVE){this.#b(t.payload);return}if(t.pduType===pe.DEACTIVATE_ALL){console.info("[RDP] Host deactivated the share; waiting for a new demand active"),this.state=N.CAPABILITIES;return}if(t.pduType===pe.SERVER_REDIRECT)throw new Error("This host redirected the session to another server, which this client cannot follow.");if(t.pduType!==pe.DATA)return;let s=Us(t.payload);if(s.compressedType&32)throw new Error("RDP: the host compressed a PDU although this client advertised no compression support");this.#_(s)}#b(e){let{shareId:t,capabilities:s}=Os(e);this.shareId=t;let r=ws(s);if(this.options.remoteApp?.program&&(!(r.railSupportLevel&1)||!r.windowSupportLevel))throw new Error("This RDP host did not accept RemoteApp mode. Publish the application on the host or connect without a RemoteApp program.");if(r.desktopWidth&&r.desktopHeight){let a=this.state===N.CONNECTED&&(r.desktopWidth!==this.desktopWidth||r.desktopHeight!==this.desktopHeight);this.desktopWidth=r.desktopWidth,this.desktopHeight=r.desktopHeight,a&&(console.info("[RDP] Host resized the desktop",{desktop:`${this.desktopWidth}x${this.desktopHeight}`}),this.dispatchEvent(new CustomEvent("resize",{detail:{width:this.desktopWidth,height:this.desktopHeight}})))}this.refreshRectSupported=r.refreshRectSupport,console.info("[RDP] Demand active",{shareId:t,desktop:`${this.desktopWidth}x${this.desktopHeight}`,bitsPerPixel:r.preferredBitsPerPixel,refreshRectSupport:r.refreshRectSupport,remoteApp:!!this.options.remoteApp?.program});let{bytes:i,count:o}=ys({width:this.desktopWidth,height:this.desktopHeight,keyboardLayout:this.options.keyboardLayout,remoteApp:!!this.options.remoteApp?.program,remoteAppCaps:r});this.#M(pe.CONFIRM_ACTIVE,Cs(this.shareId,i,o)),this.#w(M.SYNCHRONIZE,bs(this.serverChannelId)),this.#w(M.CONTROL,Yt(Wt.COOPERATE)),this.#w(M.CONTROL,Yt(Wt.REQUEST_CONTROL)),this.#w(M.FONT_LIST,_s())}#_(e){switch(e.pduType2){case M.UPDATE:this.#C(new _(e.payload));return;case M.POINTER:this.dispatchEvent(new CustomEvent("pointer",{detail:jt(new _(e.payload))}));return;case M.FONT_MAP:this.#U();return;case M.SET_ERROR_INFO:{let t=new _(e.payload).u32le();if(t===0)return;this.#i(new Error(Ss(t)));return}case M.SAVE_SESSION_INFO:console.info("[RDP] Host reported a completed sign-in");return;case M.SHUTDOWN_DENIED:console.info("[RDP] Host denied the shutdown request");return;case M.CONTROL:case M.SYNCHRONIZE:case M.PLAY_SOUND:case M.MONITOR_LAYOUT:return;default:return}}#C(e){let t=e.u16le();if(this.firstUpdateLogged||(this.firstUpdateLogged=!0,console.info("[RDP] First host update received",{updateType:t})),t===ht.BITMAP){let s=zt(e);s.length>0&&this.dispatchEvent(new CustomEvent("bitmap",{detail:{rects:s,palette:this.palette}}));return}if(t===ht.PALETTE){this.palette=Qt(e),this.dispatchEvent(new CustomEvent("palette",{detail:this.palette}));return}if(t===ht.ORDERS){this.options.remoteApp?.program?this.#R(ds(e)):console.warn("[RDP] Ignoring a drawing-order update the client did not advertise");return}}#R(e){for(let t of e){if(t.type==="deleted"){this.remoteAppWindows.delete(t.windowId),this.dispatchEvent(new CustomEvent("remoteappwindow",{detail:{...t,count:this.remoteAppWindows.size}}));continue}t.type==="new"?(clearTimeout(this.remoteAppCloseTimer),this.remoteAppCloseTimer=null,this.remoteAppHadWindow=!0):this.remoteAppWindows.has(t.windowId)||(this.remoteAppHadWindow=!0);let r={...this.remoteAppWindows.get(t.windowId)||{windowId:t.windowId},...t,type:void 0};this.remoteAppWindows.set(t.windowId,r),this.dispatchEvent(new CustomEvent("remoteappwindow",{detail:{...t,window:r,count:this.remoteAppWindows.size}})),this.remoteAppFit&&this.#v(r)&&!this.#N(r)&&this.#A()}this.#I(),!(!this.remoteAppHadWindow||this.remoteAppWindows.size>0||this.remoteAppCloseTimer)&&(this.remoteAppCloseTimer=setTimeout(()=>{this.remoteAppCloseTimer=null,!(this.state!==N.CONNECTED||this.remoteAppWindows.size>0)&&(console.info("[RDP] Last RemoteApp window closed; ending the session"),this.dispatchEvent(new CustomEvent("remoteappclosed",{detail:{application:this.options.remoteApp}})))},Po))}get remoteAppPrimaryWindow(){let e=null,t=-1;for(let s of this.remoteAppWindows.values()){if(!us(s)||s.showState===be.HIDDEN)continue;let r=(s.width||0)*(s.height||0);r>t&&(e=s,t=r)}return e}#v(e){let t=this.remoteAppPrimaryWindow;return!!t&&t.windowId===e.windowId}#N(e){let t=this.remoteAppFit;return t?Math.abs(e.x||0)<=dt&&Math.abs(e.y||0)<=dt&&Math.abs((e.width||0)-t.width)<=dt&&Math.abs((e.height||0)-t.height)<=dt:!0}#A(){this.remoteAppFitTimer||(this.remoteAppFitTimer=setTimeout(()=>{this.remoteAppFitTimer=null,this.#L()},Mo))}#L(){let e=this.remoteAppFit;if(!e||!this.rail||this.state!==N.CONNECTED)return;this.rail.setWorkArea(e.width,e.height);let t=this.remoteAppPrimaryWindow;if(!t||t.showState===be.MINIMIZED)return;let s=`${t.width||0}x${t.height||0}+${t.x||0}+${t.y||0}`;if(s!==e.lastGeometry&&(e.attempts=0),e.lastGeometry=s,!(e.attempts>=Ho||e.moves>=Ko)){if(e.attempts+=1,e.moves+=1,t.showState===be.MAXIMIZED){console.info("[RDP] Restoring the maximized RemoteApp window before fitting it"),this.rail.sysCommand(t.windowId,as.RESTORE);return}console.info("[RDP] Fitting the RemoteApp window to the browser",{windowId:t.windowId,from:`${t.width||0}x${t.height||0}+${t.x||0}+${t.y||0}`,to:`${e.width}x${e.height}+0+0`,attempt:e.attempts}),this.rail.activate(t.windowId),this.rail.moveWindow(t.windowId,{left:0,top:0,right:e.width,bottom:e.height})}}#I(){let e=this.remoteAppPrimaryWindow;if(!e||!e.width||!e.height||e.showState===be.MINIMIZED||e.showState===be.HIDDEN)return;let t=Math.max(0,Math.min(this.desktopWidth-1,e.x||0)),s=Math.max(0,Math.min(this.desktopHeight-1,e.y||0)),r={x:t,y:s,width:Math.max(1,Math.min(this.desktopWidth-t,e.width)),height:Math.max(1,Math.min(this.desktopHeight-s,e.height))},i=this.remoteAppViewport;i&&i.x===r.x&&i.y===r.y&&i.width===r.width&&i.height===r.height||(this.remoteAppViewport=r,this.dispatchEvent(new CustomEvent("remoteappviewport",{detail:r})))}fitRemoteApp(e,t){if(!this.options.remoteApp?.program||!Number.isFinite(e)||!Number.isFinite(t))return!1;let s={width:Math.max(Ms,Math.min(this.desktopWidth,Math.floor(e))),height:Math.max(Ms,Math.min(this.desktopHeight,Math.floor(t))),attempts:0,moves:0,lastGeometry:""};return this.remoteAppFit=s,this.#A(),!0}#U(){this.state!==N.CONNECTED&&(this.state=N.CONNECTED,console.info("[RDP] Session established",{desktop:`${this.desktopWidth}x${this.desktopHeight}`,encryption:this.security.encryptionEnabled?`RC4 ${this.security.keys.keyLength*8}-bit`:"TLS transport"}),this.dispatchEvent(new CustomEvent("ready",{detail:{width:this.desktopWidth,height:this.desktopHeight}})),this.setOutputEnabled(!0),this.refresh())}#O(e){let t=e[0]>>6&3,s=e[1]&128?2:1,r=e.subarray(1+s);t&2&&(r=this.security.decryptFastPath(r));let i=new _(r);for(;i.remaining>=3;){let o=i.u8(),a=o&15,c=o>>4&3;o>>6&3&2&&i.u8();let m=i.u16le(),y=i.raw(Math.min(m,i.remaining));if(c!==0){if(c===2&&(this.fastPathFragments=[]),this.fastPathFragments.push(y.slice()),c!==1)continue;y=b(...this.fastPathFragments),this.fastPathFragments=[]}this.#k(a,y)}}#k(e,t){let s=new _(t);switch(e){case 1:{s.u16le();let r=zt(s);r.length>0&&this.dispatchEvent(new CustomEvent("bitmap",{detail:{rects:r,palette:this.palette}}));return}case 2:this.palette=Qt(s),this.dispatchEvent(new CustomEvent("palette",{detail:this.palette}));return;case 5:this.dispatchEvent(new CustomEvent("pointer",{detail:{kind:"system",hidden:!0}}));return;case 6:this.dispatchEvent(new CustomEvent("pointer",{detail:{kind:"system",hidden:!1}}));return;case 8:this.dispatchEvent(new CustomEvent("pointer",{detail:{kind:"position",x:s.u16le(),y:s.u16le()}}));return;case 9:case 10:case 11:{let r={9:6,10:7,11:8}[e],i=new Uint8Array([r,0,0,0]);this.dispatchEvent(new CustomEvent("pointer",{detail:jt(new _(b(i,t)))}));return}default:return}}#D(e,t){let s=this.channelReassemblers.get(e);s||(s=new ct,this.channelReassemblers.set(e,s));let r=s.push(t);if(r){if(e===Jt.name){this.#x().receive(r);return}e===en.name&&this.#P().receive(r)}}#S(e,t){let s=[...this.channelNamesById].find(([,r])=>r===e)?.[0];if(s===void 0)return!1;for(let r of Es(t,Bt,ms))this.#n(Ht(this.userId,s,this.security.wrap(r)));return!0}#P(){return this.rail?this.rail:(this.rail=new at({application:this.options.remoteApp,width:this.remoteAppFit?.width||this.desktopWidth,height:this.remoteAppFit?.height||this.desktopHeight,send:e=>this.#S(en.name,e),onReady:({buildNumber:e,extended:t,flags:s})=>{console.info("[RDP] RemoteApp channel ready",{buildNumber:e,extended:!!t,flags:s||0}),this.dispatchEvent(new CustomEvent("remoteappready",{detail:{application:this.options.remoteApp}}))},onResult:e=>{let t={...e,application:this.options.remoteApp};this.dispatchEvent(new CustomEvent("remoteappresult",{detail:t})),e.ok?console.info("[RDP] Remote application launched",t):this.#i(new Error(e.message))}}),this.rail)}#x(){return this.clipboard?this.clipboard:(this.clipboard=new it({send:e=>this.#S(Jt.name,e),log:(e,t)=>console.info(`[RDP] ${e}`,t)}),this.clipboard.addEventListener("text",e=>{this.dispatchEvent(new CustomEvent("clipboard",{detail:e.detail}))}),this.clipboard)}setClipboardText(e){return!this.connected||!this.channelNamesById.size?Promise.resolve(!1):this.#x().setLocalText(e||"")}get clipboardShared(){return!!this.clipboard?.ready}pasteToHost(e){if(!e||!this.connected)return Promise.resolve(!1);let t=()=>{this.connected&&(this.sendKeyByCode("ControlLeft",!0),this.sendKeyByCode("KeyV",!0),this.sendKeyByCode("KeyV",!1),this.sendKeyByCode("ControlLeft",!1))};return this.setClipboardText(e).then(s=>(s?t():this.sendUnicode(e),!0))}#M(e,t){this.#d(this.security.wrap(Vt(e,this.userId,t)))}#w(e,t){this.#d(this.security.wrap(xs(this.shareId,this.userId,e,t)))}get connected(){return this.state===N.CONNECTED}#f(e){!this.connected||e.length===0||this.#w(M.INPUT,Rs(e))}sendKeyByCode(e,t){let s=Zt(e);return s?(this.#f([$t(s.scancode,t,s.extended)]),!0):!1}sendUnicode(e){let t=[];for(let s of e)for(let r=0;r<s.length;r++){let i=s.charCodeAt(r);t.push(qt(i,!0)),t.push(qt(i,!1))}for(let s=0;s<t.length;s+=40)this.#f(t.slice(s,s+40))}sendCtrlAltDel(){let e=Ps.map(({code:t,pressed:s})=>{let r=Zt(t);return $t(r.scancode,s,r.extended)});this.#f(e)}sendMouseMove(e,t){this.#f([ut(te.MOVE,e,t)])}sendMouseButton(e,t,s,r){let i={0:te.BUTTON1,1:te.BUTTON3,2:te.BUTTON2}[e];if(i===void 0){let o=e===3?1:2;this.#f([vs(o|(t?te.DOWN:0),s,r)]);return}this.#f([ut(i|(t?te.DOWN:0),s,r)])}sendWheel(e,t,s,r=!1){let i=As(e,r);i&&this.#f([ut(i,t,s)])}sendKeyboardSync(e){this.toggleFlags=e>>>0,this.#f([Xt(this.toggleFlags)])}refresh(e){!this.connected||!this.refreshRectSupported||this.#w(M.REFRESH_RECT,Ns([e||{left:0,top:0,right:this.desktopWidth-1,bottom:this.desktopHeight-1}]))}setOutputEnabled(e){this.connected&&this.#w(M.SUPPRESS_OUTPUT,Ls(e,{left:0,top:0,right:this.desktopWidth-1,bottom:this.desktopHeight-1}))}};function Fo(n){return(n&192)!==192?n>>5:(n&240)===240?n:n>>4}function Bo(n,e,t,s){let r=new Uint32Array(e*t),i=s>=4?4294967295:(1<<s*8)-1,o=0,a=0,c=i,h=!1,m=!0,y=()=>{let f=0;for(let l=0;l<s;l++)f|=n[o+l]<<l*8;return o+=s,f>>>0},E=f=>{let l=n[o];if(f===2){let S=l&31;return S===0?(o+=2,n[o-1]+1):(o+=1,S*8)}if(f===13){let S=l&15;return S===0?(o+=2,n[o-1]+1):(o+=1,S*8)}if(f===0||f===1||f===3||f===4){let S=l&31;return S===0?(o+=2,n[o-1]+32):(o+=1,S)}if(f===12||f===14){let S=l&15;return S===0?(o+=2,n[o-1]+16):(o+=1,S)}let A=n[o+1]|n[o+2]<<8;return o+=3,A},w=(f,l)=>{let A=1;for(let S=0;S<l;S++){if(m)r[a]=f&A?c:0;else{let T=r[a-e];r[a]=f&A?(T^c)>>>0:T}a++,A=A<<1&255}};for(;o<n.length&&a<r.length;){m&&a>=e&&(m=!1);let f=Fo(n[o]);if(f===0||f===240){let l=E(f);if(m)for(h&&(r[a++]=c,l--);l-- >0&&a<r.length;)r[a++]=0;else for(h&&(r[a]=(r[a-e]^c)>>>0,a++,l--);l-- >0&&a<r.length;)r[a]=r[a-e],a++;h=!0;continue}switch(h=!1,f){case 1:case 241:case 12:case 246:{let l=E(f);if((f===12||f===246)&&(c=y()),m)for(;l-- >0&&a<r.length;)r[a++]=c;else for(;l-- >0&&a<r.length;)r[a]=(r[a-e]^c)>>>0,a++;break}case 14:case 248:{let l=E(f),A=y(),S=y();for(;l-- >0&&a<r.length-1;)r[a++]=A,r[a++]=S;break}case 3:case 243:{let l=E(f),A=y();for(;l-- >0&&a<r.length;)r[a++]=A;break}case 2:case 242:case 13:case 247:{let l=E(f);for((f===13||f===247)&&(c=y());l>8;)w(n[o++],8),l-=8;l>0&&w(n[o++],l);break}case 4:case 244:{let l=E(f);for(;l-- >0&&a<r.length;)r[a++]=y();break}case 249:o++,w(3,8);break;case 250:o++,w(5,8);break;case 253:o++,r[a++]=i;break;case 254:o++,r[a++]=0;break;default:throw new Error(`RDP: unsupported bitmap compression order 0x${f.toString(16)}`)}}return r}function Go(n,e){if(e<=0)return n;let t=Math.floor(n.length/e);if(t<2)return n;let s=new Uint32Array(n.length);for(let r=0;r<t;r++)s.set(n.subarray(r*e,(r+1)*e),(t-1-r)*e);return s}function Wo(n,e,t,s){let r=new Uint32Array(e*t);for(let i=0;i<t;i++){let o=(t-1-i)*e,a=i*e*s;for(let c=0;c<e;c++){let h=0;for(let m=0;m<s;m++)h|=n[a+m]<<m*8;r[o+c]=h>>>0,a+=s}}return r}function Vo(n,e,t){let s=new Uint8ClampedArray(n.length*4);for(let r=0;r<n.length;r++){let i=n[r],o,a,c;switch(e){case 15:o=(i>>10&31)*255/31,a=(i>>5&31)*255/31,c=(i&31)*255/31;break;case 16:o=(i>>11&31)*255/31,a=(i>>5&63)*255/63,c=(i&31)*255/31;break;case 8:{let m=(i&255)*3;o=t?t[m]:i,a=t?t[m+1]:i,c=t?t[m+2]:i;break}default:o=i>>16&255,a=i>>8&255,c=i&255;break}let h=r*4;s[h]=o,s[h+1]=a,s[h+2]=c,s[h+3]=255}return s}function Hs(n,e){let t=Math.max(1,Math.ceil(n.bitsPerPixel/8)),s=n.compressed?Go(Bo(n.data,n.width,n.height,t),n.width):Wo(n.data,n.width,n.height,t);return Vo(s,n.bitsPerPixel,e)}var tn=/Mac|iPod|iPhone|iPad/.test(globalThis.navigator?.platform||globalThis.navigator?.userAgent||""),Ks={MetaLeft:"ControlLeft",MetaRight:"ControlRight"},Fs=60,Yo=16,Bs=20,$o=8,qo=1,pt=class{constructor(e){this.container=e,this.canvas=document.createElement("canvas"),this.canvas.tabIndex=0,this.canvas.style.display="block",this.canvas.style.position="absolute",this.canvas.style.outline="none",this.canvas.style.imageRendering="auto",this.canvas.style.boxShadow="none",this.context=this.canvas.getContext("2d",{alpha:!1}),this.viewportElement=document.createElement("div"),this.viewportElement.style.position="relative",this.viewportElement.style.overflow="hidden",this.viewportElement.style.margin="auto",this.viewportElement.style.background="#000",this.viewportElement.style.boxShadow="0 10px 30px rgba(0, 0, 0, 0.8)",this.viewportElement.appendChild(this.canvas),e.replaceChildren(this.viewportElement),this.scrollHost=e.parentElement||e,this.width=0,this.height=0,this.viewport={x:0,y:0,width:0,height:0},this.scale=1,this.scaleViewport=!0,this.zoom=1,this.userZoomed=!1,this.viewOnly=!1,this.client=null,this.palette=null,this.cursorCache=new Map,this.heldKeys=new Set,this.keyboardSynced=!1,this.onWindowResize=()=>this.applyScale(),window.addEventListener("resize",this.onWindowResize),this.resizeObserver=typeof ResizeObserver=="function"?new ResizeObserver(()=>this.applyScale()):null,this.resizeObserver?.observe(this.scrollHost)}resize(e,t){this.width=e,this.height=t,this.canvas.width=e,this.canvas.height=t,this.context.fillStyle="#000",this.context.fillRect(0,0,e,t),this.setViewport({x:0,y:0,width:e,height:t})}setViewport({x:e=0,y:t=0,width:s,height:r}={}){if(!this.width||!this.height)return;let i=Math.max(0,Math.min(this.width-1,Math.floor(e))),o=Math.max(0,Math.min(this.height-1,Math.floor(t)));this.viewport={x:i,y:o,width:Math.max(1,Math.min(this.width-i,Math.floor(s||this.width))),height:Math.max(1,Math.min(this.height-o,Math.floor(r||this.height)))},this.canvas.dataset.viewport=[this.viewport.x,this.viewport.y,this.viewport.width,this.viewport.height].join(","),this.applyScale()}#e(){let e=this.scrollHost;return{width:e.clientWidth||this.container.clientWidth||1,height:e.clientHeight||this.container.clientHeight||1}}#t(e=this.#e()){let t=Math.min(e.width/this.viewport.width,e.height/this.viewport.height);return Number.isFinite(t)&&t>0?t:1}#r(){return 1}applyScale(){if(!this.width||!this.height)return;let e=this.viewport,t=this.#e(),s=this.#t(t);this.userZoomed||(this.zoom=this.#r());let r=(this.scaleViewport?s:1)*this.zoom;this.scale=r,this.viewportElement.style.width=`${e.width*r}px`,this.viewportElement.style.height=`${e.height*r}px`,this.canvas.style.width=`${this.width*r}px`,this.canvas.style.height=`${this.height*r}px`,this.canvas.style.left=`${-e.x*r}px`,this.canvas.style.top=`${-e.y*r}px`}setZoom(e,t=null){let s=Math.min($o,Math.max(qo,e));if(!Number.isFinite(s)||s===this.zoom)return;let r=this.scrollHost,i=this.scale,o=r.getBoundingClientRect(),a=t?t.x-o.left:o.width/2,c=t?t.y-o.top:o.height/2,h=r.scrollLeft+a,m=r.scrollTop+c;this.zoom=s,this.applyScale();let y=i>0?this.scale/i:1;r.scrollLeft=h*y-a,r.scrollTop=m*y-c}panBy(e,t){let s=this.scrollHost,r=s.scrollLeft,i=s.scrollTop;return s.scrollLeft=r-e,s.scrollTop=i-t,{x:r-s.scrollLeft,y:i-s.scrollTop}}canPan(){if(this.zoom<=1.05)return!1;let e=this.scrollHost;return e.scrollWidth>e.clientWidth+2||e.scrollHeight>e.clientHeight+2}setScaleViewport(e){this.scaleViewport=e,e||(this.userZoomed=!1),this.applyScale()}resetZoom(){this.userZoomed=!1,this.zoom=1,this.applyScale();let e=this.scrollHost;e.scrollLeft=0,e.scrollTop=0}drawRects(e,t){t&&(this.palette=t);for(let s of e)if(!(s.width===0||s.height===0))try{let r=Hs(s,this.palette),i=new ImageData(r,s.width,s.height);this.context.putImageData(i,s.left,s.top)}catch(r){console.warn("[RDP] Dropped an undecodable bitmap rectangle",{geometry:`${s.width}x${s.height}+${s.left}+${s.top}`,bitsPerPixel:s.bitsPerPixel,compressed:s.compressed,error:r instanceof Error?r.message:String(r)})}}#n(e){let{width:t,height:s,xorBpp:r,xorMask:i,andMask:o,hotSpotX:a,hotSpotY:c}=e;if(!t||!s)return null;let h=Math.ceil(t*r/8/2)*2,m=Math.ceil(t/8/2)*2,y=new Uint8ClampedArray(t*s*4);for(let l=0;l<s;l++){let A=s-1-l;for(let S=0;S<t;S++){let T=o[A*m+(S>>3)],u=T!==void 0&&(T&128>>(S&7))!==0,d=0,x=0,R=0,C=u?0:255;if(r===1)d=x=R=i[A*h+(S>>3)]&128>>(S&7)?255:0;else{let v=r/8,U=A*h+S*v;if(r===16){let Q=i[U]|i[U+1]<<8;d=(Q>>11&31)*255/31,x=(Q>>5&63)*255/63,R=(Q&31)*255/31}else R=i[U]||0,x=i[U+1]||0,d=i[U+2]||0,r===32&&i[U+3]!==void 0&&o.length===0&&(C=i[U+3])}let L=(l*t+S)*4;y[L]=d,y[L+1]=x,y[L+2]=R,y[L+3]=C}}let E=document.createElement("canvas");E.width=t,E.height=s,E.getContext("2d").putImageData(new ImageData(y,t,s),0,0);let w=Math.min(a||0,t-1),f=Math.min(c||0,s-1);return`url(${E.toDataURL("image/png")}) ${w} ${f}, default`}applyPointer(e){if(e.kind==="system"){this.canvas.style.cursor=e.hidden?"none":"default";return}if(e.kind!=="position"){if(e.kind==="cached"){let t=this.cursorCache.get(e.cacheIndex);t&&(this.canvas.style.cursor=t);return}if(e.kind==="bitmap")try{let t=this.#n(e);if(!t)return;this.cursorCache.set(e.cacheIndex,t),this.canvas.style.cursor=t}catch(t){console.warn("[RDP] Could not build a cursor from the host pointer update",t)}}}#s(e){let t=this.canvas.getBoundingClientRect(),s=this.width/(t.width||1),r=this.height/(t.height||1);return{x:Math.max(0,Math.min(this.width-1,(e.clientX-t.left)*s)),y:Math.max(0,Math.min(this.height-1,(e.clientY-t.top)*r))}}#c(e){if(this.keyboardSynced||!this.client)return;this.keyboardSynced=!0;let t=0;e.getModifierState?.("CapsLock")&&(t|=lt.CAPS_LOCK),e.getModifierState?.("NumLock")&&(t|=lt.NUM_LOCK),e.getModifierState?.("ScrollLock")&&(t|=lt.SCROLL_LOCK),this.client.sendKeyboardSync(t)}attachInput(e){this.client=e,this.keyboardSynced=!1;let t=()=>this.client&&this.client.connected&&!this.viewOnly,s=null,r=!1,i=0,o=!1,a=0,c=0,h=0,m=0,y={x:0,y:0},E=0,w=0,f=0,l=null,A=u=>({x:(u[0].clientX+u[1].clientX)/2,y:(u[0].clientY+u[1].clientY)/2}),S=u=>Math.hypot(u[0].clientX-u[1].clientX,u[0].clientY-u[1].clientY),T=()=>{r=!1,s&&t()&&this.client.sendMouseMove(s.x,s.y),s=null};this.handlers={mousemove:u=>{t()&&(s=this.#s(u),r||(r=!0,requestAnimationFrame(T)))},mousedown:u=>{if(this.canvas.focus(),!t())return;u.preventDefault();let{x:d,y:x}=this.#s(u);this.client.sendMouseButton(u.button,!0,d,x)},mouseup:u=>{if(!t())return;u.preventDefault();let{x:d,y:x}=this.#s(u);this.client.sendMouseButton(u.button,!1,d,x)},contextmenu:u=>u.preventDefault(),wheel:u=>{if(!t())return;u.preventDefault();let d=u.deltaY;if(u.deltaMode===WheelEvent.DOM_DELTA_LINE&&(d*=Yo),u.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(d*=Math.max(1,this.canvas.clientHeight||this.height)),!d||(i&&Math.sign(i)!==Math.sign(d)&&(i=0),i+=d,Math.abs(i)<Fs))return;let x=Math.sign(i);i-=x*Fs;let{x:R,y:C}=this.#s(u);this.client.sendWheel(x,R,C)},touchstart:u=>{if(this.canvas.focus(),!!t()){if(u.preventDefault(),u.touches.length===1){l="tap";let d=u.touches[0];a=d.clientX,c=d.clientY;let{x,y:R}=this.#s(d);this.client.sendMouseMove(x,R),this.client.sendMouseButton(0,!0,x,R),o=!0}else if(u.touches.length===2){if(l="undecided",o){let{x:R,y:C}=this.#s({clientX:a,clientY:c});this.client.sendMouseButton(0,!1,R,C),o=!1}let d=A(u.touches),x=S(u.touches);y={x:d.x,y:d.y},E=x,h=d.y,m=d.x,w=x,f=0}}},touchmove:u=>{if(t()){if(u.preventDefault(),u.touches.length===1&&l==="tap"){let d=u.touches[0];a=d.clientX,c=d.clientY;let{x,y:R}=this.#s(d);this.client.sendMouseMove(x,R)}else if(u.touches.length===2){let d=A(u.touches),x=d.x,R=d.y,C=S(u.touches),L=h-R,v=m-x;h=R,m=x;let U=Math.hypot(x-y.x,R-y.y),Q=Math.abs(C-E),me=E>0?C/E:1;if((l==="undecided"||l==="gesture")&&(Q>20&&Math.abs(me-1)>.15&&Q>U*.8?l="pinch":U>8&&(l="scroll")),l==="pinch")w>0&&Math.abs(C-w)>1&&(this.userZoomed=!0,this.setZoom(this.zoom*(C/w),{x,y:R})),w=C;else if(l==="scroll"){if(w=C,this.canPan()){this.panBy(v*-1,L*-1),f=0;return}for(L&&f&&Math.sign(f)!==Math.sign(L)&&(f=0),f+=L;Math.abs(f)>=Bs;){let le=Math.sign(f);f-=le*Bs;let{x:Ne,y:ue}=this.#s({clientX:x,clientY:R});this.client.sendWheel(le,Ne,ue)}}}}},touchend:u=>{if(t())if(u.preventDefault(),u.touches.length===0){if(o){let{x:d,y:x}=this.#s({clientX:a,clientY:c});this.client.sendMouseButton(0,!1,d,x),o=!1}l==="pinch"&&this.zoom<=1.05&&this.resetZoom(),l=null,f=0,w=0}else u.touches.length===1&&(l==="gesture"||l==="pinch"||l==="scroll"||l==="undecided")&&(l==="pinch"&&this.zoom<=1.05&&this.resetZoom(),l=null,w=0,f=0)},touchcancel:u=>{if(t()){if(o){let{x:d,y:x}=this.#s({clientX:a,clientY:c});this.client.sendMouseButton(0,!1,d,x),o=!1}l==="pinch"&&this.zoom<=1.05&&this.resetZoom(),l=null,f=0,w=0}},keydown:u=>{if(!t()||(this.#c(u),this.#a(u)))return;let d=this.#i(u.code);if(this.client.sendKeyByCode(d,!0)){if(u.preventDefault(),tn&&u.metaKey&&!Ks[u.code]){this.client.sendKeyByCode(d,!1);return}this.heldKeys.add(d)}},keyup:u=>{if(!t()||this.#a(u))return;let d=this.#i(u.code);this.client.sendKeyByCode(d,!1)&&(this.heldKeys.delete(d),u.preventDefault())},paste:u=>{if(!t())return;let d=u.target,x=d instanceof Node&&this.container.contains(d);if(document.activeElement!==this.canvas&&!x)return;u.preventDefault();let R=u.clipboardData?.getData("text/plain")||"";R&&this.client.pasteToHost(R)},blur:()=>this.releaseAllKeys()},this.canvas.addEventListener("mousemove",this.handlers.mousemove),this.canvas.addEventListener("mousedown",this.handlers.mousedown),this.canvas.addEventListener("mouseup",this.handlers.mouseup),this.canvas.addEventListener("contextmenu",this.handlers.contextmenu),this.canvas.addEventListener("wheel",this.handlers.wheel,{passive:!1}),this.canvas.addEventListener("touchstart",this.handlers.touchstart,{passive:!1}),this.canvas.addEventListener("touchmove",this.handlers.touchmove,{passive:!1}),this.canvas.addEventListener("touchend",this.handlers.touchend,{passive:!1}),this.canvas.addEventListener("touchcancel",this.handlers.touchcancel,{passive:!1}),this.canvas.addEventListener("keydown",this.handlers.keydown),this.canvas.addEventListener("keyup",this.handlers.keyup),this.canvas.addEventListener("blur",this.handlers.blur),document.addEventListener("paste",this.handlers.paste)}#i(e){return tn&&Ks[e]||e}#a(e){return e.code!=="KeyV"?!1:tn?e.metaKey:e.ctrlKey}releaseAllKeys(){if(this.client){for(let e of this.heldKeys)this.client.sendKeyByCode(e,!1);this.heldKeys.clear()}}focus(){this.canvas.focus()}blur(){this.canvas.blur()}destroy(){this.releaseAllKeys(),window.removeEventListener("resize",this.onWindowResize),this.resizeObserver?.disconnect(),this.handlers&&(this.canvas.removeEventListener("mousemove",this.handlers.mousemove),this.canvas.removeEventListener("mousedown",this.handlers.mousedown),this.canvas.removeEventListener("mouseup",this.handlers.mouseup),this.canvas.removeEventListener("contextmenu",this.handlers.contextmenu),this.canvas.removeEventListener("wheel",this.handlers.wheel),this.canvas.removeEventListener("touchstart",this.handlers.touchstart),this.canvas.removeEventListener("touchmove",this.handlers.touchmove),this.canvas.removeEventListener("touchend",this.handlers.touchend),this.canvas.removeEventListener("touchcancel",this.handlers.touchcancel),this.canvas.removeEventListener("keydown",this.handlers.keydown),this.canvas.removeEventListener("keyup",this.handlers.keyup),this.canvas.removeEventListener("blur",this.handlers.blur),document.removeEventListener("paste",this.handlers.paste)),this.client=null}};var We={vnc:5900,rdp:3389,ssh:22},Dc=We.ssh;var Pc=5*6e4;var Xo={usernameLabel:"Username",usernamePlaceholder:"Windows username",usernameHelp:"Use the Windows account name for this computer.",passwordLabel:"Password",passwordPlaceholder:"Windows password",passwordHelp:"Use the Windows account password. It may be left empty when the host presents its own sign-in screen.",requiresPassword:!1};function zo(n,e){let t=new URLSearchParams({host:e.host,port:String(e.port),security:e.security});return`${n}/rdp-ws?${t}`}function Qo({code:n,reason:e,suffix:t}){return/hybrid_required|requires network level|authenticates before/i.test(e)?`The RDP host signs in before showing a desktop${t}. Enter the Windows username and password and connect again.`:n===1011||/cannot connect|unreachable|tcp error|tcp write/i.test(e)?`The Worker could not keep a TCP connection to the RDP host${t}. Check that Remote Desktop is enabled and listening on this address and port.`:null}var nn=class extends EventTarget{protocol="rdp";constructor(e,t,s={}){super(),this.url=t,this.options=s,this.display=new pt(e),this.display.viewOnly=!!s.viewOnly,this._rfbConnectionState="connecting",this._scaleViewport=s.scaleViewport!==!1,this.display.scaleViewport=this._scaleViewport,this.lastErrorMessage="",this.hostLabel=s.hostLabel||"Remote Desktop",this.#e(s.security||"auto"),this.remoteAppLayoutObserver=s.remoteApp?.program&&typeof ResizeObserver=="function"?new ResizeObserver(()=>this.fitToViewport()):null,this.remoteAppLayoutObserver?.observe(this.display.scrollHost)}#e(e){this.security=e,this.client=new ft(this.url,{width:this.options.width,height:this.options.height,username:this.options.credentials?.username||"",password:this.options.credentials?.password||"",domain:this.options.domain||"",security:e,keyboardLayout:this.options.keyboardLayout||1033,clientName:this.options.clientName||"cf-gateway",remoteApp:this.options.remoteApp||null}),this.client.addEventListener("ready",t=>{let{width:s,height:r}=t.detail;this.display.resize(s,r),this.display.attachInput(this.client),this.display.focus(),this.fitToViewport(),this._rfbConnectionState="connected",this.dispatchEvent(new CustomEvent("connect")),this.dispatchEvent(new CustomEvent("desktopname",{detail:{name:`${this.hostLabel} (${s}x${r})`}}))}),this.client.addEventListener("resize",t=>{let{width:s,height:r}=t.detail;this.display.resize(s,r),this.dispatchEvent(new CustomEvent("desktopname",{detail:{name:`${this.hostLabel} (${s}x${r})`}})),this.fitToViewport()}),this.client.addEventListener("remoteappviewport",t=>{this.display.setViewport(t.detail)}),this.client.addEventListener("bitmap",t=>{this.display.drawRects(t.detail.rects,t.detail.palette),this.dispatchEvent(new CustomEvent("frame",{detail:{rects:t.detail.rects}}))}),this.client.addEventListener("palette",t=>{this.display.palette=t.detail}),this.client.addEventListener("pointer",t=>{this.display.applyPointer(t.detail)}),this.client.addEventListener("clipboard",t=>{this.dispatchEvent(new CustomEvent("clipboard",{detail:{text:t.detail.text}}))}),this.client.addEventListener("remoteappresult",t=>{this.dispatchEvent(new CustomEvent("remoteappresult",{detail:t.detail}))}),this.client.addEventListener("remoteappwindow",t=>{this.dispatchEvent(new CustomEvent("remoteappwindow",{detail:t.detail}))}),this.client.addEventListener("remoteappclosed",t=>{this.dispatchEvent(new CustomEvent("remoteappclosed",{detail:t.detail}))}),this.client.addEventListener("error",t=>{this.lastErrorMessage=t.detail.message}),this.client.addEventListener("close",t=>{this._rfbConnectionState="disconnected",this.remoteAppLayoutObserver?.disconnect(),this.display.destroy(),this.dispatchEvent(new CustomEvent("disconnect",{detail:{clean:!!t.detail.clean,message:this.lastErrorMessage||t.detail.message||"",code:t.detail.code,phase:t.detail.phase}}))})}fitToViewport(){if(!this.options.remoteApp?.program)return!1;let e=this.display.container.getBoundingClientRect(),t=Math.floor(e.width||this.options.width||0),s=Math.floor(e.height||this.options.height||0);return t<=0||s<=0?!1:this.client.fitRemoteApp(t,s)}get connected(){return this._rfbConnectionState==="connected"}get canvas(){return this.display?.canvas??null}get socket(){return this.client.socket??null}get _sock(){return{_websocket:this.client.socket}}get scaleViewport(){return this._scaleViewport}set scaleViewport(e){this._scaleViewport=!!e,this.display.setScaleViewport(this._scaleViewport)}get viewOnly(){return this.display.viewOnly}set viewOnly(e){this.display.viewOnly=!!e,e&&this.display.releaseAllKeys()}sendKey(e,t,s){t&&this.client.sendKeyByCode(t,s)||!s||!e||e>=32&&e<=1114111&&this.client.sendUnicode(String.fromCodePoint(e))}sendCtrlAltDel(){this.client.sendCtrlAltDel()}movePointer(e,t){return!this.client?.connected||this.display.viewOnly?!1:(this.client.sendMouseMove(...this.#t(e,t)),!0)}clickPointer(e,t,s=0){if(!this.client?.connected||this.display.viewOnly)return!1;let[r,i]=this.#t(e,t);return this.client.sendMouseMove(r,i),this.pointerButton(r,i,s,!0),this.pointerButton(r,i,s,!1),!0}pointerButton(e,t,s=0,r=!0){if(!this.client?.connected||this.display.viewOnly)return!1;let[i,o]=this.#t(e,t);return this.client.sendMouseButton(s,r,i,o),!0}scrollPointer(e,t,s){if(!this.client?.connected||this.display.viewOnly)return!1;let[r,i]=this.#t(e,t);for(let o=0;o<Math.min(20,Math.abs(s.y));o++)this.client.sendWheel(Math.sign(s.y),r,i,!1);for(let o=0;o<Math.min(20,Math.abs(s.x));o++)this.client.sendWheel(Math.sign(s.x),r,i,!0);return!0}typeText(e){if(!this.client?.connected||this.display.viewOnly||!e)return!1;let t="",s=()=>{t&&(this.client.sendUnicode(t),t="")};for(let r of e)r===`
|
|
2
|
-
`||r==="\r"?(s(),this.client.sendKeyByCode("Enter",!0),this.client.sendKeyByCode("Enter",!1)):r===" "?(s(),this.client.sendKeyByCode("Tab",!0),this.client.sendKeyByCode("Tab",!1)):t+=r;return s(),!0}#t(e,t){return[Math.max(0,Math.min((this.display.width||1)-1,Math.round(e))),Math.max(0,Math.min((this.display.height||1)-1,Math.round(t)))]}get screenGeometry(){return{width:this.display.width,height:this.display.height,viewport:{...this.display.viewport}}}clipboardPasteFrom(e){if(!e)return;let t=this.client.setClipboardText(e);if(!t||typeof t.then!="function"){this.client.sendUnicode(e);return}t.then(s=>{s||this.client.sendUnicode(e)})}pasteText(e){return e?this.client.pasteToHost(e):!1}releaseKeyboard(){this.display.releaseAllKeys(),this.display.blur()}get clipboardShared(){return this.client.clipboardShared}disconnect(){this.remoteAppLayoutObserver?.disconnect(),this.client.disconnect(),this.display.destroy(),this._rfbConnectionState="disconnected"}},Gs={protocol:"rdp",label:"RDP Client",defaultPort:We.rdp,dialog:Xo,buildUrl:zo,createSession:(n,e,t)=>new
|
|
3
|
-
`?65293:t===" "?65289:s;this.#e.sendKey(r,null,!0),this.#e.sendKey(r,null,!1)}return!0}};function ea({code:n,reason:e,suffix:t}){return n===4001||/auth|password|credential/i.test(e)?`VNC authentication failed${t}. Verify the macOS account username and its password.`:n===4002||/apple dh/i.test(e)?`macOS VNC authentication handshake failed${t}.`:n===1011||/cannot connect|unreachable|tcp error|tcp write/i.test(e)?`The Worker could not keep a TCP connection to the VNC host${t}. Check that Screen Sharing is running and listening on this address.`:null}var Ys={protocol:"vnc",label:"VNC Client",defaultPort:We.vnc,dialog:jo,buildUrl:Zo,createSession:(n,e,t)=>new
|
|
4
|
-
`)),this.keepaliveTimer=setInterval(()=>{if(this.socket?.readyState===WebSocket.OPEN&&(this.socket.send(Re),this.sessionId))try{this.#h(new
|
|
5
|
-
`}}));return}case
|
|
6
|
-
`).replace(/\r/g,"")}function Aa(n,e){let t=n.displayFilter;if(!t)return e;t.pending+=Ve(e);let s="";if(t.stage==="before"){let i=t.pending.indexOf(t.begin);if(i===-1)return
|
|
7
|
-
`);return r!==-1&&(s+=t.pending.slice(r+1),n.displayFilter=null),s?oe(s):
|
|
8
|
-
`)}),this.transport.addEventListener("banner",s=>this.#t(s.detail.text)),this.transport.addEventListener("keys",s=>{this.fingerprint=s.detail.fingerprint,this.#e("secured",`Host key ${s.detail.fingerprint} verified.`),this.dispatchEvent(new CustomEvent("secure",{detail:s.detail})),s.detail.firstTime&&this.#p()}),this.transport.addEventListener("hostdisconnect",s=>{this.lastMessage=s.detail.reason}),this.transport.addEventListener("error",s=>{this.lastMessage=s.detail.message,this.dispatchEvent(new CustomEvent("error",{detail:s.detail}))}),this.transport.addEventListener("close",s=>{this.closed||(this.closed=!0,clearTimeout(this.powerShellTimer),this.#
|
|
9
|
-
`).filter(Boolean).pop()||"no detail"}`))}return}let Q=
|
|
1
|
+
function bt(n){return new Uint8Array(n)}var p=class{bytes;view;offset=0;constructor(e=512){this.bytes=bt(e),this.view=new DataView(this.bytes.buffer)}#e(e){if(this.offset+e<=this.bytes.length)return;let t=this.bytes.length*2;for(;t<this.offset+e;)t*=2;let s=bt(t);s.set(this.bytes.subarray(0,this.offset)),this.bytes=s,this.view=new DataView(s.buffer)}u8(e){return this.#e(1),this.view.setUint8(this.offset,e),this.offset+=1,this}u16le(e){return this.#e(2),this.view.setUint16(this.offset,e,!0),this.offset+=2,this}u16be(e){return this.#e(2),this.view.setUint16(this.offset,e,!1),this.offset+=2,this}u32le(e){return this.#e(4),this.view.setUint32(this.offset,e>>>0,!0),this.offset+=4,this}u32be(e){return this.#e(4),this.view.setUint32(this.offset,e>>>0,!1),this.offset+=4,this}raw(e){return this.#e(e.length),this.bytes.set(e,this.offset),this.offset+=e.length,this}zeros(e){return this.#e(e),this.offset+=e,this}utf16le(e,t){let s=this.offset;for(let r of e){let i=r.codePointAt(0)??0;if(t!==void 0&&this.offset-s>=t-2)break;if(i>65535)for(let o=0;o<r.length;o++)this.u16le(r.charCodeAt(o));else this.u16le(i)}return t!==void 0&&this.zeros(t-(this.offset-s)),this}patchU16le(e,t){return this.view.setUint16(e,t,!0),this}patchU16be(e,t){return this.view.setUint16(e,t,!1),this}get length(){return this.offset}take(){return this.bytes.slice(0,this.offset)}},_=class{bytes;view;offset;constructor(e,t=0){this.bytes=e,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.offset=t}get remaining(){return this.bytes.length-this.offset}#e(e){if(this.remaining<e)throw new Error(`RDP: truncated frame (needed ${e} bytes, ${this.remaining} left)`)}u8(){return this.#e(1),this.view.getUint8(this.offset++)}u16le(){this.#e(2);let e=this.view.getUint16(this.offset,!0);return this.offset+=2,e}u16be(){this.#e(2);let e=this.view.getUint16(this.offset,!1);return this.offset+=2,e}u32le(){this.#e(4);let e=this.view.getUint32(this.offset,!0);return this.offset+=4,e}u32be(){this.#e(4);let e=this.view.getUint32(this.offset,!1);return this.offset+=4,e}raw(e){this.#e(e);let t=this.bytes.subarray(this.offset,this.offset+e);return this.offset+=e,t}skip(e){return this.#e(e),this.offset+=e,this}rest(){return this.bytes.subarray(this.offset)}};function b(...n){let e=n.reduce((r,i)=>r+i.length,0),t=bt(e),s=0;for(let r of n)t.set(r,s),s+=r.length;return t}var fr=[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],pr=new Uint32Array(Array.from({length:64},(n,e)=>Math.floor(Math.abs(Math.sin(e+1))*4294967296)));function Qe(n,e){return n<<e|n>>>32-e}function re(n){let e=n.length*8,t=Math.floor((n.length+8)/64)+1,s=new Uint8Array(t*64);s.set(n),s[n.length]=128;let r=new DataView(s.buffer,s.byteLength-8,8);r.setUint32(0,e>>>0,!0),r.setUint32(4,Math.floor(e/4294967296),!0);let i=1732584193,o=4023233417,a=2562383102,c=271733878,h=new Uint32Array(16),m=new DataView(s.buffer,s.byteOffset,s.byteLength);for(let y=0;y<t;y++){for(let T=0;T<16;T++)h[T]=m.getUint32(y*64+T*4,!0);let f=i,l=o,S=a,A=c;for(let T=0;T<64;T++){let u,d;T<16?(u=l&S|~l&A,d=T):T<32?(u=A&l|~A&S,d=(5*T+1)%16):T<48?(u=l^S^A,d=(3*T+5)%16):(u=S^(l|~A),d=7*T%16);let x=A;A=S,S=l;let R=f+u+pr[T]+h[d]|0;l=l+Qe(R,fr[T])|0,f=x}i=i+f|0,o=o+l|0,a=a+S|0,c=c+A|0}let g=new Uint8Array(16),E=new DataView(g.buffer);return E.setUint32(0,i>>>0,!0),E.setUint32(4,o>>>0,!0),E.setUint32(8,a>>>0,!0),E.setUint32(12,c>>>0,!0),g}function Ct(n){let e=n.length*8,t=Math.floor((n.length+8)/64)+1,s=new Uint8Array(t*64);s.set(n),s[n.length]=128;let r=new DataView(s.buffer,s.byteLength-8,8);r.setUint32(0,Math.floor(e/4294967296)),r.setUint32(4,e>>>0);let i=1732584193,o=4023233417,a=2562383102,c=271733878,h=3285377520,m=new Uint32Array(80),g=new DataView(s.buffer,s.byteOffset,s.byteLength);for(let f=0;f<t;f++){for(let d=0;d<16;d++)m[d]=g.getUint32(f*64+d*4);for(let d=16;d<80;d++)m[d]=Qe(m[d-3]^m[d-8]^m[d-14]^m[d-16],1);let l=i,S=o,A=a,T=c,u=h;for(let d=0;d<80;d++){let x,R;d<20?(x=S&A|~S&T,R=1518500249):d<40?(x=S^A^T,R=1859775393):d<60?(x=S&A|S&T|A&T,R=2400959708):(x=S^A^T,R=3395469782);let C=Qe(l,5)+x+u+R+m[d]|0;u=T,T=A,A=Qe(S,30),S=l,l=C}i=i+l|0,o=o+S|0,a=a+A|0,c=c+T|0,h=h+u|0}let E=new Uint8Array(20),y=new DataView(E.buffer);return[i,o,a,c,h].forEach((f,l)=>y.setUint32(l*4,f>>>0)),E}function Z(n){let e=new Uint8Array(256);for(let s=0;s<256;s++)e[s]=s;let t=0;for(let s=0;s<256;s++){t=t+(e[s]??0)+(n[s%n.length]??0)&255;let r=e[s]??0;e[s]=e[t]??0,e[t]=r}return{s:e,i:0,j:0}}function X(n,e){let t=new Uint8Array(e.length),{s}=n,{i:r,j:i}=n;for(let o=0;o<e.length;o++){r=r+1&255,i=i+s[r]&255;let a=s[r];s[r]=s[i],s[i]=a,t[o]=e[o]^s[s[r]+s[i]&255]}return n.i=r,n.j=i,t}function _t(n){let e=0n;for(let t=n.length-1;t>=0;t--)e=e<<8n|BigInt(n[t]);return e}function mr(n,e){let t=new Uint8Array(e),s=n;for(let r=0;r<e;r++)t[r]=Number(s&0xffn),s>>=8n;return t}function yn(n,e,t){let s=1n,r=n%t,i=e;for(;i>0n;)i&1n&&(s=s*r%t),r=r*r%t,i>>=1n;return s}function wn(n,e,t){let s=_t(e),r=_t(t),i=_t(n);if(i>=s)throw new Error("RDP: client random is larger than the server RSA modulus");return mr(yn(i,r,s),e.length)}function gn(n,e,t){let s=y=>{let f=0n;for(let l of y)f=f<<8n|BigInt(l);return f},r=s(e),i=s(t),o=e.length;if(n.length>o-11)throw new Error("TLS: RSA message is too long for this key");let a=new Uint8Array(o);a[0]=0,a[1]=2;let c=o-n.length-3,h=new Uint8Array(c);crypto.getRandomValues(h);for(let y=0;y<c;y++){for(;h[y]===0;)h[y]=Math.max(1,crypto.getRandomValues(new Uint8Array(1))[0]);a[2+y]=h[y]}a[2+c]=0,a.set(n,3+c);let m=yn(s(a),i,r),g=new Uint8Array(o),E=m;for(let y=o-1;y>=0;y--)g[y]=Number(E&0xffn),E>>=8n;return g}var An=new Uint8Array(40).fill(54),Sn=new Uint8Array(48).fill(92),se={NONE:0,BIT_40:1,BIT_128:2,BIT_56:8,FIPS:16};function j(...n){let e=n.reduce((r,i)=>r+i.length,0),t=new Uint8Array(e),s=0;for(let r of n)t.set(r,s),s+=r.length;return t}function ye(n,e,t,s){return re(j(n,Ct(j(e,n,t,s))))}function En(n,e,t){return re(j(n,e,t))}var Er=new Uint8Array([65]),yr=new Uint8Array([66,66]),wr=new Uint8Array([67,67,67]),gr=new Uint8Array([88]),Ar=new Uint8Array([89,89]),Sr=new Uint8Array([90,90,90]);function xn(n,e,t){if(e!==8)return n.slice(0,e);let s=n.slice(0,8);return s[0]=209,t&&(s[1]=38,s[2]=158),s}function xr(n){return n===se.BIT_40||n===se.BIT_56?8:16}function Tn(n,e,t){let s=j(n.subarray(0,24),e.subarray(0,24)),r=j(ye(s,Er,n,e),ye(s,yr,n,e),ye(s,wr,n,e)),i=j(ye(r,gr,n,e),ye(r,Ar,n,e),ye(r,Sr,n,e)),o=xr(t),a=t===se.BIT_40,c=E=>xn(E,o,a),h=c(i.subarray(0,16)),m=c(En(i.subarray(16,32),n,e)),g=c(En(i.subarray(32,48),n,e));return{macKey:h,keyLength:o,is40Bit:a,initialDecryptKey:m.slice(),initialEncryptKey:g.slice(),decryptKey:m,encryptKey:g}}function bn(n,e){let t=new Uint8Array(4);new DataView(t.buffer).setUint32(0,e.length,!0);let s=Ct(j(n,An,t,e));return re(j(n,Sn,s)).subarray(0,8)}function Rt(n,e,t,s){let r=Ct(j(n,An,e)),i=re(j(n,Sn,r)).slice(0,t),o=X(Z(i),i);return xn(o,t,s)}var vt=3,_n=4,Tr=224,br=208,_r=240,Cr=1,Rr=2,vr=3,Cn={SSL_REQUIRED:1,SSL_NOT_ALLOWED:2,SSL_CERT_NOT_ON_SERVER:3,INCONSISTENT_FLAGS:4,HYBRID_REQUIRED:5,SSL_WITH_USER_AUTH_REQUIRED:6},P={RDP:0,SSL:1,HYBRID:2,RDSTLS:4,HYBRID_EX:8},Lr={1:"The host requires TLS. Choose the TLS security option for this target.",2:'The host does not allow TLS. Choose the "RDP (standard)" security option.',3:"The host has no certificate installed, so it cannot negotiate TLS.",4:"The host rejected the requested protocol flags as inconsistent.",5:'The host requires Network Level Authentication (NLA/CredSSP). Turn NLA off on the host, or set its security layer to "RDP".',6:"The host requires TLS with early user authentication, which this gateway does not support."};function Rn(n){let e=new p(32);return e.u8(vt).u8(0).u16be(19),e.u8(14).u8(Tr).u16be(0).u16be(0).u8(0),e.u8(Cr).u8(0).u16le(8).u32le(n),e.take()}function vn(n){let e=new _(n);e.skip(_n),e.u8();let t=e.u8();if(t!==br)throw new Error(`RDP: expected an X.224 connection confirm, got TPDU code 0x${t.toString(16)}`);if(e.skip(5),e.remaining<8)return{selectedProtocol:P.RDP,negotiated:!1};let s=e.u8();if(e.u8(),e.u16le(),s===vr){let r=e.u32le(),i=new Error(Lr[r]||`The host refused the RDP connection (negotiation failure 0x${r.toString(16)}).`);throw i.negotiationFailure=r,i}return s!==Rr?{selectedProtocol:P.RDP,negotiated:!1}:{selectedProtocol:e.u32le(),negotiated:!0}}function we(n){let e=new p(n.length+7);return e.u8(vt).u8(0).u16be(n.length+7),e.u8(2).u8(_r).u8(128),e.raw(n),e.take()}function Ne(n){if(n.length<7)throw new Error("RDP: X.224 data frame is too short");return n.subarray(7)}function Ln(n){let e=[],t=0;for(;n.length-t>=4;){let s,r=!1;if(n[t]===vt){if(s=n[t+2]<<8|n[t+3],s<_n)throw new Error("RDP: malformed TPKT length")}else if(r=!0,s=n[t+1]&128?(n[t+1]&127)<<8|n[t+2]:n[t+1],s<2)throw new Error("RDP: malformed fast-path length");if(n.length-t<s)break;e.push({fastPath:r,frame:n.subarray(t,t+s)}),t+=s}return{frames:e,rest:n.subarray(t)}}var Nr=1,Ir=2,Ur=826364754,Or=6,In=[42,134,72,134,247,13,1,1,1];function de(n,e){let t=e,s=n[t++],r=n[t++];if(r&128){let i=r&127;r=0;for(let o=0;o<i;o++)r=r<<8|n[t++]}return{tag:s,contentStart:t,contentEnd:t+r,next:t+r,content:n.subarray(t,t+r)}}function ge(n){let e=[],t=0;for(;t<n.length;){let s=de(n,t);if(e.push(s),s.next<=t)break;t=s.next}return e}function Un(n,e){e:for(let t=0;t+e.length<=n.length;t++){for(let s=0;s<e.length;s++)if(n[t+s]!==e[s])continue e;return!0}return!1}function Nn(n){let e=0;for(;e<n.length-1&&n[e]===0;)e++;return n.subarray(e).slice().reverse()}function kr(n){let e=de(n,0),t=de(n,e.contentStart);for(let s of ge(t.content)){if(s.tag!==48)continue;let r=ge(s.content);if(r.length<2||r[0].tag!==48||!Un(r[0].content,In)||r[1].tag!==3)continue;let i=de(r[1].content.subarray(1),0),[o,a]=ge(i.content);if(!o||!a)break;return{modulus:Nn(o.content),exponent:Nn(a.content),source:"x509"}}throw new Error("RDP: no RSA public key found in the host X.509 certificate")}function Pr(n){n.u32le(),n.u32le();let e=n.u16le(),t=n.u16le();if(e!==Or)throw new Error(`RDP: unsupported public key blob type 0x${e.toString(16)}`);let s=new _(n.raw(t));if(s.u32le()!==Ur)throw new Error("RDP: the host RSA public key blob is not in RSA1 format");let r=s.u32le();s.u32le(),s.u32le();let i=s.raw(4).slice();if(r<9)throw new Error("RDP: the host RSA modulus is too short");return{modulus:s.raw(r-8).slice(),exponent:i,source:"proprietary"}}function On(n){let e=de(n,0),t=de(n,e.contentStart);for(let s of ge(t.content)){if(s.tag!==48)continue;let r=ge(s.content);if(r.length<2||r[0].tag!==48||!Un(r[0].content,In)||r[1].tag!==3)continue;let i=r[1].content.subarray(1),o=de(i,0),[a,c]=ge(o.content);if(!a||!c)break;let h=m=>{let g=0;for(;g<m.length-1&&m[g]===0;)g++;return m.subarray(g)};return{modulus:h(a.content),exponent:h(c.content),subjectPublicKey:i}}throw new Error("TLS: no RSA public key found in the host certificate")}function kn(n){let e=new _(n),t=e.u32le()&2147483647;if(t===Nr)return Pr(e);if(t===Ir){let s=e.u32le(),r=null;for(let i=0;i<s;i++){let o=e.u32le();r=e.raw(o)}if(!r)throw new Error("RDP: the host sent an empty X.509 certificate chain");return kr(r)}throw new Error(`RDP: unsupported server certificate version ${t}`)}var Ie=771,ae={CHANGE_CIPHER_SPEC:20,ALERT:21,HANDSHAKE:22,APPLICATION_DATA:23},Y={CLIENT_HELLO:1,SERVER_HELLO:2,NEW_SESSION_TICKET:4,CERTIFICATE:11,SERVER_KEY_EXCHANGE:12,CERTIFICATE_REQUEST:13,SERVER_HELLO_DONE:14,CLIENT_KEY_EXCHANGE:16,FINISHED:20},Dr={156:{name:"TLS_RSA_WITH_AES_128_GCM_SHA256",keyLength:16,hash:"SHA-256"},157:{name:"TLS_RSA_WITH_AES_256_GCM_SHA384",keyLength:32,hash:"SHA-384"}},Mr={0:"close_notify",10:"unexpected_message",20:"bad_record_mac",40:"handshake_failure",42:"bad_certificate",46:"certificate_unknown",47:"illegal_parameter",48:"unknown_ca",50:"decode_error",51:"decrypt_error",70:"protocol_version",71:"insufficient_security",80:"internal_error",90:"user_canceled",109:"missing_extension",112:"unrecognized_name"},Hr=n=>new TextEncoder().encode(n);function K(n){return new Uint8Array([n>>8&255,n&255])}function Pn(n){return new Uint8Array([n>>16&255,n>>8&255,n&255])}function Lt(n){let e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,BigInt(n)),e}async function Kr(n,e,t,s){let r=await crypto.subtle.importKey("raw",e,{name:"HMAC",hash:n},!1,["sign"]),i=async h=>new Uint8Array(await crypto.subtle.sign("HMAC",r,h)),o=[],a=0,c=await i(t);for(;a<s;){let h=await i(b(c,t));o.push(h),a+=h.length,c=await i(c)}return b(...o).subarray(0,s)}var Nt=(n,e,t,s,r)=>Kr(n,e,b(Hr(t),s),r),je=class{constructor({send:e,onData:t,onError:s}){this.sendRaw=e,this.onData=t,this.onError=s,this.inbound=new Uint8Array(0),this.transcript=[],this.established=!1,this.serverPublicKey=null,this.suite=null,this.certificates=[],this.readSequence=0n,this.writeSequence=0n,this.readEncrypted=!1,this.writeEncrypted=!1,this.queue=Promise.resolve(),this.handshakeDone=new Promise((r,i)=>{this.resolveHandshake=r,this.rejectHandshake=i})}async start(){this.clientRandom=new Uint8Array(32),crypto.getRandomValues(this.clientRandom);let e=b(K(13),K(10),K(8),new Uint8Array([4,1,5,1,2,1,6,1]),K(65281),K(1),new Uint8Array([0])),t=b(K(Ie),this.clientRandom,new Uint8Array([0]),K(4),K(156),K(157),new Uint8Array([1,0]),K(e.length),e);return await this.#t(Y.CLIENT_HELLO,t),this.handshakeDone}#e(e,t){return b(new Uint8Array([e]),K(Ie),K(t.length),t)}async#t(e,t){let s=b(new Uint8Array([e]),Pn(t.length),t);this.transcript.push(s),await this.#s(ae.HANDSHAKE,s)}async#s(e,t){if(!this.writeEncrypted){this.sendRaw(this.#e(e,t));return}this.sendRaw(this.#e(e,await this.#n(e,t)))}async#n(e,t){let s=this.writeSequence++,r=Lt(s),i=b(this.keys.clientIv,r),o=b(Lt(s),new Uint8Array([e]),K(Ie),K(t.length)),a=await crypto.subtle.encrypt({name:"AES-GCM",iv:i,additionalData:o,tagLength:128},this.keys.clientKey,t);return b(r,new Uint8Array(a))}async#r(e,t){let s=this.readSequence++,r=t.subarray(0,8),i=t.subarray(8),o=b(this.keys.serverIv,r),a=b(Lt(s),new Uint8Array([e]),K(Ie),K(i.length-16)),c=await crypto.subtle.decrypt({name:"AES-GCM",iv:o,additionalData:a,tagLength:128},this.keys.serverKey,i);return new Uint8Array(c)}async#c(e){let{hash:t,keyLength:s}=this.suite;this.masterSecret=await Nt(t,e,"master secret",b(this.clientRandom,this.serverRandom),48);let r=await Nt(t,this.masterSecret,"key expansion",b(this.serverRandom,this.clientRandom),s*2+8),i=new _(r),o=i.raw(s),a=i.raw(s);this.keys={clientKey:await crypto.subtle.importKey("raw",o,"AES-GCM",!1,["encrypt"]),serverKey:await crypto.subtle.importKey("raw",a,"AES-GCM",!1,["decrypt"]),clientIv:i.raw(4).slice(),serverIv:i.raw(4).slice()}}async#i(){let e=await crypto.subtle.digest(this.suite.hash,b(...this.transcript));return new Uint8Array(e)}async#a(e){return Nt(this.suite.hash,this.masterSecret,e,await this.#i(),12)}receive(e){return this.queue=this.queue.then(()=>this.#h(e)).catch(t=>this.#o(t)),this.queue}#o(e){let t=e instanceof Error?e:new Error(String(e));this.rejectHandshake(t),this.onError&&this.onError(t)}async#h(e){for(this.inbound=this.inbound.length===0?e:b(this.inbound,e);this.inbound.length>=5;){let t=this.inbound[0],s=this.inbound[3]<<8|this.inbound[4];if(this.inbound.length<5+s)return;let r=this.inbound.subarray(5,5+s);this.inbound=this.inbound.subarray(5+s).slice();let i=this.readEncrypted&&t!==ae.CHANGE_CIPHER_SPEC?await this.#r(t,r):r;await this.#l(t,i)}}async#l(e,t){if(e===ae.ALERT){let r=t[0],i=t[1],o=Mr[i]||`alert ${i}`;if(o==="close_notify"){this.established=!1;return}throw new Error(`TLS: the host sent a fatal alert: ${o}${r===1?" (warning)":""}`)}if(e===ae.CHANGE_CIPHER_SPEC){this.readEncrypted=!0,this.readSequence=0n;return}if(e===ae.APPLICATION_DATA){this.onData&&t.length>0&&this.onData(t);return}if(e!==ae.HANDSHAKE)return;let s=0;for(;s+4<=t.length;){let r=t[s],i=t[s+1]<<16|t[s+2]<<8|t[s+3],o=t.subarray(s,s+4+i),a=t.subarray(s+4,s+4+i);s+=4+i,r!==Y.FINISHED&&this.transcript.push(o),await this.#p(r,a,o)}}async#p(e,t,s){switch(e){case Y.SERVER_HELLO:{let r=new _(t),i=r.u16be();if(i!==Ie)throw new Error(`TLS: the host chose an unsupported version 0x${i.toString(16)}`);this.serverRandom=r.raw(32).slice(),r.raw(r.u8());let o=r.u16be();if(this.suite=Dr[o],!this.suite)throw new Error(`TLS: the host chose cipher suite 0x${o.toString(16)}, which this client does not implement`);r.u8();return}case Y.CERTIFICATE:{let r=new _(t),i=r.u8()<<16|r.u16be(),o=r.offset+i;for(;r.offset<o;){let a=r.u8()<<16|r.u16be();this.certificates.push(r.raw(a).slice())}if(this.certificates.length===0)throw new Error("TLS: the host sent no certificate");this.serverPublicKey=On(this.certificates[0]);return}case Y.CERTIFICATE_REQUEST:this.certificateRequested=!0;return;case Y.SERVER_KEY_EXCHANGE:throw new Error("TLS: the host chose an ephemeral key exchange, which this client does not implement");case Y.SERVER_HELLO_DONE:await this.#E();return;case Y.NEW_SESSION_TICKET:return;case Y.FINISHED:{let r=await this.#a("server finished"),i=t.subarray(0,12);if(!(r.length===i.length&&r.every((a,c)=>a===i[c])))throw new Error("TLS: the host Finished message did not verify");this.transcript.push(s),this.established=!0,this.resolveHandshake({cipherSuite:this.suite.name,certificates:this.certificates,publicKey:this.serverPublicKey});return}default:return}}async#E(){this.certificateRequested&&await this.#t(Y.CERTIFICATE,Pn(0));let e=new Uint8Array(48);crypto.getRandomValues(e),e[0]=3,e[1]=3;let t=gn(e,this.serverPublicKey.modulus,this.serverPublicKey.exponent);await this.#t(Y.CLIENT_KEY_EXCHANGE,b(K(t.length),t)),await this.#c(e),await this.#s(ae.CHANGE_CIPHER_SPEC,new Uint8Array([1])),this.writeEncrypted=!0,this.writeSequence=0n,await this.#t(Y.FINISHED,await this.#a("client finished"))}write(e){return this.queue=this.queue.then(async()=>{if(!this.established)throw new Error("TLS: write before the handshake finished");await this.#s(ae.APPLICATION_DATA,e)}).catch(t=>this.#o(t)),this.queue}};function Fr(n,e){return n<<e|n>>>32-e}function Br(n){let e=Math.floor((n.length+8)/64)+1,t=new Uint8Array(e*64);t.set(n),t[n.length]=128;let s=new DataView(t.buffer),r=n.length*8;s.setUint32(t.length-8,r>>>0,!0),s.setUint32(t.length-4,Math.floor(r/4294967296),!0);let i=1732584193,o=4023233417,a=2562383102,c=271733878,h=new Uint32Array(16),m=[3,7,11,19],g=[0,4,8,12,1,5,9,13,2,6,10,14,3,7,11,15],E=[3,5,9,13],y=[0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15],f=[3,9,11,15];for(let A=0;A<e;A++){for(let C=0;C<16;C++)h[C]=s.getUint32(A*64+C*4,!0);let T=i,u=o,d=a,x=c,R=(C,I)=>Fr(C|0,I);for(let C=0;C<16;C++){let I=u&d|~u&x,v=m[C%4],U=R(T+I+h[C]|0,v);T=x,x=d,d=u,u=U}for(let C=0;C<16;C++){let I=u&d|u&x|d&x,v=E[C%4],U=R(T+I+h[g[C]]+1518500249|0,v);T=x,x=d,d=u,u=U}for(let C=0;C<16;C++){let I=u^d^x,v=f[C%4],U=R(T+I+h[y[C]]+1859775393|0,v);T=x,x=d,d=u,u=U}i=i+T|0,o=o+u|0,a=a+d|0,c=c+x|0}let l=new Uint8Array(16),S=new DataView(l.buffer);return S.setUint32(0,i>>>0,!0),S.setUint32(4,o>>>0,!0),S.setUint32(8,a>>>0,!0),S.setUint32(12,c>>>0,!0),l}function Ae(n,e){let s=n.length>64?re(n):n,r=new Uint8Array(64);r.set(s);let i=new Uint8Array(64),o=new Uint8Array(64);for(let a=0;a<64;a++)i[a]=r[a]^54,o[a]=r[a]^92;return re(b(o,re(b(i,e))))}var Hn=new Uint8Array([78,84,76,77,83,83,80,0]),$={UNICODE:1,REQUEST_TARGET:4,SIGN:16,SEAL:32,NTLM:512,ALWAYS_SIGN:32768,EXTENDED_SESSION_SECURITY:524288,TARGET_INFO:8388608,VERSION:33554432,KEY_128:536870912,KEY_EXCH:1073741824,KEY_56:2147483648},Kn=$.UNICODE|$.REQUEST_TARGET|$.SIGN|$.SEAL|$.NTLM|$.ALWAYS_SIGN|$.EXTENDED_SESSION_SECURITY|$.TARGET_INFO|$.VERSION|$.KEY_128|$.KEY_EXCH|$.KEY_56,Fn=0,Gr=7,Dn=6,Mn=2,Ut=n=>{let e=new p(n.length*2+2);return e.utf16le(n),e.take()},Bn=new Uint8Array([10,0,99,69,0,0,0,15]);function Gn(){let n=new p(40);return n.raw(Hn),n.u32le(1),n.u32le(Kn>>>0),n.u16le(0).u16le(0).u32le(0),n.u16le(0).u16le(0).u32le(0),n.raw(Bn),n.take()}function Wn(n){let e=new DataView(n.buffer,n.byteOffset,n.byteLength);if(e.getUint32(8,!0)!==2)throw new Error("NTLM: the host did not answer with a challenge message");let t=e.getUint16(12,!0),s=e.getUint32(16,!0),r=e.getUint32(20,!0),i=n.subarray(24,32).slice(),o=e.getUint16(40,!0),a=e.getUint32(44,!0);return{flags:r,serverChallenge:i,targetName:n.subarray(s,s+t).slice(),targetInfo:n.subarray(a,a+o).slice()}}function Wr(n){let e=[],t=0,s=new DataView(n.buffer,n.byteOffset,n.byteLength);for(;t+4<=n.length;){let r=s.getUint16(t,!0),i=s.getUint16(t+2,!0),o=n.subarray(t+4,t+4+i);if(t+=4+i,r===Fn)break;e.push({id:r,value:o})}return e}function Vr(n){let e=new p(256);for(let t of n)e.u16le(t.id),e.u16le(t.value.length),e.raw(t.value);return e.u16le(Fn).u16le(0),e.take()}function Yr(){let n=(BigInt(Date.now())+11644473600000n)*10000n,e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,n,!0),e}function Vn({username:n,domain:e,password:t,challenge:s,negotiateBytes:r,challengeBytes:i}){let o=Ae(Br(Ut(t)),Ut(n.toUpperCase()+e)),a=Wr(s.targetInfo),c=a.find(D=>D.id===Gr)?.value.slice()||Yr(),h=a.find(D=>D.id===Dn);if(h){let D=new DataView(h.value.buffer,h.value.byteOffset,4);D.setUint32(0,D.getUint32(0,!0)|Mn,!0)}else{let D=new Uint8Array(4);new DataView(D.buffer).setUint32(0,Mn,!0),a.push({id:Dn,value:D})}let m=Vr(a),g=new Uint8Array(8);crypto.getRandomValues(g);let E=b(new Uint8Array([1,1,0,0,0,0,0,0]),c,g,new Uint8Array(4),m,new Uint8Array(4)),y=Ae(o,b(s.serverChallenge,E)),f=b(y,E),l=Ae(o,y),S=new Uint8Array(16);crypto.getRandomValues(S);let A=X(Z(l),S),T=It(e),u=It(n),d=It(""),x=new Uint8Array(24),R=72,C=R,I=[],v=D=>(I.push({bytes:D,offset:C}),C+=D.length,I[I.length-1]),U=v(x),Q=v(f),me=v(T),le=v(u),Le=v(d),ue=v(A),V=new p(C+16);V.raw(Hn),V.u32le(3);let Ee=D=>{V.u16le(D.bytes.length),V.u16le(D.bytes.length),V.u32le(D.offset+16)};Ee(U),Ee(Q),Ee(me),Ee(le),Ee(Le),Ee(ue),V.u32le(Kn>>>0),V.raw(Bn),V.zeros(16);for(let D of I)V.raw(D.bytes);let Tt=V.take(),dr=Ae(S,b(r,i,Tt));return Tt.set(dr,R),{message:Tt,exportedSessionKey:S,keys:Qr(S)}}function It(n){return n?Ut(n).subarray(0,n.length*2).slice():new Uint8Array(0)}var $r="session key to client-to-server signing key magic constant\0",qr="session key to server-to-client signing key magic constant\0",Xr="session key to client-to-server sealing key magic constant\0",zr="session key to server-to-client sealing key magic constant\0";function Qr(n){let e=t=>re(b(n,new TextEncoder().encode(t)));return{clientSigningKey:e($r),serverSigningKey:e(qr),clientSealing:Z(e(Xr)),serverSealing:Z(e(zr))}}var Ze=class{keys;sendSequence;receiveSequence;constructor(e){this.keys=e,this.sendSequence=0,this.receiveSequence=0}seal(e){let t=new Uint8Array(4);new DataView(t.buffer).setUint32(0,this.sendSequence,!0);let s=Ae(this.keys.clientSigningKey,b(t,e)),r=X(this.keys.clientSealing,e),i=X(this.keys.clientSealing,s.subarray(0,8));return this.sendSequence+=1,b(new Uint8Array([1,0,0,0]),i,t,r)}unseal(e){if(e.length<16)throw new Error("NTLM: sealed message is too short");let t=e.subarray(16),s=X(this.keys.serverSealing,t),r=e.subarray(12,16),i=Ae(this.keys.serverSigningKey,b(r,s)),o=X(this.keys.serverSealing,i.subarray(0,8)),a=e.subarray(4,12);if(!o.every((c,h)=>c===a[h]))throw new Error("NTLM: the host signature did not verify");return this.receiveSequence+=1,s}};var Ot=6,jr="CredSSP Client-To-Server Binding Hash\0",Zr="CredSSP Server-To-Client Binding Hash\0",Jr={3221225581:"The host rejected the username or password (STATUS_LOGON_FAILURE).",3221225582:"The account is not allowed to sign in right now (STATUS_ACCOUNT_RESTRICTION).",3221225583:"The account is outside its permitted logon hours.",3221225584:"The account is not allowed to sign in from this machine (STATUS_INVALID_WORKSTATION).",3221225585:"The account password has expired.",3221225586:"The account is disabled.",3221225819:"The account is not allowed the Remote Desktop logon type -- add it to the Remote Desktop Users group.",3221225875:"The account has expired.",3221226020:"The account must change its password before signing in.",3221226036:"The account is locked out.",2148074252:"The host denied the logon (SEC_E_LOGON_DENIED).",2148074248:"The host rejected the authentication token (SEC_E_INVALID_TOKEN).",2148074242:"The host rejected the CredSSP exchange (SEC_E_UNSUPPORTED_FUNCTION) -- usually a public-key binding mismatch."};function ei(n){return n<128?new Uint8Array([n]):n<=255?new Uint8Array([129,n]):n<=65535?new Uint8Array([130,n>>8,n&255]):new Uint8Array([131,n>>16&255,n>>8&255,n&255])}var et=(n,e)=>b(new Uint8Array([n]),ei(e.length),e),Ue=(...n)=>et(48,b(...n)),ce=n=>et(4,n),z=(n,e)=>et(160|n,e);function Yn(n){let e=[],t=n;do e.unshift(t&255),t>>>=8;while(t>0);return e[0]&128&&e.unshift(0),et(2,new Uint8Array(e))}function J(n,e){let t=n[e],s=e+1,r=n[s++];if(r&128){let i=r&127;r=0;for(let o=0;o<i;o++)r=r<<8|n[s++]}return{tag:t,content:n.subarray(s,s+r),end:s+r}}function ti(n,e=0){if(n.length-e<2)return 0;let t=e+1,s=n[t++];if(s&128){let i=s&127;if(n.length-t<i)return 0;s=0;for(let o=0;o<i;o++)s=s<<8|n[t++]}let r=t-e+s;return n.length-e<r?0:r}function kt({version:n,negoToken:e,authInfo:t,pubKeyAuth:s,clientNonce:r}){let i=[z(0,Yn(n))];return e&&i.push(z(1,Ue(Ue(z(0,ce(e)))))),t&&i.push(z(2,ce(t))),s&&i.push(z(3,ce(s))),r&&i.push(z(5,ce(r))),Ue(...i)}function ni(n){let e=J(n,0),t={version:0,negoToken:null,authInfo:null,pubKeyAuth:null,errorCode:0},s=0;for(;s<e.content.length;){let r=J(e.content,s);s=r.end;let i=r.tag&31;if(i===0){t.version=J(r.content,0).content[0];continue}if(i===1){let o=J(r.content,0),a=J(o.content,0),c=J(a.content,0);t.negoToken=J(c.content,0).content;continue}if(i===2){t.authInfo=J(r.content,0).content;continue}if(i===3){t.pubKeyAuth=J(r.content,0).content;continue}if(i===4){let o=J(r.content,0).content,a=0;for(let c of o)a=(a<<8|c)>>>0;t.errorCode=a;continue}}return t}function si(n,e,t){let s=i=>{let o=new Uint8Array(i.length*2),a=new DataView(o.buffer);for(let c=0;c<i.length;c++)a.setUint16(c*2,i.charCodeAt(c),!0);return o},r=Ue(z(0,ce(s(n))),z(1,ce(s(e))),z(2,ce(s(t))));return Ue(z(0,Yn(1)),z(1,ce(r)))}var Je=class{username;domain;password;serverPublicKey;send;log;inbound;waiters;constructor({username:e,domain:t,password:s,serverPublicKey:r,send:i,log:o}){this.username=e||"",this.domain=t||"",this.password=s||"",this.serverPublicKey=r,this.send=i,this.log=o||(()=>{}),this.inbound=new Uint8Array(0),this.waiters=[]}receive(e){for(this.inbound=this.inbound.length===0?e:b(this.inbound,e);;){let t=ti(this.inbound);if(t===0)return;let s=ni(this.inbound.subarray(0,t));this.inbound=this.inbound.subarray(t).slice();let r=this.waiters.shift();r&&r.resolve(s)}}#e(e=15e3){return new Promise((t,s)=>{let r=setTimeout(()=>s(new Error("CredSSP: the host did not answer within 15s")),e);this.waiters.push({resolve:i=>{clearTimeout(r),t(i)}})})}async#t(e,t){let s=await crypto.subtle.digest("SHA-256",b(new TextEncoder().encode(e),t,this.serverPublicKey));return new Uint8Array(s)}async authenticate(){let e=Gn();this.send(kt({version:Ot,negoToken:e})),this.log("CredSSP","sent NTLM NEGOTIATE");let t=await this.#e();if(t.errorCode)throw new Error(this.#n(t.errorCode));if(!t.negoToken)throw new Error("CredSSP: the host sent no NTLM challenge");let s=t.negoToken.slice(),r=Wn(s),i=new TextDecoder("utf-16le").decode(r.targetName);if(this.log("CredSSP",`received NTLM CHALLENGE from "${i}" (host CredSSP version ${t.version})`),!this.username)return{authenticated:!1,reachedChallenge:!0,hostVersion:t.version,targetName:i,note:"no credentials supplied, stopping after the challenge"};let{message:o,keys:a}=Vn({username:this.username,domain:this.domain,password:this.password,challenge:r,negotiateBytes:e,challengeBytes:s}),c=new Ze(a),h=new Uint8Array(32);crypto.getRandomValues(h);let m=t.version<5,g=m?this.serverPublicKey:await this.#t(jr,h);this.send(kt({version:Ot,negoToken:o,pubKeyAuth:c.seal(g),clientNonce:m?null:h})),this.log("CredSSP",`sent NTLM AUTHENTICATE with the ${m?"legacy":"hashed"} public-key binding`);let E=await this.#e();if(E.errorCode)throw new Error(this.#n(E.errorCode));if(!E.pubKeyAuth)throw new Error("CredSSP: the host returned no public-key confirmation");let y=c.unseal(E.pubKeyAuth),f=m?this.#s():await this.#t(Zr,h);if(y.length!==f.length||!f.every((l,S)=>l===y[S]))throw new Error("CredSSP: the host public-key confirmation did not match. The TLS session is not the one the host authenticated, which is what this check exists to catch.");return this.log("CredSSP","host confirmed the public-key binding"),this.send(kt({version:Ot,authInfo:c.seal(si(this.domain,this.username,this.password))})),this.log("CredSSP","sent credentials"),{authenticated:!0,hostVersion:t.version,targetName:i}}#s(){let e=this.serverPublicKey.slice();return e[0]=e[0]+1&255,e}#n(e){return Jr[e]||`CredSSP: the host reported error 0x${e.toString(16).padStart(8,"0")}.`}};var Se=1001;var he={ERECT_DOMAIN_REQUEST:1,DISCONNECT_PROVIDER_ULTIMATUM:8,ATTACH_USER_REQUEST:10,ATTACH_USER_CONFIRM:11,CHANNEL_JOIN_REQUEST:14,CHANNEL_JOIN_CONFIRM:15,SEND_DATA_REQUEST:25,SEND_DATA_INDICATION:26},ri={0:"The host closed the RDP session (domain disconnected).",1:"The host closed the RDP session (provider initiated).",2:"The host closed the RDP session (token purged).",3:"The host closed the RDP session (user requested).",4:"The host closed the RDP session (channel purged)."};function ii(n){return n>255?new Uint8Array([130,n>>8&255,n&255]):n>127?new Uint8Array([129,n]):new Uint8Array([n])}function ke(n,e){return b(new Uint8Array(n),ii(e.length),e)}function oi(n){let e;return n<128?e=new Uint8Array([n]):n<32768?e=new Uint8Array([n>>8,n&255]):n<8388608?e=new Uint8Array([n>>16,n>>8&255,n&255]):e=new Uint8Array([n>>>24,n>>16&255,n>>8&255,n&255]),ke([2],e)}var Pt=n=>ke([4],n),ai=n=>ke([1],new Uint8Array([n?255:0]));function Dt(n){return ke([48],b(...n.map(oi)))}function Mt(n,e){return e>127?n.u16be(32768|e):n.u8(e),n}function $n(n){let e=n.u8();return e&128?(e&127)<<8|n.u8():e}var ci=new Uint8Array([5,0,20,124,0,1]),hi=new Uint8Array([68,117,99,97]),tt=new Uint8Array([77,99,68,110]);function li(n){let e=new p(n.length+32);return e.u8(0),e.raw(ci),Mt(e,n.length+14),e.u8(0),e.u8(8),e.u8(0),e.u8(16),e.u8(0),e.u8(1),e.u8(192),e.u8(0),e.raw(hi),Mt(e,n.length),e.raw(n),e.take()}function ui(n){for(let e=0;e+4<=n.length;e++)if(n[e]===tt[0]&&n[e+1]===tt[1]&&n[e+2]===tt[2]&&n[e+3]===tt[3]){let t=new _(n,e+4),s=$n(t),r=t.rest();return r.subarray(0,Math.min(s,r.length))}throw new Error("RDP: the host response contained no GCC server data")}var di=[34,2,0,1,0,1,65535,2],fi=[1,1,1,1,0,1,1056,2],pi=[65535,64535,65535,1,0,1,65535,2];function qn(n){let e=li(n),t=b(Pt(new Uint8Array([1])),Pt(new Uint8Array([1])),ai(!0),Dt(di),Dt(fi),Dt(pi),Pt(e));return we(ke([127,101],t))}function Oe(n){let e=n.u8();(e&31)===31&&(e=e<<8|n.u8());let t=n.u8();if(t&128){let s=t&127;t=0;for(let r=0;r<s;r++)t=t<<8|n.u8()}return{tag:e,value:n.raw(t)}}function Xn(n){let e=new _(Ne(n)),t=Oe(e);if(t.tag!==32614)throw new Error(`RDP: expected an MCS connect response, got BER tag 0x${t.tag.toString(16)}`);let s=new _(t.value),r=Oe(s);Oe(s),Oe(s);let i=Oe(s);if(r.value[0]!==0)throw new Error(`RDP: the host rejected the MCS connection (result ${r.value[0]})`);return ui(i.value)}var nt=n=>n<<2;function zn(){let n=new p(8);return n.u8(nt(he.ERECT_DOMAIN_REQUEST)),n.u8(1).u8(0),n.u8(1).u8(0),we(n.take())}function Qn(){return we(new Uint8Array([nt(he.ATTACH_USER_REQUEST)]))}function jn(n){let e=new _(Ne(n)),t=e.u8();if(t>>2!==he.ATTACH_USER_CONFIRM)throw new Error(`RDP: expected an MCS attach-user confirm, got PDU ${t>>2}`);let s=e.u8();if(s!==0)throw new Error(`RDP: the host refused to attach a user (result ${s})`);return{userId:t&2?e.u16be()+Se:Se}}function Ht(n,e){let t=new p(8);return t.u8(nt(he.CHANNEL_JOIN_REQUEST)),t.u16be(n-Se),t.u16be(e),we(t.take())}function Zn(n){let e=new _(Ne(n)),t=e.u8();if(t>>2!==he.CHANNEL_JOIN_CONFIRM)throw new Error(`RDP: expected an MCS channel-join confirm, got PDU ${t>>2}`);let s=e.u8();e.u16be();let r=e.u16be();if(s!==0)throw new Error(`RDP: the host refused to join channel ${r} (result ${s})`);return{channelId:(e.remaining>=2?e.u16be():r)||r}}function Kt(n,e,t){let s=new p(t.length+16);return s.u8(nt(he.SEND_DATA_REQUEST)),s.u16be(n-Se),s.u16be(e),s.u8(112),Mt(s,t.length),s.raw(t),we(s.take())}function Jn(n){let e=new _(Ne(n)),t=e.u8(),s=t>>2;if(s===he.SEND_DATA_INDICATION){e.u16be();let r=e.u16be();e.u8();let i=$n(e),o=e.rest();return{type:"send-data",channelId:r,payload:o.subarray(0,Math.min(i,o.length))}}if(s===he.DISCONNECT_PROVIDER_ULTIMATUM){let r=(t&1)<<1|(e.remaining>0?e.u8()>>7:0);return{type:"disconnect",reason:r,message:ri[r]||`The host closed the RDP session (reason ${r}).`}}return{type:"other",mcsPduType:s}}var mi=49153,Ei=49154,yi=49155,wi=49156,gi=3073,Ai=3074,Si=3075,xi=524292,es=51715,Ti=43523,bi=1,st={NONE:0,LOW:1,CLIENT_COMPATIBLE:2,HIGH:3,FIPS:4};function rt(n,e){let t=new p(e.length+4);return t.u16le(n).u16le(e.length+4).raw(e),t.take()}function _i({width:n,height:e,clientName:t,keyboardLayout:s,selectedProtocol:r}){let i=new p(256);return i.u32le(xi),i.u16le(n),i.u16le(e),i.u16le(es),i.u16le(Ti),i.u32le(s),i.u32le(2600),i.utf16le(t,32),i.u32le(4),i.u32le(0),i.u32le(12),i.zeros(64),i.u16le(es),i.u16le(1),i.u32le(0),i.u16le(16),i.u16le(7),i.u16le(bi),i.zeros(64),i.u8(0),i.u8(0),i.u32le(r),rt(mi,i.take())}function Ci(n){let e=new p(8);return e.u32le(n),e.u32le(0),rt(Ei,e.take())}function Ri(){let n=new p(8);return n.u32le(13),n.u32le(0),rt(wi,n.take())}function vi(n){if(n.length===0)return new Uint8Array(0);let e=new p(4+n.length*12);e.u32le(n.length);for(let t of n){let s=new Uint8Array(8);for(let r=0;r<Math.min(7,t.name.length);r++)s[r]=t.name.charCodeAt(r);e.raw(s),e.u32le(t.options>>>0)}return rt(yi,e.take())}function ts(n){return b(_i(n),Ri(),Ci(n.encryptionMethods),vi(n.channels||[]))}function ns(n){let e=new _(n),t={version:null,encryptionMethod:0,encryptionLevel:st.NONE,serverRandom:null,publicKey:null,ioChannelId:1003,channelIds:[]};for(;e.remaining>=4;){let s=e.u16le(),r=e.u16le();if(r<4||r-4>e.remaining)break;let i=new _(e.raw(r-4));if(s===gi){t.version=i.remaining>=4?i.u32le():null;continue}if(s===Si){t.ioChannelId=i.u16le();let o=i.u16le();for(let a=0;a<o&&i.remaining>=2;a++)t.channelIds.push(i.u16le());continue}if(s===Ai){if(t.encryptionMethod=i.u32le(),t.encryptionLevel=i.u32le(),t.encryptionMethod===0&&t.encryptionLevel===0||i.remaining<8)continue;let o=i.u32le(),a=i.u32le();t.serverRandom=i.raw(o).slice(),t.publicKey=kn(i.raw(a));continue}}return t}var W={MONITOR_READY:1,FORMAT_LIST:2,FORMAT_LIST_RESPONSE:3,FORMAT_DATA_REQUEST:4,FORMAT_DATA_RESPONSE:5,CLIP_CAPS:7},ss=1,Ft=2,Li=4,Pe=1,xe=13,rs=1,Ni=2,is=2,it=32,Ii=400;function Ui(n,e,t=new Uint8Array(0)){let s=new p(t.length+8);return s.u16le(n).u16le(e).u32le(t.length).raw(t),s.take()}function Oi(n){let e=new p(n.length*2+2);return e.utf16le(n),e.u16le(0),e.take()}function ki(n){let e=new Uint16Array(n.length>>1);for(let r=0;r<e.length;r++)e[r]=n[r*2]|n[r*2+1]<<8;let t=e.indexOf(0);t===-1&&(t=e.length);let s="";for(let r=0;r<t;r+=4096)s+=String.fromCharCode(...e.subarray(r,Math.min(r+4096,t)));return s}function Pi(n){let e=new p(n.length+1);for(let t of n){let s=t.codePointAt(0);e.u8(s>255?63:s)}return e.u8(0),e.take()}function Di(n){let e=n.indexOf(0);return e===-1&&(e=n.length),String.fromCharCode(...n.subarray(0,e))}var ot=class extends EventTarget{send;log;ready;longFormatNames;localText;pendingAck;constructor({send:e,log:t}){super(),this.send=e,this.log=t||(()=>{}),this.ready=!1,this.longFormatNames=!0,this.localText="",this.pendingAck=null}#e(e,t,s){this.send(Ui(e,t,s))}setLocalText(e){return this.localText=e,this.ready?(this.#e(W.FORMAT_LIST,0,this.#t(e?[xe,Pe]:[])),this.pendingAck&&this.pendingAck.resolve(!1),new Promise(t=>{let s=0,r=i=>{clearTimeout(s),this.pendingAck?.resolve===r&&(this.pendingAck=null),t(i)};s=setTimeout(()=>{this.log("clipboard format list was not acknowledged"),r(!1)},Ii),this.pendingAck={resolve:r}})):Promise.resolve(!1)}#t(e){let t=e.map(s=>{let r=new p(this.longFormatNames?6:4+it);return r.u32le(s),this.longFormatNames?r.u16le(0):r.zeros(it),r.take()});return b(...t)}receive(e){if(e.length<8)return;let t=new _(e),s=t.u16le(),r=t.u16le(),i=t.u32le(),o=t.rest(),a=o.subarray(0,Math.min(i,o.length));switch(s){case W.CLIP_CAPS:this.#s(a);return;case W.MONITOR_READY:this.#n();return;case W.FORMAT_LIST:this.#r(a,r);return;case W.FORMAT_LIST_RESPONSE:this.pendingAck?.resolve((r&Ft)===0);return;case W.FORMAT_DATA_REQUEST:this.#i(a);return;case W.FORMAT_DATA_RESPONSE:this.#a(a,r);return;default:return}}#s(e){let t=new _(e);if(t.remaining<4)return;let s=t.u16le();t.u16le();for(let r=0;r<s&&t.remaining>=4;r++){let i=t.u16le(),o=t.u16le();if(o<4||o-4>t.remaining)break;let a=new _(t.raw(o-4));if(i===rs&&a.remaining>=8){a.u32le();let c=a.u32le();this.longFormatNames=(c&is)!==0}}}#n(){let e=new p(12);e.u16le(rs).u16le(12),e.u32le(Ni),e.u32le(this.longFormatNames?is:0);let t=new p(20);t.u16le(1).u16le(0),t.raw(e.take()),this.#e(W.CLIP_CAPS,0,t.take()),this.ready=!0,this.#e(W.FORMAT_LIST,0,this.#t(this.localText?[xe,Pe]:[])),this.log("clipboard channel ready",{longFormatNames:this.longFormatNames})}#r(e,t){let s=this.#c(e,t);this.#e(W.FORMAT_LIST_RESPONSE,ss);let r=s.includes(xe)?xe:s.includes(Pe)?Pe:null;if(r===null){this.log("host clipboard holds no text format",{formats:s});return}let i=new p(4);i.u32le(r),this.#e(W.FORMAT_DATA_REQUEST,0,i.take())}#c(e,t){let s=new _(e),r=[],i=!this.longFormatNames||(t&Li)!==0;for(;s.remaining>=4;){if(r.push(s.u32le()),i){if(s.remaining<it)break;s.skip(it);continue}for(;s.remaining>=2&&s.u16le()!==0;);}return r}#i(e){let t=new _(e),s=t.remaining>=4?t.u32le():0;if(s!==xe&&s!==Pe){this.#e(W.FORMAT_DATA_RESPONSE,Ft);return}let r=s===xe?Oi(this.localText):Pi(this.localText);this.#e(W.FORMAT_DATA_RESPONSE,ss,r),this.log("handed the host our clipboard",{formatId:s,characters:this.localText.length})}#a(e,t){if(t&Ft){this.log("the host refused to hand over its clipboard");return}let r=e.length>=2&&e.length%2===0&&e[1]===0?ki(e):Di(e);r&&this.dispatchEvent(new CustomEvent("text",{detail:{text:r}}))}};var q={EXEC:1,ACTIVATE:2,SYSPARAM:3,SYSCOMMAND:4,HANDSHAKE:5,WINDOW_MOVE:8,CLIENT_STATUS:11,EXEC_RESULT:128,HANDSHAKE_EX:19},Mi={0:"The remote application started.",1:"The RemoteApp host could not load its application monitoring hook.",2:"The RemoteApp host could not decode the application launch request.",3:"The requested application is not in the host RemoteApp allowlist.",5:"The requested remote application was not found.",6:"The RemoteApp host could not start the requested application.",7:"The RemoteApp session is locked and cannot start the application."},as={MINIMIZE:61472,MAXIMIZE:61488,CLOSE:61536,RESTORE:61728},be={HIDDEN:0,MINIMIZED:2,MAXIMIZED:3,NORMAL:5},De={TYPE_WINDOW:16777216,STATE_NEW:268435456,STATE_DELETED:536870912,ICON:1073741824,CACHED_ICON:2147483648},B={OWNER:2,TITLE:4,STYLE:8,SHOW:16,WND_RECTS:256,WND_SIZE:1024,WND_OFFSET:2048,CLIENT_AREA_OFFSET:16384,CLIENT_DELTA:32768,CLIENT_AREA_SIZE:65536,RP_CONTENT:131072,ROOT_PARENT:262144,VISIBILITY:524288,VIS_OFFSET:2097152},Hi=1073741824,Ki=128,Fi=134217728,Bi=3,Gi=2,Wi=11,cs=2600,Vi=1024,Te={MOUSE_BUTTON_SWAP:33,DRAG_FULL_WINDOWS:37,WORK_AREA:47,HIGH_CONTRAST:67,KEYBOARD_PREF:69,KEYBOARD_CUES:4107};function Bt(n){let e=new p(n.length*2);return e.utf16le(n),e.take()}function ie(n,e){let t=new p(e.length+4);return t.u16le(n).u16le(e.length+4).raw(e),t.take()}function ee(n){return n|0}function Yi(n=cs){return ie(q.HANDSHAKE,new p(4).u32le(n).take())}function $i(n=Vi){return ie(q.CLIENT_STATUS,new p(4).u32le(n).take())}function at(n,e){return ie(q.SYSPARAM,new p(5).u32le(n).u8(e?1:0).take())}function qi(){let n=new p(16);return n.u32le(Te.HIGH_CONTRAST),n.u32le(126),n.u32le(2),n.u16le(0).u16le(0),ie(q.SYSPARAM,n.take())}function hs(n,e){let t=new p(12);return t.u32le(Te.WORK_AREA),t.u16le(0).u16le(0).u16le(n).u16le(e),ie(q.SYSPARAM,t.take())}function Xi(n,e){return[qi(),at(Te.MOUSE_BUTTON_SWAP,!1),at(Te.KEYBOARD_PREF,!1),at(Te.DRAG_FULL_WINDOWS,!0),at(Te.KEYBOARD_CUES,!1),hs(n,e)]}function zi(n,e=!0){let t=new p(5);return t.u32le(n).u8(e?1:0),ie(q.ACTIVATE,t.take())}function Qi(n,e){let t=new p(6);return t.u32le(n).u16le(e),ie(q.SYSCOMMAND,t.take())}function ji(n,{left:e,top:t,right:s,bottom:r}){let i=new p(12);return i.u32le(n),i.u16le(e&65535).u16le(t&65535),i.u16le(s&65535).u16le(r&65535),ie(q.WINDOW_MOVE,i.take())}function Zi({program:n,workingDir:e="",arguments:t=""}){let s=Bt(n||""),r=Bt(e||""),i=Bt(t||"");if(s.length===0||s.length>520)throw new Error("RemoteApp program must be between 1 and 260 Unicode characters.");if(r.length>520)throw new Error("RemoteApp working directory is too long.");if(i.length>16e3)throw new Error("RemoteApp arguments are too long.");let o=new p(8+s.length+r.length+i.length);return o.u16le(0),o.u16le(s.length).u16le(r.length).u16le(i.length),o.raw(s).raw(r).raw(i),ie(q.EXEC,o.take())}function ls(n){let e="";for(let t=0;t+1<n.length;t+=2){let s=n[t]|n[t+1]<<8;if(s===0)break;e+=String.fromCharCode(s)}return e}function os(n,e){let t=[];for(let s=0;s<e&&n.remaining>=8;s++){let r=n.u16le(),i=n.u16le(),o=n.u16le(),a=n.u16le();t.push({left:r,top:i,right:o,bottom:a})}return t}function Ji(n,e){let t={};if(e&B.OWNER&&(t.ownerWindowId=n.u32le()),e&B.STYLE&&(t.style=n.u32le(),t.extendedStyle=n.u32le()),e&B.SHOW&&(t.showState=n.u8()),e&B.TITLE){let s=n.u16le();t.title=ls(n.raw(Math.min(s,n.remaining)))}return e&B.CLIENT_AREA_OFFSET&&(t.clientOffsetX=ee(n.u32le()),t.clientOffsetY=ee(n.u32le())),e&B.CLIENT_AREA_SIZE&&(t.clientWidth=ee(n.u32le()),t.clientHeight=ee(n.u32le())),e&B.RP_CONTENT&&n.u8(),e&B.ROOT_PARENT&&n.u32le(),e&B.WND_OFFSET&&(t.x=ee(n.u32le()),t.y=ee(n.u32le())),e&B.CLIENT_DELTA&&(n.u32le(),n.u32le()),e&B.WND_SIZE&&(t.width=ee(n.u32le()),t.height=ee(n.u32le())),e&B.WND_RECTS&&(t.windowRects=os(n,n.u16le())),e&B.VIS_OFFSET&&(t.visibleOffsetX=ee(n.u32le()),t.visibleOffsetY=ee(n.u32le())),e&B.VISIBILITY&&(t.visibilityRects=os(n,n.u16le())),t}function us(n){return!(!n||n.ownerWindowId||(n.style||0)&Hi||(n.extendedStyle||0)&(Ki|Fi))}function ds(n){if(n.remaining<6)throw new Error("RDP RemoteApp orders update is truncated.");n.u16le();let e=n.u16le();n.u16le();let t=[];for(let s=0;s<e&&n.remaining>0;s++){let r=n.offset,i=n.u8(),o=i&Bi,a=i>>2;if(o!==Gi||a!==Wi)break;if(n.remaining<6)throw new Error("RDP RemoteApp window-order header is truncated.");let c=n.u16le(),h=n.u32le(),m=r+c;if(c<7||m>n.bytes.length)throw new Error("RDP RemoteApp window order has an invalid size.");let g=!!(h&De.TYPE_WINDOW),E=!!(h&(De.ICON|De.CACHED_ICON));if(g&&!E&&m-n.offset>=4){let y=n.u32le(),f={};try{f=Ji(n,h)}catch(S){console.warn("[RDP] Dropped an unreadable RemoteApp window order",{windowId:y,fieldFlags:`0x${(h>>>0).toString(16)}`,error:S instanceof Error?S.message:String(S)})}let l="update";h&De.STATE_DELETED?l="deleted":h&De.STATE_NEW&&(l="new"),t.push({type:l,windowId:y,fieldFlags:h,...f})}if(n.offset=m,n.offset<=r)break}return t}function eo(n){let e=new _(n),t=[];for(;e.remaining>=4;){let s=e.u16le(),r=e.u16le();if(r<4||r-4>e.remaining)throw new Error("RDP RemoteApp channel delivered a malformed PDU.");let i=new _(e.raw(r-4));if(s===q.HANDSHAKE&&i.remaining>=4){t.push({type:"handshake",buildNumber:i.u32le()});continue}if(s===q.HANDSHAKE_EX&&i.remaining>=8){t.push({type:"handshake",buildNumber:i.u32le(),flags:i.u32le(),extended:!0});continue}if(s===q.EXEC_RESULT&&i.remaining>=12){let o=i.u16le(),a=i.u16le(),c=i.u32le();i.u16le();let h=i.u16le(),m=ls(i.raw(Math.min(h,i.remaining)));t.push({type:"execute-result",flags:o,result:a,rawResult:c,program:m});continue}t.push({type:"unknown",orderType:s,body:i.rest().slice()})}return t}var ct=class{application;width;height;send;onReady;onResult;started;constructor({application:e,width:t,height:s,send:r,onReady:i,onResult:o}){this.application=e,this.width=t,this.height=s,this.send=r,this.onReady=i,this.onResult=o,this.started=!1}receive(e){for(let t of eo(e)){if(t.type==="handshake"){if(this.started)continue;this.started=!0,this.send(Yi(cs)),this.send($i());for(let s of Xi(this.width,this.height))this.send(s);this.send(Zi(this.application)),this.onReady?.(t);continue}t.type==="execute-result"&&this.onResult?.({...t,ok:t.result===0,message:Mi[t.result]||`The RemoteApp host returned launch result 0x${t.result.toString(16).padStart(4,"0")}.`})}}setWorkArea(e,t){return!this.started||e<=0||t<=0||e===this.width&&t===this.height?!1:(this.width=e,this.height=t,this.send(hs(e,t)),!0)}activate(e){return this.started?(this.send(zi(e,!0)),!0):!1}sysCommand(e,t){return this.started?(this.send(Qi(e,t)),!0):!1}moveWindow(e,t){return this.started?(this.send(ji(e,t)),!0):!1}};var fe={INITIALIZED:2147483648,ENCRYPT_RDP:1073741824,COMPRESS_RDP:8388608,SHOW_PROTOCOL:2097152},fs=1,ps=2,ms=16,Gt=1600;function Es(n,e=Gt,t=0){let s=[];for(let r=0;r<n.length||r===0;r+=e){let i=n.subarray(r,r+e),o=t;r===0&&(o|=fs),r+e>=n.length&&(o|=ps);let a=new p(i.length+8);if(a.u32le(n.length).u32le(o).raw(i),s.push(a.take()),n.length===0)break}return s}var ht=class{parts;expectedLength;constructor(){this.parts=[],this.expectedLength=0}push(e){if(e.length<8)return null;let t=new _(e),s=t.u32le(),r=t.u32le(),i=t.rest();if(r&fs&&(this.parts=[],this.expectedLength=s),this.parts.push(i.slice()),!((r&ps)!==0))return null;let a=b(...this.parts);return this.parts=[],this.expectedLength&&this.expectedLength<a.length?a.subarray(0,this.expectedLength):a}};var G={EXCHANGE_PKT:1,TRANSPORT_REQ:2,ENCRYPT:8,RESET_SEQNO:16,IGNORE_SEQNO:32,INFO_PKT:64,LICENSE_PKT:128,LICENSE_ENCRYPT_CS:512,REDIRECTION_PKT:1024,SECURE_CHECKSUM:2048,AUTODETECT_REQ:4096,AUTODETECT_RSP:8192,HEARTBEAT:16384},Wt=4096,Me=class{encryptionMethod;encryptionLevel;keys;encryptState;decryptState;encryptedPdus;decryptedPdus;constructor(){this.encryptionMethod=se.NONE,this.encryptionLevel=st.NONE,this.keys=null,this.encryptState=null,this.decryptState=null,this.encryptedPdus=0,this.decryptedPdus=0}get headerPresent(){return this.encryptionLevel!==st.NONE||this.encryptionMethod!==se.NONE}get encryptionEnabled(){return this.encryptionMethod!==se.NONE&&this.keys!==null}configure(e,t,s,r){if(this.encryptionMethod=e,this.encryptionLevel=t,e!==se.NONE){if(e&se.FIPS)throw new Error("RDP: this host requires FIPS encryption, which this client does not implement");this.keys=Tn(s,r,e),this.encryptState=Z(this.keys.encryptKey),this.decryptState=Z(this.keys.decryptKey)}}#e(){this.keys.encryptKey=Rt(this.keys.initialEncryptKey,this.keys.encryptKey,this.keys.keyLength,this.keys.is40Bit),this.encryptState=Z(this.keys.encryptKey),this.encryptedPdus=0}#t(){this.keys.decryptKey=Rt(this.keys.initialDecryptKey,this.keys.decryptKey,this.keys.keyLength,this.keys.is40Bit),this.decryptState=Z(this.keys.decryptKey),this.decryptedPdus=0}wrap(e,t=0){let s=this.encryptionEnabled;if(!s&&t===0&&!this.headerPresent)return e;let r=new p(e.length+16);return r.u16le(t|(s?G.ENCRYPT:0)),r.u16le(0),s?(r.raw(bn(this.keys.macKey,e)),r.raw(X(this.encryptState,e)),++this.encryptedPdus===Wt&&this.#e(),r.take()):(r.raw(e),r.take())}unwrap(e,t=!1){if(!this.headerPresent&&!t)return{flags:0,payload:e};if(e.length<4)return{flags:0,payload:e};let s=new _(e),r=s.u16le();if(s.u16le(),!(r&G.ENCRYPT))return{flags:r,payload:s.rest()};if(!this.encryptionEnabled)throw new Error("RDP: the host encrypted a PDU before the session keys existed");s.skip(8);let i=X(this.decryptState,s.rest());return++this.decryptedPdus===Wt&&this.#t(),{flags:r,payload:i}}decryptFastPath(e){if(!this.encryptionEnabled||e.length<=8)return e;let t=X(this.decryptState,e.subarray(8));return++this.decryptedPdus===Wt&&this.#t(),t}static securityExchange(e){let t=new p(e.length+16);return t.u16le(G.EXCHANGE_PKT),t.u16le(0),t.u32le(e.length+8),t.raw(e),t.zeros(8),t.take()}};var k={GENERAL:1,BITMAP:2,ORDER:3,BITMAPCACHE:4,CONTROL:5,ACTIVATION:7,POINTER:8,SHARE:9,COLORCACHE:10,SOUND:12,INPUT:13,FONT:14,BRUSH:15,GLYPHCACHE:16,OFFSCREENCACHE:17,VIRTUALCHANNEL:20,RAIL:23,WINDOW:24,MULTIFRAGMENTUPDATE:26,LARGE_POINTER:27,SURFACE_COMMANDS:28,BITMAP_CODECS:29},to=1,no=4,so=16,ro=1,io=4,oo=2,ao=8;function F(n,e){let t=new p(e.length+4);return t.u16le(n).u16le(e.length+4).raw(e),t.take()}function co(){let n=new p(24);return n.u16le(1),n.u16le(3),n.u16le(512),n.u16le(0),n.u16le(0),n.u16le(ro|io),n.u16le(0),n.u16le(0),n.u16le(0),n.u8(1),n.u8(1),F(k.GENERAL,n.take())}function ho(n,e){let t=new p(28);return t.u16le(16),t.u16le(1),t.u16le(1),t.u16le(1),t.u16le(n),t.u16le(e),t.u16le(0),t.u16le(1),t.u16le(1),t.u8(0),t.u8(0),t.u16le(1),t.u16le(0),F(k.BITMAP,t.take())}function lo(){let n=new p(88);return n.zeros(16),n.u32le(0),n.u16le(1),n.u16le(20),n.u16le(0),n.u16le(1),n.u16le(0),n.u16le(oo|ao),n.zeros(32),n.u16le(0),n.u16le(0),n.u32le(0),n.u32le(230400),n.u16le(0),n.u16le(0),n.u16le(0),n.u16le(0),F(k.ORDER,n.take())}function uo(){let n=new p(40);return n.zeros(24),n.u16le(0).u16le(0),n.u16le(0).u16le(0),n.u16le(0).u16le(0),F(k.BITMAPCACHE,n.take())}function fo(){let n=new p(12);return n.u16le(0),n.u16le(0),n.u16le(2),n.u16le(2),F(k.CONTROL,n.take())}function po(){let n=new p(12);return n.u16le(0).u16le(0).u16le(0).u16le(0),F(k.ACTIVATION,n.take())}function mo(){let n=new p(10);return n.u16le(1),n.u16le(20),n.u16le(20),F(k.POINTER,n.take())}function Eo(){let n=new p(8);return n.u16le(0).u16le(0),F(k.SHARE,n.take())}function yo(){let n=new p(8);return n.u16le(6).u16le(0),F(k.COLORCACHE,n.take())}function wo(){let n=new p(8);return n.u16le(0).u16le(0),F(k.SOUND,n.take())}function go(n){let e=new p(88);return e.u16le(to|no|so),e.u16le(0),e.u32le(n),e.u32le(4),e.u32le(0),e.u32le(12),e.zeros(64),F(k.INPUT,e.take())}function Ao(){let n=new p(8);return n.u16le(1).u16le(0),F(k.FONT,n.take())}function So(){let n=new p(8);return n.u32le(0),F(k.BRUSH,n.take())}function xo(){let n=new p(52);for(let e=0;e<10;e++)n.u16le(0).u16le(0);return n.u32le(0),n.u16le(0),n.u16le(0),F(k.GLYPHCACHE,n.take())}function To(){let n=new p(12);return n.u32le(0),n.u16le(0),n.u16le(0),F(k.OFFSCREENCACHE,n.take())}function bo(){let n=new p(4);return n.u32le(1),F(k.RAIL,n.take())}function _o(n=0,e=0){let t=new p(7);return t.u32le(1),t.u8(n),t.u16le(e),F(k.WINDOW,t.take())}function ys({width:n,height:e,keyboardLayout:t,remoteApp:s=!1,remoteAppCaps:r=null}){let i=[co(),ho(n,e),lo(),uo(),yo(),po(),fo(),mo(),Eo(),go(t),So(),xo(),wo(),Ao(),To()];return s&&(i.push(bo()),i.push(_o(r?.numIconCaches||0,r?.numIconCacheEntries||0))),{bytes:b(...i),count:i.length}}function ws(n){let e=new _(n),t=e.u16le();e.u16le();let s={desktopWidth:0,desktopHeight:0,preferredBitsPerPixel:16,refreshRectSupport:!1,railSupportLevel:0,windowSupportLevel:0,numIconCaches:0,numIconCacheEntries:0,types:[]};for(let r=0;r<t&&e.remaining>=4;r++){let i=e.u16le(),o=e.u16le();if(o<4||o-4>e.remaining)break;let a=new _(e.raw(o-4));if(s.types.push(i),i===k.BITMAP&&a.remaining>=20){s.preferredBitsPerPixel=a.u16le(),a.skip(6),s.desktopWidth=a.u16le(),s.desktopHeight=a.u16le();continue}if(i===k.GENERAL&&a.remaining>=20){a.skip(18),s.refreshRectSupport=a.u8()!==0;continue}if(i===k.RAIL&&a.remaining>=4){s.railSupportLevel=a.u32le();continue}if(i===k.WINDOW&&a.remaining>=7){s.windowSupportLevel=a.u32le(),s.numIconCaches=a.u8(),s.numIconCacheEntries=a.u16le();continue}}return s}var pe={DEMAND_ACTIVE:1,CONFIRM_ACTIVE:3,DEACTIVATE_ALL:6,DATA:7,SERVER_REDIRECT:10},M={UPDATE:2,CONTROL:20,POINTER:27,INPUT:28,SYNCHRONIZE:31,REFRESH_RECT:33,PLAY_SOUND:34,SUPPRESS_OUTPUT:35,SHUTDOWN_REQUEST:36,SHUTDOWN_DENIED:37,SAVE_SESSION_INFO:38,FONT_LIST:39,FONT_MAP:40,SET_ERROR_INFO:47,MONITOR_LAYOUT:55},lt={ORDERS:0,BITMAP:1,PALETTE:2,SYNCHRONIZE:3},Vt={REQUEST_CONTROL:1,GRANTED_CONTROL:2,DETACH:3,COOPERATE:4},Fe={SYNC:0,SCANCODE:4,UNICODE:5,MOUSE:32769,MOUSEX:32770},Ke={EXTENDED:256,DOWN:16384,RELEASE:32768},te={WHEEL:512,HWHEEL:1024,WHEEL_NEGATIVE:256,MOVE:2048,DOWN:32768,BUTTON1:4096,BUTTON2:8192,BUTTON3:16384};function As(n,e=!1){let t=e?Math.sign(n):-Math.sign(n);if(t===0)return 0;let s=e?te.HWHEEL:te.WHEEL,r=120;return t>0?s|r:s|te.WHEEL_NEGATIVE|-r&255}var ut={SCROLL_LOCK:1,NUM_LOCK:2,CAPS_LOCK:4,KANA_LOCK:8},_e={SYSTEM:1,POSITION:3,COLOR:6,CACHED:7,POINTER:8,LARGE:9},Co=721267,Ro=8,vo=32768,Lo={1:"The host disconnected the session (an administrative API call ended it).",2:"The host logged the session off.",3:"The session was disconnected after being idle too long.",4:"The session was disconnected because sign-in took too long.",5:"The session was taken over by another connection.",6:"The host ran out of memory.",7:"The host denied the connection.",9:"This account does not have permission to sign in remotely.",10:"The host requires fresh credentials.",11:"A user on the host ended the session.",12:"The remote user signed out.",256:"Remote Desktop licensing failed on the host (internal error).",257:"The host could not reach a Remote Desktop licensing server.",258:"The host has no Remote Desktop licence available for this client.",259:"The host rejected this client during licensing.",260:"The stored Remote Desktop licence does not match this client.",261:"The host rejected the client licence.",262:"Remote Desktop licensing could not be completed.",263:"The client ended the licensing exchange.",264:"The host rejected the client licence encryption.",265:"The host could not upgrade the client licence.",266:"The host does not accept remote connections.",4345:"The host rejected a malformed capability set from this client.",4346:"The host rejected the client capability exchange."};function Ss(n){return Lo[n]||`The host ended the session with error info 0x${n.toString(16).padStart(8,"0")}.`}function Yt(n,e,t){let s=new p(t.length+6);return s.u16le(t.length+6),s.u16le(n|16),s.u16le(e),s.raw(t),s.take()}function xs(n,e,t,s){let r=new p(s.length+12);return r.u32le(n),r.u8(0),r.u8(1),r.u16le(s.length+18),r.u8(t),r.u8(0),r.u16le(0),r.raw(s),Yt(pe.DATA,e,r.take())}function He(n,e){let t=n.length;n.utf16le(e);let s=n.length-t;return n.u16le(0),s}function Ts({domain:n,username:e,password:t,performanceFlags:s,autoLogon:r,remoteApp:i=!1}){let o=new p(512),a=He(o,n||""),c=He(o,e||""),h=He(o,t||""),m=He(o,""),g=He(o,""),E=new p(768);return E.u32le(0),E.u32le((Co|(r?Ro:0)|(i?vo:0))>>>0),E.u16le(a),E.u16le(c),E.u16le(h),E.u16le(m),E.u16le(g),E.raw(o.take()),E.u16le(2),E.u16le(2),E.u16le(0),E.u16le(2),E.u16le(0),E.zeros(172),E.u32le(0),E.u32le(s>>>0),E.u16le(0),E.take()}function bs(n){let e=new p(4);return e.u16le(1),e.u16le(n),e.take()}function $t(n){let e=new p(8);return e.u16le(n),e.u16le(0),e.u32le(0),e.take()}function _s(){let n=new p(8);return n.u16le(0),n.u16le(0),n.u16le(3),n.u16le(50),n.take()}function Cs(n,e,t){let s=new TextEncoder().encode("MSTSC\0"),r=new p(e.length+32);return r.u32le(n),r.u16le(1002),r.u16le(s.length),r.u16le(e.length+4),r.raw(s),r.u16le(t),r.u16le(0),r.raw(e),r.take()}function Rs(n){let e=new p(n.length*12+4);e.u16le(n.length),e.u16le(0);for(let t of n)e.raw(t);return e.take()}function Be(n,e){let t=new p(12);return t.u32le(0),t.u16le(n),e(t),t.take()}function qt(n,e,t){return Be(Fe.SCANCODE,s=>{s.u16le((e?Ke.DOWN:Ke.RELEASE)|(t?Ke.EXTENDED:0)),s.u16le(n),s.u16le(0)})}function Xt(n,e){return Be(Fe.UNICODE,t=>{t.u16le(e?Ke.DOWN:Ke.RELEASE),t.u16le(n),t.u16le(0)})}function dt(n,e,t){return Be(Fe.MOUSE,s=>{s.u16le(n),s.u16le(Math.max(0,Math.min(65535,Math.round(e)))),s.u16le(Math.max(0,Math.min(65535,Math.round(t))))})}function vs(n,e,t){return Be(Fe.MOUSEX,s=>{s.u16le(n),s.u16le(Math.max(0,Math.min(65535,Math.round(e)))),s.u16le(Math.max(0,Math.min(65535,Math.round(t))))})}function zt(n){return Be(Fe.SYNC,e=>{e.u16le(0),e.u32le(n>>>0)})}function Ls(n){let e=new p(4+n.length*8);e.u8(n.length),e.zeros(3);for(let t of n)e.u16le(t.left),e.u16le(t.top),e.u16le(t.right),e.u16le(t.bottom);return e.take()}function Ns(n,e){let t=new p(12);return t.u8(n?1:0),t.zeros(3),n&&e&&(t.u16le(e.left),t.u16le(e.top),t.u16le(e.right),t.u16le(e.bottom)),t.take()}function Is(n){let e=new _(n),t=e.u16le(),s=e.u16le(),r=e.u16le();return{totalLength:t,pduType:s&15,pduSource:r,payload:e.rest().subarray(0,Math.max(0,t-6))}}function Us(n){let e=new _(n),t=e.u32le();e.u8(),e.u8(),e.u16le();let s=e.u8(),r=e.u8(),i=e.u16le();return{shareId:t,pduType2:s,compressedType:r,compressedLength:i,payload:e.rest()}}function Os(n){let e=new _(n),t=e.u32le(),s=e.u16le(),r=e.u16le();e.skip(s);let i=e.raw(Math.min(r,e.remaining));return{shareId:t,capabilities:i}}var No=1,Io=1024;function Qt(n){let e=n.u16le(),t=[];for(let s=0;s<e&&n.remaining>=18;s++){let r=n.u16le(),i=n.u16le(),o=n.u16le(),a=n.u16le(),c=n.u16le(),h=n.u16le(),m=n.u16le(),g=n.u16le(),E=n.u16le(),y=!!(g&No);if(y&&!(g&Io)){n.u16le();let f=n.u16le();n.u16le(),n.u16le(),E=f}t.push({left:r,top:i,right:o,bottom:a,width:c,height:h,bitsPerPixel:m,compressed:y,data:n.raw(Math.min(E,n.remaining))})}return t}function jt(n){n.u16le(),n.u16le();let e=n.u32le(),t=new Uint8Array(256*3);for(let s=0;s<e&&s<256&&n.remaining>=3;s++)t[s*3]=n.u8(),t[s*3+1]=n.u8(),t[s*3+2]=n.u8();return t}function gs(n,e){let t=n.u16le(),s=n.u16le(),r=n.u16le(),i=n.u16le(),o=n.u16le(),a=n.u16le(),c=n.u16le(),h=n.raw(Math.min(c,n.remaining)).slice(),m=n.raw(Math.min(a,n.remaining)).slice();return{kind:"bitmap",cacheIndex:t,hotSpotX:s,hotSpotY:r,width:i,height:o,xorBpp:e||24,xorMask:h,andMask:m}}function Zt(n){let e=n.u16le();if(n.u16le(),e===_e.POSITION)return{kind:"position",x:n.u16le(),y:n.u16le()};if(e===_e.SYSTEM)return{kind:"system",hidden:n.u32le()===0};if(e===_e.CACHED)return{kind:"cached",cacheIndex:n.u16le()};if(e===_e.COLOR)return gs(n,24);if(e===_e.POINTER){let t=n.u16le();return gs(n,t)}return e===_e.LARGE?{kind:"unsupported",messageType:e}:{kind:"unsupported",messageType:e}}var ks={Escape:1,Digit1:2,Digit2:3,Digit3:4,Digit4:5,Digit5:6,Digit6:7,Digit7:8,Digit8:9,Digit9:10,Digit0:11,Minus:12,Equal:13,Backspace:14,Tab:15,KeyQ:16,KeyW:17,KeyE:18,KeyR:19,KeyT:20,KeyY:21,KeyU:22,KeyI:23,KeyO:24,KeyP:25,BracketLeft:26,BracketRight:27,Enter:28,ControlLeft:29,KeyA:30,KeyS:31,KeyD:32,KeyF:33,KeyG:34,KeyH:35,KeyJ:36,KeyK:37,KeyL:38,Semicolon:39,Quote:40,Backquote:41,ShiftLeft:42,Backslash:43,KeyZ:44,KeyX:45,KeyC:46,KeyV:47,KeyB:48,KeyN:49,KeyM:50,Comma:51,Period:52,Slash:53,ShiftRight:54,NumpadMultiply:55,AltLeft:56,Space:57,CapsLock:58,F1:59,F2:60,F3:61,F4:62,F5:63,F6:64,F7:65,F8:66,F9:67,F10:68,NumLock:69,ScrollLock:70,Numpad7:71,Numpad8:72,Numpad9:73,NumpadSubtract:74,Numpad4:75,Numpad5:76,Numpad6:77,NumpadAdd:78,Numpad1:79,Numpad2:80,Numpad3:81,Numpad0:82,NumpadDecimal:83,IntlBackslash:86,F11:87,F12:88,IntlRo:115,IntlYen:125},Ps={NumpadEnter:28,ControlRight:29,NumpadDivide:53,PrintScreen:55,AltRight:56,Home:71,ArrowUp:72,PageUp:73,ArrowLeft:75,ArrowRight:77,End:79,ArrowDown:80,PageDown:81,Insert:82,Delete:83,MetaLeft:91,MetaRight:92,ContextMenu:93};function Jt(n){return Object.prototype.hasOwnProperty.call(ks,n)?{scancode:ks[n],extended:!1}:Object.prototype.hasOwnProperty.call(Ps,n)?{scancode:Ps[n],extended:!0}:null}var Ds=[{code:"ControlLeft",pressed:!0},{code:"AltLeft",pressed:!0},{code:"Delete",pressed:!0},{code:"Delete",pressed:!1},{code:"AltLeft",pressed:!1},{code:"ControlLeft",pressed:!1}];var Ce="VNC_GATEWAY_READY_v1",Re="VNC_GATEWAY_KEEPALIVE_v1";var L={IDLE:"idle",NEGOTIATING:"negotiating",TLS_HANDSHAKE:"tls-handshake",CREDSSP:"credssp",MCS_CONNECT:"mcs-connect",ATTACH_USER:"attach-user",JOIN_CHANNELS:"join-channels",SECURE:"secure-exchange",LICENSING:"licensing",CAPABILITIES:"capabilities",CONNECTED:"connected",CLOSED:"closed"},Uo=255,en={name:"cliprdr",options:fe.INITIALIZED|fe.ENCRYPT_RDP|fe.SHOW_PROTOCOL},tn={name:"rail",options:fe.INITIALIZED|fe.ENCRYPT_RDP|fe.SHOW_PROTOCOL},Oo=1,ko=2,Po=4,Do=1200,Mo=120,ft=2,Ho=4,Ko=12,Ms=320,pt=class extends EventTarget{constructor(e,t={}){super(),this.url=e,this.options={width:1024,height:768,username:"",password:"",domain:"",keyboardLayout:1033,clientName:"cf-gateway",security:"auto",openTransport:null,clipboard:!0,remoteApp:null,performance:Oo|ko|Po,...t},this.state=L.IDLE,this.legacyRetryUsed=!1,this.desktopWidth=this.options.width,this.desktopHeight=this.options.height,this.palette=null,this.userId=Se,this.ioChannelId=1003,this.serverChannelId=1002,this.shareId=0,this.channelsToJoin=[],this.requestedChannels=[],this.channelNamesById=new Map,this.channelReassemblers=new Map,this.clipboard=null,this.rail=null,this.remoteAppWindows=new Map,this.remoteAppHadWindow=!1,this.remoteAppCloseTimer=null,this.remoteAppFit=null,this.remoteAppFitTimer=null,this.clientRandom=null,this.serverData=null,this.fastPathFragments=[],this.receiveBuffer=new Uint8Array(0),this.keepaliveTimer=null,this.closeReported=!1,this.tls=null,this.credssp=null,this.inboundQueue=Promise.resolve(),this.requestedProtocol={auto:P.SSL|P.HYBRID,nla:P.SSL|P.HYBRID,tls:P.SSL,rdp:P.RDP}[this.options.security]??P.SSL|P.HYBRID,this.#e()}#e(){this.receiveBuffer=new Uint8Array(0),this.inboundQueue=Promise.resolve(),this.tls=null,this.credssp=null,this.security=new Me,this.replacingTransport=!1,this.channelNamesById=new Map,this.channelReassemblers=new Map,this.clipboard=null,this.rail=null,this.remoteAppWindows.clear(),this.remoteAppHadWindow=!1,clearTimeout(this.remoteAppCloseTimer),clearTimeout(this.remoteAppFitTimer),this.remoteAppFitTimer=null,this.remoteAppCloseTimer=null,this.socket=this.options.openTransport?this.options.openTransport(this.url):new WebSocket(this.url),this.socket.binaryType="arraybuffer",this.socket.addEventListener("open",()=>this.#s()),this.socket.addEventListener("message",e=>this.#a(e)),this.socket.addEventListener("close",e=>this.#c(e)),this.socket.addEventListener("error",()=>{console.warn("[RDP] WebSocket transport error",{target:this.url})})}#t(e){console.info("[RDP] Reconnecting with a different security layer",{security:e}),this.legacyRetryUsed=!0,this.options.security=e,this.requestedProtocol=e==="rdp"?P.RDP:P.SSL,this.state=L.IDLE,this.replacingTransport=!0,clearInterval(this.keepaliveTimer);try{this.socket.close(1e3,"Retrying with another security layer")}catch{}this.#e()}#s(){this.socket.send(Ce),this.state=L.NEGOTIATING,this.#n(Rn(this.requestedProtocol)),this.keepaliveTimer=setInterval(()=>{if(this.socket.readyState===WebSocket.OPEN&&(this.socket.send(Re),this.state===L.CONNECTED))try{this.#f([zt(this.toggleFlags||0)])}catch{}},25e3)}#n(e){if(this.tls&&this.tls.established){this.tls.write(e);return}this.#r(e)}#r(e){this.socket.readyState===WebSocket.OPEN&&this.socket.send(e)}#c(e){if(clearInterval(this.keepaliveTimer),clearTimeout(this.remoteAppCloseTimer),clearTimeout(this.remoteAppFitTimer),this.remoteAppFitTimer=null,this.replacingTransport||this.state===L.CLOSED&&this.closeReported)return;let t=this.state===L.CONNECTED;this.state=L.CLOSED,this.closeReported=!0,this.dispatchEvent(new CustomEvent("close",{detail:{clean:e.wasClean&&t,code:e.code,message:e.reason||"",phase:t?"session":"handshake"}}))}#i(e){if(this.state===L.CLOSED)return;let t=e instanceof Error?e.message:String(e);console.error("[RDP] Protocol failure",{state:this.state,message:t}),this.dispatchEvent(new CustomEvent("error",{detail:{message:t,phase:this.state}})),this.state=L.CLOSED,this.closeReported=!0,clearInterval(this.keepaliveTimer),clearTimeout(this.remoteAppCloseTimer),clearTimeout(this.remoteAppFitTimer),this.remoteAppFitTimer=null;try{this.socket.close(4e3,t.slice(0,100))}catch{}this.dispatchEvent(new CustomEvent("close",{detail:{clean:!1,code:4e3,message:t,phase:"protocol"}}))}disconnect(){if(this.state!==L.CLOSED){this.state=L.CLOSED,this.closeReported=!0,clearInterval(this.keepaliveTimer),clearTimeout(this.remoteAppCloseTimer),clearTimeout(this.remoteAppFitTimer),this.remoteAppFitTimer=null;try{this.socket.close(1e3,"Client disconnected")}catch{}}}#a(e){this.state!==L.CLOSED&&(this.inboundQueue=this.inboundQueue.then(async()=>{if(this.state===L.CLOSED)return;let t=typeof e.data=="string"?new TextEncoder().encode(e.data):new Uint8Array(e.data);this.tls?await this.tls.receive(t):await this.#h(t)}).catch(t=>this.#i(t)))}#o(e){if(this.state===L.CREDSSP&&this.credssp){this.credssp.receive(e);return}return this.#h(e)}async#h(e){this.receiveBuffer=this.receiveBuffer.length===0?e:b(this.receiveBuffer,e);let{frames:t,rest:s}=Ln(this.receiveBuffer);this.receiveBuffer=s.length===this.receiveBuffer.length?this.receiveBuffer:s.slice();for(let{fastPath:r,frame:i}of t){if(this.state===L.CLOSED)return;r?this.#O(i):await this.#l(i)}}async#l(e){if(this.state===L.NEGOTIATING){let o;try{({selectedProtocol:o}=vn(e))}catch(a){if(this.options.security==="auto"&&!this.legacyRetryUsed&&a.negotiationFailure===Cn.SSL_NOT_ALLOWED){this.#t("rdp");return}throw a}if(this.selectedProtocol=o,console.info("[RDP] X.224 negotiation complete",{requested:this.requestedProtocol,selected:o,layer:o&P.HYBRID?"NLA / CredSSP":o&P.SSL?"TLS":"RDP standard"}),o&P.HYBRID_EX)throw new Error("This host selected CredSSP with early user authorization, which this client does not implement.");if(o&(P.SSL|P.HYBRID)){this.#E(o);return}this.#u(o);return}if(this.state===L.MCS_CONNECT){this.serverData=ns(Xn(e)),console.info("[RDP] MCS connect response",{encryptionMethod:this.serverData.encryptionMethod,encryptionLevel:this.serverData.encryptionLevel,ioChannelId:this.serverData.ioChannelId,certificate:this.serverData.publicKey?.source||"none",virtualChannels:this.serverData.channelIds}),this.ioChannelId=this.serverData.ioChannelId,this.channelNamesById=new Map,this.requestedChannels.forEach((o,a)=>{let c=this.serverData.channelIds[a];c!==void 0&&this.channelNamesById.set(c,o.name)}),this.security.configure(this.serverData.encryptionMethod,this.serverData.encryptionLevel,this.serverData.encryptionMethod?this.#y():new Uint8Array(32),this.serverData.serverRandom||new Uint8Array(32)),this.state=L.ATTACH_USER,this.#n(zn()),this.#n(Qn());return}if(this.state===L.ATTACH_USER){({userId:this.userId}=jn(e)),this.channelsToJoin=[this.userId,this.ioChannelId,...this.serverData.channelIds],this.joinedChannels=0,this.state=L.JOIN_CHANNELS,this.#n(Ht(this.userId,this.channelsToJoin[0]));return}if(this.state===L.JOIN_CHANNELS){if(Zn(e),this.joinedChannels+=1,this.joinedChannels<this.channelsToJoin.length){this.#n(Ht(this.userId,this.channelsToJoin[this.joinedChannels]));return}this.#g();return}let t=Jn(e);if(t.type==="disconnect"){this.#i(new Error(t.message));return}if(t.type!=="send-data")return;let s=this.channelNamesById.get(t.channelId);if(s){let o=this.security.headerPresent?this.security.unwrap(t.payload).payload:t.payload;this.#P(s,o);return}let{flags:r,payload:i}=this.#p(t.payload);if(i.length!==0){if(r&G.LICENSE_PKT){this.#A(i);return}this.#S(i)}}#p(e){if(this.security.headerPresent)return this.security.unwrap(e);let t=G.EXCHANGE_PKT|G.ENCRYPT|G.INFO_PKT|G.LICENSE_PKT|G.LICENSE_ENCRYPT_CS|G.REDIRECTION_PKT|G.AUTODETECT_REQ|G.HEARTBEAT;if(e.length>=4){let s=e[0]|e[1]<<8;if((e[2]|e[3]<<8)===0&&(s&t)!==0)return this.security.unwrap(e,!0)}return{flags:0,payload:e}}async#E(e){try{this.state=L.TLS_HANDSHAKE,this.tls=new je({send:s=>this.#r(s),onData:s=>this.#o(s),onError:s=>this.#i(s)});let t=await this.tls.start();if(console.info("[RDP] TLS established",{cipherSuite:t.cipherSuite,certificates:t.certificates.length,modulusBits:t.publicKey.modulus.length*8}),e&P.HYBRID){if(this.state=L.CREDSSP,this.credssp=new Je({username:this.options.username,domain:this.options.domain,password:this.options.password,serverPublicKey:t.publicKey.subjectPublicKey,send:r=>this.tls.write(r),log:(r,i)=>console.info(`[RDP] ${r}`,i)}),!this.options.password)throw new Error("This host authenticates before the desktop appears (NLA), so it needs a username and password.");let s=await this.credssp.authenticate();console.info("[RDP] Network Level Authentication succeeded",s),this.credssp=null}this.#u(e)}catch(t){this.#i(t)}}#u(e){this.state=L.MCS_CONNECT,this.requestedChannels=[],this.options.clipboard&&this.requestedChannels.push(en),this.options.remoteApp?.program&&this.requestedChannels.push(tn),this.#n(qn(ts({width:this.options.width,height:this.options.height,clientName:this.options.clientName,keyboardLayout:this.options.keyboardLayout,selectedProtocol:e,encryptionMethods:e===P.RDP?11:0,channels:this.requestedChannels})))}#y(){return this.clientRandom=new Uint8Array(32),crypto.getRandomValues(this.clientRandom),this.clientRandom}#g(){if(this.security.encryptionEnabled){let t=this.serverData.publicKey;if(!t)throw new Error("RDP: the host asked for encryption but sent no public key");let s=wn(this.clientRandom,t.modulus,t.exponent);this.#d(Me.securityExchange(s))}let e=Ts({domain:this.options.domain,username:this.options.username,password:this.options.password,performanceFlags:this.options.performance,autoLogon:!!this.options.password,remoteApp:!!this.options.remoteApp?.program});this.state=L.LICENSING,this.#d(this.security.wrap(e,G.INFO_PKT))}#d(e){this.#n(Kt(this.userId,this.ioChannelId,e))}#A(e){if(e.length<4)return;if(e[0]===Uo){console.info("[RDP] Licensing finished with an error alert (the normal path)"),this.state=L.CAPABILITIES;return}throw new Error("This host requires Remote Desktop licensing negotiation (per-device CAL), which this client does not implement.")}#S(e){let t=Is(e);if(t.pduSource&&(this.serverChannelId=t.pduSource),t.pduType===pe.DEMAND_ACTIVE){this.#m(t.payload);return}if(t.pduType===pe.DEACTIVATE_ALL){console.info("[RDP] Host deactivated the share; waiting for a new demand active"),this.state=L.CAPABILITIES;return}if(t.pduType===pe.SERVER_REDIRECT)throw new Error("This host redirected the session to another server, which this client cannot follow.");if(t.pduType!==pe.DATA)return;let s=Us(t.payload);if(s.compressedType&32)throw new Error("RDP: the host compressed a PDU although this client advertised no compression support");this.#_(s)}#m(e){let{shareId:t,capabilities:s}=Os(e);this.shareId=t;let r=ws(s);if(this.options.remoteApp?.program&&(!(r.railSupportLevel&1)||!r.windowSupportLevel))throw new Error("This RDP host did not accept RemoteApp mode. Publish the application on the host or connect without a RemoteApp program.");if(r.desktopWidth&&r.desktopHeight){let a=this.state===L.CONNECTED&&(r.desktopWidth!==this.desktopWidth||r.desktopHeight!==this.desktopHeight);this.desktopWidth=r.desktopWidth,this.desktopHeight=r.desktopHeight,a&&(console.info("[RDP] Host resized the desktop",{desktop:`${this.desktopWidth}x${this.desktopHeight}`}),this.dispatchEvent(new CustomEvent("resize",{detail:{width:this.desktopWidth,height:this.desktopHeight}})))}this.refreshRectSupported=r.refreshRectSupport,console.info("[RDP] Demand active",{shareId:t,desktop:`${this.desktopWidth}x${this.desktopHeight}`,bitsPerPixel:r.preferredBitsPerPixel,refreshRectSupport:r.refreshRectSupport,remoteApp:!!this.options.remoteApp?.program});let{bytes:i,count:o}=ys({width:this.desktopWidth,height:this.desktopHeight,keyboardLayout:this.options.keyboardLayout,remoteApp:!!this.options.remoteApp?.program,remoteAppCaps:r});this.#M(pe.CONFIRM_ACTIVE,Cs(this.shareId,i,o)),this.#w(M.SYNCHRONIZE,bs(this.serverChannelId)),this.#w(M.CONTROL,$t(Vt.COOPERATE)),this.#w(M.CONTROL,$t(Vt.REQUEST_CONTROL)),this.#w(M.FONT_LIST,_s())}#_(e){switch(e.pduType2){case M.UPDATE:this.#C(new _(e.payload));return;case M.POINTER:this.dispatchEvent(new CustomEvent("pointer",{detail:Zt(new _(e.payload))}));return;case M.FONT_MAP:this.#U();return;case M.SET_ERROR_INFO:{let t=new _(e.payload).u32le();if(t===0)return;this.#i(new Error(Ss(t)));return}case M.SAVE_SESSION_INFO:console.info("[RDP] Host reported a completed sign-in");return;case M.SHUTDOWN_DENIED:console.info("[RDP] Host denied the shutdown request");return;case M.CONTROL:case M.SYNCHRONIZE:case M.PLAY_SOUND:case M.MONITOR_LAYOUT:return;default:return}}#C(e){let t=e.u16le();if(this.firstUpdateLogged||(this.firstUpdateLogged=!0,console.info("[RDP] First host update received",{updateType:t})),t===lt.BITMAP){let s=Qt(e);s.length>0&&this.dispatchEvent(new CustomEvent("bitmap",{detail:{rects:s,palette:this.palette}}));return}if(t===lt.PALETTE){this.palette=jt(e),this.dispatchEvent(new CustomEvent("palette",{detail:this.palette}));return}if(t===lt.ORDERS){this.options.remoteApp?.program?this.#R(ds(e)):console.warn("[RDP] Ignoring a drawing-order update the client did not advertise");return}}#R(e){for(let t of e){if(t.type==="deleted"){this.remoteAppWindows.delete(t.windowId),this.dispatchEvent(new CustomEvent("remoteappwindow",{detail:{...t,count:this.remoteAppWindows.size}}));continue}t.type==="new"?(clearTimeout(this.remoteAppCloseTimer),this.remoteAppCloseTimer=null,this.remoteAppHadWindow=!0):this.remoteAppWindows.has(t.windowId)||(this.remoteAppHadWindow=!0);let r={...this.remoteAppWindows.get(t.windowId)||{windowId:t.windowId},...t,type:void 0};this.remoteAppWindows.set(t.windowId,r),this.dispatchEvent(new CustomEvent("remoteappwindow",{detail:{...t,window:r,count:this.remoteAppWindows.size}})),this.remoteAppFit&&this.#v(r)&&!this.#L(r)&&this.#x()}this.#I(),!(!this.remoteAppHadWindow||this.remoteAppWindows.size>0||this.remoteAppCloseTimer)&&(this.remoteAppCloseTimer=setTimeout(()=>{this.remoteAppCloseTimer=null,!(this.state!==L.CONNECTED||this.remoteAppWindows.size>0)&&(console.info("[RDP] Last RemoteApp window closed; ending the session"),this.dispatchEvent(new CustomEvent("remoteappclosed",{detail:{application:this.options.remoteApp}})))},Do))}get remoteAppPrimaryWindow(){let e=null,t=-1;for(let s of this.remoteAppWindows.values()){if(!us(s)||s.showState===be.HIDDEN)continue;let r=(s.width||0)*(s.height||0);r>t&&(e=s,t=r)}return e}#v(e){let t=this.remoteAppPrimaryWindow;return!!t&&t.windowId===e.windowId}#L(e){let t=this.remoteAppFit;return t?Math.abs(e.x||0)<=ft&&Math.abs(e.y||0)<=ft&&Math.abs((e.width||0)-t.width)<=ft&&Math.abs((e.height||0)-t.height)<=ft:!0}#x(){this.remoteAppFitTimer||(this.remoteAppFitTimer=setTimeout(()=>{this.remoteAppFitTimer=null,this.#N()},Mo))}#N(){let e=this.remoteAppFit;if(!e||!this.rail||this.state!==L.CONNECTED)return;this.rail.setWorkArea(e.width,e.height);let t=this.remoteAppPrimaryWindow;if(!t||t.showState===be.MINIMIZED)return;let s=`${t.width||0}x${t.height||0}+${t.x||0}+${t.y||0}`;if(s!==e.lastGeometry&&(e.attempts=0),e.lastGeometry=s,!(e.attempts>=Ho||e.moves>=Ko)){if(e.attempts+=1,e.moves+=1,t.showState===be.MAXIMIZED){console.info("[RDP] Restoring the maximized RemoteApp window before fitting it"),this.rail.sysCommand(t.windowId,as.RESTORE);return}console.info("[RDP] Fitting the RemoteApp window to the browser",{windowId:t.windowId,from:`${t.width||0}x${t.height||0}+${t.x||0}+${t.y||0}`,to:`${e.width}x${e.height}+0+0`,attempt:e.attempts}),this.rail.activate(t.windowId),this.rail.moveWindow(t.windowId,{left:0,top:0,right:e.width,bottom:e.height})}}#I(){let e=this.remoteAppPrimaryWindow;if(!e||!e.width||!e.height||e.showState===be.MINIMIZED||e.showState===be.HIDDEN)return;let t=Math.max(0,Math.min(this.desktopWidth-1,e.x||0)),s=Math.max(0,Math.min(this.desktopHeight-1,e.y||0)),r={x:t,y:s,width:Math.max(1,Math.min(this.desktopWidth-t,e.width)),height:Math.max(1,Math.min(this.desktopHeight-s,e.height))},i=this.remoteAppViewport;i&&i.x===r.x&&i.y===r.y&&i.width===r.width&&i.height===r.height||(this.remoteAppViewport=r,this.dispatchEvent(new CustomEvent("remoteappviewport",{detail:r})))}fitRemoteApp(e,t){if(!this.options.remoteApp?.program||!Number.isFinite(e)||!Number.isFinite(t))return!1;let s={width:Math.max(Ms,Math.min(this.desktopWidth,Math.floor(e))),height:Math.max(Ms,Math.min(this.desktopHeight,Math.floor(t))),attempts:0,moves:0,lastGeometry:""};return this.remoteAppFit=s,this.#x(),!0}#U(){this.state!==L.CONNECTED&&(this.state=L.CONNECTED,console.info("[RDP] Session established",{desktop:`${this.desktopWidth}x${this.desktopHeight}`,encryption:this.security.encryptionEnabled?`RC4 ${this.security.keys.keyLength*8}-bit`:"TLS transport"}),this.dispatchEvent(new CustomEvent("ready",{detail:{width:this.desktopWidth,height:this.desktopHeight}})),this.setOutputEnabled(!0),this.refresh())}#O(e){let t=e[0]>>6&3,s=e[1]&128?2:1,r=e.subarray(1+s);t&2&&(r=this.security.decryptFastPath(r));let i=new _(r);for(;i.remaining>=3;){let o=i.u8(),a=o&15,c=o>>4&3;o>>6&3&2&&i.u8();let m=i.u16le(),g=i.raw(Math.min(m,i.remaining));if(c!==0){if(c===2&&(this.fastPathFragments=[]),this.fastPathFragments.push(g.slice()),c!==1)continue;g=b(...this.fastPathFragments),this.fastPathFragments=[]}this.#k(a,g)}}#k(e,t){let s=new _(t);switch(e){case 1:{s.u16le();let r=Qt(s);r.length>0&&this.dispatchEvent(new CustomEvent("bitmap",{detail:{rects:r,palette:this.palette}}));return}case 2:this.palette=jt(s),this.dispatchEvent(new CustomEvent("palette",{detail:this.palette}));return;case 5:this.dispatchEvent(new CustomEvent("pointer",{detail:{kind:"system",hidden:!0}}));return;case 6:this.dispatchEvent(new CustomEvent("pointer",{detail:{kind:"system",hidden:!1}}));return;case 8:this.dispatchEvent(new CustomEvent("pointer",{detail:{kind:"position",x:s.u16le(),y:s.u16le()}}));return;case 9:case 10:case 11:{let r={9:6,10:7,11:8}[e],i=new Uint8Array([r,0,0,0]);this.dispatchEvent(new CustomEvent("pointer",{detail:Zt(new _(b(i,t)))}));return}default:return}}#P(e,t){let s=this.channelReassemblers.get(e);s||(s=new ht,this.channelReassemblers.set(e,s));let r=s.push(t);if(r){if(e===en.name){this.#b().receive(r);return}e===tn.name&&this.#D().receive(r)}}#T(e,t){let s=[...this.channelNamesById].find(([,r])=>r===e)?.[0];if(s===void 0)return!1;for(let r of Es(t,Gt,ms))this.#n(Kt(this.userId,s,this.security.wrap(r)));return!0}#D(){return this.rail?this.rail:(this.rail=new ct({application:this.options.remoteApp,width:this.remoteAppFit?.width||this.desktopWidth,height:this.remoteAppFit?.height||this.desktopHeight,send:e=>this.#T(tn.name,e),onReady:({buildNumber:e,extended:t,flags:s})=>{console.info("[RDP] RemoteApp channel ready",{buildNumber:e,extended:!!t,flags:s||0}),this.dispatchEvent(new CustomEvent("remoteappready",{detail:{application:this.options.remoteApp}}))},onResult:e=>{let t={...e,application:this.options.remoteApp};this.dispatchEvent(new CustomEvent("remoteappresult",{detail:t})),e.ok?console.info("[RDP] Remote application launched",t):this.#i(new Error(e.message))}}),this.rail)}#b(){return this.clipboard?this.clipboard:(this.clipboard=new ot({send:e=>this.#T(en.name,e),log:(e,t)=>console.info(`[RDP] ${e}`,t)}),this.clipboard.addEventListener("text",e=>{this.dispatchEvent(new CustomEvent("clipboard",{detail:e.detail}))}),this.clipboard)}setClipboardText(e){return!this.connected||!this.channelNamesById.size?Promise.resolve(!1):this.#b().setLocalText(e||"")}get clipboardShared(){return!!this.clipboard?.ready}pasteToHost(e){if(!e||!this.connected)return Promise.resolve(!1);let t=()=>{this.connected&&(this.sendKeyByCode("ControlLeft",!0),this.sendKeyByCode("KeyV",!0),this.sendKeyByCode("KeyV",!1),this.sendKeyByCode("ControlLeft",!1))};return this.setClipboardText(e).then(s=>(s?t():this.sendUnicode(e),!0))}#M(e,t){this.#d(this.security.wrap(Yt(e,this.userId,t)))}#w(e,t){this.#d(this.security.wrap(xs(this.shareId,this.userId,e,t)))}get connected(){return this.state===L.CONNECTED}#f(e){!this.connected||e.length===0||this.#w(M.INPUT,Rs(e))}sendKeyByCode(e,t){let s=Jt(e);return s?(this.#f([qt(s.scancode,t,s.extended)]),!0):!1}sendUnicode(e){let t=[];for(let s of e)for(let r=0;r<s.length;r++){let i=s.charCodeAt(r);t.push(Xt(i,!0)),t.push(Xt(i,!1))}for(let s=0;s<t.length;s+=40)this.#f(t.slice(s,s+40))}sendCtrlAltDel(){let e=Ds.map(({code:t,pressed:s})=>{let r=Jt(t);return qt(r.scancode,s,r.extended)});this.#f(e)}sendMouseMove(e,t){this.#f([dt(te.MOVE,e,t)])}sendMouseButton(e,t,s,r){let i={0:te.BUTTON1,1:te.BUTTON3,2:te.BUTTON2}[e];if(i===void 0){let o=e===3?1:2;this.#f([vs(o|(t?te.DOWN:0),s,r)]);return}this.#f([dt(i|(t?te.DOWN:0),s,r)])}sendWheel(e,t,s,r=!1){let i=As(e,r);i&&this.#f([dt(i,t,s)])}sendKeyboardSync(e){this.toggleFlags=e>>>0,this.#f([zt(this.toggleFlags)])}refresh(e){!this.connected||!this.refreshRectSupported||this.#w(M.REFRESH_RECT,Ls([e||{left:0,top:0,right:this.desktopWidth-1,bottom:this.desktopHeight-1}]))}setOutputEnabled(e){this.connected&&this.#w(M.SUPPRESS_OUTPUT,Ns(e,{left:0,top:0,right:this.desktopWidth-1,bottom:this.desktopHeight-1}))}};function Fo(n){return(n&192)!==192?n>>5:(n&240)===240?n:n>>4}function Bo(n,e,t,s){let r=new Uint32Array(e*t),i=s>=4?4294967295:(1<<s*8)-1,o=0,a=0,c=i,h=!1,m=!0,g=()=>{let f=0;for(let l=0;l<s;l++)f|=n[o+l]<<l*8;return o+=s,f>>>0},E=f=>{let l=n[o];if(f===2){let A=l&31;return A===0?(o+=2,n[o-1]+1):(o+=1,A*8)}if(f===13){let A=l&15;return A===0?(o+=2,n[o-1]+1):(o+=1,A*8)}if(f===0||f===1||f===3||f===4){let A=l&31;return A===0?(o+=2,n[o-1]+32):(o+=1,A)}if(f===12||f===14){let A=l&15;return A===0?(o+=2,n[o-1]+16):(o+=1,A)}let S=n[o+1]|n[o+2]<<8;return o+=3,S},y=(f,l)=>{let S=1;for(let A=0;A<l;A++){if(m)r[a]=f&S?c:0;else{let T=r[a-e];r[a]=f&S?(T^c)>>>0:T}a++,S=S<<1&255}};for(;o<n.length&&a<r.length;){m&&a>=e&&(m=!1);let f=Fo(n[o]);if(f===0||f===240){let l=E(f);if(m)for(h&&(r[a++]=c,l--);l-- >0&&a<r.length;)r[a++]=0;else for(h&&(r[a]=(r[a-e]^c)>>>0,a++,l--);l-- >0&&a<r.length;)r[a]=r[a-e],a++;h=!0;continue}switch(h=!1,f){case 1:case 241:case 12:case 246:{let l=E(f);if((f===12||f===246)&&(c=g()),m)for(;l-- >0&&a<r.length;)r[a++]=c;else for(;l-- >0&&a<r.length;)r[a]=(r[a-e]^c)>>>0,a++;break}case 14:case 248:{let l=E(f),S=g(),A=g();for(;l-- >0&&a<r.length-1;)r[a++]=S,r[a++]=A;break}case 3:case 243:{let l=E(f),S=g();for(;l-- >0&&a<r.length;)r[a++]=S;break}case 2:case 242:case 13:case 247:{let l=E(f);for((f===13||f===247)&&(c=g());l>8;)y(n[o++],8),l-=8;l>0&&y(n[o++],l);break}case 4:case 244:{let l=E(f);for(;l-- >0&&a<r.length;)r[a++]=g();break}case 249:o++,y(3,8);break;case 250:o++,y(5,8);break;case 253:o++,r[a++]=i;break;case 254:o++,r[a++]=0;break;default:throw new Error(`RDP: unsupported bitmap compression order 0x${f.toString(16)}`)}}return r}function Go(n,e){if(e<=0)return n;let t=Math.floor(n.length/e);if(t<2)return n;let s=new Uint32Array(n.length);for(let r=0;r<t;r++)s.set(n.subarray(r*e,(r+1)*e),(t-1-r)*e);return s}function Wo(n,e,t,s){let r=new Uint32Array(e*t);for(let i=0;i<t;i++){let o=(t-1-i)*e,a=i*e*s;for(let c=0;c<e;c++){let h=0;for(let m=0;m<s;m++)h|=n[a+m]<<m*8;r[o+c]=h>>>0,a+=s}}return r}function Vo(n,e,t){let s=new Uint8ClampedArray(n.length*4);for(let r=0;r<n.length;r++){let i=n[r],o,a,c;switch(e){case 15:o=(i>>10&31)*255/31,a=(i>>5&31)*255/31,c=(i&31)*255/31;break;case 16:o=(i>>11&31)*255/31,a=(i>>5&63)*255/63,c=(i&31)*255/31;break;case 8:{let m=(i&255)*3;o=t?t[m]:i,a=t?t[m+1]:i,c=t?t[m+2]:i;break}default:o=i>>16&255,a=i>>8&255,c=i&255;break}let h=r*4;s[h]=o,s[h+1]=a,s[h+2]=c,s[h+3]=255}return s}function Hs(n,e){let t=Math.max(1,Math.ceil(n.bitsPerPixel/8)),s=n.compressed?Go(Bo(n.data,n.width,n.height,t),n.width):Wo(n.data,n.width,n.height,t);return Vo(s,n.bitsPerPixel,e)}var nn=/Mac|iPod|iPhone|iPad/.test(globalThis.navigator?.platform||globalThis.navigator?.userAgent||""),Ks={MetaLeft:"ControlLeft",MetaRight:"ControlRight"},Fs=60,Yo=16,Bs=20,$o=8,qo=1,mt=class{constructor(e){this.container=e,this.canvas=document.createElement("canvas"),this.canvas.tabIndex=0,this.canvas.style.display="block",this.canvas.style.position="absolute",this.canvas.style.outline="none",this.canvas.style.imageRendering="auto",this.canvas.style.boxShadow="none",this.context=this.canvas.getContext("2d",{alpha:!1}),this.viewportElement=document.createElement("div"),this.viewportElement.style.position="relative",this.viewportElement.style.overflow="hidden",this.viewportElement.style.margin="auto",this.viewportElement.style.background="#000",this.viewportElement.style.boxShadow="0 10px 30px rgba(0, 0, 0, 0.8)",this.viewportElement.appendChild(this.canvas),e.replaceChildren(this.viewportElement),this.scrollHost=e.parentElement||e,this.width=0,this.height=0,this.viewport={x:0,y:0,width:0,height:0},this.scale=1,this.scaleViewport=!0,this.zoom=1,this.userZoomed=!1,this.viewOnly=!1,this.client=null,this.palette=null,this.cursorCache=new Map,this.heldKeys=new Set,this.keyboardSynced=!1,this.onWindowResize=()=>this.applyScale(),window.addEventListener("resize",this.onWindowResize),this.resizeObserver=typeof ResizeObserver=="function"?new ResizeObserver(()=>this.applyScale()):null,this.resizeObserver?.observe(this.scrollHost)}resize(e,t){this.width=e,this.height=t,this.canvas.width=e,this.canvas.height=t,this.context.fillStyle="#000",this.context.fillRect(0,0,e,t),this.setViewport({x:0,y:0,width:e,height:t})}setViewport({x:e=0,y:t=0,width:s,height:r}={}){if(!this.width||!this.height)return;let i=Math.max(0,Math.min(this.width-1,Math.floor(e))),o=Math.max(0,Math.min(this.height-1,Math.floor(t)));this.viewport={x:i,y:o,width:Math.max(1,Math.min(this.width-i,Math.floor(s||this.width))),height:Math.max(1,Math.min(this.height-o,Math.floor(r||this.height)))},this.canvas.dataset.viewport=[this.viewport.x,this.viewport.y,this.viewport.width,this.viewport.height].join(","),this.applyScale()}#e(){let e=this.scrollHost;return{width:e.clientWidth||this.container.clientWidth||1,height:e.clientHeight||this.container.clientHeight||1}}#t(e=this.#e()){let t=Math.min(e.width/this.viewport.width,e.height/this.viewport.height);return Number.isFinite(t)&&t>0?t:1}#s(){return 1}applyScale(){if(!this.width||!this.height)return;let e=this.viewport,t=this.#e(),s=this.#t(t);this.userZoomed||(this.zoom=this.#s());let r=(this.scaleViewport?s:1)*this.zoom;this.scale=r,this.viewportElement.style.width=`${e.width*r}px`,this.viewportElement.style.height=`${e.height*r}px`,this.canvas.style.width=`${this.width*r}px`,this.canvas.style.height=`${this.height*r}px`,this.canvas.style.left=`${-e.x*r}px`,this.canvas.style.top=`${-e.y*r}px`}setZoom(e,t=null){let s=Math.min($o,Math.max(qo,e));if(!Number.isFinite(s)||s===this.zoom)return;let r=this.scrollHost,i=this.scale,o=r.getBoundingClientRect(),a=t?t.x-o.left:o.width/2,c=t?t.y-o.top:o.height/2,h=r.scrollLeft+a,m=r.scrollTop+c;this.zoom=s,this.applyScale();let g=i>0?this.scale/i:1;r.scrollLeft=h*g-a,r.scrollTop=m*g-c}panBy(e,t){let s=this.scrollHost,r=s.scrollLeft,i=s.scrollTop;return s.scrollLeft=r-e,s.scrollTop=i-t,{x:r-s.scrollLeft,y:i-s.scrollTop}}canPan(){if(this.zoom<=1.05)return!1;let e=this.scrollHost;return e.scrollWidth>e.clientWidth+2||e.scrollHeight>e.clientHeight+2}setScaleViewport(e){this.scaleViewport=e,e||(this.userZoomed=!1),this.applyScale()}resetZoom(){this.userZoomed=!1,this.zoom=1,this.applyScale();let e=this.scrollHost;e.scrollLeft=0,e.scrollTop=0}drawRects(e,t){t&&(this.palette=t);for(let s of e)if(!(s.width===0||s.height===0))try{let r=Hs(s,this.palette),i=new ImageData(r,s.width,s.height);this.context.putImageData(i,s.left,s.top)}catch(r){console.warn("[RDP] Dropped an undecodable bitmap rectangle",{geometry:`${s.width}x${s.height}+${s.left}+${s.top}`,bitsPerPixel:s.bitsPerPixel,compressed:s.compressed,error:r instanceof Error?r.message:String(r)})}}#n(e){let{width:t,height:s,xorBpp:r,xorMask:i,andMask:o,hotSpotX:a,hotSpotY:c}=e;if(!t||!s)return null;let h=Math.ceil(t*r/8/2)*2,m=Math.ceil(t/8/2)*2,g=new Uint8ClampedArray(t*s*4);for(let l=0;l<s;l++){let S=s-1-l;for(let A=0;A<t;A++){let T=o[S*m+(A>>3)],u=T!==void 0&&(T&128>>(A&7))!==0,d=0,x=0,R=0,C=u?0:255;if(r===1)d=x=R=i[S*h+(A>>3)]&128>>(A&7)?255:0;else{let v=r/8,U=S*h+A*v;if(r===16){let Q=i[U]|i[U+1]<<8;d=(Q>>11&31)*255/31,x=(Q>>5&63)*255/63,R=(Q&31)*255/31}else R=i[U]||0,x=i[U+1]||0,d=i[U+2]||0,r===32&&i[U+3]!==void 0&&o.length===0&&(C=i[U+3])}let I=(l*t+A)*4;g[I]=d,g[I+1]=x,g[I+2]=R,g[I+3]=C}}let E=document.createElement("canvas");E.width=t,E.height=s,E.getContext("2d").putImageData(new ImageData(g,t,s),0,0);let y=Math.min(a||0,t-1),f=Math.min(c||0,s-1);return`url(${E.toDataURL("image/png")}) ${y} ${f}, default`}applyPointer(e){if(e.kind==="system"){this.canvas.style.cursor=e.hidden?"none":"default";return}if(e.kind!=="position"){if(e.kind==="cached"){let t=this.cursorCache.get(e.cacheIndex);t&&(this.canvas.style.cursor=t);return}if(e.kind==="bitmap")try{let t=this.#n(e);if(!t)return;this.cursorCache.set(e.cacheIndex,t),this.canvas.style.cursor=t}catch(t){console.warn("[RDP] Could not build a cursor from the host pointer update",t)}}}#r(e){let t=this.canvas.getBoundingClientRect(),s=this.width/(t.width||1),r=this.height/(t.height||1);return{x:Math.max(0,Math.min(this.width-1,(e.clientX-t.left)*s)),y:Math.max(0,Math.min(this.height-1,(e.clientY-t.top)*r))}}#c(e){if(this.keyboardSynced||!this.client)return;this.keyboardSynced=!0;let t=0;e.getModifierState?.("CapsLock")&&(t|=ut.CAPS_LOCK),e.getModifierState?.("NumLock")&&(t|=ut.NUM_LOCK),e.getModifierState?.("ScrollLock")&&(t|=ut.SCROLL_LOCK),this.client.sendKeyboardSync(t)}attachInput(e){this.client=e,this.keyboardSynced=!1;let t=()=>this.client&&this.client.connected&&!this.viewOnly,s=null,r=!1,i=0,o=!1,a=0,c=0,h=0,m=0,g={x:0,y:0},E=0,y=0,f=0,l=null,S=u=>({x:(u[0].clientX+u[1].clientX)/2,y:(u[0].clientY+u[1].clientY)/2}),A=u=>Math.hypot(u[0].clientX-u[1].clientX,u[0].clientY-u[1].clientY),T=()=>{r=!1,s&&t()&&this.client.sendMouseMove(s.x,s.y),s=null};this.handlers={mousemove:u=>{t()&&(s=this.#r(u),r||(r=!0,requestAnimationFrame(T)))},mousedown:u=>{if(this.canvas.focus(),!t())return;u.preventDefault();let{x:d,y:x}=this.#r(u);this.client.sendMouseButton(u.button,!0,d,x)},mouseup:u=>{if(!t())return;u.preventDefault();let{x:d,y:x}=this.#r(u);this.client.sendMouseButton(u.button,!1,d,x)},contextmenu:u=>u.preventDefault(),wheel:u=>{if(!t())return;u.preventDefault();let d=u.deltaY;if(u.deltaMode===WheelEvent.DOM_DELTA_LINE&&(d*=Yo),u.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(d*=Math.max(1,this.canvas.clientHeight||this.height)),!d||(i&&Math.sign(i)!==Math.sign(d)&&(i=0),i+=d,Math.abs(i)<Fs))return;let x=Math.sign(i);i-=x*Fs;let{x:R,y:C}=this.#r(u);this.client.sendWheel(x,R,C)},touchstart:u=>{if(this.canvas.focus(),!!t()){if(u.preventDefault(),u.touches.length===1){l="tap";let d=u.touches[0];a=d.clientX,c=d.clientY;let{x,y:R}=this.#r(d);this.client.sendMouseMove(x,R),this.client.sendMouseButton(0,!0,x,R),o=!0}else if(u.touches.length===2){if(l="undecided",o){let{x:R,y:C}=this.#r({clientX:a,clientY:c});this.client.sendMouseButton(0,!1,R,C),o=!1}let d=S(u.touches),x=A(u.touches);g={x:d.x,y:d.y},E=x,h=d.y,m=d.x,y=x,f=0}}},touchmove:u=>{if(t()){if(u.preventDefault(),u.touches.length===1&&l==="tap"){let d=u.touches[0];a=d.clientX,c=d.clientY;let{x,y:R}=this.#r(d);this.client.sendMouseMove(x,R)}else if(u.touches.length===2){let d=S(u.touches),x=d.x,R=d.y,C=A(u.touches),I=h-R,v=m-x;h=R,m=x;let U=Math.hypot(x-g.x,R-g.y),Q=Math.abs(C-E),me=E>0?C/E:1;if((l==="undecided"||l==="gesture")&&(Q>20&&Math.abs(me-1)>.15&&Q>U*.8?l="pinch":U>8&&(l="scroll")),l==="pinch")y>0&&Math.abs(C-y)>1&&(this.userZoomed=!0,this.setZoom(this.zoom*(C/y),{x,y:R})),y=C;else if(l==="scroll"){if(y=C,this.canPan()){this.panBy(v*-1,I*-1),f=0;return}for(I&&f&&Math.sign(f)!==Math.sign(I)&&(f=0),f+=I;Math.abs(f)>=Bs;){let le=Math.sign(f);f-=le*Bs;let{x:Le,y:ue}=this.#r({clientX:x,clientY:R});this.client.sendWheel(le,Le,ue)}}}}},touchend:u=>{if(t())if(u.preventDefault(),u.touches.length===0){if(o){let{x:d,y:x}=this.#r({clientX:a,clientY:c});this.client.sendMouseButton(0,!1,d,x),o=!1}l==="pinch"&&this.zoom<=1.05&&this.resetZoom(),l=null,f=0,y=0}else u.touches.length===1&&(l==="gesture"||l==="pinch"||l==="scroll"||l==="undecided")&&(l==="pinch"&&this.zoom<=1.05&&this.resetZoom(),l=null,y=0,f=0)},touchcancel:u=>{if(t()){if(o){let{x:d,y:x}=this.#r({clientX:a,clientY:c});this.client.sendMouseButton(0,!1,d,x),o=!1}l==="pinch"&&this.zoom<=1.05&&this.resetZoom(),l=null,f=0,y=0}},keydown:u=>{if(!t()||(this.#c(u),this.#a(u)))return;let d=this.#i(u.code);if(this.client.sendKeyByCode(d,!0)){if(u.preventDefault(),nn&&u.metaKey&&!Ks[u.code]){this.client.sendKeyByCode(d,!1);return}this.heldKeys.add(d)}},keyup:u=>{if(!t()||this.#a(u))return;let d=this.#i(u.code);this.client.sendKeyByCode(d,!1)&&(this.heldKeys.delete(d),u.preventDefault())},paste:u=>{if(!t())return;let d=u.target,x=d instanceof Node&&this.container.contains(d);if(document.activeElement!==this.canvas&&!x)return;u.preventDefault();let R=u.clipboardData?.getData("text/plain")||"";R&&this.client.pasteToHost(R)},blur:()=>this.releaseAllKeys()},this.canvas.addEventListener("mousemove",this.handlers.mousemove),this.canvas.addEventListener("mousedown",this.handlers.mousedown),this.canvas.addEventListener("mouseup",this.handlers.mouseup),this.canvas.addEventListener("contextmenu",this.handlers.contextmenu),this.canvas.addEventListener("wheel",this.handlers.wheel,{passive:!1}),this.canvas.addEventListener("touchstart",this.handlers.touchstart,{passive:!1}),this.canvas.addEventListener("touchmove",this.handlers.touchmove,{passive:!1}),this.canvas.addEventListener("touchend",this.handlers.touchend,{passive:!1}),this.canvas.addEventListener("touchcancel",this.handlers.touchcancel,{passive:!1}),this.canvas.addEventListener("keydown",this.handlers.keydown),this.canvas.addEventListener("keyup",this.handlers.keyup),this.canvas.addEventListener("blur",this.handlers.blur),document.addEventListener("paste",this.handlers.paste)}#i(e){return nn&&Ks[e]||e}#a(e){return e.code!=="KeyV"?!1:nn?e.metaKey:e.ctrlKey}releaseAllKeys(){if(this.client){for(let e of this.heldKeys)this.client.sendKeyByCode(e,!1);this.heldKeys.clear()}}focus(){this.canvas.focus()}blur(){this.canvas.blur()}destroy(){this.releaseAllKeys(),window.removeEventListener("resize",this.onWindowResize),this.resizeObserver?.disconnect(),this.handlers&&(this.canvas.removeEventListener("mousemove",this.handlers.mousemove),this.canvas.removeEventListener("mousedown",this.handlers.mousedown),this.canvas.removeEventListener("mouseup",this.handlers.mouseup),this.canvas.removeEventListener("contextmenu",this.handlers.contextmenu),this.canvas.removeEventListener("wheel",this.handlers.wheel),this.canvas.removeEventListener("touchstart",this.handlers.touchstart),this.canvas.removeEventListener("touchmove",this.handlers.touchmove),this.canvas.removeEventListener("touchend",this.handlers.touchend),this.canvas.removeEventListener("touchcancel",this.handlers.touchcancel),this.canvas.removeEventListener("keydown",this.handlers.keydown),this.canvas.removeEventListener("keyup",this.handlers.keyup),this.canvas.removeEventListener("blur",this.handlers.blur),document.removeEventListener("paste",this.handlers.paste)),this.client=null}};var We={vnc:5900,rdp:3389,ssh:22},Pc=We.ssh;var Dc=5*6e4;var Xo={usernameLabel:"Username",usernamePlaceholder:"Windows username",usernameHelp:"Use the Windows account name for this computer.",passwordLabel:"Password",passwordPlaceholder:"Windows password",passwordHelp:"Use the Windows account password. It may be left empty when the host presents its own sign-in screen.",requiresPassword:!1};function zo(n,e){let t=new URLSearchParams({host:e.host,port:String(e.port),security:e.security});return`${n}/rdp-ws?${t}`}function Qo({code:n,reason:e,suffix:t}){return/hybrid_required|requires network level|authenticates before/i.test(e)?`The RDP host signs in before showing a desktop${t}. Enter the Windows username and password and connect again.`:n===1011||/cannot connect|unreachable|tcp error|tcp write/i.test(e)?`The Worker could not keep a TCP connection to the RDP host${t}. Check that Remote Desktop is enabled and listening on this address and port.`:null}var sn=class extends EventTarget{protocol="rdp";constructor(e,t,s={}){super(),this.url=t,this.options=s,this.display=new mt(e),this.display.viewOnly=!!s.viewOnly,this._rfbConnectionState="connecting",this._scaleViewport=s.scaleViewport!==!1,this.display.scaleViewport=this._scaleViewport,this.lastErrorMessage="",this.hostLabel=s.hostLabel||"Remote Desktop",this.#e(s.security||"auto"),this.remoteAppLayoutObserver=s.remoteApp?.program&&typeof ResizeObserver=="function"?new ResizeObserver(()=>this.fitToViewport()):null,this.remoteAppLayoutObserver?.observe(this.display.scrollHost)}#e(e){this.security=e,this.client=new pt(this.url,{width:this.options.width,height:this.options.height,username:this.options.credentials?.username||"",password:this.options.credentials?.password||"",domain:this.options.domain||"",security:e,keyboardLayout:this.options.keyboardLayout||1033,clientName:this.options.clientName||"cf-gateway",remoteApp:this.options.remoteApp||null}),this.client.addEventListener("ready",t=>{let{width:s,height:r}=t.detail;this.display.resize(s,r),this.display.attachInput(this.client),this.display.focus(),this.fitToViewport(),this._rfbConnectionState="connected",this.dispatchEvent(new CustomEvent("connect")),this.dispatchEvent(new CustomEvent("desktopname",{detail:{name:`${this.hostLabel} (${s}x${r})`}}))}),this.client.addEventListener("resize",t=>{let{width:s,height:r}=t.detail;this.display.resize(s,r),this.dispatchEvent(new CustomEvent("desktopname",{detail:{name:`${this.hostLabel} (${s}x${r})`}})),this.fitToViewport()}),this.client.addEventListener("remoteappviewport",t=>{this.display.setViewport(t.detail)}),this.client.addEventListener("bitmap",t=>{this.display.drawRects(t.detail.rects,t.detail.palette),this.dispatchEvent(new CustomEvent("frame",{detail:{rects:t.detail.rects}}))}),this.client.addEventListener("palette",t=>{this.display.palette=t.detail}),this.client.addEventListener("pointer",t=>{this.display.applyPointer(t.detail)}),this.client.addEventListener("clipboard",t=>{this.dispatchEvent(new CustomEvent("clipboard",{detail:{text:t.detail.text}}))}),this.client.addEventListener("remoteappresult",t=>{this.dispatchEvent(new CustomEvent("remoteappresult",{detail:t.detail}))}),this.client.addEventListener("remoteappwindow",t=>{this.dispatchEvent(new CustomEvent("remoteappwindow",{detail:t.detail}))}),this.client.addEventListener("remoteappclosed",t=>{this.dispatchEvent(new CustomEvent("remoteappclosed",{detail:t.detail}))}),this.client.addEventListener("error",t=>{this.lastErrorMessage=t.detail.message}),this.client.addEventListener("close",t=>{this._rfbConnectionState="disconnected",this.remoteAppLayoutObserver?.disconnect(),this.display.destroy(),this.dispatchEvent(new CustomEvent("disconnect",{detail:{clean:!!t.detail.clean,message:this.lastErrorMessage||t.detail.message||"",code:t.detail.code,phase:t.detail.phase}}))})}fitToViewport(){if(!this.options.remoteApp?.program)return!1;let e=this.display.container.getBoundingClientRect(),t=Math.floor(e.width||this.options.width||0),s=Math.floor(e.height||this.options.height||0);return t<=0||s<=0?!1:this.client.fitRemoteApp(t,s)}get connected(){return this._rfbConnectionState==="connected"}get canvas(){return this.display?.canvas??null}get socket(){return this.client.socket??null}get _sock(){return{_websocket:this.client.socket}}get scaleViewport(){return this._scaleViewport}set scaleViewport(e){this._scaleViewport=!!e,this.display.setScaleViewport(this._scaleViewport)}get viewOnly(){return this.display.viewOnly}set viewOnly(e){this.display.viewOnly=!!e,e&&this.display.releaseAllKeys()}sendKey(e,t,s){t&&this.client.sendKeyByCode(t,s)||!s||!e||e>=32&&e<=1114111&&this.client.sendUnicode(String.fromCodePoint(e))}sendCtrlAltDel(){this.client.sendCtrlAltDel()}movePointer(e,t){return!this.client?.connected||this.display.viewOnly?!1:(this.client.sendMouseMove(...this.#t(e,t)),!0)}clickPointer(e,t,s=0){if(!this.client?.connected||this.display.viewOnly)return!1;let[r,i]=this.#t(e,t);return this.client.sendMouseMove(r,i),this.pointerButton(r,i,s,!0),this.pointerButton(r,i,s,!1),!0}pointerButton(e,t,s=0,r=!0){if(!this.client?.connected||this.display.viewOnly)return!1;let[i,o]=this.#t(e,t);return this.client.sendMouseButton(s,r,i,o),!0}scrollPointer(e,t,s){if(!this.client?.connected||this.display.viewOnly)return!1;let[r,i]=this.#t(e,t);for(let o=0;o<Math.min(20,Math.abs(s.y));o++)this.client.sendWheel(Math.sign(s.y),r,i,!1);for(let o=0;o<Math.min(20,Math.abs(s.x));o++)this.client.sendWheel(Math.sign(s.x),r,i,!0);return!0}typeText(e){if(!this.client?.connected||this.display.viewOnly||!e)return!1;let t="",s=()=>{t&&(this.client.sendUnicode(t),t="")};for(let r of e)r===`
|
|
2
|
+
`||r==="\r"?(s(),this.client.sendKeyByCode("Enter",!0),this.client.sendKeyByCode("Enter",!1)):r===" "?(s(),this.client.sendKeyByCode("Tab",!0),this.client.sendKeyByCode("Tab",!1)):t+=r;return s(),!0}#t(e,t){return[Math.max(0,Math.min((this.display.width||1)-1,Math.round(e))),Math.max(0,Math.min((this.display.height||1)-1,Math.round(t)))]}get screenGeometry(){return{width:this.display.width,height:this.display.height,viewport:{...this.display.viewport}}}clipboardPasteFrom(e){if(!e)return;let t=this.client.setClipboardText(e);if(!t||typeof t.then!="function"){this.client.sendUnicode(e);return}t.then(s=>{s||this.client.sendUnicode(e)})}pasteText(e){return e?this.client.pasteToHost(e):!1}releaseKeyboard(){this.display.releaseAllKeys(),this.display.blur()}get clipboardShared(){return this.client.clipboardShared}disconnect(){this.remoteAppLayoutObserver?.disconnect(),this.client.disconnect(),this.display.destroy(),this._rfbConnectionState="disconnected"}},Gs={protocol:"rdp",label:"RDP Client",defaultPort:We.rdp,dialog:Xo,buildUrl:zo,createSession:(n,e,t)=>new sn(n,e,t),describeState:()=>({}),describeDisconnect:Qo};import rn from"@novnc/novnc";function Ws(n){let e=[],t=[{amount:n.y,negativeMask:8,positiveMask:16},{amount:n.x,negativeMask:32,positiveMask:64}];for(let{amount:s,negativeMask:r,positiveMask:i}of t){let o=s<0?r:i;for(let a=0;a<Math.min(20,Math.abs(s));a++)e.push(o)}return e}var jo={usernameLabel:"Username",usernamePlaceholder:"macOS username (optional)",usernameHelp:"Use your macOS account name. Leave it empty when the VNC server only asks for a password.",passwordLabel:"Password",passwordPlaceholder:"Screen sharing password",passwordHelp:"Use the macOS account password, or the password configured for VNC screen sharing.",requiresPassword:!0};function Zo(n,e){let t=new URLSearchParams({host:e.host,port:String(e.port)});return e.username&&t.set("vnc_user",e.username),e.password&&t.set("vnc_pass",e.password),`${n}/ws?${t}`}var Vs={0:1,1:2,2:4};function Jo(n){if(!("detail"in n))return{};let e=n.detail;if(!e||typeof e!="object")return{};let t={};for(let[s,r]of Object.entries(e))t[s]=r;return t}var Et=class extends EventTarget{protocol="vnc";#e;#t;#s=null;#n=null;#r=!1;#c=null;constructor(e,t,s){super(),this.#t=s.credentials,this.#e=new rn(e,t,{credentials:{username:s.credentials.username,password:s.credentials.password},shared:!0,wsProtocols:["binary"]}),this.#e._cursor?._canvas?.classList.add("remote-cursor-overlay"),this.#e.showDotCursor=!0,this.#e.resizeSession=s.allowRemoteResize,this.#e.clipViewport=!0,this.#e.scaleViewport=s.scaleViewport,this.#e.viewOnly=s.viewOnly,this.#e.qualityLevel=s.quality,this.#e.compressionLevel=s.compression,this.#i();for(let r of["connect","disconnect","credentialsrequired","desktopname","clipboard","bell"])this.#e.addEventListener(r,i=>{r==="credentialsrequired"&&this.#e.sendCredentials({username:this.#t.username,password:this.#t.password});let o=Jo(i);r==="disconnect"&&this.#c&&(o.code=this.#c.code,o.reason=this.#c.reason),this.dispatchEvent(new CustomEvent(r,{detail:o}))})}#i(){let e=()=>{let r=this.#e._sock?._websocket??null;if(!r||this.#s===r)return!!r;this.#s=r;let i=()=>{this.#r||r.readyState!==WebSocket.OPEN||(this.#r=!0,r.send(Ce))};return r.addEventListener("open",i),r.addEventListener("close",o=>{this.#c={code:o.code,reason:o.reason??""},this.#a()},!0),this.#n=setInterval(()=>{if(r.readyState===WebSocket.OPEN)try{r.send(Re);let o=this.#e._sock;o&&this.#e._rfbConnectionState==="connected"&&rn.messages.fbUpdateRequest(o,!0,0,0,1,1)}catch{}},25e3),i(),!0};if(e())return;let t=0,s=setInterval(()=>{(e()||++t>20)&&clearInterval(s)},25)}#a(){this.#n&&clearInterval(this.#n),this.#n=null}get connected(){return this.#e._rfbConnectionState==="connected"}get socket(){return this.#e._sock?._websocket??null}get canvas(){return this.#e._canvas}get scaleViewport(){return this.#e.scaleViewport}set scaleViewport(e){this.#e.scaleViewport=e}get viewOnly(){return this.#e.viewOnly}set viewOnly(e){this.#e.viewOnly=e}get qualityLevel(){return this.#e.qualityLevel}set qualityLevel(e){this.#e.qualityLevel=e}get compressionLevel(){return this.#e.compressionLevel}set compressionLevel(e){this.#e.compressionLevel=e}get screenGeometry(){let e=this.#e._fbWidth||0,t=this.#e._fbHeight||0;return{width:e,height:t,viewport:{x:0,y:0,width:e,height:t}}}describeState(){let e=this.#e._sock;return{connectionState:this.#e._rfbConnectionState,initializationState:this.#e._rfbInitState,queuedReceiveBytes:Math.max(0,(e?._rQlen??0)-(e?._rQi??0))}}disconnect(){this.#a(),this.#e.disconnect()}sendKey(e,t,s){this.#e.sendKey(e,t,s)}sendClipboard(e){this.#e.clipboardPasteFrom(e)}releaseKeyboard(){this.#e.blur()}#o(e,t,s){let r=this.#e._sock;if(!r||this.#e._rfbConnectionState!=="connected"||this.#e.viewOnly)return!1;let i=this.#e._fbWidth||1,o=this.#e._fbHeight||1;return rn.messages.pointerEvent(r,Math.max(0,Math.min(i-1,Math.round(e))),Math.max(0,Math.min(o-1,Math.round(t))),s),!0}movePointer(e,t){return this.#o(e,t,0)}clickPointer(e,t,s=0){return this.#o(e,t,0)?(this.#o(e,t,Vs[s]),this.#o(e,t,0),!0):!1}pointerButton(e,t,s=0,r=!0){return this.#o(e,t,r?Vs[s]:0)}scrollPointer(e,t,s){for(let r of Ws(s))if(!this.#o(e,t,r)||!this.#o(e,t,0))return!1;return!0}typeText(e){if(this.#e._rfbConnectionState!=="connected"||this.#e.viewOnly||!e)return!1;for(let t of e){let s=t.codePointAt(0)??0,r=t===`
|
|
3
|
+
`?65293:t===" "?65289:s;this.#e.sendKey(r,null,!0),this.#e.sendKey(r,null,!1)}return!0}};function ea({code:n,reason:e,suffix:t}){return n===4001||/auth|password|credential/i.test(e)?`VNC authentication failed${t}. Verify the macOS account username and its password.`:n===4002||/apple dh/i.test(e)?`macOS VNC authentication handshake failed${t}.`:n===1011||/cannot connect|unreachable|tcp error|tcp write/i.test(e)?`The Worker could not keep a TCP connection to the VNC host${t}. Check that Screen Sharing is running and listening on this address.`:null}var Ys={protocol:"vnc",label:"VNC Client",defaultPort:We.vnc,dialog:jo,buildUrl:Zo,createSession:(n,e,t)=>new Et(n,e,t),describeState:n=>n instanceof Et?n.describeState():{},describeDisconnect:ea};var w={DISCONNECT:1,IGNORE:2,UNIMPLEMENTED:3,DEBUG:4,SERVICE_REQUEST:5,SERVICE_ACCEPT:6,EXT_INFO:7,KEXINIT:20,NEWKEYS:21,KEX_ECDH_INIT:30,KEX_ECDH_REPLY:31,USERAUTH_REQUEST:50,USERAUTH_FAILURE:51,USERAUTH_SUCCESS:52,USERAUTH_BANNER:53,USERAUTH_INFO_REQUEST:60,USERAUTH_PK_OK:60,USERAUTH_INFO_RESPONSE:61,GLOBAL_REQUEST:80,REQUEST_SUCCESS:81,REQUEST_FAILURE:82,CHANNEL_OPEN:90,CHANNEL_OPEN_CONFIRMATION:91,CHANNEL_OPEN_FAILURE:92,CHANNEL_WINDOW_ADJUST:93,CHANNEL_DATA:94,CHANNEL_EXTENDED_DATA:95,CHANNEL_EOF:96,CHANNEL_CLOSE:97,CHANNEL_REQUEST:98,CHANNEL_SUCCESS:99,CHANNEL_FAILURE:100},$s=1,qs={1:"the host reported a protocol error",2:"the host could not agree on a key exchange method",3:"the key exchange failed",5:"the host ran out of resources",6:"the connection was lost below SSH",7:"the host application ended the connection",8:"too many connections",9:"authentication was cancelled by the user",10:"no more authentication methods are available",11:"the host closed the connection",12:"authentication was cancelled by the host",14:"the host refused the authentication attempt",15:"the host closed the connection while authenticating"};var ta=new TextEncoder,na=new TextDecoder;function oe(n){return ta.encode(n)}function Ve(n){return na.decode(n)}function ne(...n){let e=n.reduce((r,i)=>r+i.length,0),t=new Uint8Array(e),s=0;for(let r of n)t.set(r,s),s+=r.length;return t}function Ye(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e)}function on(n){return Ye(n).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}var N=class{bytes;view;offset=0;constructor(e=256){this.bytes=new Uint8Array(new ArrayBuffer(e)),this.view=new DataView(this.bytes.buffer)}#e(e){if(this.offset+e<=this.bytes.length)return;let t=Math.max(this.bytes.length*2,64);for(;t<this.offset+e;)t*=2;let s=new Uint8Array(new ArrayBuffer(t));s.set(this.bytes.subarray(0,this.offset)),this.bytes=s,this.view=new DataView(s.buffer)}u8(e){return this.#e(1),this.view.setUint8(this.offset,e),this.offset+=1,this}boolean(e){return this.u8(e?1:0)}u32(e){return this.#e(4),this.view.setUint32(this.offset,e>>>0,!1),this.offset+=4,this}raw(e){return this.#e(e.length),this.bytes.set(e,this.offset),this.offset+=e.length,this}string(e){let t=typeof e=="string"?oe(e):e;return this.u32(t.length).raw(t)}nameList(e){return this.string(e.join(","))}mpint(e){let t=0;for(;t<e.length&&e[t]===0;)t++;let s=e.subarray(t);return s.length===0?this.u32(0):(s[0]??0)&128?(this.u32(s.length+1).u8(0),this.raw(s)):this.u32(s.length).raw(s)}get length(){return this.offset}take(){return this.bytes.slice(0,this.offset)}},O=class{bytes;view;offset;constructor(e,t=0){this.bytes=e,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.offset=t}get remaining(){return this.bytes.length-this.offset}#e(e){if(e<0||this.remaining<e)throw new Error(`SSH: truncated packet (needed ${e} bytes, ${this.remaining} left)`)}u8(){return this.#e(1),this.view.getUint8(this.offset++)}boolean(){return this.u8()!==0}u32(){this.#e(4);let e=this.view.getUint32(this.offset,!1);return this.offset+=4,e}raw(e){this.#e(e);let t=this.bytes.subarray(this.offset,this.offset+e);return this.offset+=e,t}stringBytes(){return this.raw(this.u32())}string(){return Ve(this.stringBytes())}nameList(){let e=this.string();return e?e.split(","):[]}mpint(){let e=this.stringBytes(),t=0;for(;t<e.length&&e[t]===0;)t++;return e.subarray(t)}skip(e){return this.#e(e),this.offset+=e,this}rest(){return this.bytes.subarray(this.offset)}};function an(n,e){if(n.length===e)return n;if(n.length>e)return n.subarray(n.length-e);let t=new Uint8Array(e);return t.set(n,e-n.length),t}var H=globalThis.crypto?.subtle,sa={"curve25519-sha256":{type:"x25519",hash:"SHA-256"},"curve25519-sha256@libssh.org":{type:"x25519",hash:"SHA-256"},"ecdh-sha2-nistp256":{type:"ecdh",curve:"P-256",hash:"SHA-256"}},cn={"ssh-ed25519":{keyType:"ssh-ed25519",kind:"ed25519"},"rsa-sha2-512":{keyType:"ssh-rsa",kind:"rsa",hash:"SHA-512"},"rsa-sha2-256":{keyType:"ssh-rsa",kind:"rsa",hash:"SHA-256"},"ecdsa-sha2-nistp256":{keyType:"ecdsa-sha2-nistp256",kind:"ecdsa",curve:"P-256",hash:"SHA-256"}};async function Xs(n,e){if(!H)return!1;try{return await H.generateKey(n,!1,e),!0}catch{return!1}}var yt=null;async function zs(){if(yt)return yt;let[n,e]=await Promise.all([Xs({name:"X25519"},["deriveBits"]),Xs({name:"Ed25519"},["sign","verify"])]),t=[];n&&t.push("curve25519-sha256","curve25519-sha256@libssh.org"),t.push("ecdh-sha2-nistp256");let s=[];return e&&s.push("ssh-ed25519"),s.push("rsa-sha2-512","rsa-sha2-256","ecdsa-sha2-nistp256"),yt={kex:t,hostKey:s,x25519:n,ed25519:e},yt}async function Qs(n){let e=sa[n];if(!e)throw new Error(`SSH: unsupported key exchange ${n}`);if(e.type==="x25519"){let r=await H.generateKey({name:"X25519"},!1,["deriveBits"]),i=new Uint8Array(await H.exportKey("raw",r.publicKey));return{hash:e.hash,publicKey:i,async sharedSecret(o){if(o.length!==32)throw new Error("SSH: the host sent a malformed X25519 key.");let a=await H.importKey("raw",o,{name:"X25519"},!1,[]),c=new Uint8Array(await H.deriveBits({name:"X25519",public:a},r.privateKey,256));if(c.every(h=>h===0))throw new Error("SSH: the host sent a degenerate X25519 key.");return c}}}let t=await H.generateKey({name:"ECDH",namedCurve:e.curve},!1,["deriveBits"]),s=new Uint8Array(await H.exportKey("raw",t.publicKey));return{hash:e.hash,publicKey:s,async sharedSecret(r){let i=await H.importKey("raw",r,{name:"ECDH",namedCurve:e.curve},!1,[]);return new Uint8Array(await H.deriveBits({name:"ECDH",public:i},t.privateKey,256))}}}function js(n){return new O(n).string()}async function Zs(n){let e=new Uint8Array(await H.digest("SHA-256",n));return`SHA256:${Ye(e).replace(/=+$/,"")}`}async function ra(n,e){let t=cn[n];if(!t)throw new Error(`SSH: unsupported host key algorithm ${n}`);let s=new O(e),r=s.string();if(r!==t.keyType)throw new Error(`SSH: the host key is a ${r} but was announced as ${n}.`);if(t.kind==="ed25519")return H.importKey("raw",s.stringBytes(),{name:"Ed25519"},!1,["verify"]);if(t.kind==="rsa"){let i=s.mpint(),o=s.mpint();return H.importKey("jwk",{kty:"RSA",n:on(o),e:on(i),ext:!0},{name:"RSASSA-PKCS1-v1_5",hash:t.hash},!1,["verify"])}return s.string(),H.importKey("raw",s.stringBytes(),{name:"ECDSA",namedCurve:t.curve},!1,["verify"])}function ia(n,e){let t=new O(e),s=t.string();if(s!==n)throw new Error(`SSH: the host signed with ${s} after agreeing on ${n}.`);let r=t.stringBytes();if(cn[n]?.kind!=="ecdsa")return r;let i=new O(r),o=i.mpint(),a=i.mpint();return ne(an(o,32),an(a,32))}async function Js({algorithm:n,keyBlob:e,signatureBlob:t,exchangeHash:s}){let{kind:r,hash:i}=cn[n],o=await ra(n,e),a=ia(n,t),c=r==="ecdsa"?{name:"ECDSA",hash:i}:r==="rsa"?{name:"RSASSA-PKCS1-v1_5"}:{name:"Ed25519"};return H.verify(c,o,a,s)}async function er({hash:n,clientVersion:e,serverVersion:t,clientKexInit:s,serverKexInit:r,hostKeyBlob:i,clientPublicKey:o,serverPublicKey:a,sharedSecret:c}){let h=new N(1024);return h.string(e),h.string(t),h.string(s),h.string(r),h.string(i),h.string(o),h.string(a),h.mpint(c),new Uint8Array(await H.digest(n,h.take()))}async function $e({hash:n,sharedSecret:e,exchangeHash:t,letter:s,sessionId:r,length:i}){let o=new N(64+t.length).mpint(e).take(),a=ne(o,t,new Uint8Array([s.charCodeAt(0)]),r),c=new Uint8Array(await H.digest(n,a));for(;c.length<i;){let h=new Uint8Array(await H.digest(n,ne(o,t,c)));c=ne(c,h)}return c.subarray(0,i)}var tr="SSH-2.0-CloudflareGateway_1.0",un={"aes256-gcm@openssh.com":{keyLength:32},"aes128-gcm@openssh.com":{keyLength:16}},gt=Object.keys(un),nr=["hmac-sha2-256","hmac-sha2-512"],sr=["none"],qe=16,hn=16,rr=12,ln=8,or=4,ir=262144,oa=8192,dn=globalThis.crypto?.subtle;function wt(n,e){return n.find(t=>e.includes(t))||null}var At=class n{key;fixed;counter;constructor(e,t){this.key=e,this.fixed=t.slice(0,4),this.counter=t.slice(4,12)}static async create(e,t){let s=await dn.importKey("raw",e,{name:"AES-GCM"},!1,["encrypt","decrypt"]);return new n(s,t)}nextIv(){let e=ne(this.fixed,this.counter);for(let t=this.counter.length-1;t>=0&&(this.counter[t]=this.counter[t]+1&255,this.counter[t]===0);t--);return e}},St=class extends EventTarget{url;verifyHost;log;socket;openTransport;closed;buffer;serverVersion;greeting;sendSequence;receiveSequence;outgoing;incoming;sessionId;kex;kexQueue;keepaliveTimer;bytesSent;bytesReceived;encryptChain;newKeysBarrier;releaseNewKeys;pendingServerKexInit;established;constructor(e,{verifyHost:t,log:s,openTransport:r}={}){super(),this.url=e,this.verifyHost=t||(()=>!0),this.log=s||(()=>{}),this.openTransport=r||null,this.socket=null,this.closed=!1,this.buffer=new Uint8Array(0),this.serverVersion="",this.greeting=[],this.sendSequence=0,this.receiveSequence=0,this.outgoing=null,this.incoming=null,this.sessionId=null,this.kex=null,this.kexQueue=[],this.keepaliveTimer=null,this.bytesSent=0,this.bytesReceived=0}connect(){this.socket=this.openTransport?this.openTransport(this.url):new WebSocket(this.url),this.socket.binaryType="arraybuffer",this.socket.addEventListener("open",()=>{this.socket.send(Ce),this.#t(oe(`${tr}\r
|
|
4
|
+
`)),this.keepaliveTimer=setInterval(()=>{if(this.socket?.readyState===WebSocket.OPEN&&(this.socket.send(Re),this.sessionId))try{this.#h(new N(64).u8(w.GLOBAL_REQUEST).string("keepalive@openssh.com").u8(1).take())}catch{}},25e3)}),this.socket.addEventListener("message",e=>{typeof e.data!="string"&&this.#s(new Uint8Array(e.data))}),this.socket.addEventListener("close",e=>{this.#e({clean:e.code===1e3,code:e.code,message:e.reason||(e.code===1006?"The gateway rejected or could not reach this SSH target. Confirm that SSH is published for this host.":"")})}),this.socket.addEventListener("error",()=>{this.log("The SSH gateway WebSocket reported a transport error; waiting for its close reason.")})}disconnect(e="Client disconnected"){if(this.closed)return;try{let s=new N(64).u8(w.DISCONNECT).u32(11).string(e).string("").take();this.#h(s)}catch{}let t=this.socket;Promise.resolve(this.encryptChain).finally(()=>{try{t?.close(1e3,"Client disconnected")}catch{}}),this.#e({clean:!0,code:1e3,message:""})}#e(e){this.closed||(this.closed=!0,clearInterval(this.keepaliveTimer),this.keepaliveTimer=null,this.dispatchEvent(new CustomEvent("close",{detail:e})))}fail(e){let t=e instanceof Error?e.message:String(e);if(!this.closed){this.dispatchEvent(new CustomEvent("error",{detail:{message:t}})),this.#e({clean:!1,code:4e3,message:t});try{this.socket?.close(4e3,t.slice(0,100))}catch{}}}#t(e){this.socket?.readyState===WebSocket.OPEN&&(this.bytesSent+=e.length,this.socket.send(e))}#s(e){this.bytesReceived+=e.length,this.buffer=this.buffer.length?ne(this.buffer,e):e,this.drainChain=(this.drainChain||Promise.resolve()).then(()=>this.#n()).catch(t=>this.fail(t))}async#n(){if(!this.closed&&!(!this.serverVersion&&!this.#r()))for(;!this.closed;){if(this.newKeysBarrier){let t=this.newKeysBarrier;this.newKeysBarrier=null,await t;continue}if(!this.incoming){let t=this.#c();if(!t)return;this.#o(t);continue}let e=this.#i();if(!e)return;this.#o(await this.#a(e))}}#r(){for(;;){let e=this.buffer.indexOf(10);if(e===-1){if(this.buffer.length>oa)throw new Error("SSH: the host sent no version line.");return!1}let t=e;t>0&&this.buffer[t-1]===13&&t--;let s=new TextDecoder().decode(this.buffer.subarray(0,t));if(this.buffer=this.buffer.subarray(e+1),!s.startsWith("SSH-")){s.trim()&&this.greeting.push(s);continue}if(!s.startsWith("SSH-2.0-")&&!s.startsWith("SSH-1.99-"))throw new Error(`SSH: this host speaks ${s.split("-").slice(0,2).join("-")}, which is too old.`);return this.serverVersion=s,this.log("version",{server:s,greeting:this.greeting}),this.dispatchEvent(new CustomEvent("greeting",{detail:{lines:this.greeting.slice()}})),this.#p(),!0}}#c(){if(this.buffer.length<5)return null;let t=new DataView(this.buffer.buffer,this.buffer.byteOffset,this.buffer.byteLength).getUint32(0,!1);if(t<8||t>ir)throw new Error("SSH: the host sent a packet of an impossible size.");if(this.buffer.length<4+t)return null;let s=this.buffer[4];if(s+1>t)throw new Error("SSH: a packet claimed more padding than it had.");let r=this.buffer.slice(5,4+t-s);return this.buffer=this.buffer.subarray(4+t),this.receiveSequence=this.receiveSequence+1>>>0,r}#i(){if(this.buffer.length<4)return null;let t=new DataView(this.buffer.buffer,this.buffer.byteOffset,this.buffer.byteLength).getUint32(0,!1);if(t<qe||t%qe!==0||t>ir)throw new Error("SSH: the host sent a packet of an impossible size.");let s=4+t+hn;if(this.buffer.length<s)return null;let r=this.buffer.slice(0,s);return this.buffer=this.buffer.subarray(s),r}async#a(e){let t;try{t=new Uint8Array(await dn.decrypt({name:"AES-GCM",iv:this.incoming.nextIv(),additionalData:e.subarray(0,4),tagLength:hn*8},this.incoming.key,e.subarray(4)))}catch{throw new Error("SSH: a packet failed its integrity check, so the session was dropped.")}let s=t[0];if(s+1>t.length)throw new Error("SSH: a packet claimed more padding than it had.");return this.receiveSequence=this.receiveSequence+1>>>0,t.slice(1,t.length-s)}#o(e){if(e.length===0)return;let t=e[0];switch(t){case w.DISCONNECT:{let s=new O(e,1),r=s.u32(),o=s.string()||qs[r]||`reason ${r}`;this.dispatchEvent(new CustomEvent("hostdisconnect",{detail:{code:r,reason:o}})),this.#e({clean:r===11,code:1e3,message:o});try{this.socket?.close(1e3,"Host disconnected")}catch{}return}case w.IGNORE:case w.UNIMPLEMENTED:case w.EXT_INFO:return;case w.DEBUG:{let s=new O(e,1),r=s.boolean(),i=s.string();this.log("debug",{message:i,alwaysDisplay:r}),r&&this.dispatchEvent(new CustomEvent("banner",{detail:{text:`${i}\r
|
|
5
|
+
`}}));return}case w.KEXINIT:this.#E(e);return;case w.NEWKEYS:this.#d();return;case w.GLOBAL_REQUEST:{let s=new O(e,1);s.string(),s.boolean()&&this.#h(new Uint8Array([w.REQUEST_FAILURE]));return}case w.REQUEST_SUCCESS:case w.REQUEST_FAILURE:return;default:break}if(this.kex&&t>=30&&t<=49){this.#u(e);return}this.dispatchEvent(new CustomEvent("packet",{detail:{type:t,payload:e}}))}send(e){return this.closed?!1:this.kex?.running?(this.kexQueue.push(e),!0):(this.#h(e),!0)}#h(e){if(!(this.closed||this.socket?.readyState!==WebSocket.OPEN)){if(!this.outgoing){this.#t(ca(e)),this.sendSequence=this.sendSequence+1>>>0;return}this.#l(e)}}async#l(e){let t=this.encryptChain||Promise.resolve();return this.encryptChain=t.then(async()=>{if(this.closed||!this.outgoing)return;let s=aa(e.length),r=new Uint8Array(1+e.length+s);r[0]=s,r.set(e,1),crypto.getRandomValues(r.subarray(1+e.length));let i=new N(4).u32(r.length).take(),o=new Uint8Array(await dn.encrypt({name:"AES-GCM",iv:this.outgoing.nextIv(),additionalData:i,tagLength:hn*8},this.outgoing.key,r));this.#t(ne(i,o)),this.sendSequence=this.sendSequence+1>>>0}).catch(s=>this.fail(s)),this.encryptChain}async#p(){if(!this.kex?.running){this.kex={running:!0,clientKexInit:null,pending:null,inbox:[]};try{let e=await zs(),t=ha(e);this.kex.clientKexInit=t,this.#h(t);let s=this.pendingServerKexInit||await this.#y(w.KEXINIT);this.pendingServerKexInit=null,await this.#g(e,t,s)}catch(e){this.fail(e)}}}async#E(e){if(this.kex?.running){this.#u(e);return}this.log("rekey",{reason:"the host asked for new keys"}),this.pendingServerKexInit=e,await this.#p()}#u(e){if(this.kex){if(this.kex.pending){let t=this.kex.pending;this.kex.pending=null,t(e);return}this.kex.inbox.push(e)}}#y(e){return new Promise((t,s)=>{let r=o=>{if(e!==void 0&&o[0]!==e){s(new Error(`SSH: expected message ${e} during key exchange but got ${o[0]}.`));return}t(o)},i=this.kex.inbox.shift();if(i){r(i);return}this.kex.pending=o=>{this.kex.pending=null,r(o)}})}async#g(e,t,s){let r=la(s),i=wt(e.kex,r.kex),o=wt(e.hostKey,r.hostKey),a=wt(gt,r.cipherClientToServer),c=wt(gt,r.cipherServerToClient);if(!i)throw new Error(`SSH: no shared key exchange method. The host offers ${r.kex.join(", ")}.`);if(!o)throw new Error(`SSH: no host key type this browser can verify. The host offers ${r.hostKey.join(", ")}.`);if(!a||!c)throw new Error(`SSH: the host does not offer AES-GCM, which is the only cipher this client can use. It offers ${r.cipherServerToClient.join(", ")}.`);this.log("negotiated",{kex:i,hostKey:o,cipher:c,rekey:!!this.sessionId});let h=await Qs(i);this.#h(new N(128).u8(w.KEX_ECDH_INIT).string(h.publicKey).take());let m=new O(await this.#y(w.KEX_ECDH_REPLY),1),g=m.stringBytes(),E=m.stringBytes(),y=m.stringBytes(),f=await h.sharedSecret(E),l=await er({hash:h.hash,clientVersion:tr,serverVersion:this.serverVersion,clientKexInit:t,serverKexInit:s,hostKeyBlob:g,clientPublicKey:h.publicKey,serverPublicKey:E,sharedSecret:f});if(!await Js({algorithm:o,keyBlob:g,signatureBlob:y,exchangeHash:l}))throw new Error("SSH: the host key signature is invalid, so this is not the machine it claims to be.");let A=await Zs(g);if(!this.sessionId){if(!await this.verifyHost({fingerprint:A,keyType:js(g),algorithm:o}))throw new Error("SSH: the host key was not accepted, so the connection was stopped.");this.sessionId=l}this.#h(new Uint8Array([w.NEWKEYS])),await this.#y(w.NEWKEYS);let T={hash:h.hash,sharedSecret:f,exchangeHash:l,sessionId:this.sessionId},[u,d,x,R]=await Promise.all([$e({...T,letter:"A",length:rr}),$e({...T,letter:"B",length:rr}),$e({...T,letter:"C",length:un[a].keyLength}),$e({...T,letter:"D",length:un[c].keyLength})]);this.outgoing=await At.create(x,u),this.incoming=await At.create(R,d),this.kex.running=!1,this.releaseNewKeys?.(),this.releaseNewKeys=null;let C=this.kexQueue;this.kexQueue=[];for(let v of C)this.#h(v);let I=!this.established;this.established=!0,this.dispatchEvent(new CustomEvent("keys",{detail:{fingerprint:A,kexAlgorithm:i,hostKeyAlgorithm:o,cipher:c,firstTime:I}}))}#d(){this.kex&&(this.newKeysBarrier=new Promise(e=>{this.releaseNewKeys=e}),this.#u(new Uint8Array([w.NEWKEYS])))}};function aa(n){let e=1+n,t=qe-e%qe;for(;t<or;)t+=qe;return t}function ca(n){let e=5+n.length,t=ln-e%ln;t<or&&(t+=ln);let s=new N(e+t);s.u32(1+n.length+t),s.u8(t),s.raw(n);let r=s.take(),i=new Uint8Array(t);return crypto.getRandomValues(i),ne(r,i)}function ha(n){let e=new Uint8Array(16);crypto.getRandomValues(e);let t=new N(512);return t.u8(w.KEXINIT).raw(e),t.nameList(n.kex),t.nameList(n.hostKey),t.nameList(gt),t.nameList(gt),t.nameList(nr),t.nameList(nr),t.nameList(sr),t.nameList(sr),t.nameList([]),t.nameList([]),t.boolean(!1),t.u32(0),t.take()}function la(n){let e=new O(n,17);return{kex:e.nameList(),hostKey:e.nameList(),cipherClientToServer:e.nameList(),cipherServerToClient:e.nameList(),macClientToServer:e.nameList(),macServerToClient:e.nameList(),compressionClientToServer:e.nameList(),compressionServerToClient:e.nameList()}}var oh=22,Xe="ssh-connection",ua="xterm-256color",ze=2*1024*1024,fn=32*1024,da=ze/2,fa=new Uint8Array([0]),pa=2e4,ma=5*6e4,Ea=60*6e4,xt=new Uint8Array(0);function ya(n){return`'${String(n).replace(/'/g,"'\\''")}'`}function ar(n){let e=n.slice(-400);return/(?:^|\n)PS [A-Za-z]:\\[^\n]*>\s*$/.test(e)?"powershell":/(?:^|\n)[^\n]*[A-Za-z]:\\[^\n]*>\s*$/.test(e)?"cmd":""}var wa=/is not recognized as an internal or external command|command not found|not recognized as the name of a cmdlet|CommandNotFoundException/i;function ga(n,e,t){if(n==="cmd")return`echo.&echo CCB${t}&${e}&call echo.CCE${t} %^ERRORLEVEL%\r`;if(n==="powershell"){let s=Ye(oe(e));return`Write-Output ""; Write-Output ("CCB" + "${t}"); $__ccCode = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${s}')); $global:LASTEXITCODE = $null; . ([ScriptBlock]::Create($__ccCode)); $__ccOk = $?; $__cc = if ($LASTEXITCODE -ne $null) { $LASTEXITCODE } elseif ($__ccOk) { 0 } else { 1 }; Write-Output ("CCE" + "${t} " + $__cc)\r`}return`printf '\\n%s%s\\n' 'CCB' '${t}'; eval ${ya(e)}; __cc=$?; printf '\\n%s%s %s\\n' 'CCE' '${t}' "$__cc"\r`}function ve(n){return n.replace(/\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)/g,"").replace(/\u001b\[[0-9;?]*[ -/]*[@-~]/g,"").replace(/\u001b[@-Z\\-_]/g,"").replace(/\r\n/g,`
|
|
6
|
+
`).replace(/\r/g,"")}function Aa(n,e){let t=n.displayFilter;if(!t)return e;t.pending+=Ve(e);let s="";if(t.stage==="before"){let i=t.pending.indexOf(t.begin);if(i===-1)return xt;t.pending=t.pending.slice(i+t.begin.length).replace(/^\r?\n/,""),t.stage="inside"}if(t.stage==="inside"){let i=t.pending.indexOf(t.end);if(i===-1)return s=t.pending,t.pending="",s?oe(s):xt;s=t.pending.slice(0,i),t.pending=t.pending.slice(i),t.stage="closing"}let r=t.pending.indexOf(`
|
|
7
|
+
`);return r!==-1&&(s+=t.pending.slice(r+1),n.displayFilter=null),s?oe(s):xt}function Sa(n){let e=n.displayFilter;n.displayFilter=null,!(!e||e.stage!=="before"||!e.pending)&&n.dispatchEvent(new CustomEvent("data",{detail:{bytes:xt,display:oe(e.pending),isStderr:!1}}))}var cr=class extends EventTarget{constructor(e,t={}){super(),this.options=t,this.username=t.username||"",this.password=t.password||"",this.identities=t.identities||[],this.requestInput=t.requestInput||(async()=>""),this.canAsk=!!t.requestInput,this.columns=t.columns||80,this.rows=t.rows||24,this.channelId=0,this.remoteChannelId=null,this.remoteWindow=0,this.remoteMaxPacket=fn,this.localWindow=ze,this.pendingWrites=[],this.shellOpen=!1,this.commandInFlight=!1,this.displayFilter=null,this.readySignaled=!1,this.powerShellAttempted=!1,this.powerShellTimer=null,this.shellFamily="",this.promptTail="",this.exitStatus=null,this.authMethods=[],this.triedKeys=[],this.passwordRejected=!1,this.closed=!1,this.waiters=new Map,this.transport=new St(e,{verifyHost:t.verifyHost||(async()=>!0),openTransport:t.openTransport||null,log:(s,r)=>console.info(`[SSH] ${s}`,r)}),this.transport.addEventListener("packet",s=>{this.#c(s.detail.type,s.detail.payload)}),this.transport.addEventListener("greeting",s=>{for(let r of s.detail.lines)this.#t(`${r}\r
|
|
8
|
+
`)}),this.transport.addEventListener("banner",s=>this.#t(s.detail.text)),this.transport.addEventListener("keys",s=>{this.fingerprint=s.detail.fingerprint,this.#e("secured",`Host key ${s.detail.fingerprint} verified.`),this.dispatchEvent(new CustomEvent("secure",{detail:s.detail})),s.detail.firstTime&&this.#p()}),this.transport.addEventListener("hostdisconnect",s=>{this.lastMessage=s.detail.reason}),this.transport.addEventListener("error",s=>{this.lastMessage=s.detail.message,this.dispatchEvent(new CustomEvent("error",{detail:s.detail}))}),this.transport.addEventListener("close",s=>{this.closed||(this.closed=!0,clearTimeout(this.powerShellTimer),this.#r(s.detail.message||"The SSH connection closed."),this.dispatchEvent(new CustomEvent("close",{detail:{...s.detail,message:s.detail.message||this.lastMessage||"",exitStatus:this.exitStatus}})))})}connect(){this.#e("connecting","Opening the SSH transport\u2026"),this.transport.connect()}disconnect(){this.closed||(clearTimeout(this.powerShellTimer),this.shellOpen&&this.remoteChannelId!==null&&this.transport.send(new N(8).u8(w.CHANNEL_CLOSE).u32(this.remoteChannelId).take()),this.transport.disconnect("Closed by the user"))}write(e){let t=typeof e=="string"?oe(e):e;t.length&&(this.pendingWrites.push(t),this.#l())}runCommand(e,{startMs:t=pa,idleMs:s=ma,maxMs:r=Ea}={}){let i=String(e||"").trim();if(!i)return Promise.reject(new Error("No command was given."));if(!this.shellOpen||this.closed)return Promise.reject(new Error("The SSH shell is not open."));if(this.readySignaled===!1)return Promise.reject(new Error("The SSH shell is still starting."));if(this.commandInFlight)return Promise.reject(new Error("Another command is still running in this shell."));let o=Array.from(crypto.getRandomValues(new Uint8Array(6))).map(g=>g.toString(16).padStart(2,"0")).join(""),a=`CCB${o}`,c=`CCE${o}`,h=this.shellFamily||"posix";this.commandInFlight=!0;let m=Date.now();return this.displayFilter={begin:a,end:c,stage:"before",pending:""},this.dispatchEvent(new CustomEvent("command",{detail:{phase:"start",id:o,command:i}})),new Promise((g,E)=>{let y="",f=!1,l=null,S=null,A=null,T=v=>{clearTimeout(l),clearTimeout(S),clearTimeout(A),this.removeEventListener("data",C),this.removeEventListener("close",I),this.commandInFlight=!1,Sa(this),v()},u=v=>T(()=>{this.dispatchEvent(new CustomEvent("command",{detail:{phase:"end",id:o,command:i,exitStatus:v.exitStatus,timedOut:v.timedOut,started:v.started!==!1,reason:v.reason,durationMs:v.durationMs}})),g(v)}),d=v=>T(()=>{this.dispatchEvent(new CustomEvent("command",{detail:{phase:"end",id:o,command:i,exitStatus:null,timedOut:!1,started:f,durationMs:Date.now()-m,error:v.message}})),E(v)}),x=()=>{let v=y.indexOf(a);return v===-1?"":ve(y.slice(v+a.length)).replace(/^\r?\n/,"").replace(/\s+$/,"")},R=v=>{this.write(""),u({output:x(),exitStatus:null,timedOut:!0,started:f,reason:v,durationMs:Date.now()-m})},C=v=>{y+=Ve(v.detail.bytes),!f&&y.indexOf(a)!==-1&&(f=!0,clearTimeout(l),l=null),f&&(clearTimeout(S),S=setTimeout(()=>R("idle"),s));let U=y.indexOf(`${c} `);if(U===-1){if(!f&&wa.test(ve(y))){let ue=ar(ve(y))||"cmd",V=h!==ue;this.shellFamily=ue,d(new Error(V?`This shell is ${ue==="powershell"?"PowerShell":"Windows cmd"}, not a POSIX shell, and it rejected the wrapper used to capture output. The shell has been noted; run the command again and it will be framed correctly.`:`The shell rejected the wrapper used to capture output: ${ve(y).split(`
|
|
9
|
+
`).filter(Boolean).pop()||"no detail"}`))}return}let Q=y.slice(U),me=parseInt(Q.slice(c.length+1).trim(),10),le=y.indexOf(a),Le=le===-1?y.slice(0,U):y.slice(le+a.length,U);u({output:ve(Le).replace(/^\r?\n/,"").replace(/\s+$/,""),exitStatus:Number.isInteger(me)?me:null,timedOut:!1,started:!0,durationMs:Date.now()-m})},I=()=>d(new Error("The SSH session closed while the command was running."));this.addEventListener("data",C),this.addEventListener("close",I),l=setTimeout(()=>R("start"),t),S=setTimeout(()=>R("idle"),s),A=setTimeout(()=>R("max"),r),this.write(ga(h,i,o))})}resize(e,t){let s=Math.max(1,Math.floor(e)),r=Math.max(1,Math.floor(t));s===this.columns&&r===this.rows||(this.columns=s,this.rows=r,!(!this.shellOpen||this.remoteChannelId===null)&&this.transport.send(new N(64).u8(w.CHANNEL_REQUEST).u32(this.remoteChannelId).string("window-change").boolean(!1).u32(s).u32(r).u32(0).u32(0).take()))}#e(e,t){this.dispatchEvent(new CustomEvent("status",{detail:{phase:e,message:t}}))}#t(e){e&&this.dispatchEvent(new CustomEvent("banner",{detail:{text:e}}))}#s(...e){return new Promise((t,s)=>{for(let r of e)this.waiters.set(r,{resolve:t,reject:s})})}#n(e,t){let s=this.waiters.get(e);return s?(this.waiters.clear(),s.resolve({type:e,payload:t}),!0):!1}#r(e){if(this.waiters.size===0)return;let t=[...new Set(this.waiters.values())];this.waiters.clear();for(let s of t)s.reject(new Error(e))}#c(e,t){if(!this.#n(e,t))switch(e){case w.USERAUTH_BANNER:this.#t(new O(t,1).string().replaceAll(`
|
|
10
10
|
`,`\r
|
|
11
|
-
`));return;case
|
|
11
|
+
`));return;case w.CHANNEL_DATA:{let s=new O(t,1);s.u32(),this.#h(s.stringBytes());return}case w.CHANNEL_EXTENDED_DATA:{let s=new O(t,1);s.u32();let r=s.u32(),i=s.stringBytes();this.#h(i,r===$s);return}case w.CHANNEL_WINDOW_ADJUST:{let s=new O(t,1);s.u32(),this.remoteWindow+=s.u32(),this.#l();return}case w.CHANNEL_REQUEST:{let s=new O(t,1);s.u32();let r=s.string(),i=s.boolean();r==="exit-status"&&(this.exitStatus=s.u32()),r==="exit-signal"&&(this.exitSignal=s.string()),i&&this.remoteChannelId!==null&&this.transport.send(new N(8).u8(w.CHANNEL_SUCCESS).u32(this.remoteChannelId).take());return}case w.CHANNEL_EOF:return;case w.CHANNEL_CLOSE:this.shellOpen=!1,this.#e("closed","The remote shell ended."),this.transport.disconnect("Shell closed");return;default:return}}#i(e){this.promptTail=(this.promptTail+ve(Ve(e))).slice(-400);let t=ar(this.promptTail);if(t){if(t==="cmd"&&!this.powerShellAttempted){this.#a();return}t==="cmd"&&this.powerShellAttempted&&!this.readySignaled||(this.shellFamily=t,t==="powershell"&&!this.readySignaled&&this.#o("Connected \xB7 PowerShell"))}}#a(){this.powerShellAttempted||!this.shellOpen||(this.powerShellAttempted=!0,this.readySignaled=!1,this.shellFamily="",this.#e("opening","Starting PowerShell\u2026"),this.write("powershell.exe -NoLogo\r"),this.powerShellTimer=setTimeout(()=>{this.readySignaled||this.closed||(this.shellFamily="powershell",this.#o("Connected \xB7 PowerShell"))},2e3))}#o(e="Connected."){clearTimeout(this.powerShellTimer),this.powerShellTimer=null,this.readySignaled=!0,this.#e("ready",e),this.dispatchEvent(new CustomEvent("ready",{detail:{fingerprint:this.fingerprint,shellFamily:this.shellFamily||"posix"}}))}#h(e,t=!1){if(!e.length||(this.#i(e),this.dispatchEvent(new CustomEvent("data",{detail:{bytes:e,display:Aa(this,e),isStderr:t}})),this.localWindow-=e.length,this.localWindow>da||this.remoteChannelId===null))return;let s=ze-this.localWindow;this.localWindow=ze,this.transport.send(new N(16).u8(w.CHANNEL_WINDOW_ADJUST).u32(this.remoteChannelId).u32(s).take())}#l(){if(!(!this.shellOpen||this.remoteChannelId===null))for(;this.pendingWrites.length>0;){let e=this.pendingWrites[0],t=Math.min(this.remoteWindow,this.remoteMaxPacket-64);if(t<=0)return;let s=e.length<=t?e:e.subarray(0,t);s.length===e.length?this.pendingWrites.shift():this.pendingWrites[0]=e.subarray(s.length),this.remoteWindow-=s.length,this.transport.send(new N(s.length+16).u8(w.CHANNEL_DATA).u32(this.remoteChannelId).string(s).take())}}async#p(){try{if(this.#e("authenticating",`Authenticating as ${this.username}\u2026`),this.transport.send(new N(32).u8(w.SERVICE_REQUEST).string("ssh-userauth").take()),await this.#s(w.SERVICE_ACCEPT),await this.#E())return void await this.#m();if(this.authMethods.includes("publickey")){for(let e of await this.#y())if(await this.#g(e))return void await this.#m()}if(this.authMethods.includes("password")&&this.password){if(await this.#u(this.password))return void await this.#m();this.passwordRejected=!0}if(this.authMethods.includes("keyboard-interactive")){if(await this.#d())return void await this.#m();if(this.canAsk&&this.authMethods.includes("keyboard-interactive")&&await this.#d({usePassword:!1}))return void await this.#m()}if(this.canAsk&&this.authMethods.includes("password")){let e=await this.requestInput({prompt:`${this.username}@${this.options.hostLabel||"host"}'s password: `,echo:!1});if(e&&await this.#u(e))return void await this.#m()}throw new Error(this.authMethods.length?`SSH: authentication failed${this.triedKeys.length?` (the host refused ${this.triedKeys.join(", ")})`:""}. The host accepts ${this.authMethods.join(", ")}.`:"SSH: the host rejected the connection before any authentication method was offered.")}catch(e){this.closed||this.transport.fail(e)}}async#E(){return this.transport.send(new N(64).u8(w.USERAUTH_REQUEST).string(this.username).string(Xe).string("none").take()),this.#A()}async#u(e){return this.transport.send(new N(128).u8(w.USERAUTH_REQUEST).string(this.username).string(Xe).string("password").boolean(!1).string(e).take()),this.#A()}async#y(){let e=this.identities,t=typeof e=="function"?await e():e;return this.identities=t,t}async#g(e){let t=this.transport.sessionId;if(!t)throw new Error("SSH: no session identifier to sign against.");for(let s of e.algorithms){this.#e("authenticating",`Offering ${e.comment||e.keyType}\u2026`),this.transport.send(new N(e.keyBlob.length+128).u8(w.USERAUTH_REQUEST).string(this.username).string(Xe).string("publickey").boolean(!1).string(s).string(e.keyBlob).take());let r=await this.#s(w.USERAUTH_PK_OK,w.USERAUTH_FAILURE,w.USERAUTH_SUCCESS);if(r.type===w.USERAUTH_SUCCESS)return!0;if(r.type===w.USERAUTH_FAILURE){if(this.#S(r.payload),!this.authMethods.includes("publickey"))return!1;continue}let i=new N(e.keyBlob.length+128).u8(w.USERAUTH_REQUEST).string(this.username).string(Xe).string("publickey").boolean(!0).string(s).string(e.keyBlob).take(),o=await e.sign(new N(i.length+t.length+8).string(t).raw(i).take(),s);return this.transport.send(new N(i.length+o.length+8).raw(i).string(o).take()),await this.#A()?!0:(this.triedKeys.push(e.comment||e.keyType),!1)}return this.triedKeys.push(e.comment||e.keyType),!1}async#d({usePassword:e=!0}={}){this.passwordRejected&&(e=!1),this.transport.send(new N(96).u8(w.USERAUTH_REQUEST).string(this.username).string(Xe).string("keyboard-interactive").string("").string("").take());let t=!e,s=0;for(;;){let{type:r,payload:i}=await this.#s(w.USERAUTH_SUCCESS,w.USERAUTH_FAILURE,w.USERAUTH_INFO_REQUEST);if(r===w.USERAUTH_SUCCESS)return!0;if(r===w.USERAUTH_FAILURE)return this.#S(i),!1;let o=new O(i,1),a=o.string(),c=o.string();o.string();let h=o.u32();if(a&&this.#t(`${a.replaceAll(`
|
|
12
12
|
`,`\r
|
|
13
13
|
`)}\r
|
|
14
|
-
`),
|
|
14
|
+
`),c&&this.#t(`${c.replaceAll(`
|
|
15
15
|
`,`\r
|
|
16
16
|
`)}\r
|
|
17
|
-
`);let
|
|
17
|
+
`),++s>3)return!1;let m=[],g=!1;for(let y=0;y<h;y++){let f=o.string(),l=o.boolean();if(!l&&/pass(word|phrase)/i.test(f)&&this.password&&!t){t=!0,g=!0,m.push(this.password);continue}let A=this.canAsk?await this.requestInput({prompt:f,echo:l}):"";A&&(g=!0),m.push(A)}if(h>0&&!g)return!1;let E=new N(256).u8(w.USERAUTH_INFO_RESPONSE).u32(m.length);for(let y of m)E.string(y);this.transport.send(E.take())}}async#A(){let{type:e,payload:t}=await this.#s(w.USERAUTH_SUCCESS,w.USERAUTH_FAILURE);return e===w.USERAUTH_SUCCESS?!0:(this.#S(t),!1)}#S(e){let t=new O(e,1);this.authMethods=t.nameList(),t.boolean()&&this.#t(`\r
|
|
18
18
|
One factor accepted; the host wants another.\r
|
|
19
|
-
`)}async#
|
|
19
|
+
`)}async#m(){this.#e("opening","Starting the remote shell\u2026"),this.transport.send(new N(64).u8(w.CHANNEL_OPEN).string("session").u32(this.channelId).u32(ze).u32(fn).take());let e=await this.#s(w.CHANNEL_OPEN_CONFIRMATION,w.CHANNEL_OPEN_FAILURE);if(e.type===w.CHANNEL_OPEN_FAILURE){let i=new O(e.payload,1);throw i.u32(),i.u32(),new Error(`SSH: the host refused to open a session channel (${i.string()}).`)}let t=new O(e.payload,1);if(t.u32(),this.remoteChannelId=t.u32(),this.remoteWindow=t.u32(),this.remoteMaxPacket=Math.max(1024,Math.min(t.u32(),fn)),this.transport.send(new N(128).u8(w.CHANNEL_REQUEST).u32(this.remoteChannelId).string("pty-req").boolean(!0).string(ua).u32(this.columns).u32(this.rows).u32(0).u32(0).string(fa).take()),(await this.#s(w.CHANNEL_SUCCESS,w.CHANNEL_FAILURE)).type===w.CHANNEL_FAILURE)throw new Error("SSH: the host refused a pseudo-terminal, so there is no interactive shell to show.");if(this.transport.send(new N(32).u8(w.CHANNEL_REQUEST).u32(this.remoteChannelId).string("shell").boolean(!0).take()),(await this.#s(w.CHANNEL_SUCCESS,w.CHANNEL_FAILURE)).type===w.CHANNEL_FAILURE)throw new Error("SSH: the host refused to start a shell for this account.");this.shellOpen=!0,this.#l(),this.options.preferredShell==="powershell"?this.#a():this.#o()}};import{Terminal as xa}from"@xterm/xterm";import{FitAddon as Ta}from"@xterm/addon-fit";import ba from"@xterm/xterm/css/xterm.css";var hr="xterm-styles",pn=80,mn=13,_a=7;function Ca(){if(document.getElementById(hr))return;let n=document.createElement("style");n.id=hr,n.textContent=ba,document.head.appendChild(n)}var Ra={background:"#0b0d12",foreground:"#dfe4ec",cursor:"#f38020",cursorAccent:"#0b0d12",selectionBackground:"rgba(243, 128, 32, 0.32)",black:"#1b1f27",red:"#ff6b6b",green:"#4ade80",yellow:"#fbbf24",blue:"#60a5fa",magenta:"#c084fc",cyan:"#34d3ee",white:"#cbd3e1",brightBlack:"#63708a",brightRed:"#ff8787",brightGreen:"#86efac",brightYellow:"#fcd34d",brightBlue:"#93c5fd",brightMagenta:"#d8b4fe",brightCyan:"#67e8f9",brightWhite:"#f5f7fa"},lr=class{constructor(e){Ca(),this.container=e,this.terminal=new xa({allowProposedApi:!0,convertEol:!1,cursorBlink:!0,cursorStyle:"bar",drawBoldTextInBrightColors:!0,fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace',fontSize:mn,lineHeight:1.25,letterSpacing:0,macOptionIsMeta:!0,minimumContrastRatio:1.5,scrollback:1e4,theme:Ra}),this.fitAddon=new Ta,this.terminal.loadAddon(this.fitAddon),this.terminal.open(e),this.fit(),this.observer=new ResizeObserver(()=>this.fit()),this.observer.observe(e),this.dataHandler=null,this.terminal.onData(t=>this.dataHandler?.(t))}get columns(){return this.terminal.cols}get rows(){return this.terminal.rows}onData(e){this.dataHandler=e}onResize(e){this.terminal.onResize(({cols:t,rows:s})=>e(t,s))}write(e){this.terminal.write(e)}notice(e,t="info"){let s={info:"\x1B[38;5;245m",good:"\x1B[38;5;114m",bad:"\x1B[38;5;203m"}[t]||"";this.terminal.write(`${s}${e}\x1B[0m\r
|
|
20
20
|
`)}clear(){this.terminal.clear()}focus(){this.terminal.focus()}fit(){if(!this.fitting&&!(this.container.clientWidth<=0||this.container.clientHeight<=0)){this.fitting=!0;try{for(let t=0;t<2;t++){let s=this.fitAddon.proposeDimensions();if(!s||!(s.cols>0))break;let r=this.terminal.options.fontSize||mn,i=Math.min(mn,Math.max(_a,Math.floor(r*s.cols/pn)));if(i===r)break;this.terminal.options.fontSize=i}this.fitAddon.fit();let e=this.terminal.cols<pn;this.container.classList.toggle("is-narrow",e),e&&this.terminal.resize(pn,this.terminal.rows)}catch{}finally{this.fitting=!1}}}get geometry(){return{columns:this.terminal.cols,rows:this.terminal.rows,fontSize:this.terminal.options.fontSize}}get selection(){return this.terminal.getSelection()}readLine({prompt:e="",echo:t=!1}={}){return new Promise(s=>{let r=this.dataHandler,i="";this.terminal.write(e.replaceAll(`
|
|
21
21
|
`,`\r
|
|
22
22
|
`)),this.dataHandler=o=>{for(let a of o){let c=a.charCodeAt(0);if(c===13||c===10){this.terminal.write(`\r
|