tabby-rdp 0.6.2 → 0.6.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.md +16 -11
  3. package/bin/SHA256SUMS +8 -8
  4. package/bin/darwin-arm64/tabby-rdp-proxy +0 -0
  5. package/bin/darwin-x64/tabby-rdp-proxy +0 -0
  6. package/bin/linux-arm/tabby-rdp-proxy +0 -0
  7. package/bin/linux-arm64/tabby-rdp-proxy +0 -0
  8. package/bin/linux-x64/tabby-rdp-proxy +0 -0
  9. package/bin/win32-arm64/tabby-rdp-proxy.exe +0 -0
  10. package/bin/win32-x64/tabby-rdp-proxy.exe +0 -0
  11. package/dist/audio.js +26 -5
  12. package/dist/clipboard.js +8 -2
  13. package/dist/desktop.service.js +60 -14
  14. package/dist/desktopForm.js +1 -1
  15. package/dist/fileTransfer.js +41 -8
  16. package/dist/freerdp.js +36 -14
  17. package/dist/freerdpClipboard.js +39 -9
  18. package/dist/freerdpFiles.js +183 -0
  19. package/dist/freerdpWasm.js +183 -0
  20. package/dist/freerdpWasmSocket.js +28 -0
  21. package/dist/freerdpWasmWorker.js +174 -0
  22. package/dist/pduTrace.js +27 -5
  23. package/dist/rdpClient.js +2 -2
  24. package/dist/rdpProfile.js +2 -2
  25. package/dist/settingsPage.js +6 -6
  26. package/dist/ui.js +2 -2
  27. package/dist/zgfx.js +33 -18
  28. package/native/README.md +64 -32
  29. package/package.json +6 -18
  30. package/vendor/SHA256SUMS +16 -5
  31. package/vendor/iron-remote-desktop-rdp.js +301 -301
  32. package/vendor/iron-remote-desktop.js +770 -736
  33. package/vendor/ironrdp-factory.js +301 -301
  34. package/vendor/ironrdp_web_bg.wasm +0 -0
  35. package/wasm/freerdp/BUILD.json +63 -0
  36. package/wasm/freerdp/licenses/Emscripten-LICENSE +102 -0
  37. package/wasm/freerdp/licenses/FreeRDP-LICENSE +202 -0
  38. package/wasm/freerdp/licenses/FreeRDP-NOTICE +13 -0
  39. package/wasm/freerdp/licenses/LibreSSL-LICENSE +133 -0
  40. package/wasm/freerdp/licenses/Unicode-NOTICE +21 -0
  41. package/wasm/freerdp/licenses/zlib-LICENSE +22 -0
  42. package/wasm/freerdp/tabby-freerdp.js +2 -0
  43. package/wasm/freerdp/tabby-freerdp.wasm +0 -0
package/dist/freerdp.js CHANGED
@@ -20,9 +20,13 @@ const fs_1 = require("fs");
20
20
  const net_1 = require("net");
21
21
  const path_1 = require("path");
22
22
  const tls_1 = require("tls");
23
+ const timers_1 = require("timers");
23
24
  const byteQueue_1 = require("./byteQueue");
24
25
  const authorities_1 = require("./authorities");
26
+ const freerdpWasm_1 = require("./freerdpWasm");
25
27
  const MAX_FRAME = 1024 * 1024;
28
+ const MAX_FILE_FRAME = 16 * 1024 * 1024 + 12;
29
+ const frameLimit = (type) => type === 's' ? MAX_FILE_FRAME : ['f', 'o'].includes(type) ? 8 + 10000 * 592 : MAX_FRAME;
26
30
  const MAX_AUTHORITIES = 16 * 1024 * 1024;
