mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-16 20:11:08 +00:00
Co-authored-by: yuzifu <yuzifu@TB16PGen5.Info>
This commit is contained in:
1 parent
7da983a56c
commit
fb9400a5fb
7 files changed
+952
-59
No files matched your search
+46
-8
@@ -50,6 +50,7 @@ import { TerminalComposeBar } from "./terminal/TerminalComposeBar";
|
||||
import { TerminalContextMenu } from "./terminal/TerminalContextMenu";
|
||||
import { TerminalSearchBar } from "./terminal/TerminalSearchBar";
|
||||
import { ZmodemProgressIndicator } from "./terminal/ZmodemProgressIndicator";
|
||||
import { createReplaySafeTerminalLogSanitizer } from "./terminal/replaySafeTerminalLog";
|
||||
import { useZmodemTransfer } from "./terminal/hooks/useZmodemTransfer";
|
||||
import { createTerminalSessionStarters, type PendingAuth } from "./terminal/runtime/createTerminalSessionStarters";
|
||||
import { createXTermRuntime, primaryFontFamily, type XTermRuntime } from "./terminal/runtime/createXTermRuntime";
|
||||
@@ -64,6 +65,8 @@ import { useServerStats } from "./terminal/hooks/useServerStats";
|
||||
import { extractDropEntries, getPathForFile, DropEntry } from "../lib/sftpFileUtils";
|
||||
import { useTerminalAutocomplete, AutocompletePopup } from "./terminal/autocomplete";
|
||||
|
||||
const MAX_CONNECTION_LOG_DATA_CHARS = 1_000_000;
|
||||
|
||||
/**
|
||||
* Extract unique root paths from drop entries for local terminal path insertion.
|
||||
* For nested files, extracts the root folder path; for single files, uses the full path.
|
||||
@@ -285,6 +288,8 @@ const TerminalComponent: React.FC<TerminalProps> = ({
|
||||
// cancelled retry can't fire a startNewSession after the fact.
|
||||
const retryTokenRef = useRef<symbol | null>(null);
|
||||
const terminalDataCapturedRef = useRef(false);
|
||||
const terminalLogDataRef = useRef("");
|
||||
const terminalLogSanitizerRef = useRef(createReplaySafeTerminalLogSanitizer());
|
||||
const onTerminalDataCaptureRef = useRef(onTerminalDataCapture);
|
||||
const commandBufferRef = useRef<string>("");
|
||||
const [hasMouseTracking, setHasMouseTracking] = useState(false);
|
||||
@@ -300,6 +305,32 @@ const TerminalComponent: React.FC<TerminalProps> = ({
|
||||
const lastFittedSizeRef = useRef<{ width: number; height: number } | null>(null);
|
||||
const fontWeightFixupDoneRef = useRef(false);
|
||||
|
||||
const captureTerminalLogData = useCallback((data: string) => {
|
||||
const replaySafeData = terminalLogSanitizerRef.current.append(data);
|
||||
if (!replaySafeData) return;
|
||||
terminalLogDataRef.current += replaySafeData;
|
||||
if (terminalLogDataRef.current.length > MAX_CONNECTION_LOG_DATA_CHARS) {
|
||||
terminalLogDataRef.current = terminalLogDataRef.current.slice(-MAX_CONNECTION_LOG_DATA_CHARS);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const finalizeTerminalLogData = useCallback(() => {
|
||||
const replaySafeData = terminalLogSanitizerRef.current.finish();
|
||||
if (replaySafeData) {
|
||||
terminalLogDataRef.current += replaySafeData;
|
||||
if (terminalLogDataRef.current.length > MAX_CONNECTION_LOG_DATA_CHARS) {
|
||||
terminalLogDataRef.current = terminalLogDataRef.current.slice(-MAX_CONNECTION_LOG_DATA_CHARS);
|
||||
}
|
||||
}
|
||||
return terminalLogDataRef.current;
|
||||
}, []);
|
||||
|
||||
const writeLocalTerminalData = useCallback((data: string) => {
|
||||
if (!data) return;
|
||||
captureTerminalLogData(data);
|
||||
termRef.current?.write(data);
|
||||
}, [captureTerminalLogData]);
|
||||
|
||||
useEffect(() => {
|
||||
if (xtermRuntimeRef.current) {
|
||||
// Merge global rules with host-level rules
|
||||
@@ -437,20 +468,20 @@ const TerminalComponent: React.FC<TerminalProps> = ({
|
||||
const line = serialLineBufferRef.current + "\r";
|
||||
terminalBackend.writeToSession(id, line);
|
||||
serialLineBufferRef.current = "";
|
||||
if (serialConfig?.localEcho) termRef.current?.write("\r\n");
|
||||
if (serialConfig?.localEcho) writeLocalTerminalData("\r\n");
|
||||
} else if (ch === "\x15") {
|
||||
if (serialConfig?.localEcho && serialLineBufferRef.current.length > 0) {
|
||||
termRef.current?.write("\b \b".repeat(serialLineBufferRef.current.length));
|
||||
writeLocalTerminalData("\b \b".repeat(serialLineBufferRef.current.length));
|
||||
}
|
||||
serialLineBufferRef.current = "";
|
||||
} else if (ch === "\b" || ch === "\x7f") {
|
||||
if (serialLineBufferRef.current.length > 0) {
|
||||
serialLineBufferRef.current = serialLineBufferRef.current.slice(0, -1);
|
||||
if (serialConfig?.localEcho) termRef.current?.write("\b \b");
|
||||
if (serialConfig?.localEcho) writeLocalTerminalData("\b \b");
|
||||
}
|
||||
} else if (ch.charCodeAt(0) >= 32) {
|
||||
serialLineBufferRef.current += ch;
|
||||
if (serialConfig?.localEcho) termRef.current?.write(ch);
|
||||
if (serialConfig?.localEcho) writeLocalTerminalData(ch);
|
||||
}
|
||||
}
|
||||
// Still update commandBuffer and broadcast for serial line mode
|
||||
@@ -460,9 +491,9 @@ const TerminalComponent: React.FC<TerminalProps> = ({
|
||||
terminalBackend.writeToSession(id, text);
|
||||
for (const ch of text) {
|
||||
if (ch === "\r") {
|
||||
termRef.current?.write("\r\n");
|
||||
writeLocalTerminalData("\r\n");
|
||||
} else if (ch.charCodeAt(0) >= 32) {
|
||||
termRef.current?.write(ch);
|
||||
writeLocalTerminalData(ch);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@@ -754,12 +785,15 @@ const TerminalComponent: React.FC<TerminalProps> = ({
|
||||
hasConnectedRef.current = next === "connected";
|
||||
onStatusChange?.(sessionId, next);
|
||||
};
|
||||
|
||||
const handleTerminalDataCaptureOnce = useCallback((capturedSessionId: string, data: string) => {
|
||||
const captureHandler = onTerminalDataCaptureRef.current;
|
||||
if (!captureHandler || terminalDataCapturedRef.current) return;
|
||||
terminalDataCapturedRef.current = true;
|
||||
captureHandler(capturedSessionId, data);
|
||||
}, []);
|
||||
const replaySafeLogData = finalizeTerminalLogData();
|
||||
const capturedData = replaySafeLogData || data;
|
||||
captureHandler(capturedSessionId, capturedData);
|
||||
}, [finalizeTerminalLogData]);
|
||||
|
||||
const cleanupSession = () => {
|
||||
disposeDataRef.current?.();
|
||||
@@ -847,6 +881,7 @@ const TerminalComponent: React.FC<TerminalProps> = ({
|
||||
},
|
||||
onSessionExit,
|
||||
onTerminalDataCapture: handleTerminalDataCaptureOnce,
|
||||
onTerminalLogData: captureTerminalLogData,
|
||||
onOsDetected,
|
||||
onCommandExecuted,
|
||||
sessionLog,
|
||||
@@ -856,6 +891,8 @@ const TerminalComponent: React.FC<TerminalProps> = ({
|
||||
useEffect(() => {
|
||||
let disposed = false;
|
||||
terminalDataCapturedRef.current = false;
|
||||
terminalLogDataRef.current = "";
|
||||
terminalLogSanitizerRef.current = createReplaySafeTerminalLogSanitizer();
|
||||
setError(null);
|
||||
hasConnectedRef.current = false;
|
||||
pendingOutputScrollRef.current = false;
|
||||
@@ -892,6 +929,7 @@ const TerminalComponent: React.FC<TerminalProps> = ({
|
||||
serialLocalEcho: serialConfig?.localEcho,
|
||||
serialLineMode: serialConfig?.lineMode,
|
||||
serialLineBufferRef,
|
||||
onTerminalLogData: captureTerminalLogData,
|
||||
onCwdChange: (cwd: string) => {
|
||||
knownCwdRef.current = cwd;
|
||||
},
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
import {
|
||||
createReplaySafeTerminalLog,
|
||||
createReplaySafeTerminalLogSanitizer,
|
||||
} from "./replaySafeTerminalLog";
|
||||
|
||||
test("common shell clear sequence is safe to replay", () => {
|
||||
const log = createReplaySafeTerminalLog("login banner\n$ clear\n\x1b[H\x1b[2J\x1b[3Jafter clear\n");
|
||||
|
||||
assert.equal(log, "login banner\n$ clear\n\r\nafter clear\n");
|
||||
assert.equal(log.includes("\x1b[2J"), false);
|
||||
assert.equal(log.includes("\x1b[3J"), false);
|
||||
});
|
||||
|
||||
test("display clear followed by cursor home keeps prior replay history", () => {
|
||||
assert.equal(
|
||||
createReplaySafeTerminalLog("old1\nold2\n\x1b[2J\x1b[Hnew\n"),
|
||||
"old1\nold2\n\r\nnew\n",
|
||||
);
|
||||
});
|
||||
|
||||
test("home erase-to-end clear keeps prior replay history", () => {
|
||||
assert.equal(
|
||||
createReplaySafeTerminalLog("before zellij\n$ zellij\n\x1b[H\x1b[Jzellij pane\n"),
|
||||
"before zellij\n$ zellij\n\r\nzellij pane\n",
|
||||
);
|
||||
});
|
||||
|
||||
test("repeated home erase-to-end clears create fresh replay sections", () => {
|
||||
const log = createReplaySafeTerminalLog("history\n\x1b[2Jframe1\x1b[H\x1b[Jframe2\n");
|
||||
|
||||
assert.equal(log, "history\n\r\nframe1\r\n\r\nframe2\n");
|
||||
assert.equal(log.includes("\x1b[H"), false);
|
||||
assert.equal(log.includes("\x1b[J"), false);
|
||||
});
|
||||
|
||||
test("repeated cursor home before clear does not overwrite replay history", () => {
|
||||
const log = createReplaySafeTerminalLog("old1\nold2\n\x1b[H\x1b[H\x1b[2Jafter\n");
|
||||
|
||||
assert.equal(log, "old1\nold2\n\r\nafter\n");
|
||||
assert.equal(log.includes("\x1b[H"), false);
|
||||
});
|
||||
|
||||
test("mode controls after clear do not allow later home to overwrite history", () => {
|
||||
const log = createReplaySafeTerminalLog("history\n\x1b[H\x1b[2J\x1b[?25l\x1b[Hnew\n");
|
||||
|
||||
assert.equal(log, "history\n\r\n\x1b[?25lnew\n");
|
||||
});
|
||||
|
||||
test("cursor positioning after clear does not overwrite replay history", () => {
|
||||
const log = createReplaySafeTerminalLog(
|
||||
"old1\nold2\n\x1b[2J\x1b[10;5Hpanel\x1b[999Aup\x1b[5Fprev\x1b[12drow\x1b[20Gcol\n",
|
||||
);
|
||||
|
||||
assert.equal(log, "old1\nold2\n\r\npanelupprevrowcol\n");
|
||||
assert.equal(log.includes("\x1b[10;5H"), false);
|
||||
assert.equal(log.includes("\x1b[999A"), false);
|
||||
assert.equal(log.includes("\x1b[5F"), false);
|
||||
assert.equal(log.includes("\x1b[12d"), false);
|
||||
assert.equal(log.includes("\x1b[20G"), false);
|
||||
});
|
||||
|
||||
test("cursor home after protected clear is dropped when no erase follows", () => {
|
||||
const log = createReplaySafeTerminalLog("old\n\x1b[2Jframe\x1b[H\x1b[?25ltext\n");
|
||||
|
||||
assert.equal(log, "old\n\r\nframe\x1b[?25ltext\n");
|
||||
assert.equal(log.includes("\x1b[H"), false);
|
||||
});
|
||||
|
||||
test("single-character cursor controls after clear do not overwrite replay history", () => {
|
||||
const log = createReplaySafeTerminalLog("old\n\x1b[2J\x1bMri\x8dc1ri\x1bDind\x84c1ind\x1bEnel\x85c1nel\n");
|
||||
|
||||
assert.equal(log, "old\n\r\nric1riindc1indnelc1nel\n");
|
||||
assert.equal(log.includes("\x1bM"), false);
|
||||
assert.equal(log.includes("\x8d"), false);
|
||||
assert.equal(log.includes("\x1bD"), false);
|
||||
assert.equal(log.includes("\x84"), false);
|
||||
assert.equal(log.includes("\x1bE"), false);
|
||||
assert.equal(log.includes("\x85"), false);
|
||||
});
|
||||
|
||||
test("queued cursor and erase controls before clear are not preserved", () => {
|
||||
const log = createReplaySafeTerminalLog("old\n\x1b[H\x1b[2;1H\x1b[K\x1b[s\x1b[u\x1b[?25l\x1b[2Jnew\n");
|
||||
|
||||
assert.equal(log, "old\n\r\n\x1b[?25lnew\n");
|
||||
assert.equal(log.includes("\x1b[2;1H"), false);
|
||||
assert.equal(log.includes("\x1b[K"), false);
|
||||
assert.equal(log.includes("\x1b[s"), false);
|
||||
assert.equal(log.includes("\x1b[u"), false);
|
||||
});
|
||||
|
||||
test("cursor save and restore are preserved before any protected clear", () => {
|
||||
const log = createReplaySafeTerminalLog("abc\x1b[sXYZ\x1b[u!");
|
||||
|
||||
assert.equal(log, "abc\x1b[sXYZ\x1b[u!");
|
||||
});
|
||||
|
||||
test("pending cursor-home controls are preserved when no clear follows", () => {
|
||||
const log = createReplaySafeTerminalLog("abc\x1b[H\x1b[s\x1b[2;1HXYZ");
|
||||
|
||||
assert.equal(log, "abc\x1b[H\x1b[s\x1b[2;1HXYZ");
|
||||
});
|
||||
|
||||
test("mode controls between home and erase are kept without preserving clear controls", () => {
|
||||
const log = createReplaySafeTerminalLog("history\n\x1b[H\x1b[?25l\x1b[Jnew\n");
|
||||
|
||||
assert.equal(log, "history\n\r\n\x1b[?25lnew\n");
|
||||
});
|
||||
|
||||
test("erase-display backward controls are dropped from replay data", () => {
|
||||
const log = createReplaySafeTerminalLog("old\n\x1b[2Jnew\x1b[1Jafter\n");
|
||||
|
||||
assert.equal(log, "old\n\r\nnew\r\n\r\nafter\n");
|
||||
assert.equal(log.includes("\x1b[1J"), false);
|
||||
});
|
||||
|
||||
test("scrollback-only clears protect replay history", () => {
|
||||
const log = createReplaySafeTerminalLog("history\n\x1b[3J\x1b[Hoverwrite\n");
|
||||
|
||||
assert.equal(log, "history\n\r\noverwrite\n");
|
||||
assert.equal(log.includes("\x1b[3J"), false);
|
||||
assert.equal(log.includes("\x1b[H"), false);
|
||||
});
|
||||
|
||||
test("terminal control strings are stripped from replay data", () => {
|
||||
const log = createReplaySafeTerminalLog(
|
||||
"before\x1b]52;c;secret\x07mid\x1b]7;file://host/path\x1b\\"
|
||||
+ "dcs\x1bP1$rpayload\x1b\\apc\x1b_payload\x1b\\pm\x1b^payload\x1b\\"
|
||||
+ "sos\x1bXpayload\x1b\\c1sos\x98hidden\x9cafter",
|
||||
);
|
||||
|
||||
assert.equal(log, "beforemiddcsapcpmsosc1sosafter");
|
||||
assert.equal(log.includes("\x1b"), false);
|
||||
assert.equal(log.includes("secret"), false);
|
||||
assert.equal(log.includes("payload"), false);
|
||||
assert.equal(log.includes("hidden"), false);
|
||||
});
|
||||
|
||||
test("split terminal control strings are stripped before truncation", () => {
|
||||
const sanitizer = createReplaySafeTerminalLogSanitizer();
|
||||
const hiddenPayload = "secret".repeat(200_000);
|
||||
let captured = "";
|
||||
|
||||
captured += sanitizer.append("before\x1b]52;c;");
|
||||
captured = captured.slice(-1_000_000);
|
||||
captured += sanitizer.append(hiddenPayload);
|
||||
captured = captured.slice(-1_000_000);
|
||||
captured += sanitizer.append("\x07after");
|
||||
captured = captured.slice(-1_000_000);
|
||||
captured += sanitizer.finish();
|
||||
|
||||
assert.equal(captured, "beforeafter");
|
||||
assert.equal(captured.includes("secret"), false);
|
||||
});
|
||||
|
||||
test("overlong pending csi data is discarded until the sequence ends", () => {
|
||||
const sanitizer = createReplaySafeTerminalLogSanitizer();
|
||||
const parameters = "1;".repeat(3000);
|
||||
|
||||
const log = sanitizer.append(`before\x1b[${parameters}`)
|
||||
+ sanitizer.append(parameters)
|
||||
+ sanitizer.append("mafter")
|
||||
+ sanitizer.finish();
|
||||
|
||||
assert.equal(log, "beforeafter");
|
||||
assert.equal(log.includes(parameters.slice(0, 32)), false);
|
||||
});
|
||||
|
||||
test("pending cursor-home lookahead controls are bounded before clear", () => {
|
||||
const controls = "\x1b[31m".repeat(900);
|
||||
const log = createReplaySafeTerminalLog(`old\n\x1b[H${controls}\x1b[2Jnew\n`);
|
||||
|
||||
assert.equal(log, "old\n\r\nnew\n");
|
||||
assert.equal(log.includes("\x1b[31m"), false);
|
||||
});
|
||||
|
||||
test("alternate-screen entry protects preserved replay history", () => {
|
||||
const log = createReplaySafeTerminalLog(
|
||||
"before\n\x1b[?1049h\x1b[Hvim screen\n\x1b[?1049lafter\n"
|
||||
+ "\x1b[?47h\x1b[10;5Htop screen\n\x1b[?47l"
|
||||
+ "\x1b[?25lcursor hidden\n",
|
||||
);
|
||||
|
||||
assert.equal(log, "before\n\r\nvim screen\nafter\n\r\ntop screen\n\x1b[?25lcursor hidden\n");
|
||||
assert.equal(log.includes("\x1b[?1049h"), false);
|
||||
assert.equal(log.includes("\x1b[?1049l"), false);
|
||||
assert.equal(log.includes("\x1b[?47h"), false);
|
||||
assert.equal(log.includes("\x1b[?47l"), false);
|
||||
assert.equal(log.includes("\x1b[H"), false);
|
||||
assert.equal(log.includes("\x1b[10;5H"), false);
|
||||
assert.equal(log.includes("\x1b[?25l"), true);
|
||||
});
|
||||
|
||||
test("dec cursor save mode is not treated as alternate screen", () => {
|
||||
const log = createReplaySafeTerminalLog("before\n\x1b[?1048h\x1b[?1048l\x1b[10;5Hpositioned\n");
|
||||
|
||||
assert.equal(log, "before\n\x1b[?1048h\x1b[?1048l\x1b[10;5Hpositioned\n");
|
||||
});
|
||||
|
||||
test("cursor save and restore controls are stripped around protected clears", () => {
|
||||
const log = createReplaySafeTerminalLog("old\n\x1b[s\x1b7\x1b[2J\x1b[uafter\x1b8done\n");
|
||||
|
||||
assert.equal(log, "old\n\x1b[s\x1b7\r\n\r\nafterdone\n");
|
||||
assert.equal(log.includes("\x1b[s"), true);
|
||||
assert.equal(log.includes("\x1b[u"), false);
|
||||
assert.equal(log.includes("\x1b7"), true);
|
||||
assert.equal(log.includes("\x1b8"), false);
|
||||
});
|
||||
|
||||
test("terminal reset controls are dropped from replay data", () => {
|
||||
const log = createReplaySafeTerminalLog("before\x1bcafter\n");
|
||||
|
||||
assert.equal(log, "before\r\n\r\nafter\n");
|
||||
assert.equal(log.includes("\x1bc"), false);
|
||||
});
|
||||
|
||||
test("split terminal reset controls are dropped from replay data", () => {
|
||||
const sanitizer = createReplaySafeTerminalLogSanitizer();
|
||||
|
||||
const log = sanitizer.append("before\x1b")
|
||||
+ sanitizer.append("cafter\n")
|
||||
+ sanitizer.finish();
|
||||
|
||||
assert.equal(log, "before\r\n\r\nafter\n");
|
||||
assert.equal(log.includes("\x1bc"), false);
|
||||
});
|
||||
|
||||
test("non-clear cursor and color controls are preserved", () => {
|
||||
const input = "\x1b[H\x1b[31mred\x1b[0m\n";
|
||||
|
||||
assert.equal(createReplaySafeTerminalLog(input), input);
|
||||
});
|
||||
@@ -0,0 +1,427 @@
|
||||
type CsiSequence = {
|
||||
raw: string;
|
||||
end: number;
|
||||
final: string;
|
||||
params: string;
|
||||
};
|
||||
|
||||
const ESC = "\x1b";
|
||||
const BEL = "\x07";
|
||||
const ST = "\x9c";
|
||||
const CSI = "\x9b";
|
||||
const MAX_PENDING_ESCAPE_CHARS = 4096;
|
||||
|
||||
type ControlStringMode = "osc" | "string";
|
||||
|
||||
export interface ReplaySafeTerminalLogSanitizer {
|
||||
append(input: string): string;
|
||||
finish(): string;
|
||||
}
|
||||
|
||||
const isCsiFinal = (ch: string): boolean => ch >= "@" && ch <= "~";
|
||||
|
||||
const readCsiSequence = (input: string, index: number): CsiSequence | null => {
|
||||
const isEscCsi = input[index] === ESC && input[index + 1] === "[";
|
||||
const isC1Csi = input[index] === CSI;
|
||||
if (!isEscCsi && !isC1Csi) return null;
|
||||
|
||||
const paramsStart = isEscCsi ? index + 2 : index + 1;
|
||||
for (let i = paramsStart; i < input.length; i += 1) {
|
||||
if (isCsiFinal(input[i])) {
|
||||
return {
|
||||
raw: input.slice(index, i + 1),
|
||||
end: i + 1,
|
||||
final: input[i],
|
||||
params: input.slice(paramsStart, i),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
const startsCsiSequence = (input: string, index: number): boolean =>
|
||||
(input[index] === ESC && input[index + 1] === "[") || input[index] === CSI;
|
||||
|
||||
const isEscControlStringIntroducer = (ch: string): boolean =>
|
||||
ch === "]" || ch === "P" || ch === "_" || ch === "^" || ch === "X";
|
||||
|
||||
const isC1ControlStringIntroducer = (ch: string): boolean =>
|
||||
ch === "\x90" || ch === "\x98" || ch === "\x9d" || ch === "\x9e" || ch === "\x9f";
|
||||
|
||||
const getControlStringStart = (
|
||||
input: string,
|
||||
index: number,
|
||||
): { mode: ControlStringMode; dataStart: number } | null => {
|
||||
const ch = input[index];
|
||||
|
||||
if (ch === ESC) {
|
||||
const introducer = input[index + 1];
|
||||
if (!isEscControlStringIntroducer(introducer)) return null;
|
||||
return {
|
||||
mode: introducer === "]" ? "osc" : "string",
|
||||
dataStart: index + 2,
|
||||
};
|
||||
}
|
||||
|
||||
if (isC1ControlStringIntroducer(ch)) {
|
||||
return {
|
||||
mode: ch === "\x9d" ? "osc" : "string",
|
||||
dataStart: index + 1,
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
const parseCsiParams = (params: string): Array<number | undefined> => {
|
||||
const parameterBytes = params.replace(/[?><=]/g, "").replace(/[ -/]+$/g, "");
|
||||
if (!parameterBytes) return [];
|
||||
return parameterBytes.split(";").map((part) => {
|
||||
if (!part) return undefined;
|
||||
const n = Number.parseInt(part, 10);
|
||||
return Number.isFinite(n) ? n : undefined;
|
||||
});
|
||||
};
|
||||
|
||||
const normalizedPosition = (value: number | undefined): number => Math.max(1, value ?? 1);
|
||||
|
||||
const isCursorHomeSequence = (sequence: CsiSequence): boolean => {
|
||||
if (sequence.final !== "H" && sequence.final !== "f") return false;
|
||||
const values = parseCsiParams(sequence.params);
|
||||
return normalizedPosition(values[0]) === 1 && normalizedPosition(values[1]) === 1;
|
||||
};
|
||||
|
||||
const isCursorMovementSequence = (sequence: CsiSequence): boolean =>
|
||||
sequence.final === "A"
|
||||
|| sequence.final === "B"
|
||||
|| sequence.final === "C"
|
||||
|| sequence.final === "D"
|
||||
|| sequence.final === "E"
|
||||
|| sequence.final === "F"
|
||||
|| sequence.final === "H"
|
||||
|| sequence.final === "f"
|
||||
|| sequence.final === "G"
|
||||
|| sequence.final === "`"
|
||||
|| sequence.final === "d"
|
||||
|| sequence.final === "a"
|
||||
|| sequence.final === "e";
|
||||
|
||||
const isCursorStateSequence = (sequence: CsiSequence): boolean =>
|
||||
sequence.final === "s"
|
||||
|| sequence.final === "u"
|
||||
|| (
|
||||
(sequence.final === "h" || sequence.final === "l")
|
||||
&& sequence.params.includes("?")
|
||||
&& parseCsiParams(sequence.params).includes(1048)
|
||||
);
|
||||
|
||||
const isUnsafeCursorReplaySequence = (sequence: CsiSequence): boolean =>
|
||||
isCursorMovementSequence(sequence) || isCursorStateSequence(sequence);
|
||||
|
||||
const getEraseDisplayMode = (sequence: CsiSequence): number | null => {
|
||||
if (sequence.final !== "J") return null;
|
||||
const values = parseCsiParams(sequence.params);
|
||||
return values[0] ?? 0;
|
||||
};
|
||||
|
||||
const isEraseSequence = (sequence: CsiSequence): boolean =>
|
||||
sequence.final === "J" || sequence.final === "K" || sequence.final === "X";
|
||||
|
||||
const isSafePendingAfterCursorHomeSequence = (sequence: CsiSequence): boolean =>
|
||||
!isUnsafeCursorReplaySequence(sequence) && !isEraseSequence(sequence);
|
||||
|
||||
const getAlternateScreenMode = (sequence: CsiSequence): "enter" | "exit" | null => {
|
||||
if (sequence.final !== "h" && sequence.final !== "l") return null;
|
||||
if (!sequence.params.includes("?")) return null;
|
||||
const isAlternateScreen = parseCsiParams(sequence.params).some((value) =>
|
||||
value === 47 || value === 1047 || value === 1049,
|
||||
);
|
||||
if (!isAlternateScreen) return null;
|
||||
return sequence.final === "h" ? "enter" : "exit";
|
||||
};
|
||||
|
||||
const isC1SingleCharCursorControl = (ch: string): boolean =>
|
||||
ch === "\x84" || ch === "\x85" || ch === "\x8d";
|
||||
|
||||
const isEscSingleCharCursorControl = (ch: string): boolean =>
|
||||
ch === "D" || ch === "E" || ch === "M";
|
||||
|
||||
class ReplaySafeTerminalLogSanitizerImpl implements ReplaySafeTerminalLogSanitizer {
|
||||
private pendingInput = "";
|
||||
private pendingCursorHome = "";
|
||||
private pendingAfterCursorHome = "";
|
||||
private replaySafePendingAfterCursorHome = "";
|
||||
private pendingAfterCursorHomeOverflowed = false;
|
||||
private controlStringMode: ControlStringMode | null = null;
|
||||
private controlStringEscPending = false;
|
||||
private discardingCsi = false;
|
||||
private inClearCluster = false;
|
||||
private protectingClearedHistory = false;
|
||||
private hasOutput = false;
|
||||
private lastOutputChar = "";
|
||||
|
||||
append(input: string): string {
|
||||
let output = "";
|
||||
const data = this.pendingInput + input;
|
||||
this.pendingInput = "";
|
||||
|
||||
const appendOutput = (next: string) => {
|
||||
if (!next) return;
|
||||
output += next;
|
||||
this.hasOutput = true;
|
||||
this.lastOutputChar = next[next.length - 1];
|
||||
};
|
||||
|
||||
const flushPendingCursorHome = () => {
|
||||
if (!this.pendingCursorHome) return;
|
||||
if (this.protectingClearedHistory) {
|
||||
appendOutput(this.replaySafePendingAfterCursorHome);
|
||||
} else {
|
||||
appendOutput(this.pendingCursorHome);
|
||||
appendOutput(this.pendingAfterCursorHome);
|
||||
}
|
||||
this.pendingCursorHome = "";
|
||||
this.pendingAfterCursorHome = "";
|
||||
this.replaySafePendingAfterCursorHome = "";
|
||||
this.pendingAfterCursorHomeOverflowed = false;
|
||||
};
|
||||
|
||||
const emitClearSeparator = (preservePendingControls: boolean) => {
|
||||
const preservedControls = preservePendingControls ? this.replaySafePendingAfterCursorHome : "";
|
||||
this.pendingCursorHome = "";
|
||||
this.pendingAfterCursorHome = "";
|
||||
this.replaySafePendingAfterCursorHome = "";
|
||||
this.pendingAfterCursorHomeOverflowed = false;
|
||||
if (!this.inClearCluster && this.hasOutput) {
|
||||
appendOutput(/[\r\n]$/.test(this.lastOutputChar) ? "\r\n" : "\r\n\r\n");
|
||||
}
|
||||
appendOutput(preservedControls);
|
||||
this.inClearCluster = true;
|
||||
this.protectingClearedHistory = true;
|
||||
};
|
||||
|
||||
for (let i = 0; i < data.length;) {
|
||||
if (this.discardingCsi) {
|
||||
i = this.consumeDiscardedCsi(data, i);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (this.controlStringMode) {
|
||||
i = this.consumeControlString(data, i);
|
||||
continue;
|
||||
}
|
||||
|
||||
const controlStringStart = getControlStringStart(data, i);
|
||||
if (controlStringStart) {
|
||||
this.controlStringMode = controlStringStart.mode;
|
||||
this.controlStringEscPending = false;
|
||||
i = controlStringStart.dataStart;
|
||||
continue;
|
||||
}
|
||||
|
||||
const sequence = readCsiSequence(data, i);
|
||||
|
||||
if (!sequence && startsCsiSequence(data, i)) {
|
||||
this.setPendingEscapeInput(data.slice(i));
|
||||
break;
|
||||
}
|
||||
|
||||
if (sequence) {
|
||||
const alternateScreenMode = getAlternateScreenMode(sequence);
|
||||
if (alternateScreenMode) {
|
||||
if (alternateScreenMode === "enter") {
|
||||
emitClearSeparator(false);
|
||||
}
|
||||
i = sequence.end;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isCursorHomeSequence(sequence)) {
|
||||
if (!this.inClearCluster) {
|
||||
if (!this.pendingCursorHome) {
|
||||
flushPendingCursorHome();
|
||||
}
|
||||
this.pendingCursorHome = sequence.raw;
|
||||
}
|
||||
i = sequence.end;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (this.protectingClearedHistory && isUnsafeCursorReplaySequence(sequence)) {
|
||||
i = sequence.end;
|
||||
continue;
|
||||
}
|
||||
|
||||
const eraseMode = getEraseDisplayMode(sequence);
|
||||
if (eraseMode !== null) {
|
||||
if (eraseMode === 3) {
|
||||
emitClearSeparator(false);
|
||||
} else if (eraseMode === 1) {
|
||||
emitClearSeparator(false);
|
||||
} else if (eraseMode === 2 || (eraseMode === 0 && this.pendingCursorHome)) {
|
||||
emitClearSeparator(true);
|
||||
} else {
|
||||
flushPendingCursorHome();
|
||||
appendOutput(sequence.raw);
|
||||
this.inClearCluster = false;
|
||||
}
|
||||
i = sequence.end;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (this.pendingCursorHome) {
|
||||
this.appendPendingAfterCursorHome(sequence);
|
||||
i = sequence.end;
|
||||
continue;
|
||||
}
|
||||
|
||||
const preserveClearCluster = this.inClearCluster;
|
||||
flushPendingCursorHome();
|
||||
appendOutput(sequence.raw);
|
||||
this.inClearCluster = preserveClearCluster;
|
||||
i = sequence.end;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (this.protectingClearedHistory && isC1SingleCharCursorControl(data[i])) {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (data[i] === ESC) {
|
||||
if (i + 1 >= data.length) {
|
||||
this.setPendingEscapeInput(data.slice(i));
|
||||
break;
|
||||
}
|
||||
|
||||
if (data[i + 1] === "c") {
|
||||
emitClearSeparator(false);
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (this.protectingClearedHistory && (data[i + 1] === "7" || data[i + 1] === "8")) {
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (this.protectingClearedHistory && isEscSingleCharCursorControl(data[i + 1])) {
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
flushPendingCursorHome();
|
||||
appendOutput(data[i]);
|
||||
this.inClearCluster = false;
|
||||
i += 1;
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
finish(): string {
|
||||
this.pendingInput = "";
|
||||
this.controlStringMode = null;
|
||||
this.controlStringEscPending = false;
|
||||
this.discardingCsi = false;
|
||||
|
||||
let output = "";
|
||||
if (this.pendingCursorHome) {
|
||||
output = this.pendingCursorHome + this.pendingAfterCursorHome;
|
||||
this.hasOutput = true;
|
||||
this.lastOutputChar = output[output.length - 1];
|
||||
this.pendingCursorHome = "";
|
||||
this.pendingAfterCursorHome = "";
|
||||
this.replaySafePendingAfterCursorHome = "";
|
||||
this.pendingAfterCursorHomeOverflowed = false;
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
private appendPendingAfterCursorHome(sequence: CsiSequence): void {
|
||||
if (this.pendingAfterCursorHomeOverflowed) return;
|
||||
|
||||
const nextLength = this.pendingAfterCursorHome.length + sequence.raw.length;
|
||||
if (nextLength > MAX_PENDING_ESCAPE_CHARS) {
|
||||
this.pendingAfterCursorHome = "";
|
||||
this.replaySafePendingAfterCursorHome = "";
|
||||
this.pendingAfterCursorHomeOverflowed = true;
|
||||
return;
|
||||
}
|
||||
|
||||
this.pendingAfterCursorHome += sequence.raw;
|
||||
if (isSafePendingAfterCursorHomeSequence(sequence)) {
|
||||
this.replaySafePendingAfterCursorHome += sequence.raw;
|
||||
}
|
||||
}
|
||||
|
||||
private setPendingEscapeInput(input: string): void {
|
||||
if (input.length > MAX_PENDING_ESCAPE_CHARS) {
|
||||
this.pendingInput = "";
|
||||
this.discardingCsi = true;
|
||||
return;
|
||||
}
|
||||
this.pendingInput = input;
|
||||
}
|
||||
|
||||
private consumeDiscardedCsi(input: string, index: number): number {
|
||||
for (let i = index; i < input.length; i += 1) {
|
||||
if (isCsiFinal(input[i])) {
|
||||
this.discardingCsi = false;
|
||||
return i + 1;
|
||||
}
|
||||
}
|
||||
|
||||
return input.length;
|
||||
}
|
||||
|
||||
private consumeControlString(input: string, index: number): number {
|
||||
let i = index;
|
||||
|
||||
if (this.controlStringEscPending) {
|
||||
if (input[i] === "\\") {
|
||||
this.controlStringMode = null;
|
||||
this.controlStringEscPending = false;
|
||||
return i + 1;
|
||||
}
|
||||
this.controlStringEscPending = false;
|
||||
}
|
||||
|
||||
for (; i < input.length; i += 1) {
|
||||
if (this.controlStringMode === "osc" && input[i] === BEL) {
|
||||
this.controlStringMode = null;
|
||||
return i + 1;
|
||||
}
|
||||
if (input[i] === ST) {
|
||||
this.controlStringMode = null;
|
||||
return i + 1;
|
||||
}
|
||||
if (input[i] === ESC) {
|
||||
if (i + 1 >= input.length) {
|
||||
this.controlStringEscPending = true;
|
||||
return input.length;
|
||||
}
|
||||
if (input[i + 1] === "\\") {
|
||||
this.controlStringMode = null;
|
||||
return i + 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return input.length;
|
||||
}
|
||||
}
|
||||
|
||||
export const createReplaySafeTerminalLogSanitizer = (): ReplaySafeTerminalLogSanitizer =>
|
||||
new ReplaySafeTerminalLogSanitizerImpl();
|
||||
|
||||
/**
|
||||
* Convert terminal output into a form that can be replayed in LogView without
|
||||
* allowing shell `clear` / ED2 / ED3 controls to wipe earlier log history.
|
||||
*/
|
||||
export function createReplaySafeTerminalLog(input: string): string {
|
||||
const sanitizer = createReplaySafeTerminalLogSanitizer();
|
||||
return sanitizer.append(input) + sanitizer.finish();
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import { createTerminalSessionStarters, getMissingChainHostIds } from "./createTerminalSessionStarters";
|
||||
import { pasteTextIntoTerminal } from "./terminalUserPaste";
|
||||
|
||||
const noop = () => undefined;
|
||||
const ENCRYPTED_CREDENTIAL_PLACEHOLDER = "enc:v1:djEwAAAA";
|
||||
@@ -22,6 +23,170 @@ test("getMissingChainHostIds reports unresolved jump hosts", () => {
|
||||
);
|
||||
});
|
||||
|
||||
test("startSerial captures direct connected banner in terminal log data", async () => {
|
||||
const capturedLogData: string[] = [];
|
||||
const writtenLines: string[] = [];
|
||||
|
||||
const terminalBackend = {
|
||||
backendAvailable: () => true,
|
||||
telnetAvailable: () => true,
|
||||
moshAvailable: () => true,
|
||||
localAvailable: () => true,
|
||||
serialAvailable: () => true,
|
||||
execAvailable: () => true,
|
||||
startSSHSession: async () => "ssh-session",
|
||||
startTelnetSession: async () => "telnet-session",
|
||||
startMoshSession: async () => "mosh-session",
|
||||
startLocalSession: async () => "local-session",
|
||||
startSerialSession: async () => "serial-session",
|
||||
execCommand: async () => ({}),
|
||||
onSessionData: () => noop,
|
||||
onSessionExit: () => noop,
|
||||
onChainProgress: () => noop,
|
||||
writeToSession: noop,
|
||||
resizeSession: noop,
|
||||
};
|
||||
|
||||
const ctx = {
|
||||
host: {
|
||||
id: "serial-host",
|
||||
label: "Serial",
|
||||
hostname: "COM3",
|
||||
username: "",
|
||||
protocol: "serial",
|
||||
},
|
||||
keys: [],
|
||||
resolvedChainHosts: [],
|
||||
sessionId: "session-1",
|
||||
terminalSettings: {},
|
||||
terminalBackend,
|
||||
serialConfig: {
|
||||
path: "COM3",
|
||||
baudRate: 9600,
|
||||
dataBits: 8,
|
||||
stopBits: 1,
|
||||
parity: "none",
|
||||
flowControl: "none",
|
||||
},
|
||||
sessionRef: { current: null },
|
||||
hasConnectedRef: { current: false },
|
||||
hasRunStartupCommandRef: { current: false },
|
||||
disposeDataRef: { current: null },
|
||||
disposeExitRef: { current: null },
|
||||
fitAddonRef: { current: null },
|
||||
serializeAddonRef: { current: null },
|
||||
pendingAuthRef: { current: null },
|
||||
updateStatus: noop,
|
||||
setStatus: noop,
|
||||
setError: noop,
|
||||
setNeedsAuth: noop,
|
||||
setAuthRetryMessage: noop,
|
||||
setAuthPassword: noop,
|
||||
setProgressLogs: noop,
|
||||
setProgressValue: noop,
|
||||
setChainProgress: noop,
|
||||
onTerminalLogData: (data: string) => capturedLogData.push(data),
|
||||
};
|
||||
|
||||
const term = {
|
||||
cols: 120,
|
||||
rows: 32,
|
||||
write: noop,
|
||||
writeln: (data: string) => writtenLines.push(data),
|
||||
scrollToBottom: noop,
|
||||
};
|
||||
|
||||
await createTerminalSessionStarters(ctx as never).startSerial(term as never);
|
||||
|
||||
const banner = "[Connected to COM3 at 9600 baud]";
|
||||
assert.deepEqual(writtenLines, [banner]);
|
||||
assert.deepEqual(capturedLogData, [`${banner}\r\n`]);
|
||||
});
|
||||
|
||||
test("local session captures paste cleanup writes in terminal log data", async () => {
|
||||
const capturedLogData: string[] = [];
|
||||
const writes: string[] = [];
|
||||
let onData: ((data: string) => void) | null = null;
|
||||
|
||||
const terminalBackend = {
|
||||
backendAvailable: () => true,
|
||||
telnetAvailable: () => true,
|
||||
moshAvailable: () => true,
|
||||
localAvailable: () => true,
|
||||
serialAvailable: () => true,
|
||||
execAvailable: () => true,
|
||||
startSSHSession: async () => "ssh-session",
|
||||
startTelnetSession: async () => "telnet-session",
|
||||
startMoshSession: async () => "mosh-session",
|
||||
startLocalSession: async () => "local-session",
|
||||
startSerialSession: async () => "serial-session",
|
||||
execCommand: async () => ({}),
|
||||
onSessionData: (_id: string, cb: (data: string) => void) => {
|
||||
onData = cb;
|
||||
return noop;
|
||||
},
|
||||
onSessionExit: () => noop,
|
||||
onChainProgress: () => noop,
|
||||
writeToSession: noop,
|
||||
resizeSession: noop,
|
||||
};
|
||||
|
||||
const ctx = {
|
||||
host: {
|
||||
id: "local-host",
|
||||
label: "Local",
|
||||
hostname: "local",
|
||||
username: "",
|
||||
protocol: "local",
|
||||
},
|
||||
keys: [],
|
||||
resolvedChainHosts: [],
|
||||
sessionId: "session-1",
|
||||
terminalSettings: {},
|
||||
terminalBackend,
|
||||
sessionRef: { current: null },
|
||||
hasConnectedRef: { current: false },
|
||||
hasRunStartupCommandRef: { current: false },
|
||||
disposeDataRef: { current: null },
|
||||
disposeExitRef: { current: null },
|
||||
fitAddonRef: { current: null },
|
||||
serializeAddonRef: { current: null },
|
||||
pendingAuthRef: { current: null },
|
||||
updateStatus: noop,
|
||||
setStatus: noop,
|
||||
setError: noop,
|
||||
setNeedsAuth: noop,
|
||||
setAuthRetryMessage: noop,
|
||||
setAuthPassword: noop,
|
||||
setProgressLogs: noop,
|
||||
setProgressValue: noop,
|
||||
setChainProgress: noop,
|
||||
onTerminalLogData: (data: string) => capturedLogData.push(data),
|
||||
};
|
||||
|
||||
const term = {
|
||||
cols: 20,
|
||||
rows: 4,
|
||||
paste: noop,
|
||||
write: (data: string, callback?: () => void) => {
|
||||
writes.push(data);
|
||||
callback?.();
|
||||
},
|
||||
writeln: noop,
|
||||
scrollToBottom: noop,
|
||||
};
|
||||
|
||||
const longPaste = Array.from({ length: 20 }, (_, index) => `line ${index} with enough content`).join("\n");
|
||||
pasteTextIntoTerminal(term, longPaste, { scrollOnPaste: false });
|
||||
await createTerminalSessionStarters(ctx as never).startLocal(term as never);
|
||||
|
||||
assert.notEqual(onData, null);
|
||||
onData?.("\x1b[7mline 3 with enough content\x1b[27m");
|
||||
|
||||
assert.deepEqual(writes, ["line 3 with enough content", "\x1b[K"]);
|
||||
assert.deepEqual(capturedLogData, ["line 3 with enough content", "\x1b[K"]);
|
||||
});
|
||||
|
||||
test("startSSH allows jump hosts that use reference key files with unavailable saved passphrases", async () => {
|
||||
let capturedOptions: Record<string, unknown> | null = null;
|
||||
let error = "";
|
||||
|
||||
@@ -153,6 +153,7 @@ export type TerminalSessionStartersContext = {
|
||||
onSessionAttached?: (sessionId: string) => void;
|
||||
onSessionExit?: (sessionId: string, evt: { exitCode?: number; signal?: number; error?: string; reason?: "exited" | "error" | "timeout" | "closed" }) => void;
|
||||
onTerminalDataCapture?: (sessionId: string, data: string) => void;
|
||||
onTerminalLogData?: (data: string) => void;
|
||||
onOsDetected?: (hostId: string, distro: string) => void;
|
||||
onCommandExecuted?: (
|
||||
command: string,
|
||||
@@ -205,22 +206,38 @@ const handleTerminalOutputAutoScroll = (
|
||||
term.scrollToBottom();
|
||||
};
|
||||
|
||||
const writeTerminalLine = (
|
||||
ctx: TerminalSessionStartersContext,
|
||||
term: XTerm,
|
||||
data: string,
|
||||
) => {
|
||||
ctx.onTerminalLogData?.(`${data}\r\n`);
|
||||
term.writeln(data);
|
||||
};
|
||||
|
||||
const writeSessionData = (
|
||||
ctx: TerminalSessionStartersContext,
|
||||
term: XTerm,
|
||||
data: string,
|
||||
) => {
|
||||
const displayData = prepareTerminalDataForUserPasteDisplay(term, data);
|
||||
ctx.onTerminalLogData?.(displayData);
|
||||
const clearPasteResidualAndCapture = () => {
|
||||
const cleanupData = clearPasteResidualAfterTerminalWrite(term);
|
||||
if (cleanupData) {
|
||||
ctx.onTerminalLogData?.(cleanupData);
|
||||
}
|
||||
};
|
||||
const settings = ctx.terminalSettingsRef?.current ?? ctx.terminalSettings;
|
||||
if (!shouldScrollOnTerminalOutput(settings)) {
|
||||
term.write(displayData, () => {
|
||||
clearPasteResidualAfterTerminalWrite(term);
|
||||
clearPasteResidualAndCapture();
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
term.write(displayData, () => {
|
||||
clearPasteResidualAfterTerminalWrite(term);
|
||||
clearPasteResidualAndCapture();
|
||||
handleTerminalOutputAutoScroll(ctx, term);
|
||||
});
|
||||
};
|
||||
@@ -271,7 +288,8 @@ const attachSessionToTerminal = (
|
||||
if (evt.error) {
|
||||
ctx.setError(evt.error);
|
||||
}
|
||||
term.writeln(opts?.onExitMessage?.(evt) ?? "\r\n[session closed]");
|
||||
const exitMessage = opts?.onExitMessage?.(evt) ?? "\r\n[session closed]";
|
||||
writeTerminalLine(ctx, term, exitMessage);
|
||||
|
||||
if (ctx.onTerminalDataCapture && ctx.serializeAddonRef.current) {
|
||||
try {
|
||||
@@ -392,7 +410,9 @@ export const createTerminalSessionStarters = (ctx: TerminalSessionStartersContex
|
||||
const startSSH = async (term: XTerm) => {
|
||||
if (!ctx.terminalBackend.backendAvailable()) {
|
||||
ctx.setError("Native SSH bridge unavailable. Launch via Electron app.");
|
||||
term.writeln(
|
||||
writeTerminalLine(
|
||||
ctx,
|
||||
term,
|
||||
"\r\n[netcatty SSH bridge unavailable. Please run the desktop build to connect.]",
|
||||
);
|
||||
ctx.updateStatus("disconnected");
|
||||
@@ -412,7 +432,7 @@ export const createTerminalSessionStarters = (ctx: TerminalSessionStartersContex
|
||||
ctx.setNeedsAuth(false);
|
||||
ctx.setAuthRetryMessage(null);
|
||||
ctx.setError(message);
|
||||
term.writeln(`\r\n[${message}]`);
|
||||
writeTerminalLine(ctx, term, `\r\n[${message}]`);
|
||||
ctx.updateStatus("disconnected");
|
||||
return;
|
||||
}
|
||||
@@ -455,7 +475,7 @@ export const createTerminalSessionStarters = (ctx: TerminalSessionStartersContex
|
||||
if (ctx.host.proxyProfileId && !ctx.host.proxyConfig) {
|
||||
const message = `Saved proxy for host "${ctx.host.label || ctx.host.hostname}" is missing. Open host settings and select a valid proxy.`;
|
||||
ctx.setError(message);
|
||||
term.writeln(`\r\n[${message}]`);
|
||||
writeTerminalLine(ctx, term, `\r\n[${message}]`);
|
||||
ctx.updateStatus("disconnected");
|
||||
return;
|
||||
}
|
||||
@@ -475,7 +495,7 @@ export const createTerminalSessionStarters = (ctx: TerminalSessionStartersContex
|
||||
if (unresolvedJumpProxyHost) {
|
||||
const message = `Saved proxy for jump host "${unresolvedJumpProxyHost.label || unresolvedJumpProxyHost.hostname}" is missing. Open host settings and select a valid proxy.`;
|
||||
ctx.setError(message);
|
||||
term.writeln(`\r\n[${message}]`);
|
||||
writeTerminalLine(ctx, term, `\r\n[${message}]`);
|
||||
ctx.updateStatus("disconnected");
|
||||
return;
|
||||
}
|
||||
@@ -563,7 +583,7 @@ export const createTerminalSessionStarters = (ctx: TerminalSessionStartersContex
|
||||
ctx.setNeedsAuth(false);
|
||||
ctx.setAuthRetryMessage(null);
|
||||
ctx.setError(message);
|
||||
term.writeln(`\r\n[${message}]`);
|
||||
writeTerminalLine(ctx, term, `\r\n[${message}]`);
|
||||
ctx.updateStatus("disconnected");
|
||||
return;
|
||||
}
|
||||
@@ -582,7 +602,7 @@ export const createTerminalSessionStarters = (ctx: TerminalSessionStartersContex
|
||||
ctx.setNeedsAuth(false);
|
||||
ctx.setAuthRetryMessage(null);
|
||||
ctx.setError(message);
|
||||
term.writeln(`\r\n[${message}]`);
|
||||
writeTerminalLine(ctx, term, `\r\n[${message}]`);
|
||||
ctx.updateStatus("disconnected");
|
||||
return;
|
||||
}
|
||||
@@ -823,7 +843,7 @@ export const createTerminalSessionStarters = (ctx: TerminalSessionStartersContex
|
||||
ctx.setStatus("connecting");
|
||||
} else {
|
||||
ctx.setError(message);
|
||||
term.writeln(`\r\n[Failed to start SSH: ${message}]`);
|
||||
writeTerminalLine(ctx, term, `\r\n[Failed to start SSH: ${message}]`);
|
||||
ctx.updateStatus("disconnected");
|
||||
}
|
||||
|
||||
@@ -835,7 +855,7 @@ export const createTerminalSessionStarters = (ctx: TerminalSessionStartersContex
|
||||
const startTelnet = async (term: XTerm) => {
|
||||
if (!ctx.terminalBackend.telnetAvailable()) {
|
||||
ctx.setError("Telnet bridge unavailable. Please run the desktop build.");
|
||||
term.writeln("\r\n[Telnet bridge unavailable. Please run the desktop build.]");
|
||||
writeTerminalLine(ctx, term, "\r\n[Telnet bridge unavailable. Please run the desktop build.]");
|
||||
ctx.updateStatus("disconnected");
|
||||
return;
|
||||
}
|
||||
@@ -843,7 +863,7 @@ export const createTerminalSessionStarters = (ctx: TerminalSessionStartersContex
|
||||
if (ctx.host.proxyProfileId && !ctx.host.proxyConfig) {
|
||||
const message = `Saved proxy for host "${ctx.host.label || ctx.host.hostname}" is missing. Open host settings and select a valid proxy.`;
|
||||
ctx.setError(message);
|
||||
term.writeln(`\r\n[${message}]`);
|
||||
writeTerminalLine(ctx, term, `\r\n[${message}]`);
|
||||
ctx.updateStatus("disconnected");
|
||||
return;
|
||||
}
|
||||
@@ -851,7 +871,7 @@ export const createTerminalSessionStarters = (ctx: TerminalSessionStartersContex
|
||||
if (ctx.host.proxyConfig?.host && ctx.host.proxyConfig?.port) {
|
||||
const message = "Telnet does not support proxy connections. Use SSH for this host or remove the proxy from this connection.";
|
||||
ctx.setError(message);
|
||||
term.writeln(`\r\n[${message}]`);
|
||||
writeTerminalLine(ctx, term, `\r\n[${message}]`);
|
||||
ctx.updateStatus("disconnected");
|
||||
return;
|
||||
}
|
||||
@@ -887,7 +907,7 @@ export const createTerminalSessionStarters = (ctx: TerminalSessionStartersContex
|
||||
ctx.setNeedsAuth(false);
|
||||
ctx.setAuthRetryMessage(null);
|
||||
ctx.setError(message);
|
||||
term.writeln(`\r\n[${message}]`);
|
||||
writeTerminalLine(ctx, term, `\r\n[${message}]`);
|
||||
ctx.updateStatus("disconnected");
|
||||
return;
|
||||
}
|
||||
@@ -928,24 +948,24 @@ export const createTerminalSessionStarters = (ctx: TerminalSessionStartersContex
|
||||
});
|
||||
telnetSessionId = id;
|
||||
|
||||
attachSessionToTerminal(ctx, term, id, {
|
||||
onExitMessage: (evt) =>
|
||||
`\r\n[Telnet session closed${evt?.exitCode !== undefined ? ` (code ${evt.exitCode})` : ""}]`,
|
||||
onExit: cleanupTelnetStartupWait,
|
||||
});
|
||||
const disposeTelnetExit = ctx.disposeExitRef.current;
|
||||
ctx.disposeExitRef.current = () => {
|
||||
cleanupTelnetStartupWait();
|
||||
disposeTelnetExit?.();
|
||||
};
|
||||
if (waitsForAutoLogin) {
|
||||
return;
|
||||
}
|
||||
} catch (err) {
|
||||
cleanupTelnetStartupWait();
|
||||
attachSessionToTerminal(ctx, term, id, {
|
||||
onExitMessage: (evt) =>
|
||||
`\r\n[Telnet session closed${evt?.exitCode !== undefined ? ` (code ${evt.exitCode})` : ""}]`,
|
||||
onExit: cleanupTelnetStartupWait,
|
||||
});
|
||||
const disposeTelnetExit = ctx.disposeExitRef.current;
|
||||
ctx.disposeExitRef.current = () => {
|
||||
cleanupTelnetStartupWait();
|
||||
disposeTelnetExit?.();
|
||||
};
|
||||
if (waitsForAutoLogin) {
|
||||
return;
|
||||
}
|
||||
} catch (err) {
|
||||
cleanupTelnetStartupWait();
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
ctx.setError(message);
|
||||
term.writeln(`\r\n[Failed to start Telnet: ${message}]`);
|
||||
writeTerminalLine(ctx, term, `\r\n[Failed to start Telnet: ${message}]`);
|
||||
ctx.updateStatus("disconnected");
|
||||
}
|
||||
};
|
||||
@@ -953,7 +973,7 @@ export const createTerminalSessionStarters = (ctx: TerminalSessionStartersContex
|
||||
const startMosh = async (term: XTerm) => {
|
||||
if (!ctx.terminalBackend.moshAvailable()) {
|
||||
ctx.setError("Mosh bridge unavailable. Please run the desktop build.");
|
||||
term.writeln("\r\n[Mosh bridge unavailable. Please run the desktop build.]");
|
||||
writeTerminalLine(ctx, term, "\r\n[Mosh bridge unavailable. Please run the desktop build.]");
|
||||
ctx.updateStatus("disconnected");
|
||||
return;
|
||||
}
|
||||
@@ -961,7 +981,7 @@ export const createTerminalSessionStarters = (ctx: TerminalSessionStartersContex
|
||||
try {
|
||||
const stopMosh = (message: string) => {
|
||||
ctx.setError(message);
|
||||
term.writeln(`\r\n[${message}]`);
|
||||
writeTerminalLine(ctx, term, `\r\n[${message}]`);
|
||||
ctx.updateStatus("disconnected");
|
||||
};
|
||||
|
||||
@@ -1074,7 +1094,7 @@ export const createTerminalSessionStarters = (ctx: TerminalSessionStartersContex
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
ctx.setError(message);
|
||||
term.writeln(`\r\n[Failed to start Mosh: ${message}]`);
|
||||
writeTerminalLine(ctx, term, `\r\n[Failed to start Mosh: ${message}]`);
|
||||
ctx.updateStatus("disconnected");
|
||||
}
|
||||
};
|
||||
@@ -1082,7 +1102,9 @@ export const createTerminalSessionStarters = (ctx: TerminalSessionStartersContex
|
||||
const startLocal = async (term: XTerm) => {
|
||||
if (!ctx.terminalBackend.localAvailable()) {
|
||||
ctx.setError("Local shell bridge unavailable. Please run the desktop build.");
|
||||
term.writeln(
|
||||
writeTerminalLine(
|
||||
ctx,
|
||||
term,
|
||||
"\r\n[Local shell bridge unavailable. Please run the desktop build to spawn a local terminal.]",
|
||||
);
|
||||
ctx.updateStatus("disconnected");
|
||||
@@ -1133,9 +1155,8 @@ export const createTerminalSessionStarters = (ctx: TerminalSessionStartersContex
|
||||
|
||||
ctx.disposeExitRef.current = ctx.terminalBackend.onSessionExit(id, (evt) => {
|
||||
ctx.updateStatus("disconnected");
|
||||
term.writeln(
|
||||
`\r\n[session closed${evt?.exitCode !== undefined ? ` (code ${evt.exitCode})` : ""}]`,
|
||||
);
|
||||
const exitMessage = `\r\n[session closed${evt?.exitCode !== undefined ? ` (code ${evt.exitCode})` : ""}]`;
|
||||
writeTerminalLine(ctx, term, exitMessage);
|
||||
|
||||
logger.info("[Terminal] Session exit, capturing data", {
|
||||
sessionId: ctx.sessionId,
|
||||
@@ -1161,7 +1182,7 @@ export const createTerminalSessionStarters = (ctx: TerminalSessionStartersContex
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
ctx.setError(message);
|
||||
term.writeln(`\r\n[Failed to start local shell: ${message}]`);
|
||||
writeTerminalLine(ctx, term, `\r\n[Failed to start local shell: ${message}]`);
|
||||
ctx.updateStatus("disconnected");
|
||||
}
|
||||
};
|
||||
@@ -1170,7 +1191,7 @@ export const createTerminalSessionStarters = (ctx: TerminalSessionStartersContex
|
||||
const startSerial = async (term: XTerm) => {
|
||||
if (!ctx.serialConfig) {
|
||||
ctx.setError("No serial configuration provided");
|
||||
term.writeln("\r\n[Error: No serial configuration provided]");
|
||||
writeTerminalLine(ctx, term, "\r\n[Error: No serial configuration provided]");
|
||||
ctx.updateStatus("disconnected");
|
||||
return;
|
||||
}
|
||||
@@ -1197,7 +1218,7 @@ export const createTerminalSessionStarters = (ctx: TerminalSessionStartersContex
|
||||
// Update status right away since serial ports don't require handshake
|
||||
ctx.updateStatus("connected");
|
||||
ctx.setProgressValue(100);
|
||||
term.writeln(`[Connected to ${ctx.serialConfig.path} at ${ctx.serialConfig.baudRate} baud]`);
|
||||
writeTerminalLine(ctx, term, `[Connected to ${ctx.serialConfig.path} at ${ctx.serialConfig.baudRate} baud]`);
|
||||
|
||||
attachSessionToTerminal(ctx, term, id, {
|
||||
onExitMessage: (evt) =>
|
||||
@@ -1208,7 +1229,7 @@ export const createTerminalSessionStarters = (ctx: TerminalSessionStartersContex
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
ctx.setError(message);
|
||||
term.writeln(`\r\n[Failed to connect to serial port: ${message}]`);
|
||||
writeTerminalLine(ctx, term, `\r\n[Failed to connect to serial port: ${message}]`);
|
||||
ctx.updateStatus("disconnected");
|
||||
}
|
||||
};
|
||||
|
||||
@@ -114,6 +114,7 @@ export type CreateXTermRuntimeContext = {
|
||||
serialLocalEcho?: boolean;
|
||||
serialLineMode?: boolean;
|
||||
serialLineBufferRef?: RefObject<string>;
|
||||
onTerminalLogData?: (data: string) => void;
|
||||
|
||||
// Callback when shell reports CWD change via OSC 7
|
||||
onCwdChange?: (cwd: string) => void;
|
||||
@@ -614,6 +615,11 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime
|
||||
fitAddon.fit();
|
||||
term.focus();
|
||||
|
||||
const writeLocalTerminalData = (nextData: string) => {
|
||||
ctx.onTerminalLogData?.(nextData);
|
||||
term.write(nextData);
|
||||
};
|
||||
|
||||
term.onData((data) => {
|
||||
const id = ctx.sessionRef.current;
|
||||
if (id) {
|
||||
@@ -623,7 +629,7 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime
|
||||
bufferRef: ctx.serialLineBufferRef,
|
||||
localEcho: ctx.serialLocalEcho,
|
||||
writeToSession: (nextData) => ctx.terminalBackend.writeToSession(id, nextData),
|
||||
writeToTerminal: (nextData) => term.write(nextData),
|
||||
writeToTerminal: writeLocalTerminalData,
|
||||
});
|
||||
} else {
|
||||
// Character mode (default): send immediately
|
||||
@@ -637,13 +643,13 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime
|
||||
// Local echo for serial connections only when explicitly enabled
|
||||
if (ctx.host.protocol === "serial" && ctx.serialLocalEcho) {
|
||||
if (data === "\r") {
|
||||
term.write("\r\n");
|
||||
writeLocalTerminalData("\r\n");
|
||||
} else if (data === "\x7f" || data === "\b") {
|
||||
term.write("\b \b");
|
||||
writeLocalTerminalData("\b \b");
|
||||
} else if (data === "\x03") {
|
||||
term.write("^C");
|
||||
writeLocalTerminalData("^C");
|
||||
} else if (data.charCodeAt(0) >= 32 || data.length > 1) {
|
||||
term.write(data);
|
||||
writeLocalTerminalData(data);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -302,14 +302,16 @@ export function prepareTerminalDataForUserPasteDisplay(term: object, data: strin
|
||||
return data;
|
||||
}
|
||||
|
||||
export function clearPasteResidualAfterTerminalWrite(term: object): void {
|
||||
export function clearPasteResidualAfterTerminalWrite(term: object): string | null {
|
||||
const state = pasteDisplayStates.get(term);
|
||||
if (!isStateActive(state)) return;
|
||||
if (state.clearPending <= 0) return;
|
||||
if (typeof (term as Partial<Pick<XTerm, "write">>).write !== "function") return;
|
||||
if (!isStateActive(state)) return null;
|
||||
if (state.clearPending <= 0) return null;
|
||||
if (typeof (term as Partial<Pick<XTerm, "write">>).write !== "function") return null;
|
||||
|
||||
// Readline can leave stale cells to the right of the cursor after very long
|
||||
// bracketed paste redraws; clear them locally without sending bytes upstream.
|
||||
state.clearPending -= 1;
|
||||
(term as Pick<XTerm, "write">).write("\x1b[K");
|
||||
const cleanupData = "\x1b[K";
|
||||
(term as Pick<XTerm, "write">).write(cleanupData);
|
||||
return cleanupData;
|
||||
}
|
||||
Reference in new issue
Block a user