-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver.ts
More file actions
1678 lines (1575 loc) · 62.7 KB
/
Copy pathserver.ts
File metadata and controls
1678 lines (1575 loc) · 62.7 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 * as net from "node:net";
import * as fs from "node:fs";
import * as path from "node:path";
import { execFileSync } from "node:child_process";
import { randomBytes } from "node:crypto";
import * as pty from "node-pty";
// @xterm/headless is CJS-only, so keep its default import. The serialize addon
// ships native ESM with named exports, so import its runtime namespace.
import type { Terminal } from "@xterm/headless";
import type { SerializeAddon } from "@xterm/addon-serialize";
import xterm from "@xterm/headless";
import * as xtermSerialize from "@xterm/addon-serialize";
import {
MessageType,
PacketReader,
encodeData,
encodeExit,
encodeScreen,
encodeStatusResponse,
encodeActivity,
encodeGuardedData,
encodeGeometry,
decodeSize,
} from "./protocol.ts";
import { ActivityLease, parseActivityCommand } from "./activity.ts";
import {
parseGuardedSendCommand,
type GuardedSendResponse,
} from "./guarded-send.ts";
import {
getSocketPath,
getPidPath,
getMetadataPath,
getSessionDir,
ensureSessionDir,
cleanupOwnedSocket,
cleanupOwnedAll,
writeMetadata,
readMetadata,
mutateMetadataUnderLock,
shouldReapAtExit,
reapOnExitDefault,
type SessionMetadata,
type MetadataMutationResult,
} from "./sessions.ts";
import { EventWriter, clearEvents, EventType, type EventRecord } from "./events.ts";
import {
RECOVERY_PROTOCOL,
assertPrivateRecoveryPaths,
atomicWritePrivate,
ensureRecoveryDir,
launchIdentity,
metadataRevision,
publishPrivateNoReplace,
readBoundedJson,
readProcessStartToken,
recoveryDir,
recoveryLockContents,
recoveryLockIdentity,
recoveryRequestPath,
recoveryRevisionPath,
recoveryResultPath,
signRecoveryRevision,
signRecoveryResult,
stampRecoveryMetadata,
verifyRecoveryRequest,
verifyRecoveryRevision,
type RecoveryCapability,
type RecoveryRequest,
type RecoveryRevision,
type RecoveryResultPayload,
} from "./recovery.ts";
import type { StatsResult } from "./client.ts";
interface Client {
socket: net.Socket;
reader: PacketReader;
rows: number;
cols: number;
readonly: boolean;
attachSeq: number;
/** DATA/EXIT must not overtake the SCREEN baseline for ATTACH or PEEK. */
initialScreenPhase: "live" | "settling" | "cutting";
/** Invalidates a delayed SCREEN when the same socket changes attach mode. */
initialScreenGeneration: number;
postCutPackets: Array<{
type: typeof MessageType.DATA | typeof MessageType.EXIT;
packet: Buffer;
}>;
}
export interface ServerOptions {
name: string;
generation?: string;
command: string;
args: string[];
displayCommand: string;
cwd: string;
rows: number;
cols: number;
ephemeral?: boolean;
tags?: Record<string, string>;
/** Optional human-friendly alias recorded in SessionMetadata.displayName.
* Mutable via `pty rename`; `name` stays the immutable stable id. */
displayName?: string;
onExit?: (code: number) => void;
/** When true, spawn the child with a scrubbed environment containing only
* a small allow-list of variables (plus any entries in `extraEnv`).
* Intended for contexts where the daemon may have inherited secrets that
* shouldn't leak into the session (e.g., a daemon launched by pty-relay
* for a remote client). See BUG-4. */
isolateEnv?: boolean;
/** Additional `KEY=VALUE` env entries overlaid on the inherited child
* environment, or on the safe allow-list when `isolateEnv` is true. */
extraEnv?: Record<string, string>;
/** Environment keys removed from the inherited child environment. Applied
* before `extraEnv`, so an explicit assignment wins when both mention a key. */
unsetEnv?: string[];
/** Use this env dict verbatim for the spawned child — no inheritance from
* the daemon's `process.env`, no allow-list. `PTY_SESSION` and the opaque
* `PTY_SESSION_GENERATION` owner token are always injected on top so
* nesting detection and generation-safe `pty exec` keep working.
*
* Mutually exclusive with `isolateEnv` / `extraEnv` / `unsetEnv` — passing
* `env` together with inherited-environment policy throws. Use this when
* the caller wants total control of the child environment (e.g., a
* launcher shell that injects a shim tmux on `PATH`). */
env?: Record<string, string>;
}
/** Env variables that are safe to pass through to a session child when
* `isolateEnv` is on. Keeps terminal/locale/path functionality working
* without propagating the operator's shell secrets. */
const ISOLATED_ENV_ALLOWLIST = new Set([
"PATH", "HOME", "USER", "LOGNAME", "SHELL",
"TERM", "COLORTERM", "LANG", "TZ", "PWD", "TMPDIR",
// pty-internal
"PTY_ROOT",
"PTY_SESSION_DIR",
]);
/** Fallback TERM for child PTYs when no value was inherited. `xterm-256color`
* is the lowest common denominator every modern TUI knows how to drive; the
* kitty keyboard / modifyOtherKeys handshakes are dynamic CSI probes that
* work fine on top of it. Important specifically for daemons launched from
* a parent with a minimal env (launchd, systemd, cron, sparse CI runners) —
* those contexts drop TERM entirely, and a child without TERM causes many
* TUIs (Claude Code, vim, etc.) to fall back to legacy key encoding where
* Shift+Enter is indistinguishable from Enter. */
const DEFAULT_CHILD_TERM = "xterm-256color";
/** Apply the TERM default in-place after the env has been assembled. Never
* overrides an explicit value — only fills in when it's absent. */
function ensureChildTerm(env: Record<string, string>): void {
if (!env.TERM) env.TERM = DEFAULT_CHILD_TERM;
}
function buildChildEnv(options: ServerOptions): Record<string, string> {
// Mutual exclusion: `env` (explicit, verbatim) can't be combined with the
// inherited-environment policy path. If you want total control you pass
// `env`; otherwise isolation/removals/assignments compose explicitly. Picking
// one implicitly would hide intent.
if (options.env && (options.isolateEnv || options.extraEnv || options.unsetEnv?.length)) {
throw new Error(
"ServerOptions.env is mutually exclusive with isolateEnv/extraEnv/unsetEnv. " +
"Use env for verbatim control, or inherited environment policy options — not both."
);
}
// Explicit verbatim env. No inheritance. PTY's identity and owner token are
// forced on top so internal tooling can fail closed across same-id reuse.
if (options.env) {
const env = { ...options.env };
env.PTY_SESSION = options.name;
if (options.generation) env.PTY_SESSION_GENERATION = options.generation;
ensureChildTerm(env);
return env;
}
const source = process.env as Record<string, string>;
if (!options.isolateEnv) {
// Legacy behaviour: full inheritance, minus the server-config handoff.
const env = { ...source };
delete env.PTY_SERVER_CONFIG;
for (const key of options.unsetEnv ?? []) delete env[key];
if (options.extraEnv) {
for (const [k, v] of Object.entries(options.extraEnv)) env[k] = v;
}
env.PTY_SESSION = options.name;
if (options.generation) env.PTY_SESSION_GENERATION = options.generation;
ensureChildTerm(env);
return env;
}
const env: Record<string, string> = {};
for (const [k, v] of Object.entries(source)) {
if (v === undefined) continue;
if (ISOLATED_ENV_ALLOWLIST.has(k) || k.startsWith("LC_")) env[k] = v;
}
for (const key of options.unsetEnv ?? []) delete env[key];
if (options.extraEnv) {
for (const [k, v] of Object.entries(options.extraEnv)) env[k] = v;
}
env.PTY_SESSION = options.name;
if (options.generation) env.PTY_SESSION_GENERATION = options.generation;
ensureChildTerm(env);
return env;
}
const LAST_LINES_COUNT = 200;
export interface ProcessResources {
rssKb: number; // Resident set size in KB
cpuPercent: number; // CPU usage percentage
}
/** Query CPU and memory usage for a process via ps. Returns null on failure. */
function queryProcessResources(pid: number): ProcessResources | null {
try {
const output = execFileSync("ps", ["-o", "rss=,pcpu=", "-p", String(pid)], {
encoding: "utf-8",
timeout: 1000,
}).trim();
const parts = output.split(/\s+/);
if (parts.length < 2) return null;
return {
rssKb: parseInt(parts[0], 10),
cpuPercent: parseFloat(parts[1]),
};
} catch {
return null;
}
}
/** Validate that cwd is usable for spawning a process. Returns undefined if
* valid, or a descriptive error string explaining what's wrong. */
function describeInvalidCwd(cwd: string): string | undefined {
if (cwd.length === 0) return "Working directory is empty.";
let stats: fs.Stats;
try {
stats = fs.statSync(cwd);
} catch (err: any) {
if (err?.code === "ENOENT") {
return `Working directory does not exist: ${cwd}`;
}
return `Working directory is not accessible: ${cwd} (${err?.message ?? String(err)})`;
}
if (!stats.isDirectory()) {
return `Working directory is not a directory: ${cwd}`;
}
try {
fs.accessSync(cwd, fs.constants.X_OK);
} catch {
return `Working directory is not searchable: ${cwd}`;
}
return undefined;
}
/** Strip terminal query sequences that should not be forwarded to clients.
* Exported for unit testing. */
export function stripTerminalQueries(data: string): string {
return data
.replace(/\x1b\]1[01];\?\x07/g, "") // OSC 10/11 with BEL
.replace(/\x1b\]1[01];\?\x1b\\/g, "") // OSC 10/11 with ST
.replace(/\x1b\]4;\d+;\?\x07/g, "") // OSC 4 with BEL
.replace(/\x1b\]4;\d+;\?\x1b\\/g, "") // OSC 4 with ST
.replace(/\x1b\[c/g, "") // DA1
.replace(/\x1b\[>c/g, "") // DA2
.replace(/\x1b\[6n/g, "") // DSR cursor position
.replace(/\x1b\[>0q/g, ""); // XTVERSION
}
export class PtyServer {
private terminal: Terminal;
private serialize: SerializeAddon;
private ptyProcess: pty.IPty;
private socketServer: net.Server;
private retiredSocketServers: net.Server[] = [];
private clients = new Map<net.Socket, Client>();
private exited = false;
private exitCode = 0;
private name: string;
private options: ServerOptions;
private attachCounter = 0;
private sgrMouseMode = false;
private cursorHidden = false;
private kittyKeyboardStack: number[] = [];
// Alt-screen buffer state (DEC private modes ?1049 / ?1047 / ?47). Set when
// the child process enters the alternate screen buffer; cleared when it
// leaves. Replayed to attaching clients so the SCREEN snapshot lands in the
// right host-terminal buffer — without this, a TUI's alt-screen frames get
// painted into the host's main buffer, which under tmux means every frame
// enters scrollback (see #41).
private altScreenActive = false;
// Mouse tracking modes — these are separate DEC private modes (set/cleared
// independently by the child process) that control WHICH events the
// terminal should report. SGR mode (1006) only controls the ENCODING of
// reports, not whether tracking is active. Clients attaching to a session
// that's already mid-stream need all active modes replayed so their own
// mouse forwarding logic sees the correct state.
private mouseTracking1000 = false; // button press/release tracking
private mouseTracking1002 = false; // button-motion tracking
private mouseTracking1003 = false; // any-motion tracking
private lastResizeTime = 0;
private eventWriter: EventWriter;
private generation: string;
private ioRevision = 0;
private recoveryCapability: RecoveryCapability | null = null;
private recoveryRoot = "";
private recoveryInFlight = false;
private recoveryWatcher: fs.FSWatcher | null = null;
private lastTitle = "";
private activity: ActivityLease<net.Socket>;
readonly ready: Promise<void>;
// Resolves when the child process's onExit has fired — used by close() to
// make sure session_exit has been queued to the event chain before we
// flush and exit the daemon. See flake #2.
private childExited: Promise<void>;
private resolveChildExited!: () => void;
constructor(options: ServerOptions) {
this.name = options.name;
this.options = options;
this.generation = options.generation ?? randomBytes(16).toString("hex");
this.activity = new ActivityLease(this.generation);
this.eventWriter = new EventWriter(options.name);
this.childExited = new Promise<void>((resolve) => {
this.resolveChildExited = resolve;
});
// Set up xterm-headless for screen buffer tracking
this.terminal = new xterm.Terminal({
rows: options.rows,
cols: options.cols,
scrollback: 10000,
allowProposedApi: true,
});
this.serialize = new xtermSerialize.SerializeAddon();
this.terminal.loadAddon(this.serialize);
// Track terminal modes not exposed by xterm's serialize addon
this.terminal.parser.registerCsiHandler(
{ prefix: "?", final: "h" },
(params) => {
for (const p of params) {
const v = typeof p === "number" ? p : p[0];
if (v === 1006) this.sgrMouseMode = true;
if (v === 1000) this.mouseTracking1000 = true;
if (v === 1002) this.mouseTracking1002 = true;
if (v === 1003) this.mouseTracking1003 = true;
if (v === 1049 || v === 1047 || v === 47) this.altScreenActive = true;
if (v === 25) {
if (this.cursorHidden) this.emitEvent(EventType.CURSOR_VISIBLE);
this.cursorHidden = false;
}
if (v === 1004) this.emitEvent(EventType.FOCUS_REQUEST);
}
return false;
}
);
this.terminal.parser.registerCsiHandler(
{ prefix: "?", final: "l" },
(params) => {
for (const p of params) {
const v = typeof p === "number" ? p : p[0];
if (v === 1006) this.sgrMouseMode = false;
if (v === 1000) this.mouseTracking1000 = false;
if (v === 1002) this.mouseTracking1002 = false;
if (v === 1003) this.mouseTracking1003 = false;
if (v === 1049 || v === 1047 || v === 47) this.altScreenActive = false;
if (v === 25) this.cursorHidden = true;
}
return false;
}
);
this.terminal.parser.registerCsiHandler(
{ prefix: ">", final: "u" },
(params) => {
const flags = typeof params[0] === "number" ? params[0] : params[0][0];
this.kittyKeyboardStack.push(flags);
return false;
}
);
this.terminal.parser.registerCsiHandler(
{ prefix: "<", final: "u" },
() => {
this.kittyKeyboardStack.pop();
return false;
}
);
// Respond to DA1 (Primary Device Attribute) queries from the child process.
// Shells like fish 4.x send ESC[c at startup and block for up to 10s waiting
// for a response. Since xterm-headless doesn't reply, we intercept the query
// in the output stream and write a VT220 response back to the pty process.
this.terminal.parser.registerCsiHandler(
{ final: "c" },
(params) => {
if (params.length === 0 || params[0] === 0) {
this.writeToPty("\x1b[?62;22c");
}
return false;
}
);
// ── Event detection ──
this.terminal.onBell(() => {
this.emitEvent(EventType.BELL);
});
this.terminal.onTitleChange((title: string) => {
if (title !== this.lastTitle) {
this.lastTitle = title;
this.emitEvent(EventType.TITLE_CHANGE, { value: title });
}
});
// iTerm2 desktop notification (OSC 9)
this.terminal.parser.registerOscHandler(9, (data: string) => {
this.emitEvent(EventType.NOTIFICATION, { body: data, source: "osc9" });
return false;
});
// Kitty notification (OSC 99) — key=value;key=value payload
this.terminal.parser.registerOscHandler(99, (data: string) => {
const fields: Record<string, string> = {};
for (const part of data.split(";")) {
const eq = part.indexOf("=");
if (eq !== -1) {
fields[part.slice(0, eq)] = part.slice(eq + 1);
}
}
this.emitEvent(EventType.NOTIFICATION, {
title: fields["title"] ?? fields["t"],
body: fields["body"] ?? fields["b"],
source: "osc99",
});
return false;
});
// rxvt notification (OSC 777) — notify;title;body
this.terminal.parser.registerOscHandler(777, (data: string) => {
const parts = data.split(";");
if (parts[0] === "notify" && parts.length >= 2) {
this.emitEvent(EventType.NOTIFICATION, {
title: parts[1],
body: parts.slice(2).join(";"),
source: "osc777",
});
}
return false;
});
// ── Terminal query responses ──
// Programs send queries expecting the terminal to respond on stdin.
// xterm-headless doesn't answer, so the query leaks to the client's
// real terminal, whose response comes back as garbage input. We
// intercept common queries and respond directly to the PTY process.
// OSC 10: foreground color query (less, vim)
// Return true to consume the sequence so it doesn't leak to clients.
this.terminal.parser.registerOscHandler(10, (data: string) => {
if (data === "?") {
this.writeToPty("\x1b]10;rgb:c0c0/c0c0/c0c0\x1b\\");
return true; // consume — don't pass to client
}
return false;
});
// OSC 11: background color query (less, vim)
this.terminal.parser.registerOscHandler(11, (data: string) => {
if (data === "?") {
this.writeToPty("\x1b]11;rgb:0000/0000/0000\x1b\\");
return true;
}
return false;
});
// OSC 4: palette color query (vim, emacs)
this.terminal.parser.registerOscHandler(4, (data: string) => {
if (data.includes("?")) {
const idx = parseInt(data, 10);
if (!isNaN(idx)) {
this.writeToPty(`\x1b]4;${idx};rgb:0000/0000/0000\x1b\\`);
}
return true;
}
return false;
});
// DA2: secondary device attributes (vim, tmux)
this.terminal.parser.registerCsiHandler(
{ prefix: ">", final: "c" },
(_params) => {
// Respond as xterm version 382
this.writeToPty("\x1b[>0;382;0c");
return false;
}
);
// DSR: cursor position query (CSI 6 n, vim, readline)
this.terminal.parser.registerCsiHandler(
{ final: "n" },
(params) => {
if (params.length === 1 && params[0] === 6) {
const buf = this.terminal.buffer.active;
this.writeToPty(`\x1b[${buf.cursorY + 1};${buf.cursorX + 1}R`);
}
return false;
}
);
// XTVERSION: terminal version query (CSI > 0 q, vim)
this.terminal.parser.registerCsiHandler(
{ prefix: ">", final: "q" },
(_params) => {
this.writeToPty("\x1bP>|pty(0.8)\x1b\\");
return false;
}
);
// Spawn the child process in a PTY via a shell, so that shell scripts,
// symlinks, and shebangs all work reliably (like tmux/screen do).
// `exec "$@"` replaces the shell with the actual process.
const childEnv = buildChildEnv({ ...options, generation: this.generation });
const invalidCwd = describeInvalidCwd(options.cwd);
if (invalidCwd !== undefined) {
throw new Error(
`${invalidCwd}\nCannot start session "${options.name}" for command "${options.command}".`
);
}
try {
// NOTE: intentionally no `name:` option here — node-pty's `name`
// unconditionally clobbers env.TERM, which would hide any TERM the
// caller inherited or set explicitly. `buildChildEnv` guarantees
// childEnv.TERM is populated (defaulting to xterm-256color if absent),
// so node-pty will pick it up naturally. Was `name: "xterm-256color"`
// before; removing it lets inherited values like `xterm-kitty` flow
// through and lets TUIs negotiate the richer capabilities they allow.
this.ptyProcess = pty.spawn(
"/bin/sh",
["-c", 'exec "$@"', "sh", options.command, ...options.args],
{
cols: options.cols,
rows: options.rows,
cwd: options.cwd,
env: childEnv as Record<string, string>,
}
);
} catch (err: any) {
const msg = err?.message ?? String(err);
if (msg.includes("posix_spawnp") || msg.includes("spawn")) {
throw new Error(
`Failed to spawn PTY shell "/bin/sh" for command "${options.command}" in cwd "${options.cwd}": ${msg}`
);
}
throw err;
}
// Feed PTY output into xterm-headless and broadcast to clients.
// Query sequences (OSC 10/11, DA1, etc.) are intercepted by parser
// handlers above and must NOT be forwarded to clients — otherwise the
// client's terminal responds and its response appears as garbage input.
this.ptyProcess.onData((data: string) => {
this.bumpIoRevision();
this.terminal.write(data);
const cleaned = stripTerminalQueries(data);
if (cleaned.length > 0) {
this.broadcast(MessageType.DATA, encodeData(cleaned));
}
});
this.ptyProcess.onExit(({ exitCode, signal }) => {
this.exited = true;
this.bumpIoRevision();
// A signal death (e.g. an OS OOM SIGKILL) arrives from node-pty with a
// nonzero `signal` and often exitCode 0 — if we recorded only the raw
// exitCode, a killed process would look like a clean finish and any
// consumer gating on "nonzero exit" (convoy's crash→ding) would miss it.
// Surface it the way a shell does: 128 + signal (SIGKILL 9 → 137).
const code = signal ? 128 + signal : exitCode;
this.exitCode = code;
this.broadcast(MessageType.EXIT, encodeExit(code));
this.emitEvent(EventType.SESSION_EXIT, {
exitCode: code,
...(signal ? { signal } : {}),
});
// Save exit status immediately so the session shows as "exited"
// in pty list during the cleanup window. lastLines may be incomplete
// here since PTY data could still be in-flight — close() will
// update with the final output.
const exitMetadataStatus = this.saveExitMetadata(code);
if (exitMetadataStatus === "busy" || exitMetadataStatus === "stale") {
// Startup may still hold the creation lock for this generation. Retry
// within the existing 500ms client grace so exit metadata is observable
// before shutdown cleanup, while close() retains the final bounded retry.
void this.saveExitMetadataUntilSettled(code, 400).catch(() => {});
}
this.resolveChildExited();
options.onExit?.(code);
});
// Create Unix socket server
ensureSessionDir();
this.recoveryRoot = path.resolve(getSessionDir());
const processStartToken = readProcessStartToken(process.pid);
try {
ensureRecoveryDir(this.recoveryRoot);
const paths = assertPrivateRecoveryPaths(this.recoveryRoot);
if (processStartToken === null) throw new Error("process start identity unavailable");
const identity = launchIdentity({
command: options.command,
args: options.args,
displayCommand: options.displayCommand,
cwd: options.cwd,
rows: options.rows,
cols: options.cols,
ephemeral: options.ephemeral,
isolateEnv: options.isolateEnv,
extraEnv: options.extraEnv,
env: options.env,
});
this.recoveryCapability = {
protocol: RECOVERY_PROTOCOL,
secret: randomBytes(32).toString("hex"),
processStartToken,
launchIdentity: identity,
...paths,
metadataRevision: "",
};
this.startRecoveryWatcher();
} catch {}
clearEvents(this.name);
const socketPath = getSocketPath(this.name);
// Remove stale socket if it exists
try {
fs.unlinkSync(socketPath);
} catch {}
this.socketServer = net.createServer((socket) =>
this.handleClient(socket)
);
// Tighten umask around listen() so the socket inode is never transiently
// group/world-readable (BUG-5). The chmodSync below is kept as
// belt-and-suspenders for good measure.
const prevUmask = process.umask(0o077);
this.ready = new Promise((resolve, reject) => {
let settled = false;
this.socketServer.once("error", (err) => {
if (settled) return;
settled = true;
reject(err);
});
this.socketServer.listen(socketPath, () => {
try { fs.chmodSync(socketPath, 0o600); } catch {}
fs.writeFileSync(getPidPath(this.name), process.pid.toString());
writeMetadata(this.name, {
generation: this.generation,
daemonPid: process.pid,
...(this.recoveryCapability ? { recovery: this.recoveryCapability } : {}),
command: options.command,
args: options.args,
displayCommand: options.displayCommand,
cwd: options.cwd,
rows: options.rows,
cols: options.cols,
ephemeral: options.ephemeral === true,
createdAt: new Date().toISOString(),
...(options.tags && Object.keys(options.tags).length > 0 ? { tags: options.tags } : {}),
...(options.displayName ? { displayName: options.displayName } : {}),
...(options.isolateEnv ? { isolateEnv: true } : {}),
...(options.extraEnv && Object.keys(options.extraEnv).length > 0 ? { extraEnv: options.extraEnv } : {}),
...(options.unsetEnv && options.unsetEnv.length > 0 ? { unsetEnv: options.unsetEnv } : {}),
...(options.env ? { env: options.env } : {}),
});
this.emitEvent(EventType.SESSION_START, {
...(options.tags && Object.keys(options.tags).length > 0 ? { tags: options.tags } : {}),
});
if (settled) return;
settled = true;
resolve();
});
});
process.umask(prevUmask);
// Post-listen errors (e.g., socket file unlinked out from under us) must
// not crash the process, but they also mustn't interfere with the
// initial ready resolution above.
this.socketServer.on("error", (err) => {
console.error(`Socket server error: ${err.message}`);
});
}
private startRecoveryWatcher(): void {
const requestPath = recoveryRequestPath(this.recoveryRoot, this.name);
this.recoveryWatcher = fs.watch(
recoveryDir(this.recoveryRoot),
{ persistent: false },
(_event, filename) => {
if (
filename === path.basename(requestPath) &&
fs.existsSync(requestPath) &&
!this.recoveryInFlight
) {
void this.handleRecoveryRequest();
}
},
);
}
private recoveryMetadata(
observed: SessionMetadata,
capability: RecoveryCapability,
): SessionMetadata {
return stampRecoveryMetadata({
...observed,
generation: this.generation,
daemonPid: process.pid,
recovery: capability,
});
}
private async handleRecoveryRequest(): Promise<void> {
const capability = this.recoveryCapability;
if (!capability || this.recoveryInFlight) return;
this.recoveryInFlight = true;
const requestPath = recoveryRequestPath(this.recoveryRoot, this.name);
const resultPath = recoveryResultPath(this.recoveryRoot, this.name);
let request: RecoveryRequest | null = null;
let result: RecoveryResultPayload | null = null;
try {
assertPrivateRecoveryPaths(this.recoveryRoot, capability);
request = readBoundedJson<RecoveryRequest>(requestPath);
const currentStart = readProcessStartToken(process.pid);
const metadataCapability = request.metadata?.recovery;
const lockPath = path.join(this.recoveryRoot, `${this.name}.lock`);
const lockContents = recoveryLockContents(process.pid, request.lockIdentity);
const expectedLockIdentity = recoveryLockIdentity({
name: request.name,
daemonPid: request.daemonPid,
processStartToken: request.processStartToken,
rootDevice: request.rootDevice,
rootInode: request.rootInode,
recoveryDirDevice: capability.recoveryDirDevice,
recoveryDirInode: capability.recoveryDirInode,
});
const revision = readBoundedJson<RecoveryRevision>(
recoveryRevisionPath(this.recoveryRoot, this.name),
);
const exact =
request.protocol === RECOVERY_PROTOCOL &&
request.name === this.name &&
request.daemonPid === process.pid &&
request.generation === this.generation &&
request.processStartToken === capability.processStartToken &&
request.launchIdentity === capability.launchIdentity &&
request.rootDevice === capability.rootDevice &&
request.rootInode === capability.rootInode &&
currentStart === capability.processStartToken &&
request.lockIdentity === expectedLockIdentity &&
fs.readFileSync(lockPath, "utf8") === lockContents &&
metadataCapability?.protocol === capability.protocol &&
metadataCapability.secret === capability.secret &&
metadataCapability.processStartToken === capability.processStartToken &&
metadataCapability.launchIdentity === capability.launchIdentity &&
metadataCapability.rootDevice === capability.rootDevice &&
metadataCapability.rootInode === capability.rootInode &&
metadataCapability.recoveryDirDevice === capability.recoveryDirDevice &&
metadataCapability.recoveryDirInode === capability.recoveryDirInode &&
metadataCapability.metadataRevision === metadataRevision(request.metadata) &&
revision.protocol === RECOVERY_PROTOCOL &&
revision.name === this.name &&
revision.generation === this.generation &&
revision.metadataRevision === metadataCapability.metadataRevision &&
verifyRecoveryRevision(capability.secret, revision) &&
verifyRecoveryRequest(capability.secret, request);
if (!exact) throw new Error("recovery identity or authentication mismatch");
const socketPath = getSocketPath(this.name);
const pidPath = getPidPath(this.name);
const metadataPath = getMetadataPath(this.name);
for (const target of [socketPath, pidPath, metadataPath]) {
if (fs.existsSync(target)) throw new Error("recovery target is no longer empty");
}
const replacement = net.createServer((socket) => this.handleClient(socket));
await new Promise<void>((resolve, reject) => {
replacement.once("error", reject);
assertPrivateRecoveryPaths(this.recoveryRoot, capability);
replacement.listen(socketPath, resolve);
});
replacement.on("error", (error) => {
console.error(`Socket server error: ${error.message}`);
});
let socketIdentity: { dev: number; ino: number } | null = null;
let publishedPid = false;
let publishedMetadata = false;
let rotatedCapability: RecoveryCapability | null = null;
try {
fs.chmodSync(socketPath, 0o600);
const socketStat = fs.lstatSync(socketPath);
socketIdentity = { dev: socketStat.dev, ino: socketStat.ino };
if (fs.existsSync(pidPath) || fs.existsSync(metadataPath)) {
throw new Error("recovery sidecar appeared during publication");
}
assertPrivateRecoveryPaths(this.recoveryRoot, capability);
const rotated: RecoveryCapability = {
...capability,
secret: randomBytes(32).toString("hex"),
metadataRevision: "",
};
const recoveredMetadata = this.recoveryMetadata(request.metadata, rotated);
rotatedCapability = recoveredMetadata.recovery!;
// Advance the authoritative signed revision before any rotated
// capability-bearing metadata becomes visible. A later publication
// failure intentionally leaves recovery unavailable rather than
// allowing the old snapshot/secret to roll metadata back.
assertPrivateRecoveryPaths(this.recoveryRoot, capability);
atomicWritePrivate(
recoveryRevisionPath(this.recoveryRoot, this.name),
signRecoveryRevision(rotatedCapability.secret, {
protocol: RECOVERY_PROTOCOL,
name: this.name,
generation: this.generation,
metadataRevision: rotatedCapability.metadataRevision,
}),
);
publishPrivateNoReplace(pidPath, process.pid.toString());
publishedPid = true;
publishPrivateNoReplace(metadataPath, JSON.stringify(recoveredMetadata, null, 2));
publishedMetadata = true;
const finalSocket = fs.lstatSync(socketPath);
if (finalSocket.dev !== socketIdentity.dev || finalSocket.ino !== socketIdentity.ino) {
throw new Error("recovery pathname was replaced during publication");
}
const previous = this.socketServer;
this.socketServer = replacement;
this.recoveryCapability = rotatedCapability;
// Node remembers a Unix server's pathname and unlinks it on close.
// The old listener still remembers the same string even though its
// inode was externally unlinked; closing it now would unlink the new
// listener. Keep the unreachable fd unref'd until daemon shutdown.
previous.unref();
this.retiredSocketServers.push(previous);
result = {
protocol: RECOVERY_PROTOCOL,
name: this.name,
nonce: request.nonce,
ok: true,
daemonPid: process.pid,
generation: this.generation,
processStartToken: capability.processStartToken,
launchIdentity: capability.launchIdentity,
};
} catch (error) {
try { replacement.close(); } catch {}
if (publishedMetadata && rotatedCapability) {
try {
const current = readMetadata(this.name);
if (current?.recovery?.secret === rotatedCapability.secret) {
fs.unlinkSync(metadataPath);
}
} catch {}
}
if (publishedPid) {
try {
if (fs.readFileSync(pidPath, "utf8").trim() === String(process.pid)) {
fs.unlinkSync(pidPath);
}
} catch {}
}
if (socketIdentity) {
try {
const current = fs.lstatSync(socketPath);
if (current.dev === socketIdentity.dev && current.ino === socketIdentity.ino) {
fs.unlinkSync(socketPath);
}
} catch {}
}
throw error;
}
} catch (error) {
result = {
protocol: RECOVERY_PROTOCOL,
name: this.name,
nonce: request?.nonce ?? "",
ok: false,
error: error instanceof Error ? error.message : "recovery refused",
};
} finally {
try {
assertPrivateRecoveryPaths(this.recoveryRoot, capability);
if (result) {
atomicWritePrivate(
resultPath,
signRecoveryResult(capability.secret, result),
);
}
fs.unlinkSync(requestPath);
} catch {}
this.recoveryInFlight = false;
}
}
private handleClient(socket: net.Socket): void {
const client: Client = {
socket,
reader: new PacketReader(),
rows: this.terminal.rows,
cols: this.terminal.cols,
readonly: false,
attachSeq: 0,
initialScreenPhase: "live",
initialScreenGeneration: 0,
postCutPackets: [],
};
this.clients.set(socket, client);
socket.on("data", (data: Buffer) => {
let packets;
try {
packets = client.reader.feed(data);
} catch (err: any) {
// BUG-3: peer sent an oversize length header (or some other malformed
// frame) — drop them rather than buffer unbounded.
console.error(`Rejected client packet: ${err.message}`);
try { socket.destroy(); } catch {}
return;
}
for (const packet of packets) {
switch (packet.type) {
case MessageType.ATTACH: {
if (packet.payload.length < 4) break;
const size = decodeSize(packet.payload);
// Read before negotiateSize(): a smaller client shrinks the session
// to its own size, which would then look like it had matched.
const sizeMatched =
size.rows === this.terminal.rows && size.cols === this.terminal.cols;
client.readonly = false;
client.rows = size.rows;
client.cols = size.cols;
client.attachSeq = ++this.attachCounter;
client.initialScreenPhase = "settling";
client.postCutPackets = [];
const initialScreenGeneration = ++client.initialScreenGeneration;
const resized = this.negotiateSize();
if (!resized) {
socket.write(encodeGeometry(this.terminal.rows, this.terminal.cols));
}
// Best-effort: a concurrent metadata command wins this attach
// stamp, but neither writer can overwrite the other's snapshot.
try {
mutateMetadataUnderLock(this.name, (meta) => {
meta.lastAttachAt = new Date().toISOString();
return true;
}, { expectedGeneration: this.generation });
} catch {}
const sendScreen = () => {
this.beginInitialScreenCut(
client,
initialScreenGeneration,
() => this.getModePrefix(true) + this.serialize.serialize(),
() => {
// The serialize addon's output is an approximation — ECH/CUF
// sequences may not perfectly reproduce what the app originally
// drew (e.g., background fills in ratatui). Nudge the child
// with a SIGWINCH so it does a fresh full redraw, whose DATA
// overwrites any serialize artifacts on the client.
//
// Skipped when the client attached at the size the session
// already has: the child is drawn for that geometry, so the
// nudge buys nothing and wakes an otherwise idle process every
// time someone connects.
if (!this.exited && !sizeMatched) this.nudgeRedraw();
}
);
};
if (!this.exited) {
// If the PTY was just resized (either by this attach or
// recently by another client), wait for the process to
// redraw before serializing. Without this delay, the client
// sees a transient mid-redraw state.
const sinceLast = Date.now() - this.lastResizeTime;
const REDRAW_SETTLE_MS = 80;
if (resized || sinceLast < REDRAW_SETTLE_MS) {
const delay = resized ? REDRAW_SETTLE_MS : REDRAW_SETTLE_MS - sinceLast;
setTimeout(sendScreen, delay);
} else {
sendScreen();
}
} else {
sendScreen();
}