forked from pingdotgg/t3code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtunnel.ts
More file actions
1600 lines (1509 loc) · 52.6 KB
/
Copy pathtunnel.ts
File metadata and controls
1600 lines (1509 loc) · 52.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type {
DesktopSshEnvironmentBootstrap,
DesktopSshEnvironmentTarget,
} from "@t3tools/contracts";
import {
describeReadinessCause,
waitForHttpReady as waitForHttpReadyShared,
} from "@t3tools/shared/httpReadiness";
import * as NetService from "@t3tools/shared/Net";
import { extractJsonObject, fromLenientJson } from "@t3tools/shared/schemaJson";
import { satisfiesSemverRange } from "@t3tools/shared/semver";
import * as Context from "effect/Context";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import { HttpClient } from "effect/unstable/http";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import {
buildSshChildEnvironment,
type SshAuthOptions,
SshPasswordPrompt,
isSshAuthFailure,
} from "./auth.ts";
import {
baseSshArgs,
buildSshHostSpecEffect,
collectProcessOutput,
getLastNonEmptyOutputLine,
remoteStateKey,
resolveSshCommand,
resolveSshTarget,
runSshCommand,
targetConnectionKey,
} from "./command.ts";
import {
SshCommandError,
SshHttpBridgeError,
SshInvalidTargetError,
SshLaunchError,
SshPairingError,
SshPasswordPromptError,
SshReadinessError,
} from "./errors.ts";
export const DEFAULT_REMOTE_PORT = 3773;
const REMOTE_PORT_SCAN_WINDOW = 200;
const SSH_READY_TIMEOUT_MS = 20_000;
const SSH_READY_PROBE_TIMEOUT_MS = 1_000;
const TUNNEL_SHUTDOWN_TIMEOUT_MS = 2_000;
const REMOTE_READY_TIMEOUT_MS = 15_000;
const REMOTE_REUSE_READY_TIMEOUT_MS = 2_000;
export interface RemoteT3RunnerOptions {
readonly packageSpec?: string;
readonly nodeScriptPath?: string | null;
readonly nodeEngineRange?: string | null;
}
export interface SshEnvironmentManagerOptions {
readonly resolveCliPackageSpec?: () => string;
readonly resolveCliRunner?: Effect.Effect<RemoteT3RunnerOptions>;
}
interface SshTunnelEntry {
readonly key: string;
readonly target: DesktopSshEnvironmentTarget;
readonly remotePort: number;
readonly remoteServerKind: "external" | "managed" | null;
readonly localPort: number;
readonly httpBaseUrl: string;
readonly wsBaseUrl: string;
readonly process: ChildProcessSpawner.ChildProcessHandle;
readonly scope: Scope.Scope;
}
type SshEnvironmentEffectContext =
| ChildProcessSpawner.ChildProcessSpawner
| FileSystem.FileSystem
| Path.Path
| HttpClient.HttpClient
| NetService.NetService
| SshPasswordPrompt;
type SshEnvironmentEffectError =
| SshCommandError
| SshInvalidTargetError
| SshLaunchError
| SshPairingError
| SshReadinessError
| SshPasswordPromptError
| NetService.NetError;
function makeSshTunnelCancelledError(target: DesktopSshEnvironmentTarget): SshCommandError {
return new SshCommandError({
command: ["ssh"],
exitCode: null,
stderr: "",
message: `SSH environment connection was cancelled for ${target.alias || target.hostname}.`,
});
}
function sshTargetLogFields(target: DesktopSshEnvironmentTarget) {
return {
alias: target.alias,
hostname: target.hostname,
username: target.username,
port: target.port,
};
}
function sshRunnerLogFields(runner: RemoteT3RunnerOptions | undefined) {
if (runner?.nodeScriptPath?.trim()) {
return { runner: "node-script", nodeScriptPath: runner.nodeScriptPath.trim() };
}
if (runner?.packageSpec?.trim()) {
return { runner: "package", packageSpec: runner.packageSpec.trim() };
}
return { runner: "default" };
}
interface SshAuthOperationInput<T> {
readonly key: string;
readonly target: DesktopSshEnvironmentTarget;
readonly operation: (
authOptions: SshAuthOptions,
) => Effect.Effect<T, SshEnvironmentEffectError, SshEnvironmentEffectContext>;
}
interface SshAuthAttemptInput<T> extends SshAuthOperationInput<T> {
readonly promptCount: number;
readonly authSecret: string | null;
}
export interface SshEnvironmentManagerShape {
readonly ensureEnvironment: (
target: DesktopSshEnvironmentTarget,
options?: { readonly issuePairingToken?: boolean },
) => Effect.Effect<
DesktopSshEnvironmentBootstrap,
SshEnvironmentEffectError,
SshEnvironmentEffectContext
>;
readonly disconnectEnvironment: (
target: DesktopSshEnvironmentTarget,
) => Effect.Effect<void, SshEnvironmentEffectError, SshEnvironmentEffectContext>;
}
const RemoteLaunchResult = Schema.Struct({
remotePort: Schema.Number,
serverKind: Schema.optional(Schema.Literals(["external", "managed"])),
});
const RemotePairingResult = Schema.Struct({
credential: Schema.String,
});
const decodeRemoteLaunchResult = Schema.decodeEffect(fromLenientJson(RemoteLaunchResult));
const decodeRemotePairingResult = Schema.decodeEffect(fromLenientJson(RemotePairingResult));
const decodeRemoteJsonOutput = <A, E>(
stdout: string,
decode: (input: string) => Effect.Effect<A, E>,
): Effect.Effect<A, E> =>
decode(stdout).pipe(
Effect.catch((error) =>
Effect.gen(function* () {
const jsonObject = extractJsonObject(stdout);
if (jsonObject === stdout.trim()) {
return yield* Effect.fail(error);
}
const exit = yield* Effect.exit(decode(jsonObject));
if (Exit.isSuccess(exit)) {
return exit.value;
}
return yield* Effect.fail(error);
}),
),
);
const decodeRemoteLaunchOutput = (stdout: string) =>
decodeRemoteJsonOutput(stdout, decodeRemoteLaunchResult);
const decodeRemotePairingOutput = (stdout: string) =>
decodeRemoteJsonOutput(stdout, decodeRemotePairingResult);
const remoteNodeEngineCheckMain = function remoteNodeEngineCheckMain() {
const range = process.argv[2] || "";
const rawVersion =
process.versions && process.versions.node ? process.versions.node : process.version;
if (!satisfiesSemverRange(rawVersion, range)) {
process.stderr.write(
"Remote node " + rawVersion + " does not satisfy required range " + range + ".\n",
);
process.exit(1);
}
};
function buildRemoteNodeEngineCheckScript(): string {
return `${satisfiesSemverRange.toString()}
(${remoteNodeEngineCheckMain.toString()})();`;
}
export function normalizeSshErrorMessage(stderr: string, fallbackMessage: string): string {
const cleaned = stderr.trim();
return cleaned.length > 0 ? cleaned : fallbackMessage;
}
function stripTrailingNewlines(value: string): string {
return value.replace(/\n+$/u, "");
}
function shellSingleQuote(value: string): string {
return `'${value.replaceAll("'", "'\\''")}'`;
}
function applyScriptPlaceholders(
template: string,
replacements: Readonly<Record<string, string>>,
): string {
let result = template;
for (const [token, value] of Object.entries(replacements)) {
result = result.replaceAll(`@@${token}@@`, value);
}
return result;
}
// Re-exported from the shared HTTP readiness module so existing importers
// (notably tunnel.test.ts) keep resolving it from here.
export { describeReadinessCause };
export const REMOTE_PICK_PORT_SCRIPT = `const fs = require("node:fs");
const net = require("node:net");
const filePath = process.argv[2] ?? "";
const defaultPort = Number.parseInt(process.argv[3] ?? "", 10);
const scanWindow = Number.parseInt(process.argv[4] ?? "", 10);
const raw = fs.existsSync(filePath) ? fs.readFileSync(filePath, "utf8").trim() : "";
const preferred = Number.parseInt(raw, 10);
const start = Number.isInteger(preferred) ? preferred : defaultPort;
const end = start + scanWindow;
function tryPort(port) {
return new Promise((resolve) => {
const server = net.createServer();
server.unref();
server.once("error", () => resolve(false));
server.listen(port, "127.0.0.1", () => {
server.close((error) => resolve(error ? false : port));
});
});
}
(async () => {
for (let port = start; port < end; port += 1) {
const available = await tryPort(port);
if (available) {
process.stdout.write(String(port));
return;
}
}
process.exit(1);
})().catch(() => process.exit(1));
`;
export const REMOTE_WAIT_READY_SCRIPT = `const http = require("node:http");
const port = Number.parseInt(process.argv[2] ?? "", 10);
const timeoutMs = Number.parseInt(process.argv[3] ?? "", 10);
const probeTimeoutMs = Number.parseInt(process.argv[4] ?? "", 10);
if (!Number.isInteger(port) || !Number.isInteger(timeoutMs) || !Number.isInteger(probeTimeoutMs)) {
process.exit(1);
}
const deadline = Date.now() + timeoutMs;
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function probe() {
return new Promise((resolve) => {
const request = http.get(
{
hostname: "127.0.0.1",
port,
path: "/",
timeout: probeTimeoutMs,
},
(response) => {
response.resume();
response.once("end", () => {
resolve(response.statusCode >= 200 && response.statusCode < 300);
});
},
);
request.once("timeout", () => {
request.destroy();
resolve(false);
});
request.once("error", () => resolve(false));
});
}
(async () => {
while (Date.now() < deadline) {
if (await probe()) {
process.exit(0);
}
await sleep(100);
}
process.exit(1);
})().catch(() => process.exit(1));
`;
export const REMOTE_NODE_ENV_SCRIPT = `prepend_path_if_dir() {
if [ -d "$1" ]; then
case ":$PATH:" in
*":$1:"*) ;;
*) PATH="$1:$PATH" ;;
esac
fi
}
remote_node_satisfies_engine() {
T3_NODE_ENGINE_RANGE=@@T3_NODE_ENGINE_RANGE@@
if [ -z "$T3_NODE_ENGINE_RANGE" ]; then
return 0
fi
node - "$T3_NODE_ENGINE_RANGE" <<'NODE'
@@T3_NODE_ENGINE_CHECK_SCRIPT@@
NODE
}
ensure_remote_node_path() {
if command -v node >/dev/null 2>&1 && remote_node_satisfies_engine >/dev/null 2>&1; then
return 0
fi
prepend_path_if_dir "$HOME/.local/bin"
prepend_path_if_dir "$HOME/bin"
prepend_path_if_dir "/opt/homebrew/bin"
prepend_path_if_dir "/usr/local/bin"
prepend_path_if_dir "/usr/bin"
prepend_path_if_dir "/bin"
if [ -z "\${VOLTA_HOME:-}" ]; then
VOLTA_HOME="$HOME/.volta"
fi
export VOLTA_HOME
prepend_path_if_dir "$VOLTA_HOME/bin"
prepend_path_if_dir "$HOME/.asdf/shims"
prepend_path_if_dir "$HOME/.asdf/bin"
if [ ! -x "$HOME/.asdf/shims/node" ] && [ -s "$HOME/.asdf/asdf.sh" ]; then
# shellcheck disable=SC1090
. "$HOME/.asdf/asdf.sh"
fi
prepend_path_if_dir "$HOME/.local/share/mise/shims"
prepend_path_if_dir "$HOME/.mise/shims"
if ! command -v node >/dev/null 2>&1 && command -v mise >/dev/null 2>&1; then
eval "$(mise activate sh)" >/dev/null 2>&1 || true
fi
if [ -z "\${FNM_DIR:-}" ]; then
FNM_DIR="$HOME/.local/share/fnm"
fi
export FNM_DIR
prepend_path_if_dir "$FNM_DIR"
prepend_path_if_dir "$HOME/.fnm"
if ! command -v node >/dev/null 2>&1 && command -v fnm >/dev/null 2>&1; then
eval "$(fnm env --shell bash)" >/dev/null 2>&1 || true
fnm use --silent-if-unchanged >/dev/null 2>&1 || fnm use default >/dev/null 2>&1 || true
fi
prepend_path_if_dir "$HOME/.nodenv/bin"
prepend_path_if_dir "$HOME/.nodenv/shims"
if ! command -v node >/dev/null 2>&1 && command -v nodenv >/dev/null 2>&1; then
eval "$(nodenv init -)" >/dev/null 2>&1 || true
fi
if [ -z "\${NVM_DIR:-}" ]; then
NVM_DIR="$HOME/.nvm"
fi
export NVM_DIR
if [ -s "$NVM_DIR/nvm.sh" ]; then
# shellcheck disable=SC1090
. "$NVM_DIR/nvm.sh"
if ! command -v node >/dev/null 2>&1 && command -v nvm >/dev/null 2>&1; then
nvm use --silent default >/dev/null 2>&1 || nvm use --silent node >/dev/null 2>&1 || nvm use --silent --lts >/dev/null 2>&1 || true
fi
fi
if ! command -v node >/dev/null 2>&1 && [ -d "$NVM_DIR/versions/node" ]; then
for T3_NODE_BIN in "$NVM_DIR"/versions/node/*/bin; do
if [ -x "$T3_NODE_BIN/node" ]; then
PATH="$T3_NODE_BIN:$PATH"
export PATH
fi
done
fi
command -v node >/dev/null 2>&1 && remote_node_satisfies_engine
}
`;
export const REMOTE_RUNNER_SCRIPT = `#!/bin/sh
set -eu
@@T3_NODE_ENV_SCRIPT@@
ensure_remote_node_path || true
T3_NODE_SCRIPT_PATH=@@T3_NODE_SCRIPT_PATH@@
if [ -n "$T3_NODE_SCRIPT_PATH" ]; then
if ! command -v node >/dev/null 2>&1; then
printf 'Remote host is missing node on PATH. Install Node or configure a supported version manager for non-interactive shells.\\n' >&2
exit 1
fi
exec node "$T3_NODE_SCRIPT_PATH" "$@"
fi
if command -v t3 >/dev/null 2>&1; then
exec t3 "$@"
fi
if command -v npx >/dev/null 2>&1; then
exec npx --yes @@T3_PACKAGE_SPEC@@ "$@"
fi
if command -v npm >/dev/null 2>&1; then
exec npm exec --yes @@T3_PACKAGE_SPEC@@ -- "$@"
fi
printf 'Remote host is missing the t3 CLI and could not install @@T3_PACKAGE_SPEC@@ because node/npm/npx are unavailable on PATH. Install Node or configure a supported version manager for non-interactive shells.\\n' >&2
exit 1
`;
export const REMOTE_LAUNCH_SCRIPT = `set -eu
@@T3_NODE_ENV_SCRIPT@@
STATE_KEY="$1"
STATE_DIR="$HOME/.t3/ssh-launch/$STATE_KEY"
DEFAULT_SERVER_HOME="$HOME/.t3"
DEFAULT_RUNTIME_FILE="$DEFAULT_SERVER_HOME/userdata/server-runtime.json"
PORT_FILE="$STATE_DIR/port"
PID_FILE="$STATE_DIR/pid"
MANAGED_FILE="$STATE_DIR/managed"
LOG_FILE="$STATE_DIR/server.log"
RUNNER_FILE="$STATE_DIR/run-t3.sh"
RUNNER_NEXT="$STATE_DIR/run-t3.next.$$"
mkdir -p "$STATE_DIR"
cleanup_runner_next() {
rm -f "$RUNNER_NEXT"
}
trap cleanup_runner_next EXIT
cat >"$RUNNER_NEXT" <<'SH'
@@T3_RUNNER_SCRIPT@@
SH
RUNNER_CHANGED=0
if [ ! -f "$RUNNER_FILE" ] || ! cmp -s "$RUNNER_NEXT" "$RUNNER_FILE"; then
RUNNER_CHANGED=1
fi
mv "$RUNNER_NEXT" "$RUNNER_FILE"
chmod 700 "$RUNNER_FILE"
if ! ensure_remote_node_path; then
printf 'Remote host is missing node on PATH. Install Node or configure a supported version manager for non-interactive shells.\\n' >&2
exit 1
fi
pick_port() {
node - "$PORT_FILE" "@@T3_DEFAULT_REMOTE_PORT@@" "@@T3_REMOTE_PORT_SCAN_WINDOW@@" <<'NODE'
@@T3_PICK_PORT_SCRIPT@@
NODE
}
wait_ready() {
node - "$REMOTE_PORT" "$1" "@@T3_READY_PROBE_TIMEOUT_MS@@" <<'NODE'
@@T3_WAIT_READY_SCRIPT@@
NODE
}
wait_for_pid_exit() {
PID_TO_WAIT="$1"
WAIT_COUNT=0
while kill -0 "$PID_TO_WAIT" 2>/dev/null && [ "$WAIT_COUNT" -lt 20 ]; do
WAIT_COUNT=$((WAIT_COUNT + 1))
sleep 0.1
done
}
resolve_default_runtime_port() {
node - "$DEFAULT_RUNTIME_FILE" <<'NODE'
const fs = require("node:fs");
const runtimePath = process.argv[2] ?? "";
try {
const runtime = JSON.parse(fs.readFileSync(runtimePath, "utf8"));
const pid = Number(runtime.pid);
const port = Number(runtime.port);
if (!Number.isInteger(pid) || pid <= 0 || !Number.isInteger(port)) {
process.exit(1);
}
const origin = new URL(String(runtime.origin ?? ""));
if (origin.protocol !== "http:" || !["127.0.0.1", "localhost"].includes(origin.hostname)) {
process.exit(1);
}
process.kill(pid, 0);
process.stdout.write(\`\${pid} \${port}\`);
} catch {
process.exit(1);
}
NODE
}
REMOTE_PID="$(cat "$PID_FILE" 2>/dev/null || true)"
REMOTE_PORT="$(cat "$PORT_FILE" 2>/dev/null || true)"
REMOTE_MANAGED="$(cat "$MANAGED_FILE" 2>/dev/null || true)"
DEFAULT_RUNTIME_INFO="$(resolve_default_runtime_port 2>/dev/null || true)"
DEFAULT_RUNTIME_PID=""
DEFAULT_REMOTE_PORT=""
if [ -n "$DEFAULT_RUNTIME_INFO" ]; then
DEFAULT_RUNTIME_PID="\${DEFAULT_RUNTIME_INFO%% *}"
DEFAULT_REMOTE_PORT="\${DEFAULT_RUNTIME_INFO#* }"
fi
if [ -n "$DEFAULT_REMOTE_PORT" ]; then
REMOTE_PORT="$DEFAULT_REMOTE_PORT"
if wait_ready "@@T3_REUSE_READY_TIMEOUT_MS@@"; then
if [ "$REMOTE_MANAGED" = "managed" ]; then
PID_TO_STOP="\${REMOTE_PID:-$DEFAULT_RUNTIME_PID}"
if [ -n "$PID_TO_STOP" ] && kill -0 "$PID_TO_STOP" 2>/dev/null; then
kill "$PID_TO_STOP" 2>/dev/null || true
wait_for_pid_exit "$PID_TO_STOP"
fi
REMOTE_PID=""
REMOTE_PORT="$DEFAULT_REMOTE_PORT"
REMOTE_MANAGED="external"
rm -f "$PID_FILE"
printf '%s\\n' "$REMOTE_PORT" >"$PORT_FILE"
printf 'external\\n' >"$MANAGED_FILE"
else
printf '%s\\n' "$REMOTE_PORT" >"$PORT_FILE"
printf 'external\\n' >"$MANAGED_FILE"
REMOTE_PID=""
REMOTE_MANAGED="external"
fi
else
REMOTE_PID="$(cat "$PID_FILE" 2>/dev/null || true)"
REMOTE_PORT="$(cat "$PORT_FILE" 2>/dev/null || true)"
REMOTE_MANAGED="$(cat "$MANAGED_FILE" 2>/dev/null || true)"
fi
fi
if [ "$REMOTE_MANAGED" = "external" ]; then
if [ -z "$REMOTE_PORT" ] || ! wait_ready "@@T3_REUSE_READY_TIMEOUT_MS@@"; then
REMOTE_PID=""
REMOTE_PORT=""
REMOTE_MANAGED=""
fi
elif [ -n "$REMOTE_PID" ] && [ -n "$REMOTE_PORT" ] && kill -0 "$REMOTE_PID" 2>/dev/null; then
if [ "$RUNNER_CHANGED" -eq 1 ]; then
kill "$REMOTE_PID" 2>/dev/null || true
wait_for_pid_exit "$REMOTE_PID"
REMOTE_PID=""
REMOTE_PORT=""
REMOTE_MANAGED=""
elif ! wait_ready "@@T3_REUSE_READY_TIMEOUT_MS@@"; then
kill "$REMOTE_PID" 2>/dev/null || true
wait_for_pid_exit "$REMOTE_PID"
REMOTE_PID=""
REMOTE_PORT=""
REMOTE_MANAGED=""
fi
else
REMOTE_PID=""
REMOTE_PORT=""
REMOTE_MANAGED=""
fi
if [ -z "$REMOTE_PORT" ]; then
REMOTE_PORT="$(pick_port)" || true
if [ -z "$REMOTE_PORT" ]; then
printf 'Failed to find an available port on the remote host. Ensure node is available on PATH.\\n' >&2
exit 1
fi
nohup env T3CODE_NO_BROWSER=1 "$RUNNER_FILE" serve --host 127.0.0.1 --port "$REMOTE_PORT" --base-dir "$DEFAULT_SERVER_HOME" >>"$LOG_FILE" 2>&1 < /dev/null &
REMOTE_PID="$!"
printf '%s\\n' "$REMOTE_PID" >"$PID_FILE"
printf '%s\\n' "$REMOTE_PORT" >"$PORT_FILE"
printf 'managed\\n' >"$MANAGED_FILE"
if ! wait_ready "@@T3_READY_TIMEOUT_MS@@"; then
printf 'Remote T3 server did not become ready on 127.0.0.1:%s.\\n' "$REMOTE_PORT" >&2
tail -n 80 "$LOG_FILE" >&2 2>/dev/null || true
kill "$REMOTE_PID" 2>/dev/null || true
wait_for_pid_exit "$REMOTE_PID"
rm -f "$PID_FILE" "$PORT_FILE" "$MANAGED_FILE"
exit 1
fi
fi
printf '{"remotePort":%s,"serverKind":"%s"}\\n' "$REMOTE_PORT" "\${REMOTE_MANAGED:-managed}"
`;
export const REMOTE_PAIRING_SCRIPT = `set -eu
STATE_DIR="$HOME/.t3/ssh-launch/@@T3_STATE_KEY@@"
DEFAULT_SERVER_HOME="$HOME/.t3"
RUNNER_FILE="$STATE_DIR/run-t3.sh"
mkdir -p "$STATE_DIR"
cat >"$RUNNER_FILE" <<'SH'
@@T3_RUNNER_SCRIPT@@
SH
chmod 700 "$RUNNER_FILE"
PAIRING_BASE_DIR="$DEFAULT_SERVER_HOME"
"$RUNNER_FILE" auth pairing create --base-dir "$PAIRING_BASE_DIR" --json
`;
export const REMOTE_STOP_SCRIPT = `set -eu
STATE_DIR="$HOME/.t3/ssh-launch/@@T3_STATE_KEY@@"
PID_FILE="$STATE_DIR/pid"
PORT_FILE="$STATE_DIR/port"
MANAGED_FILE="$STATE_DIR/managed"
REMOTE_MANAGED="$(cat "$MANAGED_FILE" 2>/dev/null || true)"
REMOTE_PID="$(cat "$PID_FILE" 2>/dev/null || true)"
if [ "$REMOTE_MANAGED" != "external" ] && [ -n "$REMOTE_PID" ] && kill -0 "$REMOTE_PID" 2>/dev/null; then
kill "$REMOTE_PID" 2>/dev/null || true
WAIT_COUNT=0
while kill -0 "$REMOTE_PID" 2>/dev/null && [ "$WAIT_COUNT" -lt 20 ]; do
WAIT_COUNT=$((WAIT_COUNT + 1))
sleep 0.1
done
fi
rm -f "$PID_FILE" "$PORT_FILE" "$MANAGED_FILE"
printf '{"stopped":true}\\n'
`;
const REMOTE_LOG_TAIL_SCRIPT = `set -eu
STATE_DIR="$HOME/.t3/ssh-launch/@@T3_STATE_KEY@@"
LOG_FILE="$STATE_DIR/server.log"
if [ -f "$LOG_FILE" ]; then
tail -n 80 "$LOG_FILE" 2>/dev/null || true
fi
`;
export function buildRemoteT3RunnerScript(input?: RemoteT3RunnerOptions): string {
const packageSpec = shellSingleQuote(input?.packageSpec?.trim() || "t3@latest");
const nodeScriptPath = input?.nodeScriptPath?.trim() || "";
return stripTrailingNewlines(
applyScriptPlaceholders(REMOTE_RUNNER_SCRIPT, {
T3_PACKAGE_SPEC: packageSpec,
T3_NODE_SCRIPT_PATH: shellSingleQuote(nodeScriptPath),
T3_NODE_ENV_SCRIPT: buildRemoteNodeEnvScript(input),
}),
);
}
export function buildRemoteNodeEnvScript(input?: RemoteT3RunnerOptions): string {
return stripTrailingNewlines(
applyScriptPlaceholders(REMOTE_NODE_ENV_SCRIPT, {
T3_NODE_ENGINE_RANGE: shellSingleQuote(input?.nodeEngineRange?.trim() || ""),
T3_NODE_ENGINE_CHECK_SCRIPT: stripTrailingNewlines(buildRemoteNodeEngineCheckScript()),
}),
);
}
export function buildRemoteLaunchScript(input?: RemoteT3RunnerOptions): string {
return applyScriptPlaceholders(REMOTE_LAUNCH_SCRIPT, {
T3_NODE_ENV_SCRIPT: buildRemoteNodeEnvScript(input),
T3_RUNNER_SCRIPT: stripTrailingNewlines(buildRemoteT3RunnerScript(input)),
T3_PICK_PORT_SCRIPT: stripTrailingNewlines(REMOTE_PICK_PORT_SCRIPT),
T3_WAIT_READY_SCRIPT: stripTrailingNewlines(REMOTE_WAIT_READY_SCRIPT),
T3_DEFAULT_REMOTE_PORT: String(DEFAULT_REMOTE_PORT),
T3_REMOTE_PORT_SCAN_WINDOW: String(REMOTE_PORT_SCAN_WINDOW),
T3_READY_TIMEOUT_MS: String(REMOTE_READY_TIMEOUT_MS),
T3_REUSE_READY_TIMEOUT_MS: String(REMOTE_REUSE_READY_TIMEOUT_MS),
T3_READY_PROBE_TIMEOUT_MS: String(SSH_READY_PROBE_TIMEOUT_MS),
});
}
export function buildRemotePairingScript(
target: DesktopSshEnvironmentTarget,
input?: RemoteT3RunnerOptions,
): string {
return applyScriptPlaceholders(REMOTE_PAIRING_SCRIPT, {
T3_STATE_KEY: remoteStateKey(target),
T3_RUNNER_SCRIPT: stripTrailingNewlines(buildRemoteT3RunnerScript(input)),
});
}
export function buildRemoteStopScript(target: DesktopSshEnvironmentTarget): string {
return applyScriptPlaceholders(REMOTE_STOP_SCRIPT, {
T3_STATE_KEY: remoteStateKey(target),
});
}
function buildRemoteLogTailScript(target: DesktopSshEnvironmentTarget): string {
return applyScriptPlaceholders(REMOTE_LOG_TAIL_SCRIPT, {
T3_STATE_KEY: remoteStateKey(target),
});
}
export const launchOrReuseRemoteServer = Effect.fn("ssh/tunnel.launchOrReuseRemoteServer")(
function* (
target: DesktopSshEnvironmentTarget,
input?: SshAuthOptions,
runner?: RemoteT3RunnerOptions,
): Effect.fn.Return<
{ readonly remotePort: number; readonly remoteServerKind: "external" | "managed" | null },
SshCommandError | SshInvalidTargetError | SshLaunchError,
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
> {
yield* Effect.logInfo("ssh.remoteServer.launch.start", {
...sshTargetLogFields(target),
...sshRunnerLogFields(runner),
stateKey: remoteStateKey(target),
});
const result = yield* runSshCommand(target, {
remoteCommandArgs: ["sh", "-s", "--", remoteStateKey(target)],
stdin: buildRemoteLaunchScript(runner),
...(input?.authSecret === undefined ? {} : { authSecret: input.authSecret }),
...(input?.batchMode === undefined ? {} : { batchMode: input.batchMode }),
...(input?.interactiveAuth === undefined ? {} : { interactiveAuth: input.interactiveAuth }),
});
if (!getLastNonEmptyOutputLine(result.stdout)) {
return yield* new SshLaunchError({
message: "SSH launch did not return a remote port.",
stdout: result.stdout,
});
}
const parsed = yield* decodeRemoteLaunchOutput(result.stdout).pipe(
Effect.mapError(
(cause) =>
new SshLaunchError({
message: "SSH launch returned unparseable output.",
stdout: result.stdout,
cause,
}),
),
);
if (!Number.isInteger(parsed.remotePort)) {
return yield* new SshLaunchError({
message: `SSH launch returned an invalid remote port: ${String(parsed.remotePort)}.`,
stdout: result.stdout,
});
}
yield* Effect.logInfo("ssh.remoteServer.launch.ready", {
...sshTargetLogFields(target),
remotePort: parsed.remotePort,
remoteServerKind: parsed.serverKind ?? null,
stateKey: remoteStateKey(target),
});
return {
remotePort: parsed.remotePort,
remoteServerKind: parsed.serverKind ?? null,
};
},
);
export const issueRemotePairingToken = Effect.fn("ssh/tunnel.issueRemotePairingToken")(function* (
target: DesktopSshEnvironmentTarget,
input?: SshAuthOptions,
runner?: RemoteT3RunnerOptions,
): Effect.fn.Return<
{
readonly credential: string;
},
SshCommandError | SshInvalidTargetError | SshPairingError,
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
> {
yield* Effect.logDebug("ssh.remoteServer.pairingToken.start", {
...sshTargetLogFields(target),
stateKey: remoteStateKey(target),
});
const result = yield* runSshCommand(target, {
remoteCommandArgs: ["sh", "-s"],
stdin: buildRemotePairingScript(target, runner),
...(input?.authSecret === undefined ? {} : { authSecret: input.authSecret }),
...(input?.batchMode === undefined ? {} : { batchMode: input.batchMode }),
...(input?.interactiveAuth === undefined ? {} : { interactiveAuth: input.interactiveAuth }),
});
if (!getLastNonEmptyOutputLine(result.stdout)) {
return yield* new SshPairingError({
message: "SSH pairing did not return a credential.",
stdout: result.stdout,
});
}
const parsed = yield* decodeRemotePairingOutput(result.stdout).pipe(
Effect.mapError(
(cause) =>
new SshPairingError({
message: "SSH pairing returned unparseable output.",
stdout: result.stdout,
cause,
}),
),
);
if (parsed.credential.trim().length === 0) {
return yield* new SshPairingError({
message: "SSH pairing command returned an invalid credential.",
stdout: result.stdout,
});
}
yield* Effect.logDebug("ssh.remoteServer.pairingToken.created", {
...sshTargetLogFields(target),
stateKey: remoteStateKey(target),
});
return {
credential: parsed.credential,
};
});
export const stopRemoteServer = Effect.fn("ssh/tunnel.stopRemoteServer")(function* (
target: DesktopSshEnvironmentTarget,
input?: SshAuthOptions,
): Effect.fn.Return<
void,
SshCommandError | SshInvalidTargetError,
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
> {
yield* Effect.logInfo("ssh.remoteServer.stop.start", {
...sshTargetLogFields(target),
stateKey: remoteStateKey(target),
});
yield* runSshCommand(target, {
remoteCommandArgs: ["sh", "-s"],
stdin: buildRemoteStopScript(target),
...(input?.authSecret === undefined ? {} : { authSecret: input.authSecret }),
...(input?.batchMode === undefined ? {} : { batchMode: input.batchMode }),
...(input?.interactiveAuth === undefined ? {} : { interactiveAuth: input.interactiveAuth }),
});
yield* Effect.logInfo("ssh.remoteServer.stop.succeeded", {
...sshTargetLogFields(target),
stateKey: remoteStateKey(target),
});
});
const readRemoteServerLogTail = Effect.fn("ssh/tunnel.readRemoteServerLogTail")(function* (
target: DesktopSshEnvironmentTarget,
input?: SshAuthOptions,
): Effect.fn.Return<
string,
SshCommandError | SshInvalidTargetError,
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
> {
const result = yield* runSshCommand(target, {
remoteCommandArgs: ["sh", "-s"],
stdin: buildRemoteLogTailScript(target),
timeoutMs: 10_000,
...(input?.authSecret === undefined ? {} : { authSecret: input.authSecret }),
...(input?.batchMode === undefined ? {} : { batchMode: input.batchMode }),
...(input?.interactiveAuth === undefined ? {} : { interactiveAuth: input.interactiveAuth }),
});
return result.stdout.trim();
});
export const waitForHttpReady = (input: {
readonly baseUrl: string;
readonly timeoutMs?: number;
readonly intervalMs?: number;
readonly probeTimeoutMs?: number;
readonly path?: string;
}): Effect.Effect<void, SshReadinessError, HttpClient.HttpClient> =>
waitForHttpReadyShared({
baseUrl: input.baseUrl,
...(input.path === undefined ? {} : { path: input.path }),
...(input.timeoutMs === undefined ? {} : { timeoutMs: input.timeoutMs }),
...(input.intervalMs === undefined ? {} : { intervalMs: input.intervalMs }),
probeTimeoutMs: input.probeTimeoutMs ?? SSH_READY_PROBE_TIMEOUT_MS,
makeError: ({ requestUrl, probeTimeoutMs, cause }) => {
if (typeof cause === "object" && cause !== null && "kind" in cause) {
const kind = (cause as { readonly kind?: unknown }).kind;
if (kind === "probe-timeout") {
return new SshReadinessError({
message: `Backend readiness probe exceeded ${probeTimeoutMs}ms at ${requestUrl}.`,
cause,
});
}
if (kind === "overall-timeout") {
const overall = cause as unknown as {
readonly baseUrl: string;
readonly timeoutMs: number;
readonly lastFailure: unknown;
};
return new SshReadinessError({
message: `Timed out waiting ${overall.timeoutMs}ms for backend readiness at ${overall.baseUrl}.`,
cause: overall.lastFailure,
});
}
}
return new SshReadinessError({
message: `Backend readiness probe failed at ${requestUrl}.`,
cause,
});
},
});
function isLoopbackHostname(hostname: string): boolean {
const normalized = hostname
.trim()
.toLowerCase()
.replace(/^\[(.*)\]$/, "$1");
return normalized === "127.0.0.1" || normalized === "::1" || normalized === "localhost";
}
export const resolveLoopbackSshHttpBaseUrl = Effect.fn("ssh/tunnel.resolveLoopbackSshHttpBaseUrl")(
function* (rawHttpBaseUrl: unknown): Effect.fn.Return<string, SshHttpBridgeError> {
return yield* Effect.try({
try: () => {
if (typeof rawHttpBaseUrl !== "string" || rawHttpBaseUrl.trim().length === 0) {
throw new Error("Invalid SSH forwarded http base URL.");
}
const baseUrl = new URL(rawHttpBaseUrl);
if (!isLoopbackHostname(baseUrl.hostname)) {
throw new Error("SSH desktop bridge only supports loopback forwarded URLs.");
}
return baseUrl.toString();
},
catch: (cause) =>
new SshHttpBridgeError({
message: cause instanceof Error ? cause.message : "Invalid SSH forwarded http base URL.",
cause,
}),
});
},
);
const reserveLocalTunnelPort = Effect.fn("ssh/tunnel.reserveLocalTunnelPort")(function* () {
const net = yield* NetService.NetService;
return yield* net.reserveLoopbackPort();
});
const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input: {
readonly key: string;
readonly resolvedTarget: DesktopSshEnvironmentTarget;
readonly remotePort: number;
readonly localPort: number;
readonly httpBaseUrl: string;
readonly wsBaseUrl: string;
readonly authOptions: SshAuthOptions;
readonly remoteServerKind: "external" | "managed" | null;
}): Effect.fn.Return<
SshTunnelEntry,
SshCommandError | SshInvalidTargetError | SshReadinessError,
| ChildProcessSpawner.ChildProcessSpawner
| FileSystem.FileSystem
| Path.Path
| HttpClient.HttpClient
| NetService.NetService
| Scope.Scope
> {
const hostSpec = yield* buildSshHostSpecEffect(input.resolvedTarget);
const childEnvironment = yield* buildSshChildEnvironment({
...(input.authOptions.authSecret === undefined
? {}
: { authSecret: input.authOptions.authSecret }),
...(input.authOptions.interactiveAuth === undefined
? {}
: { interactiveAuth: input.authOptions.interactiveAuth }),
}).pipe(
Effect.mapError(
(cause) =>
new SshCommandError({
command: ["ssh"],
exitCode: null,
stderr: "",
message: "Failed to prepare SSH authentication helpers.",
cause,
}),
),
);
const args = [
...baseSshArgs(input.resolvedTarget, {
batchMode: input.authOptions.batchMode ?? "no",
}),
"-o",
"ExitOnForwardFailure=yes",
"-o",
"ServerAliveInterval=15",
"-o",
"ServerAliveCountMax=3",
"-n",
"-N",
"-L",
`${input.localPort}:127.0.0.1:${input.remotePort}`,
hostSpec,
];
const sshCommand = yield* resolveSshCommand;
const tunnelCommand = [sshCommand, ...args];
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const scope = yield* Scope.Scope;
yield* Effect.logDebug("ssh.tunnel.spawn.start", {
...sshTargetLogFields(input.resolvedTarget),
command: tunnelCommand,
localPort: input.localPort,
remotePort: input.remotePort,
remoteServerKind: input.remoteServerKind,
httpBaseUrl: input.httpBaseUrl,
});
const child = yield* spawner
.spawn(
ChildProcess.make(sshCommand, args, {
env: childEnvironment,
extendEnv: true,
stdin: {
stream: Stream.empty,
endOnDone: true,
},
}),
)
.pipe(
Effect.mapError(
(cause) =>