jsgotty 0.9.1 → 1.1.1

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/client.mjs ADDED
@@ -0,0 +1,694 @@
1
+ #!/usr/bin/env bun
2
+
3
+ import process from "node:process";
4
+ import { Buffer } from "node:buffer";
5
+ import WebSocket from "ws";
6
+
7
+ const MSG_INPUT = "1";
8
+ const MSG_PING = "2";
9
+ const MSG_RESIZE_TERMINAL = "3";
10
+ const MSG_SET_ENCODING = "4";
11
+
12
+ const MSG_OUTPUT = "1";
13
+ const MSG_PONG = "2";
14
+ const MSG_SET_WINDOW_TITLE = "3";
15
+ const MSG_SET_PREFERENCES = "4";
16
+ const MSG_SET_RECONNECT = "5";
17
+ const MSG_SET_BUFFER_SIZE = "6";
18
+ const MSG_SET_ROLE = "a";
19
+ const MSG_CONTROL_RESULT = "b";
20
+
21
+ const DEFAULT_URL = "ws://127.0.0.1:8080/ws";
22
+
23
+ function usage() {
24
+ console.log(`Usage:
25
+ bun client.mjs [options] [target]
26
+
27
+ Target:
28
+ Defaults to ${DEFAULT_URL}
29
+ A pure number connects to 127.0.0.1 on that port, for example 8080.
30
+ Accepts http(s) page URLs or ws(s) WebSocket URLs.
31
+
32
+ Options:
33
+ -r, --reconnect-token <token|pid>
34
+ Resume a session by token or PID
35
+ -d, --detach <token|pid>
36
+ Disconnect the active writer for a session and exit
37
+ -k, --kill <token|pid>
38
+ Terminate the session PTY for a token or PID
39
+ -ls
40
+ List reconnectable sessions and exit
41
+
42
+ -c, --credential <user:pass>
43
+ GoTTY credential/AuthToken
44
+ --readonly
45
+ Never request terminal write access
46
+ --arg <value>
47
+ Add ?arg=<value> to the init Arguments
48
+ --arguments <query>
49
+ Raw init Arguments, for example "?arg=bash"
50
+ --cols <number>
51
+ Initial terminal columns
52
+ --rows <number>
53
+ Initial terminal rows
54
+ -h, --help
55
+ Show help
56
+
57
+ Environment:
58
+ GOTTY_CREDENTIAL
59
+ GOTTY_RECONNECT_TOKEN`);
60
+ }
61
+
62
+ function parseArgs(argv) {
63
+ const options = {
64
+ url: "",
65
+ credential: process.env.GOTTY_CREDENTIAL || "",
66
+ reconnectToken: process.env.GOTTY_RECONNECT_TOKEN || "",
67
+ arguments: "",
68
+ args: [],
69
+ cols: 0,
70
+ rows: 0,
71
+ readonly: false,
72
+ listSessions: false,
73
+ disconnectWriterTarget: "",
74
+ killSessionTarget: ""
75
+ };
76
+
77
+ for (let i = 0; i < argv.length; i += 1) {
78
+ const arg = argv[i];
79
+ const next = () => {
80
+ i += 1;
81
+ if (i >= argv.length) {
82
+ throw new Error(`${arg} requires a value`);
83
+ }
84
+ return argv[i];
85
+ };
86
+
87
+ switch (arg) {
88
+ case "-h":
89
+ case "--help":
90
+ usage();
91
+ process.exit(0);
92
+ break;
93
+ case "-c":
94
+ case "--credential":
95
+ options.credential = next();
96
+ break;
97
+ case "-r":
98
+ case "--reconnect-token":
99
+ options.reconnectToken = next();
100
+ break;
101
+ case "-d":
102
+ case "--detach":
103
+ options.disconnectWriterTarget = next();
104
+ break;
105
+ case "-k":
106
+ case "--kill":
107
+ options.killSessionTarget = next();
108
+ break;
109
+ case "-ls":
110
+ options.listSessions = true;
111
+ break;
112
+ case "--readonly":
113
+ options.readonly = true;
114
+ break;
115
+ case "--arg":
116
+ options.args.push(next());
117
+ break;
118
+ case "--arguments":
119
+ options.arguments = next();
120
+ break;
121
+ case "--cols":
122
+ options.cols = Number.parseInt(next(), 10) || 0;
123
+ break;
124
+ case "--rows":
125
+ options.rows = Number.parseInt(next(), 10) || 0;
126
+ break;
127
+ default:
128
+ if (arg.startsWith("-")) {
129
+ throw new Error(`unknown option: ${arg}`);
130
+ }
131
+ if (options.url) {
132
+ throw new Error(`unexpected extra URL/argument: ${arg}`);
133
+ }
134
+ options.url = arg;
135
+ break;
136
+ }
137
+ }
138
+
139
+ return options;
140
+ }
141
+
142
+ function normalizeUrl(input) {
143
+ const raw = input || DEFAULT_URL;
144
+ const target = /^\d+$/.test(raw) ? `127.0.0.1:${raw}` : raw;
145
+ const withScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(target) ? target : `ws://${target}`;
146
+ const url = new URL(withScheme);
147
+ const reconnectToken = url.searchParams.get("reconnect-token")?.trim() || "";
148
+ url.searchParams.delete("reconnect-token");
149
+ if (!url.port) {
150
+ url.port = "8080";
151
+ }
152
+ let initArguments = "";
153
+
154
+ const appendWsPath = () => {
155
+ if (!url.pathname || url.pathname === "/") {
156
+ url.pathname = "/ws";
157
+ } else if (url.pathname.endsWith("/")) {
158
+ url.pathname = `${url.pathname}ws`;
159
+ } else if (!url.pathname.endsWith("/ws")) {
160
+ url.pathname = `${url.pathname}/ws`;
161
+ }
162
+ };
163
+
164
+ if (url.protocol === "http:" || url.protocol === "https:") {
165
+ initArguments = url.search || "";
166
+ url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
167
+ url.search = "";
168
+ appendWsPath();
169
+ } else if (url.protocol !== "ws:" && url.protocol !== "wss:") {
170
+ throw new Error(`unsupported URL protocol: ${url.protocol}`);
171
+ }
172
+
173
+ appendWsPath();
174
+
175
+ return {
176
+ wsUrl: url.toString(),
177
+ initArguments,
178
+ reconnectToken
179
+ };
180
+ }
181
+
182
+ function buildArguments(options, urlArguments) {
183
+ if (options.arguments) {
184
+ return options.arguments.startsWith("?") ? options.arguments : `?${options.arguments}`;
185
+ }
186
+ if (options.args.length > 0) {
187
+ const params = new URLSearchParams();
188
+ for (const arg of options.args) {
189
+ params.append("arg", arg);
190
+ }
191
+ return `?${params.toString()}`;
192
+ }
193
+ return urlArguments;
194
+ }
195
+
196
+ function terminalSize(options) {
197
+ return {
198
+ columns: options.cols || process.stdout.columns || 80,
199
+ rows: options.rows || process.stdout.rows || 24
200
+ };
201
+ }
202
+
203
+ function sendResize(ws, options) {
204
+ const size = terminalSize(options);
205
+ ws.send(MSG_RESIZE_TERMINAL + JSON.stringify(size));
206
+ }
207
+
208
+ function setRawMode(enabled) {
209
+ if (process.stdin.isTTY && typeof process.stdin.setRawMode === "function") {
210
+ process.stdin.setRawMode(enabled);
211
+ }
212
+ }
213
+
214
+ function writeStatus(message) {
215
+ const colorEnabled = process.stderr.isTTY && !("NO_COLOR" in process.env);
216
+ const label = colorEnabled ? "\u001b[1;36m[gotty]\u001b[0m" : "[gotty]";
217
+ process.stderr.write(`${message.replaceAll("[gotty]", label)}\n`);
218
+ }
219
+
220
+ function sessionListUrl(wsUrl) {
221
+ const url = new URL(wsUrl);
222
+ url.protocol = url.protocol === "wss:" ? "https:" : "http:";
223
+ url.pathname = url.pathname.endsWith("/ws")
224
+ ? `${url.pathname.slice(0, -2)}css.md`
225
+ : `${url.pathname.replace(/\/?$/, "/")}css.md`;
226
+ url.search = "";
227
+ url.hash = "";
228
+ return url.toString();
229
+ }
230
+
231
+ async function listSessions(options, wsUrl) {
232
+ const url = sessionListUrl(wsUrl);
233
+ const headers = {};
234
+ if (options.credential) {
235
+ headers.Authorization = `Basic ${Buffer.from(options.credential).toString("base64")}`;
236
+ }
237
+
238
+ try {
239
+ const response = await fetch(url, { headers });
240
+ if (!response.ok) {
241
+ throw new Error(`HTTP ${response.status}`);
242
+ }
243
+ const contentType = response.headers.get("content-type") || "";
244
+ if (!contentType.toLowerCase().includes("text/markdown")) {
245
+ throw new Error(`unexpected Content-Type: ${contentType || "(missing)"}`);
246
+ }
247
+ const markdown = await response.text();
248
+ const markdownToAnsi = globalThis.Bun?.markdown?.ansi;
249
+ const output = typeof markdownToAnsi === "function"
250
+ ? markdownToAnsi(markdown)
251
+ : markdown;
252
+ process.stdout.write(output.endsWith("\n") ? output : `${output}\n`);
253
+ } catch (error) {
254
+ writeStatus(`[gotty] 無法列出 sessions:舊版或 Golang GoTTY 伺服器不支援此功能
255
+ Can't list sessions: older or Golang GoTTY servers do not support this feature`);
256
+ process.exitCode = 1;
257
+ }
258
+ }
259
+
260
+ async function sendSessionControl(options, wsUrl, {
261
+ target,
262
+ request,
263
+ successMessage,
264
+ errorPrefix,
265
+ timeoutMessage,
266
+ unsupportedMessage,
267
+ timeoutMs = 5000,
268
+ }) {
269
+ await new Promise((resolve) => {
270
+ const ws = new WebSocket(wsUrl, "webtty");
271
+ let completed = false;
272
+ const finish = (exitCode) => {
273
+ if (completed) {
274
+ return;
275
+ }
276
+ completed = true;
277
+ clearTimeout(timer);
278
+ process.exitCode = exitCode;
279
+ resolve();
280
+ };
281
+ const timer = setTimeout(() => {
282
+ writeStatus(timeoutMessage);
283
+ finish(1);
284
+ try {
285
+ ws.close();
286
+ } catch {}
287
+ }, timeoutMs);
288
+
289
+ ws.on("open", () => {
290
+ ws.send(JSON.stringify({
291
+ Arguments: "",
292
+ AuthToken: options.credential,
293
+ ReconnectToken: target,
294
+ ReadOnly: true,
295
+ ...request
296
+ }));
297
+ });
298
+
299
+ ws.on("message", (data) => {
300
+ const text = Buffer.isBuffer(data) ? data.toString("utf8") : String(data);
301
+ if (!text || text[0] !== MSG_CONTROL_RESULT) {
302
+ return;
303
+ }
304
+ try {
305
+ const result = JSON.parse(text.slice(1));
306
+ if (result.ok) {
307
+ writeStatus(successMessage(result));
308
+ finish(0);
309
+ } else {
310
+ writeStatus(`${errorPrefix}\n ${result.message}`);
311
+ finish(1);
312
+ }
313
+ } catch (error) {
314
+ writeStatus(`[gotty] invalid session control response:\n ${error.message}`);
315
+ finish(1);
316
+ }
317
+ ws.close();
318
+ });
319
+
320
+ ws.on("error", (error) => {
321
+ writeStatus(`${errorPrefix}\n ${error.message}`);
322
+ finish(1);
323
+ });
324
+
325
+ ws.on("close", (code, reason) => {
326
+ if (!completed) {
327
+ const detail = reason?.length ? `: ${reason.toString()}` : "";
328
+ writeStatus(`${unsupportedMessage} (${code})${detail}`);
329
+ finish(1);
330
+ }
331
+ });
332
+ });
333
+ }
334
+
335
+ async function disconnectWriter(options, wsUrl) {
336
+ const target = options.disconnectWriterTarget.trim();
337
+ return sendSessionControl(options, wsUrl, {
338
+ target,
339
+ request: { DisconnectWriter: true },
340
+ successMessage: (result) => `[gotty] ${result.message}
341
+ reconnect token:
342
+ ${result.token}
343
+ pid:
344
+ ${result.pid}`,
345
+ errorPrefix: "[gotty] failed to disconnect writer:",
346
+ timeoutMessage: "[gotty] writer disconnect request timed out",
347
+ unsupportedMessage: "[gotty] server does not support writer disconnect"
348
+ });
349
+ }
350
+
351
+ async function killSession(options, wsUrl) {
352
+ const target = options.killSessionTarget.trim();
353
+ return sendSessionControl(options, wsUrl, {
354
+ target,
355
+ request: { TerminateSession: true },
356
+ successMessage: (result) => `[gotty] ${result.message}
357
+ pid:
358
+ ${result.pid}
359
+ token:
360
+ ${result.token || "(none)"}`,
361
+ errorPrefix: "[gotty] failed to terminate session:",
362
+ timeoutMessage: "[gotty] session terminate request timed out",
363
+ unsupportedMessage: "[gotty] server does not support session terminate",
364
+ timeoutMs: 7000
365
+ });
366
+ }
367
+
368
+ async function main() {
369
+ const cliArgs = process.argv.slice(2);
370
+ if (cliArgs[0] === "attach" ||
371
+ cliArgs[0] === "a") {
372
+ cliArgs[0] = "-r";
373
+ } else if (cliArgs[0] === "detach") {
374
+ cliArgs[0] = "-d";
375
+ } else if (cliArgs[0] === "kill-session" ||
376
+ cliArgs[0] === "stop") {
377
+ cliArgs[0] = "-k";
378
+ } else if (["ls", "list", "list-sessions"].includes(cliArgs[0])) {
379
+ cliArgs[0] = "-ls";
380
+ }
381
+ const options = parseArgs(cliArgs);
382
+ options.reconnectToken = options.reconnectToken.trim();
383
+ const {
384
+ wsUrl,
385
+ initArguments,
386
+ reconnectToken: urlReconnectToken
387
+ } = normalizeUrl(options.url);
388
+ if (!options.reconnectToken && urlReconnectToken) {
389
+ options.reconnectToken = urlReconnectToken;
390
+ }
391
+ if (options.listSessions) {
392
+ await listSessions(options, wsUrl);
393
+ return;
394
+ }
395
+ if (options.disconnectWriterTarget) {
396
+ await disconnectWriter(options, wsUrl);
397
+ return;
398
+ }
399
+ if (options.killSessionTarget) {
400
+ await killSession(options, wsUrl);
401
+ return;
402
+ }
403
+ const args = buildArguments(options, initArguments);
404
+ writeStatus(`[gotty] connecting to\n ${wsUrl}`);
405
+ const ws = new WebSocket(wsUrl, "webtty");
406
+ let pingTimer = null;
407
+ let closed = false;
408
+ let disconnectedReported = false;
409
+ let rawEnabled = false;
410
+ let writable = false;
411
+ let accessRole = "";
412
+ let fallbackInputActive = false;
413
+ let fallbackProbe = "";
414
+ let fallbackOutputTail = "";
415
+ let viewerInputActive = false;
416
+ let sessionPid = "(unknown)";
417
+
418
+ const normalizeEcho = (value) => String(value)
419
+ .replaceAll("\r", "")
420
+ .replace(/\n+$/g, "");
421
+
422
+ const handleInput = (chunk) => {
423
+ if (!writable || ws.readyState !== WebSocket.OPEN) {
424
+ return;
425
+ }
426
+ ws.send(MSG_INPUT + Buffer.from(chunk).toString("base64"));
427
+ };
428
+
429
+ const handleResize = () => {
430
+ if (writable && ws.readyState === WebSocket.OPEN) {
431
+ sendResize(ws, options);
432
+ }
433
+ };
434
+
435
+ const exitClient = (code = 0) => {
436
+ cleanup();
437
+ reportDisconnected();
438
+ ws.close();
439
+ process.exit(code);
440
+ };
441
+
442
+ const handleViewerInput = (chunk) => {
443
+ for (const byte of Buffer.from(chunk)) {
444
+ if (byte === 0x03) {
445
+ exitClient(130);
446
+ }
447
+ if (byte === 0x04 || byte === 0x11) {
448
+ exitClient(0);
449
+ }
450
+ }
451
+ };
452
+
453
+ const stopViewerInput = () => {
454
+ if (!viewerInputActive) {
455
+ return;
456
+ }
457
+ viewerInputActive = false;
458
+ process.stdin.removeListener("data", handleViewerInput);
459
+ };
460
+
461
+ const startViewerInput = () => {
462
+ if (viewerInputActive) {
463
+ return;
464
+ }
465
+ stopFallbackInput();
466
+ process.stdin.removeListener("data", handleInput);
467
+ process.stdout.removeListener("resize", handleResize);
468
+ viewerInputActive = true;
469
+ process.stdin.on("data", handleViewerInput);
470
+ process.stdin.resume();
471
+ setRawMode(true);
472
+ rawEnabled = process.stdin.isTTY;
473
+ };
474
+
475
+ const stopFallbackInput = () => {
476
+ if (!fallbackInputActive) {
477
+ return;
478
+ }
479
+ fallbackInputActive = false;
480
+ process.stdin.removeListener("data", handleFallbackInput);
481
+ };
482
+
483
+ const handleFallbackInput = (chunk) => {
484
+ if (
485
+ options.readonly ||
486
+ accessRole === "viewer" ||
487
+ ws.readyState !== WebSocket.OPEN
488
+ ) {
489
+ return;
490
+ }
491
+
492
+ const input = Buffer.from(chunk);
493
+ fallbackProbe = normalizeEcho(input.toString("utf8"));
494
+ ws.send(MSG_INPUT + input.toString("base64"));
495
+ stopFallbackInput();
496
+ };
497
+
498
+ const startFallbackInput = () => {
499
+ if (options.readonly || writable || accessRole === "viewer" || fallbackInputActive) {
500
+ return;
501
+ }
502
+ fallbackInputActive = true;
503
+ process.stdin.on("data", handleFallbackInput);
504
+ process.stdin.resume();
505
+ };
506
+
507
+ const setWritable = (enabled) => {
508
+ const nextWritable = enabled && !options.readonly;
509
+ stopFallbackInput();
510
+ stopViewerInput();
511
+ fallbackProbe = "";
512
+ fallbackOutputTail = "";
513
+
514
+ if (writable === nextWritable) {
515
+ return;
516
+ }
517
+ writable = nextWritable;
518
+
519
+ if (writable) {
520
+ process.stdin.on("data", handleInput);
521
+ process.stdout.on("resize", handleResize);
522
+ process.stdin.resume();
523
+ setRawMode(true);
524
+ rawEnabled = process.stdin.isTTY;
525
+ sendResize(ws, options);
526
+ return;
527
+ }
528
+
529
+ process.stdin.removeListener("data", handleInput);
530
+ process.stdout.removeListener("resize", handleResize);
531
+ };
532
+
533
+ const reportDisconnected = () => {
534
+ if (disconnectedReported) {
535
+ return;
536
+ }
537
+ disconnectedReported = true;
538
+ writeStatus(`
539
+ [gotty] disconnected from
540
+ ${wsUrl}
541
+ reconnect token:
542
+ ${options.reconnectToken || "(unknown)"}
543
+ pid:
544
+ ${sessionPid}`);
545
+ };
546
+
547
+ const cleanup = () => {
548
+ if (closed) {
549
+ return;
550
+ }
551
+ closed = true;
552
+ if (pingTimer) {
553
+ clearInterval(pingTimer);
554
+ pingTimer = null;
555
+ }
556
+ setWritable(false);
557
+ stopFallbackInput();
558
+ stopViewerInput();
559
+ if (rawEnabled) {
560
+ setRawMode(false);
561
+ rawEnabled = false;
562
+ }
563
+ process.stdin.pause();
564
+ };
565
+
566
+ ws.on("open", () => {
567
+ ws.send(JSON.stringify({
568
+ Arguments: args,
569
+ AuthToken: options.credential,
570
+ ReconnectToken: options.reconnectToken,
571
+ ReadOnly: options.readonly
572
+ }));
573
+ ws.send(MSG_SET_ENCODING + "base64");
574
+ if (options.readonly) {
575
+ startViewerInput();
576
+ } else {
577
+ startFallbackInput();
578
+ }
579
+
580
+ pingTimer = setInterval(() => {
581
+ if (ws.readyState === WebSocket.OPEN) {
582
+ ws.send(MSG_PING);
583
+ }
584
+ }, 30000);
585
+ });
586
+
587
+ ws.on("message", (data) => {
588
+ const text = Buffer.isBuffer(data) ? data.toString("utf8") : String(data);
589
+ if (!text) {
590
+ return;
591
+ }
592
+
593
+ const type = text[0];
594
+ const payload = text.slice(1);
595
+
596
+ switch (type) {
597
+ case MSG_OUTPUT:
598
+ {
599
+ const output = Buffer.from(payload, "base64");
600
+ process.stdout.write(output);
601
+ if (fallbackProbe && accessRole === "") {
602
+ fallbackOutputTail = normalizeEcho(
603
+ `${fallbackOutputTail}${output.toString("utf8")}`
604
+ ).slice(-8192);
605
+ }
606
+ if (fallbackProbe && accessRole === "" && fallbackOutputTail.includes(fallbackProbe)) {
607
+ setWritable(true);
608
+ accessRole = "writer";
609
+ writeStatus("[gotty] access:\n writer (read/write, inferred)");
610
+ }
611
+ }
612
+ break;
613
+ case MSG_PONG:
614
+ case MSG_SET_PREFERENCES:
615
+ case MSG_SET_BUFFER_SIZE:
616
+ break;
617
+ case MSG_SET_WINDOW_TITLE:
618
+ if (process.stdout.isTTY && payload) {
619
+ process.stdout.write(`\u001b]0;${payload}\u0007`);
620
+ }
621
+ break;
622
+ case MSG_SET_RECONNECT: {
623
+ try {
624
+ const reconnect = JSON.parse(payload);
625
+ if (reconnect && typeof reconnect === "object" && typeof reconnect.token === "string") {
626
+ options.reconnectToken = reconnect.token;
627
+ const pid = Number.isInteger(reconnect.pid) || typeof reconnect.pid === "string"
628
+ ? String(reconnect.pid)
629
+ : "(unknown)";
630
+ sessionPid = pid;
631
+ writeStatus(`
632
+ [gotty] session:
633
+ reconnect token:
634
+ ${reconnect.token}
635
+ pid:
636
+ ${pid}`);
637
+ }
638
+ } catch {}
639
+ break;
640
+ }
641
+ case MSG_SET_ROLE: {
642
+ try {
643
+ const status = JSON.parse(payload);
644
+ const canWrite = status?.role === "writer" && status?.writable === true;
645
+ const nextRole = canWrite ? "writer" : "viewer";
646
+ const previousRole = accessRole;
647
+ accessRole = nextRole;
648
+ setWritable(canWrite);
649
+ if (!canWrite) {
650
+ startViewerInput();
651
+ }
652
+ if (previousRole !== nextRole) {
653
+ writeStatus(`[gotty] access:\n ${canWrite ? "writer (read/write)" : "viewer (read-only)"}`);
654
+ if (!canWrite) {
655
+ writeStatus("[gotty] Exit by Ctrl+C/D/Q");
656
+ }
657
+ }
658
+ } catch {}
659
+ break;
660
+ }
661
+ default:
662
+ break;
663
+ }
664
+ });
665
+
666
+ ws.on("close", (code, reason) => {
667
+ cleanup();
668
+ reportDisconnected();
669
+ if (code !== 1000 && code !== 1005) {
670
+ const suffix = reason?.length ? `: ${reason.toString()}` : "";
671
+ writeStatus(`[gotty] websocket closed (${code})${suffix}`);
672
+ process.exitCode = 1;
673
+ }
674
+ });
675
+
676
+ ws.on("error", (error) => {
677
+ cleanup();
678
+ writeStatus(`[gotty] websocket error: ${error.message}`);
679
+ process.exitCode = 1;
680
+ });
681
+
682
+ process.on("SIGINT", () => {
683
+ exitClient(130);
684
+ });
685
+
686
+ process.on("SIGTERM", () => {
687
+ exitClient(143);
688
+ });
689
+ }
690
+
691
+ main().catch((error) => {
692
+ console.error(`client.mjs: ${error.message}`);
693
+ process.exitCode = 1;
694
+ });