ai-remote 0.4.3 → 0.4.4
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/dist/index.js +1 -1
- package/dist/{protocols/index.d.ts → protocols.d.ts} +2 -0
- package/dist/protocols.js +24 -0
- package/package.json +15 -10
- package/dist/protocols/index.js +0 -3
- package/dist/protocols/ssh/session.d.ts +0 -66
- package/dist/protocols/ssh/session.js +0 -17
- package/dist/protocols/ssh/terminal.d.ts +0 -46
- package/dist/protocols/ssh/terminal.js +0 -6
- package/dist/protocols/types.d.ts +0 -127
- package/dist/protocols/types.js +0 -0
- package/dist/shared/connection.d.ts +0 -81
- package/dist/shared/connection.js +0 -1
- package/dist/shared/device.d.ts +0 -26
- package/dist/shared/device.js +0 -0
- package/dist/shared/hosts.d.ts +0 -63
- package/dist/shared/hosts.js +0 -1
- package/dist/shared/icons.d.ts +0 -46
- package/dist/shared/icons.js +0 -1
- package/dist/shared/protocol.d.ts +0 -28
- package/dist/shared/protocol.js +0 -1
- package/dist/shared/signals.d.ts +0 -37
- package/dist/shared/signals.js +0 -1
package/dist/protocols/index.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
function rt(n){return new Uint8Array(n)}var p=class{bytes;view;offset=0;constructor(e=512){this.bytes=rt(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=rt(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 g(...n){let e=n.reduce((r,i)=>r+i.length,0),t=rt(e),s=0;for(let r of n)t.set(r,s),s+=r.length;return t}var As=[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],xs=new Uint32Array(Array.from({length:64},(n,e)=>Math.floor(Math.abs(Math.sin(e+1))*4294967296)));function ve(n,e){return n<<e|n>>>32-e}function j(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,d=new Uint32Array(16),E=new DataView(s.buffer,s.byteOffset,s.byteLength);for(let S=0;S<t;S++){for(let R=0;R<16;R++)d[R]=E.getUint32(S*64+R*4,!0);let f=i,l=o,A=a,x=c;for(let R=0;R<64;R++){let h,u;R<16?(h=l&A|~l&x,u=R):R<32?(h=x&l|~x&A,u=(5*R+1)%16):R<48?(h=l^A^x,u=(3*R+5)%16):(h=A^(l|~x),u=7*R%16);let w=x;x=A,A=l;let b=f+h+xs[R]+d[u]|0;l=l+ve(b,As[R])|0,f=w}i=i+f|0,o=o+l|0,a=a+A|0,c=c+x|0}let y=new Uint8Array(16),m=new DataView(y.buffer);return m.setUint32(0,i>>>0,!0),m.setUint32(4,o>>>0,!0),m.setUint32(8,a>>>0,!0),m.setUint32(12,c>>>0,!0),y}function ot(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,d=3285377520,E=new Uint32Array(80),y=new DataView(s.buffer,s.byteOffset,s.byteLength);for(let f=0;f<t;f++){for(let u=0;u<16;u++)E[u]=y.getUint32(f*64+u*4);for(let u=16;u<80;u++)E[u]=ve(E[u-3]^E[u-8]^E[u-14]^E[u-16],1);let l=i,A=o,x=a,R=c,h=d;for(let u=0;u<80;u++){let w,b;u<20?(w=A&x|~A&R,b=1518500249):u<40?(w=A^x^R,b=1859775393):u<60?(w=A&x|A&R|x&R,b=2400959708):(w=A^x^R,b=3395469782);let _=ve(l,5)+w+h+b+E[u]|0;h=R,R=x,x=ve(A,30),A=l,l=_}i=i+l|0,o=o+A|0,a=a+x|0,c=c+R|0,d=d+h|0}let m=new Uint8Array(20),S=new DataView(m.buffer);return[i,o,a,c,d].forEach((f,l)=>S.setUint32(l*4,f>>>0)),m}function $(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 W(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 it(n){let e=0n;for(let t=n.length-1;t>=0;t--)e=e<<8n|BigInt(n[t]);return e}function gs(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 Bt(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 Kt(n,e,t){let s=it(e),r=it(t),i=it(n);if(i>=s)throw new Error("RDP: client random is larger than the server RSA modulus");return gs(Bt(i,r,s),e.length)}function Wt(n,e,t){let s=S=>{let f=0n;for(let l of S)f=f<<8n|BigInt(l);return f},r=s(e),i=s(t),o=e.length;if(n.length>o-11)throw new Error("TLS: RSA message is too long for this key");let a=new Uint8Array(o);a[0]=0,a[1]=2;let c=o-n.length-3,d=new Uint8Array(c);crypto.getRandomValues(d);for(let S=0;S<c;S++){for(;d[S]===0;)d[S]=Math.max(1,crypto.getRandomValues(new Uint8Array(1))[0]);a[2+S]=d[S]}a[2+c]=0,a.set(n,3+c);let E=Bt(s(a),i,r),y=new Uint8Array(o),m=E;for(let S=o-1;S>=0;S--)y[S]=Number(m&0xffn),m>>=8n;return y}var Vt=new Uint8Array(40).fill(54),Yt=new Uint8Array(48).fill(92),Q={NONE:0,BIT_40:1,BIT_128:2,BIT_56:8,FIPS:16};function q(...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 ce(n,e,t,s){return j(q(n,ot(q(e,n,t,s))))}function Ft(n,e,t){return j(q(n,e,t))}var Ss=new Uint8Array([65]),Ts=new Uint8Array([66,66]),Rs=new Uint8Array([67,67,67]),_s=new Uint8Array([88]),bs=new Uint8Array([89,89]),Cs=new Uint8Array([90,90,90]);function qt(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 Ls(n){return n===Q.BIT_40||n===Q.BIT_56?8:16}function $t(n,e,t){let s=q(n.subarray(0,24),e.subarray(0,24)),r=q(ce(s,Ss,n,e),ce(s,Ts,n,e),ce(s,Rs,n,e)),i=q(ce(r,_s,n,e),ce(r,bs,n,e),ce(r,Cs,n,e)),o=Ls(t),a=t===Q.BIT_40,c=m=>qt(m,o,a),d=c(i.subarray(0,16)),E=c(Ft(i.subarray(16,32),n,e)),y=c(Ft(i.subarray(32,48),n,e));return{macKey:d,keyLength:o,is40Bit:a,initialDecryptKey:E.slice(),initialEncryptKey:y.slice(),decryptKey:E,encryptKey:y}}function Xt(n,e){let t=new Uint8Array(4);new DataView(t.buffer).setUint32(0,e.length,!0);let s=ot(q(n,Vt,t,e));return j(q(n,Yt,s)).subarray(0,8)}function at(n,e,t,s){let r=ot(q(n,Vt,e)),i=j(q(n,Yt,r)).slice(0,t),o=W($(i),i);return qt(o,t,s)}var ct=3,zt=4,Ns=224,Is=208,vs=240,Os=1,Us=2,Ps=3,Zt={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},I={RDP:0,SSL:1,HYBRID:2,RDSTLS:4,HYBRID_EX:8},Ds={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 Qt(n){let e=new p(32);return e.u8(ct).u8(0).u16be(19),e.u8(14).u8(Ns).u16be(0).u16be(0).u8(0),e.u8(Os).u8(0).u16le(8).u32le(n),e.take()}function jt(n){let e=new T(n);e.skip(zt),e.u8();let t=e.u8();if(t!==Is)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:I.RDP,negotiated:!1};let s=e.u8();if(e.u8(),e.u16le(),s===Ps){let r=e.u32le(),i=new Error(Ds[r]||`The host refused the RDP connection (negotiation failure 0x${r.toString(16)}).`);throw i.negotiationFailure=r,i}return s!==Us?{selectedProtocol:I.RDP,negotiated:!1}:{selectedProtocol:e.u32le(),negotiated:!0}}function he(n){let e=new p(n.length+7);return e.u8(ct).u8(0).u16be(n.length+7),e.u8(2).u8(vs).u8(128),e.raw(n),e.take()}function ye(n){if(n.length<7)throw new Error("RDP: X.224 data frame is too short");return n.subarray(7)}function Jt(n){let e=[],t=0;for(;n.length-t>=4;){let s,r=!1;if(n[t]===ct){if(s=n[t+2]<<8|n[t+3],s<zt)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 ks=1,Ms=2,Gs=826364754,Hs=6,tn=[42,134,72,134,247,13,1,1,1];function re(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 le(n){let e=[],t=0;for(;t<n.length;){let s=re(n,t);if(e.push(s),s.next<=t)break;t=s.next}return e}function nn(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 en(n){let e=0;for(;e<n.length-1&&n[e]===0;)e++;return n.subarray(e).slice().reverse()}function Fs(n){let e=re(n,0),t=re(n,e.contentStart);for(let s of le(t.content)){if(s.tag!==48)continue;let r=le(s.content);if(r.length<2||r[0].tag!==48||!nn(r[0].content,tn)||r[1].tag!==3)continue;let i=re(r[1].content.subarray(1),0),[o,a]=le(i.content);if(!o||!a)break;return{modulus:en(o.content),exponent:en(a.content),source:"x509"}}throw new Error("RDP: no RSA public key found in the host X.509 certificate")}function Bs(n){n.u32le(),n.u32le();let e=n.u16le(),t=n.u16le();if(e!==Hs)throw new Error(`RDP: unsupported public key blob type 0x${e.toString(16)}`);let s=new T(n.raw(t));if(s.u32le()!==Gs)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 sn(n){let e=re(n,0),t=re(n,e.contentStart);for(let s of le(t.content)){if(s.tag!==48)continue;let r=le(s.content);if(r.length<2||r[0].tag!==48||!nn(r[0].content,tn)||r[1].tag!==3)continue;let i=r[1].content.subarray(1),o=re(i,0),[a,c]=le(o.content);if(!a||!c)break;let d=E=>{let y=0;for(;y<E.length-1&&E[y]===0;)y++;return E.subarray(y)};return{modulus:d(a.content),exponent:d(c.content),subjectPublicKey:i}}throw new Error("TLS: no RSA public key found in the host certificate")}function rn(n){let e=new T(n),t=e.u32le()&2147483647;if(t===ks)return Bs(e);if(t===Ms){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 Fs(r)}throw new Error(`RDP: unsupported server certificate version ${t}`)}var we=771,te={CHANGE_CIPHER_SPEC:20,ALERT:21,HANDSHAKE:22,APPLICATION_DATA:23},F={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},Ks={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"}},Ws={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"},Vs=n=>new TextEncoder().encode(n);function D(n){return new Uint8Array([n>>8&255,n&255])}function on(n){return new Uint8Array([n>>16&255,n>>8&255,n&255])}function ht(n){let e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,BigInt(n)),e}async function Ys(n,e,t,s){let r=await crypto.subtle.importKey("raw",e,{name:"HMAC",hash:n},!1,["sign"]),i=async d=>new Uint8Array(await crypto.subtle.sign("HMAC",r,d)),o=[],a=0,c=await i(t);for(;a<s;){let d=await i(g(c,t));o.push(d),a+=d.length,c=await i(c)}return g(...o).subarray(0,s)}var lt=(n,e,t,s,r)=>Ys(n,e,g(Vs(t),s),r),Oe=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=g(D(13),D(10),D(8),new Uint8Array([4,1,5,1,2,1,6,1]),D(65281),D(1),new Uint8Array([0])),t=g(D(we),this.clientRandom,new Uint8Array([0]),D(4),D(156),D(157),new Uint8Array([1,0]),D(e.length),e);return await this.#t(F.CLIENT_HELLO,t),this.handshakeDone}#e(e,t){return g(new Uint8Array([e]),D(we),D(t.length),t)}async#t(e,t){let s=g(new Uint8Array([e]),on(t.length),t);this.transcript.push(s),await this.#i(te.HANDSHAKE,s)}async#i(e,t){if(!this.writeEncrypted){this.sendRaw(this.#e(e,t));return}this.sendRaw(this.#e(e,await this.#n(e,t)))}async#n(e,t){let s=this.writeSequence++,r=ht(s),i=g(this.keys.clientIv,r),o=g(ht(s),new Uint8Array([e]),D(we),D(t.length)),a=await crypto.subtle.encrypt({name:"AES-GCM",iv:i,additionalData:o,tagLength:128},this.keys.clientKey,t);return g(r,new Uint8Array(a))}async#s(e,t){let s=this.readSequence++,r=t.subarray(0,8),i=t.subarray(8),o=g(this.keys.serverIv,r),a=g(ht(s),new Uint8Array([e]),D(we),D(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#o(e){let{hash:t,keyLength:s}=this.suite;this.masterSecret=await lt(t,e,"master secret",g(this.clientRandom,this.serverRandom),48);let r=await lt(t,this.masterSecret,"key expansion",g(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#r(){let e=await crypto.subtle.digest(this.suite.hash,g(...this.transcript));return new Uint8Array(e)}async#a(e){return lt(this.suite.hash,this.masterSecret,e,await this.#r(),12)}receive(e){return this.queue=this.queue.then(()=>this.#u(e)).catch(t=>this.#c(t)),this.queue}#c(e){let t=e instanceof Error?e:new Error(String(e));this.rejectHandshake(t),this.onError&&this.onError(t)}async#u(e){for(this.inbound=this.inbound.length===0?e:g(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!==te.CHANGE_CIPHER_SPEC?await this.#s(t,r):r;await this.#p(t,i)}}async#p(e,t){if(e===te.ALERT){let r=t[0],i=t[1],o=Ws[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===te.CHANGE_CIPHER_SPEC){this.readEncrypted=!0,this.readSequence=0n;return}if(e===te.APPLICATION_DATA){this.onData&&t.length>0&&this.onData(t);return}if(e!==te.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!==F.FINISHED&&this.transcript.push(o),await this.#f(r,a,o)}}async#f(e,t,s){switch(e){case F.SERVER_HELLO:{let r=new T(t),i=r.u16be();if(i!==we)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=Ks[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 F.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=sn(this.certificates[0]);return}case F.CERTIFICATE_REQUEST:this.certificateRequested=!0;return;case F.SERVER_KEY_EXCHANGE:throw new Error("TLS: the host chose an ephemeral key exchange, which this client does not implement");case F.SERVER_HELLO_DONE:await this.#E();return;case F.NEW_SESSION_TICKET:return;case F.FINISHED:{let r=await this.#a("server finished"),i=t.subarray(0,12);if(!(r.length===i.length&&r.every((a,c)=>a===i[c])))throw new Error("TLS: the host Finished message did not verify");this.transcript.push(s),this.established=!0,this.resolveHandshake({cipherSuite:this.suite.name,certificates:this.certificates,publicKey:this.serverPublicKey});return}default:return}}async#E(){this.certificateRequested&&await this.#t(F.CERTIFICATE,on(0));let e=new Uint8Array(48);crypto.getRandomValues(e),e[0]=3,e[1]=3;let t=Wt(e,this.serverPublicKey.modulus,this.serverPublicKey.exponent);await this.#t(F.CLIENT_KEY_EXCHANGE,g(D(t.length),t)),await this.#o(e),await this.#i(te.CHANGE_CIPHER_SPEC,new Uint8Array([1])),this.writeEncrypted=!0,this.writeSequence=0n,await this.#t(F.FINISHED,await this.#a("client finished"))}write(e){return this.queue=this.queue.then(async()=>{if(!this.established)throw new Error("TLS: write before the handshake finished");await this.#i(te.APPLICATION_DATA,e)}).catch(t=>this.#c(t)),this.queue}};function qs(n,e){return n<<e|n>>>32-e}function $s(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,d=new Uint32Array(16),E=[3,7,11,19],y=[0,4,8,12,1,5,9,13,2,6,10,14,3,7,11,15],m=[3,5,9,13],S=[0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15],f=[3,9,11,15];for(let x=0;x<e;x++){for(let _=0;_<16;_++)d[_]=s.getUint32(x*64+_*4,!0);let R=i,h=o,u=a,w=c,b=(_,L)=>qs(_|0,L);for(let _=0;_<16;_++){let L=h&u|~h&w,P=E[_%4],v=b(R+L+d[_]|0,P);R=w,w=u,u=h,h=v}for(let _=0;_<16;_++){let L=h&u|h&w|u&w,P=m[_%4],v=b(R+L+d[y[_]]+1518500249|0,P);R=w,w=u,u=h,h=v}for(let _=0;_<16;_++){let L=h^u^w,P=f[_%4],v=b(R+L+d[S[_]]+1859775393|0,P);R=w,w=u,u=h,h=v}i=i+R|0,o=o+h|0,a=a+u|0,c=c+w|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 ue(n,e){let s=n.length>64?j(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 j(g(o,j(g(i,e))))}var hn=new Uint8Array([78,84,76,77,83,83,80,0]),B={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},ln=B.UNICODE|B.REQUEST_TARGET|B.SIGN|B.SEAL|B.NTLM|B.ALWAYS_SIGN|B.EXTENDED_SESSION_SECURITY|B.TARGET_INFO|B.VERSION|B.KEY_128|B.KEY_EXCH|B.KEY_56,un=0,Xs=7,an=6,cn=2,dt=n=>{let e=new p(n.length*2+2);return e.utf16le(n),e.take()},dn=new Uint8Array([10,0,99,69,0,0,0,15]);function pn(){let n=new p(40);return n.raw(hn),n.u32le(1),n.u32le(ln>>>0),n.u16le(0).u16le(0).u32le(0),n.u16le(0).u16le(0).u32le(0),n.raw(dn),n.take()}function fn(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 zs(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===un)break;e.push({id:r,value:o})}return e}function Zs(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(un).u16le(0),e.take()}function Qs(){let n=(BigInt(Date.now())+11644473600000n)*10000n,e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,n,!0),e}function En({username:n,domain:e,password:t,challenge:s,negotiateBytes:r,challengeBytes:i}){let o=ue($s(dt(t)),dt(n.toUpperCase()+e)),a=zs(s.targetInfo),c=a.find(O=>O.id===Xs)?.value.slice()||Qs(),d=a.find(O=>O.id===an);if(d){let O=new DataView(d.value.buffer,d.value.byteOffset,4);O.setUint32(0,O.getUint32(0,!0)|cn,!0)}else{let O=new Uint8Array(4);new DataView(O.buffer).setUint32(0,cn,!0),a.push({id:an,value:O})}let E=Zs(a),y=new Uint8Array(8);crypto.getRandomValues(y);let m=g(new Uint8Array([1,1,0,0,0,0,0,0]),c,y,new Uint8Array(4),E,new Uint8Array(4)),S=ue(o,g(s.serverChallenge,m)),f=g(S,m),l=ue(o,S),A=new Uint8Array(16);crypto.getRandomValues(A);let x=W($(l),A),R=ut(e),h=ut(n),u=ut(""),w=new Uint8Array(24),b=72,_=b,L=[],P=O=>(L.push({bytes:O,offset:_}),_+=O.length,L[L.length-1]),v=P(w),ee=P(f),et=P(R),Ie=P(h),tt=P(u),nt=P(x),Y=new p(_+16);Y.raw(hn),Y.u32le(3);let ae=O=>{Y.u16le(O.bytes.length),Y.u16le(O.bytes.length),Y.u32le(O.offset+16)};ae(v),ae(ee),ae(et),ae(Ie),ae(tt),ae(nt),Y.u32le(ln>>>0),Y.raw(dn),Y.zeros(16);for(let O of L)Y.raw(O.bytes);let st=Y.take(),ws=ue(A,g(r,i,st));return st.set(ws,b),{message:st,exportedSessionKey:A,keys:nr(A)}}function ut(n){return n?dt(n).subarray(0,n.length*2).slice():new Uint8Array(0)}var js="session key to client-to-server signing key magic constant\0",Js="session key to server-to-client signing key magic constant\0",er="session key to client-to-server sealing key magic constant\0",tr="session key to server-to-client sealing key magic constant\0";function nr(n){let e=t=>j(g(n,new TextEncoder().encode(t)));return{clientSigningKey:e(js),serverSigningKey:e(Js),clientSealing:$(e(er)),serverSealing:$(e(tr))}}var Ue=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=ue(this.keys.clientSigningKey,g(t,e)),r=W(this.keys.clientSealing,e),i=W(this.keys.clientSealing,s.subarray(0,8));return this.sendSequence+=1,g(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=W(this.keys.serverSealing,t),r=e.subarray(12,16),i=ue(this.keys.serverSigningKey,g(r,s)),o=W(this.keys.serverSealing,i.subarray(0,8)),a=e.subarray(4,12);if(!o.every((c,d)=>c===a[d]))throw new Error("NTLM: the host signature did not verify");return this.receiveSequence+=1,s}};var pt=6,sr="CredSSP Client-To-Server Binding Hash\0",rr="CredSSP Server-To-Client Binding Hash\0",ir={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 or(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 De=(n,e)=>g(new Uint8Array([n]),or(e.length),e),Ae=(...n)=>De(48,g(...n)),ne=n=>De(4,n),V=(n,e)=>De(160|n,e);function mn(n){let e=[],t=n;do e.unshift(t&255),t>>>=8;while(t>0);return e[0]&128&&e.unshift(0),De(2,new Uint8Array(e))}function X(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 ar(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 ft({version:n,negoToken:e,authInfo:t,pubKeyAuth:s,clientNonce:r}){let i=[V(0,mn(n))];return e&&i.push(V(1,Ae(Ae(V(0,ne(e)))))),t&&i.push(V(2,ne(t))),s&&i.push(V(3,ne(s))),r&&i.push(V(5,ne(r))),Ae(...i)}function cr(n){let e=X(n,0),t={version:0,negoToken:null,authInfo:null,pubKeyAuth:null,errorCode:0},s=0;for(;s<e.content.length;){let r=X(e.content,s);s=r.end;let i=r.tag&31;if(i===0){t.version=X(r.content,0).content[0];continue}if(i===1){let o=X(r.content,0),a=X(o.content,0),c=X(a.content,0);t.negoToken=X(c.content,0).content;continue}if(i===2){t.authInfo=X(r.content,0).content;continue}if(i===3){t.pubKeyAuth=X(r.content,0).content;continue}if(i===4){let o=X(r.content,0).content,a=0;for(let c of o)a=(a<<8|c)>>>0;t.errorCode=a;continue}}return t}function hr(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=Ae(V(0,ne(s(n))),V(1,ne(s(e))),V(2,ne(s(t))));return Ae(V(0,mn(1)),V(1,ne(r)))}var Pe=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:g(this.inbound,e);;){let t=ar(this.inbound);if(t===0)return;let s=cr(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",g(new TextEncoder().encode(e),t,this.serverPublicKey));return new Uint8Array(s)}async authenticate(){let e=pn();this.send(ft({version:pt,negoToken:e})),this.log("CredSSP","sent NTLM NEGOTIATE");let t=await this.#e();if(t.errorCode)throw new Error(this.#n(t.errorCode));if(!t.negoToken)throw new Error("CredSSP: the host sent no NTLM challenge");let s=t.negoToken.slice(),r=fn(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}=En({username:this.username,domain:this.domain,password:this.password,challenge:r,negotiateBytes:e,challengeBytes:s}),c=new Ue(a),d=new Uint8Array(32);crypto.getRandomValues(d);let E=t.version<5,y=E?this.serverPublicKey:await this.#t(sr,d);this.send(ft({version:pt,negoToken:o,pubKeyAuth:c.seal(y),clientNonce:E?null:d})),this.log("CredSSP",`sent NTLM AUTHENTICATE with the ${E?"legacy":"hashed"} public-key binding`);let m=await this.#e();if(m.errorCode)throw new Error(this.#n(m.errorCode));if(!m.pubKeyAuth)throw new Error("CredSSP: the host returned no public-key confirmation");let S=c.unseal(m.pubKeyAuth),f=E?this.#i():await this.#t(rr,d);if(S.length!==f.length||!f.every((l,A)=>l===S[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:pt,authInfo:c.seal(hr(this.domain,this.username,this.password))})),this.log("CredSSP","sent credentials"),{authenticated:!0,hostVersion:t.version,targetName:i}}#i(){let e=this.serverPublicKey.slice();return e[0]=e[0]+1&255,e}#n(e){return ir[e]||`CredSSP: the host reported error 0x${e.toString(16).padStart(8,"0")}.`}};var de=1001;var se={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},lr={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 ur(n){return n>255?new Uint8Array([130,n>>8&255,n&255]):n>127?new Uint8Array([129,n]):new Uint8Array([n])}function ge(n,e){return g(new Uint8Array(n),ur(e.length),e)}function dr(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]),ge([2],e)}var Et=n=>ge([4],n),pr=n=>ge([1],new Uint8Array([n?255:0]));function mt(n){return ge([48],g(...n.map(dr)))}function yt(n,e){return e>127?n.u16be(32768|e):n.u8(e),n}function yn(n){let e=n.u8();return e&128?(e&127)<<8|n.u8():e}var fr=new Uint8Array([5,0,20,124,0,1]),Er=new Uint8Array([68,117,99,97]),ke=new Uint8Array([77,99,68,110]);function mr(n){let e=new p(n.length+32);return e.u8(0),e.raw(fr),yt(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(Er),yt(e,n.length),e.raw(n),e.take()}function yr(n){for(let e=0;e+4<=n.length;e++)if(n[e]===ke[0]&&n[e+1]===ke[1]&&n[e+2]===ke[2]&&n[e+3]===ke[3]){let t=new T(n,e+4),s=yn(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 wr=[34,2,0,1,0,1,65535,2],Ar=[1,1,1,1,0,1,1056,2],xr=[65535,64535,65535,1,0,1,65535,2];function wn(n){let e=mr(n),t=g(Et(new Uint8Array([1])),Et(new Uint8Array([1])),pr(!0),mt(wr),mt(Ar),mt(xr),Et(e));return he(ge([127,101],t))}function xe(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 An(n){let e=new T(ye(n)),t=xe(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=xe(s);xe(s),xe(s);let i=xe(s);if(r.value[0]!==0)throw new Error(`RDP: the host rejected the MCS connection (result ${r.value[0]})`);return yr(i.value)}var Me=n=>n<<2;function xn(){let n=new p(8);return n.u8(Me(se.ERECT_DOMAIN_REQUEST)),n.u8(1).u8(0),n.u8(1).u8(0),he(n.take())}function gn(){return he(new Uint8Array([Me(se.ATTACH_USER_REQUEST)]))}function Sn(n){let e=new T(ye(n)),t=e.u8();if(t>>2!==se.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()+de:de}}function wt(n,e){let t=new p(8);return t.u8(Me(se.CHANNEL_JOIN_REQUEST)),t.u16be(n-de),t.u16be(e),he(t.take())}function Tn(n){let e=new T(ye(n)),t=e.u8();if(t>>2!==se.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 At(n,e,t){let s=new p(t.length+16);return s.u8(Me(se.SEND_DATA_REQUEST)),s.u16be(n-de),s.u16be(e),s.u8(112),yt(s,t.length),s.raw(t),he(s.take())}function Rn(n){let e=new T(ye(n)),t=e.u8(),s=t>>2;if(s===se.SEND_DATA_INDICATION){e.u16be();let r=e.u16be();e.u8();let i=yn(e),o=e.rest();return{type:"send-data",channelId:r,payload:o.subarray(0,Math.min(i,o.length))}}if(s===se.DISCONNECT_PROVIDER_ULTIMATUM){let r=(t&1)<<1|(e.remaining>0?e.u8()>>7:0);return{type:"disconnect",reason:r,message:lr[r]||`The host closed the RDP session (reason ${r}).`}}return{type:"other",mcsPduType:s}}var gr=49153,Sr=49154,Tr=49155,Rr=49156,_r=3073,br=3074,Cr=3075,Lr=524292,_n=51715,Nr=43523,Ir=1,Ge={NONE:0,LOW:1,CLIENT_COMPATIBLE:2,HIGH:3,FIPS:4};function He(n,e){let t=new p(e.length+4);return t.u16le(n).u16le(e.length+4).raw(e),t.take()}function vr({width:n,height:e,clientName:t,keyboardLayout:s,selectedProtocol:r}){let i=new p(256);return i.u32le(Lr),i.u16le(n),i.u16le(e),i.u16le(_n),i.u16le(Nr),i.u32le(s),i.u32le(2600),i.utf16le(t,32),i.u32le(4),i.u32le(0),i.u32le(12),i.zeros(64),i.u16le(_n),i.u16le(1),i.u32le(0),i.u16le(16),i.u16le(7),i.u16le(Ir),i.zeros(64),i.u8(0),i.u8(0),i.u32le(r),He(gr,i.take())}function Or(n){let e=new p(8);return e.u32le(n),e.u32le(0),He(Sr,e.take())}function Ur(){let n=new p(8);return n.u32le(13),n.u32le(0),He(Rr,n.take())}function Pr(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 He(Tr,e.take())}function bn(n){return g(vr(n),Ur(),Or(n.encryptionMethods),Pr(n.channels||[]))}function Cn(n){let e=new T(n),t={version:null,encryptionMethod:0,encryptionLevel:Ge.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===_r){t.version=i.remaining>=4?i.u32le():null;continue}if(s===Cr){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===br){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=rn(i.raw(a));continue}}return t}var H={MONITOR_READY:1,FORMAT_LIST:2,FORMAT_LIST_RESPONSE:3,FORMAT_DATA_REQUEST:4,FORMAT_DATA_RESPONSE:5,CLIP_CAPS:7},Ln=1,xt=2,Dr=4,Se=1,pe=13,Nn=1,kr=2,In=2,Fe=32,Mr=400;function Gr(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 Hr(n){let e=new p(n.length*2+2);return e.utf16le(n),e.u16le(0),e.take()}function Fr(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 Br(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 Kr(n){let e=n.indexOf(0);return e===-1&&(e=n.length),String.fromCharCode(...n.subarray(0,e))}var Be=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(Gr(e,t,s))}setLocalText(e){return this.localText=e,this.ready?(this.#e(H.FORMAT_LIST,0,this.#t(e?[pe,Se]:[])),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)},Mr),this.pendingAck={resolve:r}})):Promise.resolve(!1)}#t(e){let t=e.map(s=>{let r=new p(this.longFormatNames?6:4+Fe);return r.u32le(s),this.longFormatNames?r.u16le(0):r.zeros(Fe),r.take()});return g(...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 H.CLIP_CAPS:this.#i(a);return;case H.MONITOR_READY:this.#n();return;case H.FORMAT_LIST:this.#s(a,r);return;case H.FORMAT_LIST_RESPONSE:this.pendingAck?.resolve((r&xt)===0);return;case H.FORMAT_DATA_REQUEST:this.#r(a);return;case H.FORMAT_DATA_RESPONSE:this.#a(a,r);return;default:return}}#i(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===Nn&&a.remaining>=8){a.u32le();let c=a.u32le();this.longFormatNames=(c&In)!==0}}}#n(){let e=new p(12);e.u16le(Nn).u16le(12),e.u32le(kr),e.u32le(this.longFormatNames?In:0);let t=new p(20);t.u16le(1).u16le(0),t.raw(e.take()),this.#e(H.CLIP_CAPS,0,t.take()),this.ready=!0,this.#e(H.FORMAT_LIST,0,this.#t(this.localText?[pe,Se]:[])),this.log("clipboard channel ready",{longFormatNames:this.longFormatNames})}#s(e,t){let s=this.#o(e,t);this.#e(H.FORMAT_LIST_RESPONSE,Ln);let r=s.includes(pe)?pe:s.includes(Se)?Se: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(H.FORMAT_DATA_REQUEST,0,i.take())}#o(e,t){let s=new T(e),r=[],i=!this.longFormatNames||(t&Dr)!==0;for(;s.remaining>=4;){if(r.push(s.u32le()),i){if(s.remaining<Fe)break;s.skip(Fe);continue}for(;s.remaining>=2&&s.u16le()!==0;);}return r}#r(e){let t=new T(e),s=t.remaining>=4?t.u32le():0;if(s!==pe&&s!==Se){this.#e(H.FORMAT_DATA_RESPONSE,xt);return}let r=s===pe?Hr(this.localText):Br(this.localText);this.#e(H.FORMAT_DATA_RESPONSE,Ln,r),this.log("handed the host our clipboard",{formatId:s,characters:this.localText.length})}#a(e,t){if(t&xt){this.log("the host refused to hand over its clipboard");return}let r=e.length>=2&&e.length%2===0&&e[1]===0?Fr(e):Kr(e);r&&this.dispatchEvent(new CustomEvent("text",{detail:{text:r}}))}};var K={EXEC:1,ACTIVATE:2,SYSPARAM:3,SYSCOMMAND:4,HANDSHAKE:5,WINDOW_MOVE:8,CLIENT_STATUS:11,EXEC_RESULT:128,HANDSHAKE_EX:19},Wr={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."},On={MINIMIZE:61472,MAXIMIZE:61488,CLOSE:61536,RESTORE:61728},Ee={HIDDEN:0,MINIMIZED:2,MAXIMIZED:3,NORMAL:5},Te={TYPE_WINDOW:16777216,STATE_NEW:268435456,STATE_DELETED:536870912,ICON:1073741824,CACHED_ICON:2147483648},M={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},Vr=1073741824,Yr=128,qr=134217728,$r=3,Xr=2,zr=11,Un=2600,Zr=1024,fe={MOUSE_BUTTON_SWAP:33,DRAG_FULL_WINDOWS:37,WORK_AREA:47,HIGH_CONTRAST:67,KEYBOARD_PREF:69,KEYBOARD_CUES:4107};function gt(n){let e=new p(n.length*2);return e.utf16le(n),e.take()}function J(n,e){let t=new p(e.length+4);return t.u16le(n).u16le(e.length+4).raw(e),t.take()}function z(n){return n|0}function Qr(n=Un){return J(K.HANDSHAKE,new p(4).u32le(n).take())}function jr(n=Zr){return J(K.CLIENT_STATUS,new p(4).u32le(n).take())}function Ke(n,e){return J(K.SYSPARAM,new p(5).u32le(n).u8(e?1:0).take())}function Jr(){let n=new p(16);return n.u32le(fe.HIGH_CONTRAST),n.u32le(126),n.u32le(2),n.u16le(0).u16le(0),J(K.SYSPARAM,n.take())}function Pn(n,e){let t=new p(12);return t.u32le(fe.WORK_AREA),t.u16le(0).u16le(0).u16le(n).u16le(e),J(K.SYSPARAM,t.take())}function ei(n,e){return[Jr(),Ke(fe.MOUSE_BUTTON_SWAP,!1),Ke(fe.KEYBOARD_PREF,!1),Ke(fe.DRAG_FULL_WINDOWS,!0),Ke(fe.KEYBOARD_CUES,!1),Pn(n,e)]}function ti(n,e=!0){let t=new p(5);return t.u32le(n).u8(e?1:0),J(K.ACTIVATE,t.take())}function ni(n,e){let t=new p(6);return t.u32le(n).u16le(e),J(K.SYSCOMMAND,t.take())}function si(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),J(K.WINDOW_MOVE,i.take())}function ri({program:n,workingDir:e="",arguments:t=""}){let s=gt(n||""),r=gt(e||""),i=gt(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),J(K.EXEC,o.take())}function Dn(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 vn(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 ii(n,e){let t={};if(e&M.OWNER&&(t.ownerWindowId=n.u32le()),e&M.STYLE&&(t.style=n.u32le(),t.extendedStyle=n.u32le()),e&M.SHOW&&(t.showState=n.u8()),e&M.TITLE){let s=n.u16le();t.title=Dn(n.raw(Math.min(s,n.remaining)))}return e&M.CLIENT_AREA_OFFSET&&(t.clientOffsetX=z(n.u32le()),t.clientOffsetY=z(n.u32le())),e&M.CLIENT_AREA_SIZE&&(t.clientWidth=z(n.u32le()),t.clientHeight=z(n.u32le())),e&M.RP_CONTENT&&n.u8(),e&M.ROOT_PARENT&&n.u32le(),e&M.WND_OFFSET&&(t.x=z(n.u32le()),t.y=z(n.u32le())),e&M.CLIENT_DELTA&&(n.u32le(),n.u32le()),e&M.WND_SIZE&&(t.width=z(n.u32le()),t.height=z(n.u32le())),e&M.WND_RECTS&&(t.windowRects=vn(n,n.u16le())),e&M.VIS_OFFSET&&(t.visibleOffsetX=z(n.u32le()),t.visibleOffsetY=z(n.u32le())),e&M.VISIBILITY&&(t.visibilityRects=vn(n,n.u16le())),t}function kn(n){return!(!n||n.ownerWindowId||(n.style||0)&Vr||(n.extendedStyle||0)&(Yr|qr))}function Mn(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&$r,a=i>>2;if(o!==Xr||a!==zr)break;if(n.remaining<6)throw new Error("RDP RemoteApp window-order header is truncated.");let c=n.u16le(),d=n.u32le(),E=r+c;if(c<7||E>n.bytes.length)throw new Error("RDP RemoteApp window order has an invalid size.");let y=!!(d&Te.TYPE_WINDOW),m=!!(d&(Te.ICON|Te.CACHED_ICON));if(y&&!m&&E-n.offset>=4){let S=n.u32le(),f={};try{f=ii(n,d)}catch(A){console.warn("[RDP] Dropped an unreadable RemoteApp window order",{windowId:S,fieldFlags:`0x${(d>>>0).toString(16)}`,error:A instanceof Error?A.message:String(A)})}let l="update";d&Te.STATE_DELETED?l="deleted":d&Te.STATE_NEW&&(l="new"),t.push({type:l,windowId:S,fieldFlags:d,...f})}if(n.offset=E,n.offset<=r)break}return t}function oi(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===K.HANDSHAKE&&i.remaining>=4){t.push({type:"handshake",buildNumber:i.u32le()});continue}if(s===K.HANDSHAKE_EX&&i.remaining>=8){t.push({type:"handshake",buildNumber:i.u32le(),flags:i.u32le(),extended:!0});continue}if(s===K.EXEC_RESULT&&i.remaining>=12){let o=i.u16le(),a=i.u16le(),c=i.u32le();i.u16le();let d=i.u16le(),E=Dn(i.raw(Math.min(d,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 We=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 oi(e)){if(t.type==="handshake"){if(this.started)continue;this.started=!0,this.send(Qr(Un)),this.send(jr());for(let s of ei(this.width,this.height))this.send(s);this.send(ri(this.application)),this.onReady?.(t);continue}t.type==="execute-result"&&this.onResult?.({...t,ok:t.result===0,message:Wr[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(Pn(e,t)),!0)}activate(e){return this.started?(this.send(ti(e,!0)),!0):!1}sysCommand(e,t){return this.started?(this.send(ni(e,t)),!0):!1}moveWindow(e,t){return this.started?(this.send(si(e,t)),!0):!1}};var ie={INITIALIZED:2147483648,ENCRYPT_RDP:1073741824,COMPRESS_RDP:8388608,SHOW_PROTOCOL:2097152},Gn=1,Hn=2,Fn=16,St=1600;function Bn(n,e=St,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|=Gn),r+e>=n.length&&(o|=Hn);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 Ve=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&Gn&&(this.parts=[],this.expectedLength=s),this.parts.push(i.slice()),!((r&Hn)!==0))return null;let a=g(...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},Tt=4096,Re=class{encryptionMethod;encryptionLevel;keys;encryptState;decryptState;encryptedPdus;decryptedPdus;constructor(){this.encryptionMethod=Q.NONE,this.encryptionLevel=Ge.NONE,this.keys=null,this.encryptState=null,this.decryptState=null,this.encryptedPdus=0,this.decryptedPdus=0}get headerPresent(){return this.encryptionLevel!==Ge.NONE||this.encryptionMethod!==Q.NONE}get encryptionEnabled(){return this.encryptionMethod!==Q.NONE&&this.keys!==null}configure(e,t,s,r){if(this.encryptionMethod=e,this.encryptionLevel=t,e!==Q.NONE){if(e&Q.FIPS)throw new Error("RDP: this host requires FIPS encryption, which this client does not implement");this.keys=$t(s,r,e),this.encryptState=$(this.keys.encryptKey),this.decryptState=$(this.keys.decryptKey)}}#e(){this.keys.encryptKey=at(this.keys.initialEncryptKey,this.keys.encryptKey,this.keys.keyLength,this.keys.is40Bit),this.encryptState=$(this.keys.encryptKey),this.encryptedPdus=0}#t(){this.keys.decryptKey=at(this.keys.initialDecryptKey,this.keys.decryptKey,this.keys.keyLength,this.keys.is40Bit),this.decryptState=$(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(Xt(this.keys.macKey,e)),r.raw(W(this.encryptState,e)),++this.encryptedPdus===Tt&&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=W(this.decryptState,s.rest());return++this.decryptedPdus===Tt&&this.#t(),{flags:r,payload:i}}decryptFastPath(e){if(!this.encryptionEnabled||e.length<=8)return e;let t=W(this.decryptState,e.subarray(8));return++this.decryptedPdus===Tt&&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 N={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},ai=1,ci=4,hi=16,li=1,ui=4,di=2,pi=8;function k(n,e){let t=new p(e.length+4);return t.u16le(n).u16le(e.length+4).raw(e),t.take()}function fi(){let n=new p(24);return n.u16le(1),n.u16le(3),n.u16le(512),n.u16le(0),n.u16le(0),n.u16le(li|ui),n.u16le(0),n.u16le(0),n.u16le(0),n.u8(1),n.u8(1),k(N.GENERAL,n.take())}function Ei(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),k(N.BITMAP,t.take())}function mi(){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(di|pi),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(N.ORDER,n.take())}function yi(){let n=new p(40);return n.zeros(24),n.u16le(0).u16le(0),n.u16le(0).u16le(0),n.u16le(0).u16le(0),k(N.BITMAPCACHE,n.take())}function wi(){let n=new p(12);return n.u16le(0),n.u16le(0),n.u16le(2),n.u16le(2),k(N.CONTROL,n.take())}function Ai(){let n=new p(12);return n.u16le(0).u16le(0).u16le(0).u16le(0),k(N.ACTIVATION,n.take())}function xi(){let n=new p(10);return n.u16le(1),n.u16le(20),n.u16le(20),k(N.POINTER,n.take())}function gi(){let n=new p(8);return n.u16le(0).u16le(0),k(N.SHARE,n.take())}function Si(){let n=new p(8);return n.u16le(6).u16le(0),k(N.COLORCACHE,n.take())}function Ti(){let n=new p(8);return n.u16le(0).u16le(0),k(N.SOUND,n.take())}function Ri(n){let e=new p(88);return e.u16le(ai|ci|hi),e.u16le(0),e.u32le(n),e.u32le(4),e.u32le(0),e.u32le(12),e.zeros(64),k(N.INPUT,e.take())}function _i(){let n=new p(8);return n.u16le(1).u16le(0),k(N.FONT,n.take())}function bi(){let n=new p(8);return n.u32le(0),k(N.BRUSH,n.take())}function Ci(){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),k(N.GLYPHCACHE,n.take())}function Li(){let n=new p(12);return n.u32le(0),n.u16le(0),n.u16le(0),k(N.OFFSCREENCACHE,n.take())}function Ni(){let n=new p(4);return n.u32le(1),k(N.RAIL,n.take())}function Ii(n=0,e=0){let t=new p(7);return t.u32le(1),t.u8(n),t.u16le(e),k(N.WINDOW,t.take())}function Kn({width:n,height:e,keyboardLayout:t,remoteApp:s=!1,remoteAppCaps:r=null}){let i=[fi(),Ei(n,e),mi(),yi(),Si(),Ai(),wi(),xi(),gi(),Ri(t),bi(),Ci(),Ti(),_i(),Li()];return s&&(i.push(Ni()),i.push(Ii(r?.numIconCaches||0,r?.numIconCacheEntries||0))),{bytes:g(...i),count:i.length}}function Wn(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===N.BITMAP&&a.remaining>=20){s.preferredBitsPerPixel=a.u16le(),a.skip(6),s.desktopWidth=a.u16le(),s.desktopHeight=a.u16le();continue}if(i===N.GENERAL&&a.remaining>=20){a.skip(18),s.refreshRectSupport=a.u8()!==0;continue}if(i===N.RAIL&&a.remaining>=4){s.railSupportLevel=a.u32le();continue}if(i===N.WINDOW&&a.remaining>=7){s.windowSupportLevel=a.u32le(),s.numIconCaches=a.u8(),s.numIconCacheEntries=a.u16le();continue}}return s}var oe={DEMAND_ACTIVE:1,CONFIRM_ACTIVE:3,DEACTIVATE_ALL:6,DATA:7,SERVER_REDIRECT:10},U={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},Ye={ORDERS:0,BITMAP:1,PALETTE:2,SYNCHRONIZE:3},Rt={REQUEST_CONTROL:1,GRANTED_CONTROL:2,DETACH:3,COOPERATE:4},Ce={SYNC:0,SCANCODE:4,UNICODE:5,MOUSE:32769,MOUSEX:32770},be={EXTENDED:256,DOWN:16384,RELEASE:32768},Z={WHEEL:512,HWHEEL:1024,WHEEL_NEGATIVE:256,MOVE:2048,DOWN:32768,BUTTON1:4096,BUTTON2:8192,BUTTON3:16384};function Yn(n,e=!1){let t=e?Math.sign(n):-Math.sign(n);if(t===0)return 0;let s=e?Z.HWHEEL:Z.WHEEL,r=120;return t>0?s|r:s|Z.WHEEL_NEGATIVE|-r&255}var qe={SCROLL_LOCK:1,NUM_LOCK:2,CAPS_LOCK:4,KANA_LOCK:8},me={SYSTEM:1,POSITION:3,COLOR:6,CACHED:7,POINTER:8,LARGE:9},vi=721267,Oi=8,Ui=32768,Pi={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 qn(n){return Pi[n]||`The host ended the session with error info 0x${n.toString(16).padStart(8,"0")}.`}function _t(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 $n(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),_t(oe.DATA,e,r.take())}function _e(n,e){let t=n.length;n.utf16le(e);let s=n.length-t;return n.u16le(0),s}function Xn({domain:n,username:e,password:t,performanceFlags:s,autoLogon:r,remoteApp:i=!1}){let o=new p(512),a=_e(o,n||""),c=_e(o,e||""),d=_e(o,t||""),E=_e(o,""),y=_e(o,""),m=new p(768);return m.u32le(0),m.u32le((vi|(r?Oi:0)|(i?Ui:0))>>>0),m.u16le(a),m.u16le(c),m.u16le(d),m.u16le(E),m.u16le(y),m.raw(o.take()),m.u16le(2),m.u16le(2),m.u16le(0),m.u16le(2),m.u16le(0),m.zeros(172),m.u32le(0),m.u32le(s>>>0),m.u16le(0),m.take()}function zn(n){let e=new p(4);return e.u16le(1),e.u16le(n),e.take()}function bt(n){let e=new p(8);return e.u16le(n),e.u16le(0),e.u32le(0),e.take()}function Zn(){let n=new p(8);return n.u16le(0),n.u16le(0),n.u16le(3),n.u16le(50),n.take()}function Qn(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 jn(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 Le(n,e){let t=new p(12);return t.u32le(0),t.u16le(n),e(t),t.take()}function Ct(n,e,t){return Le(Ce.SCANCODE,s=>{s.u16le((e?be.DOWN:be.RELEASE)|(t?be.EXTENDED:0)),s.u16le(n),s.u16le(0)})}function Lt(n,e){return Le(Ce.UNICODE,t=>{t.u16le(e?be.DOWN:be.RELEASE),t.u16le(n),t.u16le(0)})}function $e(n,e,t){return Le(Ce.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 Jn(n,e,t){return Le(Ce.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 Nt(n){return Le(Ce.SYNC,e=>{e.u16le(0),e.u32le(n>>>0)})}function es(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 ts(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 ns(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 ss(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 rs(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 Di=1,ki=1024;function It(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(),d=n.u16le(),E=n.u16le(),y=n.u16le(),m=n.u16le(),S=!!(y&Di);if(S&&!(y&ki)){n.u16le();let f=n.u16le();n.u16le(),n.u16le(),m=f}t.push({left:r,top:i,right:o,bottom:a,width:c,height:d,bitsPerPixel:E,compressed:S,data:n.raw(Math.min(m,n.remaining))})}return t}function vt(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 Vn(n,e){let t=n.u16le(),s=n.u16le(),r=n.u16le(),i=n.u16le(),o=n.u16le(),a=n.u16le(),c=n.u16le(),d=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:d,andMask:E}}function Ot(n){let e=n.u16le();if(n.u16le(),e===me.POSITION)return{kind:"position",x:n.u16le(),y:n.u16le()};if(e===me.SYSTEM)return{kind:"system",hidden:n.u32le()===0};if(e===me.CACHED)return{kind:"cached",cacheIndex:n.u16le()};if(e===me.COLOR)return Vn(n,24);if(e===me.POINTER){let t=n.u16le();return Vn(n,t)}return e===me.LARGE?{kind:"unsupported",messageType:e}:{kind:"unsupported",messageType:e}}var is={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},os={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 Ut(n){return Object.prototype.hasOwnProperty.call(is,n)?{scancode:is[n],extended:!1}:Object.prototype.hasOwnProperty.call(os,n)?{scancode:os[n],extended:!0}:null}var as=[{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 Xe="VNC_GATEWAY_READY_v1",ze="VNC_GATEWAY_KEEPALIVE_v1";var C={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"},Mi=255,Pt={name:"cliprdr",options:ie.INITIALIZED|ie.ENCRYPT_RDP|ie.SHOW_PROTOCOL},Dt={name:"rail",options:ie.INITIALIZED|ie.ENCRYPT_RDP|ie.SHOW_PROTOCOL},Gi=1,Hi=2,Fi=4,Bi=1200,Ki=120,Ze=2,Wi=4,Vi=12,cs=320,Qe=class extends EventTarget{constructor(e,t={}){super(),this.url=e,this.options={width:1024,height:768,username:"",password:"",domain:"",keyboardLayout:1033,clientName:"cf-gateway",security:"auto",openTransport:null,clipboard:!0,remoteApp:null,performance:Gi|Hi|Fi,...t},this.state=C.IDLE,this.legacyRetryUsed=!1,this.desktopWidth=this.options.width,this.desktopHeight=this.options.height,this.palette=null,this.userId=de,this.ioChannelId=1003,this.serverChannelId=1002,this.shareId=0,this.channelsToJoin=[],this.requestedChannels=[],this.channelNamesById=new Map,this.channelReassemblers=new Map,this.clipboard=null,this.rail=null,this.remoteAppWindows=new Map,this.remoteAppHadWindow=!1,this.remoteAppCloseTimer=null,this.remoteAppFit=null,this.remoteAppFitTimer=null,this.clientRandom=null,this.serverData=null,this.fastPathFragments=[],this.receiveBuffer=new Uint8Array(0),this.keepaliveTimer=null,this.closeReported=!1,this.tls=null,this.credssp=null,this.inboundQueue=Promise.resolve(),this.requestedProtocol={auto:I.SSL|I.HYBRID,nla:I.SSL|I.HYBRID,tls:I.SSL,rdp:I.RDP}[this.options.security]??I.SSL|I.HYBRID,this.#e()}#e(){this.receiveBuffer=new Uint8Array(0),this.inboundQueue=Promise.resolve(),this.tls=null,this.credssp=null,this.security=new Re,this.replacingTransport=!1,this.channelNamesById=new Map,this.channelReassemblers=new Map,this.clipboard=null,this.rail=null,this.remoteAppWindows.clear(),this.remoteAppHadWindow=!1,clearTimeout(this.remoteAppCloseTimer),clearTimeout(this.remoteAppFitTimer),this.remoteAppFitTimer=null,this.remoteAppCloseTimer=null,this.socket=this.options.openTransport?this.options.openTransport(this.url):new WebSocket(this.url),this.socket.binaryType="arraybuffer",this.socket.addEventListener("open",()=>this.#i()),this.socket.addEventListener("message",e=>this.#a(e)),this.socket.addEventListener("close",e=>this.#o(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"?I.RDP:I.SSL,this.state=C.IDLE,this.replacingTransport=!0,clearInterval(this.keepaliveTimer);try{this.socket.close(1e3,"Retrying with another security layer")}catch{}this.#e()}#i(){this.socket.send(Xe),this.state=C.NEGOTIATING,this.#n(Qt(this.requestedProtocol)),this.keepaliveTimer=setInterval(()=>{if(this.socket.readyState===WebSocket.OPEN&&(this.socket.send(ze),this.state===C.CONNECTED))try{this.#h([Nt(this.toggleFlags||0)])}catch{}},25e3)}#n(e){if(this.tls&&this.tls.established){this.tls.write(e);return}this.#s(e)}#s(e){this.socket.readyState===WebSocket.OPEN&&this.socket.send(e)}#o(e){if(clearInterval(this.keepaliveTimer),clearTimeout(this.remoteAppCloseTimer),clearTimeout(this.remoteAppFitTimer),this.remoteAppFitTimer=null,this.replacingTransport||this.state===C.CLOSED&&this.closeReported)return;let t=this.state===C.CONNECTED;this.state=C.CLOSED,this.closeReported=!0,this.dispatchEvent(new CustomEvent("close",{detail:{clean:e.wasClean&&t,code:e.code,message:e.reason||"",phase:t?"session":"handshake"}}))}#r(e){if(this.state===C.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=C.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!==C.CLOSED){this.state=C.CLOSED,this.closeReported=!0,clearInterval(this.keepaliveTimer),clearTimeout(this.remoteAppCloseTimer),clearTimeout(this.remoteAppFitTimer),this.remoteAppFitTimer=null;try{this.socket.close(1e3,"Client disconnected")}catch{}}}#a(e){this.state!==C.CLOSED&&(this.inboundQueue=this.inboundQueue.then(async()=>{if(this.state===C.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.#u(t)}).catch(t=>this.#r(t)))}#c(e){if(this.state===C.CREDSSP&&this.credssp){this.credssp.receive(e);return}return this.#u(e)}async#u(e){this.receiveBuffer=this.receiveBuffer.length===0?e:g(this.receiveBuffer,e);let{frames:t,rest:s}=Jt(this.receiveBuffer);this.receiveBuffer=s.length===this.receiveBuffer.length?this.receiveBuffer:s.slice();for(let{fastPath:r,frame:i}of t){if(this.state===C.CLOSED)return;r?this.#U(i):await this.#p(i)}}async#p(e){if(this.state===C.NEGOTIATING){let o;try{({selectedProtocol:o}=jt(e))}catch(a){if(this.options.security==="auto"&&!this.legacyRetryUsed&&a.negotiationFailure===Zt.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&I.HYBRID?"NLA / CredSSP":o&I.SSL?"TLS":"RDP standard"}),o&I.HYBRID_EX)throw new Error("This host selected CredSSP with early user authorization, which this client does not implement.");if(o&(I.SSL|I.HYBRID)){this.#E(o);return}this.#m(o);return}if(this.state===C.MCS_CONNECT){this.serverData=Cn(An(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.#x():new Uint8Array(32),this.serverData.serverRandom||new Uint8Array(32)),this.state=C.ATTACH_USER,this.#n(xn()),this.#n(gn());return}if(this.state===C.ATTACH_USER){({userId:this.userId}=Sn(e)),this.channelsToJoin=[this.userId,this.ioChannelId,...this.serverData.channelIds],this.joinedChannels=0,this.state=C.JOIN_CHANNELS,this.#n(wt(this.userId,this.channelsToJoin[0]));return}if(this.state===C.JOIN_CHANNELS){if(Tn(e),this.joinedChannels+=1,this.joinedChannels<this.channelsToJoin.length){this.#n(wt(this.userId,this.channelsToJoin[this.joinedChannels]));return}this.#g();return}let t=Rn(e);if(t.type==="disconnect"){this.#r(new Error(t.message));return}if(t.type!=="send-data")return;let s=this.channelNamesById.get(t.channelId);if(s){let o=this.security.headerPresent?this.security.unwrap(t.payload).payload:t.payload;this.#D(s,o);return}let{flags:r,payload:i}=this.#f(t.payload);if(i.length!==0){if(r&G.LICENSE_PKT){this.#S(i);return}this.#T(i)}}#f(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=C.TLS_HANDSHAKE,this.tls=new Oe({send:s=>this.#s(s),onData:s=>this.#c(s),onError:s=>this.#r(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&I.HYBRID){if(this.state=C.CREDSSP,this.credssp=new Pe({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.#m(e)}catch(t){this.#r(t)}}#m(e){this.state=C.MCS_CONNECT,this.requestedChannels=[],this.options.clipboard&&this.requestedChannels.push(Pt),this.options.remoteApp?.program&&this.requestedChannels.push(Dt),this.#n(wn(bn({width:this.options.width,height:this.options.height,clientName:this.options.clientName,keyboardLayout:this.options.keyboardLayout,selectedProtocol:e,encryptionMethods:e===I.RDP?11:0,channels:this.requestedChannels})))}#x(){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=Kt(this.clientRandom,t.modulus,t.exponent);this.#d(Re.securityExchange(s))}let e=Xn({domain:this.options.domain,username:this.options.username,password:this.options.password,performanceFlags:this.options.performance,autoLogon:!!this.options.password,remoteApp:!!this.options.remoteApp?.program});this.state=C.LICENSING,this.#d(this.security.wrap(e,G.INFO_PKT))}#d(e){this.#n(At(this.userId,this.ioChannelId,e))}#S(e){if(e.length<4)return;if(e[0]===Mi){console.info("[RDP] Licensing finished with an error alert (the normal path)"),this.state=C.CAPABILITIES;return}throw new Error("This host requires Remote Desktop licensing negotiation (per-device CAL), which this client does not implement.")}#T(e){let t=ns(e);if(t.pduSource&&(this.serverChannelId=t.pduSource),t.pduType===oe.DEMAND_ACTIVE){this.#R(t.payload);return}if(t.pduType===oe.DEACTIVATE_ALL){console.info("[RDP] Host deactivated the share; waiting for a new demand active"),this.state=C.CAPABILITIES;return}if(t.pduType===oe.SERVER_REDIRECT)throw new Error("This host redirected the session to another server, which this client cannot follow.");if(t.pduType!==oe.DATA)return;let s=ss(t.payload);if(s.compressedType&32)throw new Error("RDP: the host compressed a PDU although this client advertised no compression support");this.#_(s)}#R(e){let{shareId:t,capabilities:s}=rs(e);this.shareId=t;let r=Wn(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===C.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}=Kn({width:this.desktopWidth,height:this.desktopHeight,keyboardLayout:this.options.keyboardLayout,remoteApp:!!this.options.remoteApp?.program,remoteAppCaps:r});this.#M(oe.CONFIRM_ACTIVE,Qn(this.shareId,i,o)),this.#l(U.SYNCHRONIZE,zn(this.serverChannelId)),this.#l(U.CONTROL,bt(Rt.COOPERATE)),this.#l(U.CONTROL,bt(Rt.REQUEST_CONTROL)),this.#l(U.FONT_LIST,Zn())}#_(e){switch(e.pduType2){case U.UPDATE:this.#b(new T(e.payload));return;case U.POINTER:this.dispatchEvent(new CustomEvent("pointer",{detail:Ot(new T(e.payload))}));return;case U.FONT_MAP:this.#O();return;case U.SET_ERROR_INFO:{let t=new T(e.payload).u32le();if(t===0)return;this.#r(new Error(qn(t)));return}case U.SAVE_SESSION_INFO:console.info("[RDP] Host reported a completed sign-in");return;case U.SHUTDOWN_DENIED:console.info("[RDP] Host denied the shutdown request");return;case U.CONTROL:case U.SYNCHRONIZE:case U.PLAY_SOUND:case U.MONITOR_LAYOUT:return;default:return}}#b(e){let t=e.u16le();if(this.firstUpdateLogged||(this.firstUpdateLogged=!0,console.info("[RDP] First host update received",{updateType:t})),t===Ye.BITMAP){let s=It(e);s.length>0&&this.dispatchEvent(new CustomEvent("bitmap",{detail:{rects:s,palette:this.palette}}));return}if(t===Ye.PALETTE){this.palette=vt(e),this.dispatchEvent(new CustomEvent("palette",{detail:this.palette}));return}if(t===Ye.ORDERS){this.options.remoteApp?.program?this.#C(Mn(e)):console.warn("[RDP] Ignoring a drawing-order update the client did not advertise");return}}#C(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.#L(r)&&!this.#N(r)&&this.#y()}this.#v(),!(!this.remoteAppHadWindow||this.remoteAppWindows.size>0||this.remoteAppCloseTimer)&&(this.remoteAppCloseTimer=setTimeout(()=>{this.remoteAppCloseTimer=null,!(this.state!==C.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}})))},Bi))}get remoteAppPrimaryWindow(){let e=null,t=-1;for(let s of this.remoteAppWindows.values()){if(!kn(s)||s.showState===Ee.HIDDEN)continue;let r=(s.width||0)*(s.height||0);r>t&&(e=s,t=r)}return e}#L(e){let t=this.remoteAppPrimaryWindow;return!!t&&t.windowId===e.windowId}#N(e){let t=this.remoteAppFit;return t?Math.abs(e.x||0)<=Ze&&Math.abs(e.y||0)<=Ze&&Math.abs((e.width||0)-t.width)<=Ze&&Math.abs((e.height||0)-t.height)<=Ze:!0}#y(){this.remoteAppFitTimer||(this.remoteAppFitTimer=setTimeout(()=>{this.remoteAppFitTimer=null,this.#I()},Ki))}#I(){let e=this.remoteAppFit;if(!e||!this.rail||this.state!==C.CONNECTED)return;this.rail.setWorkArea(e.width,e.height);let t=this.remoteAppPrimaryWindow;if(!t||t.showState===Ee.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>=Wi||e.moves>=Vi)){if(e.attempts+=1,e.moves+=1,t.showState===Ee.MAXIMIZED){console.info("[RDP] Restoring the maximized RemoteApp window before fitting it"),this.rail.sysCommand(t.windowId,On.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})}}#v(){let e=this.remoteAppPrimaryWindow;if(!e||!e.width||!e.height||e.showState===Ee.MINIMIZED||e.showState===Ee.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(cs,Math.min(this.desktopWidth,Math.floor(e))),height:Math.max(cs,Math.min(this.desktopHeight,Math.floor(t))),attempts:0,moves:0,lastGeometry:""};return this.remoteAppFit=s,this.#y(),!0}#O(){this.state!==C.CONNECTED&&(this.state=C.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())}#U(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(),y=i.raw(Math.min(E,i.remaining));if(c!==0){if(c===2&&(this.fastPathFragments=[]),this.fastPathFragments.push(y.slice()),c!==1)continue;y=g(...this.fastPathFragments),this.fastPathFragments=[]}this.#P(a,y)}}#P(e,t){let s=new T(t);switch(e){case 1:{s.u16le();let r=It(s);r.length>0&&this.dispatchEvent(new CustomEvent("bitmap",{detail:{rects:r,palette:this.palette}}));return}case 2:this.palette=vt(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:Ot(new T(g(i,t)))}));return}default:return}}#D(e,t){let s=this.channelReassemblers.get(e);s||(s=new Ve,this.channelReassemblers.set(e,s));let r=s.push(t);if(r){if(e===Pt.name){this.#A().receive(r);return}e===Dt.name&&this.#k().receive(r)}}#w(e,t){let s=[...this.channelNamesById].find(([,r])=>r===e)?.[0];if(s===void 0)return!1;for(let r of Bn(t,St,Fn))this.#n(At(this.userId,s,this.security.wrap(r)));return!0}#k(){return this.rail?this.rail:(this.rail=new We({application:this.options.remoteApp,width:this.remoteAppFit?.width||this.desktopWidth,height:this.remoteAppFit?.height||this.desktopHeight,send:e=>this.#w(Dt.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.#r(new Error(e.message))}}),this.rail)}#A(){return this.clipboard?this.clipboard:(this.clipboard=new Be({send:e=>this.#w(Pt.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.#A().setLocalText(e||"")}get clipboardShared(){return!!this.clipboard?.ready}pasteToHost(e){if(!e||!this.connected)return Promise.resolve(!1);let t=()=>{this.connected&&(this.sendKeyByCode("ControlLeft",!0),this.sendKeyByCode("KeyV",!0),this.sendKeyByCode("KeyV",!1),this.sendKeyByCode("ControlLeft",!1))};return this.setClipboardText(e).then(s=>(s?t():this.sendUnicode(e),!0))}#M(e,t){this.#d(this.security.wrap(_t(e,this.userId,t)))}#l(e,t){this.#d(this.security.wrap($n(this.shareId,this.userId,e,t)))}get connected(){return this.state===C.CONNECTED}#h(e){!this.connected||e.length===0||this.#l(U.INPUT,jn(e))}sendKeyByCode(e,t){let s=Ut(e);return s?(this.#h([Ct(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(Lt(i,!0)),t.push(Lt(i,!1))}for(let s=0;s<t.length;s+=40)this.#h(t.slice(s,s+40))}sendCtrlAltDel(){let e=as.map(({code:t,pressed:s})=>{let r=Ut(t);return Ct(r.scancode,s,r.extended)});this.#h(e)}sendMouseMove(e,t){this.#h([$e(Z.MOVE,e,t)])}sendMouseButton(e,t,s,r){let i={0:Z.BUTTON1,1:Z.BUTTON3,2:Z.BUTTON2}[e];if(i===void 0){let o=e===3?1:2;this.#h([Jn(o|(t?Z.DOWN:0),s,r)]);return}this.#h([$e(i|(t?Z.DOWN:0),s,r)])}sendWheel(e,t,s,r=!1){let i=Yn(e,r);i&&this.#h([$e(i,t,s)])}sendKeyboardSync(e){this.toggleFlags=e>>>0,this.#h([Nt(this.toggleFlags)])}refresh(e){!this.connected||!this.refreshRectSupported||this.#l(U.REFRESH_RECT,es([e||{left:0,top:0,right:this.desktopWidth-1,bottom:this.desktopHeight-1}]))}setOutputEnabled(e){this.connected&&this.#l(U.SUPPRESS_OUTPUT,ts(e,{left:0,top:0,right:this.desktopWidth-1,bottom:this.desktopHeight-1}))}};function Yi(n){return(n&192)!==192?n>>5:(n&240)===240?n:n>>4}function qi(n,e,t,s){let r=new Uint32Array(e*t),i=s>=4?4294967295:(1<<s*8)-1,o=0,a=0,c=i,d=!1,E=!0,y=()=>{let f=0;for(let l=0;l<s;l++)f|=n[o+l]<<l*8;return o+=s,f>>>0},m=f=>{let l=n[o];if(f===2){let x=l&31;return x===0?(o+=2,n[o-1]+1):(o+=1,x*8)}if(f===13){let x=l&15;return x===0?(o+=2,n[o-1]+1):(o+=1,x*8)}if(f===0||f===1||f===3||f===4){let x=l&31;return x===0?(o+=2,n[o-1]+32):(o+=1,x)}if(f===12||f===14){let x=l&15;return x===0?(o+=2,n[o-1]+16):(o+=1,x)}let A=n[o+1]|n[o+2]<<8;return o+=3,A},S=(f,l)=>{let A=1;for(let x=0;x<l;x++){if(E)r[a]=f&A?c:0;else{let R=r[a-e];r[a]=f&A?(R^c)>>>0:R}a++,A=A<<1&255}};for(;o<n.length&&a<r.length;){E&&a>=e&&(E=!1);let f=Yi(n[o]);if(f===0||f===240){let l=m(f);if(E)for(d&&(r[a++]=c,l--);l-- >0&&a<r.length;)r[a++]=0;else for(d&&(r[a]=(r[a-e]^c)>>>0,a++,l--);l-- >0&&a<r.length;)r[a]=r[a-e],a++;d=!0;continue}switch(d=!1,f){case 1:case 241:case 12:case 246:{let l=m(f);if((f===12||f===246)&&(c=y()),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=m(f),A=y(),x=y();for(;l-- >0&&a<r.length-1;)r[a++]=A,r[a++]=x;break}case 3:case 243:{let l=m(f),A=y();for(;l-- >0&&a<r.length;)r[a++]=A;break}case 2:case 242:case 13:case 247:{let l=m(f);for((f===13||f===247)&&(c=y());l>8;)S(n[o++],8),l-=8;l>0&&S(n[o++],l);break}case 4:case 244:{let l=m(f);for(;l-- >0&&a<r.length;)r[a++]=y();break}case 249:o++,S(3,8);break;case 250:o++,S(5,8);break;case 253:o++,r[a++]=i;break;case 254:o++,r[a++]=0;break;default:throw new Error(`RDP: unsupported bitmap compression order 0x${f.toString(16)}`)}}return r}function $i(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 Xi(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 d=0;for(let E=0;E<s;E++)d|=n[a+E]<<E*8;r[o+c]=d>>>0,a+=s}}return r}function zi(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 d=r*4;s[d]=o,s[d+1]=a,s[d+2]=c,s[d+3]=255}return s}function hs(n,e){let t=Math.max(1,Math.ceil(n.bitsPerPixel/8)),s=n.compressed?$i(qi(n.data,n.width,n.height,t),n.width):Xi(n.data,n.width,n.height,t);return zi(s,n.bitsPerPixel,e)}var Mt=/Mac|iPod|iPhone|iPad/.test(globalThis.navigator?.platform||globalThis.navigator?.userAgent||""),ls={MetaLeft:"ControlLeft",MetaRight:"ControlRight"},us=60,Zi=16,ds=20,Qi=8,ji=1,je=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}#i(){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.#i());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(Qi,Math.max(ji,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,d=r.scrollLeft+a,E=r.scrollTop+c;this.zoom=s,this.applyScale();let y=i>0?this.scale/i:1;r.scrollLeft=d*y-a,r.scrollTop=E*y-c}panBy(e,t){let s=this.scrollHost,r=s.scrollLeft,i=s.scrollTop;return s.scrollLeft=r-e,s.scrollTop=i-t,{x:r-s.scrollLeft,y:i-s.scrollTop}}canPan(){if(this.zoom<=1.05)return!1;let e=this.scrollHost;return e.scrollWidth>e.clientWidth+2||e.scrollHeight>e.clientHeight+2}setScaleViewport(e){this.scaleViewport=e,e||(this.userZoomed=!1),this.applyScale()}resetZoom(){this.userZoomed=!1,this.zoom=1,this.applyScale();let e=this.scrollHost;e.scrollLeft=0,e.scrollTop=0}drawRects(e,t){t&&(this.palette=t);for(let s of e)if(!(s.width===0||s.height===0))try{let r=hs(s,this.palette),i=new ImageData(r,s.width,s.height);this.context.putImageData(i,s.left,s.top)}catch(r){console.warn("[RDP] Dropped an undecodable bitmap rectangle",{geometry:`${s.width}x${s.height}+${s.left}+${s.top}`,bitsPerPixel:s.bitsPerPixel,compressed:s.compressed,error:r instanceof Error?r.message:String(r)})}}#n(e){let{width:t,height:s,xorBpp:r,xorMask:i,andMask:o,hotSpotX:a,hotSpotY:c}=e;if(!t||!s)return null;let d=Math.ceil(t*r/8/2)*2,E=Math.ceil(t/8/2)*2,y=new Uint8ClampedArray(t*s*4);for(let l=0;l<s;l++){let A=s-1-l;for(let x=0;x<t;x++){let R=o[A*E+(x>>3)],h=R!==void 0&&(R&128>>(x&7))!==0,u=0,w=0,b=0,_=h?0:255;if(r===1)u=w=b=i[A*d+(x>>3)]&128>>(x&7)?255:0;else{let P=r/8,v=A*d+x*P;if(r===16){let ee=i[v]|i[v+1]<<8;u=(ee>>11&31)*255/31,w=(ee>>5&63)*255/63,b=(ee&31)*255/31}else b=i[v]||0,w=i[v+1]||0,u=i[v+2]||0,r===32&&i[v+3]!==void 0&&o.length===0&&(_=i[v+3])}let L=(l*t+x)*4;y[L]=u,y[L+1]=w,y[L+2]=b,y[L+3]=_}}let m=document.createElement("canvas");m.width=t,m.height=s,m.getContext("2d").putImageData(new ImageData(y,t,s),0,0);let S=Math.min(a||0,t-1),f=Math.min(c||0,s-1);return`url(${m.toDataURL("image/png")}) ${S} ${f}, default`}applyPointer(e){if(e.kind==="system"){this.canvas.style.cursor=e.hidden?"none":"default";return}if(e.kind!=="position"){if(e.kind==="cached"){let t=this.cursorCache.get(e.cacheIndex);t&&(this.canvas.style.cursor=t);return}if(e.kind==="bitmap")try{let t=this.#n(e);if(!t)return;this.cursorCache.set(e.cacheIndex,t),this.canvas.style.cursor=t}catch(t){console.warn("[RDP] Could not build a cursor from the host pointer update",t)}}}#s(e){let t=this.canvas.getBoundingClientRect(),s=this.width/(t.width||1),r=this.height/(t.height||1);return{x:Math.max(0,Math.min(this.width-1,(e.clientX-t.left)*s)),y:Math.max(0,Math.min(this.height-1,(e.clientY-t.top)*r))}}#o(e){if(this.keyboardSynced||!this.client)return;this.keyboardSynced=!0;let t=0;e.getModifierState?.("CapsLock")&&(t|=qe.CAPS_LOCK),e.getModifierState?.("NumLock")&&(t|=qe.NUM_LOCK),e.getModifierState?.("ScrollLock")&&(t|=qe.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,d=0,E=0,y={x:0,y:0},m=0,S=0,f=0,l=null,A=h=>({x:(h[0].clientX+h[1].clientX)/2,y:(h[0].clientY+h[1].clientY)/2}),x=h=>Math.hypot(h[0].clientX-h[1].clientX,h[0].clientY-h[1].clientY),R=()=>{r=!1,s&&t()&&this.client.sendMouseMove(s.x,s.y),s=null};this.handlers={mousemove:h=>{t()&&(s=this.#s(h),r||(r=!0,requestAnimationFrame(R)))},mousedown:h=>{if(this.canvas.focus(),!t())return;h.preventDefault();let{x:u,y:w}=this.#s(h);this.client.sendMouseButton(h.button,!0,u,w)},mouseup:h=>{if(!t())return;h.preventDefault();let{x:u,y:w}=this.#s(h);this.client.sendMouseButton(h.button,!1,u,w)},contextmenu:h=>h.preventDefault(),wheel:h=>{if(!t())return;h.preventDefault();let u=h.deltaY;if(h.deltaMode===WheelEvent.DOM_DELTA_LINE&&(u*=Zi),h.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(u*=Math.max(1,this.canvas.clientHeight||this.height)),!u||(i&&Math.sign(i)!==Math.sign(u)&&(i=0),i+=u,Math.abs(i)<us))return;let w=Math.sign(i);i-=w*us;let{x:b,y:_}=this.#s(h);this.client.sendWheel(w,b,_)},touchstart:h=>{if(this.canvas.focus(),!!t()){if(h.preventDefault(),h.touches.length===1){l="tap";let u=h.touches[0];a=u.clientX,c=u.clientY;let{x:w,y:b}=this.#s(u);this.client.sendMouseMove(w,b),this.client.sendMouseButton(0,!0,w,b),o=!0}else if(h.touches.length===2){if(l="undecided",o){let{x:b,y:_}=this.#s({clientX:a,clientY:c});this.client.sendMouseButton(0,!1,b,_),o=!1}let u=A(h.touches),w=x(h.touches);y={x:u.x,y:u.y},m=w,d=u.y,E=u.x,S=w,f=0}}},touchmove:h=>{if(t()){if(h.preventDefault(),h.touches.length===1&&l==="tap"){let u=h.touches[0];a=u.clientX,c=u.clientY;let{x:w,y:b}=this.#s(u);this.client.sendMouseMove(w,b)}else if(h.touches.length===2){let u=A(h.touches),w=u.x,b=u.y,_=x(h.touches),L=d-b,P=E-w;d=b,E=w;let v=Math.hypot(w-y.x,b-y.y),ee=Math.abs(_-m),et=m>0?_/m:1;if((l==="undecided"||l==="gesture")&&(ee>20&&Math.abs(et-1)>.15&&ee>v*.8?l="pinch":v>8&&(l="scroll")),l==="pinch")S>0&&Math.abs(_-S)>1&&(this.userZoomed=!0,this.setZoom(this.zoom*(_/S),{x:w,y:b})),S=_;else if(l==="scroll"){if(S=_,this.canPan()){this.panBy(P*-1,L*-1),f=0;return}for(L&&f&&Math.sign(f)!==Math.sign(L)&&(f=0),f+=L;Math.abs(f)>=ds;){let Ie=Math.sign(f);f-=Ie*ds;let{x:tt,y:nt}=this.#s({clientX:w,clientY:b});this.client.sendWheel(Ie,tt,nt)}}}}},touchend:h=>{if(t())if(h.preventDefault(),h.touches.length===0){if(o){let{x:u,y:w}=this.#s({clientX:a,clientY:c});this.client.sendMouseButton(0,!1,u,w),o=!1}l==="pinch"&&this.zoom<=1.05&&this.resetZoom(),l=null,f=0,S=0}else h.touches.length===1&&(l==="gesture"||l==="pinch"||l==="scroll"||l==="undecided")&&(l==="pinch"&&this.zoom<=1.05&&this.resetZoom(),l=null,S=0,f=0)},touchcancel:h=>{if(t()){if(o){let{x:u,y:w}=this.#s({clientX:a,clientY:c});this.client.sendMouseButton(0,!1,u,w),o=!1}l==="pinch"&&this.zoom<=1.05&&this.resetZoom(),l=null,f=0,S=0}},keydown:h=>{if(!t()||(this.#o(h),this.#a(h)))return;let u=this.#r(h.code);if(this.client.sendKeyByCode(u,!0)){if(h.preventDefault(),Mt&&h.metaKey&&!ls[h.code]){this.client.sendKeyByCode(u,!1);return}this.heldKeys.add(u)}},keyup:h=>{if(!t()||this.#a(h))return;let u=this.#r(h.code);this.client.sendKeyByCode(u,!1)&&(this.heldKeys.delete(u),h.preventDefault())},paste:h=>{if(!t())return;let u=h.target,w=u instanceof Node&&this.container.contains(u);if(document.activeElement!==this.canvas&&!w)return;h.preventDefault();let b=h.clipboardData?.getData("text/plain")||"";b&&this.client.pasteToHost(b)},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)}#r(e){return Mt&&ls[e]||e}#a(e){return e.code!=="KeyV"?!1:Mt?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 Ne={vnc:5900,rdp:3389,ssh:22},fa=Ne.ssh;var Ji={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 eo(n,e){let t=new URLSearchParams({host:e.host,port:String(e.port),security:e.security});return`${n}/rdp-ws?${t}`}function to({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 Gt=class extends EventTarget{protocol="rdp";constructor(e,t,s={}){super(),this.url=t,this.options=s,this.display=new je(e),this.display.viewOnly=!!s.viewOnly,this._rfbConnectionState="connecting",this._scaleViewport=s.scaleViewport!==!1,this.display.scaleViewport=this._scaleViewport,this.lastErrorMessage="",this.hostLabel=s.hostLabel||"Remote Desktop",this.#e(s.security||"auto"),this.remoteAppLayoutObserver=s.remoteApp?.program&&typeof ResizeObserver=="function"?new ResizeObserver(()=>this.fitToViewport()):null,this.remoteAppLayoutObserver?.observe(this.display.scrollHost)}#e(e){this.security=e,this.client=new Qe(this.url,{width:this.options.width,height:this.options.height,username:this.options.credentials?.username||"",password:this.options.credentials?.password||"",domain:this.options.domain||"",security:e,keyboardLayout:this.options.keyboardLayout||1033,clientName:this.options.clientName||"cf-gateway",remoteApp:this.options.remoteApp||null}),this.client.addEventListener("ready",t=>{let{width:s,height:r}=t.detail;this.display.resize(s,r),this.display.attachInput(this.client),this.display.focus(),this.fitToViewport(),this._rfbConnectionState="connected",this.dispatchEvent(new CustomEvent("connect")),this.dispatchEvent(new CustomEvent("desktopname",{detail:{name:`${this.hostLabel} (${s}x${r})`}}))}),this.client.addEventListener("resize",t=>{let{width:s,height:r}=t.detail;this.display.resize(s,r),this.dispatchEvent(new CustomEvent("desktopname",{detail:{name:`${this.hostLabel} (${s}x${r})`}})),this.fitToViewport()}),this.client.addEventListener("remoteappviewport",t=>{this.display.setViewport(t.detail)}),this.client.addEventListener("bitmap",t=>{this.display.drawRects(t.detail.rects,t.detail.palette),this.dispatchEvent(new CustomEvent("frame",{detail:{rects:t.detail.rects}}))}),this.client.addEventListener("palette",t=>{this.display.palette=t.detail}),this.client.addEventListener("pointer",t=>{this.display.applyPointer(t.detail)}),this.client.addEventListener("clipboard",t=>{this.dispatchEvent(new CustomEvent("clipboard",{detail:{text:t.detail.text}}))}),this.client.addEventListener("remoteappresult",t=>{this.dispatchEvent(new CustomEvent("remoteappresult",{detail:t.detail}))}),this.client.addEventListener("remoteappwindow",t=>{this.dispatchEvent(new CustomEvent("remoteappwindow",{detail:t.detail}))}),this.client.addEventListener("remoteappclosed",t=>{this.dispatchEvent(new CustomEvent("remoteappclosed",{detail:t.detail}))}),this.client.addEventListener("error",t=>{this.lastErrorMessage=t.detail.message}),this.client.addEventListener("close",t=>{this._rfbConnectionState="disconnected",this.remoteAppLayoutObserver?.disconnect(),this.display.destroy(),this.dispatchEvent(new CustomEvent("disconnect",{detail:{clean:!!t.detail.clean,message:this.lastErrorMessage||t.detail.message||"",code:t.detail.code,phase:t.detail.phase}}))})}fitToViewport(){if(!this.options.remoteApp?.program)return!1;let e=this.display.container.getBoundingClientRect(),t=Math.floor(e.width||this.options.width||0),s=Math.floor(e.height||this.options.height||0);return t<=0||s<=0?!1:this.client.fitRemoteApp(t,s)}get connected(){return this._rfbConnectionState==="connected"}get canvas(){return this.display?.canvas??null}get socket(){return this.client.socket??null}get _sock(){return{_websocket:this.client.socket}}get scaleViewport(){return this._scaleViewport}set scaleViewport(e){this._scaleViewport=!!e,this.display.setScaleViewport(this._scaleViewport)}get viewOnly(){return this.display.viewOnly}set viewOnly(e){this.display.viewOnly=!!e,e&&this.display.releaseAllKeys()}sendKey(e,t,s){t&&this.client.sendKeyByCode(t,s)||!s||!e||e>=32&&e<=1114111&&this.client.sendUnicode(String.fromCodePoint(e))}sendCtrlAltDel(){this.client.sendCtrlAltDel()}movePointer(e,t){return!this.client?.connected||this.display.viewOnly?!1:(this.client.sendMouseMove(...this.#t(e,t)),!0)}clickPointer(e,t,s=0){if(!this.client?.connected||this.display.viewOnly)return!1;let[r,i]=this.#t(e,t);return this.client.sendMouseMove(r,i),this.pointerButton(r,i,s,!0),this.pointerButton(r,i,s,!1),!0}pointerButton(e,t,s=0,r=!0){if(!this.client?.connected||this.display.viewOnly)return!1;let[i,o]=this.#t(e,t);return this.client.sendMouseButton(s,r,i,o),!0}scrollPointer(e,t,s){if(!this.client?.connected||this.display.viewOnly)return!1;let[r,i]=this.#t(e,t);for(let o=0;o<Math.min(20,Math.abs(s.y));o++)this.client.sendWheel(Math.sign(s.y),r,i,!1);for(let o=0;o<Math.min(20,Math.abs(s.x));o++)this.client.sendWheel(Math.sign(s.x),r,i,!0);return!0}typeText(e){if(!this.client?.connected||this.display.viewOnly||!e)return!1;let t="",s=()=>{t&&(this.client.sendUnicode(t),t="")};for(let r of e)r===`
|
|
2
|
-
`||r==="\r"?(s(),this.client.sendKeyByCode("Enter",!0),this.client.sendKeyByCode("Enter",!1)):r===" "?(s(),this.client.sendKeyByCode("Tab",!0),this.client.sendKeyByCode("Tab",!1)):t+=r;return s(),!0}#t(e,t){return[Math.max(0,Math.min((this.display.width||1)-1,Math.round(e))),Math.max(0,Math.min((this.display.height||1)-1,Math.round(t)))]}get screenGeometry(){return{width:this.display.width,height:this.display.height,viewport:{...this.display.viewport}}}clipboardPasteFrom(e){if(!e)return;let t=this.client.setClipboardText(e);if(!t||typeof t.then!="function"){this.client.sendUnicode(e);return}t.then(s=>{s||this.client.sendUnicode(e)})}pasteText(e){return e?this.client.pasteToHost(e):!1}releaseKeyboard(){this.display.releaseAllKeys(),this.display.blur()}get clipboardShared(){return this.client.clipboardShared}disconnect(){this.remoteAppLayoutObserver?.disconnect(),this.client.disconnect(),this.display.destroy(),this._rfbConnectionState="disconnected"}},ps={protocol:"rdp",label:"RDP Client",defaultPort:Ne.rdp,dialog:Ji,buildUrl:eo,createSession:(n,e,t)=>new Gt(n,e,t),describeState:()=>({}),describeDisconnect:to};import Ht from"@novnc/novnc";function fs(n){let e=[],t=[{amount:n.y,negativeMask:8,positiveMask:16},{amount:n.x,negativeMask:32,positiveMask:64}];for(let{amount:s,negativeMask:r,positiveMask:i}of t){let o=s<0?r:i;for(let a=0;a<Math.min(20,Math.abs(s));a++)e.push(o)}return e}var no={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 so(n,e){let t=new URLSearchParams({host:e.host,port:String(e.port)});return e.username&&t.set("vnc_user",e.username),e.password&&t.set("vnc_pass",e.password),`${n}/ws?${t}`}var Es={0:1,1:2,2:4};function ro(n){if(!("detail"in n))return{};let e=n.detail;if(!e||typeof e!="object")return{};let t={};for(let[s,r]of Object.entries(e))t[s]=r;return t}var Je=class extends EventTarget{protocol="vnc";#e;#t;#i=null;#n=null;#s=!1;#o=null;constructor(e,t,s){super(),this.#t=s.credentials,this.#e=new Ht(e,t,{credentials:{username:s.credentials.username,password:s.credentials.password},shared:!0,wsProtocols:["binary"]}),this.#e._cursor?._canvas?.classList.add("remote-cursor-overlay"),this.#e.showDotCursor=!0,this.#e.resizeSession=s.allowRemoteResize,this.#e.clipViewport=!0,this.#e.scaleViewport=s.scaleViewport,this.#e.viewOnly=s.viewOnly,this.#e.qualityLevel=s.quality,this.#e.compressionLevel=s.compression,this.#r();for(let r of["connect","disconnect","credentialsrequired","desktopname","clipboard","bell"])this.#e.addEventListener(r,i=>{r==="credentialsrequired"&&this.#e.sendCredentials({username:this.#t.username,password:this.#t.password});let o=ro(i);r==="disconnect"&&this.#o&&(o.code=this.#o.code,o.reason=this.#o.reason),this.dispatchEvent(new CustomEvent(r,{detail:o}))})}#r(){let e=()=>{let r=this.#e._sock?._websocket??null;if(!r||this.#i===r)return!!r;this.#i=r;let i=()=>{this.#s||r.readyState!==WebSocket.OPEN||(this.#s=!0,r.send(Xe))};return r.addEventListener("open",i),r.addEventListener("close",o=>{this.#o={code:o.code,reason:o.reason??""},this.#a()},!0),this.#n=setInterval(()=>{if(r.readyState===WebSocket.OPEN)try{r.send(ze);let o=this.#e._sock;o&&this.#e._rfbConnectionState==="connected"&&Ht.messages.fbUpdateRequest(o,!0,0,0,1,1)}catch{}},25e3),i(),!0};if(e())return;let t=0,s=setInterval(()=>{(e()||++t>20)&&clearInterval(s)},25)}#a(){this.#n&&clearInterval(this.#n),this.#n=null}get connected(){return this.#e._rfbConnectionState==="connected"}get socket(){return this.#e._sock?._websocket??null}get canvas(){return this.#e._canvas}get scaleViewport(){return this.#e.scaleViewport}set scaleViewport(e){this.#e.scaleViewport=e}get viewOnly(){return this.#e.viewOnly}set viewOnly(e){this.#e.viewOnly=e}get qualityLevel(){return this.#e.qualityLevel}set qualityLevel(e){this.#e.qualityLevel=e}get compressionLevel(){return this.#e.compressionLevel}set compressionLevel(e){this.#e.compressionLevel=e}get screenGeometry(){let e=this.#e._fbWidth||0,t=this.#e._fbHeight||0;return{width:e,height:t,viewport:{x:0,y:0,width:e,height:t}}}describeState(){let e=this.#e._sock;return{connectionState:this.#e._rfbConnectionState,initializationState:this.#e._rfbInitState,queuedReceiveBytes:Math.max(0,(e?._rQlen??0)-(e?._rQi??0))}}disconnect(){this.#a(),this.#e.disconnect()}sendKey(e,t,s){this.#e.sendKey(e,t,s)}sendClipboard(e){this.#e.clipboardPasteFrom(e)}releaseKeyboard(){this.#e.blur()}#c(e,t,s){let r=this.#e._sock;if(!r||this.#e._rfbConnectionState!=="connected"||this.#e.viewOnly)return!1;let i=this.#e._fbWidth||1,o=this.#e._fbHeight||1;return Ht.messages.pointerEvent(r,Math.max(0,Math.min(i-1,Math.round(e))),Math.max(0,Math.min(o-1,Math.round(t))),s),!0}movePointer(e,t){return this.#c(e,t,0)}clickPointer(e,t,s=0){return this.#c(e,t,0)?(this.#c(e,t,Es[s]),this.#c(e,t,0),!0):!1}pointerButton(e,t,s=0,r=!0){return this.#c(e,t,r?Es[s]:0)}scrollPointer(e,t,s){for(let r of fs(s))if(!this.#c(e,t,r)||!this.#c(e,t,0))return!1;return!0}typeText(e){if(this.#e._rfbConnectionState!=="connected"||this.#e.viewOnly||!e)return!1;for(let t of e){let s=t.codePointAt(0)??0,r=t===`
|
|
3
|
-
`?65293:t===" "?65289:s;this.#e.sendKey(r,null,!0),this.#e.sendKey(r,null,!1)}return!0}};function io({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 ms={protocol:"vnc",label:"VNC Client",defaultPort:Ne.vnc,dialog:no,buildUrl:so,createSession:(n,e,t)=>new Je(n,e,t),describeState:n=>n instanceof Je?n.describeState():{},describeDisconnect:io};var ys={vnc:ms,rdp:ps};function oo(n){return ys[n]??ys.vnc}function La(n,e,t){if(t)return t;let s=n.close?.code,r=n.close?.reason.trim()??"",i=s?` (WebSocket ${s}${r?`: ${r}`:""})`:"",o={...s===void 0?{}:{code:s},reason:r,suffix:i},a=oo(n.protocol),c=a.describeDisconnect(o);if(c)return c;let d=a.protocol.toUpperCase();return/tcp (reached )?eof/i.test(r)?`The ${d} host accepted the connection and then closed it${i}. Check its remote-access permissions and the account name.`:s===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.":r?`The remote session ended${i}.`:e?`The remote server closed the session cleanly${i||" (no reason supplied)"}.`:`The ${d} negotiation failed${i||" before the server supplied a close reason"}.`}export{ys as DRIVERS,oo as driverFor,La as explainDisconnect};
|
|
@@ -1,66 +0,0 @@
|
|
|
1
|
-
export declare const DEFAULT_PORT = 22;
|
|
2
|
-
/**
|
|
3
|
-
* How patient `runCommand` is, in three different senses.
|
|
4
|
-
*
|
|
5
|
-
* A single deadline cannot tell "the shell ignored me" apart from "the
|
|
6
|
-
* installer is three minutes into a download", and a short one turns every
|
|
7
|
-
* real piece of work -- a package install, a build, a large copy -- into a
|
|
8
|
-
* false failure that also leaves the command running on the far side.
|
|
9
|
-
*
|
|
10
|
-
* So the wait is judged by what the shell is doing. It has START_MS to
|
|
11
|
-
* acknowledge the command at all; after that it may take as long as it likes
|
|
12
|
-
* as long as it keeps printing, and only silence longer than IDLE_MS, or a run
|
|
13
|
-
* longer than MAX_MS, is treated as stuck.
|
|
14
|
-
*/
|
|
15
|
-
export declare const COMMAND_START_MS = 20000;
|
|
16
|
-
export declare const COMMAND_IDLE_MS: number;
|
|
17
|
-
export declare const COMMAND_MAX_MS: number;
|
|
18
|
-
/**
|
|
19
|
-
* The one line that runs `command` and marks where its output starts and ends.
|
|
20
|
-
*
|
|
21
|
-
* Each shell gets its own, because none of the three agree on how to print a
|
|
22
|
-
* string, run a command and read back its exit status.
|
|
23
|
-
*/
|
|
24
|
-
export declare function frameCommand(family: any, command: string, id: any): string;
|
|
25
|
-
export declare class SshSession extends EventTarget {
|
|
26
|
-
#private;
|
|
27
|
-
/**
|
|
28
|
-
* @param {string} url gateway WebSocket URL
|
|
29
|
-
* @param {object} options
|
|
30
|
-
* @param {string} options.username
|
|
31
|
-
* @param {string} [options.password]
|
|
32
|
-
* @param {'powershell'} [options.preferredShell]
|
|
33
|
-
* @param {(info: object) => Promise<boolean>} [options.verifyHost]
|
|
34
|
-
* @param {(prompt: object) => Promise<string>} [options.requestInput]
|
|
35
|
-
*/
|
|
36
|
-
constructor(url: string, options?: {});
|
|
37
|
-
connect(): void;
|
|
38
|
-
disconnect(): void;
|
|
39
|
-
/** Send keystrokes, or anything else the terminal produces, to the shell. */
|
|
40
|
-
write(data: Uint8Array): void;
|
|
41
|
-
/**
|
|
42
|
-
* Run one command in this shell and return what it printed.
|
|
43
|
-
*
|
|
44
|
-
* Deliberately the *same* shell the user is looking at, not a second channel:
|
|
45
|
-
* a command the assistant runs inherits the working directory, the
|
|
46
|
-
* environment and the login the user already has, and it appears in their
|
|
47
|
-
* terminal as it happens. An agent acting on a machine invisibly is worse
|
|
48
|
-
* than an agent that is slower to read.
|
|
49
|
-
*
|
|
50
|
-
* The output is framed by markers rather than measured, because an
|
|
51
|
-
* interactive shell echoes its input and prints a prompt around it. The
|
|
52
|
-
* markers are assembled by the shell from two pieces, so the echoed command
|
|
53
|
-
* line -- which contains the pieces but not the joined marker -- never looks
|
|
54
|
-
* like the real boundary.
|
|
55
|
-
*
|
|
56
|
-
* A `command` event brackets the run so the terminal can label it, and the
|
|
57
|
-
* three deadlines above decide when a command is stuck rather than slow.
|
|
58
|
-
*/
|
|
59
|
-
runCommand(command: string, { startMs, idleMs, maxMs, }?: {
|
|
60
|
-
idleMs?: number;
|
|
61
|
-
maxMs?: number;
|
|
62
|
-
startMs?: number;
|
|
63
|
-
}): Promise<unknown>;
|
|
64
|
-
/** Tell the shell its window changed, so full-screen programs redraw. */
|
|
65
|
-
resize(columns: number, rows: number): void;
|
|
66
|
-
}
|
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
var o={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_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},se=1,re={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 Ue=new TextEncoder,ve=new TextDecoder;function S(s){return Ue.encode(s)}function k(s){return ve.decode(s)}function m(...s){let e=s.reduce((r,i)=>r+i.length,0),t=new Uint8Array(e),n=0;for(let r of s)t.set(r,n),n+=r.length;return t}function x(s){let e="";for(let t of s)e+=String.fromCharCode(t);return btoa(e)}function X(s){return x(s).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}var c=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 n=new Uint8Array(new ArrayBuffer(t));n.set(this.bytes.subarray(0,this.offset)),this.bytes=n,this.view=new DataView(n.buffer)}u8(e){return this.#e(1),this.view.setUint8(this.offset,e),this.offset+=1,this}boolean(e){return this.u8(e?1:0)}u32(e){return this.#e(4),this.view.setUint32(this.offset,e>>>0,!1),this.offset+=4,this}raw(e){return this.#e(e.length),this.bytes.set(e,this.offset),this.offset+=e.length,this}string(e){let t=typeof e=="string"?S(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 n=e.subarray(t);return n.length===0?this.u32(0):(n[0]??0)&128?(this.u32(n.length+1).u8(0),this.raw(n)):this.u32(n.length).raw(n)}get length(){return this.offset}take(){return this.bytes.slice(0,this.offset)}},u=class{bytes;view;offset;constructor(e,t=0){this.bytes=e,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.offset=t}get remaining(){return this.bytes.length-this.offset}#e(e){if(e<0||this.remaining<e)throw new Error(`SSH: truncated packet (needed ${e} bytes, ${this.remaining} left)`)}u8(){return this.#e(1),this.view.getUint8(this.offset++)}boolean(){return this.u8()!==0}u32(){this.#e(4);let e=this.view.getUint32(this.offset,!1);return this.offset+=4,e}raw(e){this.#e(e);let t=this.bytes.subarray(this.offset,this.offset+e);return this.offset+=e,t}stringBytes(){return this.raw(this.u32())}string(){return k(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 Q(s,e){if(s.length===e)return s;if(s.length>e)return s.subarray(s.length-e);let t=new Uint8Array(e);return t.set(s,e-s.length),t}var p=globalThis.crypto?.subtle,_e={"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"}},Y={"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 ie(s,e){if(!p)return!1;try{return await p.generateKey(s,!1,e),!0}catch{return!1}}var P=null;async function oe(){if(P)return P;let[s,e]=await Promise.all([ie({name:"X25519"},["deriveBits"]),ie({name:"Ed25519"},["sign","verify"])]),t=[];s&&t.push("curve25519-sha256","curve25519-sha256@libssh.org"),t.push("ecdh-sha2-nistp256");let n=[];return e&&n.push("ssh-ed25519"),n.push("rsa-sha2-512","rsa-sha2-256","ecdsa-sha2-nistp256"),P={kex:t,hostKey:n,x25519:s,ed25519:e},P}async function ae(s){let e=_e[s];if(!e)throw new Error(`SSH: unsupported key exchange ${s}`);if(e.type==="x25519"){let r=await p.generateKey({name:"X25519"},!1,["deriveBits"]),i=new Uint8Array(await p.exportKey("raw",r.publicKey));return{hash:e.hash,publicKey:i,async sharedSecret(a){if(a.length!==32)throw new Error("SSH: the host sent a malformed X25519 key.");let d=await p.importKey("raw",a,{name:"X25519"},!1,[]),l=new Uint8Array(await p.deriveBits({name:"X25519",public:d},r.privateKey,256));if(l.every(h=>h===0))throw new Error("SSH: the host sent a degenerate X25519 key.");return l}}}let t=await p.generateKey({name:"ECDH",namedCurve:e.curve},!1,["deriveBits"]),n=new Uint8Array(await p.exportKey("raw",t.publicKey));return{hash:e.hash,publicKey:n,async sharedSecret(r){let i=await p.importKey("raw",r,{name:"ECDH",namedCurve:e.curve},!1,[]);return new Uint8Array(await p.deriveBits({name:"ECDH",public:i},t.privateKey,256))}}}function he(s){return new u(s).string()}async function ce(s){let e=new Uint8Array(await p.digest("SHA-256",s));return`SHA256:${x(e).replace(/=+$/,"")}`}async function ke(s,e){let t=Y[s];if(!t)throw new Error(`SSH: unsupported host key algorithm ${s}`);let n=new u(e),r=n.string();if(r!==t.keyType)throw new Error(`SSH: the host key is a ${r} but was announced as ${s}.`);if(t.kind==="ed25519")return p.importKey("raw",n.stringBytes(),{name:"Ed25519"},!1,["verify"]);if(t.kind==="rsa"){let i=n.mpint(),a=n.mpint();return p.importKey("jwk",{kty:"RSA",n:X(a),e:X(i),ext:!0},{name:"RSASSA-PKCS1-v1_5",hash:t.hash},!1,["verify"])}return n.string(),p.importKey("raw",n.stringBytes(),{name:"ECDSA",namedCurve:t.curve},!1,["verify"])}function xe(s,e){let t=new u(e),n=t.string();if(n!==s)throw new Error(`SSH: the host signed with ${n} after agreeing on ${s}.`);let r=t.stringBytes();if(Y[s]?.kind!=="ecdsa")return r;let i=new u(r),a=i.mpint(),d=i.mpint();return m(Q(a,32),Q(d,32))}async function le({algorithm:s,keyBlob:e,signatureBlob:t,exchangeHash:n}){let{kind:r,hash:i}=Y[s],a=await ke(s,e),d=xe(s,t),l=r==="ecdsa"?{name:"ECDSA",hash:i}:r==="rsa"?{name:"RSASSA-PKCS1-v1_5"}:{name:"Ed25519"};return p.verify(l,a,d,n)}async function ue({hash:s,clientVersion:e,serverVersion:t,clientKexInit:n,serverKexInit:r,hostKeyBlob:i,clientPublicKey:a,serverPublicKey:d,sharedSecret:l}){let h=new c(1024);return h.string(e),h.string(t),h.string(n),h.string(r),h.string(i),h.string(a),h.string(d),h.mpint(l),new Uint8Array(await p.digest(s,h.take()))}async function N({hash:s,sharedSecret:e,exchangeHash:t,letter:n,sessionId:r,length:i}){let a=new c(64+t.length).mpint(e).take(),d=m(a,t,new Uint8Array([n.charCodeAt(0)]),r),l=new Uint8Array(await p.digest(s,d));for(;l.length<i;){let h=new Uint8Array(await p.digest(s,m(a,t,l)));l=m(l,h)}return l.subarray(0,i)}var de="VNC_GATEWAY_READY_v1",fe="VNC_GATEWAY_KEEPALIVE_v1";var pe="SSH-2.0-CloudflareGateway_1.0",z={"aes256-gcm@openssh.com":{keyLength:32},"aes128-gcm@openssh.com":{keyLength:16}},B=Object.keys(z),ge=["hmac-sha2-256","hmac-sha2-512"],ye=["none"],L=16,q=16,we=12,j=8,me=4,Ee=262144,Le=8192,J=globalThis.crypto?.subtle;function M(s,e){return s.find(t=>e.includes(t))||null}var $=class s{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 n=await J.importKey("raw",e,{name:"AES-GCM"},!1,["encrypt","decrypt"]);return new s(n,t)}nextIv(){let e=m(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}},F=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:n,openTransport:r}={}){super(),this.url=e,this.verifyHost=t||(()=>!0),this.log=n||(()=>{}),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(de),this.#n(S(`${pe}\r
|
|
2
|
-
`)),this.keepaliveTimer=setInterval(()=>{if(this.socket?.readyState===WebSocket.OPEN&&(this.socket.send(fe),this.sessionId))try{this.#t(new c(64).u8(o.GLOBAL_REQUEST).string("keepalive@openssh.com").u8(1).take())}catch{}},25e3)}),this.socket.addEventListener("message",e=>{typeof e.data!="string"&&this.#s(new Uint8Array(e.data))}),this.socket.addEventListener("close",e=>{this.#e({clean:e.code===1e3,code:e.code,message:e.reason||(e.code===1006?"The gateway rejected or could not reach this SSH target. Confirm that SSH is published for this host.":"")})}),this.socket.addEventListener("error",()=>{this.log("The SSH gateway WebSocket reported a transport error; waiting for its close reason.")})}disconnect(e="Client disconnected"){if(this.closed)return;try{let n=new c(64).u8(o.DISCONNECT).u32(11).string(e).string("").take();this.#t(n)}catch{}let t=this.socket;Promise.resolve(this.encryptChain).finally(()=>{try{t?.close(1e3,"Client disconnected")}catch{}}),this.#e({clean:!0,code:1e3,message:""})}#e(e){this.closed||(this.closed=!0,clearInterval(this.keepaliveTimer),this.keepaliveTimer=null,this.dispatchEvent(new CustomEvent("close",{detail:e})))}fail(e){let t=e instanceof Error?e.message:String(e);if(!this.closed){this.dispatchEvent(new CustomEvent("error",{detail:{message:t}})),this.#e({clean:!1,code:4e3,message:t});try{this.socket?.close(4e3,t.slice(0,100))}catch{}}}#n(e){this.socket?.readyState===WebSocket.OPEN&&(this.bytesSent+=e.length,this.socket.send(e))}#s(e){this.bytesReceived+=e.length,this.buffer=this.buffer.length?m(this.buffer,e):e,this.drainChain=(this.drainChain||Promise.resolve()).then(()=>this.#f()).catch(t=>this.fail(t))}async#f(){if(!this.closed&&!(!this.serverVersion&&!this.#p()))for(;!this.closed;){if(this.newKeysBarrier){let t=this.newKeysBarrier;this.newKeysBarrier=null,await t;continue}if(!this.incoming){let t=this.#g();if(!t)return;this.#r(t);continue}let e=this.#y();if(!e)return;this.#r(await this.#c(e))}}#p(){for(;;){let e=this.buffer.indexOf(10);if(e===-1){if(this.buffer.length>Le)throw new Error("SSH: the host sent no version line.");return!1}let t=e;t>0&&this.buffer[t-1]===13&&t--;let n=new TextDecoder().decode(this.buffer.subarray(0,t));if(this.buffer=this.buffer.subarray(e+1),!n.startsWith("SSH-")){n.trim()&&this.greeting.push(n);continue}if(!n.startsWith("SSH-2.0-")&&!n.startsWith("SSH-1.99-"))throw new Error(`SSH: this host speaks ${n.split("-").slice(0,2).join("-")}, which is too old.`);return this.serverVersion=n,this.log("version",{server:n,greeting:this.greeting}),this.dispatchEvent(new CustomEvent("greeting",{detail:{lines:this.greeting.slice()}})),this.#l(),!0}}#g(){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>Ee)throw new Error("SSH: the host sent a packet of an impossible size.");if(this.buffer.length<4+t)return null;let n=this.buffer[4];if(n+1>t)throw new Error("SSH: a packet claimed more padding than it had.");let r=this.buffer.slice(5,4+t-n);return this.buffer=this.buffer.subarray(4+t),this.receiveSequence=this.receiveSequence+1>>>0,r}#y(){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<L||t%L!==0||t>Ee)throw new Error("SSH: the host sent a packet of an impossible size.");let n=4+t+q;if(this.buffer.length<n)return null;let r=this.buffer.slice(0,n);return this.buffer=this.buffer.subarray(n),r}async#c(e){let t;try{t=new Uint8Array(await J.decrypt({name:"AES-GCM",iv:this.incoming.nextIv(),additionalData:e.subarray(0,4),tagLength:q*8},this.incoming.key,e.subarray(4)))}catch{throw new Error("SSH: a packet failed its integrity check, so the session was dropped.")}let n=t[0];if(n+1>t.length)throw new Error("SSH: a packet claimed more padding than it had.");return this.receiveSequence=this.receiveSequence+1>>>0,t.slice(1,t.length-n)}#r(e){if(e.length===0)return;let t=e[0];switch(t){case o.DISCONNECT:{let n=new u(e,1),r=n.u32(),a=n.string()||re[r]||`reason ${r}`;this.dispatchEvent(new CustomEvent("hostdisconnect",{detail:{code:r,reason:a}})),this.#e({clean:r===11,code:1e3,message:a});try{this.socket?.close(1e3,"Host disconnected")}catch{}return}case o.IGNORE:case o.UNIMPLEMENTED:case o.EXT_INFO:return;case o.DEBUG:{let n=new u(e,1),r=n.boolean(),i=n.string();this.log("debug",{message:i,alwaysDisplay:r}),r&&this.dispatchEvent(new CustomEvent("banner",{detail:{text:`${i}\r
|
|
3
|
-
`}}));return}case o.KEXINIT:this.#w(e);return;case o.NEWKEYS:this.#d();return;case o.GLOBAL_REQUEST:{let n=new u(e,1);n.string(),n.boolean()&&this.#t(new Uint8Array([o.REQUEST_FAILURE]));return}case o.REQUEST_SUCCESS:case o.REQUEST_FAILURE:return;default:break}if(this.kex&&t>=30&&t<=49){this.#i(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.#t(e),!0)}#t(e){if(!(this.closed||this.socket?.readyState!==WebSocket.OPEN)){if(!this.outgoing){this.#n(He(e)),this.sendSequence=this.sendSequence+1>>>0;return}this.#a(e)}}async#a(e){let t=this.encryptChain||Promise.resolve();return this.encryptChain=t.then(async()=>{if(this.closed||!this.outgoing)return;let n=Ie(e.length),r=new Uint8Array(1+e.length+n);r[0]=n,r.set(e,1),crypto.getRandomValues(r.subarray(1+e.length));let i=new c(4).u32(r.length).take(),a=new Uint8Array(await J.encrypt({name:"AES-GCM",iv:this.outgoing.nextIv(),additionalData:i,tagLength:q*8},this.outgoing.key,r));this.#n(m(i,a)),this.sendSequence=this.sendSequence+1>>>0}).catch(n=>this.fail(n)),this.encryptChain}async#l(){if(!this.kex?.running){this.kex={running:!0,clientKexInit:null,pending:null,inbox:[]};try{let e=await oe(),t=Re(e);this.kex.clientKexInit=t,this.#t(t);let n=this.pendingServerKexInit||await this.#o(o.KEXINIT);this.pendingServerKexInit=null,await this.#u(e,t,n)}catch(e){this.fail(e)}}}async#w(e){if(this.kex?.running){this.#i(e);return}this.log("rekey",{reason:"the host asked for new keys"}),this.pendingServerKexInit=e,await this.#l()}#i(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)}}#o(e){return new Promise((t,n)=>{let r=a=>{if(e!==void 0&&a[0]!==e){n(new Error(`SSH: expected message ${e} during key exchange but got ${a[0]}.`));return}t(a)},i=this.kex.inbox.shift();if(i){r(i);return}this.kex.pending=a=>{this.kex.pending=null,r(a)}})}async#u(e,t,n){let r=Oe(n),i=M(e.kex,r.kex),a=M(e.hostKey,r.hostKey),d=M(B,r.cipherClientToServer),l=M(B,r.cipherServerToClient);if(!i)throw new Error(`SSH: no shared key exchange method. The host offers ${r.kex.join(", ")}.`);if(!a)throw new Error(`SSH: no host key type this browser can verify. The host offers ${r.hostKey.join(", ")}.`);if(!d||!l)throw new Error(`SSH: the host does not offer AES-GCM, which is the only cipher this client can use. It offers ${r.cipherServerToClient.join(", ")}.`);this.log("negotiated",{kex:i,hostKey:a,cipher:l,rekey:!!this.sessionId});let h=await ae(i);this.#t(new c(128).u8(o.KEX_ECDH_INIT).string(h.publicKey).take());let w=new u(await this.#o(o.KEX_ECDH_REPLY),1),y=w.stringBytes(),C=w.stringBytes(),g=w.stringBytes(),E=await h.sharedSecret(C),A=await ue({hash:h.hash,clientVersion:pe,serverVersion:this.serverVersion,clientKexInit:t,serverKexInit:n,hostKeyBlob:y,clientPublicKey:h.publicKey,serverPublicKey:C,sharedSecret:E});if(!await le({algorithm:a,keyBlob:y,signatureBlob:g,exchangeHash:A}))throw new Error("SSH: the host key signature is invalid, so this is not the machine it claims to be.");let _=await ce(y);if(!this.sessionId){if(!await this.verifyHost({fingerprint:_,keyType:he(y),algorithm:a}))throw new Error("SSH: the host key was not accepted, so the connection was stopped.");this.sessionId=A}this.#t(new Uint8Array([o.NEWKEYS])),await this.#o(o.NEWKEYS);let b={hash:h.hash,sharedSecret:E,exchangeHash:A,sessionId:this.sessionId},[H,R,V,T]=await Promise.all([N({...b,letter:"A",length:we}),N({...b,letter:"B",length:we}),N({...b,letter:"C",length:z[d].keyLength}),N({...b,letter:"D",length:z[l].keyLength})]);this.outgoing=await $.create(V,H),this.incoming=await $.create(T,R),this.kex.running=!1,this.releaseNewKeys?.(),this.releaseNewKeys=null;let O=this.kexQueue;this.kexQueue=[];for(let f of O)this.#t(f);let K=!this.established;this.established=!0,this.dispatchEvent(new CustomEvent("keys",{detail:{fingerprint:_,kexAlgorithm:i,hostKeyAlgorithm:a,cipher:l,firstTime:K}}))}#d(){this.kex&&(this.newKeysBarrier=new Promise(e=>{this.releaseNewKeys=e}),this.#i(new Uint8Array([o.NEWKEYS])))}};function Ie(s){let e=1+s,t=L-e%L;for(;t<me;)t+=L;return t}function He(s){let e=5+s.length,t=j-e%j;t<me&&(t+=j);let n=new c(e+t);n.u32(1+s.length+t),n.u8(t),n.raw(s);let r=n.take(),i=new Uint8Array(t);return crypto.getRandomValues(i),m(r,i)}function Re(s){let e=new Uint8Array(16);crypto.getRandomValues(e);let t=new c(512);return t.u8(o.KEXINIT).raw(e),t.nameList(s.kex),t.nameList(s.hostKey),t.nameList(B),t.nameList(B),t.nameList(ge),t.nameList(ge),t.nameList(ye),t.nameList(ye),t.nameList([]),t.nameList([]),t.boolean(!1),t.u32(0),t.take()}function Oe(s){let e=new u(s,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 ot=22,Z="ssh-connection",Ke="xterm-256color",I=2*1024*1024,ee=32*1024,De=I/2,Pe=new Uint8Array([0]),Me=2e4,Be=5*6e4,$e=60*6e4,W=new Uint8Array(0);function Fe(s){return`'${String(s).replace(/'/g,"'\\''")}'`}function Se(s){let e=s.slice(-400);return/(?:^|\n)PS [A-Za-z]:\\[^\n]*>\s*$/.test(e)?"powershell":/(?:^|\n)[^\n]*[A-Za-z]:\\[^\n]*>\s*$/.test(e)?"cmd":""}var We=/is not recognized as an internal or external command|command not found|not recognized as the name of a cmdlet|CommandNotFoundException/i;function Ve(s,e,t){if(s==="cmd")return`echo.&echo CCB${t}&${e}&call echo.CCE${t} %^ERRORLEVEL%\r`;if(s==="powershell"){let n=x(S(e));return`Write-Output ""; Write-Output ("CCB" + "${t}"); $__ccCode = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${n}')); $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 ${Fe(e)}; __cc=$?; printf '\\n%s%s %s\\n' 'CCE' '${t}' "$__cc"\r`}function U(s){return s.replace(/\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)/g,"").replace(/\u001b\[[0-9;?]*[ -/]*[@-~]/g,"").replace(/\u001b[@-Z\\-_]/g,"").replace(/\r\n/g,`
|
|
4
|
-
`).replace(/\r/g,"")}function Ge(s,e){let t=s.displayFilter;if(!t)return e;t.pending+=k(e);let n="";if(t.stage==="before"){let i=t.pending.indexOf(t.begin);if(i===-1)return W;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 n=t.pending,t.pending="",n?S(n):W;n=t.pending.slice(0,i),t.pending=t.pending.slice(i),t.stage="closing"}let r=t.pending.indexOf(`
|
|
5
|
-
`);return r!==-1&&(n+=t.pending.slice(r+1),s.displayFilter=null),n?S(n):W}function Xe(s){let e=s.displayFilter;s.displayFilter=null,!(!e||e.stage!=="before"||!e.pending)&&s.dispatchEvent(new CustomEvent("data",{detail:{bytes:W,display:S(e.pending),isStderr:!1}}))}var Ae=class extends EventTarget{constructor(e,t={}){super(),this.options=t,this.username=t.username||"",this.password=t.password||"",this.requestInput=t.requestInput||(async()=>""),this.columns=t.columns||80,this.rows=t.rows||24,this.channelId=0,this.remoteChannelId=null,this.remoteWindow=0,this.remoteMaxPacket=ee,this.localWindow=I,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.closed=!1,this.waiters=new Map,this.transport=new F(e,{verifyHost:t.verifyHost||(async()=>!0),openTransport:t.openTransport||null,log:(n,r)=>console.info(`[SSH] ${n}`,r)}),this.transport.addEventListener("packet",n=>{this.#g(n.detail.type,n.detail.payload)}),this.transport.addEventListener("greeting",n=>{for(let r of n.detail.lines)this.#n(`${r}\r
|
|
6
|
-
`)}),this.transport.addEventListener("banner",n=>this.#n(n.detail.text)),this.transport.addEventListener("keys",n=>{this.fingerprint=n.detail.fingerprint,this.#e("secured",`Host key ${n.detail.fingerprint} verified.`),this.dispatchEvent(new CustomEvent("secure",{detail:n.detail})),n.detail.firstTime&&this.#l()}),this.transport.addEventListener("hostdisconnect",n=>{this.lastMessage=n.detail.reason}),this.transport.addEventListener("error",n=>{this.lastMessage=n.detail.message,this.dispatchEvent(new CustomEvent("error",{detail:n.detail}))}),this.transport.addEventListener("close",n=>{this.closed||(this.closed=!0,clearTimeout(this.powerShellTimer),this.#p(n.detail.message||"The SSH connection closed."),this.dispatchEvent(new CustomEvent("close",{detail:{...n.detail,message:n.detail.message||this.lastMessage||"",exitStatus:this.exitStatus}})))})}connect(){this.#e("connecting","Opening the SSH transport\u2026"),this.transport.connect()}disconnect(){this.closed||(clearTimeout(this.powerShellTimer),this.shellOpen&&this.remoteChannelId!==null&&this.transport.send(new c(8).u8(o.CHANNEL_CLOSE).u32(this.remoteChannelId).take()),this.transport.disconnect("Closed by the user"))}write(e){let t=typeof e=="string"?S(e):e;t.length&&(this.pendingWrites.push(t),this.#a())}runCommand(e,{startMs:t=Me,idleMs:n=Be,maxMs:r=$e}={}){let i=String(e||"").trim();if(!i)return Promise.reject(new Error("No command was given."));if(!this.shellOpen||this.closed)return Promise.reject(new Error("The SSH shell is not open."));if(this.readySignaled===!1)return Promise.reject(new Error("The SSH shell is still starting."));if(this.commandInFlight)return Promise.reject(new Error("Another command is still running in this shell."));let a=Array.from(crypto.getRandomValues(new Uint8Array(6))).map(y=>y.toString(16).padStart(2,"0")).join(""),d=`CCB${a}`,l=`CCE${a}`,h=this.shellFamily||"posix";this.commandInFlight=!0;let w=Date.now();return this.displayFilter={begin:d,end:l,stage:"before",pending:""},this.dispatchEvent(new CustomEvent("command",{detail:{phase:"start",id:a,command:i}})),new Promise((y,C)=>{let g="",E=!1,A=null,v=null,_=null,b=f=>{clearTimeout(A),clearTimeout(v),clearTimeout(_),this.removeEventListener("data",O),this.removeEventListener("close",K),this.commandInFlight=!1,Xe(this),f()},H=f=>b(()=>{this.dispatchEvent(new CustomEvent("command",{detail:{phase:"end",id:a,command:i,exitStatus:f.exitStatus,timedOut:f.timedOut,started:f.started!==!1,reason:f.reason,durationMs:f.durationMs}})),y(f)}),R=f=>b(()=>{this.dispatchEvent(new CustomEvent("command",{detail:{phase:"end",id:a,command:i,exitStatus:null,timedOut:!1,started:E,durationMs:Date.now()-w,error:f.message}})),C(f)}),V=()=>{let f=g.indexOf(d);return f===-1?"":U(g.slice(f+d.length)).replace(/^\r?\n/,"").replace(/\s+$/,"")},T=f=>{this.write(""),H({output:V(),exitStatus:null,timedOut:!0,started:E,reason:f,durationMs:Date.now()-w})},O=f=>{g+=k(f.detail.bytes),!E&&g.indexOf(d)!==-1&&(E=!0,clearTimeout(A),A=null),E&&(clearTimeout(v),v=setTimeout(()=>T("idle"),n));let D=g.indexOf(`${l} `);if(D===-1){if(!E&&We.test(U(g))){let G=Se(U(g))||"cmd",Te=h!==G;this.shellFamily=G,R(new Error(Te?`This shell is ${G==="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: ${U(g).split(`
|
|
7
|
-
`).filter(Boolean).pop()||"no detail"}`))}return}let Ce=g.slice(D),te=parseInt(Ce.slice(l.length+1).trim(),10),ne=g.indexOf(d),be=ne===-1?g.slice(0,D):g.slice(ne+d.length,D);H({output:U(be).replace(/^\r?\n/,"").replace(/\s+$/,""),exitStatus:Number.isInteger(te)?te:null,timedOut:!1,started:!0,durationMs:Date.now()-w})},K=()=>R(new Error("The SSH session closed while the command was running."));this.addEventListener("data",O),this.addEventListener("close",K),A=setTimeout(()=>T("start"),t),v=setTimeout(()=>T("idle"),n),_=setTimeout(()=>T("max"),r),this.write(Ve(h,i,a))})}resize(e,t){let n=Math.max(1,Math.floor(e)),r=Math.max(1,Math.floor(t));n===this.columns&&r===this.rows||(this.columns=n,this.rows=r,!(!this.shellOpen||this.remoteChannelId===null)&&this.transport.send(new c(64).u8(o.CHANNEL_REQUEST).u32(this.remoteChannelId).string("window-change").boolean(!1).u32(n).u32(r).u32(0).u32(0).take()))}#e(e,t){this.dispatchEvent(new CustomEvent("status",{detail:{phase:e,message:t}}))}#n(e){e&&this.dispatchEvent(new CustomEvent("banner",{detail:{text:e}}))}#s(...e){return new Promise((t,n)=>{for(let r of e)this.waiters.set(r,{resolve:t,reject:n})})}#f(e,t){let n=this.waiters.get(e);return n?(this.waiters.clear(),n.resolve({type:e,payload:t}),!0):!1}#p(e){if(this.waiters.size===0)return;let t=[...new Set(this.waiters.values())];this.waiters.clear();for(let n of t)n.reject(new Error(e))}#g(e,t){if(!this.#f(e,t))switch(e){case o.USERAUTH_BANNER:this.#n(new u(t,1).string().replaceAll(`
|
|
8
|
-
`,`\r
|
|
9
|
-
`));return;case o.CHANNEL_DATA:{let n=new u(t,1);n.u32(),this.#t(n.stringBytes());return}case o.CHANNEL_EXTENDED_DATA:{let n=new u(t,1);n.u32();let r=n.u32(),i=n.stringBytes();this.#t(i,r===se);return}case o.CHANNEL_WINDOW_ADJUST:{let n=new u(t,1);n.u32(),this.remoteWindow+=n.u32(),this.#a();return}case o.CHANNEL_REQUEST:{let n=new u(t,1);n.u32();let r=n.string(),i=n.boolean();r==="exit-status"&&(this.exitStatus=n.u32()),r==="exit-signal"&&(this.exitSignal=n.string()),i&&this.remoteChannelId!==null&&this.transport.send(new c(8).u8(o.CHANNEL_SUCCESS).u32(this.remoteChannelId).take());return}case o.CHANNEL_EOF:return;case o.CHANNEL_CLOSE:this.shellOpen=!1,this.#e("closed","The remote shell ended."),this.transport.disconnect("Shell closed");return;default:return}}#y(e){this.promptTail=(this.promptTail+U(k(e))).slice(-400);let t=Se(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.#r("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.#r("Connected \xB7 PowerShell"))},2e3))}#r(e="Connected."){clearTimeout(this.powerShellTimer),this.powerShellTimer=null,this.readySignaled=!0,this.#e("ready",e),this.dispatchEvent(new CustomEvent("ready",{detail:{fingerprint:this.fingerprint,shellFamily:this.shellFamily||"posix"}}))}#t(e,t=!1){if(!e.length||(this.#y(e),this.dispatchEvent(new CustomEvent("data",{detail:{bytes:e,display:Ge(this,e),isStderr:t}})),this.localWindow-=e.length,this.localWindow>De||this.remoteChannelId===null))return;let n=I-this.localWindow;this.localWindow=I,this.transport.send(new c(16).u8(o.CHANNEL_WINDOW_ADJUST).u32(this.remoteChannelId).u32(n).take())}#a(){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 n=e.length<=t?e:e.subarray(0,t);n.length===e.length?this.pendingWrites.shift():this.pendingWrites[0]=e.subarray(n.length),this.remoteWindow-=n.length,this.transport.send(new c(n.length+16).u8(o.CHANNEL_DATA).u32(this.remoteChannelId).string(n).take())}}async#l(){try{if(this.#e("authenticating",`Authenticating as ${this.username}\u2026`),this.transport.send(new c(32).u8(o.SERVICE_REQUEST).string("ssh-userauth").take()),await this.#s(o.SERVICE_ACCEPT),await this.#w())return void await this.#h();if(this.authMethods.includes("password")&&this.password&&await this.#i(this.password))return void await this.#h();if(this.authMethods.includes("keyboard-interactive")){if(await this.#o())return void await this.#h();if(this.authMethods.includes("keyboard-interactive")&&await this.#o({usePassword:!1}))return void await this.#h()}if(this.authMethods.includes("password")){let e=await this.requestInput({prompt:`${this.username}@${this.options.hostLabel||"host"}'s password: `,echo:!1});if(e&&await this.#i(e))return void await this.#h()}throw new Error(this.authMethods.length?`SSH: authentication failed. 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#w(){return this.transport.send(new c(64).u8(o.USERAUTH_REQUEST).string(this.username).string(Z).string("none").take()),this.#u()}async#i(e){return this.transport.send(new c(128).u8(o.USERAUTH_REQUEST).string(this.username).string(Z).string("password").boolean(!1).string(e).take()),this.#u()}async#o({usePassword:e=!0}={}){this.transport.send(new c(96).u8(o.USERAUTH_REQUEST).string(this.username).string(Z).string("keyboard-interactive").string("").string("").take());let t=!e;for(;;){let{type:n,payload:r}=await this.#s(o.USERAUTH_SUCCESS,o.USERAUTH_FAILURE,o.USERAUTH_INFO_REQUEST);if(n===o.USERAUTH_SUCCESS)return!0;if(n===o.USERAUTH_FAILURE)return this.#d(r),!1;let i=new u(r,1),a=i.string(),d=i.string();i.string();let l=i.u32();a&&this.#n(`${a.replaceAll(`
|
|
10
|
-
`,`\r
|
|
11
|
-
`)}\r
|
|
12
|
-
`),d&&this.#n(`${d.replaceAll(`
|
|
13
|
-
`,`\r
|
|
14
|
-
`)}\r
|
|
15
|
-
`);let h=[];for(let y=0;y<l;y++){let C=i.string(),g=i.boolean();if(!g&&/pass(word|phrase)/i.test(C)&&this.password&&!t){t=!0,h.push(this.password);continue}h.push(await this.requestInput({prompt:C,echo:g}))}let w=new c(256).u8(o.USERAUTH_INFO_RESPONSE).u32(h.length);for(let y of h)w.string(y);this.transport.send(w.take())}}async#u(){let{type:e,payload:t}=await this.#s(o.USERAUTH_SUCCESS,o.USERAUTH_FAILURE);return e===o.USERAUTH_SUCCESS?!0:(this.#d(t),!1)}#d(e){let t=new u(e,1);this.authMethods=t.nameList(),t.boolean()&&this.#n(`\r
|
|
16
|
-
One factor accepted; the host wants another.\r
|
|
17
|
-
`)}async#h(){this.#e("opening","Starting the remote shell\u2026"),this.transport.send(new c(64).u8(o.CHANNEL_OPEN).string("session").u32(this.channelId).u32(I).u32(ee).take());let e=await this.#s(o.CHANNEL_OPEN_CONFIRMATION,o.CHANNEL_OPEN_FAILURE);if(e.type===o.CHANNEL_OPEN_FAILURE){let i=new u(e.payload,1);throw i.u32(),i.u32(),new Error(`SSH: the host refused to open a session channel (${i.string()}).`)}let t=new u(e.payload,1);if(t.u32(),this.remoteChannelId=t.u32(),this.remoteWindow=t.u32(),this.remoteMaxPacket=Math.max(1024,Math.min(t.u32(),ee)),this.transport.send(new c(128).u8(o.CHANNEL_REQUEST).u32(this.remoteChannelId).string("pty-req").boolean(!0).string(Ke).u32(this.columns).u32(this.rows).u32(0).u32(0).string(Pe).take()),(await this.#s(o.CHANNEL_SUCCESS,o.CHANNEL_FAILURE)).type===o.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 c(32).u8(o.CHANNEL_REQUEST).u32(this.remoteChannelId).string("shell").boolean(!0).take()),(await this.#s(o.CHANNEL_SUCCESS,o.CHANNEL_FAILURE)).type===o.CHANNEL_FAILURE)throw new Error("SSH: the host refused to start a shell for this account.");this.shellOpen=!0,this.#a(),this.options.preferredShell==="powershell"?this.#c():this.#r()}};export{Be as COMMAND_IDLE_MS,$e as COMMAND_MAX_MS,Me as COMMAND_START_MS,ot as DEFAULT_PORT,Ae as SshSession,Ve as frameCommand};
|
|
@@ -1,46 +0,0 @@
|
|
|
1
|
-
export declare class SshTerminal {
|
|
2
|
-
constructor(container: any);
|
|
3
|
-
get columns(): any;
|
|
4
|
-
get rows(): any;
|
|
5
|
-
onData(handler: any): void;
|
|
6
|
-
onResize(handler: any): void;
|
|
7
|
-
write(data: Uint8Array): void;
|
|
8
|
-
/** Gateway-side notices, kept visually apart from what the host prints. */
|
|
9
|
-
notice(text: string, tone?: string): void;
|
|
10
|
-
clear(): void;
|
|
11
|
-
focus(): void;
|
|
12
|
-
/**
|
|
13
|
-
* Size the terminal to the panel, choosing the font so MIN_COLUMNS fit.
|
|
14
|
-
*
|
|
15
|
-
* The columns matter more than the type size here: the commands people run in
|
|
16
|
-
* a side panel -- `ls -l`, `top`, anything in PowerShell that prints a table
|
|
17
|
-
* -- are laid out for 80 columns, and a narrower grid wraps every row into an
|
|
18
|
-
* unreadable stack.
|
|
19
|
-
*
|
|
20
|
-
* `proposeDimensions()` reports the grid the current font size yields, and a
|
|
21
|
-
* monospace cell's width scales with its font size, so `fontSize * cols /
|
|
22
|
-
* MIN_COLUMNS` lands close to the size that gives MIN_COLUMNS. It is measured
|
|
23
|
-
* rather than assumed because the cell-width-to-font-size ratio belongs to
|
|
24
|
-
* whichever font the platform picked. A second pass settles the rounding.
|
|
25
|
-
* Changing the font resizes the element, which the ResizeObserver sees, so
|
|
26
|
-
* the guard keeps that from recursing.
|
|
27
|
-
*/
|
|
28
|
-
fit(): void;
|
|
29
|
-
/** The grid the host is being told about, for a status line or a log. */
|
|
30
|
-
get geometry(): {
|
|
31
|
-
columns: any;
|
|
32
|
-
rows: any;
|
|
33
|
-
fontSize: any;
|
|
34
|
-
};
|
|
35
|
-
get selection(): any;
|
|
36
|
-
/**
|
|
37
|
-
* Read one line from the user, for a password or a one-time code the host
|
|
38
|
-
* asked for during authentication. The shell is not open yet, so the
|
|
39
|
-
* terminal is free to be a prompt.
|
|
40
|
-
*/
|
|
41
|
-
readLine({ prompt, echo }?: {
|
|
42
|
-
echo?: boolean;
|
|
43
|
-
prompt?: string;
|
|
44
|
-
}): Promise<unknown>;
|
|
45
|
-
destroy(): void;
|
|
46
|
-
}
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import{Terminal as m}from"@xterm/xterm";import{FitAddon as u}from"@xterm/addon-fit";import b from"@xterm/xterm/css/xterm.css";var h="xterm-styles",l=80,c=13,g=7;function w(){if(document.getElementById(h))return;let s=document.createElement("style");s.id=h,s.textContent=b,document.head.appendChild(s)}var p={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"},f=class{constructor(t){w(),this.container=t,this.terminal=new m({allowProposedApi:!0,convertEol:!1,cursorBlink:!0,cursorStyle:"bar",drawBoldTextInBrightColors:!0,fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace',fontSize:c,lineHeight:1.25,letterSpacing:0,macOptionIsMeta:!0,minimumContrastRatio:1.5,scrollback:1e4,theme:p}),this.fitAddon=new u,this.terminal.loadAddon(this.fitAddon),this.terminal.open(t),this.fit(),this.observer=new ResizeObserver(()=>this.fit()),this.observer.observe(t),this.dataHandler=null,this.terminal.onData(e=>this.dataHandler?.(e))}get columns(){return this.terminal.cols}get rows(){return this.terminal.rows}onData(t){this.dataHandler=t}onResize(t){this.terminal.onResize(({cols:e,rows:i})=>t(e,i))}write(t){this.terminal.write(t)}notice(t,e="info"){let i={info:"\x1B[38;5;245m",good:"\x1B[38;5;114m",bad:"\x1B[38;5;203m"}[e]||"";this.terminal.write(`${i}${t}\x1B[0m\r
|
|
2
|
-
`)}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 e=0;e<2;e++){let i=this.fitAddon.proposeDimensions();if(!i||!(i.cols>0))break;let o=this.terminal.options.fontSize||c,r=Math.min(c,Math.max(g,Math.floor(o*i.cols/l)));if(r===o)break;this.terminal.options.fontSize=r}this.fitAddon.fit();let t=this.terminal.cols<l;this.container.classList.toggle("is-narrow",t),t&&this.terminal.resize(l,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:t="",echo:e=!1}={}){return new Promise(i=>{let o=this.dataHandler,r="";this.terminal.write(t.replaceAll(`
|
|
3
|
-
`,`\r
|
|
4
|
-
`)),this.dataHandler=d=>{for(let a of d){let n=a.charCodeAt(0);if(n===13||n===10){this.terminal.write(`\r
|
|
5
|
-
`),this.dataHandler=o,i(r);return}if(n===127||n===8){if(r.length===0)continue;r=r.slice(0,-1),e&&this.terminal.write("\b \b");continue}if(n===3){this.terminal.write(`^C\r
|
|
6
|
-
`),this.dataHandler=o,i("");return}n<32||(r+=a,e&&this.terminal.write(a))}}})}destroy(){this.observer?.disconnect(),this.terminal.dispose()}};export{f as SshTerminal};
|
|
@@ -1,127 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* The interface every remote-desktop protocol presents to the UI.
|
|
3
|
-
*
|
|
4
|
-
* The workspace -- toolbar, stats rail, on-screen keyboard, reconnects -- does
|
|
5
|
-
* not care whether a session is VNC or RDP. Everything that does differ is
|
|
6
|
-
* reached through this interface instead of branching at each call site.
|
|
7
|
-
*/
|
|
8
|
-
import type { ConnectionSettings, RemoteAppLaunch } from '../shared/connection';
|
|
9
|
-
import type { RdpSecurity, RemoteProtocol } from '../shared/protocol';
|
|
10
|
-
/** Where the pointer may go, in framebuffer pixels. */
|
|
11
|
-
export interface ScreenGeometry {
|
|
12
|
-
width: number;
|
|
13
|
-
height: number;
|
|
14
|
-
viewport: {
|
|
15
|
-
x: number;
|
|
16
|
-
y: number;
|
|
17
|
-
width: number;
|
|
18
|
-
height: number;
|
|
19
|
-
};
|
|
20
|
-
}
|
|
21
|
-
/** Mouse buttons, as the UI names them. */
|
|
22
|
-
export type PointerButton = 0 | 1 | 2;
|
|
23
|
-
/** Wheel movement in discrete remote-protocol notches. Positive is right/down. */
|
|
24
|
-
export interface ScrollDelta {
|
|
25
|
-
x: number;
|
|
26
|
-
y: number;
|
|
27
|
-
}
|
|
28
|
-
/**
|
|
29
|
-
* A live session. Both drivers expose this, so the AI pane's screen tool and
|
|
30
|
-
* the toolbar never have to ask which protocol they are driving.
|
|
31
|
-
*/
|
|
32
|
-
export interface RemoteSession extends EventTarget {
|
|
33
|
-
readonly protocol: RemoteProtocol;
|
|
34
|
-
disconnect(): void;
|
|
35
|
-
/** True once the desktop has been reached. */
|
|
36
|
-
readonly connected: boolean;
|
|
37
|
-
/** Fit the remote desktop to the pane rather than scrolling it. */
|
|
38
|
-
scaleViewport: boolean;
|
|
39
|
-
/** Watch without sending keyboard or pointer input. */
|
|
40
|
-
viewOnly: boolean;
|
|
41
|
-
/** RFB quality level. RDP ignores it. */
|
|
42
|
-
qualityLevel?: number;
|
|
43
|
-
/** RFB compression level. RDP ignores it. */
|
|
44
|
-
compressionLevel?: number;
|
|
45
|
-
/** The transport the metrics rail instruments. Can appear a tick after construction. */
|
|
46
|
-
readonly socket?: WebSocket | null;
|
|
47
|
-
readonly screenGeometry: ScreenGeometry;
|
|
48
|
-
movePointer(x: number, y: number): boolean;
|
|
49
|
-
clickPointer(x: number, y: number, button?: PointerButton): boolean;
|
|
50
|
-
pointerButton(x: number, y: number, button?: PointerButton, pressed?: boolean): boolean;
|
|
51
|
-
scrollPointer(x: number, y: number, delta: ScrollDelta): boolean;
|
|
52
|
-
typeText(text: string): boolean;
|
|
53
|
-
/** Prefer the protocol clipboard for longer text when it can paste reliably. */
|
|
54
|
-
pasteText?(text: string): boolean | Promise<boolean>;
|
|
55
|
-
/** Press or release one key by keysym. */
|
|
56
|
-
sendKey(keysym: number, code: string | null, down?: boolean): void;
|
|
57
|
-
/** Send text to the host's clipboard, when the protocol carries one. */
|
|
58
|
-
sendClipboard?(text: string): void;
|
|
59
|
-
/**
|
|
60
|
-
* Stop taking keystrokes: the workspace has given the keyboard to something
|
|
61
|
-
* local, such as the terminal or the assistant's message box.
|
|
62
|
-
*
|
|
63
|
-
* Both protocols listen on the element they paint into, so a key only leaves
|
|
64
|
-
* for the host while that element holds focus. Handing focus back is the
|
|
65
|
-
* whole mechanism -- plus, for RDP, letting go of anything still held down,
|
|
66
|
-
* which would otherwise stay down on the far side.
|
|
67
|
-
*/
|
|
68
|
-
releaseKeyboard?(): void;
|
|
69
|
-
/** Ask the host for a different desktop size, when the protocol allows it. */
|
|
70
|
-
requestDesktopSize?(width: number, height: number): void;
|
|
71
|
-
/** The canvas the session paints into, for screenshots and thumbnails. */
|
|
72
|
-
readonly canvas?: HTMLCanvasElement | null;
|
|
73
|
-
}
|
|
74
|
-
/** What the workspace hands a driver to open a session. */
|
|
75
|
-
export interface SessionOptions {
|
|
76
|
-
credentials: {
|
|
77
|
-
username: string;
|
|
78
|
-
password: string;
|
|
79
|
-
};
|
|
80
|
-
domain: string;
|
|
81
|
-
security: RdpSecurity;
|
|
82
|
-
remoteApp: RemoteAppLaunch | null;
|
|
83
|
-
/** Desktop size to ask the host for. */
|
|
84
|
-
width: number;
|
|
85
|
-
height: number;
|
|
86
|
-
/** False on a phone, where resizing the host would make a portrait strip of it. */
|
|
87
|
-
allowRemoteResize: boolean;
|
|
88
|
-
scaleViewport: boolean;
|
|
89
|
-
viewOnly: boolean;
|
|
90
|
-
quality: number;
|
|
91
|
-
compression: number;
|
|
92
|
-
/** Shown in this driver's own log lines. */
|
|
93
|
-
hostLabel: string;
|
|
94
|
-
}
|
|
95
|
-
/** Wording for the one connect dialog, which is shared markup across protocols. */
|
|
96
|
-
export interface DialogCopy {
|
|
97
|
-
usernameLabel: string;
|
|
98
|
-
usernamePlaceholder: string;
|
|
99
|
-
usernameHelp: string;
|
|
100
|
-
passwordLabel: string;
|
|
101
|
-
passwordPlaceholder: string;
|
|
102
|
-
passwordHelp: string;
|
|
103
|
-
/** A VNC session needs some secret; RDP can sign in on the host's own screen. */
|
|
104
|
-
requiresPassword: boolean;
|
|
105
|
-
}
|
|
106
|
-
/** Everything the UI knows about a close, before anyone tries to explain it. */
|
|
107
|
-
export interface DisconnectContext {
|
|
108
|
-
code?: number;
|
|
109
|
-
reason: string;
|
|
110
|
-
/** Pre-rendered ` (WebSocket 1006: ...)` tail, so wording stays consistent. */
|
|
111
|
-
suffix: string;
|
|
112
|
-
}
|
|
113
|
-
/** One protocol implementation. */
|
|
114
|
-
export interface ProtocolDriver {
|
|
115
|
-
readonly protocol: RemoteProtocol;
|
|
116
|
-
/** Used as the prefix of this driver's console lines. */
|
|
117
|
-
readonly label: string;
|
|
118
|
-
readonly defaultPort: number;
|
|
119
|
-
readonly dialog: DialogCopy;
|
|
120
|
-
/** The gateway endpoint for this connection, including any query it needs. */
|
|
121
|
-
buildUrl(origin: string, settings: ConnectionSettings): string;
|
|
122
|
-
createSession(container: HTMLElement, url: string, options: SessionOptions): RemoteSession;
|
|
123
|
-
/** Extra detail worth logging once the first server frame has been parsed. */
|
|
124
|
-
describeState(session: RemoteSession): Record<string, unknown>;
|
|
125
|
-
/** Protocol-specific wording for a close, or null to fall back to the shared text. */
|
|
126
|
-
describeDisconnect(context: DisconnectContext): string | null;
|
|
127
|
-
}
|
package/dist/protocols/types.js
DELETED
|
File without changes
|