27
31
  function freeRDPAuthorities(authorities) {
28
32
  const text = authorities.join('\n');
@@ -33,7 +37,7 @@ function freeRDPAuthorities(authorities) {
33
37
  }
34
38
  function helperEnvironment() {
35
39
  // The helper needs OS paths/locale, not the parent app's API keys or the test runner's passwords.
36
- // WLOG_*: FreeRDP's own logging, for a diagnosis (see tools/pdu-trace/README.md): the helper keeps its log off
40
+ // WLOG_*: the native development helper's FreeRDP logging (WASM does not export it), for a diagnosis (see tools/pdu-trace/README.md): the helper keeps its log off
37
41
  // unless these ask for a channel's log into a file (WLOG_APPENDER=FILE); its console stays the IPC's.
38
42
  const keys = ['PATH', 'HOME', 'USERPROFILE', 'APPDATA', 'LOCALAPPDATA', 'SystemRoot', 'WINDIR', 'TEMP', 'TMP', 'TMPDIR',
39
43
  'LANG', 'LC_ALL', 'TZ', 'OPENSSL_CONF', 'WLOG_FILTER', 'WLOG_APPENDER', 'WLOG_FILEAPPENDER_OUTPUT_FILE_PATH',
@@ -68,7 +72,11 @@ function nativeHelperPath() {
68
72
  function requireFreeRDP() {
69
73
  if (!hasFreeRDP()) {
70
74
  const platform = `${process.platform}-${process.arch}`;
71
- const platforms = require('../package.json').tabbyRdp?.freerdpPlatforms;
75
+ const metadata = require('../package.json').tabbyRdp;
76
+ if (metadata?.packageFormat === 6) {
77
+ throw new Error(`The native FreeRDP comparison build for ${platform} is missing. Build it with npm run build:freerdp; the packaged client uses WebAssembly.`);
78
+ }
79
+ const platforms = metadata?.freerdpPlatforms;
72
80
  throw new Error(Array.isArray(platforms) && platforms.includes(platform)
73
81
  ? `FreeRDP's helper for ${platform} is not installed. npm installs it with the plugin, as ${freeRDPPackage(platform)}: reinstall tabby-rdp, or choose IronRDP in this desktop's settings.`
74
82
  : `FreeRDP is not available for ${platform}. Choose IronRDP in this desktop's settings.`);
@@ -82,7 +90,7 @@ function helperStopped(code, signal, platform = process.platform) {
82
90
  return new Error(`The FreeRDP helper stopped (${signal ?? code ?? 'unknown'})`);
83
91
  }
84
92
  function ipcFrame(type, payload = Buffer.alloc(0)) {
85
- if (type.length !== 1 || payload.length > MAX_FRAME) {
93
+ if (type.length !== 1 || payload.length > frameLimit(type)) {
86
94
  throw new Error('Invalid FreeRDP IPC message');
87
95
  }
88
96
  const header = Buffer.alloc(5);
@@ -100,7 +108,7 @@ class FreeRDPFrames {
100
108
  while (this.queue.length >= 5) {
101
109
  const header = this.queue.peek(5);
102
110
  const length = header.readUInt32BE(1);
103
- if (length > MAX_FRAME) {
111
+ if (length > frameLimit(String.fromCharCode(header[0]))) {
104
112
  throw new Error('FreeRDP sent an oversized IPC message');
105
113
  }
106
114
  if (this.queue.length < length + 5) {
@@ -118,7 +126,7 @@ function numbers(...values) {
118
126
  values.forEach((v, i) => out.writeUInt32BE(v >>> 0, i * 4));
119
127
  return out;
120
128
  }
121
- /** The native helper's IPC 6 start message: six strings followed by nine uint32 fields, the last the clipboard's ways. */
129
+ /** The native helper's IPC 8 start message: six strings followed by nine uint32 fields, the last the clipboard's ways. */
122
130
  function freeRDPStart(options, relay) {
123
131
  const strings = [options.host, options.username, options.password, options.domain, '', relay.token];
124
132
  const fields = strings.map(value => {
@@ -233,9 +241,9 @@ const SESSION_END_REASONS = {
233
241
  0x1000b: 'The remote user disconnected the session.',
234
242
  0x1000c: 'The remote user signed out.',
235
243
  };
236
- /** One native process, relay and set of promises per attempt. A native crash cannot take another desktop down. */
237
244
  class FreeRDPProcess {
238
- constructor() {
245
+ constructor(runtime = 'native') {
246
+ this.runtime = runtime;
239
247
  this.frameCount = 0;
240
248
  this.child = null;
241
249
  this.relay = null;
@@ -250,18 +258,29 @@ class FreeRDPProcess {
250
258
  const started = this.started;
251
259
  started.catch(() => undefined);
252
260
  try {
253
- requireFreeRDP();
261
+ if (this.runtime === 'wasm') {
262
+ (0, freerdpWasm_1.requireFreeRDPWasm)();
263
+ }
264
+ else {
265
+ requireFreeRDP();
266
+ }
254
267
  const authorities = freeRDPAuthorities(options.authorities ?? (0, authorities_1.certificateAuthorities)() ?? tls_1.rootCertificates);
255
268
  this.relay = await freeRDPRelay(options.open);
256
269
  if (this.closed) {
257
270
  this.relay.close();
258
271
  throw new Error('FreeRDP connection cancelled');
259
272
  }
260
- const child = this.child = (0, child_process_1.spawn)(nativeHelperPath(), [], { stdio: 'pipe', windowsHide: true, env: helperEnvironment() });
273
+ const child = this.child = this.runtime === 'wasm'
274
+ ? await freerdpWasm_1.FreeRDPWasmProcess.create(this.relay, helperEnvironment())
275
+ : (0, child_process_1.spawn)(nativeHelperPath(), [], { stdio: 'pipe', windowsHide: true, env: helperEnvironment() });
276
+ if (this.closed) {
277
+ child.kill();
278
+ throw new Error('FreeRDP connection cancelled');
279
+ }
261
280
  const frames = new FreeRDPFrames();
262
281
  const timer = setTimeout(() => this.fail(new Error('FreeRDP connection timed out')), 45000);
263
282
  started.then(() => clearTimeout(timer), () => clearTimeout(timer));
264
- child.once('error', () => this.fail(new Error('Could not start the FreeRDP helper. Rebuild it for this computer.')));
283
+ child.once('error', (error) => this.fail(this.runtime === 'wasm' ? error : new Error('Could not start the FreeRDP helper. Rebuild it for this computer.')));
265
284
  child.stdin.on('error', () => this.fail(new Error('The FreeRDP helper stopped reading input' + (process.platform === 'win32' ? '. Check that the Microsoft Visual C++ 2015–2022 Redistributable is installed; see the compatibility guide.' : ''))));
266
285
  // Do not surface FreeRDP logs: native libraries can log authentication details.
267
286
  child.stderr.resume();
@@ -326,6 +345,9 @@ class FreeRDPProcess {
326
345
  else if (type === 'F') {
327
346
  options.frame(decodeNativeFrame(data));
328
347
  }
348
+ else if (['l', 'f', 'a', 'q', 's'].includes(type)) {
349
+ options.clipboardFiles?.(type, data);
350
+ }
329
351
  else if (type === 'T') {
330
352
  options.remoteText?.(data.toString('utf8'));
331
353
  }
@@ -359,11 +381,11 @@ class FreeRDPProcess {
359
381
  }
360
382
  // During freerdp_connect the helper reads certificate/NLA decisions directly from stdin. User input
361
383
  // must not get ahead of those replies and be mistaken for a refusal.
362
- if (!this.connected && ['K', 'M', 'R', 'P', 'W'].includes(type)) {
384
+ if (!this.connected && ['K', 'M', 'R', 'P', 'W', 'o', 'q', 's'].includes(type)) {
363
385
  return;
364
386
  }
365
387
  // A child that has stalled must not accumulate an unbounded queue of mouse/keyboard events.
366
- if (this.child.stdin.writableLength > MAX_FRAME) {
388
+ if (this.child.stdin.writableLength > 4 * MAX_FILE_FRAME) {
367
389
  this.fail(new Error('FreeRDP input stopped responding'));
368
390
  return;
369
391
  }
@@ -410,11 +432,11 @@ class FreeRDPProcess {
410
432
  this.child?.kill();
411
433
  const child = this.child;
412
434
  if (child) {
413
- const timer = setTimeout(() => { if (child.exitCode === null && child.signalCode === null) {
435
+ const timer = (0, timers_1.setTimeout)(() => { if (child.exitCode === null && child.signalCode === null) {
414
436
  child.kill('SIGKILL');
415
437
  } }, 1000);
416
438
  timer.unref();
417
- child.once('close', () => clearTimeout(timer));
439
+ child.once('close', () => (0, timers_1.clearTimeout)(timer));
418
440
  }
419
441
  }
420
442
  }
@@ -5,7 +5,7 @@ exports.freeRDPClipboardLog = freeRDPClipboardLog;
5
5
  /** The log line for the clipboard a FreeRDP connection was set up with (IronRDP's says the same of pictures and files). */
6
6
  function freeRDPClipboardLog(mode) {
7
7
  return `clipboard: ${mode === 'both' ? 'both ways' : mode === 'fromRemote' ? 'only from the remote desktop (this computer\'s is neither read nor sent)'
8
- : 'off (no clipboard channel)'}${mode === 'off' ? '' : '; FreeRDP shares text only'}`;
8
+ : 'off (no clipboard channel)'}${mode === 'off' ? '' : '; FreeRDP shares text and files'}`;
9
9
  }
10
10
  /**
11
11
  * Text through FreeRDP's clipboard channel: the helper's 'P' message offers this computer's text to the server, and 'T'
@@ -14,15 +14,28 @@ function freeRDPClipboardLog(mode) {
14
14
  * a change is sent; what the server's gets is written here then, or, from a desktop without the focus, the latest of
15
15
  * it once it has the focus again; and it is remembered, so that it isn't sent straight back. A desktop in the
16
16
  * background can't change this computer's clipboard. In view only no clipboard goes either way, and what the desktop's
17
- * clipboard gets meanwhile is dropped.
17
+ * clipboard gets meanwhile is dropped. Entering it withdraws what this side offered, if that is still the latest on the
18
+ * server's clipboard (a copy of the server's own since is left alone); leaving it offers that again. The helper reports every server format list, including copies without text.
18
19
  *
19
20
  * The ways are asked on every turn: a narrowing while connected (see RemoteDesktopService.applyClipboard) stops the
20
21
  * sending at once, and is passed on to the helper (`narrow`), which drops what it was holding for the server.
21
- * Nothing is read before `start`, once the connection is up. Pictures and files don't go through FreeRDP.
22
+ * Nothing is read before `start`, once the connection is up. File offers suppress text polling until pasted.
22
23
  */
23
24
  /** How soon the same text from the server counts as the same copy announced again (see FreeRDPClipboard.remote). */
24
25
  const REPEATED_COPY_MS = 1500;
25
26
  class FreeRDPClipboard {
27
+ /** A file offer must not be overwritten by the text already on the local clipboard. */
28
+ localFiles() {
29
+ this.pending = undefined;
30
+ this.offered = true;
31
+ if (this.ways().toRemote) {
32
+ try {
33
+ this.last = this.io.read();
34
+ }
35
+ catch { }
36
+ }
37
+ }
38
+ remoteChanged() { this.pending = undefined; this.offered = false; this.withdrawn = false; }
26
39
  constructor(io, ways,
27
40
  /** `focused`: the desktop has the focus; `viewOnly`: it is in view only. */
28
41
  focus, interval = 100, now = Date.now) {
@@ -32,6 +45,11 @@ class FreeRDPClipboard {
32
45
  this.interval = interval;
33
46
  this.now = now;
34
47
  this.paused = false;
48
+ this.filesPending = () => false;
49
+ /** Whether the latest on the server's clipboard is what this side offered, as far as this side knows. */
50
+ this.offered = false;
51
+ /** Whether entering view only withdrew what this side offered, which leaving it offers again. */
52
+ this.withdrawn = false;
35
53
  // The ways the connection was set up with, which the helper has.
36
54
  this.told = ways();
37
55
  }
@@ -47,19 +65,26 @@ class FreeRDPClipboard {
47
65
  this.io.narrow(ways);
48
66
  }
49
67
  if (this.focus.viewOnly()) {
50
- // Entering view only: what the helper still holds for the server is withdrawn, and the clipboard here is
51
- // offered again once view only ends.
68
+ // Entering view only: what the helper still holds for the server is withdrawn, if it is still the latest
69
+ // there, and the clipboard here is offered again once view only ends.
52
70
  if (!this.paused) {
53
71
  this.paused = true;
54
- this.last = undefined;
55
- if (ways.toRemote) {
72
+ if (this.offered && ways.toRemote) {
73
+ this.offered = false;
74
+ this.withdrawn = true;
56
75
  this.io.send('');
57
76
  }
58
77
  }
59
78
  this.pending = undefined;
60
79
  return;
61
80
  }
62
- this.paused = false;
81
+ if (this.paused) {
82
+ this.paused = false;
83
+ if (this.withdrawn) {
84
+ this.withdrawn = false;
85
+ this.last = undefined;
86
+ }
87
+ }
63
88
  if (!this.focus.focused()) {
64
89
  return;
65
90
  }
@@ -71,7 +96,7 @@ class FreeRDPClipboard {
71
96
  this.io.write(text);
72
97
  }
73
98
  }
74
- if (!ways.toRemote) {
99
+ if (!ways.toRemote || this.filesPending()) {
75
100
  return;
76
101
  }
77
102
  let text;
@@ -83,11 +108,15 @@ class FreeRDPClipboard {
83
108
  }
84
109
  if (text !== this.last) {
85
110
  this.last = text;
111
+ this.offered = text !== '';
86
112
  this.io.send(text);
87
113
  }
88
114
  }
89
115
  /** Text the server's clipboard got, if it may come: written here now with the focus, else once it has it. */
90
116
  remote(text) {
117
+ // The server's own copy: the latest there, which leaving view only doesn't overwrite.
118
+ this.offered = false;
119
+ this.withdrawn = false;
91
120
  if (!this.ways().fromRemote || this.focus.viewOnly()) {
92
121
  return;
93
122
  }
@@ -114,6 +143,7 @@ class FreeRDPClipboard {
114
143
  }
115
144
  const text = this.io.read();
116
145
  this.last = text;
146
+ this.offered = text !== '';
117
147
  this.io.send(text);
118
148
  }
119
149
  stop() {
@@ -0,0 +1,183 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MAX_FILE_MESSAGE = exports.MAX_FILE_LIST = void 0;
4
+ exports.encodeFileList = encodeFileList;
5
+ exports.decodeFileList = decodeFileList;
6
+ exports.freeRDPFileProvider = freeRDPFileProvider;
7
+ const fileTransfer_1 = require("./fileTransfer");
8
+ const freerdp_1 = require("./freerdp");
9
+ const DESCRIPTOR_SIZE = 592;
10
+ exports.MAX_FILE_LIST = 4 + fileTransfer_1.MAX_ENTRIES * DESCRIPTOR_SIZE;
11
+ exports.MAX_FILE_MESSAGE = fileTransfer_1.MAX_RANGE + 12;
12
+ /** MS-RDPECLIP FILEGROUPDESCRIPTORW; its fields are little endian, unlike the helper IPC. */
13
+ function encodeFileList(files) {
14
+ if (!files.length || files.length > fileTransfer_1.MAX_ENTRIES) {
15
+ throw new Error('Too many clipboard files, or an empty offer');
16
+ }
17
+ const data = Buffer.alloc(4 + files.length * DESCRIPTOR_SIZE);
18
+ data.writeUInt32LE(files.length);
19
+ files.forEach((file, i) => {
20
+ const full = checkedPath(file.path ? `${file.path}\\${file.name}` : file.name);
21
+ // No huge-file capability is negotiated. Reject rather than silently truncate a size or a name.
22
+ if (full.length >= 260 || !Number.isSafeInteger(file.size) || file.size < 0 || file.size > 0xffffffff) {
23
+ throw new Error('Clipboard file names must fit 259 UTF-16 characters and files must be smaller than 4 GiB');
24
+ }
25
+ const offset = 4 + i * DESCRIPTOR_SIZE;
26
+ data.writeUInt32LE(0x44, offset); // FD_ATTRIBUTES | FD_FILESIZE
27
+ data.writeUInt32LE(file.isDirectory ? 0x10 : 0x80, offset + 36);
28
+ data.writeUInt32LE(file.isDirectory ? 0 : file.size, offset + 68);
29
+ data.write(full, offset + 72, 520, 'utf16le');
30
+ });
31
+ return data;
32
+ }
33
+ function checkedPath(name) {
34
+ if (!name || name.includes('\0') || name.startsWith('/') || name.startsWith('\\') || name.includes('/')) {
35
+ throw new Error('Invalid clipboard file path');
36
+ }
37
+ const parts = name.split('\\');
38
+ if (parts.some(part => !part || part === '.' || part === '..' || /[<>:"|?*\x00-\x1f]/.test(part))) {
39
+ throw new Error('Invalid clipboard file path');
40
+ }
41
+ return parts.join('\\');
42
+ }
43
+ function decodeFileList(data) {
44
+ if (data.length < 4 || data.length > exports.MAX_FILE_LIST) {
45
+ throw new Error('Invalid clipboard file list length');
46
+ }
47
+ const count = data.readUInt32LE(0);
48
+ if (count > fileTransfer_1.MAX_ENTRIES || data.length !== 4 + count * DESCRIPTOR_SIZE) {
49
+ throw new Error('Invalid clipboard file count');
50
+ }
51
+ return Array.from({ length: count }, (_, i) => {
52
+ const offset = 4 + i * DESCRIPTOR_SIZE;
53
+ const text = data.subarray(offset + 72, offset + 592).toString('utf16le');
54
+ const end = text.indexOf('\0');
55
+ if (end < 0) {
56
+ throw new Error('Unterminated clipboard file name');
57
+ }
58
+ const full = checkedPath(text.slice(0, end));
59
+ const parts = full.split('\\'), name = parts.pop();
60
+ const flags = data.readUInt32LE(offset);
61
+ const size = flags & 0x40 ? data.readUInt32LE(offset + 64) * 0x100000000 + data.readUInt32LE(offset + 68) : 0;
62
+ if (!Number.isSafeInteger(size)) {
63
+ throw new Error('Invalid clipboard file size');
64
+ }
65
+ return { name, path: parts.length ? parts.join('\\') : undefined, size,
66
+ isDirectory: !!(flags & 4 && data.readUInt32LE(offset + 36) & 0x10) };
67
+ });
68
+ }
69
+ /** Uses the existing JS transfer provider and disk/UI policy; no IronRDP WASM instance is needed. */
70
+ function freeRDPFileProvider(Base, send, ways, localOffer) {
71
+ return class extends Base {
72
+ constructor() {
73
+ super(...arguments);
74
+ this.localGeneration = 0;
75
+ this.remoteGeneration = 0;
76
+ this.requests = new Map();
77
+ this.downloads = new Map();
78
+ }
79
+ discardFileContentsRequest(stream) { this.requests.delete(stream); }
80
+ downloadFile(file, index) {
81
+ if (this.availableFiles[index] !== file) {
82
+ throw new Error('The remote clipboard changed before this file could be saved');
83
+ }
84
+ const handle = super.downloadFile(file, index);
85
+ handle.completion.finally(() => this.downloads.delete(handle.transferId)).catch(() => undefined);
86
+ return handle;
87
+ }
88
+ dispose() {
89
+ this.requests.clear();
90
+ this.downloads.clear();
91
+ super.dispose();
92
+ }
93
+ sendInitiateFileCopy(files) {
94
+ if (!ways().toRemote) {
95
+ throw new Error('Clipboard files cannot go to this desktop');
96
+ }
97
+ const descriptors = encodeFileList(files);
98
+ for (const [stream, generation] of this.requests) {
99
+ send('s', (0, freerdp_1.numbers)(generation, stream, 1));
100
+ }
101
+ this.requests.clear();
102
+ this.localGeneration = (this.localGeneration + 1) >>> 0;
103
+ localOffer();
104
+ send('o', Buffer.concat([(0, freerdp_1.numbers)(this.localGeneration), descriptors]));
105
+ }
106
+ sendRequestFileContents(stream, index, flags, position, size) {
107
+ if (!ways().fromRemote) {
108
+ throw new Error('Clipboard files cannot come from this desktop');
109
+ }
110
+ if (!Number.isSafeInteger(position) || position < 0 || size > fileTransfer_1.MAX_RANGE) {
111
+ throw new Error('Invalid file contents request');
112
+ }
113
+ if (flags === 1 && !this.downloads.has(stream)) {
114
+ this.downloads.set(stream, this.remoteGeneration);
115
+ }
116
+ if (this.downloads.get(stream) !== this.remoteGeneration) {
117
+ throw new Error('The remote clipboard changed during the download');
118
+ }
119
+ send('q', (0, freerdp_1.numbers)(this.remoteGeneration, stream, index, flags, position % 0x100000000, Math.floor(position / 0x100000000), size));
120
+ }
121
+ sendSubmitFileContents(stream, error, data) {
122
+ const generation = this.requests.get(stream);
123
+ this.requests.delete(stream);
124
+ if (generation === undefined) {
125
+ return;
126
+ }
127
+ const refused = error || !ways().toRemote || generation !== this.localGeneration || data.length > fileTransfer_1.MAX_RANGE;
128
+ send('s', Buffer.concat([(0, freerdp_1.numbers)(generation, stream, +refused), refused ? Buffer.alloc(0) : Buffer.from(data)]));
129
+ }
130
+ receive(type, data) {
131
+ if (type === 'l' && data.length === 4) {
132
+ this.remoteGeneration = data.readUInt32BE(0);
133
+ for (const [stream, generation] of this.requests) {
134
+ send('s', (0, freerdp_1.numbers)(generation, stream, 1));
135
+ }
136
+ this.requests.clear();
137
+ // Without clipboard locking, a new offer invalidates unfinished downloads.
138
+ for (const stream of this.downloads.keys()) {
139
+ this.handleFileContentsResponse({ streamId: stream, isError: true, data: new Uint8Array() });
140
+ }
141
+ this.downloads.clear();
142
+ this.handleFilesAvailable([], undefined);
143
+ }
144
+ else if (type === 'f' && data.length >= 4) {
145
+ if (!ways().fromRemote || data.readUInt32BE(0) !== this.remoteGeneration) {
146
+ return;
147
+ }
148
+ try {
149
+ this.handleFilesAvailable(decodeFileList(data.subarray(4)), undefined);
150
+ }
151
+ catch (error) {
152
+ this.emit('error', { message: error.message });
153
+ }
154
+ }
155
+ else if (type === 'a' && data.length === 5) {
156
+ if (data.readUInt32BE(0) === this.localGeneration) {
157
+ this.handleFormatListResponse(data[4] === 1);
158
+ }
159
+ }
160
+ else if (type === 'q' && data.length === 28) {
161
+ this.beforeFileContentsRequest?.();
162
+ const generation = data.readUInt32BE(0), stream = data.readUInt32BE(4);
163
+ const position = data.readUInt32BE(16) + data.readUInt32BE(20) * 0x100000000;
164
+ if (generation !== this.localGeneration || !ways().toRemote || !Number.isSafeInteger(position) || this.requests.has(stream) || this.requests.size >= 1024) {
165
+ send('s', (0, freerdp_1.numbers)(generation, stream, 1));
166
+ return;
167
+ }
168
+ this.requests.set(stream, generation);
169
+ this.handleFileContentsRequest({ streamId: stream, index: data.readUInt32BE(8), flags: data.readUInt32BE(12), position, size: data.readUInt32BE(24) });
170
+ }
171
+ else if (type === 's' && data.length >= 8) {
172
+ const stream = data.readUInt32BE(0);
173
+ if (!this.downloads.has(stream)) {
174
+ return;
175
+ }
176
+ this.handleFileContentsResponse({ streamId: stream, isError: !!data.readUInt32BE(4) || !ways().fromRemote, data: data.subarray(8) });
177
+ }
178
+ else {
179
+ throw new Error('Invalid FreeRDP clipboard message');
180
+ }
181
+ }
182
+ };
183
+ }
@@ -0,0 +1,183 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FreeRDPWasmProcess = void 0;
4
+ exports.freeRDPWasmPath = freeRDPWasmPath;
5
+ exports.hasFreeRDPWasm = hasFreeRDPWasm;
6
+ exports.requireFreeRDPWasm = requireFreeRDPWasm;
7
+ const fs_1 = require("fs");
8
+ const path_1 = require("path");
9
+ const net_1 = require("net");
10
+ const events_1 = require("events");
11
+ const stream_1 = require("stream");
12
+ const worker_threads_1 = require("worker_threads");
13
+ const crypto_1 = require("crypto");
14
+ function freeRDPWasmPath() { return (0, path_1.join)(__dirname, '..', 'wasm/freerdp/tabby-freerdp.js'); }
15
+ function hasFreeRDPWasm() { return (0, fs_1.existsSync)(freeRDPWasmPath()) && (0, fs_1.existsSync)(freeRDPWasmPath().replace(/\.js$/, '.wasm')); }
16
+ function requireFreeRDPWasm() {
17
+ if (!hasFreeRDPWasm()) {
18
+ throw new Error('The FreeRDP WebAssembly build is missing. Install a complete tabby-rdp package or choose another client.');
19
+ }
20
+ }
21
+ /** Same bounded framed transport as the native client, backed by a WASM worker instead of a helper executable. */
22
+ class FreeRDPWasmProcess extends events_1.EventEmitter {
23
+ constructor() {
24
+ super();
25
+ this.stdout = new stream_1.PassThrough();
26
+ this.stderr = new stream_1.PassThrough();
27
+ this.exitCode = null;
28
+ this.signalCode = null;
29
+ this.connections = new Set();
30
+ this.ended = false;
31
+ this.stdin = new stream_1.Writable({ write: (data, _encoding, done) => {
32
+ if (!this.worker || this.ended) {
33
+ done(new Error('FreeRDP WebAssembly stopped'));
34
+ return;
35
+ }
36
+ this.inputDone = done;
37
+ this.worker.postMessage({ type: 'input', data: new Uint8Array(data) });
38
+ }, final: done => { this.worker?.postMessage({ type: 'eof' }); done(); } });
39
+ }
40
+ static async create(relay, env) {
41
+ requireFreeRDPWasm();
42
+ const child = new FreeRDPWasmProcess();
43
+ const { WebSocketServer } = require('ws');
44
+ // Only this worker knows the path; browser origins are never accepted. The TCP relay independently
45
+ // authenticates the 64-byte token before opening SSH, RD Gateway, or a direct remote connection.
46
+ child.server = new WebSocketServer({ host: '127.0.0.1', port: 0, maxPayload: 16 * 1024 * 1024, perMessageDeflate: false,
47
+ verifyClient: (info) => !info.origin && info.req.url === `/${relay.token}` });
48
+ child.server.on('connection', (websocket) => {
49
+ const socket = (0, net_1.connect)({ host: '127.0.0.1', port: relay.port });
50
+ child.connections.add(websocket);
51
+ child.connections.add(socket);
52
+ const close = () => { websocket.terminate(); socket.destroy(); child.connections.delete(websocket); child.connections.delete(socket); };
53
+ websocket.on('error', close);
54
+ websocket.on('close', close);
55
+ socket.on('error', close);
56
+ // ws queues its close frame after earlier sends. A clean TCP end must preserve the
57
+ // server's final disconnect/error-info PDU; errors and explicit kills still abort.
58
+ socket.on('end', () => websocket.close());
59
+ socket.on('close', (failed) => failed ? close() : websocket.close());
60
+ websocket.on('message', (data, binary) => {
61
+ if (!binary) {
62
+ close();
63
+ return;
64
+ }
65
+ if (!socket.write(data)) {
66
+ websocket.pause();
67
+ }
68
+ });
69
+ socket.on('drain', () => websocket.resume());
70
+ socket.on('data', data => { socket.pause(); websocket.send(data, (error) => error ? close() : socket.resume()); });
71
+ });
72
+ await new Promise((resolve, reject) => { child.server.once('listening', resolve); child.server.once('error', reject); });
73
+ child.server.on('error', () => { child.emit('error', new Error('FreeRDP WebAssembly transport failed')); child.kill(); });
74
+ try {
75
+ const config = { module: freeRDPWasmPath(), websocket: `ws://127.0.0.1:${child.server.address().port}/${relay.token}` };
76
+ let events;
77
+ if (process.type === 'renderer') {
78
+ // Electron's renderer cannot host Node pthreads. A utility process can, and contains runtime failures.
79
+ const remote = require('@electron/remote');
80
+ const utility = remote.getBuiltin('utilityProcess')
81
+ .fork((0, path_1.join)(__dirname, 'freerdpWasmWorker.js'), [], { env, stdio: 'pipe', serviceName: 'tabby-rdp FreeRDP WebAssembly' });
82
+ utility.stdout?.on('data', () => { });
83
+ utility.stderr?.on('data', () => { });
84
+ // Remote calls are synchronous RPC through Electron's main process. Keep only process creation
85
+ // there: pixel chunks and input acknowledgements use a direct renderer/utility message port.
86
+ child.worker = { postMessage: message => utility.postMessage(message), terminate: async () => utility.kill() };
87
+ const ipc = require('electron').ipcRenderer;
88
+ const channelName = 'tabby-rdp-freerdp-' + (0, crypto_1.randomBytes)(16).toString('hex');
89
+ const channel = new (remote.getBuiltin('MessageChannelMain'))();
90
+ const messagePort = await new Promise((resolve, reject) => {
91
+ const receive = (event) => { clearTimeout(timer); resolve(event.ports[0]); };
92
+ const timer = setTimeout(() => { ipc.removeListener(channelName, receive); reject(new Error('FreeRDP message channel timed out')); }, 10000);
93
+ ipc.once(channelName, receive);
94
+ try {
95
+ utility.postMessage({ type: 'port' }, [channel.port2]);
96
+ remote.getCurrentWebContents().postMessage(channelName, null, [channel.port1]);
97
+ }
98
+ catch (error) {
99
+ clearTimeout(timer);
100
+ ipc.removeListener(channelName, receive);
101
+ reject(error);
102
+ }
103
+ });
104
+ events = new events_1.EventEmitter();
105
+ messagePort.onmessage = event => events.emit('message', event.data);
106
+ messagePort.onmessageerror = () => events.emit('error', new Error('FreeRDP message channel failed'));
107
+ utility.on('error', (error) => events.emit('error', error));
108
+ utility.on('exit', (code) => events.emit('exit', code));
109
+ child.worker = { postMessage: message => messagePort.postMessage(message), terminate: async () => { messagePort.close(); utility.kill(); } };
110
+ child.unload = () => { child.kill(); };
111
+ window.addEventListener('beforeunload', child.unload);
112
+ }
113
+ else {
114
+ events = new worker_threads_1.Worker((0, path_1.join)(__dirname, 'freerdpWasmWorker.js'), { env, workerData: config });
115
+ child.worker = events;
116
+ }
117
+ events.on('message', (message) => {
118
+ if (message.type === 'ready') {
119
+ child.worker?.postMessage({ type: 'init', config });
120
+ }
121
+ else if (message.type === 'input-ack') {
122
+ const done = child.inputDone;
123
+ child.inputDone = undefined;
124
+ done?.();
125
+ }
126
+ else if (message.type === 'output') {
127
+ const accepted = child.stdout.write(Buffer.from(message.data));
128
+ const ack = () => child.worker?.postMessage({ type: 'output-ack' });
129
+ if (accepted) {
130
+ ack();
131
+ }
132
+ else {
133
+ child.stdout.once('drain', ack);
134
+ }
135
+ }
136
+ else if (message.type === 'failure') {
137
+ child.emit('error', new Error(message.message));
138
+ child.kill();
139
+ }
140
+ else if (message.type === 'exit') {
141
+ child.exitCode = message.code;
142
+ child.kill();
143
+ }
144
+ });
145
+ events.on('error', () => { child.emit('error', new Error('FreeRDP WebAssembly worker failed')); child.kill(); });
146
+ events.on('exit', (code) => {
147
+ child.exitCode ??= code;
148
+ child.kill();
149
+ child.stdout.end();
150
+ child.stderr.end();
151
+ child.emit('close', child.exitCode, child.signalCode);
152
+ });
153
+ }
154
+ catch (error) {
155
+ child.kill();
156
+ throw error;
157
+ }
158
+ return child;
159
+ }
160
+ kill(signal = 'SIGTERM') {
161
+ if (this.ended) {
162
+ return false;
163
+ }
164
+ this.ended = true;
165
+ if (this.unload) {
166
+ window.removeEventListener('beforeunload', this.unload);
167
+ this.unload = undefined;
168
+ }
169
+ this.signalCode = this.exitCode === null ? signal : null;
170
+ this.server?.close();
171
+ for (const connection of this.connections) {
172
+ connection.terminate?.();
173
+ connection.destroy?.();
174
+ }
175
+ this.connections.clear();
176
+ this.worker?.terminate().catch(() => undefined);
177
+ const done = this.inputDone;
178
+ this.inputDone = undefined;
179
+ done?.(new Error('FreeRDP WebAssembly stopped'));
180
+ return true;
181
+ }
182
+ }
183
+ exports.FreeRDPWasmProcess = FreeRDPWasmProcess;
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MAX_WASM_SOCKET_BACKLOG = void 0;
4
+ exports.boundedWebSocket = boundedWebSocket;
5
+ /** Maximum data retained by a WASM socket when its peer stops reading. */
6
+ exports.MAX_WASM_SOCKET_BACKLOG = 64 * 1024 * 1024;
7
+ /** Used only in the isolated WASM worker, before Emscripten loads its ws constructor. */
8
+ function boundedWebSocket(Socket, overflow) {
9
+ return class extends Socket {
10
+ constructor() {
11
+ super(...arguments);
12
+ this.overflowed = false;
13
+ }
14
+ send(data, ...args) {
15
+ if (this.overflowed) {
16
+ return;
17
+ }
18
+ const size = typeof data === 'string' ? Buffer.byteLength(data) : data?.byteLength ?? data?.length ?? 0;
19
+ if (!Number.isSafeInteger(size) || size < 0 || this.bufferedAmount + size > exports.MAX_WASM_SOCKET_BACKLOG) {
20
+ this.overflowed = true;
21
+ this.terminate();
22
+ overflow();
23
+ return;
24
+ }
25
+ super.send(data, ...args);
26
+ }
27
+ };
28
+ }