ai-remote 0.5.0 → 0.6.0
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 +40 -0
- package/SKILL.md +123 -13
- package/dist/{cli-chunk-Q33YGIDO.mjs → cli-chunk-L6E2YYPQ.mjs} +19 -5
- package/dist/{cli-chunk-F2TSY3YW.mjs → cli-chunk-P4645KKB.mjs} +3 -3
- package/dist/{cli-chunk-OZG2CODR.mjs → cli-chunk-TKKENOSJ.mjs} +1 -1
- package/dist/{cli-chunk-S2TWL5LF.mjs → cli-chunk-UD2YES3P.mjs} +107 -39
- package/dist/cli-chunk-WWORJ2NE.mjs +72 -0
- package/dist/{cli-copy-BOF44DWQ.mjs → cli-copy-2HQU2E7D.mjs} +18 -5
- package/dist/{cli-daemon-3BBFQCML.mjs → cli-daemon-3L36TBIB.mjs} +852 -274
- package/dist/{cli-identities-ZILT4XCR.mjs → cli-identities-GBQWYF2O.mjs} +4 -4
- package/dist/cli-known-hosts-UU427T4N.mjs +12 -0
- package/dist/{cli-secrets-26D3F6EN.mjs → cli-secrets-BMYFPDB2.mjs} +1 -1
- package/dist/cli-shell-JEC6BEME.mjs +11 -0
- package/dist/{cli-window-ZKAXEHQV.mjs → cli-window-AWXZ5NJX.mjs} +2 -2
- package/dist/cli.mjs +219 -109
- package/dist/computer.d.ts +77 -0
- package/dist/computer.js +3 -0
- package/dist/index.d.ts +80 -1
- package/dist/index.js +1 -1
- package/dist/protocols.d.ts +247 -17
- package/dist/protocols.js +16 -16
- package/package.json +6 -1
- package/dist/cli-shell-45XRTE7O.mjs +0 -10
package/dist/protocols.js
CHANGED
|
@@ -1,25 +1,25 @@
|
|
|
1
|
-
function vt(n){return new Uint8Array(n)}var p=class{bytes;view;offset=0;constructor(e=512){this.bytes=vt(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=vt(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)}},T=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=vt(e),s=0;for(let r of n)t.set(r,s),s+=r.length;return t}var Tr=[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],br=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 ae(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),E=new DataView(s.buffer,s.byteOffset,s.byteLength);for(let f=0;f<t;f++){for(let _=0;_<16;_++)h[_]=E.getUint32(f*64+_*4,!0);let m=i,l=o,A=a,g=c;for(let _=0;_<64;_++){let u,d;_<16?(u=l&A|~l&g,d=_):_<32?(u=g&l|~g&A,d=(5*_+1)%16):_<48?(u=l^A^g,d=(3*_+5)%16):(u=A^(l|~g),d=7*_%16);let S=g;g=A,A=l;let R=m+u+br[_]+h[d]|0;l=l+Ze(R,Tr[_])|0,m=S}i=i+m|0,o=o+l|0,a=a+A|0,c=c+g|0}let w=new Uint8Array(16),x=new DataView(w.buffer);return x.setUint32(0,i>>>0,!0),x.setUint32(4,o>>>0,!0),x.setUint32(8,a>>>0,!0),x.setUint32(12,c>>>0,!0),w}function Nt(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,E=new Uint32Array(80),w=new DataView(s.buffer,s.byteOffset,s.byteLength);for(let m=0;m<t;m++){for(let d=0;d<16;d++)E[d]=w.getUint32(m*64+d*4);for(let d=16;d<80;d++)E[d]=Ze(E[d-3]^E[d-8]^E[d-14]^E[d-16],1);let l=i,A=o,g=a,_=c,u=h;for(let d=0;d<80;d++){let S,R;d<20?(S=A&g|~A&_,R=1518500249):d<40?(S=A^g^_,R=1859775393):d<60?(S=A&g|A&_|g&_,R=2400959708):(S=A^g^_,R=3395469782);let C=Ze(l,5)+S+u+R+E[d]|0;u=_,_=g,g=Ze(A,30),A=l,l=C}i=i+l|0,o=o+A|0,a=a+g|0,c=c+_|0,h=h+u|0}let x=new Uint8Array(20),f=new DataView(x.buffer);return[i,o,a,c,h].forEach((m,l)=>f.setUint32(l*4,m>>>0)),x}function J(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 z(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 Lt(n){let e=0n;for(let t=n.length-1;t>=0;t--)e=e<<8n|BigInt(n[t]);return e}function _r(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 Tn(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 bn(n,e,t){let s=Lt(e),r=Lt(t),i=Lt(n);if(i>=s)throw new Error("RDP: client random is larger than the server RSA modulus");return _r(Tn(i,r,s),e.length)}function _n(n,e,t){let s=f=>{let m=0n;for(let l of f)m=m<<8n|BigInt(l);return m},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 f=0;f<c;f++){for(;h[f]===0;)h[f]=Math.max(1,crypto.getRandomValues(new Uint8Array(1))[0]);a[2+f]=h[f]}a[2+c]=0,a.set(n,3+c);let E=Tn(s(a),i,r),w=new Uint8Array(o),x=E;for(let f=o-1;f>=0;f--)w[f]=Number(x&0xffn),x>>=8n;return w}var Cn=new Uint8Array(40).fill(54),Rn=new Uint8Array(48).fill(92),oe={NONE:0,BIT_40:1,BIT_128:2,BIT_56:8,FIPS:16};function Z(...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 we(n,e,t,s){return ae(Z(n,Nt(Z(e,n,t,s))))}function xn(n,e,t){return ae(Z(n,e,t))}var Cr=new Uint8Array([65]),Rr=new Uint8Array([66,66]),vr=new Uint8Array([67,67,67]),Lr=new Uint8Array([88]),Nr=new Uint8Array([89,89]),Ur=new Uint8Array([90,90,90]);function vn(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 Ir(n){return n===oe.BIT_40||n===oe.BIT_56?8:16}function Ln(n,e,t){let s=Z(n.subarray(0,24),e.subarray(0,24)),r=Z(we(s,Cr,n,e),we(s,Rr,n,e),we(s,vr,n,e)),i=Z(we(r,Lr,n,e),we(r,Nr,n,e),we(r,Ur,n,e)),o=Ir(t),a=t===oe.BIT_40,c=x=>vn(x,o,a),h=c(i.subarray(0,16)),E=c(xn(i.subarray(16,32),n,e)),w=c(xn(i.subarray(32,48),n,e));return{macKey:h,keyLength:o,is40Bit:a,initialDecryptKey:E.slice(),initialEncryptKey:w.slice(),decryptKey:E,encryptKey:w}}function Nn(n,e){let t=new Uint8Array(4);new DataView(t.buffer).setUint32(0,e.length,!0);let s=Nt(Z(n,Cn,t,e));return ae(Z(n,Rn,s)).subarray(0,8)}function Ut(n,e,t,s){let r=Nt(Z(n,Cn,e)),i=ae(Z(n,Rn,r)).slice(0,t),o=z(J(i),i);return vn(o,t,s)}var It=3,Un=4,Or=224,kr=208,Pr=240,Dr=1,Mr=2,Hr=3,In={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},Fr={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 On(n){let e=new p(32);return e.u8(It).u8(0).u16be(19),e.u8(14).u8(Or).u16be(0).u16be(0).u8(0),e.u8(Dr).u8(0).u16le(8).u32le(n),e.take()}function kn(n){let e=new T(n);e.skip(Un),e.u8();let t=e.u8();if(t!==kr)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===Hr){let r=e.u32le(),i=new Error(Fr[r]||`The host refused the RDP connection (negotiation failure 0x${r.toString(16)}).`);throw i.negotiationFailure=r,i}return s!==Mr?{selectedProtocol:P.RDP,negotiated:!1}:{selectedProtocol:e.u32le(),negotiated:!0}}function ge(n){let e=new p(n.length+7);return e.u8(It).u8(0).u16be(n.length+7),e.u8(2).u8(Pr).u8(128),e.raw(n),e.take()}function Ue(n){if(n.length<7)throw new Error("RDP: X.224 data frame is too short");return n.subarray(7)}function Pn(n){let e=[],t=0;for(;n.length-t>=4;){let s,r=!1;if(n[t]===It){if(s=n[t+2]<<8|n[t+3],s<Un)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 Br=1,Kr=2,Gr=826364754,Wr=6,Mn=[42,134,72,134,247,13,1,1,1];function pe(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 Ae(n){let e=[],t=0;for(;t<n.length;){let s=pe(n,t);if(e.push(s),s.next<=t)break;t=s.next}return e}function Hn(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 Dn(n){let e=0;for(;e<n.length-1&&n[e]===0;)e++;return n.subarray(e).slice().reverse()}function Vr(n){let e=pe(n,0),t=pe(n,e.contentStart);for(let s of Ae(t.content)){if(s.tag!==48)continue;let r=Ae(s.content);if(r.length<2||r[0].tag!==48||!Hn(r[0].content,Mn)||r[1].tag!==3)continue;let i=pe(r[1].content.subarray(1),0),[o,a]=Ae(i.content);if(!o||!a)break;return{modulus:Dn(o.content),exponent:Dn(a.content),source:"x509"}}throw new Error("RDP: no RSA public key found in the host X.509 certificate")}function Yr(n){n.u32le(),n.u32le();let e=n.u16le(),t=n.u16le();if(e!==Wr)throw new Error(`RDP: unsupported public key blob type 0x${e.toString(16)}`);let s=new T(n.raw(t));if(s.u32le()!==Gr)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 Fn(n){let e=pe(n,0),t=pe(n,e.contentStart);for(let s of Ae(t.content)){if(s.tag!==48)continue;let r=Ae(s.content);if(r.length<2||r[0].tag!==48||!Hn(r[0].content,Mn)||r[1].tag!==3)continue;let i=r[1].content.subarray(1),o=pe(i,0),[a,c]=Ae(o.content);if(!a||!c)break;let h=E=>{let w=0;for(;w<E.length-1&&E[w]===0;)w++;return E.subarray(w)};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 Bn(n){let e=new T(n),t=e.u32le()&2147483647;if(t===Br)return Yr(e);if(t===Kr){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 Vr(r)}throw new Error(`RDP: unsupported server certificate version ${t}`)}var Ie=771,he={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},$r={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"}},qr={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"},Xr=n=>new TextEncoder().encode(n);function F(n){return new Uint8Array([n>>8&255,n&255])}function Kn(n){return new Uint8Array([n>>16&255,n>>8&255,n&255])}function Ot(n){let e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,BigInt(n)),e}async function zr(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 kt=(n,e,t,s,r)=>zr(n,e,b(Xr(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(F(13),F(10),F(8),new Uint8Array([4,1,5,1,2,1,6,1]),F(65281),F(1),new Uint8Array([0])),t=b(F(Ie),this.clientRandom,new Uint8Array([0]),F(4),F(156),F(157),new Uint8Array([1,0]),F(e.length),e);return await this.#t(Y.CLIENT_HELLO,t),this.handshakeDone}#e(e,t){return b(new Uint8Array([e]),F(Ie),F(t.length),t)}async#t(e,t){let s=b(new Uint8Array([e]),Kn(t.length),t);this.transcript.push(s),await this.#n(he.HANDSHAKE,s)}async#n(e,t){if(!this.writeEncrypted){this.sendRaw(this.#e(e,t));return}this.sendRaw(this.#e(e,await this.#s(e,t)))}async#s(e,t){let s=this.writeSequence++,r=Ot(s),i=b(this.keys.clientIv,r),o=b(Ot(s),new Uint8Array([e]),F(Ie),F(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(Ot(s),new Uint8Array([e]),F(Ie),F(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#a(e){let{hash:t,keyLength:s}=this.suite;this.masterSecret=await kt(t,e,"master secret",b(this.clientRandom,this.serverRandom),48);let r=await kt(t,this.masterSecret,"key expansion",b(this.serverRandom,this.clientRandom),s*2+8),i=new T(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#c(e){return kt(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!==he.CHANGE_CIPHER_SPEC?await this.#r(t,r):r;await this.#l(t,i)}}async#l(e,t){if(e===he.ALERT){let r=t[0],i=t[1],o=qr[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===he.CHANGE_CIPHER_SPEC){this.readEncrypted=!0,this.readSequence=0n;return}if(e===he.APPLICATION_DATA){this.onData&&t.length>0&&this.onData(t);return}if(e!==he.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(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=$r[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(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=Fn(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.#c("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,Kn(0));let e=new Uint8Array(48);crypto.getRandomValues(e),e[0]=3,e[1]=3;let t=_n(e,this.serverPublicKey.modulus,this.serverPublicKey.exponent);await this.#t(Y.CLIENT_KEY_EXCHANGE,b(F(t.length),t)),await this.#a(e),await this.#n(he.CHANGE_CIPHER_SPEC,new Uint8Array([1])),this.writeEncrypted=!0,this.writeSequence=0n,await this.#t(Y.FINISHED,await this.#c("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.#n(he.APPLICATION_DATA,e)}).catch(t=>this.#o(t)),this.queue}};function Qr(n,e){return n<<e|n>>>32-e}function jr(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),E=[3,7,11,19],w=[0,4,8,12,1,5,9,13,2,6,10,14,3,7,11,15],x=[3,5,9,13],f=[0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15],m=[3,9,11,15];for(let g=0;g<e;g++){for(let C=0;C<16;C++)h[C]=s.getUint32(g*64+C*4,!0);let _=i,u=o,d=a,S=c,R=(C,U)=>Qr(C|0,U);for(let C=0;C<16;C++){let U=u&d|~u&S,v=E[C%4],I=R(_+U+h[C]|0,v);_=S,S=d,d=u,u=I}for(let C=0;C<16;C++){let U=u&d|u&S|d&S,v=x[C%4],I=R(_+U+h[w[C]]+1518500249|0,v);_=S,S=d,d=u,u=I}for(let C=0;C<16;C++){let U=u^d^S,v=m[C%4],I=R(_+U+h[f[C]]+1859775393|0,v);_=S,S=d,d=u,u=I}i=i+_|0,o=o+u|0,a=a+d|0,c=c+S|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 Se(n,e){let s=n.length>64?ae(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 ae(b(o,ae(b(i,e))))}var Vn=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},Yn=$.UNICODE|$.REQUEST_TARGET|$.SIGN|$.SEAL|$.NTLM|$.ALWAYS_SIGN|$.EXTENDED_SESSION_SECURITY|$.TARGET_INFO|$.VERSION|$.KEY_128|$.KEY_EXCH|$.KEY_56,$n=0,Zr=7,Gn=6,Wn=2,Dt=n=>{let e=new p(n.length*2+2);return e.utf16le(n),e.take()},qn=new Uint8Array([10,0,99,69,0,0,0,15]);function Xn(){let n=new p(40);return n.raw(Vn),n.u32le(1),n.u32le(Yn>>>0),n.u16le(0).u16le(0).u32le(0),n.u16le(0).u16le(0).u32le(0),n.raw(qn),n.take()}function zn(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 Jr(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===$n)break;e.push({id:r,value:o})}return e}function ei(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($n).u16le(0),e.take()}function ti(){let n=(BigInt(Date.now())+11644473600000n)*10000n,e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,n,!0),e}function Qn({username:n,domain:e,password:t,challenge:s,negotiateBytes:r,challengeBytes:i}){let o=Se(jr(Dt(t)),Dt(n.toUpperCase()+e)),a=Jr(s.targetInfo),c=a.find(D=>D.id===Zr)?.value.slice()||ti(),h=a.find(D=>D.id===Gn);if(h){let D=new DataView(h.value.buffer,h.value.byteOffset,4);D.setUint32(0,D.getUint32(0,!0)|Wn,!0)}else{let D=new Uint8Array(4);new DataView(D.buffer).setUint32(0,Wn,!0),a.push({id:Gn,value:D})}let E=ei(a),w=new Uint8Array(8);crypto.getRandomValues(w);let x=b(new Uint8Array([1,1,0,0,0,0,0,0]),c,w,new Uint8Array(4),E,new Uint8Array(4)),f=Se(o,b(s.serverChallenge,x)),m=b(f,x),l=Se(o,f),A=new Uint8Array(16);crypto.getRandomValues(A);let g=z(J(l),A),_=Pt(e),u=Pt(n),d=Pt(""),S=new Uint8Array(24),R=72,C=R,U=[],v=D=>(U.push({bytes:D,offset:C}),C+=D.length,U[U.length-1]),I=v(S),j=v(m),Ee=v(_),de=v(u),Ne=v(d),fe=v(g),V=new p(C+16);V.raw(Vn),V.u32le(3);let ye=D=>{V.u16le(D.bytes.length),V.u16le(D.bytes.length),V.u32le(D.offset+16)};ye(I),ye(j),ye(Ee),ye(de),ye(Ne),ye(fe),V.u32le(Yn>>>0),V.raw(qn),V.zeros(16);for(let D of U)V.raw(D.bytes);let Rt=V.take(),xr=Se(A,b(r,i,Rt));return Rt.set(xr,R),{message:Rt,exportedSessionKey:A,keys:oi(A)}}function Pt(n){return n?Dt(n).subarray(0,n.length*2).slice():new Uint8Array(0)}var ni="session key to client-to-server signing key magic constant\0",si="session key to server-to-client signing key magic constant\0",ri="session key to client-to-server sealing key magic constant\0",ii="session key to server-to-client sealing key magic constant\0";function oi(n){let e=t=>ae(b(n,new TextEncoder().encode(t)));return{clientSigningKey:e(ni),serverSigningKey:e(si),clientSealing:J(e(ri)),serverSealing:J(e(ii))}}var et=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=Se(this.keys.clientSigningKey,b(t,e)),r=z(this.keys.clientSealing,e),i=z(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=z(this.keys.serverSealing,t),r=e.subarray(12,16),i=Se(this.keys.serverSigningKey,b(r,s)),o=z(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 Mt=6,ai="CredSSP Client-To-Server Binding Hash\0",ci="CredSSP Server-To-Client Binding Hash\0",hi={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 li(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 nt=(n,e)=>b(new Uint8Array([n]),li(e.length),e),Oe=(...n)=>nt(48,b(...n)),le=n=>nt(4,n),Q=(n,e)=>nt(160|n,e);function jn(n){let e=[],t=n;do e.unshift(t&255),t>>>=8;while(t>0);return e[0]&128&&e.unshift(0),nt(2,new Uint8Array(e))}function ee(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 ui(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 Ht({version:n,negoToken:e,authInfo:t,pubKeyAuth:s,clientNonce:r}){let i=[Q(0,jn(n))];return e&&i.push(Q(1,Oe(Oe(Q(0,le(e)))))),t&&i.push(Q(2,le(t))),s&&i.push(Q(3,le(s))),r&&i.push(Q(5,le(r))),Oe(...i)}function di(n){let e=ee(n,0),t={version:0,negoToken:null,authInfo:null,pubKeyAuth:null,errorCode:0},s=0;for(;s<e.content.length;){let r=ee(e.content,s);s=r.end;let i=r.tag&31;if(i===0){t.version=ee(r.content,0).content[0];continue}if(i===1){let o=ee(r.content,0),a=ee(o.content,0),c=ee(a.content,0);t.negoToken=ee(c.content,0).content;continue}if(i===2){t.authInfo=ee(r.content,0).content;continue}if(i===3){t.pubKeyAuth=ee(r.content,0).content;continue}if(i===4){let o=ee(r.content,0).content,a=0;for(let c of o)a=(a<<8|c)>>>0;t.errorCode=a;continue}}return t}function fi(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=Oe(Q(0,le(s(n))),Q(1,le(s(e))),Q(2,le(s(t))));return Oe(Q(0,jn(1)),Q(1,le(r)))}var tt=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=ui(this.inbound);if(t===0)return;let s=di(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=Xn();this.send(Ht({version:Mt,negoToken:e})),this.log("CredSSP","sent NTLM NEGOTIATE");let t=await this.#e();if(t.errorCode)throw new Error(this.#s(t.errorCode));if(!t.negoToken)throw new Error("CredSSP: the host sent no NTLM challenge");let s=t.negoToken.slice(),r=zn(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}=Qn({username:this.username,domain:this.domain,password:this.password,challenge:r,negotiateBytes:e,challengeBytes:s}),c=new et(a),h=new Uint8Array(32);crypto.getRandomValues(h);let E=t.version<5,w=E?this.serverPublicKey:await this.#t(ai,h);this.send(Ht({version:Mt,negoToken:o,pubKeyAuth:c.seal(w),clientNonce:E?null:h})),this.log("CredSSP",`sent NTLM AUTHENTICATE with the ${E?"legacy":"hashed"} public-key binding`);let x=await this.#e();if(x.errorCode)throw new Error(this.#s(x.errorCode));if(!x.pubKeyAuth)throw new Error("CredSSP: the host returned no public-key confirmation");let f=c.unseal(x.pubKeyAuth),m=E?this.#n():await this.#t(ci,h);if(f.length!==m.length||!m.every((l,A)=>l===f[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(Ht({version:Mt,authInfo:c.seal(fi(this.domain,this.username,this.password))})),this.log("CredSSP","sent credentials"),{authenticated:!0,hostVersion:t.version,targetName:i}}#n(){let e=this.serverPublicKey.slice();return e[0]=e[0]+1&255,e}#s(e){return hi[e]||`CredSSP: the host reported error 0x${e.toString(16).padStart(8,"0")}.`}};var xe=1001;var ue={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},pi={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 mi(n){return n>255?new Uint8Array([130,n>>8&255,n&255]):n>127?new Uint8Array([129,n]):new Uint8Array([n])}function Pe(n,e){return b(new Uint8Array(n),mi(e.length),e)}function Ei(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]),Pe([2],e)}var Ft=n=>Pe([4],n),yi=n=>Pe([1],new Uint8Array([n?255:0]));function Bt(n){return Pe([48],b(...n.map(Ei)))}function Kt(n,e){return e>127?n.u16be(32768|e):n.u8(e),n}function Zn(n){let e=n.u8();return e&128?(e&127)<<8|n.u8():e}var wi=new Uint8Array([5,0,20,124,0,1]),gi=new Uint8Array([68,117,99,97]),st=new Uint8Array([77,99,68,110]);function Ai(n){let e=new p(n.length+32);return e.u8(0),e.raw(wi),Kt(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(gi),Kt(e,n.length),e.raw(n),e.take()}function Si(n){for(let e=0;e+4<=n.length;e++)if(n[e]===st[0]&&n[e+1]===st[1]&&n[e+2]===st[2]&&n[e+3]===st[3]){let t=new T(n,e+4),s=Zn(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 xi=[34,2,0,1,0,1,65535,2],Ti=[1,1,1,1,0,1,1056,2],bi=[65535,64535,65535,1,0,1,65535,2];function Jn(n){let e=Ai(n),t=b(Ft(new Uint8Array([1])),Ft(new Uint8Array([1])),yi(!0),Bt(xi),Bt(Ti),Bt(bi),Ft(e));return ge(Pe([127,101],t))}function ke(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 es(n){let e=new T(Ue(n)),t=ke(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(t.value),r=ke(s);ke(s),ke(s);let i=ke(s);if(r.value[0]!==0)throw new Error(`RDP: the host rejected the MCS connection (result ${r.value[0]})`);return Si(i.value)}var rt=n=>n<<2;function ts(){let n=new p(8);return n.u8(rt(ue.ERECT_DOMAIN_REQUEST)),n.u8(1).u8(0),n.u8(1).u8(0),ge(n.take())}function ns(){return ge(new Uint8Array([rt(ue.ATTACH_USER_REQUEST)]))}function ss(n){let e=new T(Ue(n)),t=e.u8();if(t>>2!==ue.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()+xe:xe}}function Gt(n,e){let t=new p(8);return t.u8(rt(ue.CHANNEL_JOIN_REQUEST)),t.u16be(n-xe),t.u16be(e),ge(t.take())}function rs(n){let e=new T(Ue(n)),t=e.u8();if(t>>2!==ue.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 Wt(n,e,t){let s=new p(t.length+16);return s.u8(rt(ue.SEND_DATA_REQUEST)),s.u16be(n-xe),s.u16be(e),s.u8(112),Kt(s,t.length),s.raw(t),ge(s.take())}function is(n){let e=new T(Ue(n)),t=e.u8(),s=t>>2;if(s===ue.SEND_DATA_INDICATION){e.u16be();let r=e.u16be();e.u8();let i=Zn(e),o=e.rest();return{type:"send-data",channelId:r,payload:o.subarray(0,Math.min(i,o.length))}}if(s===ue.DISCONNECT_PROVIDER_ULTIMATUM){let r=(t&1)<<1|(e.remaining>0?e.u8()>>7:0);return{type:"disconnect",reason:r,message:pi[r]||`The host closed the RDP session (reason ${r}).`}}return{type:"other",mcsPduType:s}}var _i=49153,Ci=49154,Ri=49155,vi=49156,Li=3073,Ni=3074,Ui=3075,Ii=524292,os=51715,Oi=43523,ki=1,it={NONE:0,LOW:1,CLIENT_COMPATIBLE:2,HIGH:3,FIPS:4};function ot(n,e){let t=new p(e.length+4);return t.u16le(n).u16le(e.length+4).raw(e),t.take()}function Pi({width:n,height:e,clientName:t,keyboardLayout:s,selectedProtocol:r}){let i=new p(256);return i.u32le(Ii),i.u16le(n),i.u16le(e),i.u16le(os),i.u16le(Oi),i.u32le(s),i.u32le(2600),i.utf16le(t,32),i.u32le(4),i.u32le(0),i.u32le(12),i.zeros(64),i.u16le(os),i.u16le(1),i.u32le(0),i.u16le(16),i.u16le(7),i.u16le(ki),i.zeros(64),i.u8(0),i.u8(0),i.u32le(r),ot(_i,i.take())}function Di(n){let e=new p(8);return e.u32le(n),e.u32le(0),ot(Ci,e.take())}function Mi(){let n=new p(8);return n.u32le(13),n.u32le(0),ot(vi,n.take())}function Hi(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 ot(Ri,e.take())}function as(n){return b(Pi(n),Mi(),Di(n.encryptionMethods),Hi(n.channels||[]))}function cs(n){let e=new T(n),t={version:null,encryptionMethod:0,encryptionLevel:it.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 T(e.raw(r-4));if(s===Li){t.version=i.remaining>=4?i.u32le():null;continue}if(s===Ui){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===Ni){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=Bn(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},hs=1,Vt=2,Fi=4,De=1,Te=13,ls=1,Bi=2,us=2,at=32,Ki=400;function Gi(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 Wi(n){let e=new p(n.length*2+2);return e.utf16le(n),e.u16le(0),e.take()}function Vi(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 Yi(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 $i(n){let e=n.indexOf(0);return e===-1&&(e=n.length),String.fromCharCode(...n.subarray(0,e))}var ct=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(Gi(e,t,s))}setLocalText(e){return this.localText=e,this.ready?(this.#e(W.FORMAT_LIST,0,this.#t(e?[Te,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)},Ki),this.pendingAck={resolve:r}})):Promise.resolve(!1)}#t(e){let t=e.map(s=>{let r=new p(this.longFormatNames?6:4+at);return r.u32le(s),this.longFormatNames?r.u16le(0):r.zeros(at),r.take()});return b(...t)}receive(e){if(e.length<8)return;let t=new T(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.#n(a);return;case W.MONITOR_READY:this.#s();return;case W.FORMAT_LIST:this.#r(a,r);return;case W.FORMAT_LIST_RESPONSE:this.pendingAck?.resolve((r&Vt)===0);return;case W.FORMAT_DATA_REQUEST:this.#i(a);return;case W.FORMAT_DATA_RESPONSE:this.#c(a,r);return;default:return}}#n(e){let t=new T(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(t.raw(o-4));if(i===ls&&a.remaining>=8){a.u32le();let c=a.u32le();this.longFormatNames=(c&us)!==0}}}#s(){let e=new p(12);e.u16le(ls).u16le(12),e.u32le(Bi),e.u32le(this.longFormatNames?us: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?[Te,De]:[])),this.log("clipboard channel ready",{longFormatNames:this.longFormatNames})}#r(e,t){let s=this.#a(e,t);this.#e(W.FORMAT_LIST_RESPONSE,hs);let r=s.includes(Te)?Te: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())}#a(e,t){let s=new T(e),r=[],i=!this.longFormatNames||(t&Fi)!==0;for(;s.remaining>=4;){if(r.push(s.u32le()),i){if(s.remaining<at)break;s.skip(at);continue}for(;s.remaining>=2&&s.u16le()!==0;);}return r}#i(e){let t=new T(e),s=t.remaining>=4?t.u32le():0;if(s!==Te&&s!==De){this.#e(W.FORMAT_DATA_RESPONSE,Vt);return}let r=s===Te?Wi(this.localText):Yi(this.localText);this.#e(W.FORMAT_DATA_RESPONSE,hs,r),this.log("handed the host our clipboard",{formatId:s,characters:this.localText.length})}#c(e,t){if(t&Vt){this.log("the host refused to hand over its clipboard");return}let r=e.length>=2&&e.length%2===0&&e[1]===0?Vi(e):$i(e);r&&this.dispatchEvent(new CustomEvent("text",{detail:{text:r}}))}};var q={CLOSE:1,WAVE:2,SET_VOLUME:3,SET_PITCH:4,WAVE_CONFIRM:5,TRAINING:6,FORMATS:7,CRYPT_KEY:8,WAVE_ENCRYPT:9,UDP_WAVE:10,UDP_WAVE_LAST:11,QUALITY_MODE:12,WAVE2:13},qi=1,Xi=1,zi=2,Qi=2147450879,ji=6,Zi=2,Ji=6,Yt=4,eo=8,ds=12;function to(n){return n.formatTag===qi&&(n.bitsPerSample===8||n.bitsPerSample===16)&&n.channels>=1&&n.channels<=2&&n.samplesPerSec>=8e3&&n.samplesPerSec<=96e3}function ht(n,e){let t=new p(e.length+4);return t.u8(n).u8(0).u16le(e.length).raw(e),t.take()}function no(n){if(n.remaining<18)return null;let e={formatTag:n.u16le(),channels:n.u16le(),samplesPerSec:n.u32le(),avgBytesPerSec:n.u32le(),blockAlign:n.u16le(),bitsPerSample:n.u16le(),extra:new Uint8Array(0)},t=n.u16le();return t>n.remaining?null:(e.extra=n.raw(t).slice(),e)}function so(n){let e=new p(18+n.extra.length);return e.u16le(n.formatTag),e.u16le(n.channels),e.u32le(n.samplesPerSec),e.u32le(n.avgBytesPerSec),e.u16le(n.blockAlign),e.u16le(n.bitsPerSample),e.u16le(n.extra.length),e.raw(n.extra),e.take()}function ro(n){return n.blockAlign||Math.max(1,(n.bitsPerSample>>3)*n.channels)}var lt=class extends EventTarget{send;log;formats=[];serverVersion=0;ready=!1;#e=null;constructor({send:e,log:t}){super(),this.send=e,this.log=t??(()=>{})}receive(e){if(this.#e){this.#a(e);return}if(e.length<4)return;let t=new T(e),s=t.u8();t.u8();let r=t.u16le(),i=t.rest(),o=i.subarray(0,Math.min(r,i.length));switch(s){case q.FORMATS:this.#t(o);return;case q.TRAINING:this.#s(o);return;case q.WAVE:this.#r(o,r);return;case q.WAVE2:this.#i(o,r);return;case q.CLOSE:this.log("the host closed the audio stream"),this.dispatchEvent(new CustomEvent("close"));return;case q.SET_VOLUME:case q.SET_PITCH:return;case q.CRYPT_KEY:return;default:this.log("unhandled audio PDU",{msgType:s,bodySize:r});return}}#t(e){if(e.length<20)return;let t=new T(e);t.u32le(),t.u32le(),t.u32le(),t.u16le();let s=t.u16le();t.u8(),this.serverVersion=t.u16le(),t.u8();let r=[];for(let i=0;i<s;i++){let o=no(t);if(!o)break;r.push(o)}this.formats=r.filter(to),this.log("audio formats offered by the host",{offered:r.length,accepted:this.formats.length,version:this.serverVersion}),this.#n(),this.ready=this.formats.length>0,this.serverVersion>=Ji&&this.send(ht(q.QUALITY_MODE,new p(4).u16le(Zi).u16le(0).take())),this.ready&&this.dispatchEvent(new CustomEvent("ready",{detail:{formats:this.formats.slice(),version:this.serverVersion}}))}#n(){let e=new p(20);e.u32le(Xi|zi),e.u32le(Qi),e.u32le(0),e.u16le(0),e.u16le(this.formats.length),e.u8(0),e.u16le(ji),e.u8(0),this.send(ht(q.FORMATS,b(e.take(),...this.formats.map(so))))}#s(e){if(e.length<4)return;let t=new T(e),s=t.u16le(),r=t.u16le();this.send(ht(q.TRAINING,new p(4).u16le(s).u16le(r).take()))}#r(e,t){if(e.length<12)return;let s=new T(e),r=s.u16le(),i=s.u16le(),o=s.u8();s.skip(3);let a=s.raw(Yt).slice(),c=Math.max(0,t-eo),h=this.formats[i];if(!h){this.log("the host chose an audio format that was never offered",{formatNo:i}),this.#c(r,o);return}this.#e={format:h,timestamp:r,blockNo:o,prefix:a,remaining:Math.max(0,c-Yt)},this.#e.remaining===0&&this.#a(new Uint8Array(0),!0)}#a(e,t=!1){let s=this.#e;if(this.#e=null,!s)return;let r=t?e:e.subarray(Yt),i=b(s.prefix,r.subarray(0,s.remaining));this.#o(s.format,i,s.timestamp),this.#c(s.timestamp,s.blockNo)}#i(e,t){if(e.length<ds)return;let s=new T(e),r=s.u16le(),i=s.u16le(),o=s.u8();s.skip(3),s.u32le();let a=Math.max(0,t-ds),c=s.rest().subarray(0,a),h=this.formats[i];h?this.#o(h,c.slice(),r):this.log("the host chose an audio format that was never offered",{formatNo:i}),this.#c(r,o)}#c(e,t){this.send(ht(q.WAVE_CONFIRM,new p(4).u16le(e).u8(t).u8(0).take()))}#o(e,t,s){if(!t.length)return;let r=ro(e),i=t.length-t.length%r;i<=0||this.dispatchEvent(new CustomEvent("audio",{detail:{format:e,samples:t.subarray(0,i),timestamp:s}}))}};var X={EXEC:1,ACTIVATE:2,SYSPARAM:3,SYSCOMMAND:4,HANDSHAKE:5,WINDOW_MOVE:8,CLIENT_STATUS:11,EXEC_RESULT:128,HANDSHAKE_EX:19},io={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."},ps={MINIMIZE:61472,MAXIMIZE:61488,CLOSE:61536,RESTORE:61728},_e={HIDDEN:0,MINIMIZED:2,MAXIMIZED:3,NORMAL:5},Me={TYPE_WINDOW:16777216,STATE_NEW:268435456,STATE_DELETED:536870912,ICON:1073741824,CACHED_ICON:2147483648},K={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},oo=1073741824,ao=128,co=134217728,ho=3,lo=2,uo=11,ms=2600,fo=1024,be={MOUSE_BUTTON_SWAP:33,DRAG_FULL_WINDOWS:37,WORK_AREA:47,HIGH_CONTRAST:67,KEYBOARD_PREF:69,KEYBOARD_CUES:4107};function $t(n){let e=new p(n.length*2);return e.utf16le(n),e.take()}function ce(n,e){let t=new p(e.length+4);return t.u16le(n).u16le(e.length+4).raw(e),t.take()}function te(n){return n|0}function po(n=ms){return ce(X.HANDSHAKE,new p(4).u32le(n).take())}function mo(n=fo){return ce(X.CLIENT_STATUS,new p(4).u32le(n).take())}function ut(n,e){return ce(X.SYSPARAM,new p(5).u32le(n).u8(e?1:0).take())}function Eo(){let n=new p(16);return n.u32le(be.HIGH_CONTRAST),n.u32le(126),n.u32le(2),n.u16le(0).u16le(0),ce(X.SYSPARAM,n.take())}function Es(n,e){let t=new p(12);return t.u32le(be.WORK_AREA),t.u16le(0).u16le(0).u16le(n).u16le(e),ce(X.SYSPARAM,t.take())}function yo(n,e){return[Eo(),ut(be.MOUSE_BUTTON_SWAP,!1),ut(be.KEYBOARD_PREF,!1),ut(be.DRAG_FULL_WINDOWS,!0),ut(be.KEYBOARD_CUES,!1),Es(n,e)]}function wo(n,e=!0){let t=new p(5);return t.u32le(n).u8(e?1:0),ce(X.ACTIVATE,t.take())}function go(n,e){let t=new p(6);return t.u32le(n).u16le(e),ce(X.SYSCOMMAND,t.take())}function Ao(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),ce(X.WINDOW_MOVE,i.take())}function So({program:n,workingDir:e="",arguments:t=""}){let s=$t(n||""),r=$t(e||""),i=$t(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),ce(X.EXEC,o.take())}function ys(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 fs(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 xo(n,e){let t={};if(e&K.OWNER&&(t.ownerWindowId=n.u32le()),e&K.STYLE&&(t.style=n.u32le(),t.extendedStyle=n.u32le()),e&K.SHOW&&(t.showState=n.u8()),e&K.TITLE){let s=n.u16le();t.title=ys(n.raw(Math.min(s,n.remaining)))}return e&K.CLIENT_AREA_OFFSET&&(t.clientOffsetX=te(n.u32le()),t.clientOffsetY=te(n.u32le())),e&K.CLIENT_AREA_SIZE&&(t.clientWidth=te(n.u32le()),t.clientHeight=te(n.u32le())),e&K.RP_CONTENT&&n.u8(),e&K.ROOT_PARENT&&n.u32le(),e&K.WND_OFFSET&&(t.x=te(n.u32le()),t.y=te(n.u32le())),e&K.CLIENT_DELTA&&(n.u32le(),n.u32le()),e&K.WND_SIZE&&(t.width=te(n.u32le()),t.height=te(n.u32le())),e&K.WND_RECTS&&(t.windowRects=fs(n,n.u16le())),e&K.VIS_OFFSET&&(t.visibleOffsetX=te(n.u32le()),t.visibleOffsetY=te(n.u32le())),e&K.VISIBILITY&&(t.visibilityRects=fs(n,n.u16le())),t}function ws(n){return!(!n||n.ownerWindowId||(n.style||0)&oo||(n.extendedStyle||0)&(ao|co))}function gs(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&ho,a=i>>2;if(o!==lo||a!==uo)break;if(n.remaining<6)throw new Error("RDP RemoteApp window-order header is truncated.");let c=n.u16le(),h=n.u32le(),E=r+c;if(c<7||E>n.bytes.length)throw new Error("RDP RemoteApp window order has an invalid size.");let w=!!(h&Me.TYPE_WINDOW),x=!!(h&(Me.ICON|Me.CACHED_ICON));if(w&&!x&&E-n.offset>=4){let f=n.u32le(),m={};try{m=xo(n,h)}catch(A){console.warn("[RDP] Dropped an unreadable RemoteApp window order",{windowId:f,fieldFlags:`0x${(h>>>0).toString(16)}`,error:A instanceof Error?A.message:String(A)})}let l="update";h&Me.STATE_DELETED?l="deleted":h&Me.STATE_NEW&&(l="new"),t.push({type:l,windowId:f,fieldFlags:h,...m})}if(n.offset=E,n.offset<=r)break}return t}function To(n){let e=new T(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 T(e.raw(r-4));if(s===X.HANDSHAKE&&i.remaining>=4){t.push({type:"handshake",buildNumber:i.u32le()});continue}if(s===X.HANDSHAKE_EX&&i.remaining>=8){t.push({type:"handshake",buildNumber:i.u32le(),flags:i.u32le(),extended:!0});continue}if(s===X.EXEC_RESULT&&i.remaining>=12){let o=i.u16le(),a=i.u16le(),c=i.u32le();i.u16le();let h=i.u16le(),E=ys(i.raw(Math.min(h,i.remaining)));t.push({type:"execute-result",flags:o,result:a,rawResult:c,program:E});continue}t.push({type:"unknown",orderType:s,body:i.rest().slice()})}return t}var dt=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 To(e)){if(t.type==="handshake"){if(this.started)continue;this.started=!0,this.send(po(ms)),this.send(mo());for(let s of yo(this.width,this.height))this.send(s);this.send(So(this.application)),this.onReady?.(t);continue}t.type==="execute-result"&&this.onResult?.({...t,ok:t.result===0,message:io[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(Es(e,t)),!0)}activate(e){return this.started?(this.send(wo(e,!0)),!0):!1}sysCommand(e,t){return this.started?(this.send(go(e,t)),!0):!1}moveWindow(e,t){return this.started?(this.send(Ao(e,t)),!0):!1}};var ne={INITIALIZED:2147483648,ENCRYPT_RDP:1073741824,COMPRESS_RDP:8388608,SHOW_PROTOCOL:2097152},As=1,Ss=2,xs=16,qt=1600;function Ts(n,e=qt,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|=As),r+e>=n.length&&(o|=Ss);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 ft=class{parts;expectedLength;constructor(){this.parts=[],this.expectedLength=0}push(e){if(e.length<8)return null;let t=new T(e),s=t.u32le(),r=t.u32le(),i=t.rest();if(r&As&&(this.parts=[],this.expectedLength=s),this.parts.push(i.slice()),!((r&Ss)!==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},Xt=4096,He=class{encryptionMethod;encryptionLevel;keys;encryptState;decryptState;encryptedPdus;decryptedPdus;constructor(){this.encryptionMethod=oe.NONE,this.encryptionLevel=it.NONE,this.keys=null,this.encryptState=null,this.decryptState=null,this.encryptedPdus=0,this.decryptedPdus=0}get headerPresent(){return this.encryptionLevel!==it.NONE||this.encryptionMethod!==oe.NONE}get encryptionEnabled(){return this.encryptionMethod!==oe.NONE&&this.keys!==null}configure(e,t,s,r){if(this.encryptionMethod=e,this.encryptionLevel=t,e!==oe.NONE){if(e&oe.FIPS)throw new Error("RDP: this host requires FIPS encryption, which this client does not implement");this.keys=Ln(s,r,e),this.encryptState=J(this.keys.encryptKey),this.decryptState=J(this.keys.decryptKey)}}#e(){this.keys.encryptKey=Ut(this.keys.initialEncryptKey,this.keys.encryptKey,this.keys.keyLength,this.keys.is40Bit),this.encryptState=J(this.keys.encryptKey),this.encryptedPdus=0}#t(){this.keys.decryptKey=Ut(this.keys.initialDecryptKey,this.keys.decryptKey,this.keys.keyLength,this.keys.is40Bit),this.decryptState=J(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(Nn(this.keys.macKey,e)),r.raw(z(this.encryptState,e)),++this.encryptedPdus===Xt&&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 T(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=z(this.decryptState,s.rest());return++this.decryptedPdus===Xt&&this.#t(),{flags:r,payload:i}}decryptFastPath(e){if(!this.encryptionEnabled||e.length<=8)return e;let t=z(this.decryptState,e.subarray(8));return++this.decryptedPdus===Xt&&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},bo=1,_o=4,Co=16,Ro=1,vo=4,Lo=2,No=8;function B(n,e){let t=new p(e.length+4);return t.u16le(n).u16le(e.length+4).raw(e),t.take()}function Uo(){let n=new p(24);return n.u16le(1),n.u16le(3),n.u16le(512),n.u16le(0),n.u16le(0),n.u16le(Ro|vo),n.u16le(0),n.u16le(0),n.u16le(0),n.u8(1),n.u8(1),B(k.GENERAL,n.take())}function Io(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),B(k.BITMAP,t.take())}function Oo(){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(Lo|No),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),B(k.ORDER,n.take())}function ko(){let n=new p(40);return n.zeros(24),n.u16le(0).u16le(0),n.u16le(0).u16le(0),n.u16le(0).u16le(0),B(k.BITMAPCACHE,n.take())}function Po(){let n=new p(12);return n.u16le(0),n.u16le(0),n.u16le(2),n.u16le(2),B(k.CONTROL,n.take())}function Do(){let n=new p(12);return n.u16le(0).u16le(0).u16le(0).u16le(0),B(k.ACTIVATION,n.take())}function Mo(){let n=new p(10);return n.u16le(1),n.u16le(20),n.u16le(20),B(k.POINTER,n.take())}function Ho(){let n=new p(8);return n.u16le(0).u16le(0),B(k.SHARE,n.take())}function Fo(){let n=new p(8);return n.u16le(6).u16le(0),B(k.COLORCACHE,n.take())}function Bo(){let n=new p(8);return n.u16le(0).u16le(0),B(k.SOUND,n.take())}function Ko(n){let e=new p(88);return e.u16le(bo|_o|Co),e.u16le(0),e.u32le(n),e.u32le(4),e.u32le(0),e.u32le(12),e.zeros(64),B(k.INPUT,e.take())}function Go(){let n=new p(8);return n.u16le(1).u16le(0),B(k.FONT,n.take())}function Wo(){let n=new p(8);return n.u32le(0),B(k.BRUSH,n.take())}function Vo(){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),B(k.GLYPHCACHE,n.take())}function Yo(){let n=new p(12);return n.u32le(0),n.u16le(0),n.u16le(0),B(k.OFFSCREENCACHE,n.take())}function $o(){let n=new p(4);return n.u32le(1),B(k.RAIL,n.take())}function qo(n=0,e=0){let t=new p(7);return t.u32le(1),t.u8(n),t.u16le(e),B(k.WINDOW,t.take())}function bs({width:n,height:e,keyboardLayout:t,remoteApp:s=!1,remoteAppCaps:r=null}){let i=[Uo(),Io(n,e),Oo(),ko(),Fo(),Do(),Po(),Mo(),Ho(),Ko(t),Wo(),Vo(),Bo(),Go(),Yo()];return s&&(i.push($o()),i.push(qo(r?.numIconCaches||0,r?.numIconCacheEntries||0))),{bytes:b(...i),count:i.length}}function _s(n){let e=new T(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 T(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 me={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},pt={ORDERS:0,BITMAP:1,PALETTE:2,SYNCHRONIZE:3},zt={REQUEST_CONTROL:1,GRANTED_CONTROL:2,DETACH:3,COOPERATE:4},Ke={SYNC:0,SCANCODE:4,UNICODE:5,MOUSE:32769,MOUSEX:32770},Be={EXTENDED:256,DOWN:16384,RELEASE:32768},se={WHEEL:512,HWHEEL:1024,WHEEL_NEGATIVE:256,MOVE:2048,DOWN:32768,BUTTON1:4096,BUTTON2:8192,BUTTON3:16384};function Rs(n,e=!1){let t=e?Math.sign(n):-Math.sign(n);if(t===0)return 0;let s=e?se.HWHEEL:se.WHEEL,r=120;return t>0?s|r:s|se.WHEEL_NEGATIVE|-r&255}var mt={SCROLL_LOCK:1,NUM_LOCK:2,CAPS_LOCK:4,KANA_LOCK:8},Ce={SYSTEM:1,POSITION:3,COLOR:6,CACHED:7,POINTER:8,LARGE:9},Xo=196979,zo=8,Qo=32768,jo=524288,Zo={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 vs(n){return Zo[n]||`The host ended the session with error info 0x${n.toString(16).padStart(8,"0")}.`}function Qt(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 Ls(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),Qt(me.DATA,e,r.take())}function Fe(n,e){let t=n.length;n.utf16le(e);let s=n.length-t;return n.u16le(0),s}function Ns({domain:n,username:e,password:t,performanceFlags:s,autoLogon:r,remoteApp:i=!1,audio:o=!1}){let a=new p(512),c=Fe(a,n||""),h=Fe(a,e||""),E=Fe(a,t||""),w=Fe(a,""),x=Fe(a,""),f=new p(768);return f.u32le(0),f.u32le((Xo|(r?zo:0)|(i?Qo:0)|(o?0:jo))>>>0),f.u16le(c),f.u16le(h),f.u16le(E),f.u16le(w),f.u16le(x),f.raw(a.take()),f.u16le(2),f.u16le(2),f.u16le(0),f.u16le(2),f.u16le(0),f.zeros(172),f.u32le(0),f.u32le(s>>>0),f.u16le(0),f.take()}function Us(n){let e=new p(4);return e.u16le(1),e.u16le(n),e.take()}function jt(n){let e=new p(8);return e.u16le(n),e.u16le(0),e.u32le(0),e.take()}function Is(){let n=new p(8);return n.u16le(0),n.u16le(0),n.u16le(3),n.u16le(50),n.take()}function Os(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 ks(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 Ge(n,e){let t=new p(12);return t.u32le(0),t.u16le(n),e(t),t.take()}function Zt(n,e,t){return Ge(Ke.SCANCODE,s=>{s.u16le((e?Be.DOWN:Be.RELEASE)|(t?Be.EXTENDED:0)),s.u16le(n),s.u16le(0)})}function Jt(n,e){return Ge(Ke.UNICODE,t=>{t.u16le(e?Be.DOWN:Be.RELEASE),t.u16le(n),t.u16le(0)})}function Et(n,e,t){return Ge(Ke.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 Ps(n,e,t){return Ge(Ke.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 en(n){return Ge(Ke.SYNC,e=>{e.u16le(0),e.u32le(n>>>0)})}function Ds(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 Ms(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 Hs(n){let e=new T(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 Fs(n){let e=new T(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 Bs(n){let e=new T(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 Jo=1,ea=1024;function tn(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(),E=n.u16le(),w=n.u16le(),x=n.u16le(),f=!!(w&Jo);if(f&&!(w&ea)){n.u16le();let m=n.u16le();n.u16le(),n.u16le(),x=m}t.push({left:r,top:i,right:o,bottom:a,width:c,height:h,bitsPerPixel:E,compressed:f,data:n.raw(Math.min(x,n.remaining))})}return t}function nn(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 Cs(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(),E=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:E}}function sn(n){let e=n.u16le();if(n.u16le(),e===Ce.POSITION)return{kind:"position",x:n.u16le(),y:n.u16le()};if(e===Ce.SYSTEM)return{kind:"system",hidden:n.u32le()===0};if(e===Ce.CACHED)return{kind:"cached",cacheIndex:n.u16le()};if(e===Ce.COLOR)return Cs(n,24);if(e===Ce.POINTER){let t=n.u16le();return Cs(n,t)}return e===Ce.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},Gs={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 rn(n){return Object.prototype.hasOwnProperty.call(Ks,n)?{scancode:Ks[n],extended:!1}:Object.prototype.hasOwnProperty.call(Gs,n)?{scancode:Gs[n],extended:!0}:null}var Ws=[{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 Re="VNC_GATEWAY_READY_v1",ve="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"},ta=255,on={name:"cliprdr",options:ne.INITIALIZED|ne.ENCRYPT_RDP|ne.SHOW_PROTOCOL},an={name:"rail",options:ne.INITIALIZED|ne.ENCRYPT_RDP|ne.SHOW_PROTOCOL},cn={name:"rdpsnd",options:ne.INITIALIZED|ne.ENCRYPT_RDP},na=1,sa=2,ra=4,ia=1200,oa=120,yt=2,aa=4,ca=12,Vs=320,wt=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,audio:!1,remoteApp:null,performance:na|sa|ra,...t},this.state=L.IDLE,this.legacyRetryUsed=!1,this.desktopWidth=this.options.width,this.desktopHeight=this.options.height,this.palette=null,this.userId=xe,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.audio=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 He,this.replacingTransport=!1,this.channelNamesById=new Map,this.channelReassemblers=new Map,this.clipboard=null,this.rail=null,this.audio=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.#n()),this.socket.addEventListener("message",e=>this.#c(e)),this.socket.addEventListener("close",e=>this.#a(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()}#n(){this.socket.send(Re),this.state=L.NEGOTIATING,this.#s(On(this.requestedProtocol)),this.keepaliveTimer=setInterval(()=>{if(this.socket.readyState===WebSocket.OPEN&&(this.socket.send(ve),this.state===L.CONNECTED))try{this.#f([en(this.toggleFlags||0)])}catch{}},25e3)}#s(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)}#a(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{}}}#c(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}=Pn(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}=kn(e))}catch(a){if(this.options.security==="auto"&&!this.legacyRetryUsed&&a.negotiationFailure===In.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=cs(es(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.#s(ts()),this.#s(ns());return}if(this.state===L.ATTACH_USER){({userId:this.userId}=ss(e)),this.channelsToJoin=[this.userId,this.ioChannelId,...this.serverData.channelIds],this.joinedChannels=0,this.state=L.JOIN_CHANNELS,this.#s(Gt(this.userId,this.channelsToJoin[0]));return}if(this.state===L.JOIN_CHANNELS){if(rs(e),this.joinedChannels+=1,this.joinedChannels<this.channelsToJoin.length){this.#s(Gt(this.userId,this.channelsToJoin[this.joinedChannels]));return}this.#g();return}let t=is(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 tt({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(on),this.options.audio&&this.requestedChannels.push(cn),this.options.remoteApp?.program&&this.requestedChannels.push(an),this.#s(Jn(as({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=bn(this.clientRandom,t.modulus,t.exponent);this.#d(He.securityExchange(s))}let e=Ns({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,audio:!!this.options.audio});this.state=L.LICENSING,this.#d(this.security.wrap(e,G.INFO_PKT))}#d(e){this.#s(Wt(this.userId,this.ioChannelId,e))}#A(e){if(e.length<4)return;if(e[0]===ta){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=Hs(e);if(t.pduSource&&(this.serverChannelId=t.pduSource),t.pduType===me.DEMAND_ACTIVE){this.#m(t.payload);return}if(t.pduType===me.DEACTIVATE_ALL){console.info("[RDP] Host deactivated the share; waiting for a new demand active"),this.state=L.CAPABILITIES;return}if(t.pduType===me.SERVER_REDIRECT)throw new Error("This host redirected the session to another server, which this client cannot follow.");if(t.pduType!==me.DATA)return;let s=Fs(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}=Bs(e);this.shareId=t;let r=_s(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}=bs({width:this.desktopWidth,height:this.desktopHeight,keyboardLayout:this.options.keyboardLayout,remoteApp:!!this.options.remoteApp?.program,remoteAppCaps:r});this.#H(me.CONFIRM_ACTIVE,Os(this.shareId,i,o)),this.#w(M.SYNCHRONIZE,Us(this.serverChannelId)),this.#w(M.CONTROL,jt(zt.COOPERATE)),this.#w(M.CONTROL,jt(zt.REQUEST_CONTROL)),this.#w(M.FONT_LIST,Is())}#_(e){switch(e.pduType2){case M.UPDATE:this.#C(new T(e.payload));return;case M.POINTER:this.dispatchEvent(new CustomEvent("pointer",{detail:sn(new T(e.payload))}));return;case M.FONT_MAP:this.#I();return;case M.SET_ERROR_INFO:{let t=new T(e.payload).u32le();if(t===0)return;this.#i(new Error(vs(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===pt.BITMAP){let s=tn(e);s.length>0&&this.dispatchEvent(new CustomEvent("bitmap",{detail:{rects:s,palette:this.palette}}));return}if(t===pt.PALETTE){this.palette=nn(e),this.dispatchEvent(new CustomEvent("palette",{detail:this.palette}));return}if(t===pt.ORDERS){this.options.remoteApp?.program?this.#R(gs(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.#T()}this.#U(),!(!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}})))},ia))}get remoteAppPrimaryWindow(){let e=null,t=-1;for(let s of this.remoteAppWindows.values()){if(!ws(s)||s.showState===_e.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)<=yt&&Math.abs(e.y||0)<=yt&&Math.abs((e.width||0)-t.width)<=yt&&Math.abs((e.height||0)-t.height)<=yt:!0}#T(){this.remoteAppFitTimer||(this.remoteAppFitTimer=setTimeout(()=>{this.remoteAppFitTimer=null,this.#N()},oa))}#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===_e.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>=aa||e.moves>=ca)){if(e.attempts+=1,e.moves+=1,t.showState===_e.MAXIMIZED){console.info("[RDP] Restoring the maximized RemoteApp window before fitting it"),this.rail.sysCommand(t.windowId,ps.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})}}#U(){let e=this.remoteAppPrimaryWindow;if(!e||!e.width||!e.height||e.showState===_e.MINIMIZED||e.showState===_e.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(Vs,Math.min(this.desktopWidth,Math.floor(e))),height:Math.max(Vs,Math.min(this.desktopHeight,Math.floor(t))),attempts:0,moves:0,lastGeometry:""};return this.remoteAppFit=s,this.#T(),!0}#I(){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 T(r);for(;i.remaining>=3;){let o=i.u8(),a=o&15,c=o>>4&3;o>>6&3&2&&i.u8();let E=i.u16le(),w=i.raw(Math.min(E,i.remaining));if(c!==0){if(c===2&&(this.fastPathFragments=[]),this.fastPathFragments.push(w.slice()),c!==1)continue;w=b(...this.fastPathFragments),this.fastPathFragments=[]}this.#k(a,w)}}#k(e,t){let s=new T(t);switch(e){case 1:{s.u16le();let r=tn(s);r.length>0&&this.dispatchEvent(new CustomEvent("bitmap",{detail:{rects:r,palette:this.palette}}));return}case 2:this.palette=nn(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:sn(new T(b(i,t)))}));return}default:return}}#P(e,t){let s=this.channelReassemblers.get(e);s||(s=new ft,this.channelReassemblers.set(e,s));let r=s.push(t);if(r){if(e===on.name){this.#b().receive(r);return}if(e===an.name){this.#D().receive(r);return}if(e===cn.name)try{this.#M().receive(r)}catch(i){console.warn("[RDP] dropped an unreadable audio PDU",i)}}}#x(e,t){let s=[...this.channelNamesById].find(([,o])=>o===e)?.[0];if(s===void 0)return!1;let i=(this.requestedChannels.find(o=>o.name===e)?.options??0)&ne.SHOW_PROTOCOL?xs:0;for(let o of Ts(t,qt,i))this.#s(Wt(this.userId,s,this.security.wrap(o)));return!0}#D(){return this.rail?this.rail:(this.rail=new dt({application:this.options.remoteApp,width:this.remoteAppFit?.width||this.desktopWidth,height:this.remoteAppFit?.height||this.desktopHeight,send:e=>this.#x(an.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)}#M(){return this.audio?this.audio:(this.audio=new lt({send:e=>this.#x(cn.name,e),log:(e,t)=>console.info(`[RDP] ${e}`,t??"")}),this.audio.addEventListener("ready",e=>{this.dispatchEvent(new CustomEvent("audioready",{detail:e.detail}))}),this.audio.addEventListener("audio",e=>{this.dispatchEvent(new CustomEvent("audio",{detail:e.detail}))}),this.audio.addEventListener("close",()=>{this.dispatchEvent(new CustomEvent("audioclosed"))}),this.audio)}get audioActive(){return!!this.audio?.ready}#b(){return this.clipboard?this.clipboard:(this.clipboard=new ct({send:e=>this.#x(on.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))}#H(e,t){this.#d(this.security.wrap(Qt(e,this.userId,t)))}#w(e,t){this.#d(this.security.wrap(Ls(this.shareId,this.userId,e,t)))}get connected(){return this.state===L.CONNECTED}#f(e){!this.connected||e.length===0||this.#w(M.INPUT,ks(e))}sendKeyByCode(e,t){let s=rn(e);return s?(this.#f([Zt(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(Jt(i,!0)),t.push(Jt(i,!1))}for(let s=0;s<t.length;s+=40)this.#f(t.slice(s,s+40))}sendCtrlAltDel(){let e=Ws.map(({code:t,pressed:s})=>{let r=rn(t);return Zt(r.scancode,s,r.extended)});this.#f(e)}sendMouseMove(e,t){this.#f([Et(se.MOVE,e,t)])}sendMouseButton(e,t,s,r){let i={0:se.BUTTON1,1:se.BUTTON3,2:se.BUTTON2}[e];if(i===void 0){let o=e===3?1:2;this.#f([Ps(o|(t?se.DOWN:0),s,r)]);return}this.#f([Et(i|(t?se.DOWN:0),s,r)])}sendWheel(e,t,s,r=!1){let i=Rs(e,r);i&&this.#f([Et(i,t,s)])}sendKeyboardSync(e){this.toggleFlags=e>>>0,this.#f([en(this.toggleFlags)])}refresh(e){!this.connected||!this.refreshRectSupported||this.#w(M.REFRESH_RECT,Ds([e||{left:0,top:0,right:this.desktopWidth-1,bottom:this.desktopHeight-1}]))}setOutputEnabled(e){this.connected&&this.#w(M.SUPPRESS_OUTPUT,Ms(e,{left:0,top:0,right:this.desktopWidth-1,bottom:this.desktopHeight-1}))}};function ha(n){return(n&192)!==192?n>>5:(n&240)===240?n:n>>4}function la(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,E=!0,w=()=>{let m=0;for(let l=0;l<s;l++)m|=n[o+l]<<l*8;return o+=s,m>>>0},x=m=>{let l=n[o];if(m===2){let g=l&31;return g===0?(o+=2,n[o-1]+1):(o+=1,g*8)}if(m===13){let g=l&15;return g===0?(o+=2,n[o-1]+1):(o+=1,g*8)}if(m===0||m===1||m===3||m===4){let g=l&31;return g===0?(o+=2,n[o-1]+32):(o+=1,g)}if(m===12||m===14){let g=l&15;return g===0?(o+=2,n[o-1]+16):(o+=1,g)}let A=n[o+1]|n[o+2]<<8;return o+=3,A},f=(m,l)=>{let A=1;for(let g=0;g<l;g++){if(E)r[a]=m&A?c:0;else{let _=r[a-e];r[a]=m&A?(_^c)>>>0:_}a++,A=A<<1&255}};for(;o<n.length&&a<r.length;){E&&a>=e&&(E=!1);let m=ha(n[o]);if(m===0||m===240){let l=x(m);if(E)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,m){case 1:case 241:case 12:case 246:{let l=x(m);if((m===12||m===246)&&(c=w()),E)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=x(m),A=w(),g=w();for(;l-- >0&&a<r.length-1;)r[a++]=A,r[a++]=g;break}case 3:case 243:{let l=x(m),A=w();for(;l-- >0&&a<r.length;)r[a++]=A;break}case 2:case 242:case 13:case 247:{let l=x(m);for((m===13||m===247)&&(c=w());l>8;)f(n[o++],8),l-=8;l>0&&f(n[o++],l);break}case 4:case 244:{let l=x(m);for(;l-- >0&&a<r.length;)r[a++]=w();break}case 249:o++,f(3,8);break;case 250:o++,f(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${m.toString(16)}`)}}return r}function ua(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 da(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 E=0;E<s;E++)h|=n[a+E]<<E*8;r[o+c]=h>>>0,a+=s}}return r}function fa(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 E=(i&255)*3;o=t?t[E]:i,a=t?t[E+1]:i,c=t?t[E+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 Ys(n,e){let t=Math.max(1,Math.ceil(n.bitsPerPixel/8)),s=n.compressed?ua(la(n.data,n.width,n.height,t),n.width):da(n.data,n.width,n.height,t);return fa(s,n.bitsPerPixel,e)}var hn=/Mac|iPod|iPhone|iPad/.test(globalThis.navigator?.platform||globalThis.navigator?.userAgent||""),$s={MetaLeft:"ControlLeft",MetaRight:"ControlRight"},qs=60,pa=16,Xs=20,ma=8,Ea=1,gt=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}#n(){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.#n());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(ma,Math.max(Ea,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,E=r.scrollTop+c;this.zoom=s,this.applyScale();let w=i>0?this.scale/i:1;r.scrollLeft=h*w-a,r.scrollTop=E*w-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=Ys(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)})}}#s(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,E=Math.ceil(t/8/2)*2,w=new Uint8ClampedArray(t*s*4);for(let l=0;l<s;l++){let A=s-1-l;for(let g=0;g<t;g++){let _=o[A*E+(g>>3)],u=_!==void 0&&(_&128>>(g&7))!==0,d=0,S=0,R=0,C=u?0:255;if(r===1)d=S=R=i[A*h+(g>>3)]&128>>(g&7)?255:0;else{let v=r/8,I=A*h+g*v;if(r===16){let j=i[I]|i[I+1]<<8;d=(j>>11&31)*255/31,S=(j>>5&63)*255/63,R=(j&31)*255/31}else R=i[I]||0,S=i[I+1]||0,d=i[I+2]||0,r===32&&i[I+3]!==void 0&&o.length===0&&(C=i[I+3])}let U=(l*t+g)*4;w[U]=d,w[U+1]=S,w[U+2]=R,w[U+3]=C}}let x=document.createElement("canvas");x.width=t,x.height=s,x.getContext("2d").putImageData(new ImageData(w,t,s),0,0);let f=Math.min(a||0,t-1),m=Math.min(c||0,s-1);return`url(${x.toDataURL("image/png")}) ${f} ${m}, 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.#s(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))}}#a(e){if(this.keyboardSynced||!this.client)return;this.keyboardSynced=!0;let t=0;e.getModifierState?.("CapsLock")&&(t|=mt.CAPS_LOCK),e.getModifierState?.("NumLock")&&(t|=mt.NUM_LOCK),e.getModifierState?.("ScrollLock")&&(t|=mt.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,E=0,w={x:0,y:0},x=0,f=0,m=0,l=null,A=u=>({x:(u[0].clientX+u[1].clientX)/2,y:(u[0].clientY+u[1].clientY)/2}),g=u=>Math.hypot(u[0].clientX-u[1].clientX,u[0].clientY-u[1].clientY),_=()=>{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(_)))},mousedown:u=>{if(this.canvas.focus(),!t())return;u.preventDefault();let{x:d,y:S}=this.#r(u);this.client.sendMouseButton(u.button,!0,d,S)},mouseup:u=>{if(!t())return;u.preventDefault();let{x:d,y:S}=this.#r(u);this.client.sendMouseButton(u.button,!1,d,S)},contextmenu:u=>u.preventDefault(),wheel:u=>{if(!t())return;u.preventDefault();let d=u.deltaY;if(u.deltaMode===WheelEvent.DOM_DELTA_LINE&&(d*=pa),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)<qs))return;let S=Math.sign(i);i-=S*qs;let{x:R,y:C}=this.#r(u);this.client.sendWheel(S,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:S,y:R}=this.#r(d);this.client.sendMouseMove(S,R),this.client.sendMouseButton(0,!0,S,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=A(u.touches),S=g(u.touches);w={x:d.x,y:d.y},x=S,h=d.y,E=d.x,f=S,m=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:S,y:R}=this.#r(d);this.client.sendMouseMove(S,R)}else if(u.touches.length===2){let d=A(u.touches),S=d.x,R=d.y,C=g(u.touches),U=h-R,v=E-S;h=R,E=S;let I=Math.hypot(S-w.x,R-w.y),j=Math.abs(C-x),Ee=x>0?C/x:1;if((l==="undecided"||l==="gesture")&&(j>20&&Math.abs(Ee-1)>.15&&j>I*.8?l="pinch":I>8&&(l="scroll")),l==="pinch")f>0&&Math.abs(C-f)>1&&(this.userZoomed=!0,this.setZoom(this.zoom*(C/f),{x:S,y:R})),f=C;else if(l==="scroll"){if(f=C,this.canPan()){this.panBy(v*-1,U*-1),m=0;return}for(U&&m&&Math.sign(m)!==Math.sign(U)&&(m=0),m+=U;Math.abs(m)>=Xs;){let de=Math.sign(m);m-=de*Xs;let{x:Ne,y:fe}=this.#r({clientX:S,clientY:R});this.client.sendWheel(de,Ne,fe)}}}}},touchend:u=>{if(t())if(u.preventDefault(),u.touches.length===0){if(o){let{x:d,y:S}=this.#r({clientX:a,clientY:c});this.client.sendMouseButton(0,!1,d,S),o=!1}l==="pinch"&&this.zoom<=1.05&&this.resetZoom(),l=null,m=0,f=0}else u.touches.length===1&&(l==="gesture"||l==="pinch"||l==="scroll"||l==="undecided")&&(l==="pinch"&&this.zoom<=1.05&&this.resetZoom(),l=null,f=0,m=0)},touchcancel:u=>{if(t()){if(o){let{x:d,y:S}=this.#r({clientX:a,clientY:c});this.client.sendMouseButton(0,!1,d,S),o=!1}l==="pinch"&&this.zoom<=1.05&&this.resetZoom(),l=null,m=0,f=0}},keydown:u=>{if(!t()||(this.#a(u),this.#c(u)))return;let d=this.#i(u.code);if(this.client.sendKeyByCode(d,!0)){if(u.preventDefault(),hn&&u.metaKey&&!$s[u.code]){this.client.sendKeyByCode(d,!1);return}this.heldKeys.add(d)}},keyup:u=>{if(!t()||this.#c(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,S=d instanceof Node&&this.container.contains(d);if(document.activeElement!==this.canvas&&!S)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 hn&&$s[e]||e}#c(e){return e.code!=="KeyV"?!1:hn?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 zs=["pointerdown","keydown","touchend"];function Qs(){return typeof globalThis.AudioContext=="function"?globalThis.AudioContext:null}function js(){return Qs()!==null}function ya(n){let{channels:e,bitsPerSample:t}=n.format,s=t>>3,r=s*e;if(!r)return null;let i=Math.floor(n.samples.length/r);if(i<=0)return null;let o=Array.from({length:e},()=>new Float32Array(i)),a=new DataView(n.samples.buffer,n.samples.byteOffset,n.samples.byteLength);for(let c=0;c<i;c++)for(let h=0;h<e;h++){let E=c*r+h*s;o[h][c]=t===16?a.getInt16(E,!0)/32768:(a.getUint8(E)-128)/128}return o}var At=class{#e=null;#t=null;#n=0;#s=!1;#r=1;#a=!1;#i=null;dropped=0;played=0;constructor({volume:e=1,muted:t=!1}={}){this.#r=e,this.#s=t}#c(e){if(this.#a)return null;if(this.#e)return this.#e;let t=Qs();if(!t)return null;let s;try{s=new t({sampleRate:e})}catch{s=new t}let r=s.createGain();return r.gain.value=this.#s?0:this.#r,r.connect(s.destination),this.#e=s,this.#t=r,this.#n=s.currentTime,this.#o(),s}#o(){if(this.#i||typeof globalThis.addEventListener!="function")return;let e=()=>{this.resume()};for(let t of zs)globalThis.addEventListener(t,e,{passive:!0});this.#i=()=>{for(let t of zs)globalThis.removeEventListener(t,e);this.#i=null}}async resume(){let e=this.#e;if(!e||this.#a)return!1;if(e.state==="running")return!0;try{await e.resume()}catch{return!1}return e.state==="running"&&(this.#n=e.currentTime+.06),e.state==="running"}get running(){return this.#e?.state==="running"}get muted(){return this.#s}set muted(e){this.#s=e,this.#t&&(this.#t.gain.value=e?0:this.#r)}get volume(){return this.#r}set volume(e){this.#r=Math.min(1,Math.max(0,e)),this.#t&&!this.#s&&(this.#t.gain.value=this.#r)}play(e){if(this.#a||this.#s)return!1;let t=ya(e);if(!t?.length)return!1;let s=this.#c(e.format.samplesPerSec);if(!s||!this.#t)return!1;if(s.state!=="running"&&(this.resume(),s.state!=="running"))return this.dropped++,!1;let r=s.currentTime;if(this.#n<r-.25)this.#n=r+.06;else if(this.#n>r+1)return this.dropped++,!1;let i=s.createBuffer(t.length,t[0].length,e.format.samplesPerSec);for(let a=0;a<t.length;a++)i.copyToChannel(t[a],a);let o=s.createBufferSource();return o.buffer=i,o.connect(this.#t),o.start(Math.max(this.#n,r)),this.#n=Math.max(this.#n,r)+i.duration,this.played++,!0}reset(){this.#e&&(this.#n=this.#e.currentTime)}dispose(){this.#a=!0,this.#i?.();let e=this.#e;this.#e=null,this.#t=null,e&&e.close().catch(()=>{})}};var Ve={vnc:5900,rdp:3389,ssh:22},lh=Ve.ssh;var uh=5*6e4;var wa={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 ga(n,e){let t=new URLSearchParams({host:e.host,port:String(e.port),security:e.security});return`${n}/rdp-ws?${t}`}function Aa({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 ln=class extends EventTarget{protocol="rdp";constructor(e,t,s={}){super(),this.url=t,this.options=s,this.display=new gt(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.audio=null,this.audioMuted=!1,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 wt(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,audio:!!this.options.audio&&js()}),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("audioready",t=>{this.audio??=new At({muted:this.audioMuted}),this.dispatchEvent(new CustomEvent("audio",{detail:{on:!0,formats:t.detail.formats.length}}))}),this.client.addEventListener("audio",t=>{this.audio?.play(t.detail)}),this.client.addEventListener("audioclosed",()=>{this.audio?.reset(),this.dispatchEvent(new CustomEvent("audio",{detail:{on:!1,formats:0}}))}),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.audio?.dispose(),this.audio=null,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
|
-
`||
|
|
3
|
-
`?65293:t===" "?65289:s;this.#e.sendKey(r,null,!0),this.#e.sendKey(r,null,!1)}return!0}};function ba({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 tr={protocol:"vnc",label:"VNC Client",defaultPort:Ve.vnc,dialog:Sa,buildUrl:xa,createSession:(n,e,t)=>new St(n,e,t),describeState:n=>n instanceof St?n.describeState():{},describeDisconnect:ba};var y={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},nr=1,sr={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 _a=new TextEncoder,Ca=new TextDecoder;function re(n){return _a.encode(n)}function Ye(n){return Ca.decode(n)}function ie(...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 $e(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e)}function dn(n){return $e(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}u64(e){let t=Math.floor(e);return this.u32(Math.floor(t/4294967296)).u32(t%4294967296)}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"?re(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}u64(){return this.u32()*4294967296+this.u32()}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 Ye(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 fn(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,Ra={"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"}},pn={"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 rr(n,e){if(!H)return!1;try{return await H.generateKey(n,!1,e),!0}catch{return!1}}var xt=null;async function ir(){if(xt)return xt;let[n,e]=await Promise.all([rr({name:"X25519"},["deriveBits"]),rr({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"),xt={kex:t,hostKey:s,x25519:n,ed25519:e},xt}async function or(n){let e=Ra[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 ar(n){return new O(n).string()}async function cr(n){let e=new Uint8Array(await H.digest("SHA-256",n));return`SHA256:${$e(e).replace(/=+$/,"")}`}async function va(n,e){let t=pn[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:dn(o),e:dn(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 La(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(pn[n]?.kind!=="ecdsa")return r;let i=new O(r),o=i.mpint(),a=i.mpint();return ie(fn(o,32),fn(a,32))}async function hr({algorithm:n,keyBlob:e,signatureBlob:t,exchangeHash:s}){let{kind:r,hash:i}=pn[n],o=await va(n,e),a=La(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 lr({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 qe({hash:n,sharedSecret:e,exchangeHash:t,letter:s,sessionId:r,length:i}){let o=new N(64+t.length).mpint(e).take(),a=ie(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,ie(o,t,c)));c=ie(c,h)}return c.subarray(0,i)}var ur="SSH-2.0-CloudflareGateway_1.0",yn={"aes256-gcm@openssh.com":{keyLength:32},"aes128-gcm@openssh.com":{keyLength:16}},bt=Object.keys(yn),dr=["hmac-sha2-256","hmac-sha2-512"],fr=["none"],Xe=16,mn=16,pr=12,En=8,Er=4,mr=262144,Na=8192,wn=globalThis.crypto?.subtle;function Tt(n,e){return n.find(t=>e.includes(t))||null}var _t=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 wn.importKey("raw",e,{name:"AES-GCM"},!1,["encrypt","decrypt"]);return new n(s,t)}nextIv(){let e=ie(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}},Ct=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(Re),this.#t(re(`${ur}\r
|
|
4
|
-
`)),this.keepaliveTimer=setInterval(()=>{if(this.socket?.readyState===WebSocket.OPEN&&(this.socket.send(
|
|
5
|
-
`}}));return}case
|
|
6
|
-
`).replace(/\r/g,"")}function
|
|
7
|
-
`);return
|
|
8
|
-
`),isStderr:!1}}))}function
|
|
9
|
-
`)}),this.transport.addEventListener("banner",
|
|
10
|
-
`).filter(Boolean).pop()||"no detail"}`))}return}let
|
|
1
|
+
function Nt(n){return new Uint8Array(n)}var f=class{bytes;view;offset=0;constructor(e=512){this.bytes=Nt(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 r=Nt(t);r.set(this.bytes.subarray(0,this.offset)),this.bytes=r,this.view=new DataView(r.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 r=this.offset;for(let s of e){let i=s.codePointAt(0)??0;if(t!==void 0&&this.offset-r>=t-2)break;if(i>65535)for(let o=0;o<s.length;o++)this.u16le(s.charCodeAt(o));else this.u16le(i)}return t!==void 0&&this.zeros(t-(this.offset-r)),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)}},S=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 T(...n){let e=n.reduce((s,i)=>s+i.length,0),t=Nt(e),r=0;for(let s of n)t.set(s,r),r+=s.length;return t}var Ns=[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],Us=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 ae(n){let e=n.length*8,t=Math.floor((n.length+8)/64)+1,r=new Uint8Array(t*64);r.set(n),r[n.length]=128;let s=new DataView(r.buffer,r.byteLength-8,8);s.setUint32(0,e>>>0,!0),s.setUint32(4,Math.floor(e/4294967296),!0);let i=1732584193,o=4023233417,a=2562383102,c=271733878,l=new Uint32Array(16),m=new DataView(r.buffer,r.byteOffset,r.byteLength);for(let p=0;p<t;p++){for(let v=0;v<16;v++)l[v]=m.getUint32(p*64+v*4,!0);let y=i,h=o,A=a,w=c;for(let v=0;v<64;v++){let u,d;v<16?(u=h&A|~h&w,d=v):v<32?(u=w&h|~w&A,d=(5*v+1)%16):v<48?(u=h^A^w,d=(3*v+5)%16):(u=A^(h|~w),d=7*v%16);let b=w;w=A,A=h;let C=y+u+Us[v]+l[d]|0;h=h+Ze(C,Ns[v])|0,y=b}i=i+y|0,o=o+h|0,a=a+A|0,c=c+w|0}let E=new Uint8Array(16),x=new DataView(E.buffer);return x.setUint32(0,i>>>0,!0),x.setUint32(4,o>>>0,!0),x.setUint32(8,a>>>0,!0),x.setUint32(12,c>>>0,!0),E}function Ot(n){let e=n.length*8,t=Math.floor((n.length+8)/64)+1,r=new Uint8Array(t*64);r.set(n),r[n.length]=128;let s=new DataView(r.buffer,r.byteLength-8,8);s.setUint32(0,Math.floor(e/4294967296)),s.setUint32(4,e>>>0);let i=1732584193,o=4023233417,a=2562383102,c=271733878,l=3285377520,m=new Uint32Array(80),E=new DataView(r.buffer,r.byteOffset,r.byteLength);for(let y=0;y<t;y++){for(let d=0;d<16;d++)m[d]=E.getUint32(y*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 h=i,A=o,w=a,v=c,u=l;for(let d=0;d<80;d++){let b,C;d<20?(b=A&w|~A&v,C=1518500249):d<40?(b=A^w^v,C=1859775393):d<60?(b=A&w|A&v|w&v,C=2400959708):(b=A^w^v,C=3395469782);let R=Ze(h,5)+b+u+C+m[d]|0;u=v,v=w,w=Ze(A,30),A=h,h=R}i=i+h|0,o=o+A|0,a=a+w|0,c=c+v|0,l=l+u|0}let x=new Uint8Array(20),p=new DataView(x.buffer);return[i,o,a,c,l].forEach((y,h)=>p.setUint32(h*4,y>>>0)),x}function ee(n){let e=new Uint8Array(256);for(let r=0;r<256;r++)e[r]=r;let t=0;for(let r=0;r<256;r++){t=t+(e[r]??0)+(n[r%n.length]??0)&255;let s=e[r]??0;e[r]=e[t]??0,e[t]=s}return{s:e,i:0,j:0}}function j(n,e){let t=new Uint8Array(e.length),{s:r}=n,{i:s,j:i}=n;for(let o=0;o<e.length;o++){s=s+1&255,i=i+r[s]&255;let a=r[s];r[s]=r[i],r[i]=a,t[o]=e[o]^r[r[s]+r[i]&255]}return n.i=s,n.j=i,t}function Ut(n){let e=0n;for(let t=n.length-1;t>=0;t--)e=e<<8n|BigInt(n[t]);return e}function Os(n,e){let t=new Uint8Array(e),r=n;for(let s=0;s<e;s++)t[s]=Number(r&0xffn),r>>=8n;return t}function Cn(n,e,t){let r=1n,s=n%t,i=e;for(;i>0n;)i&1n&&(r=r*s%t),s=s*s%t,i>>=1n;return r}function _n(n,e,t){let r=Ut(e),s=Ut(t),i=Ut(n);if(i>=r)throw new Error("RDP: client random is larger than the server RSA modulus");return Os(Cn(i,s,r),e.length)}function Ln(n,e,t){let r=p=>{let y=0n;for(let h of p)y=y<<8n|BigInt(h);return y},s=r(e),i=r(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,l=new Uint8Array(c);crypto.getRandomValues(l);for(let p=0;p<c;p++){for(;l[p]===0;)l[p]=Math.max(1,crypto.getRandomValues(new Uint8Array(1))[0]);a[2+p]=l[p]}a[2+c]=0,a.set(n,3+c);let m=Cn(r(a),i,s),E=new Uint8Array(o),x=m;for(let p=o-1;p>=0;p--)E[p]=Number(x&0xffn),x>>=8n;return E}var In=new Uint8Array(40).fill(54),Nn=new Uint8Array(48).fill(92),oe={NONE:0,BIT_40:1,BIT_128:2,BIT_56:8,FIPS:16};function J(...n){let e=n.reduce((s,i)=>s+i.length,0),t=new Uint8Array(e),r=0;for(let s of n)t.set(s,r),r+=s.length;return t}function Ee(n,e,t,r){return ae(J(n,Ot(J(e,n,t,r))))}function Rn(n,e,t){return ae(J(n,e,t))}var ks=new Uint8Array([65]),Ps=new Uint8Array([66,66]),Ds=new Uint8Array([67,67,67]),Ms=new Uint8Array([88]),Bs=new Uint8Array([89,89]),Hs=new Uint8Array([90,90,90]);function Un(n,e,t){if(e!==8)return n.slice(0,e);let r=n.slice(0,8);return r[0]=209,t&&(r[1]=38,r[2]=158),r}function Ks(n){return n===oe.BIT_40||n===oe.BIT_56?8:16}function On(n,e,t){let r=J(n.subarray(0,24),e.subarray(0,24)),s=J(Ee(r,ks,n,e),Ee(r,Ps,n,e),Ee(r,Ds,n,e)),i=J(Ee(s,Ms,n,e),Ee(s,Bs,n,e),Ee(s,Hs,n,e)),o=Ks(t),a=t===oe.BIT_40,c=x=>Un(x,o,a),l=c(i.subarray(0,16)),m=c(Rn(i.subarray(16,32),n,e)),E=c(Rn(i.subarray(32,48),n,e));return{macKey:l,keyLength:o,is40Bit:a,initialDecryptKey:m.slice(),initialEncryptKey:E.slice(),decryptKey:m,encryptKey:E}}function kn(n,e){let t=new Uint8Array(4);new DataView(t.buffer).setUint32(0,e.length,!0);let r=Ot(J(n,In,t,e));return ae(J(n,Nn,r)).subarray(0,8)}function kt(n,e,t,r){let s=Ot(J(n,In,e)),i=ae(J(n,Nn,s)).slice(0,t),o=j(ee(i),i);return Un(o,t,r)}var Pt=3,Pn=4,Fs=224,Gs=208,Ws=240,Vs=1,Ys=2,$s=3,Dn={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},qs={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 Mn(n){let e=new f(32);return e.u8(Pt).u8(0).u16be(19),e.u8(14).u8(Fs).u16be(0).u16be(0).u8(0),e.u8(Vs).u8(0).u16le(8).u32le(n),e.take()}function Bn(n){let e=new S(n);e.skip(Pn),e.u8();let t=e.u8();if(t!==Gs)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 r=e.u8();if(e.u8(),e.u16le(),r===$s){let s=e.u32le(),i=new Error(qs[s]||`The host refused the RDP connection (negotiation failure 0x${s.toString(16)}).`);throw i.negotiationFailure=s,i}return r!==Ys?{selectedProtocol:P.RDP,negotiated:!1}:{selectedProtocol:e.u32le(),negotiated:!0}}function we(n){let e=new f(n.length+7);return e.u8(Pt).u8(0).u16be(n.length+7),e.u8(2).u8(Ws).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 Hn(n){let e=[],t=0;for(;n.length-t>=4;){let r,s=!1;if(n[t]===Pt){if(r=n[t+2]<<8|n[t+3],r<Pn)throw new Error("RDP: malformed TPKT length")}else if(s=!0,r=n[t+1]&128?(n[t+1]&127)<<8|n[t+2]:n[t+1],r<2)throw new Error("RDP: malformed fast-path length");if(n.length-t<r)break;e.push({fastPath:s,frame:n.subarray(t,t+r)}),t+=r}return{frames:e,rest:n.subarray(t)}}var Xs=1,zs=2,Qs=826364754,js=6,Fn=[42,134,72,134,247,13,1,1,1];function fe(n,e){let t=e,r=n[t++],s=n[t++];if(s&128){let i=s&127;s=0;for(let o=0;o<i;o++)s=s<<8|n[t++]}return{tag:r,contentStart:t,contentEnd:t+s,next:t+s,content:n.subarray(t,t+s)}}function Ae(n){let e=[],t=0;for(;t<n.length;){let r=fe(n,t);if(e.push(r),r.next<=t)break;t=r.next}return e}function Gn(n,e){e:for(let t=0;t+e.length<=n.length;t++){for(let r=0;r<e.length;r++)if(n[t+r]!==e[r])continue e;return!0}return!1}function Kn(n){let e=0;for(;e<n.length-1&&n[e]===0;)e++;return n.subarray(e).slice().toReversed()}function Zs(n){let e=fe(n,0),t=fe(n,e.contentStart);for(let r of Ae(t.content)){if(r.tag!==48)continue;let s=Ae(r.content);if(s.length<2||s[0].tag!==48||!Gn(s[0].content,Fn)||s[1].tag!==3)continue;let i=fe(s[1].content.subarray(1),0),[o,a]=Ae(i.content);if(!o||!a)break;return{modulus:Kn(o.content),exponent:Kn(a.content),source:"x509"}}throw new Error("RDP: no RSA public key found in the host X.509 certificate")}function Js(n){n.u32le(),n.u32le();let e=n.u16le(),t=n.u16le();if(e!==js)throw new Error(`RDP: unsupported public key blob type 0x${e.toString(16)}`);let r=new S(n.raw(t));if(r.u32le()!==Qs)throw new Error("RDP: the host RSA public key blob is not in RSA1 format");let s=r.u32le();r.u32le(),r.u32le();let i=r.raw(4).slice();if(s<9)throw new Error("RDP: the host RSA modulus is too short");return{modulus:r.raw(s-8).slice(),exponent:i,source:"proprietary"}}function Wn(n){let e=fe(n,0),t=fe(n,e.contentStart);for(let r of Ae(t.content)){if(r.tag!==48)continue;let s=Ae(r.content);if(s.length<2||s[0].tag!==48||!Gn(s[0].content,Fn)||s[1].tag!==3)continue;let i=s[1].content.subarray(1),o=fe(i,0),[a,c]=Ae(o.content);if(!a||!c)break;let l=m=>{let E=0;for(;E<m.length-1&&m[E]===0;)E++;return m.subarray(E)};return{modulus:l(a.content),exponent:l(c.content),subjectPublicKey:i}}throw new Error("TLS: no RSA public key found in the host certificate")}function Vn(n){let e=new S(n),t=e.u32le()&2147483647;if(t===Xs)return Js(e);if(t===zs){let r=e.u32le(),s=null;for(let i=0;i<r;i++){let o=e.u32le();s=e.raw(o)}if(!s)throw new Error("RDP: the host sent an empty X.509 certificate chain");return Zs(s)}throw new Error(`RDP: unsupported server certificate version ${t}`)}var Ue=771,le={CHANGE_CIPHER_SPEC:20,ALERT:21,HANDSHAKE:22,APPLICATION_DATA:23},$={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},ei={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"}},ti={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"},ni=n=>new TextEncoder().encode(n);function H(n){return new Uint8Array([n>>8&255,n&255])}function Yn(n){return new Uint8Array([n>>16&255,n>>8&255,n&255])}function Dt(n){let e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,BigInt(n)),e}async function ri(n,e,t,r){let s=await crypto.subtle.importKey("raw",e,{name:"HMAC",hash:n},!1,["sign"]),i=async l=>new Uint8Array(await crypto.subtle.sign("HMAC",s,l)),o=[],a=0,c=await i(t);for(;a<r;){let l=await i(T(c,t));o.push(l),a+=l.length,c=await i(c)}return T(...o).subarray(0,r)}var Mt=(n,e,t,r,s)=>ri(n,e,T(ni(t),r),s),Je=class{sendRaw;onData;onError;inbound;transcript;established;serverPublicKey;suite;certificates;certificateRequested=!1;clientRandom=new Uint8Array(0);serverRandom=new Uint8Array(0);masterSecret=new Uint8Array(0);keys=null;readSequence;writeSequence;readEncrypted;writeEncrypted;queue;handshakeDone;resolveHandshake;rejectHandshake;constructor({send:e,onData:t,onError:r}){this.sendRaw=e,this.onData=t,this.onError=r,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((s,i)=>{this.resolveHandshake=s,this.rejectHandshake=i})}async start(){this.clientRandom=new Uint8Array(32),crypto.getRandomValues(this.clientRandom);let e=T(H(13),H(10),H(8),new Uint8Array([4,1,5,1,2,1,6,1]),H(65281),H(1),new Uint8Array([0])),t=T(H(Ue),this.clientRandom,new Uint8Array([0]),H(4),H(156),H(157),new Uint8Array([1,0]),H(e.length),e);return await this.#t($.CLIENT_HELLO,t),this.handshakeDone}#e(e,t){return T(new Uint8Array([e]),H(Ue),H(t.length),t)}async#t(e,t){let r=T(new Uint8Array([e]),Yn(t.length),t);this.transcript.push(r),await this.#n(le.HANDSHAKE,r)}async#n(e,t){if(!this.writeEncrypted){this.sendRaw(this.#e(e,t));return}this.sendRaw(this.#e(e,await this.#o(e,t)))}async#o(e,t){let r=this.writeSequence++,s=Dt(r),{clientIv:i,clientKey:o}=this.#c(),a=T(i,s),c=T(Dt(r),new Uint8Array([e]),H(Ue),H(t.length)),l=await crypto.subtle.encrypt({name:"AES-GCM",iv:a,additionalData:c,tagLength:128},o,t);return T(s,new Uint8Array(l))}async#r(e,t){let r=this.readSequence++,s=t.subarray(0,8),i=t.subarray(8),{serverIv:o,serverKey:a}=this.#c(),c=T(o,s),l=T(Dt(r),new Uint8Array([e]),H(Ue),H(i.length-16)),m=await crypto.subtle.decrypt({name:"AES-GCM",iv:c,additionalData:l,tagLength:128},a,i);return new Uint8Array(m)}async#s(e){let{hash:t,keyLength:r}=this.#a();this.masterSecret=await Mt(t,e,"master secret",T(this.clientRandom,this.serverRandom),48);let s=await Mt(t,this.masterSecret,"key expansion",T(this.serverRandom,this.clientRandom),r*2+8),i=new S(s),o=i.raw(r).slice(),a=i.raw(r).slice();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()}}#a(){if(!this.suite)throw new Error("TLS: a record was processed before ServerHello chose a cipher suite");return this.suite}#c(){if(!this.keys)throw new Error("TLS: a record was protected before the key block was derived");return this.keys}async#i(){let e=await crypto.subtle.digest(this.#a().hash,T(...this.transcript));return new Uint8Array(e)}async#l(e){return Mt(this.#a().hash,this.masterSecret,e,await this.#i(),12)}receive(e){return this.queue=this.queue.then(()=>this.#d(e)).catch(t=>this.#h(t)),this.queue}#h(e){let t=e instanceof Error?e:new Error(String(e));this.rejectHandshake(t),this.onError&&this.onError(t)}async#d(e){for(this.inbound=this.inbound.length===0?e:T(this.inbound,e);this.inbound.length>=5;){let t=this.inbound[0],r=this.inbound[3]<<8|this.inbound[4];if(this.inbound.length<5+r)return;let s=this.inbound.subarray(5,5+r);this.inbound=this.inbound.subarray(5+r).slice();let i=this.readEncrypted&&t!==le.CHANGE_CIPHER_SPEC?await this.#r(t,s):s;await this.#g(t,i)}}async#g(e,t){if(e===le.ALERT){let s=t[0],i=t[1],o=ti[i]||`alert ${i}`;if(o==="close_notify"){this.established=!1;return}throw new Error(`TLS: the host sent a fatal alert: ${o}${s===1?" (warning)":""}`)}if(e===le.CHANGE_CIPHER_SPEC){this.readEncrypted=!0,this.readSequence=0n;return}if(e===le.APPLICATION_DATA){this.onData&&t.length>0&&this.onData(t);return}if(e!==le.HANDSHAKE)return;let r=0;for(;r+4<=t.length;){let s=t[r],i=t[r+1]<<16|t[r+2]<<8|t[r+3],o=t.subarray(r,r+4+i),a=t.subarray(r+4,r+4+i);r+=4+i,s!==$.FINISHED&&this.transcript.push(o),await this.#u(s,a,o)}}async#u(e,t,r){switch(e){case $.SERVER_HELLO:{let s=new S(t),i=s.u16be();if(i!==Ue)throw new Error(`TLS: the host chose an unsupported version 0x${i.toString(16)}`);this.serverRandom=s.raw(32).slice(),s.raw(s.u8());let o=s.u16be();if(this.suite=ei[o]??null,!this.suite)throw new Error(`TLS: the host chose cipher suite 0x${o.toString(16)}, which this client does not implement`);s.u8();return}case $.CERTIFICATE:{let s=new S(t),i=s.u8()<<16|s.u16be(),o=s.offset+i;for(;s.offset<o;){let a=s.u8()<<16|s.u16be();this.certificates.push(s.raw(a).slice())}if(this.certificates.length===0)throw new Error("TLS: the host sent no certificate");this.serverPublicKey=Wn(this.certificates[0]);return}case $.CERTIFICATE_REQUEST:this.certificateRequested=!0;return;case $.SERVER_KEY_EXCHANGE:throw new Error("TLS: the host chose an ephemeral key exchange, which this client does not implement");case $.SERVER_HELLO_DONE:await this.#p();return;case $.NEW_SESSION_TICKET:return;case $.FINISHED:{let s=await this.#l("server finished"),i=t.subarray(0,12);if(!(s.length===i.length&&s.every((a,c)=>a===i[c])))throw new Error("TLS: the host Finished message did not verify");this.transcript.push(r),this.established=!0,this.resolveHandshake({cipherSuite:this.#a().name,certificates:this.certificates,publicKey:this.serverPublicKey});return}default:return}}async#p(){this.certificateRequested&&await this.#t($.CERTIFICATE,Yn(0));let e=new Uint8Array(48);if(crypto.getRandomValues(e),e[0]=3,e[1]=3,!this.serverPublicKey)throw new Error("TLS: the key exchange ran before the host sent a certificate");let t=Ln(e,this.serverPublicKey.modulus,this.serverPublicKey.exponent);await this.#t($.CLIENT_KEY_EXCHANGE,T(H(t.length),t)),await this.#s(e),await this.#n(le.CHANGE_CIPHER_SPEC,new Uint8Array([1])),this.writeEncrypted=!0,this.writeSequence=0n,await this.#t($.FINISHED,await this.#l("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.#n(le.APPLICATION_DATA,e)}).catch(t=>this.#h(t)),this.queue}};function si(n,e){return n<<e|n>>>32-e}function ii(n){let e=Math.floor((n.length+8)/64)+1,t=new Uint8Array(e*64);t.set(n),t[n.length]=128;let r=new DataView(t.buffer),s=n.length*8;r.setUint32(t.length-8,s>>>0,!0),r.setUint32(t.length-4,Math.floor(s/4294967296),!0);let i=1732584193,o=4023233417,a=2562383102,c=271733878,l=new Uint32Array(16),m=[3,7,11,19],E=[0,4,8,12,1,5,9,13,2,6,10,14,3,7,11,15],x=[3,5,9,13],p=[0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15],y=[3,9,11,15];for(let w=0;w<e;w++){for(let R=0;R<16;R++)l[R]=r.getUint32(w*64+R*4,!0);let v=i,u=o,d=a,b=c,C=(R,N)=>si(R|0,N);for(let R=0;R<16;R++){let N=u&d|~u&b,_=m[R%4],U=C(v+N+l[R]|0,_);v=b,b=d,d=u,u=U}for(let R=0;R<16;R++){let N=u&d|u&b|d&b,_=x[R%4],U=C(v+N+l[E[R]]+1518500249|0,_);v=b,b=d,d=u,u=U}for(let R=0;R<16;R++){let N=u^d^b,_=y[R%4],U=C(v+N+l[p[R]]+1859775393|0,_);v=b,b=d,d=u,u=U}i=i+v|0,o=o+u|0,a=a+d|0,c=c+b|0}let h=new Uint8Array(16),A=new DataView(h.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),h}function be(n,e){let r=n.length>64?ae(n):n,s=new Uint8Array(64);s.set(r);let i=new Uint8Array(64),o=new Uint8Array(64);for(let a=0;a<64;a++)i[a]=s[a]^54,o[a]=s[a]^92;return ae(T(o,ae(T(i,e))))}var Xn=new Uint8Array([78,84,76,77,83,83,80,0]),q={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},zn=q.UNICODE|q.REQUEST_TARGET|q.SIGN|q.SEAL|q.NTLM|q.ALWAYS_SIGN|q.EXTENDED_SESSION_SECURITY|q.TARGET_INFO|q.VERSION|q.KEY_128|q.KEY_EXCH|q.KEY_56,Qn=0,oi=7,$n=6,qn=2,Ht=n=>{let e=new f(n.length*2+2);return e.utf16le(n),e.take()},jn=new Uint8Array([10,0,99,69,0,0,0,15]);function Zn(){let n=new f(40);return n.raw(Xn),n.u32le(1),n.u32le(zn>>>0),n.u16le(0).u16le(0).u32le(0),n.u16le(0).u16le(0).u32le(0),n.raw(jn),n.take()}function Jn(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),r=e.getUint32(16,!0),s=e.getUint32(20,!0),i=n.subarray(24,32).slice(),o=e.getUint16(40,!0),a=e.getUint32(44,!0);return{flags:s,serverChallenge:i,targetName:n.subarray(r,r+t).slice(),targetInfo:n.subarray(a,a+o).slice()}}function ai(n){let e=[],t=0,r=new DataView(n.buffer,n.byteOffset,n.byteLength);for(;t+4<=n.length;){let s=r.getUint16(t,!0),i=r.getUint16(t+2,!0),o=n.subarray(t+4,t+4+i);if(t+=4+i,s===Qn)break;e.push({id:s,value:o})}return e}function ci(n){let e=new f(256);for(let t of n)e.u16le(t.id),e.u16le(t.value.length),e.raw(t.value);return e.u16le(Qn).u16le(0),e.take()}function li(){let n=(BigInt(Date.now())+11644473600000n)*10000n,e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,n,!0),e}function er({username:n,domain:e,password:t,challenge:r,negotiateBytes:s,challengeBytes:i}){let o=be(ii(Ht(t)),Ht(n.toUpperCase()+e)),a=ai(r.targetInfo),c=a.find(D=>D.id===oi)?.value.slice()||li(),l=a.find(D=>D.id===$n);if(l){let D=new DataView(l.value.buffer,l.value.byteOffset,4);D.setUint32(0,D.getUint32(0,!0)|qn,!0)}else{let D=new Uint8Array(4);new DataView(D.buffer).setUint32(0,qn,!0),a.push({id:$n,value:D})}let m=ci(a),E=new Uint8Array(8);crypto.getRandomValues(E);let x=T(new Uint8Array([1,1,0,0,0,0,0,0]),c,E,new Uint8Array(4),m,new Uint8Array(4)),p=be(o,T(r.serverChallenge,x)),y=T(p,x),h=be(o,p),A=new Uint8Array(16);crypto.getRandomValues(A);let w=j(ee(h),A),v=Bt(e),u=Bt(n),d=Bt(""),b=new Uint8Array(24),C=72,R=C,N=[],_=D=>(N.push({bytes:D,offset:R}),R+=D.length,N[N.length-1]),U=_(b),W=_(y),ye=_(v),de=_(u),Ie=_(d),pe=_(w),Y=new f(R+16);Y.raw(Xn),Y.u32le(3);let ge=D=>{Y.u16le(D.bytes.length),Y.u16le(D.bytes.length),Y.u32le(D.offset+16)};ge(U),ge(W),ge(ye),ge(de),ge(Ie),ge(pe),Y.u32le(zn>>>0),Y.raw(jn),Y.zeros(16);for(let D of N)Y.raw(D.bytes);let It=Y.take(),Is=be(A,T(s,i,It));return It.set(Is,C),{message:It,exportedSessionKey:A,keys:fi(A)}}function Bt(n){return n?Ht(n).subarray(0,n.length*2).slice():new Uint8Array(0)}var hi="session key to client-to-server signing key magic constant\0",ui="session key to server-to-client signing key magic constant\0",di="session key to client-to-server sealing key magic constant\0",pi="session key to server-to-client sealing key magic constant\0";function fi(n){let e=t=>ae(T(n,new TextEncoder().encode(t)));return{clientSigningKey:e(hi),serverSigningKey:e(ui),clientSealing:ee(e(di)),serverSealing:ee(e(pi))}}var et=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 r=be(this.keys.clientSigningKey,T(t,e)),s=j(this.keys.clientSealing,e),i=j(this.keys.clientSealing,r.subarray(0,8));return this.sendSequence+=1,T(new Uint8Array([1,0,0,0]),i,t,s)}unseal(e){if(e.length<16)throw new Error("NTLM: sealed message is too short");let t=e.subarray(16),r=j(this.keys.serverSealing,t),s=e.subarray(12,16),i=be(this.keys.serverSigningKey,T(s,r)),o=j(this.keys.serverSealing,i.subarray(0,8)),a=e.subarray(4,12);if(!o.every((c,l)=>c===a[l]))throw new Error("NTLM: the host signature did not verify");return this.receiveSequence+=1,r}};var Kt=6,mi="CredSSP Client-To-Server Binding Hash\0",yi="CredSSP Server-To-Client Binding Hash\0",gi={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 nt=(n,e)=>T(new Uint8Array([n]),Ei(e.length),e),Oe=(...n)=>nt(48,T(...n)),he=n=>nt(4,n),Z=(n,e)=>nt(160|n,e);function tr(n){let e=[],t=n;do e.unshift(t&255),t>>>=8;while(t>0);return e[0]&128&&e.unshift(0),nt(2,new Uint8Array(e))}function te(n,e){let t=n[e],r=e+1,s=n[r++];if(s&128){let i=s&127;s=0;for(let o=0;o<i;o++)s=s<<8|n[r++]}return{tag:t,content:n.subarray(r,r+s),end:r+s}}function wi(n,e=0){if(n.length-e<2)return 0;let t=e+1,r=n[t++];if(r&128){let i=r&127;if(n.length-t<i)return 0;r=0;for(let o=0;o<i;o++)r=r<<8|n[t++]}let s=t-e+r;return n.length-e<s?0:s}function Ft({version:n,negoToken:e,authInfo:t,pubKeyAuth:r,clientNonce:s}){let i=[Z(0,tr(n))];return e&&i.push(Z(1,Oe(Oe(Z(0,he(e)))))),t&&i.push(Z(2,he(t))),r&&i.push(Z(3,he(r))),s&&i.push(Z(5,he(s))),Oe(...i)}function Ai(n){let e=te(n,0),t={version:0,negoToken:null,authInfo:null,pubKeyAuth:null,errorCode:0},r=0;for(;r<e.content.length;){let s=te(e.content,r);r=s.end;let i=s.tag&31;if(i===0){t.version=te(s.content,0).content[0];continue}if(i===1){let o=te(s.content,0),a=te(o.content,0),c=te(a.content,0);t.negoToken=te(c.content,0).content;continue}if(i===2){t.authInfo=te(s.content,0).content;continue}if(i===3){t.pubKeyAuth=te(s.content,0).content;continue}if(i===4){let o=te(s.content,0).content,a=0;for(let c of o)a=(a<<8|c)>>>0;t.errorCode=a;continue}}return t}function bi(n,e,t){let r=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},s=Oe(Z(0,he(r(n))),Z(1,he(r(e))),Z(2,he(r(t))));return Oe(Z(0,tr(1)),Z(1,he(s)))}var tt=class{username;domain;password;serverPublicKey;send;log;inbound;waiters;constructor({username:e,domain:t,password:r,serverPublicKey:s,send:i,log:o}){this.username=e||"",this.domain=t||"",this.password=r||"",this.serverPublicKey=s,this.send=i,this.log=o||(()=>{}),this.inbound=new Uint8Array(0),this.waiters=[]}receive(e){for(this.inbound=this.inbound.length===0?e:T(this.inbound,e);;){let t=wi(this.inbound);if(t===0)return;let r=Ai(this.inbound.subarray(0,t));this.inbound=this.inbound.subarray(t).slice();let s=this.waiters.shift();s&&s.resolve(r)}}#e(e=15e3){return new Promise((t,r)=>{let s=setTimeout(()=>r(new Error("CredSSP: the host did not answer within 15s")),e);this.waiters.push({resolve:i=>{clearTimeout(s),t(i)}})})}async#t(e,t){let r=await crypto.subtle.digest("SHA-256",T(new TextEncoder().encode(e),t,this.serverPublicKey));return new Uint8Array(r)}async authenticate(){let e=Zn();this.send(Ft({version:Kt,negoToken:e})),this.log("CredSSP","sent NTLM NEGOTIATE");let t=await this.#e();if(t.errorCode)throw new Error(this.#o(t.errorCode));if(!t.negoToken)throw new Error("CredSSP: the host sent no NTLM challenge");let r=t.negoToken.slice(),s=Jn(r),i=new TextDecoder("utf-16le").decode(s.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}=er({username:this.username,domain:this.domain,password:this.password,challenge:s,negotiateBytes:e,challengeBytes:r}),c=new et(a),l=new Uint8Array(32);crypto.getRandomValues(l);let m=t.version<5,E=m?this.serverPublicKey:await this.#t(mi,l);this.send(Ft({version:Kt,negoToken:o,pubKeyAuth:c.seal(E),clientNonce:m?null:l})),this.log("CredSSP",`sent NTLM AUTHENTICATE with the ${m?"legacy":"hashed"} public-key binding`);let x=await this.#e();if(x.errorCode)throw new Error(this.#o(x.errorCode));if(!x.pubKeyAuth)throw new Error("CredSSP: the host returned no public-key confirmation");let p=c.unseal(x.pubKeyAuth),y=m?this.#n():await this.#t(yi,l);if(p.length!==y.length||!y.every((h,A)=>h===p[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(Ft({version:Kt,authInfo:c.seal(bi(this.domain,this.username,this.password))})),this.log("CredSSP","sent credentials"),{authenticated:!0,hostVersion:t.version,targetName:i}}#n(){let e=this.serverPublicKey.slice();return e[0]=e[0]+1&255,e}#o(e){return gi[e]||`CredSSP: the host reported error 0x${e.toString(16).padStart(8,"0")}.`}};var Se=1001;var ue={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},Si={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 xi(n){return n>255?new Uint8Array([130,n>>8&255,n&255]):n>127?new Uint8Array([129,n]):new Uint8Array([n])}function Pe(n,e){return T(new Uint8Array(n),xi(e.length),e)}function Ti(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]),Pe([2],e)}var Gt=n=>Pe([4],n),vi=n=>Pe([1],new Uint8Array([n?255:0]));function Wt(n){return Pe([48],T(...n.map(Ti)))}function Vt(n,e){return e>127?n.u16be(32768|e):n.u8(e),n}function nr(n){let e=n.u8();return e&128?(e&127)<<8|n.u8():e}var Ri=new Uint8Array([5,0,20,124,0,1]),Ci=new Uint8Array([68,117,99,97]),rt=new Uint8Array([77,99,68,110]);function _i(n){let e=new f(n.length+32);return e.u8(0),e.raw(Ri),Vt(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(Ci),Vt(e,n.length),e.raw(n),e.take()}function Li(n){for(let e=0;e+4<=n.length;e++)if(n[e]===rt[0]&&n[e+1]===rt[1]&&n[e+2]===rt[2]&&n[e+3]===rt[3]){let t=new S(n,e+4),r=nr(t),s=t.rest();return s.subarray(0,Math.min(r,s.length))}throw new Error("RDP: the host response contained no GCC server data")}var Ii=[34,2,0,1,0,1,65535,2],Ni=[1,1,1,1,0,1,1056,2],Ui=[65535,64535,65535,1,0,1,65535,2];function rr(n){let e=_i(n),t=T(Gt(new Uint8Array([1])),Gt(new Uint8Array([1])),vi(!0),Wt(Ii),Wt(Ni),Wt(Ui),Gt(e));return we(Pe([127,101],t))}function ke(n){let e=n.u8();(e&31)===31&&(e=e<<8|n.u8());let t=n.u8();if(t&128){let r=t&127;t=0;for(let s=0;s<r;s++)t=t<<8|n.u8()}return{tag:e,value:n.raw(t)}}function sr(n){let e=new S(Ne(n)),t=ke(e);if(t.tag!==32614)throw new Error(`RDP: expected an MCS connect response, got BER tag 0x${t.tag.toString(16)}`);let r=new S(t.value),s=ke(r);ke(r),ke(r);let i=ke(r);if(s.value[0]!==0)throw new Error(`RDP: the host rejected the MCS connection (result ${s.value[0]})`);return Li(i.value)}var st=n=>n<<2;function ir(){let n=new f(8);return n.u8(st(ue.ERECT_DOMAIN_REQUEST)),n.u8(1).u8(0),n.u8(1).u8(0),we(n.take())}function or(){return we(new Uint8Array([st(ue.ATTACH_USER_REQUEST)]))}function ar(n){let e=new S(Ne(n)),t=e.u8();if(t>>2!==ue.ATTACH_USER_CONFIRM)throw new Error(`RDP: expected an MCS attach-user confirm, got PDU ${t>>2}`);let r=e.u8();if(r!==0)throw new Error(`RDP: the host refused to attach a user (result ${r})`);return{userId:t&2?e.u16be()+Se:Se}}function Yt(n,e){let t=new f(8);return t.u8(st(ue.CHANNEL_JOIN_REQUEST)),t.u16be(n-Se),t.u16be(e),we(t.take())}function cr(n){let e=new S(Ne(n)),t=e.u8();if(t>>2!==ue.CHANNEL_JOIN_CONFIRM)throw new Error(`RDP: expected an MCS channel-join confirm, got PDU ${t>>2}`);let r=e.u8();e.u16be();let s=e.u16be();if(r!==0)throw new Error(`RDP: the host refused to join channel ${s} (result ${r})`);return{channelId:(e.remaining>=2?e.u16be():s)||s}}function $t(n,e,t){let r=new f(t.length+16);return r.u8(st(ue.SEND_DATA_REQUEST)),r.u16be(n-Se),r.u16be(e),r.u8(112),Vt(r,t.length),r.raw(t),we(r.take())}function lr(n){let e=new S(Ne(n)),t=e.u8(),r=t>>2;if(r===ue.SEND_DATA_INDICATION){e.u16be();let s=e.u16be();e.u8();let i=nr(e),o=e.rest();return{type:"send-data",channelId:s,payload:o.subarray(0,Math.min(i,o.length))}}if(r===ue.DISCONNECT_PROVIDER_ULTIMATUM){let s=(t&1)<<1|(e.remaining>0?e.u8()>>7:0);return{type:"disconnect",reason:s,message:Si[s]||`The host closed the RDP session (reason ${s}).`}}return{type:"other",mcsPduType:r}}var Oi=49153,ki=49154,Pi=49155,Di=49156,Mi=3073,Bi=3074,Hi=3075,Ki=524292,hr=51715,Fi=43523,Gi=1,it={NONE:0,LOW:1,CLIENT_COMPATIBLE:2,HIGH:3,FIPS:4};function ot(n,e){let t=new f(e.length+4);return t.u16le(n).u16le(e.length+4).raw(e),t.take()}function Wi({width:n,height:e,clientName:t,keyboardLayout:r,selectedProtocol:s}){let i=new f(256);return i.u32le(Ki),i.u16le(n),i.u16le(e),i.u16le(hr),i.u16le(Fi),i.u32le(r),i.u32le(2600),i.utf16le(t,32),i.u32le(4),i.u32le(0),i.u32le(12),i.zeros(64),i.u16le(hr),i.u16le(1),i.u32le(0),i.u16le(16),i.u16le(7),i.u16le(Gi),i.zeros(64),i.u8(0),i.u8(0),i.u32le(s),ot(Oi,i.take())}function Vi(n){let e=new f(8);return e.u32le(n),e.u32le(0),ot(ki,e.take())}function Yi(){let n=new f(8);return n.u32le(13),n.u32le(0),ot(Di,n.take())}function $i(n){if(n.length===0)return new Uint8Array(0);let e=new f(4+n.length*12);e.u32le(n.length);for(let t of n){let r=new Uint8Array(8);for(let s=0;s<Math.min(7,t.name.length);s++)r[s]=t.name.charCodeAt(s);e.raw(r),e.u32le(t.options>>>0)}return ot(Pi,e.take())}function ur(n){return T(Wi(n),Yi(),Vi(n.encryptionMethods),$i(n.channels||[]))}function dr(n){let e=new S(n),t={version:null,encryptionMethod:0,encryptionLevel:it.NONE,serverRandom:null,publicKey:null,ioChannelId:1003,channelIds:[]};for(;e.remaining>=4;){let r=e.u16le(),s=e.u16le();if(s<4||s-4>e.remaining)break;let i=new S(e.raw(s-4));if(r===Mi){t.version=i.remaining>=4?i.u32le():null;continue}if(r===Hi){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(r===Bi){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=Vn(i.raw(a));continue}}return t}var V={MONITOR_READY:1,FORMAT_LIST:2,FORMAT_LIST_RESPONSE:3,FORMAT_DATA_REQUEST:4,FORMAT_DATA_RESPONSE:5,CLIP_CAPS:7},pr=1,qt=2,qi=4,De=1,xe=13,fr=1,Xi=2,mr=2,at=32,zi=400;function Qi(n,e,t=new Uint8Array(0)){let r=new f(t.length+8);return r.u16le(n).u16le(e).u32le(t.length).raw(t),r.take()}function ji(n){let e=new f(n.length*2+2);return e.utf16le(n),e.u16le(0),e.take()}function Zi(n){let e=new Uint16Array(n.length>>1);for(let s=0;s<e.length;s++)e[s]=n[s*2]|n[s*2+1]<<8;let t=e.indexOf(0);t===-1&&(t=e.length);let r="";for(let s=0;s<t;s+=4096)r+=String.fromCharCode(...e.subarray(s,Math.min(s+4096,t)));return r}function Ji(n){let e=new f(n.length+1);for(let t of n){let r=t.codePointAt(0)??63;e.u8(r>255?63:r)}return e.u8(0),e.take()}function eo(n){let e=n.indexOf(0);return e===-1&&(e=n.length),String.fromCharCode(...n.subarray(0,e))}var ct=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,r=new Uint8Array(0)){this.send(Qi(e,t,r))}setLocalText(e){return this.localText=e,this.ready?(this.#e(V.FORMAT_LIST,0,this.#t(e?[xe,De]:[])),this.pendingAck&&this.pendingAck.resolve(!1),new Promise(t=>{let r,s=i=>{clearTimeout(r),this.pendingAck?.resolve===s&&(this.pendingAck=null),t(i)};r=setTimeout(()=>{this.log("clipboard format list was not acknowledged"),s(!1)},zi),this.pendingAck={resolve:s}})):Promise.resolve(!1)}#t(e){let t=e.map(r=>{let s=new f(this.longFormatNames?6:4+at);return s.u32le(r),this.longFormatNames?s.u16le(0):s.zeros(at),s.take()});return T(...t)}receive(e){if(e.length<8)return;let t=new S(e),r=t.u16le(),s=t.u16le(),i=t.u32le(),o=t.rest(),a=o.subarray(0,Math.min(i,o.length));switch(r){case V.CLIP_CAPS:this.#n(a);return;case V.MONITOR_READY:this.#o();return;case V.FORMAT_LIST:this.#r(a,s);return;case V.FORMAT_LIST_RESPONSE:this.pendingAck?.resolve((s&qt)===0);return;case V.FORMAT_DATA_REQUEST:this.#a(a);return;case V.FORMAT_DATA_RESPONSE:this.#c(a,s);return;default:return}}#n(e){let t=new S(e);if(t.remaining<4)return;let r=t.u16le();t.u16le();for(let s=0;s<r&&t.remaining>=4;s++){let i=t.u16le(),o=t.u16le();if(o<4||o-4>t.remaining)break;let a=new S(t.raw(o-4));if(i===fr&&a.remaining>=8){a.u32le();let c=a.u32le();this.longFormatNames=(c&mr)!==0}}}#o(){let e=new f(12);e.u16le(fr).u16le(12),e.u32le(Xi),e.u32le(this.longFormatNames?mr:0);let t=new f(20);t.u16le(1).u16le(0),t.raw(e.take()),this.#e(V.CLIP_CAPS,0,t.take()),this.ready=!0,this.#e(V.FORMAT_LIST,0,this.#t(this.localText?[xe,De]:[])),this.log("clipboard channel ready",{longFormatNames:this.longFormatNames})}#r(e,t){let r=this.#s(e,t);this.#e(V.FORMAT_LIST_RESPONSE,pr);let s=r.includes(xe)?xe:r.includes(De)?De:null;if(s===null){this.log("host clipboard holds no text format",{formats:r});return}let i=new f(4);i.u32le(s),this.#e(V.FORMAT_DATA_REQUEST,0,i.take())}#s(e,t){let r=new S(e),s=[],i=!this.longFormatNames||(t&qi)!==0;for(;r.remaining>=4;){if(s.push(r.u32le()),i){if(r.remaining<at)break;r.skip(at);continue}for(;r.remaining>=2&&r.u16le()!==0;);}return s}#a(e){let t=new S(e),r=t.remaining>=4?t.u32le():0;if(r!==xe&&r!==De){this.#e(V.FORMAT_DATA_RESPONSE,qt);return}let s=r===xe?ji(this.localText):Ji(this.localText);this.#e(V.FORMAT_DATA_RESPONSE,pr,s),this.log("handed the host our clipboard",{formatId:r,characters:this.localText.length})}#c(e,t){if(t&qt){this.log("the host refused to hand over its clipboard");return}let s=e.length>=2&&e.length%2===0&&e[1]===0?Zi(e):eo(e);s&&this.dispatchEvent(new CustomEvent("text",{detail:{text:s}}))}};var X={CLOSE:1,WAVE:2,SET_VOLUME:3,SET_PITCH:4,WAVE_CONFIRM:5,TRAINING:6,FORMATS:7,CRYPT_KEY:8,WAVE_ENCRYPT:9,UDP_WAVE:10,UDP_WAVE_LAST:11,QUALITY_MODE:12,WAVE2:13},to=1,no=1,ro=2,so=2147450879,io=6,oo=2,ao=6,Xt=4,co=8,yr=12;function lo(n){return n.formatTag===to&&(n.bitsPerSample===8||n.bitsPerSample===16)&&n.channels>=1&&n.channels<=2&&n.samplesPerSec>=8e3&&n.samplesPerSec<=96e3}function lt(n,e){let t=new f(e.length+4);return t.u8(n).u8(0).u16le(e.length).raw(e),t.take()}function ho(n){if(n.remaining<18)return null;let e={formatTag:n.u16le(),channels:n.u16le(),samplesPerSec:n.u32le(),avgBytesPerSec:n.u32le(),blockAlign:n.u16le(),bitsPerSample:n.u16le(),extra:new Uint8Array(0)},t=n.u16le();return t>n.remaining?null:(e.extra=n.raw(t).slice(),e)}function uo(n){let e=new f(18+n.extra.length);return e.u16le(n.formatTag),e.u16le(n.channels),e.u32le(n.samplesPerSec),e.u32le(n.avgBytesPerSec),e.u16le(n.blockAlign),e.u16le(n.bitsPerSample),e.u16le(n.extra.length),e.raw(n.extra),e.take()}function po(n){return n.blockAlign||Math.max(1,(n.bitsPerSample>>3)*n.channels)}var ht=class extends EventTarget{send;log;formats=[];serverVersion=0;ready=!1;#e=null;constructor({send:e,log:t}){super(),this.send=e,this.log=t??(()=>{})}receive(e){if(this.#e){this.#s(e);return}if(e.length<4)return;let t=new S(e),r=t.u8();t.u8();let s=t.u16le(),i=t.rest(),o=i.subarray(0,Math.min(s,i.length));switch(r){case X.FORMATS:this.#t(o);return;case X.TRAINING:this.#o(o);return;case X.WAVE:this.#r(o,s);return;case X.WAVE2:this.#a(o,s);return;case X.CLOSE:this.log("the host closed the audio stream"),this.dispatchEvent(new CustomEvent("close"));return;case X.SET_VOLUME:case X.SET_PITCH:return;case X.CRYPT_KEY:return;default:this.log("unhandled audio PDU",{msgType:r,bodySize:s});return}}#t(e){if(e.length<20)return;let t=new S(e);t.u32le(),t.u32le(),t.u32le(),t.u16le();let r=t.u16le();t.u8(),this.serverVersion=t.u16le(),t.u8();let s=[];for(let i=0;i<r;i++){let o=ho(t);if(!o)break;s.push(o)}this.formats=s.filter(lo),this.log("audio formats offered by the host",{offered:s.length,accepted:this.formats.length,version:this.serverVersion}),this.#n(),this.ready=this.formats.length>0,this.serverVersion>=ao&&this.send(lt(X.QUALITY_MODE,new f(4).u16le(oo).u16le(0).take())),this.ready&&this.dispatchEvent(new CustomEvent("ready",{detail:{formats:this.formats.slice(),version:this.serverVersion}}))}#n(){let e=new f(20);e.u32le(no|ro),e.u32le(so),e.u32le(0),e.u16le(0),e.u16le(this.formats.length),e.u8(0),e.u16le(io),e.u8(0),this.send(lt(X.FORMATS,T(e.take(),...this.formats.map(uo))))}#o(e){if(e.length<4)return;let t=new S(e),r=t.u16le(),s=t.u16le();this.send(lt(X.TRAINING,new f(4).u16le(r).u16le(s).take()))}#r(e,t){if(e.length<12)return;let r=new S(e),s=r.u16le(),i=r.u16le(),o=r.u8();r.skip(3);let a=r.raw(Xt).slice(),c=Math.max(0,t-co),l=this.formats[i];if(!l){this.log("the host chose an audio format that was never offered",{formatNo:i}),this.#c(s,o);return}this.#e={format:l,timestamp:s,blockNo:o,prefix:a,remaining:Math.max(0,c-Xt)},this.#e.remaining===0&&this.#s(new Uint8Array(0),!0)}#s(e,t=!1){let r=this.#e;if(this.#e=null,!r)return;let s=t?e:e.subarray(Xt),i=T(r.prefix,s.subarray(0,r.remaining));this.#i(r.format,i,r.timestamp),this.#c(r.timestamp,r.blockNo)}#a(e,t){if(e.length<yr)return;let r=new S(e),s=r.u16le(),i=r.u16le(),o=r.u8();r.skip(3),r.u32le();let a=Math.max(0,t-yr),c=r.rest().subarray(0,a),l=this.formats[i];l?this.#i(l,c.slice(),s):this.log("the host chose an audio format that was never offered",{formatNo:i}),this.#c(s,o)}#c(e,t){this.send(lt(X.WAVE_CONFIRM,new f(4).u16le(e).u8(t).u8(0).take()))}#i(e,t,r){if(!t.length)return;let s=po(e),i=t.length-t.length%s;i<=0||this.dispatchEvent(new CustomEvent("audio",{detail:{format:e,samples:t.subarray(0,i),timestamp:r}}))}};var Er=17522,fo=18798,gr=17219,mo=17230,yo=21328,go=17232,Eo=21836,wo=17473;function ut(n){return new f().u16le(Er).u16le(n)}var dt=class{constructor(e){this.send=e}send;minor=13;receive(e){if(e.length<4)return;let t=new S(e);if(t.u16le()!==Er)return;let r=t.u16le();if(console.info("[RDP] device initialization",{id:r,bytes:e.length}),r===fo){if(t.remaining<8||t.u16le()!==1)return;let s=t.u16le();if(![2,5,10,12,13].includes(s))return;this.minor=s;let i=t.u32le();this.send(ut(gr).u16le(1).u16le(s).u32le(i).take());let o=new f().utf16le("ai-remote").u16le(0).take();this.send(ut(mo).u32le(1).u32le(0).u32le(o.length).raw(o).take())}else if(r===yo){if(t.remaining<4)return;let s=t.u16le();t.skip(2);for(let i=0;i<s;i++){if(t.remaining<8)return;t.u16le();let o=t.u16le();if(o<8||o-4>t.remaining)return;t.skip(o-4)}this.send(ut(go).u16le(1).u16le(0).u16le(1).u16le(44).u32le(2).u32le(0).u32le(0).u16le(1).u16le(this.minor).u32le(0).u32le(0).u32le(4).u32le(0).u32le(0).u32le(0).take())}else(r===Eo||r===gr&&this.minor<12&&t.remaining>=8)&&this.send(ut(wo).u32le(0).take())}};var z={EXEC:1,ACTIVATE:2,SYSPARAM:3,SYSCOMMAND:4,HANDSHAKE:5,WINDOW_MOVE:8,CLIENT_STATUS:11,EXEC_RESULT:128,HANDSHAKE_EX:19},Ao={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."},Ar={MINIMIZE:61472,MAXIMIZE:61488,CLOSE:61536,RESTORE:61728},ve={HIDDEN:0,MINIMIZED:2,MAXIMIZED:3,NORMAL:5},Me={TYPE_WINDOW:16777216,STATE_NEW:268435456,STATE_DELETED:536870912,ICON:1073741824,CACHED_ICON:2147483648},F={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},bo=1073741824,So=128,xo=134217728,To=3,vo=2,Ro=11,br=2600,Co=1024,Te={MOUSE_BUTTON_SWAP:33,DRAG_FULL_WINDOWS:37,WORK_AREA:47,HIGH_CONTRAST:67,KEYBOARD_PREF:69,KEYBOARD_CUES:4107};function zt(n){let e=new f(n.length*2);return e.utf16le(n),e.take()}function ce(n,e){let t=new f(e.length+4);return t.u16le(n).u16le(e.length+4).raw(e),t.take()}function ne(n){return n|0}function _o(n=br){return ce(z.HANDSHAKE,new f(4).u32le(n).take())}function Lo(n=Co){return ce(z.CLIENT_STATUS,new f(4).u32le(n).take())}function pt(n,e){return ce(z.SYSPARAM,new f(5).u32le(n).u8(e?1:0).take())}function Io(){let n=new f(16);return n.u32le(Te.HIGH_CONTRAST),n.u32le(126),n.u32le(2),n.u16le(0).u16le(0),ce(z.SYSPARAM,n.take())}function Sr(n,e){let t=new f(12);return t.u32le(Te.WORK_AREA),t.u16le(0).u16le(0).u16le(n).u16le(e),ce(z.SYSPARAM,t.take())}function No(n,e){return[Io(),pt(Te.MOUSE_BUTTON_SWAP,!1),pt(Te.KEYBOARD_PREF,!1),pt(Te.DRAG_FULL_WINDOWS,!0),pt(Te.KEYBOARD_CUES,!1),Sr(n,e)]}function Uo(n,e=!0){let t=new f(5);return t.u32le(n).u8(e?1:0),ce(z.ACTIVATE,t.take())}function Oo(n,e){let t=new f(6);return t.u32le(n).u16le(e),ce(z.SYSCOMMAND,t.take())}function ko(n,{left:e,top:t,right:r,bottom:s}){let i=new f(12);return i.u32le(n),i.u16le(e&65535).u16le(t&65535),i.u16le(r&65535).u16le(s&65535),ce(z.WINDOW_MOVE,i.take())}function Po({program:n,workingDir:e="",arguments:t=""}){let r=zt(n||""),s=zt(e||""),i=zt(t||"");if(r.length===0||r.length>520)throw new Error("RemoteApp program must be between 1 and 260 Unicode characters.");if(s.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 f(8+r.length+s.length+i.length);return o.u16le(0),o.u16le(r.length).u16le(s.length).u16le(i.length),o.raw(r).raw(s).raw(i),ce(z.EXEC,o.take())}function xr(n){let e="";for(let t=0;t+1<n.length;t+=2){let r=n[t]|n[t+1]<<8;if(r===0)break;e+=String.fromCharCode(r)}return e}function wr(n,e){let t=[];for(let r=0;r<e&&n.remaining>=8;r++){let s=n.u16le(),i=n.u16le(),o=n.u16le(),a=n.u16le();t.push({left:s,top:i,right:o,bottom:a})}return t}function Do(n,e){let t={};if(e&F.OWNER&&(t.ownerWindowId=n.u32le()),e&F.STYLE&&(t.style=n.u32le(),t.extendedStyle=n.u32le()),e&F.SHOW&&(t.showState=n.u8()),e&F.TITLE){let r=n.u16le();t.title=xr(n.raw(Math.min(r,n.remaining)))}return e&F.CLIENT_AREA_OFFSET&&(t.clientOffsetX=ne(n.u32le()),t.clientOffsetY=ne(n.u32le())),e&F.CLIENT_AREA_SIZE&&(t.clientWidth=ne(n.u32le()),t.clientHeight=ne(n.u32le())),e&F.RP_CONTENT&&n.u8(),e&F.ROOT_PARENT&&n.u32le(),e&F.WND_OFFSET&&(t.x=ne(n.u32le()),t.y=ne(n.u32le())),e&F.CLIENT_DELTA&&(n.u32le(),n.u32le()),e&F.WND_SIZE&&(t.width=ne(n.u32le()),t.height=ne(n.u32le())),e&F.WND_RECTS&&(t.windowRects=wr(n,n.u16le())),e&F.VIS_OFFSET&&(t.visibleOffsetX=ne(n.u32le()),t.visibleOffsetY=ne(n.u32le())),e&F.VISIBILITY&&(t.visibilityRects=wr(n,n.u16le())),t}function Tr(n){return!(!n||n.ownerWindowId||(n.style||0)&bo||(n.extendedStyle||0)&(So|xo))}function vr(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 r=0;r<e&&n.remaining>0;r++){let s=n.offset,i=n.u8(),o=i&To,a=i>>2;if(o!==vo||a!==Ro)break;if(n.remaining<6)throw new Error("RDP RemoteApp window-order header is truncated.");let c=n.u16le(),l=n.u32le(),m=s+c;if(c<7||m>n.offset+n.remaining)throw new Error("RDP RemoteApp window order has an invalid size.");let E=!!(l&Me.TYPE_WINDOW),x=!!(l&(Me.ICON|Me.CACHED_ICON));if(E&&!x&&m-n.offset>=4){let p=n.u32le(),y={};try{y=Do(n,l)}catch(A){console.warn("[RDP] Dropped an unreadable RemoteApp window order",{windowId:p,fieldFlags:`0x${(l>>>0).toString(16)}`,error:A instanceof Error?A.message:String(A)})}let h="update";l&Me.STATE_DELETED?h="deleted":l&Me.STATE_NEW&&(h="new"),t.push({type:h,windowId:p,fieldFlags:l,...y})}if(n.offset=m,n.offset<=s)break}return t}function Mo(n){let e=new S(n),t=[];for(;e.remaining>=4;){let r=e.u16le(),s=e.u16le();if(s<4||s-4>e.remaining)throw new Error("RDP RemoteApp channel delivered a malformed PDU.");let i=new S(e.raw(s-4));if(r===z.HANDSHAKE&&i.remaining>=4){t.push({type:"handshake",buildNumber:i.u32le()});continue}if(r===z.HANDSHAKE_EX&&i.remaining>=8){t.push({type:"handshake",buildNumber:i.u32le(),flags:i.u32le(),extended:!0});continue}if(r===z.EXEC_RESULT&&i.remaining>=12){let o=i.u16le(),a=i.u16le(),c=i.u32le();i.u16le();let l=i.u16le(),m=xr(i.raw(Math.min(l,i.remaining)));t.push({type:"execute-result",flags:o,result:a,rawResult:c,program:m});continue}t.push({type:"unknown",orderType:r,body:i.rest().slice()})}return t}var ft=class{application;width;height;send;onReady;onResult;started;constructor({application:e,width:t,height:r,send:s,onReady:i,onResult:o}){this.application=e,this.width=t,this.height=r,this.send=s,this.onReady=i,this.onResult=o,this.started=!1}receive(e){for(let t of Mo(e)){if(t.type==="handshake"){if(this.started)continue;this.started=!0,this.send(_o(br)),this.send(Lo());for(let r of No(this.width,this.height))this.send(r);this.send(Po(this.application)),this.onReady?.(t);continue}t.type==="execute-result"&&this.onResult?.({...t,ok:t.result===0,message:Ao[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(Sr(e,t)),!0)}activate(e){return this.started?(this.send(Uo(e,!0)),!0):!1}sysCommand(e,t){return this.started?(this.send(Oo(e,t)),!0):!1}moveWindow(e,t){return this.started?(this.send(ko(e,t)),!0):!1}};var Q={INITIALIZED:2147483648,ENCRYPT_RDP:1073741824,COMPRESS_RDP:8388608,SHOW_PROTOCOL:2097152},Rr=1,Cr=2,_r=16,Qt=1600;function Lr(n,e=Qt,t=0){let r=[];for(let s=0;s<n.length||s===0;s+=e){let i=n.subarray(s,s+e),o=t;s===0&&(o|=Rr),s+e>=n.length&&(o|=Cr);let a=new f(i.length+8);if(a.u32le(n.length).u32le(o).raw(i),r.push(a.take()),n.length===0)break}return r}var mt=class{parts;expectedLength;constructor(){this.parts=[],this.expectedLength=0}push(e){if(e.length<8)return null;let t=new S(e),r=t.u32le(),s=t.u32le(),i=t.rest();if(s&Rr&&(this.parts=[],this.expectedLength=r),this.parts.push(i.slice()),!((s&Cr)!==0))return null;let a=T(...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},jt=4096,Be=class{encryptionMethod;encryptionLevel;keys;encryptState;decryptState;encryptedPdus;decryptedPdus;constructor(){this.encryptionMethod=oe.NONE,this.encryptionLevel=it.NONE,this.keys=null,this.encryptState=null,this.decryptState=null,this.encryptedPdus=0,this.decryptedPdus=0}get headerPresent(){return this.encryptionLevel!==it.NONE||this.encryptionMethod!==oe.NONE}get keyLength(){return this.keys?.keyLength??0}get encryptionEnabled(){return this.encryptionMethod!==oe.NONE&&this.keys!==null}configure(e,t,r,s){if(this.encryptionMethod=e,this.encryptionLevel=t,e!==oe.NONE){if(e&oe.FIPS)throw new Error("RDP: this host requires FIPS encryption, which this client does not implement");this.keys=On(r,s,e),this.encryptState=ee(this.keys.encryptKey),this.decryptState=ee(this.keys.decryptKey)}}#e(){if(!this.keys||!this.encryptState||!this.decryptState)throw new Error("RDP: the security layer was used before its session keys were derived");return{keys:this.keys,encryptState:this.encryptState,decryptState:this.decryptState}}#t(){let{keys:e}=this.#e();e.encryptKey=kt(e.initialEncryptKey,e.encryptKey,e.keyLength,e.is40Bit),this.encryptState=ee(e.encryptKey),this.encryptedPdus=0}#n(){let{keys:e}=this.#e();e.decryptKey=kt(e.initialDecryptKey,e.decryptKey,e.keyLength,e.is40Bit),this.decryptState=ee(e.decryptKey),this.decryptedPdus=0}wrap(e,t=0){let r=this.encryptionEnabled;if(!r&&t===0&&!this.headerPresent)return e;let s=new f(e.length+16);if(s.u16le(t|(r?G.ENCRYPT:0)),s.u16le(0),!r)return s.raw(e),s.take();let{keys:i,encryptState:o}=this.#e();return s.raw(kn(i.macKey,e)),s.raw(j(o,e)),++this.encryptedPdus===jt&&this.#t(),s.take()}unwrap(e,t=!1){if(!this.headerPresent&&!t)return{flags:0,payload:e};if(e.length<4)return{flags:0,payload:e};let r=new S(e),s=r.u16le();if(r.u16le(),!(s&G.ENCRYPT))return{flags:s,payload:r.rest()};if(!this.encryptionEnabled)throw new Error("RDP: the host encrypted a PDU before the session keys existed");r.skip(8);let i=j(this.#e().decryptState,r.rest());return++this.decryptedPdus===jt&&this.#n(),{flags:s,payload:i}}decryptFastPath(e){if(!this.encryptionEnabled||e.length<=8)return e;let t=j(this.#e().decryptState,e.subarray(8));return++this.decryptedPdus===jt&&this.#n(),t}static securityExchange(e){let t=new f(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},Bo=1,Ho=4,Ko=16,Fo=1,Go=4,Wo=2,Vo=8;function K(n,e){let t=new f(e.length+4);return t.u16le(n).u16le(e.length+4).raw(e),t.take()}function Yo(){let n=new f(24);return n.u16le(1),n.u16le(3),n.u16le(512),n.u16le(0),n.u16le(0),n.u16le(Fo|Go),n.u16le(0),n.u16le(0),n.u16le(0),n.u8(1),n.u8(1),K(k.GENERAL,n.take())}function $o(n,e){let t=new f(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),K(k.BITMAP,t.take())}function qo(){let n=new f(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(Wo|Vo),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),K(k.ORDER,n.take())}function Xo(){let n=new f(40);return n.zeros(24),n.u16le(0).u16le(0),n.u16le(0).u16le(0),n.u16le(0).u16le(0),K(k.BITMAPCACHE,n.take())}function zo(){let n=new f(12);return n.u16le(0),n.u16le(0),n.u16le(2),n.u16le(2),K(k.CONTROL,n.take())}function Qo(){let n=new f(12);return n.u16le(0).u16le(0).u16le(0).u16le(0),K(k.ACTIVATION,n.take())}function jo(){let n=new f(10);return n.u16le(1),n.u16le(20),n.u16le(20),K(k.POINTER,n.take())}function Zo(){let n=new f(8);return n.u16le(0).u16le(0),K(k.SHARE,n.take())}function Jo(){let n=new f(8);return n.u16le(6).u16le(0),K(k.COLORCACHE,n.take())}function ea(){let n=new f(8);return n.u16le(0).u16le(0),K(k.SOUND,n.take())}function ta(n){let e=new f(88);return e.u16le(Bo|Ho|Ko),e.u16le(0),e.u32le(n),e.u32le(4),e.u32le(0),e.u32le(12),e.zeros(64),K(k.INPUT,e.take())}function na(){let n=new f(8);return n.u16le(1).u16le(0),K(k.FONT,n.take())}function ra(){let n=new f(8);return n.u32le(0),K(k.BRUSH,n.take())}function sa(){let n=new f(52);for(let e=0;e<10;e++)n.u16le(0).u16le(0);return n.u32le(0),n.u16le(0),n.u16le(0),K(k.GLYPHCACHE,n.take())}function ia(){let n=new f(12);return n.u32le(0),n.u16le(0),n.u16le(0),K(k.OFFSCREENCACHE,n.take())}function oa(){let n=new f(4);return n.u32le(1),K(k.RAIL,n.take())}function aa(n=0,e=0){let t=new f(7);return t.u32le(1),t.u8(n),t.u16le(e),K(k.WINDOW,t.take())}function Ir({width:n,height:e,keyboardLayout:t,remoteApp:r=!1,remoteAppCaps:s=null}){let i=[Yo(),$o(n,e),qo(),Xo(),Jo(),Qo(),zo(),jo(),Zo(),ta(t),ra(),sa(),ea(),na(),ia()];return r&&(i.push(oa()),i.push(aa(s?.numIconCaches||0,s?.numIconCacheEntries||0))),{bytes:T(...i),count:i.length}}function Nr(n){let e=new S(n),t=e.u16le();e.u16le();let r={desktopWidth:0,desktopHeight:0,preferredBitsPerPixel:16,refreshRectSupport:!1,railSupportLevel:0,windowSupportLevel:0,numIconCaches:0,numIconCacheEntries:0,types:[]};for(let s=0;s<t&&e.remaining>=4;s++){let i=e.u16le(),o=e.u16le();if(o<4||o-4>e.remaining)break;let a=new S(e.raw(o-4));if(r.types.push(i),i===k.BITMAP&&a.remaining>=20){r.preferredBitsPerPixel=a.u16le(),a.skip(6),r.desktopWidth=a.u16le(),r.desktopHeight=a.u16le();continue}if(i===k.GENERAL&&a.remaining>=20){a.skip(18),r.refreshRectSupport=a.u8()!==0;continue}if(i===k.RAIL&&a.remaining>=4){r.railSupportLevel=a.u32le();continue}if(i===k.WINDOW&&a.remaining>=7){r.windowSupportLevel=a.u32le(),r.numIconCaches=a.u8(),r.numIconCacheEntries=a.u16le();continue}}return r}var me={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},yt={ORDERS:0,BITMAP:1,PALETTE:2,SYNCHRONIZE:3},Zt={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},re={WHEEL:512,HWHEEL:1024,WHEEL_NEGATIVE:256,MOVE:2048,DOWN:32768,BUTTON1:4096,BUTTON2:8192,BUTTON3:16384};function Or(n,e=!1){let t=e?Math.sign(n):-Math.sign(n);if(t===0)return 0;let r=e?re.HWHEEL:re.WHEEL,s=120;return t>0?r|s:r|re.WHEEL_NEGATIVE|-s&255}var gt={SCROLL_LOCK:1,NUM_LOCK:2,CAPS_LOCK:4,KANA_LOCK:8},Re={SYSTEM:1,POSITION:3,COLOR:6,CACHED:7,POINTER:8,LARGE:9},ca=196979,la=8,ha=32768,ua=524288,da={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 kr(n){return da[n]||`The host ended the session with error info 0x${n.toString(16).padStart(8,"0")}.`}function Jt(n,e,t){let r=new f(t.length+6);return r.u16le(t.length+6),r.u16le(n|16),r.u16le(e),r.raw(t),r.take()}function Pr(n,e,t,r){let s=new f(r.length+12);return s.u32le(n),s.u8(0),s.u8(1),s.u16le(r.length+18),s.u8(t),s.u8(0),s.u16le(0),s.raw(r),Jt(me.DATA,e,s.take())}function He(n,e){let t=n.length;n.utf16le(e);let r=n.length-t;return n.u16le(0),r}function Dr({domain:n,username:e,password:t,performanceFlags:r,autoLogon:s,remoteApp:i=!1,audio:o=!1}){let a=new f(512),c=He(a,n||""),l=He(a,e||""),m=He(a,t||""),E=He(a,""),x=He(a,""),p=new f(768);return p.u32le(0),p.u32le((ca|(s?la:0)|(i?ha:0)|(o?0:ua))>>>0),p.u16le(c),p.u16le(l),p.u16le(m),p.u16le(E),p.u16le(x),p.raw(a.take()),p.u16le(2),p.u16le(2),p.u16le(0),p.u16le(2),p.u16le(0),p.zeros(172),p.u32le(0),p.u32le(r>>>0),p.u16le(0),p.take()}function Mr(n){let e=new f(4);return e.u16le(1),e.u16le(n),e.take()}function en(n){let e=new f(8);return e.u16le(n),e.u16le(0),e.u32le(0),e.take()}function Br(){let n=new f(8);return n.u16le(0),n.u16le(0),n.u16le(3),n.u16le(50),n.take()}function Hr(n,e,t){let r=new TextEncoder().encode("MSTSC\0"),s=new f(e.length+32);return s.u32le(n),s.u16le(1002),s.u16le(r.length),s.u16le(e.length+4),s.raw(r),s.u16le(t),s.u16le(0),s.raw(e),s.take()}function Kr(n){let e=new f(n.length*12+4);e.u16le(n.length),e.u16le(0);for(let t of n)e.raw(t);return e.take()}function Ge(n,e){let t=new f(12);return t.u32le(0),t.u16le(n),e(t),t.take()}function tn(n,e,t){return Ge(Fe.SCANCODE,r=>{r.u16le((e?Ke.DOWN:Ke.RELEASE)|(t?Ke.EXTENDED:0)),r.u16le(n),r.u16le(0)})}function nn(n,e){return Ge(Fe.UNICODE,t=>{t.u16le(e?Ke.DOWN:Ke.RELEASE),t.u16le(n),t.u16le(0)})}function Et(n,e,t){return Ge(Fe.MOUSE,r=>{r.u16le(n),r.u16le(Math.max(0,Math.min(65535,Math.round(e)))),r.u16le(Math.max(0,Math.min(65535,Math.round(t))))})}function Fr(n,e,t){return Ge(Fe.MOUSEX,r=>{r.u16le(n),r.u16le(Math.max(0,Math.min(65535,Math.round(e)))),r.u16le(Math.max(0,Math.min(65535,Math.round(t))))})}function rn(n){return Ge(Fe.SYNC,e=>{e.u16le(0),e.u32le(n>>>0)})}function Gr(n){let e=new f(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 Wr(n,e){let t=new f(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 Vr(n){let e=new S(n),t=e.u16le(),r=e.u16le(),s=e.u16le();return{totalLength:t,pduType:r&15,pduSource:s,payload:e.rest().subarray(0,Math.max(0,t-6))}}function Yr(n){let e=new S(n),t=e.u32le();e.u8(),e.u8(),e.u16le();let r=e.u8(),s=e.u8(),i=e.u16le();return{shareId:t,pduType2:r,compressedType:s,compressedLength:i,payload:e.rest()}}function $r(n){let e=new S(n),t=e.u32le(),r=e.u16le(),s=e.u16le();e.skip(r);let i=e.raw(Math.min(s,e.remaining));return{shareId:t,capabilities:i}}var pa=1,fa=1024;function sn(n){let e=n.u16le(),t=[];for(let r=0;r<e&&n.remaining>=18;r++){let s=n.u16le(),i=n.u16le(),o=n.u16le(),a=n.u16le(),c=n.u16le(),l=n.u16le(),m=n.u16le(),E=n.u16le(),x=n.u16le(),p=!!(E&pa);if(p&&!(E&fa)){n.u16le();let y=n.u16le();n.u16le(),n.u16le(),x=y}t.push({left:s,top:i,right:o,bottom:a,width:c,height:l,bitsPerPixel:m,compressed:p,data:n.raw(Math.min(x,n.remaining))})}return t}function on(n){n.u16le(),n.u16le();let e=n.u32le(),t=new Uint8Array(256*3);for(let r=0;r<e&&r<256&&n.remaining>=3;r++)t[r*3]=n.u8(),t[r*3+1]=n.u8(),t[r*3+2]=n.u8();return t}function Ur(n,e){let t=n.u16le(),r=n.u16le(),s=n.u16le(),i=n.u16le(),o=n.u16le(),a=n.u16le(),c=n.u16le(),l=n.raw(Math.min(c,n.remaining)).slice(),m=n.raw(Math.min(a,n.remaining)).slice();return{kind:"bitmap",cacheIndex:t,hotSpotX:r,hotSpotY:s,width:i,height:o,xorBpp:e||24,xorMask:l,andMask:m}}function an(n){let e=n.u16le();if(n.u16le(),e===Re.POSITION)return{kind:"position",x:n.u16le(),y:n.u16le()};if(e===Re.SYSTEM)return{kind:"system",hidden:n.u32le()===0};if(e===Re.CACHED)return{kind:"cached",cacheIndex:n.u16le()};if(e===Re.COLOR)return Ur(n,24);if(e===Re.POINTER){let t=n.u16le();return Ur(n,t)}return e===Re.LARGE?{kind:"unsupported",messageType:e}:{kind:"unsupported",messageType:e}}var qr={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},Xr={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 cn(n){return Object.prototype.hasOwnProperty.call(qr,n)?{scancode:qr[n],extended:!1}:Object.prototype.hasOwnProperty.call(Xr,n)?{scancode:Xr[n],extended:!0}:null}var zr=[{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",_e="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"},ma=255,ln={name:"cliprdr",options:Q.INITIALIZED|Q.ENCRYPT_RDP|Q.SHOW_PROTOCOL},hn={name:"rail",options:Q.INITIALIZED|Q.ENCRYPT_RDP|Q.SHOW_PROTOCOL},un={name:"rdpsnd",options:Q.INITIALIZED|Q.ENCRYPT_RDP},dn={name:"rdpdr",options:Q.INITIALIZED|Q.ENCRYPT_RDP},ya=1,ga=2,Ea=4,wa=1200,Aa=120,wt=2,ba=4,Sa=12,Qr=320,At=class extends EventTarget{url;options;state;legacyRetryUsed;desktopWidth;desktopHeight;palette;userId;ioChannelId;serverChannelId;shareId;channelsToJoin;joinedChannels=0;requestedChannels;channelNamesById;channelReassemblers;clipboard;rail;audio;devices=null;remoteAppWindows;remoteAppHadWindow;remoteAppCloseTimer;remoteAppFit;remoteAppFitTimer;remoteAppViewport=null;clientRandom;serverData;fastPathFragments;receiveBuffer;keepaliveTimer;closeReported;tls;credssp;inboundQueue;security;replacingTransport=!1;socket;requestedProtocol;selectedProtocol=0;refreshRectSupported=!1;firstUpdateLogged=!1;toggleFlags=0;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,audio:!1,remoteApp:null,performance:ya|ga|Ea,...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.audio=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 Be,this.replacingTransport=!1,this.channelNamesById=new Map,this.channelReassemblers=new Map,this.clipboard=null,this.rail=null,this.audio=null,this.remoteAppWindows.clear(),this.remoteAppHadWindow=!1,clearTimeout(this.remoteAppCloseTimer??void 0),clearTimeout(this.remoteAppFitTimer??void 0),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.#n()),this.socket.addEventListener("message",e=>this.#l(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??void 0);try{this.socket.close(1e3,"Retrying with another security layer")}catch{}this.#e()}#n(){this.socket.send(Ce),this.state=L.NEGOTIATING,this.#s(Mn(this.requestedProtocol)),this.keepaliveTimer=setInterval(()=>{if(this.socket.readyState===WebSocket.OPEN&&(this.socket.send(_e),this.state===L.CONNECTED))try{this.#f([rn(this.toggleFlags||0)])}catch{}},25e3)}#o(){if(!this.serverData)throw new Error("RDP: the connection sequence ran ahead of the host's MCS answer");return this.serverData}#r(e){if(!this.tls)throw new Error("RDP: a secure write was attempted with no TLS channel");this.tls.write(e).catch(t=>this.#i(t))}#s(e){if(this.tls&&this.tls.established){this.#r(e);return}this.#a(e)}#a(e){this.socket.readyState===WebSocket.OPEN&&this.socket.send(e)}#c(e){if(clearInterval(this.keepaliveTimer??void 0),clearTimeout(this.remoteAppCloseTimer??void 0),clearTimeout(this.remoteAppFitTimer??void 0),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??void 0),clearTimeout(this.remoteAppCloseTimer??void 0),clearTimeout(this.remoteAppFitTimer??void 0),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??void 0),clearTimeout(this.remoteAppCloseTimer??void 0),clearTimeout(this.remoteAppFitTimer??void 0),this.remoteAppFitTimer=null;try{this.socket.close(1e3,"Client disconnected")}catch{}}}#l(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.#d(t)}).catch(t=>this.#i(t)))}#h(e){if(this.state===L.CREDSSP&&this.credssp){this.credssp.receive(e);return}this.#d(e).catch(t=>this.#i(t))}async#d(e){this.receiveBuffer=this.receiveBuffer.length===0?e:T(this.receiveBuffer,e);let{frames:t,rest:r}=Hn(this.receiveBuffer);this.receiveBuffer=r.length===this.receiveBuffer.length?this.receiveBuffer:r.slice();for(let{fastPath:s,frame:i}of t){if(this.state===L.CLOSED)return;s?this.#P(i):await this.#g(i)}}async#g(e){if(this.state===L.NEGOTIATING){let o;try{({selectedProtocol:o}=Bn(e))}catch(a){if(this.options.security==="auto"&&!this.legacyRetryUsed&&a?.negotiationFailure===Dn.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.#p(o);return}this.#w(o);return}if(this.state===L.MCS_CONNECT){this.serverData=dr(sr(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;let o=this.#o();this.requestedChannels.forEach((a,c)=>{let l=o.channelIds[c];l!==void 0&&this.channelNamesById.set(l,a.name)}),this.security.configure(this.serverData.encryptionMethod,this.serverData.encryptionLevel,this.serverData.encryptionMethod?this.#A():new Uint8Array(32),this.serverData.serverRandom||new Uint8Array(32)),this.state=L.ATTACH_USER,this.#s(ir()),this.#s(or());return}if(this.state===L.ATTACH_USER){({userId:this.userId}=ar(e)),this.channelsToJoin=[this.userId,this.ioChannelId,...this.#o().channelIds],this.joinedChannels=0,this.state=L.JOIN_CHANNELS,this.#s(Yt(this.userId,this.channelsToJoin[0]));return}if(this.state===L.JOIN_CHANNELS){if(cr(e),this.joinedChannels+=1,this.joinedChannels<this.channelsToJoin.length){this.#s(Yt(this.userId,this.channelsToJoin[this.joinedChannels]));return}this.#b();return}let t=lr(e);if(t.type==="disconnect"){this.#i(new Error(t.message));return}if(t.type!=="send-data")return;let r=this.channelNamesById.get(t.channelId);if(r){let o=this.security.headerPresent?this.security.unwrap(t.payload).payload:t.payload;this.#M(r,o);return}let{flags:s,payload:i}=this.#u(t.payload);if(i.length!==0){if(s&G.LICENSE_PKT){this.#y(i);return}this.#v(i)}}#u(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 r=e[0]|e[1]<<8;if((e[2]|e[3]<<8)===0&&(r&t)!==0)return this.security.unwrap(e,!0)}return{flags:0,payload:e}}async#p(e){try{this.state=L.TLS_HANDSHAKE,this.tls=new Je({send:s=>this.#a(s),onData:s=>this.#h(s),onError:s=>this.#i(s)});let t=await this.tls.start();if(!t.publicKey)throw new Error("RDP: the TLS handshake finished without a host public key");let r=t.publicKey;if(console.info("[RDP] TLS established",{cipherSuite:t.cipherSuite,certificates:t.certificates.length,modulusBits:r.modulus.length*8}),e&P.HYBRID){if(this.state=L.CREDSSP,this.credssp=new tt({username:this.options.username,domain:this.options.domain,password:this.options.password,serverPublicKey:r.subjectPublicKey,send:i=>this.#r(i),log:(i,o)=>console.info(`[RDP] ${i}`,o)}),!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.#w(e)}catch(t){this.#i(t)}}#w(e){this.state=L.MCS_CONNECT,this.requestedChannels=[],this.options.clipboard&&this.requestedChannels.push(ln),this.devices=null,this.options.audio&&this.requestedChannels.push(un,dn),this.options.remoteApp?.program&&this.requestedChannels.push(hn),this.#s(rr(ur({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})))}#A(){return this.clientRandom=new Uint8Array(32),crypto.getRandomValues(this.clientRandom),this.clientRandom}#b(){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");if(!this.clientRandom)throw new Error("RDP: the security exchange ran before a client random existed");let r=_n(this.clientRandom,t.modulus,t.exponent);this.#m(Be.securityExchange(r))}let e=Dr({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,audio:this.options.audio});this.state=L.LICENSING,this.#m(this.security.wrap(e,G.INFO_PKT))}#m(e){this.#s($t(this.userId,this.ioChannelId,e))}#y(e){if(e.length<4)return;if(e[0]===ma){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.")}#v(e){let t=Vr(e);if(t.pduSource&&(this.serverChannelId=t.pduSource),t.pduType===me.DEMAND_ACTIVE){this.#R(t.payload);return}if(t.pduType===me.DEACTIVATE_ALL){console.info("[RDP] Host deactivated the share; waiting for a new demand active"),this.state=L.CAPABILITIES;return}if(t.pduType===me.SERVER_REDIRECT)throw new Error("This host redirected the session to another server, which this client cannot follow.");if(t.pduType!==me.DATA)return;let r=Yr(t.payload);if(r.compressedType&32)throw new Error("RDP: the host compressed a PDU although this client advertised no compression support");this.#C(r)}#R(e){let{shareId:t,capabilities:r}=$r(e);this.shareId=t;let s=Nr(r);if(this.options.remoteApp?.program&&(!(s.railSupportLevel&1)||!s.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(s.desktopWidth&&s.desktopHeight){let a=this.state===L.CONNECTED&&(s.desktopWidth!==this.desktopWidth||s.desktopHeight!==this.desktopHeight);this.desktopWidth=s.desktopWidth,this.desktopHeight=s.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=s.refreshRectSupport,console.info("[RDP] Demand active",{shareId:t,desktop:`${this.desktopWidth}x${this.desktopHeight}`,bitsPerPixel:s.preferredBitsPerPixel,refreshRectSupport:s.refreshRectSupport,remoteApp:!!this.options.remoteApp?.program});let{bytes:i,count:o}=Ir({width:this.desktopWidth,height:this.desktopHeight,keyboardLayout:this.options.keyboardLayout,remoteApp:!!this.options.remoteApp?.program,remoteAppCaps:s});this.#K(me.CONFIRM_ACTIVE,Hr(this.shareId,i,o)),this.#E(M.SYNCHRONIZE,Mr(this.serverChannelId)),this.#E(M.CONTROL,en(Zt.COOPERATE)),this.#E(M.CONTROL,en(Zt.REQUEST_CONTROL)),this.#E(M.FONT_LIST,Br())}#C(e){switch(e.pduType2){case M.UPDATE:this.#_(new S(e.payload));return;case M.POINTER:this.dispatchEvent(new CustomEvent("pointer",{detail:an(new S(e.payload))}));return;case M.FONT_MAP:this.#k();return;case M.SET_ERROR_INFO:{let t=new S(e.payload).u32le();if(t===0)return;this.#i(new Error(kr(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}}#_(e){let t=e.u16le();if(this.firstUpdateLogged||(this.firstUpdateLogged=!0,console.info("[RDP] First host update received",{updateType:t})),t===yt.BITMAP){let r=sn(e);r.length>0&&this.dispatchEvent(new CustomEvent("bitmap",{detail:{rects:r,palette:this.palette}}));return}if(t===yt.PALETTE){this.palette=on(e),this.dispatchEvent(new CustomEvent("palette",{detail:this.palette}));return}if(t===yt.ORDERS){this.options.remoteApp?.program?this.#L(vr(e)):console.warn("[RDP] Ignoring a drawing-order update the client did not advertise");return}}#L(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??void 0),this.remoteAppCloseTimer=null,this.remoteAppHadWindow=!0):this.remoteAppWindows.has(t.windowId)||(this.remoteAppHadWindow=!0);let s={...this.remoteAppWindows.get(t.windowId)||{windowId:t.windowId},...t,type:void 0};this.remoteAppWindows.set(t.windowId,s),this.dispatchEvent(new CustomEvent("remoteappwindow",{detail:{...t,window:s,count:this.remoteAppWindows.size}})),this.remoteAppFit&&this.#I(s)&&!this.#N(s)&&this.#x()}this.#O(),!(!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}})))},wa))}get remoteAppPrimaryWindow(){let e=null,t=-1;for(let r of this.remoteAppWindows.values()){if(!Tr(r)||r.showState===ve.HIDDEN)continue;let s=(r.width||0)*(r.height||0);s>t&&(e=r,t=s)}return e}#I(e){let t=this.remoteAppPrimaryWindow;return t!==null&&t.windowId===e.windowId}#N(e){let t=this.remoteAppFit;return t?Math.abs(e.x||0)<=wt&&Math.abs(e.y||0)<=wt&&Math.abs((e.width||0)-t.width)<=wt&&Math.abs((e.height||0)-t.height)<=wt:!0}#x(){this.remoteAppFitTimer||(this.remoteAppFitTimer=setTimeout(()=>{this.remoteAppFitTimer=null,this.#U()},Aa))}#U(){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===ve.MINIMIZED)return;let r=`${t.width||0}x${t.height||0}+${t.x||0}+${t.y||0}`;if(r!==e.lastGeometry&&(e.attempts=0),e.lastGeometry=r,!(e.attempts>=ba||e.moves>=Sa)){if(e.attempts+=1,e.moves+=1,t.showState===ve.MAXIMIZED){console.info("[RDP] Restoring the maximized RemoteApp window before fitting it"),this.rail.sysCommand(t.windowId,Ar.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})}}#O(){let e=this.remoteAppPrimaryWindow;if(!e||!e.width||!e.height||e.showState===ve.MINIMIZED||e.showState===ve.HIDDEN)return;let t=Math.max(0,Math.min(this.desktopWidth-1,e.x||0)),r=Math.max(0,Math.min(this.desktopHeight-1,e.y||0)),s={x:t,y:r,width:Math.max(1,Math.min(this.desktopWidth-t,e.width)),height:Math.max(1,Math.min(this.desktopHeight-r,e.height))},i=this.remoteAppViewport;i&&i.x===s.x&&i.y===s.y&&i.width===s.width&&i.height===s.height||(this.remoteAppViewport=s,this.dispatchEvent(new CustomEvent("remoteappviewport",{detail:s})))}fitRemoteApp(e,t){if(!this.options.remoteApp?.program||!Number.isFinite(e)||!Number.isFinite(t))return!1;let r={width:Math.max(Qr,Math.min(this.desktopWidth,Math.floor(e))),height:Math.max(Qr,Math.min(this.desktopHeight,Math.floor(t))),attempts:0,moves:0,lastGeometry:""};return this.remoteAppFit=r,this.#x(),!0}#k(){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.keyLength*8}-bit`:"TLS transport"}),this.dispatchEvent(new CustomEvent("ready",{detail:{width:this.desktopWidth,height:this.desktopHeight}})),this.setOutputEnabled(!0),this.refresh())}#P(e){let t=e[0]>>6&3,r=e[1]&128?2:1,s=e.subarray(1+r);t&2&&(s=this.security.decryptFastPath(s));let i=new S(s);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(),E=i.raw(Math.min(m,i.remaining));if(c!==0){if(c===2&&(this.fastPathFragments=[]),this.fastPathFragments.push(E.slice()),c!==1)continue;E=T(...this.fastPathFragments),this.fastPathFragments=[]}this.#D(a,E)}}#D(e,t){let r=new S(t);switch(e){case 1:{r.u16le();let s=sn(r);s.length>0&&this.dispatchEvent(new CustomEvent("bitmap",{detail:{rects:s,palette:this.palette}}));return}case 2:this.palette=on(r),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:r.u16le(),y:r.u16le()}}));return;case 9:case 10:case 11:{let s={9:6,10:7,11:8}[e],i=new Uint8Array([s,0,0,0]);this.dispatchEvent(new CustomEvent("pointer",{detail:an(new S(T(i,t)))}));return}default:return}}#M(e,t){let r=this.channelReassemblers.get(e);r||(r=new mt,this.channelReassemblers.set(e,r));let s=r.push(t);if(s){if(e===dn.name){this.devices??=new dt(i=>{this.#S(dn.name,i)}),this.devices.receive(s);return}if(e===ln.name){this.#T().receive(s);return}if(e===hn.name){this.#B().receive(s);return}if(e===un.name)try{this.#H().receive(s)}catch(i){console.warn("[RDP] dropped an unreadable audio PDU",i)}}}#S(e,t){let r=[...this.channelNamesById].find(([,o])=>o===e)?.[0];if(r===void 0)return!1;let i=(this.requestedChannels.find(o=>o.name===e)?.options??0)&Q.SHOW_PROTOCOL?_r:0;for(let o of Lr(t,Qt,i))this.#s($t(this.userId,r,this.security.wrap(o)));return!0}#B(){if(this.rail)return this.rail;let e=this.options.remoteApp;if(!e)throw new Error("RDP: the RemoteApp channel opened with no application to launch");return this.rail=new ft({application:e,width:this.remoteAppFit?.width||this.desktopWidth,height:this.remoteAppFit?.height||this.desktopHeight,send:t=>this.#S(hn.name,t),onReady:t=>{if(t.type!=="handshake")return;let{buildNumber:r,extended:s,flags:i}=t;console.info("[RDP] RemoteApp channel ready",{buildNumber:r,extended:!!s,flags:i||0}),this.dispatchEvent(new CustomEvent("remoteappready",{detail:{application:this.options.remoteApp}}))},onResult:t=>{let r={...t,application:this.options.remoteApp};this.dispatchEvent(new CustomEvent("remoteappresult",{detail:r})),t.ok?console.info("[RDP] Remote application launched",r):this.#i(new Error(t.message))}}),this.rail}#H(){return this.audio?this.audio:(this.audio=new ht({send:e=>this.#S(un.name,e),log:(e,t)=>console.info(`[RDP] ${e}`,t??"")}),this.audio.addEventListener("ready",e=>{this.dispatchEvent(new CustomEvent("audioready",{detail:e.detail}))}),this.audio.addEventListener("audio",e=>{this.dispatchEvent(new CustomEvent("audio",{detail:e.detail}))}),this.audio.addEventListener("close",()=>{this.dispatchEvent(new CustomEvent("audioclosed"))}),this.audio)}get audioActive(){return!!this.audio?.ready}#T(){return this.clipboard?this.clipboard:(this.clipboard=new ct({send:e=>this.#S(ln.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.#T().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(r=>(r?t():this.sendUnicode(e),!0))}#K(e,t){this.#m(this.security.wrap(Jt(e,this.userId,t)))}#E(e,t){this.#m(this.security.wrap(Pr(this.shareId,this.userId,e,t)))}get connected(){return this.state===L.CONNECTED}#f(e){!this.connected||e.length===0||this.#E(M.INPUT,Kr(e))}sendKeyByCode(e,t){let r=cn(e);return r?(this.#f([tn(r.scancode,t,r.extended)]),!0):!1}sendUnicode(e){let t=[];for(let r of e)for(let s=0;s<r.length;s++){let i=r.charCodeAt(s);t.push(nn(i,!0)),t.push(nn(i,!1))}for(let r=0;r<t.length;r+=40)this.#f(t.slice(r,r+40))}sendCtrlAltDel(){let e=zr.flatMap(({code:t,pressed:r})=>{let s=cn(t);return s?[tn(s.scancode,r,s.extended)]:[]});this.#f(e)}sendMouseMove(e,t){this.#f([Et(re.MOVE,e,t)])}sendMouseButton(e,t,r,s){let i={0:re.BUTTON1,1:re.BUTTON3,2:re.BUTTON2}[e];if(i===void 0){let o=e===3?1:2;this.#f([Fr(o|(t?re.DOWN:0),r,s)]);return}this.#f([Et(i|(t?re.DOWN:0),r,s)])}sendWheel(e,t,r,s=!1){let i=Or(e,s);i&&this.#f([Et(i,t,r)])}sendKeyboardSync(e){this.toggleFlags=e>>>0,this.#f([rn(this.toggleFlags)])}refresh(e){!this.connected||!this.refreshRectSupported||this.#E(M.REFRESH_RECT,Gr([e||{left:0,top:0,right:this.desktopWidth-1,bottom:this.desktopHeight-1}]))}setOutputEnabled(e){this.connected&&this.#E(M.SUPPRESS_OUTPUT,Wr(e,{left:0,top:0,right:this.desktopWidth-1,bottom:this.desktopHeight-1}))}};function xa(n){return(n&192)!==192?n>>5:(n&240)===240?n:n>>4}function Ta(n,e,t,r){let s=new Uint32Array(e*t),i=r>=4?4294967295:(1<<r*8)-1,o=0,a=0,c=i,l=!1,m=!0,E=()=>{let y=0;for(let h=0;h<r;h++)y|=n[o+h]<<h*8;return o+=r,y>>>0},x=y=>{let h=n[o];if(y===2){let w=h&31;return w===0?(o+=2,n[o-1]+1):(o+=1,w*8)}if(y===13){let w=h&15;return w===0?(o+=2,n[o-1]+1):(o+=1,w*8)}if(y===0||y===1||y===3||y===4){let w=h&31;return w===0?(o+=2,n[o-1]+32):(o+=1,w)}if(y===12||y===14){let w=h&15;return w===0?(o+=2,n[o-1]+16):(o+=1,w)}let A=n[o+1]|n[o+2]<<8;return o+=3,A},p=(y,h)=>{let A=1;for(let w=0;w<h;w++){if(m)s[a]=y&A?c:0;else{let v=s[a-e];s[a]=y&A?(v^c)>>>0:v}a++,A=A<<1&255}};for(;o<n.length&&a<s.length;){m&&a>=e&&(m=!1);let y=xa(n[o]);if(y===0||y===240){let h=x(y);if(m)for(l&&(s[a++]=c,h--);h-- >0&&a<s.length;)s[a++]=0;else for(l&&(s[a]=(s[a-e]^c)>>>0,a++,h--);h-- >0&&a<s.length;)s[a]=s[a-e],a++;l=!0;continue}switch(l=!1,y){case 1:case 241:case 12:case 246:{let h=x(y);if((y===12||y===246)&&(c=E()),m)for(;h-- >0&&a<s.length;)s[a++]=c;else for(;h-- >0&&a<s.length;)s[a]=(s[a-e]^c)>>>0,a++;break}case 14:case 248:{let h=x(y),A=E(),w=E();for(;h-- >0&&a<s.length-1;)s[a++]=A,s[a++]=w;break}case 3:case 243:{let h=x(y),A=E();for(;h-- >0&&a<s.length;)s[a++]=A;break}case 2:case 242:case 13:case 247:{let h=x(y);for((y===13||y===247)&&(c=E());h>8;)p(n[o++],8),h-=8;h>0&&p(n[o++],h);break}case 4:case 244:{let h=x(y);for(;h-- >0&&a<s.length;)s[a++]=E();break}case 249:o++,p(3,8);break;case 250:o++,p(5,8);break;case 253:o++,s[a++]=i;break;case 254:o++,s[a++]=0;break;default:throw new Error(`RDP: unsupported bitmap compression order 0x${y.toString(16)}`)}}return s}function va(n,e){if(e<=0)return n;let t=Math.floor(n.length/e);if(t<2)return n;let r=new Uint32Array(n.length);for(let s=0;s<t;s++)r.set(n.subarray(s*e,(s+1)*e),(t-1-s)*e);return r}function Ra(n,e,t,r){let s=new Uint32Array(e*t);for(let i=0;i<t;i++){let o=(t-1-i)*e,a=i*e*r;for(let c=0;c<e;c++){let l=0;for(let m=0;m<r;m++)l|=n[a+m]<<m*8;s[o+c]=l>>>0,a+=r}}return s}function Ca(n,e,t){let r=new Uint8ClampedArray(n.length*4);for(let s=0;s<n.length;s++){let i=n[s],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 l=s*4;r[l]=o,r[l+1]=a,r[l+2]=c,r[l+3]=255}return r}function jr(n,e){let t=Math.max(1,Math.ceil(n.bitsPerPixel/8)),r=n.compressed?va(Ta(n.data,n.width,n.height,t),n.width):Ra(n.data,n.width,n.height,t);return Ca(r,n.bitsPerPixel,e)}var pn=/Mac|iPod|iPhone|iPad/.test(globalThis.navigator?.platform||globalThis.navigator?.userAgent||""),Zr={MetaLeft:"ControlLeft",MetaRight:"ControlRight"},Jr=60,_a=16,es=20,La=8,Ia=1,bt=class{container;canvas;context;viewportElement;scrollHost;width;height;viewport;scale;scaleViewport;zoom;userZoomed;viewOnly;client;palette;cursorCache;heldKeys;keyboardSynced;handlers=null;onWindowResize;resizeObserver;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";let t=this.canvas.getContext("2d",{alpha:!1});if(!t)throw new Error("RDP: this browser gave no 2D canvas context to paint the desktop into");this.context=t,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:r,height:s}={}){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(r||this.width))),height:Math.max(1,Math.min(this.height-o,Math.floor(s||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}#n(){return 1}applyScale(){if(!this.width||!this.height)return;let e=this.viewport,t=this.#e(),r=this.#t(t);this.userZoomed||(this.zoom=this.#n());let s=(this.scaleViewport?r:1)*this.zoom;this.scale=s,this.viewportElement.style.width=`${e.width*s}px`,this.viewportElement.style.height=`${e.height*s}px`,this.canvas.style.width=`${this.width*s}px`,this.canvas.style.height=`${this.height*s}px`,this.canvas.style.left=`${-e.x*s}px`,this.canvas.style.top=`${-e.y*s}px`}setZoom(e,t=null){let r=Math.min(La,Math.max(Ia,e));if(!Number.isFinite(r)||r===this.zoom)return;let s=this.scrollHost,i=this.scale,o=s.getBoundingClientRect(),a=t?t.x-o.left:o.width/2,c=t?t.y-o.top:o.height/2,l=s.scrollLeft+a,m=s.scrollTop+c;this.zoom=r,this.applyScale();let E=i>0?this.scale/i:1;s.scrollLeft=l*E-a,s.scrollTop=m*E-c}panBy(e,t){let r=this.scrollHost,s=r.scrollLeft,i=r.scrollTop;return r.scrollLeft=s-e,r.scrollTop=i-t,{x:s-r.scrollLeft,y:i-r.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 r of e)if(!(r.width===0||r.height===0))try{let s=jr(r,this.palette),i=new ImageData(s,r.width,r.height);this.context.putImageData(i,r.left,r.top)}catch(s){console.warn("[RDP] Dropped an undecodable bitmap rectangle",{geometry:`${r.width}x${r.height}+${r.left}+${r.top}`,bitsPerPixel:r.bitsPerPixel,compressed:r.compressed,error:s instanceof Error?s.message:String(s)})}}#o(e){let{width:t,height:r,xorBpp:s,xorMask:i,andMask:o,hotSpotX:a,hotSpotY:c}=e;if(!t||!r)return null;let l=Math.ceil(t*s/8/2)*2,m=Math.ceil(t/8/2)*2,E=new Uint8ClampedArray(t*r*4);for(let h=0;h<r;h++){let A=r-1-h;for(let w=0;w<t;w++){let v=o[A*m+(w>>3)],u=v!==void 0&&(v&128>>(w&7))!==0,d=0,b=0,C=0,R=u?0:255;if(s===1)d=b=C=i[A*l+(w>>3)]&128>>(w&7)?255:0;else{let _=s/8,U=A*l+w*_;if(s===16){let W=i[U]|i[U+1]<<8;d=(W>>11&31)*255/31,b=(W>>5&63)*255/63,C=(W&31)*255/31}else C=i[U]||0,b=i[U+1]||0,d=i[U+2]||0,s===32&&i[U+3]!==void 0&&o.length===0&&(R=i[U+3])}let N=(h*t+w)*4;E[N]=d,E[N+1]=b,E[N+2]=C,E[N+3]=R}}let x=document.createElement("canvas");x.width=t,x.height=r,x.getContext("2d")?.putImageData(new ImageData(E,t,r),0,0);let p=Math.min(a||0,t-1),y=Math.min(c||0,r-1);return`url(${x.toDataURL("image/png")}) ${p} ${y}, 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.#o(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(),r=this.width/(t.width||1),s=this.height/(t.height||1);return{x:Math.max(0,Math.min(this.width-1,(e.clientX-t.left)*r)),y:Math.max(0,Math.min(this.height-1,(e.clientY-t.top)*s))}}#s(e){if(this.keyboardSynced||!this.client)return;this.keyboardSynced=!0;let t=0;e.getModifierState?.("CapsLock")&&(t|=gt.CAPS_LOCK),e.getModifierState?.("NumLock")&&(t|=gt.NUM_LOCK),e.getModifierState?.("ScrollLock")&&(t|=gt.SCROLL_LOCK),this.client.sendKeyboardSync(t)}attachInput(e){this.client=e,this.keyboardSynced=!1;let t=()=>this.client&&e.connected&&!this.viewOnly,r=null,s=!1,i=0,o=!1,a=0,c=0,l=0,m=0,E={x:0,y:0},x=0,p=0,y=0,h=null,A=u=>({x:(u[0].clientX+u[1].clientX)/2,y:(u[0].clientY+u[1].clientY)/2}),w=u=>Math.hypot(u[0].clientX-u[1].clientX,u[0].clientY-u[1].clientY),v=()=>{s=!1,r&&t()&&e.sendMouseMove(r.x,r.y),r=null};this.handlers={mousemove:u=>{t()&&(r=this.#r(u),s||(s=!0,requestAnimationFrame(v)))},mousedown:u=>{if(this.canvas.focus(),!t())return;u.preventDefault();let{x:d,y:b}=this.#r(u);e.sendMouseButton(u.button,!0,d,b)},mouseup:u=>{if(!t())return;u.preventDefault();let{x:d,y:b}=this.#r(u);e.sendMouseButton(u.button,!1,d,b)},contextmenu:u=>u.preventDefault(),wheel:u=>{if(!t())return;u.preventDefault();let d=u.deltaY;if(u.deltaMode===WheelEvent.DOM_DELTA_LINE&&(d*=_a),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)<Jr))return;let b=Math.sign(i);i-=b*Jr;let{x:C,y:R}=this.#r(u);e.sendWheel(b,C,R)},touchstart:u=>{if(this.canvas.focus(),!!t()){if(u.preventDefault(),u.touches.length===1){h="tap";let d=u.touches[0];a=d.clientX,c=d.clientY;let{x:b,y:C}=this.#r(d);e.sendMouseMove(b,C),e.sendMouseButton(0,!0,b,C),o=!0}else if(u.touches.length===2){if(h="undecided",o){let{x:C,y:R}=this.#r({clientX:a,clientY:c});e.sendMouseButton(0,!1,C,R),o=!1}let d=A(u.touches),b=w(u.touches);E={x:d.x,y:d.y},x=b,l=d.y,m=d.x,p=b,y=0}}},touchmove:u=>{if(t()){if(u.preventDefault(),u.touches.length===1&&h==="tap"){let d=u.touches[0];a=d.clientX,c=d.clientY;let{x:b,y:C}=this.#r(d);e.sendMouseMove(b,C)}else if(u.touches.length===2){let d=A(u.touches),b=d.x,C=d.y,R=w(u.touches),N=l-C,_=m-b;l=C,m=b;let U=Math.hypot(b-E.x,C-E.y),W=Math.abs(R-x),ye=x>0?R/x:1;if(h==="undecided"&&(W>20&&Math.abs(ye-1)>.15&&W>U*.8?h="pinch":U>8&&(h="scroll")),h==="pinch")p>0&&Math.abs(R-p)>1&&(this.userZoomed=!0,this.setZoom(this.zoom*(R/p),{x:b,y:C})),p=R;else if(h==="scroll"){if(p=R,this.canPan()){this.panBy(_*-1,N*-1),y=0;return}for(N&&y&&Math.sign(y)!==Math.sign(N)&&(y=0),y+=N;Math.abs(y)>=es;){let de=Math.sign(y);y-=de*es;let{x:Ie,y:pe}=this.#r({clientX:b,clientY:C});e.sendWheel(de,Ie,pe)}}}}},touchend:u=>{if(t())if(u.preventDefault(),u.touches.length===0){if(o){let{x:d,y:b}=this.#r({clientX:a,clientY:c});e.sendMouseButton(0,!1,d,b),o=!1}h==="pinch"&&this.zoom<=1.05&&this.resetZoom(),h=null,y=0,p=0}else u.touches.length===1&&(h==="pinch"||h==="scroll"||h==="undecided")&&(h==="pinch"&&this.zoom<=1.05&&this.resetZoom(),h=null,p=0,y=0)},touchcancel:u=>{if(t()){if(o){let{x:d,y:b}=this.#r({clientX:a,clientY:c});e.sendMouseButton(0,!1,d,b),o=!1}h==="pinch"&&this.zoom<=1.05&&this.resetZoom(),h=null,y=0,p=0}},keydown:u=>{if(!t()||(this.#s(u),this.#c(u)))return;let d=this.#a(u.code);if(e.sendKeyByCode(d,!0)){if(u.preventDefault(),pn&&u.metaKey&&!Zr[u.code]){e.sendKeyByCode(d,!1);return}this.heldKeys.add(d)}},keyup:u=>{if(!t()||this.#c(u))return;let d=this.#a(u.code);e.sendKeyByCode(d,!1)&&(this.heldKeys.delete(d),u.preventDefault())},paste:u=>{if(!t())return;let d=u.target,b=d instanceof Node&&this.container.contains(d);if(document.activeElement!==this.canvas&&!b)return;u.preventDefault();let C=u.clipboardData?.getData("text/plain")||"";C&&Promise.resolve(e.pasteToHost(C)).catch(R=>{console.warn("[RDP] The paste did not reach the host",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)}#a(e){return pn&&Zr[e]||e}#c(e){return e.code!=="KeyV"?!1:pn?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 ts=["pointerdown","keydown","touchend"];function St(n){return n.state}function ns(){return typeof globalThis.AudioContext=="function"?globalThis.AudioContext:null}function rs(){return ns()!==null}function Na(n){let{channels:e,bitsPerSample:t}=n.format,r=t>>3,s=r*e;if(!s)return null;let i=Math.floor(n.samples.length/s);if(i<=0)return null;let o=Array.from({length:e},()=>new Float32Array(i)),a=new DataView(n.samples.buffer,n.samples.byteOffset,n.samples.byteLength);for(let c=0;c<i;c++)for(let l=0;l<e;l++){let m=c*s+l*r;o[l][c]=t===16?a.getInt16(m,!0)/32768:(a.getUint8(m)-128)/128}return o}var xt=class{#e=null;#t=null;#n=0;#o=!1;#r=1;#s=!1;#a=null;dropped=0;played=0;constructor({volume:e=1,muted:t=!1}={}){this.#r=e,this.#o=t}#c(e){if(this.#s)return null;if(this.#e)return this.#e;let t=ns();if(!t)return null;let r;try{r=new t({sampleRate:e})}catch{r=new t}let s=r.createGain();return s.gain.value=this.#o?0:this.#r,s.connect(r.destination),this.#e=r,this.#t=s,this.#n=r.currentTime,this.#i(),r}#i(){if(this.#a||typeof globalThis.addEventListener!="function")return;let e=()=>{this.resume()};for(let t of ts)globalThis.addEventListener(t,e,{passive:!0});this.#a=()=>{for(let t of ts)globalThis.removeEventListener(t,e);this.#a=null}}async resume(){let e=this.#e;if(!e||this.#s)return!1;if(e.state==="running")return!0;try{await e.resume()}catch{return!1}return St(e)==="running"&&(this.#n=e.currentTime+.06),St(e)==="running"}get running(){return this.#e?.state==="running"}get muted(){return this.#o}set muted(e){this.#o=e,this.#t&&(this.#t.gain.value=e?0:this.#r)}get volume(){return this.#r}set volume(e){this.#r=Math.min(1,Math.max(0,e)),this.#t&&!this.#o&&(this.#t.gain.value=this.#r)}play(e){if(this.#s||this.#o)return!1;let t=Na(e);if(!t?.length)return!1;let r=this.#c(e.format.samplesPerSec);if(!r||!this.#t)return!1;if(St(r)!=="running"&&(this.resume(),St(r)!=="running"))return this.dropped++,!1;let s=r.currentTime;if(this.#n<s-.25)this.#n=s+.06;else if(this.#n>s+1)return this.dropped++,!1;let i=r.createBuffer(t.length,t[0].length,e.format.samplesPerSec);for(let a=0;a<t.length;a++)i.copyToChannel(t[a],a);let o=r.createBufferSource();return o.buffer=i,o.connect(this.#t),o.start(Math.max(this.#n,s)),this.#n=Math.max(this.#n,s)+i.duration,this.played++,!0}reset(){this.#e&&(this.#n=this.#e.currentTime)}dispose(){this.#s=!0,this.#a?.();let e=this.#e;this.#e=null,this.#t=null,e&&e.close().catch(()=>{})}};var Ve={vnc:5900,rdp:3389,ssh:22},Cl=Ve.ssh;var _l=5*6e4;var Ua={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 Oa(n,e){let t=new URLSearchParams({host:e.host,port:String(e.port),security:e.security});return`${n}/rdp-ws?${t}`}function ka({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 fn=class extends EventTarget{protocol="rdp";url;options;display;client;security;_rfbConnectionState;_scaleViewport;lastErrorMessage;hostLabel;audio;audioMuted;remoteAppLayoutObserver;constructor(e,t,r={}){super(),this.url=t,this.options=r,this.display=new bt(e),this.display.viewOnly=!!r.viewOnly,this._rfbConnectionState="connecting",this._scaleViewport=r.scaleViewport!==!1,this.display.scaleViewport=this._scaleViewport,this.lastErrorMessage="",this.hostLabel=r.hostLabel||"Remote Desktop",this.audio=null,this.audioMuted=!1,this.#e(r.security||"auto"),this.remoteAppLayoutObserver=r.remoteApp?.program&&typeof ResizeObserver=="function"?new ResizeObserver(()=>this.fitToViewport()):null,this.remoteAppLayoutObserver?.observe(this.display.scrollHost)}#e(e){this.security=e,this.client=new At(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,audio:!!this.options.audio&&rs()}),this.client.addEventListener("ready",t=>{let{width:r,height:s}=t.detail;this.display.resize(r,s),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} (${r}x${s})`}}))}),this.client.addEventListener("resize",t=>{let{width:r,height:s}=t.detail;this.display.resize(r,s),this.dispatchEvent(new CustomEvent("desktopname",{detail:{name:`${this.hostLabel} (${r}x${s})`}})),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("audioready",t=>{this.audio??=new xt({muted:this.audioMuted}),this.dispatchEvent(new CustomEvent("audio",{detail:{on:!0,formats:t.detail.formats.length}}))}),this.client.addEventListener("audio",t=>{this.audio?.play(t.detail)}),this.client.addEventListener("audioclosed",()=>{this.audio?.reset(),this.dispatchEvent(new CustomEvent("audio",{detail:{on:!1,formats:0}}))}),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.audio?.dispose(),this.audio=null,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),r=Math.floor(e.height||this.options.height||0);return t<=0||r<=0?!1:this.client.fitRemoteApp(t,r)}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,r){t&&this.client.sendKeyByCode(t,r)||!r||!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,r=0){if(!this.client?.connected||this.display.viewOnly)return!1;let[s,i]=this.#t(e,t);return this.client.sendMouseMove(s,i),this.pointerButton(s,i,r,!0),this.pointerButton(s,i,r,!1),!0}pointerButton(e,t,r=0,s=!0){if(!this.client?.connected||this.display.viewOnly)return!1;let[i,o]=this.#t(e,t);return this.client.sendMouseButton(r,s,i,o),!0}scrollPointer(e,t,r){if(!this.client?.connected||this.display.viewOnly)return!1;let[s,i]=this.#t(e,t);for(let o=0;o<Math.min(20,Math.abs(r.y));o++)this.client.sendWheel(Math.sign(r.y),s,i,!1);for(let o=0;o<Math.min(20,Math.abs(r.x));o++)this.client.sendWheel(Math.sign(r.x),s,i,!0);return!0}typeText(e){if(!this.client?.connected||this.display.viewOnly||!e)return!1;let t="",r=()=>{t&&(this.client.sendUnicode(t),t="")};for(let s of e)s===`
|
|
2
|
+
`||s==="\r"?(r(),this.client.sendKeyByCode("Enter",!0),this.client.sendKeyByCode("Enter",!1)):s===" "?(r(),this.client.sendKeyByCode("Tab",!0),this.client.sendKeyByCode("Tab",!1)):t+=s;return r(),!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(r=>{r||this.client.sendUnicode(e)},()=>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}get audioActive(){return this.client.audioActive}setAudioMuted(e){return this.audioMuted=e,this.audio&&(this.audio.muted=this.audioMuted),this.audioMuted}get audioMutedState(){return this.audioMuted}disconnect(){this.remoteAppLayoutObserver?.disconnect(),this.client.disconnect(),this.display.destroy(),this._rfbConnectionState="disconnected"}},ss={protocol:"rdp",label:"RDP Client",defaultPort:Ve.rdp,dialog:Ua,buildUrl:Oa,createSession:(n,e,t)=>new fn(n,e,t),describeState:()=>({}),describeDisconnect:ka};import mn from"@novnc/novnc";var is="binary",Pa="airemote-cred.";function Da(n){let e=new TextEncoder().encode(n),t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}function os(n){let e=n.username||"",t=n.password||"";return!e&&!t?[is]:[is,Pa+Da(JSON.stringify({u:e,p:t}))]}function as(n){let e=[],t=[{amount:n.y,negativeMask:8,positiveMask:16},{amount:n.x,negativeMask:32,positiveMask:64}];for(let{amount:r,negativeMask:s,positiveMask:i}of t){let o=r<0?s:i;for(let a=0;a<Math.min(20,Math.abs(r));a++)e.push(o)}return e}var Ma={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 Ba(n,e){let t=new URLSearchParams({host:e.host,port:String(e.port)});return`${n}/ws?${t}`}var cs={0:1,1:2,2:4};function Ha(n){if(!("detail"in n))return{};let e=n.detail;if(!e||typeof e!="object")return{};let t={};for(let[r,s]of Object.entries(e))t[r]=s;return t}var Tt=class extends EventTarget{protocol="vnc";#e;#t;#n=null;#o=null;#r=!1;#s=null;constructor(e,t,r){super(),this.#t=r.credentials,this.#e=new mn(e,t,{credentials:{username:r.credentials.username,password:r.credentials.password},shared:!0,wsProtocols:os(r.credentials)}),this.#e._cursor?._canvas?.classList.add("remote-cursor-overlay"),this.#e.showDotCursor=!0,this.#e.resizeSession=r.allowRemoteResize,this.#e.clipViewport=!0,this.#e.scaleViewport=r.scaleViewport,this.#e.viewOnly=r.viewOnly,this.#e.qualityLevel=r.quality,this.#e.compressionLevel=r.compression,this.#a();for(let s of["connect","disconnect","credentialsrequired","desktopname","clipboard","bell"])this.#e.addEventListener(s,i=>{s==="credentialsrequired"&&this.#e.sendCredentials({username:this.#t.username,password:this.#t.password});let o=Ha(i);s==="disconnect"&&this.#s&&(o.code=this.#s.code,o.reason=this.#s.reason),this.dispatchEvent(new CustomEvent(s,{detail:o}))})}#a(){let e=()=>{let s=this.#e._sock?._websocket??null;if(!s||this.#n===s)return!!s;this.#n=s;let i=()=>{this.#r||s.readyState!==WebSocket.OPEN||(this.#r=!0,s.send(Ce))};return s.addEventListener("open",i),s.addEventListener("close",o=>{this.#s={code:o.code,reason:o.reason??""},this.#c()},!0),this.#o=setInterval(()=>{if(s.readyState===WebSocket.OPEN)try{s.send(_e);let o=this.#e._sock;o&&this.#e._rfbConnectionState==="connected"&&mn.messages.fbUpdateRequest(o,!0,0,0,1,1)}catch{}},25e3),i(),!0};if(e())return;let t=0,r=setInterval(()=>{(e()||++t>20)&&clearInterval(r)},25)}#c(){this.#o&&clearInterval(this.#o),this.#o=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.#c(),this.#e.disconnect()}sendKey(e,t,r){this.#e.sendKey(e,t,r)}sendClipboard(e){this.#e.clipboardPasteFrom(e)}releaseKeyboard(){this.#e.blur()}#i(e,t,r){let s=this.#e._sock;if(!s||this.#e._rfbConnectionState!=="connected"||this.#e.viewOnly)return!1;let i=this.#e._fbWidth||1,o=this.#e._fbHeight||1;return mn.messages.pointerEvent(s,Math.max(0,Math.min(i-1,Math.round(e))),Math.max(0,Math.min(o-1,Math.round(t))),r),!0}movePointer(e,t){return this.#i(e,t,0)}clickPointer(e,t,r=0){return this.#i(e,t,0)?(this.#i(e,t,cs[r]),this.#i(e,t,0),!0):!1}pointerButton(e,t,r=0,s=!0){return this.#i(e,t,s?cs[r]:0)}scrollPointer(e,t,r){for(let s of as(r))if(!this.#i(e,t,s)||!this.#i(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 r=t.codePointAt(0)??0,s=t===`
|
|
3
|
+
`?65293:t===" "?65289:r;this.#e.sendKey(s,null,!0),this.#e.sendKey(s,null,!1)}return!0}};function Ka({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 ls={protocol:"vnc",label:"VNC Client",defaultPort:Ve.vnc,dialog:Ma,buildUrl:Ba,createSession:(n,e,t)=>new Tt(n,e,t),describeState:n=>n instanceof Tt?n.describeState():{},describeDisconnect:Ka};var g={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},hs=1,us={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 Fa=new TextEncoder,Ga=new TextDecoder;function se(n){return Fa.encode(n)}function Ye(n){return Ga.decode(n)}function ie(...n){let e=n.reduce((s,i)=>s+i.length,0),t=new Uint8Array(e),r=0;for(let s of n)t.set(s,r),r+=s.length;return t}function $e(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e)}function yn(n){return $e(n).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}var I=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 r=new Uint8Array(new ArrayBuffer(t));r.set(this.bytes.subarray(0,this.offset)),this.bytes=r,this.view=new DataView(r.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}u64(e){let t=Math.floor(e);return this.u32(Math.floor(t/4294967296)).u32(t%4294967296)}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"?se(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 r=e.subarray(t);return r.length===0?this.u32(0):(r[0]??0)&128?(this.u32(r.length+1).u8(0),this.raw(r)):this.u32(r.length).raw(r)}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}u64(){return this.u32()*4294967296+this.u32()}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 Ye(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 gn(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 B=globalThis.crypto?.subtle,Wa={"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"}},En={"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 ds(n,e){if(!B)return!1;try{return await B.generateKey(n,!1,e),!0}catch{return!1}}var vt=null;async function ps(){if(vt)return vt;let[n,e]=await Promise.all([ds({name:"X25519"},["deriveBits"]),ds({name:"Ed25519"},["sign","verify"])]),t=[];n&&t.push("curve25519-sha256","curve25519-sha256@libssh.org"),t.push("ecdh-sha2-nistp256");let r=[];return e&&r.push("ssh-ed25519"),r.push("rsa-sha2-512","rsa-sha2-256","ecdsa-sha2-nistp256"),vt={kex:t,hostKey:r,x25519:n,ed25519:e},vt}async function fs(n){let e=Wa[n];if(!e)throw new Error(`SSH: unsupported key exchange ${n}`);if(e.type==="x25519"){let i=await B.generateKey({name:"X25519"},!1,["deriveBits"]),o=new Uint8Array(await B.exportKey("raw",i.publicKey));return{hash:e.hash,publicKey:o,async sharedSecret(a){if(a.length!==32)throw new Error("SSH: the host sent a malformed X25519 key.");let c=await B.importKey("raw",a,{name:"X25519"},!1,[]),l=new Uint8Array(await B.deriveBits({name:"X25519",public:c},i.privateKey,256));if(l.every(m=>m===0))throw new Error("SSH: the host sent a degenerate X25519 key.");return l}}}if(!e.curve)throw new Error(`SSH: ${n} names no curve to exchange over`);let t=e.curve,r=await B.generateKey({name:"ECDH",namedCurve:t},!1,["deriveBits"]),s=new Uint8Array(await B.exportKey("raw",r.publicKey));return{hash:e.hash,publicKey:s,async sharedSecret(i){let o=await B.importKey("raw",i,{name:"ECDH",namedCurve:t},!1,[]);return new Uint8Array(await B.deriveBits({name:"ECDH",public:o},r.privateKey,256))}}}function ms(n){return new O(n).string()}async function ys(n){let e=new Uint8Array(await B.digest("SHA-256",n));return`SHA256:${$e(e).replace(/=+$/,"")}`}async function Va(n,e){let t=En[n];if(!t)throw new Error(`SSH: unsupported host key algorithm ${n}`);let r=new O(e),s=r.string();if(s!==t.keyType)throw new Error(`SSH: the host key is a ${s} but was announced as ${n}.`);if(t.kind==="ed25519")return B.importKey("raw",r.stringBytes(),{name:"Ed25519"},!1,["verify"]);if(t.kind==="rsa"){let i=r.mpint(),o=r.mpint();return B.importKey("jwk",{kty:"RSA",n:yn(o),e:yn(i),ext:!0},{name:"RSASSA-PKCS1-v1_5",hash:t.hash},!1,["verify"])}return r.string(),B.importKey("raw",r.stringBytes(),{name:"ECDSA",namedCurve:t.curve},!1,["verify"])}function Ya(n,e){let t=new O(e),r=t.string();if(r!==n)throw new Error(`SSH: the host signed with ${r} after agreeing on ${n}.`);let s=t.stringBytes();if(En[n]?.kind!=="ecdsa")return s;let i=new O(s),o=i.mpint(),a=i.mpint();return ie(gn(o,32),gn(a,32))}async function gs({algorithm:n,keyBlob:e,signatureBlob:t,exchangeHash:r}){let s=En[n];if(!s)throw new Error(`SSH: unsupported host key algorithm ${n}`);let{kind:i,hash:o}=s,a=await Va(n,e),c=Ya(n,t),l=i==="ecdsa"?{name:"ECDSA",hash:o}:i==="rsa"?{name:"RSASSA-PKCS1-v1_5"}:{name:"Ed25519"};return B.verify(l,a,c,r)}async function Es({hash:n,clientVersion:e,serverVersion:t,clientKexInit:r,serverKexInit:s,hostKeyBlob:i,clientPublicKey:o,serverPublicKey:a,sharedSecret:c}){let l=new I(1024);return l.string(e),l.string(t),l.string(r),l.string(s),l.string(i),l.string(o),l.string(a),l.mpint(c),new Uint8Array(await B.digest(n,l.take()))}async function qe({hash:n,sharedSecret:e,exchangeHash:t,letter:r,sessionId:s,length:i}){let o=new I(64+t.length).mpint(e).take(),a=ie(o,t,new Uint8Array([r.charCodeAt(0)]),s),c=new Uint8Array(await B.digest(n,a));for(;c.length<i;){let l=new Uint8Array(await B.digest(n,ie(o,t,c)));c=ie(c,l)}return c.subarray(0,i)}var ws="SSH-2.0-CloudflareGateway_1.0",bn={"aes256-gcm@openssh.com":{keyLength:32},"aes128-gcm@openssh.com":{keyLength:16}},Ct=Object.keys(bn),As=["hmac-sha2-256","hmac-sha2-512"],bs=["none"],Xe=16,wn=16,Ss=12,An=8,Ts=4,xs=262144,$a=8192,Sn=globalThis.crypto?.subtle;function Rt(n,e){return n.find(t=>e.includes(t))||null}var _t=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 r=await Sn.importKey("raw",e,{name:"AES-GCM"},!1,["encrypt","decrypt"]);return new n(r,t)}nextIv(){let e=ie(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}},Lt=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;drainChain;constructor(e,{verifyHost:t,log:r,openTransport:s}={}){super(),this.url=e,this.verifyHost=t||(()=>!0),this.log=r||(()=>{}),this.openTransport=s||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=void 0,this.bytesSent=0,this.bytesReceived=0}connect(){let e=this.openTransport?this.openTransport(this.url):new WebSocket(this.url);this.socket=e,e.binaryType="arraybuffer",e.addEventListener("open",()=>{e.send(Ce),this.#t(se(`${ws}\r
|
|
4
|
+
`)),this.keepaliveTimer=setInterval(()=>{if(this.socket?.readyState===WebSocket.OPEN&&(this.socket.send(_e),this.sessionId))try{this.#l(new I(64).u8(g.GLOBAL_REQUEST).string("keepalive@openssh.com").u8(1).take())}catch{}},25e3)}),e.addEventListener("message",t=>{let{data:r}=t;typeof r!="string"&&this.#n(new Uint8Array(r))}),e.addEventListener("close",t=>{let r=t;this.#e({clean:r.code===1e3,code:r.code,message:r.reason||(r.code===1006?"The gateway rejected or could not reach this SSH target. Confirm that SSH is published for this host.":"")})}),e.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 r=new I(64).u8(g.DISCONNECT).u32(11).string(e).string("").take();this.#l(r)}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=void 0,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))}#n(e){this.bytesReceived+=e.length,this.buffer=this.buffer.length?ie(this.buffer,e):e,this.drainChain=(this.drainChain||Promise.resolve()).then(()=>this.#o()).catch(t=>this.fail(t))}async#o(){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.#s();if(!t)return;this.#i(t);continue}let e=this.#a();if(!e)return;this.#i(await this.#c(e))}}#r(){for(;;){let e=this.buffer.indexOf(10);if(e===-1){if(this.buffer.length>$a)throw new Error("SSH: the host sent no version line.");return!1}let t=e;t>0&&this.buffer[t-1]===13&&t--;let r=new TextDecoder().decode(this.buffer.subarray(0,t));if(this.buffer=this.buffer.subarray(e+1),!r.startsWith("SSH-")){r.trim()&&this.greeting.push(r);continue}if(!r.startsWith("SSH-2.0-")&&!r.startsWith("SSH-1.99-"))throw new Error(`SSH: this host speaks ${r.split("-").slice(0,2).join("-")}, which is too old.`);return this.serverVersion=r,this.log("version",{server:r,greeting:this.greeting}),this.dispatchEvent(new CustomEvent("greeting",{detail:{lines:this.greeting.slice()}})),this.#d(),!0}}#s(){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>xs)throw new Error("SSH: the host sent a packet of an impossible size.");if(this.buffer.length<4+t)return null;let r=this.buffer[4];if(r+1>t)throw new Error("SSH: a packet claimed more padding than it had.");let s=this.buffer.slice(5,4+t-r);return this.buffer=this.buffer.subarray(4+t),this.receiveSequence=this.receiveSequence+1>>>0,s}#a(){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<Xe||t%Xe!==0||t>xs)throw new Error("SSH: the host sent a packet of an impossible size.");let r=4+t+wn;if(this.buffer.length<r)return null;let s=this.buffer.slice(0,r);return this.buffer=this.buffer.subarray(r),s}async#c(e){let t=this.incoming;if(!t)throw new Error("SSH: a packet arrived before the cipher was installed.");let r;try{r=new Uint8Array(await Sn.decrypt({name:"AES-GCM",iv:t.nextIv(),additionalData:e.subarray(0,4),tagLength:wn*8},t.key,e.subarray(4)))}catch{throw new Error("SSH: a packet failed its integrity check, so the session was dropped.")}let s=r[0];if(s+1>r.length)throw new Error("SSH: a packet claimed more padding than it had.");return this.receiveSequence=this.receiveSequence+1>>>0,r.slice(1,r.length-s)}#i(e){if(e.length===0)return;let t=e[0];switch(t){case g.DISCONNECT:{let r=new O(e,1),s=r.u32(),o=r.string()||us[s]||`reason ${s}`;this.dispatchEvent(new CustomEvent("hostdisconnect",{detail:{code:s,reason:o}})),this.#e({clean:s===11,code:1e3,message:o});try{this.socket?.close(1e3,"Host disconnected")}catch{}return}case g.IGNORE:case g.UNIMPLEMENTED:case g.EXT_INFO:return;case g.DEBUG:{let r=new O(e,1),s=r.boolean(),i=r.string();this.log("debug",{message:i,alwaysDisplay:s}),s&&this.dispatchEvent(new CustomEvent("banner",{detail:{text:`${i}\r
|
|
5
|
+
`}}));return}case g.KEXINIT:this.#g(e);return;case g.NEWKEYS:this.#A();return;case g.GLOBAL_REQUEST:{let r=new O(e,1);r.string(),r.boolean()&&this.#l(new Uint8Array([g.REQUEST_FAILURE]));return}case g.REQUEST_SUCCESS:case g.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.#l(e),!0)}#l(e){if(!(this.closed||this.socket?.readyState!==WebSocket.OPEN)){if(!this.outgoing){this.#t(Xa(e)),this.sendSequence=this.sendSequence+1>>>0;return}this.#h(e)}}async#h(e){let t=this.encryptChain||Promise.resolve();return this.encryptChain=t.then(async()=>{if(this.closed||!this.outgoing)return;let r=qa(e.length),s=new Uint8Array(1+e.length+r);s[0]=r,s.set(e,1),crypto.getRandomValues(s.subarray(1+e.length));let i=new I(4).u32(s.length).take(),o=new Uint8Array(await Sn.encrypt({name:"AES-GCM",iv:this.outgoing.nextIv(),additionalData:i,tagLength:wn*8},this.outgoing.key,s));this.#t(ie(i,o)),this.sendSequence=this.sendSequence+1>>>0}).catch(r=>this.fail(r)),this.encryptChain}async#d(){if(!this.kex?.running){this.kex={running:!0,clientKexInit:null,pending:null,inbox:[]};try{let e=await ps(),t=za(e);this.kex.clientKexInit=t,this.#l(t);let r=this.pendingServerKexInit||await this.#p(g.KEXINIT);this.pendingServerKexInit=null,await this.#w(e,t,r)}catch(e){this.fail(e)}}}async#g(e){if(this.kex?.running){this.#u(e);return}this.log("rekey",{reason:"the host asked for new keys"}),this.pendingServerKexInit=e,await this.#d()}#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)}}#p(e){let t=this.kex;if(!t)throw new Error("SSH: a key-exchange packet was awaited outside a key exchange.");return new Promise((r,s)=>{let i=a=>{if(e!==void 0&&a[0]!==e){s(new Error(`SSH: expected message ${e} during key exchange but got ${a[0]}.`));return}r(a)},o=t.inbox.shift();if(o){i(o);return}t.pending=a=>{t.pending=null,i(a)}})}async#w(e,t,r){let s=Qa(r),i=Rt(e.kex,s.kex),o=Rt(e.hostKey,s.hostKey),a=Rt(Ct,s.cipherClientToServer),c=Rt(Ct,s.cipherServerToClient);if(!i)throw new Error(`SSH: no shared key exchange method. The host offers ${s.kex.join(", ")}.`);if(!o)throw new Error(`SSH: no host key type this browser can verify. The host offers ${s.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 ${s.cipherServerToClient.join(", ")}.`);this.log("negotiated",{kex:i,hostKey:o,cipher:c,rekey:!!this.sessionId});let l=await fs(i);this.#l(new I(128).u8(g.KEX_ECDH_INIT).string(l.publicKey).take());let m=new O(await this.#p(g.KEX_ECDH_REPLY),1),E=m.stringBytes(),x=m.stringBytes(),p=m.stringBytes(),y=await l.sharedSecret(x),h=await Es({hash:l.hash,clientVersion:ws,serverVersion:this.serverVersion,clientKexInit:t,serverKexInit:r,hostKeyBlob:E,clientPublicKey:l.publicKey,serverPublicKey:x,sharedSecret:y});if(!await gs({algorithm:o,keyBlob:E,signatureBlob:p,exchangeHash:h}))throw new Error("SSH: the host key signature is invalid, so this is not the machine it claims to be.");let w=await ys(E);if(!this.sessionId){if(!await this.verifyHost({fingerprint:w,keyType:ms(E),algorithm:o}))throw new Error("SSH: the host key was not accepted, so the connection was stopped.");this.sessionId=h}this.#l(new Uint8Array([g.NEWKEYS])),await this.#p(g.NEWKEYS);let v={hash:l.hash,sharedSecret:y,exchangeHash:h,sessionId:this.sessionId},u=bn[a],d=bn[c];if(!u||!d)throw new Error(`SSH: negotiated a cipher this client does not implement (${a}, ${c})`);let[b,C,R,N]=await Promise.all([qe({...v,letter:"A",length:Ss}),qe({...v,letter:"B",length:Ss}),qe({...v,letter:"C",length:u.keyLength}),qe({...v,letter:"D",length:d.keyLength})]);this.outgoing=await _t.create(R,b),this.incoming=await _t.create(N,C),this.kex&&(this.kex.running=!1),this.releaseNewKeys?.(),this.releaseNewKeys=null;let _=this.kexQueue;this.kexQueue=[];for(let W of _)this.#l(W);let U=!this.established;this.established=!0,this.dispatchEvent(new CustomEvent("keys",{detail:{fingerprint:w,kexAlgorithm:i,hostKeyAlgorithm:o,cipher:c,firstTime:U}}))}#A(){this.kex&&(this.newKeysBarrier=new Promise(e=>{this.releaseNewKeys=e}),this.#u(new Uint8Array([g.NEWKEYS])))}};function qa(n){let e=1+n,t=Xe-e%Xe;for(;t<Ts;)t+=Xe;return t}function Xa(n){let e=5+n.length,t=An-e%An;t<Ts&&(t+=An);let r=new I(e+t);r.u32(1+n.length+t),r.u8(t),r.raw(n);let s=r.take(),i=new Uint8Array(t);return crypto.getRandomValues(i),ie(s,i)}function za(n){let e=new Uint8Array(16);crypto.getRandomValues(e);let t=new I(512);return t.u8(g.KEXINIT).raw(e),t.nameList(n.kex),t.nameList(n.hostKey),t.nameList(Ct),t.nameList(Ct),t.nameList(As),t.nameList(As),t.nameList(bs),t.nameList(bs),t.nameList([]),t.nameList([]),t.boolean(!1),t.u32(0),t.take()}function Qa(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 th=22,ze="ssh-connection",ja="xterm-256color",Qe=2*1024*1024,xn=32*1024,Za=Qe/2,Ja=new Uint8Array([0]),ec=2e4,tc=5*6e4,nc=60*6e4,je=new Uint8Array(0);function rc(n){return`'${String(n).replace(/'/g,"'\\''")}'`}function vs(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 sc=/is not recognized as an internal or external command|command not found|not recognized as the name of a cmdlet|CommandNotFoundException/i;function ic(n,e,t){if(n==="cmd")return`echo.&echo CCB${t}&${e}&call echo.CCE${t} %^ERRORLEVEL%\r`;if(n==="powershell"){let r=$e(se(e));return`Write-Output ""; Write-Output ("CCB" + "${t}"); $__ccCode = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${r}')); $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 ${rc(e)}; __cc=$?; printf '\\n%s%s %s\\n' 'CCE' '${t}' "$__cc"\r`}function Le(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 oc(n,e){let t=n.displayFilter;if(!t)return e;t.pending+=Ye(e);let r="";if(t.stage==="before"){let i=t.pending.indexOf(t.begin);if(i===-1)return je;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 r=t.pending,t.pending="",r?se(r):je;r=t.pending.slice(0,i),t.pending=t.pending.slice(i),t.stage="closing"}let s=t.pending.indexOf(`
|
|
7
|
+
`);return s!==-1&&(r+=t.pending.slice(s+1),n.displayFilter=null),r?se(r):je}function ac(n,e){let t=e.replace(/\r?\n/g," \u23CE ").trimEnd();t&&n.dispatchEvent(new CustomEvent("data",{detail:{bytes:je,display:se(`\x1B[1m${t}\x1B[0m\r
|
|
8
|
+
`),isStderr:!1}}))}function cc(n){let e=n.displayFilter;n.displayFilter=null,!(!e||e.stage!=="before"||!e.pending)&&n.dispatchEvent(new CustomEvent("data",{detail:{bytes:je,display:se(e.pending),isStderr:!1}}))}var Rs=class extends EventTarget{options;username;password;identities;requestInput;canAsk;columns;rows;subsystem;channelId;remoteChannelId;remoteWindow;remoteMaxPacket;localWindow;pendingWrites;shellOpen;commandInFlight;displayFilter;readySignaled=!1;powerShellAttempted;powerShellTimer;shellFamily="";promptTail;exitStatus;exitSignal;authMethods;triedKeys;passwordRejected;closed;waiters;transport;fingerprint;lastMessage;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.subsystem=t.subsystem||"",this.channelId=0,this.remoteChannelId=null,this.remoteWindow=0,this.remoteMaxPacket=xn,this.localWindow=Qe,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 Lt(e,{verifyHost:t.verifyHost||(async()=>!0),openTransport:t.openTransport||null,log:t.log??((r,s)=>console.info(`[SSH] ${r}`,s))}),this.transport.addEventListener("packet",r=>{this.#s(r.detail.type,r.detail.payload)}),this.transport.addEventListener("greeting",r=>{for(let s of r.detail.lines)this.#t(`${s}\r
|
|
9
|
+
`)}),this.transport.addEventListener("banner",r=>this.#t(r.detail.text)),this.transport.addEventListener("keys",r=>{this.fingerprint=r.detail.fingerprint,this.#e("secured",`Host key ${r.detail.fingerprint} verified.`),this.dispatchEvent(new CustomEvent("secure",{detail:r.detail})),r.detail.firstTime&&this.#d()}),this.transport.addEventListener("hostdisconnect",r=>{this.lastMessage=r.detail.reason}),this.transport.addEventListener("error",r=>{this.lastMessage=r.detail.message,this.dispatchEvent(new CustomEvent("error",{detail:r.detail}))}),this.transport.addEventListener("close",r=>{this.closed||(this.closed=!0,clearTimeout(this.powerShellTimer??void 0),this.#r(r.detail.message||"The SSH connection closed."),this.dispatchEvent(new CustomEvent("close",{detail:{...r.detail,message:r.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??void 0),this.shellOpen&&this.remoteChannelId!==null&&this.transport.send(new I(8).u8(g.CHANNEL_CLOSE).u32(this.remoteChannelId).take()),this.transport.disconnect("Closed by the user"))}write(e){let t=typeof e=="string"?se(e):e;t.length&&(this.pendingWrites.push(t),this.#h())}runCommand(e,{startMs:t=ec,idleMs:r=tc,maxMs:s=nc}={}){let i=(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(E=>E.toString(16).padStart(2,"0")).join(""),a=`CCB${o}`,c=`CCE${o}`,l=this.shellFamily||"posix";this.commandInFlight=!0;let m=Date.now();return this.displayFilter={begin:a,end:c,stage:"before",pending:""},ac(this,i),this.dispatchEvent(new CustomEvent("command",{detail:{phase:"start",id:o,command:i}})),new Promise((E,x)=>{let p="",y=!1,h,A,w,v=_=>{clearTimeout(h),clearTimeout(A),clearTimeout(w),this.removeEventListener("data",R),this.removeEventListener("close",N),this.commandInFlight=!1,cc(this),_()},u=_=>v(()=>{this.dispatchEvent(new CustomEvent("command",{detail:{phase:"end",id:o,command:i,exitStatus:_.exitStatus,timedOut:_.timedOut,started:_.started!==!1,reason:_.reason,durationMs:_.durationMs}})),E(_)}),d=_=>v(()=>{this.dispatchEvent(new CustomEvent("command",{detail:{phase:"end",id:o,command:i,exitStatus:null,timedOut:!1,started:y,durationMs:Date.now()-m,error:_ instanceof Error?_.message:String(_)}})),x(_)}),b=()=>{let _=p.indexOf(a);return _===-1?"":Le(p.slice(_+a.length)).replace(/^\r?\n/,"").replace(/\s+$/,"")},C=_=>{this.write(""),u({output:b(),exitStatus:null,timedOut:!0,started:y,reason:_,durationMs:Date.now()-m})},R=_=>{p+=Ye(_.detail.bytes),!y&&p.indexOf(a)!==-1&&(y=!0,clearTimeout(h),h=void 0),y&&(clearTimeout(A),A=setTimeout(()=>C("idle"),r));let U=p.indexOf(`${c} `);if(U===-1){if(!y&&sc.test(Le(p))){let pe=vs(Le(p))||"cmd",Y=l!==pe;this.shellFamily=pe,d(new Error(Y?`This shell is ${pe==="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: ${Le(p).split(`
|
|
10
|
+
`).filter(Boolean).pop()||"no detail"}`))}return}let W=p.slice(U),ye=parseInt(W.slice(c.length+1).trim(),10),de=p.indexOf(a),Ie=de===-1?p.slice(0,U):p.slice(de+a.length,U);u({output:Le(Ie).replace(/^\r?\n/,"").replace(/\s+$/,""),exitStatus:Number.isInteger(ye)?ye:null,timedOut:!1,started:!0,durationMs:Date.now()-m})},N=()=>d(new Error("The SSH session closed while the command was running."));this.addEventListener("data",R),this.addEventListener("close",N),h=setTimeout(()=>C("start"),t),A=setTimeout(()=>C("idle"),r),w=setTimeout(()=>C("max"),s),this.write(ic(l,i,o))})}resize(e,t){let r=Math.max(1,Math.floor(e)),s=Math.max(1,Math.floor(t));r===this.columns&&s===this.rows||(this.columns=r,this.rows=s,!(!this.shellOpen||this.remoteChannelId===null)&&this.transport.send(new I(64).u8(g.CHANNEL_REQUEST).u32(this.remoteChannelId).string("window-change").boolean(!1).u32(r).u32(s).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}}))}#n(...e){return new Promise((t,r)=>{for(let s of e)this.waiters.set(s,{resolve:t,reject:r})})}#o(e,t){let r=this.waiters.get(e);return r?(this.waiters.clear(),r.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 r of t)r.reject(new Error(e))}#s(e,t){if(!this.#o(e,t))switch(e){case g.USERAUTH_BANNER:this.#t(new O(t,1).string().replaceAll(`
|
|
11
11
|
`,`\r
|
|
12
|
-
`));return;case
|
|
12
|
+
`));return;case g.CHANNEL_DATA:{let r=new O(t,1);r.u32(),this.#l(r.stringBytes());return}case g.CHANNEL_EXTENDED_DATA:{let r=new O(t,1);r.u32();let s=r.u32(),i=r.stringBytes();this.#l(i,s===hs);return}case g.CHANNEL_WINDOW_ADJUST:{let r=new O(t,1);r.u32(),this.remoteWindow+=r.u32(),this.#h();return}case g.CHANNEL_REQUEST:{let r=new O(t,1);r.u32();let s=r.string(),i=r.boolean();s==="exit-status"&&(this.exitStatus=r.u32()),s==="exit-signal"&&(this.exitSignal=r.string()),i&&this.remoteChannelId!==null&&this.transport.send(new I(8).u8(g.CHANNEL_SUCCESS).u32(this.remoteChannelId).take());return}case g.CHANNEL_EOF:return;case g.CHANNEL_CLOSE:this.shellOpen=!1,this.#e("closed","The remote shell ended."),this.transport.disconnect("Shell closed");return;default:return}}#a(e){this.promptTail=(this.promptTail+Le(Ye(e))).slice(-400);let t=vs(this.promptTail);if(t){if(t==="cmd"&&!this.powerShellAttempted){this.#c();return}t==="cmd"&&this.powerShellAttempted&&!this.readySignaled||(this.shellFamily=t,t==="powershell"&&!this.readySignaled&&this.#i("Connected \xB7 PowerShell"))}}#c(){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.#i("Connected \xB7 PowerShell"))},2e3))}#i(e="Connected."){clearTimeout(this.powerShellTimer??void 0),this.powerShellTimer=null,this.readySignaled=!0,this.#e("ready",e),this.dispatchEvent(new CustomEvent("ready",{detail:{fingerprint:this.fingerprint,shellFamily:this.shellFamily||"posix"}}))}#l(e,t=!1){if(!e.length||(this.subsystem||this.#a(e),this.dispatchEvent(new CustomEvent("data",{detail:{bytes:e,display:oc(this,e),isStderr:t}})),this.localWindow-=e.length,this.localWindow>Za||this.remoteChannelId===null))return;let r=Qe-this.localWindow;this.localWindow=Qe,this.transport.send(new I(16).u8(g.CHANNEL_WINDOW_ADJUST).u32(this.remoteChannelId).u32(r).take())}#h(){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 r=e.length<=t?e:e.subarray(0,t);r.length===e.length?this.pendingWrites.shift():this.pendingWrites[0]=e.subarray(r.length),this.remoteWindow-=r.length,this.transport.send(new I(r.length+16).u8(g.CHANNEL_DATA).u32(this.remoteChannelId).string(r).take())}}async#d(){try{if(this.#e("authenticating",`Authenticating as ${this.username}\u2026`),this.transport.send(new I(32).u8(g.SERVICE_REQUEST).string("ssh-userauth").take()),await this.#n(g.SERVICE_ACCEPT),await this.#g())return await this.#y();if(this.authMethods.includes("publickey")){for(let e of await this.#p())if(await this.#w(e))return await this.#y()}if(this.authMethods.includes("password")&&this.password){if(await this.#u(this.password))return await this.#y();this.passwordRejected=!0}if(this.authMethods.includes("keyboard-interactive")){if(await this.#A())return await this.#y();if(this.canAsk&&this.authMethods.includes("keyboard-interactive")&&await this.#A({usePassword:!1}))return await this.#y()}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 await this.#y()}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#g(){return this.transport.send(new I(64).u8(g.USERAUTH_REQUEST).string(this.username).string(ze).string("none").take()),this.#b()}async#u(e){return this.transport.send(new I(128).u8(g.USERAUTH_REQUEST).string(this.username).string(ze).string("password").boolean(!1).string(e).take()),this.#b()}async#p(){let e=this.identities,t=typeof e=="function"?await e():e;return this.identities=t,t}async#w(e){let t=this.transport.sessionId;if(!t)throw new Error("SSH: no session identifier to sign against.");for(let r of e.algorithms){this.#e("authenticating",`Offering ${e.comment||e.keyType}\u2026`),this.transport.send(new I(e.keyBlob.length+128).u8(g.USERAUTH_REQUEST).string(this.username).string(ze).string("publickey").boolean(!1).string(r).string(e.keyBlob).take());let s=await this.#n(g.USERAUTH_PK_OK,g.USERAUTH_FAILURE,g.USERAUTH_SUCCESS);if(s.type===g.USERAUTH_SUCCESS)return!0;if(s.type===g.USERAUTH_FAILURE){if(this.#m(s.payload),!this.authMethods.includes("publickey"))return!1;continue}let i=new I(e.keyBlob.length+128).u8(g.USERAUTH_REQUEST).string(this.username).string(ze).string("publickey").boolean(!0).string(r).string(e.keyBlob).take(),o=await e.sign(new I(i.length+t.length+8).string(t).raw(i).take(),r);return this.transport.send(new I(i.length+o.length+8).raw(i).string(o).take()),await this.#b()?!0:(this.triedKeys.push(e.comment||e.keyType),!1)}return this.triedKeys.push(e.comment||e.keyType),!1}async#A({usePassword:e=!0}={}){this.passwordRejected&&(e=!1),this.transport.send(new I(96).u8(g.USERAUTH_REQUEST).string(this.username).string(ze).string("keyboard-interactive").string("").string("").take());let t=!e,r=0;for(;;){let{type:s,payload:i}=await this.#n(g.USERAUTH_SUCCESS,g.USERAUTH_FAILURE,g.USERAUTH_INFO_REQUEST);if(s===g.USERAUTH_SUCCESS)return!0;if(s===g.USERAUTH_FAILURE)return this.#m(i),!1;let o=new O(i,1),a=o.string(),c=o.string();o.string();let l=o.u32();if(a&&this.#t(`${a.replaceAll(`
|
|
13
13
|
`,`\r
|
|
14
14
|
`)}\r
|
|
15
15
|
`),c&&this.#t(`${c.replaceAll(`
|
|
16
16
|
`,`\r
|
|
17
17
|
`)}\r
|
|
18
|
-
`),++
|
|
18
|
+
`),++r>3)return!1;let m=[],E=!1;for(let p=0;p<l;p++){let y=o.string(),h=o.boolean();if(!h&&/pass(word|phrase)/i.test(y)&&this.password&&!t){t=!0,E=!0,m.push(this.password);continue}let w=this.canAsk?await this.requestInput({prompt:y,echo:h}):"";w&&(E=!0),m.push(w)}if(l>0&&!E)return!1;let x=new I(256).u8(g.USERAUTH_INFO_RESPONSE).u32(m.length);for(let p of m)x.string(p);this.transport.send(x.take())}}async#b(){let{type:e,payload:t}=await this.#n(g.USERAUTH_SUCCESS,g.USERAUTH_FAILURE);return e===g.USERAUTH_SUCCESS?!0:(this.#m(t),!1)}#m(e){let t=new O(e,1);this.authMethods=t.nameList(),t.boolean()&&this.#t(`\r
|
|
19
19
|
One factor accepted; the host wants another.\r
|
|
20
|
-
`)}async#
|
|
21
|
-
`)}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
|
|
20
|
+
`)}async#y(){this.#e("opening",this.subsystem?`Starting the ${this.subsystem} subsystem\u2026`:"Starting the remote shell\u2026"),this.transport.send(new I(64).u8(g.CHANNEL_OPEN).string("session").u32(this.channelId).u32(Qe).u32(xn).take());let e=await this.#n(g.CHANNEL_OPEN_CONFIRMATION,g.CHANNEL_OPEN_FAILURE);if(e.type===g.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(),xn)),this.subsystem){if(this.transport.send(new I(64).u8(g.CHANNEL_REQUEST).u32(this.remoteChannelId).string("subsystem").boolean(!0).string(this.subsystem).take()),(await this.#n(g.CHANNEL_SUCCESS,g.CHANNEL_FAILURE)).type===g.CHANNEL_FAILURE)throw new Error(`SSH: the host has no ${this.subsystem} subsystem (on OpenSSH that is the \`Subsystem ${this.subsystem}\` line in sshd_config).`);this.shellOpen=!0,this.#h(),this.#i(`Connected \xB7 ${this.subsystem}`);return}if(this.transport.send(new I(128).u8(g.CHANNEL_REQUEST).u32(this.remoteChannelId).string("pty-req").boolean(!0).string(ja).u32(this.columns).u32(this.rows).u32(0).u32(0).string(Ja).take()),(await this.#n(g.CHANNEL_SUCCESS,g.CHANNEL_FAILURE)).type===g.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 I(32).u8(g.CHANNEL_REQUEST).u32(this.remoteChannelId).string("shell").boolean(!0).take()),(await this.#n(g.CHANNEL_SUCCESS,g.CHANNEL_FAILURE)).type===g.CHANNEL_FAILURE)throw new Error("SSH: the host refused to start a shell for this account.");this.shellOpen=!0,this.#h(),this.options.preferredShell==="powershell"?this.#c():this.#i()}};import{Terminal as lc}from"@xterm/xterm";import{FitAddon as hc}from"@xterm/addon-fit";import uc from"@xterm/xterm/css/xterm.css";var Cs="xterm-styles",Tn=80,vn=13,dc=7;function pc(){if(document.getElementById(Cs))return;let n=document.createElement("style");n.id=Cs,n.textContent=uc,document.head.appendChild(n)}var fc={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"},_s=class{container;terminal;fitAddon;observer;dataHandler=null;fitting=!1;constructor(e){pc(),this.container=e,this.terminal=new lc({allowProposedApi:!0,convertEol:!1,cursorBlink:!0,cursorStyle:"bar",drawBoldTextInBrightColors:!0,fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace',fontSize:vn,lineHeight:1.25,letterSpacing:0,macOptionIsMeta:!0,minimumContrastRatio:1.5,scrollback:1e4,theme:fc}),this.fitAddon=new hc,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:r})=>e(t,r))}write(e){this.terminal.write(e)}notice(e,t="info"){let r={info:"\x1B[38;5;245m",good:"\x1B[38;5;114m",bad:"\x1B[38;5;203m"}[t]||"";this.terminal.write(`${r}${e}\x1B[0m\r
|
|
21
|
+
`)}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 r=this.fitAddon.proposeDimensions();if(!r||!(r.cols>0))break;let s=this.terminal.options.fontSize||vn,i=Math.min(vn,Math.max(dc,Math.floor(s*r.cols/Tn)));if(i===s)break;this.terminal.options.fontSize=i}this.fitAddon.fit();let e=this.terminal.cols<Tn;this.container.classList.toggle("is-narrow",e),e&&this.terminal.resize(Tn,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(r=>{let s=this.dataHandler,i="";this.terminal.write(e.replaceAll(`
|
|
22
22
|
`,`\r
|
|
23
23
|
`)),this.dataHandler=o=>{for(let a of o){let c=a.charCodeAt(0);if(c===13||c===10){this.terminal.write(`\r
|
|
24
|
-
`),this.dataHandler=r
|
|
25
|
-
`),this.dataHandler=r
|
|
24
|
+
`),this.dataHandler=s,r(i);return}if(c===127||c===8){if(i.length===0)continue;i=i.slice(0,-1),t&&this.terminal.write("\b \b");continue}if(c===3){this.terminal.write(`^C\r
|
|
25
|
+
`),this.dataHandler=s,r("");return}c<32||(i+=a,t&&this.terminal.write(a))}}})}destroy(){this.observer?.disconnect(),this.terminal.dispose()}};var Ls={vnc:ls,rdp:ss};function mc(n){return Ls[n]??Ls.vnc}function lh(n,e,t){if(t)return t;let r=n.close?.code,s=n.close?.reason.trim()??"",i=r?` (WebSocket ${r}${s?`: ${s}`:""})`:"",o={...r===void 0?{}:{code:r},reason:s,suffix:i},a=mc(n.protocol),c=a.describeDisconnect(o);if(c)return c;let l=a.protocol.toUpperCase();return/tcp (reached )?eof/i.test(s)?`The ${l} host accepted the connection and then closed it${i}. Check its remote-access permissions and the account name.`:r===1006?"The connection was interrupted before a close reason arrived (WebSocket 1006). This can happen during a deployment or a brief network change. Automatic reconnect did not restore the session; reconnect once, then check Worker live logs if it repeats.":s?`The remote session ended${i}.`:e?`The remote server closed the session cleanly${i||" (no reason supplied)"}.`:`The ${l} negotiation failed${i||" before the server supplied a close reason"}.`}export{tc as COMMAND_IDLE_MS,nc as COMMAND_MAX_MS,ec as COMMAND_START_MS,th as DEFAULT_PORT,Ls as DRIVERS,Rs as SshSession,_s as SshTerminal,mc as driverFor,lh as explainDisconnect,ic as frameCommand};
|