ai-remote 0.4.2 → 0.4.3
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 -6
- package/dist/protocols/index.js +3 -34
- package/dist/protocols/ssh/session.js +17 -608
- package/dist/protocols/ssh/terminal.js +6 -190
- package/dist/shared/connection.js +1 -113
- package/dist/shared/hosts.js +1 -132
- package/dist/shared/icons.js +1 -41
- package/dist/shared/protocol.js +1 -39
- package/dist/shared/signals.js +1 -41
- package/package.json +1 -1
- package/dist/protocols/rdp/buffer.d.ts +0 -38
- package/dist/protocols/rdp/buffer.js +0 -169
- package/dist/protocols/rdp/caps.d.ts +0 -49
- package/dist/protocols/rdp/caps.js +0 -259
- package/dist/protocols/rdp/cert.d.ts +0 -18
- package/dist/protocols/rdp/cert.js +0 -134
- package/dist/protocols/rdp/client.d.ts +0 -56
- package/dist/protocols/rdp/client.js +0 -1069
- package/dist/protocols/rdp/cliprdr.d.ts +0 -27
- package/dist/protocols/rdp/cliprdr.js +0 -239
- package/dist/protocols/rdp/credssp.d.ts +0 -34
- package/dist/protocols/rdp/credssp.js +0 -253
- package/dist/protocols/rdp/crypto.d.ts +0 -63
- package/dist/protocols/rdp/crypto.js +0 -368
- package/dist/protocols/rdp/display.d.ts +0 -38
- package/dist/protocols/rdp/display.js +0 -588
- package/dist/protocols/rdp/gcc.d.ts +0 -23
- package/dist/protocols/rdp/gcc.js +0 -131
- package/dist/protocols/rdp/keymap.d.ts +0 -9
- package/dist/protocols/rdp/keymap.js +0 -131
- package/dist/protocols/rdp/mcs.d.ts +0 -40
- package/dist/protocols/rdp/mcs.js +0 -222
- package/dist/protocols/rdp/ntlm.d.ts +0 -61
- package/dist/protocols/rdp/ntlm.js +0 -304
- package/dist/protocols/rdp/pdu.d.ts +0 -155
- package/dist/protocols/rdp/pdu.js +0 -443
- package/dist/protocols/rdp/rail.d.ts +0 -119
- package/dist/protocols/rdp/rail.js +0 -382
- package/dist/protocols/rdp/rle.d.ts +0 -13
- package/dist/protocols/rdp/rle.js +0 -275
- package/dist/protocols/rdp/sec.d.ts +0 -59
- package/dist/protocols/rdp/sec.js +0 -155
- package/dist/protocols/rdp/session.d.ts +0 -62
- package/dist/protocols/rdp/session.js +0 -306
- package/dist/protocols/rdp/tls.d.ts +0 -18
- package/dist/protocols/rdp/tls.js +0 -353
- package/dist/protocols/rdp/vchannel.d.ts +0 -28
- package/dist/protocols/rdp/vchannel.js +0 -58
- package/dist/protocols/rdp/x224.d.ts +0 -40
- package/dist/protocols/rdp/x224.js +0 -109
- package/dist/protocols/ssh/kex.d.ts +0 -97
- package/dist/protocols/ssh/kex.js +0 -176
- package/dist/protocols/ssh/messages.d.ts +0 -50
- package/dist/protocols/ssh/messages.js +0 -54
- package/dist/protocols/ssh/transport.d.ts +0 -62
- package/dist/protocols/ssh/transport.js +0 -612
- package/dist/protocols/ssh/wire.d.ts +0 -52
- package/dist/protocols/ssh/wire.js +0 -188
- package/dist/protocols/vnc/input.d.ts +0 -5
- package/dist/protocols/vnc/input.js +0 -15
- package/dist/protocols/vnc/session.d.ts +0 -12
- package/dist/protocols/vnc/session.js +0 -258
package/dist/index.js
CHANGED
|
@@ -1,6 +1 @@
|
|
|
1
|
-
|
|
2
|
-
export * from "./shared/device.js";
|
|
3
|
-
export * from "./shared/hosts.js";
|
|
4
|
-
export * from "./shared/icons.js";
|
|
5
|
-
export * from "./shared/protocol.js";
|
|
6
|
-
export * from "./shared/signals.js";
|
|
1
|
+
var A=["vnc","rdp"],k=["vnc","rdp","ssh"],P=["auto","nla","tls","rdp"],a={vnc:5900,rdp:3389,ssh:22},f=a.ssh;function E(t){return A.includes(t)}function g(t){return P.includes(t)}function h(t,e="vnc"){let r=String(t??"").toLowerCase();return E(r)?r:e}function M(t,e="auto"){let r=String(t??"").toLowerCase();return g(r)?r:e}function u(t,e){let r=typeof t=="number"?t:Number.parseInt(String(t??""),10);return Number.isInteger(r)&&r>0&&r<65536?r:e}var d={quality:6,compression:2,scaling:!0,viewOnly:!1};function C(t){let e=t.remoteApp?.program?.trim()??"",r=`${t.protocol||"vnc"}:${t.host.trim()}:${t.port||""}`;return(e?`${r}:${e}`:r).toLowerCase().slice(0,64)}function I(t="vnc"){let e=a[t];return{id:"",label:"",protocol:t,host:"",port:e,username:"",password:"",domain:"",security:"auto",remoteApp:null,display:{...d},ssh:{enabled:!1,port:a.ssh,username:""},openSshOnConnect:!1}}function x(t,e,r,n){let o=typeof t=="number"?t:Number.parseInt(String(t??""),10);return Number.isInteger(o)?Math.min(n,Math.max(r,o)):e}function T(t){let e=t??{};return{quality:x(e.quality,d.quality,1,9),compression:x(e.compression,d.compression,0,9),scaling:typeof e.scaling=="boolean"?e.scaling:d.scaling,viewOnly:!!e.viewOnly}}function L(t){if(typeof t=="string"){let i=t.trim();return i?{program:i}:null}if(!t||typeof t!="object")return null;let e=t,r=String(e.program??"").trim();if(!r)return null;let n=String(e.workingDir??"").trim(),o=String(e.arguments??"").trim();return{program:r,...n?{workingDir:n}:{},...o?{arguments:o}:{}}}function N(t){let e=h(t.protocol),r=String(t.host??"").trim(),n=u(t.port,a[e]),o=L(t.remoteApp??t.program),i=t.ssh??{},c={enabled:!!i.enabled,port:u(i.port,a.ssh),username:String(i.username??"").trim()},p={id:"",label:String(t.label??"").trim()||r,protocol:e,host:r,port:n,username:String(t.username??"").trim(),password:String(t.password??""),domain:String(t.domain??"").trim(),security:M(t.security),remoteApp:o,display:T(t.display),ssh:c,openSshOnConnect:!!t.openSshOnConnect};return p.id=String(t.id??"").trim()||C(p),p}function V(t){let{password:e,...r}=t;return r}function z(t){let e=`${t.host||"no address"}:${t.port}`,r=t.remoteApp?` \xB7 ${t.remoteApp.program}`:"";return`${t.protocol.toUpperCase()} \xB7 ${e}${r}`}function O(t){if(typeof t=="string"&&t.trim())return{program:t.trim()};if(!t||typeof t!="object")return;let e=t,r=String(e.program??"").trim();if(r)return{program:r,...e.workingDir?{workingDir:String(e.workingDir)}:{},...e.arguments?{arguments:String(e.arguments)}:{}}}function _(t,e){let r=typeof e=="string"&&e.trim()?e.trim():void 0;if(t===!0)return{port:f,...r?{username:r}:{}};if(typeof t=="number"||typeof t=="string"&&/^\d+$/.test(t.trim())){let i=u(t,0);return i?{port:i,...r?{username:r}:{}}:void 0}if(!t||typeof t!="object")return;let n=t;if(n.enabled===!1)return;let o=typeof n.username=="string"&&n.username.trim()?n.username.trim():r;return{port:u(n.port,f),...o?{username:o}:{}}}function R(t,e,r,n,o){if(!t)return[];let i;try{i=JSON.parse(t)}catch(c){return console.warn(`Failed to parse ${o.toUpperCase()}_HOSTS JSON, ignoring it:`,c),[]}return!Array.isArray(i)||i.length===0?[]:i.map((c,p)=>{let s=c??{},m=h(s.protocol,e),l=m==="rdp"?O(s.remoteApp):void 0,y=_(s.ssh??s.sshPort,s.sshUser??s.sshUsername),S=String(s.host??"")||r,w=String(s.name??"").trim()||S;return{id:String(s.id??"")||`${o}-${p+1}`,name:w,host:S,port:u(s.port??n,a[m]),protocol:m,...s.domain?{domain:String(s.domain)}:{},...g(s.security)?{security:s.security}:{},...l?{remoteApp:l}:{},...y?{ssh:y}:{}}})}function B(t){let e=t.defaultHost||"10.0.0.10",r=t.defaultPort||String(a.vnc),n=[...R(t.vncHostsJson,"vnc",e,r,"vnc-host"),...R(t.rdpHostsJson,"rdp",t.defaultRdpHost||e,t.defaultRdpPort||String(a.rdp),"rdp-host")];return n.length>0?n:[{id:"default-host",name:"Primary Host",host:e,port:u(r,a.vnc),protocol:"vnc"}]}function b(t){let e=String(t).trim().split(".");if(e.length!==4)return null;let r=0;for(let n of e){if(!/^\d{1,3}$/.test(n))return null;let o=Number.parseInt(n,10);if(o>255)return null;r=r<<8|o}return r>>>0}function H(t){if(!t)return[];let e=[];for(let r of t.split(",")){let n=r.trim();if(!n)continue;let o=n.split(".").findIndex(l=>l==="*"),[i,c]=o>=0?[n.replaceAll("*","0"),String(o*8)]:n.split("/"),p=b(i??"");if(p===null)continue;let s=c===void 0?32:Number.parseInt(c,10);if(!Number.isInteger(s)||s<0||s>32)continue;let m=s===0?0:4294967295<<32-s>>>0;e.push({base:(p&m)>>>0,mask:m})}return e}function Y(t,e){let r=b(t);return r===null?!1:H(e).some(({base:n,mask:o})=>(r&o)>>>0===n)}var G={monitor:'<rect x="2" y="3" width="20" height="14" rx="2"/><path d="M8 21h8M12 17v4"/>',link:'<path d="M9 17H7A5 5 0 0 1 7 7h2M15 7h2a5 5 0 1 1 0 10h-2M8 12h8"/>',power:'<path d="M12 2v10"/><path d="M18.4 6.6a9 9 0 1 1-12.8 0"/>',maximize:'<path d="M8 3H5a2 2 0 0 0-2 2v3M21 8V5a2 2 0 0 0-2-2h-3M3 16v3a2 2 0 0 0 2 2h3M16 21h3a2 2 0 0 0 2-2v-3"/>',minimize:'<path d="M8 3v3a2 2 0 0 1-2 2H3M21 8h-3a2 2 0 0 1-2-2V3M3 16h3a2 2 0 0 1 2 2v3M16 21v-3a2 2 0 0 1 2-2h3"/>',keyboard:'<rect x="2" y="4" width="20" height="16" rx="2"/><path d="M6 8h.01M10 8h.01M14 8h.01M18 8h.01M8 12h.01M12 12h.01M16 12h.01M7 16h10"/>',clipboard:'<rect x="8" y="2" width="8" height="4" rx="1"/><path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"/>',check:'<path d="m5 13 4 4 10-10"/>',camera:'<path d="M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3l-2.5-3z"/><circle cx="12" cy="13" r="3"/>',eye:'<path d="M2 12s3.5-6 10-6 10 6 10 6-3.5 6-10 6S2 12 2 12z"/><circle cx="12" cy="12" r="3"/>',sliders:'<path d="M4 21v-7M4 10V3M12 21v-9M12 8V3M20 21v-5M20 12V3M2 14h4M10 8h4M18 16h4"/>',expand:'<path d="M15 3h6v6M9 21H3v-6M21 3l-7 7M3 21l7-7"/>',shield:'<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>',chevron:'<path d="m6 9 6 6 6-6"/>',back:'<path d="m15 18-6-6 6-6"/>',zap:'<path d="M13 2 3 14h9l-1 8 10-12h-9l1-8z"/>',cube:'<path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/><path d="m3.3 7 8.7 5 8.7-5M12 22V12"/>',logout:'<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4M16 17l5-5-5-5M21 12H9"/>',clock:'<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3.5 2"/>',activity:'<path d="M22 12h-4l-3 9L9 3l-3 9H2"/>',transfer:'<path d="m3 16 4 4 4-4M7 20V4M21 8l-4-4-4 4M17 4v16"/>',screen:'<rect x="2" y="5" width="20" height="13" rx="2"/><path d="M7 21h10"/>',command:'<path d="M15 6a3 3 0 1 1 3 3h-3zm0 0v12m0 0a3 3 0 1 0 3-3h-3zM9 6a3 3 0 1 0-3 3h3zm0 0v12m0 0a3 3 0 1 1-3-3h3z"/>',apps:'<rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/>',terminal:'<path d="m4 17 6-6-6-6M12 19h8"/>',folder:'<path d="M3 7h6l2 2h10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><path d="M3 7V6a2 2 0 0 1 2-2h4l2 3"/>',close:'<path d="M18 6 6 18M6 6l12 12"/>',sparkles:'<path d="m12 3 1.9 5.1L19 10l-5.1 1.9L12 17l-1.9-5.1L5 10l5.1-1.9L12 3z"/><path d="m19 15 .8 2.2 2.2.8-2.2.8L19 21l-.8-2.2-2.2-.8 2.2-.8z"/>',broom:'<path d="M10 10V4a2 2 0 0 1 4 0v6"/><path d="M6 10h12a2 2 0 0 1 2 2v2H4v-2a2 2 0 0 1 2-2Z"/><path d="m5 14-2 7h18l-2-7M9 18l-1 3M15 18l1 3"/>',panel:'<rect x="3" y="4" width="18" height="16" rx="2"/><path d="M14 4v16"/>',menu:'<path d="M4 7h16M4 12h16M4 17h16"/>',plus:'<path d="M12 5v14M5 12h14"/>',star:'<path d="m12 3 2.9 5.9 6.5.9-4.7 4.6 1.1 6.5L12 17.8 6.2 20.9l1.1-6.5L2.6 9.8l6.5-.9L12 3z"/>',trash:'<path d="M3 6h18M8 6V4a1 1 0 0 1 1-1h6a1 1 0 0 1 1 1v2M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/>'},q="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23f38020' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Crect x='2' y='3' width='20' height='14' rx='2'/%3E%3Cpath d='M8 21h8M12 17v4'/%3E%3C/svg%3E";var j="VNC_GATEWAY_READY_v1",W="VNC_GATEWAY_KEEPALIVE_v1",K=25e3,X=123;function Z(t){return!t.established||!t.close?!1:t.close.code===1006?!0:t.close.code===1011&&/tcp|socket|network|host closed/i.test(t.close.reason)}function Q(t){let e=new TextEncoder;if(e.encode(t).byteLength<=123)return t;let r="";for(let n of t){if(e.encode(`${r}${n}\u2026`).byteLength>123)break;r+=n}return`${r}\u2026`}function tt(t){return t===1005||t===1006||t===1015?1011:t}async function et(t){return typeof t=="string"?new TextEncoder().encode(t):t instanceof ArrayBuffer?new Uint8Array(t):t instanceof Blob?new Uint8Array(await t.arrayBuffer()):ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):null}export{d as DEFAULT_DISPLAY_SETTINGS,a as DEFAULT_PORTS,f as DEFAULT_SSH_PORT,q as FAVICON_DATA_URI,W as GATEWAY_KEEPALIVE_SIGNAL,j as GATEWAY_READY_SIGNAL,G as ICON_PATHS,K as KEEPALIVE_INTERVAL_MS,X as MAX_CLOSE_REASON_BYTES,P as RDP_SECURITY_MODES,A as REMOTE_PROTOCOLS,k as TRANSPORT_PROTOCOLS,C as connectionId,z as describeConnection,I as emptyConnection,Y as hostInAllowedSubnets,b as ipv4ToInt,g as isRdpSecurity,E as isRemoteProtocol,Z as isRetryableDisconnect,et as messageToBytes,N as normalizeConnection,T as normalizeDisplaySettings,H as parseAllowedSubnets,B as parseConfiguredHosts,tt as sendableCloseCode,u as toPort,M as toRdpSecurity,h as toRemoteProtocol,Q as websocketCloseReason,V as withoutPassword};
|
package/dist/protocols/index.js
CHANGED
|
@@ -1,34 +1,3 @@
|
|
|
1
|
-
import { rdpDriver } from "./rdp/session.js";
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
vnc: vncDriver,
|
|
5
|
-
rdp: rdpDriver
|
|
6
|
-
};
|
|
7
|
-
function driverFor(protocol) {
|
|
8
|
-
return DRIVERS[protocol] ?? DRIVERS.vnc;
|
|
9
|
-
}
|
|
10
|
-
function explainDisconnect(diagnostic, clean, protocolMessage) {
|
|
11
|
-
if (protocolMessage) return protocolMessage;
|
|
12
|
-
const code = diagnostic.close?.code;
|
|
13
|
-
const reason = diagnostic.close?.reason.trim() ?? "";
|
|
14
|
-
const suffix = code ? ` (WebSocket ${code}${reason ? `: ${reason}` : ""})` : "";
|
|
15
|
-
const context = { ...code === void 0 ? {} : { code }, reason, suffix };
|
|
16
|
-
const driver = driverFor(diagnostic.protocol);
|
|
17
|
-
const specific = driver.describeDisconnect(context);
|
|
18
|
-
if (specific) return specific;
|
|
19
|
-
const name = driver.protocol.toUpperCase();
|
|
20
|
-
if (/tcp (reached )?eof/i.test(reason)) {
|
|
21
|
-
return `The ${name} host accepted the connection and then closed it${suffix}. Check its remote-access permissions and the account name.`;
|
|
22
|
-
}
|
|
23
|
-
if (code === 1006) {
|
|
24
|
-
return "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.";
|
|
25
|
-
}
|
|
26
|
-
if (reason) return `The remote session ended${suffix}.`;
|
|
27
|
-
if (clean) return `The remote server closed the session cleanly${suffix || " (no reason supplied)"}.`;
|
|
28
|
-
return `The ${name} negotiation failed${suffix || " before the server supplied a close reason"}.`;
|
|
29
|
-
}
|
|
30
|
-
export {
|
|
31
|
-
DRIVERS,
|
|
32
|
-
driverFor,
|
|
33
|
-
explainDisconnect
|
|
34
|
-
};
|
|
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};
|