From 67f8108713e43603bf2266a5f3a87d5424d4e2ad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=A4=A7=E7=8C=AB?= <16399091+binaricat@users.noreply.github.com> Date: Thu, 23 Jul 2026 09:42:47 +0800 Subject: [PATCH] feat(plugins): add reviewed privileged terminal data pipeline (#2402) * feat(plugins): add privileged terminal data pipeline * fix(plugins): harden terminal interceptor lifecycle * fix(plugins): close terminal interceptor lifecycle gaps * fix(plugins): preserve terminal interceptor state transitions * fix(plugin): close terminal pipeline lifecycle gaps * fix(plugin): harden terminal interceptor startup * fix(plugin): isolate terminal output route attempts * fix(plugin): isolate reused terminal sessions * fix(plugin): harden terminal interceptor boundaries * fix(plugin): harden terminal replay metadata * fix(plugin): preserve terminal replay provenance * fix(plugin): close terminal pipeline lifecycle races * fix(plugin): harden terminal route handoff * fix(plugin): contain terminal handoff failures * fix(plugin): route terminal attachment through RPC * fix(plugin): validate terminal attachment RPC * fix(plugin): close unexpected runtime ports * fix(plugin): canonicalize terminal data frames * fix(plugin): close terminal pipeline lifecycle gaps * fix(plugin): close terminal interceptor review gaps * fix(plugin): harden terminal interceptor protocol handling * fix(plugin): preserve terminal flow compatibility * fix(plugin): preserve terminal protocol accounting * fix(plugin): bound terminal interceptor lifecycle * fix(plugin): close terminal interceptor review gaps --------- Co-authored-by: ryan-wong-coder --- .../usePluginTerminalSessionLifecycle.test.ts | 36 + .../usePluginTerminalSessionLifecycle.ts | 49 +- components/Terminal.tsx | 120 ++- components/TerminalLayer.tsx | 16 +- components/scripts/ScriptDialogHost.tsx | 1 + .../terminal/clipboardImagePaste.test.ts | 10 +- components/terminal/clipboardImagePaste.ts | 8 +- .../hooks/useTerminalContextActions.ts | 25 +- .../terminal/hooks/useTerminalDragDrop.ts | 11 +- .../terminal/hooks/useTerminalFilePaste.ts | 6 +- .../createTerminalSessionStarters.test.ts | 43 + .../runtime/createTerminalSessionStarters.ts | 10 +- .../createTerminalSessionStarters.types.ts | 8 +- .../terminal/runtime/createXTermRuntime.ts | 38 +- .../runtime/kittyKeyboardBroadcast.test.ts | 31 + .../runtime/kittyKeyboardBroadcast.ts | 5 + .../terminalInterceptorInputSafety.test.ts | 133 +++ .../runtime/terminalSensitiveInputRegistry.ts | 15 + .../runtime/terminalSessionAttachment.test.ts | 23 +- .../runtime/terminalSessionAttachment.ts | 78 +- .../runtime/terminalWriteQueue.test.ts | 14 + .../terminal/runtime/terminalWriteQueue.ts | 16 +- .../terminal/terminalClipboardPaste.test.ts | 13 +- components/terminal/terminalClipboardPaste.ts | 8 +- .../useTerminalContextActions.test.ts | 16 + components/terminal/useTerminalEffects.ts | 26 +- docs/plugin-platform/contract-and-sdk.md | 12 +- docs/plugin-platform/isolated-runtime.md | 11 +- .../runtime-extension-boundaries.md | 9 +- .../security-and-permissions.md | 2 + docs/plugin-platform/terminal-providers.md | 97 ++ docs/plugin-platform/threat-model.md | 18 +- electron/bridges/emitTerminalSessionData.cjs | 20 +- .../bridges/emitTerminalSessionData.test.cjs | 46 + electron/bridges/scriptBridge.cjs | 1 + electron/bridges/sshBridge/startSession.cjs | 72 +- electron/bridges/terminalAttachRestore.cjs | 17 +- electron/bridges/terminalBridge.cjs | 166 +++- .../terminalBridge.rebindOutput.test.cjs | 91 +- ...erminalBridge.terminalInterceptor.test.cjs | 132 +++ electron/bridges/terminalBridge/etSession.cjs | 17 +- .../bridges/terminalBridge/moshSession.cjs | 16 +- .../bridges/terminalBridge/telnetSession.cjs | 38 +- electron/bridges/terminalOutputChannel.cjs | 16 +- .../bridges/terminalOutputChannel.test.cjs | 21 + electron/bridges/terminalReportSequence.cjs | 25 + .../bridges/terminalReportSequence.test.cjs | 29 + electron/bridges/terminalWorkerManager.cjs | 318 +++++- .../bridges/terminalWorkerManager.test.cjs | 604 +++++++++++- electron/main/registerBridges.cjs | 49 + electron/plugins/contractValidator.cjs | 32 + .../generated/plugin-contract.schema.json | 342 +++++++ electron/plugins/hostService.cjs | 13 + electron/plugins/hostService.test.cjs | 48 + electron/plugins/nativePermissionDecision.cjs | 16 +- .../plugins/nativePermissionDecision.test.cjs | 27 + electron/plugins/permissionEngine.cjs | 90 +- electron/plugins/permissionEngine.test.cjs | 78 ++ electron/plugins/pluginBridge.cjs | 15 +- electron/plugins/pluginBridge.test.cjs | 11 + electron/plugins/rpcRouter.cjs | 12 +- electron/plugins/rpcRouter.test.cjs | 37 +- electron/plugins/runtime/runtimePeer.mjs | 165 +++- .../runtimePeer.terminalInterceptor.test.cjs | 476 +++++++++ electron/plugins/runtimeSupervisor.cjs | 20 +- electron/plugins/runtimeSupervisor.test.cjs | 47 + .../plugins/terminalDataPipelineService.cjs | 729 ++++++++++++++ .../terminalDataPipelineService.test.cjs | 920 ++++++++++++++++++ .../plugins/terminalInterceptorMessages.cjs | 63 ++ .../terminalInterceptorMessages.test.cjs | 47 + .../plugins/terminalInterceptorTransport.cjs | 70 ++ .../terminalInterceptorTransport.test.cjs | 124 +++ electron/plugins/utilityPluginRuntime.cjs | 19 + .../plugins/utilityPluginRuntime.test.cjs | 92 ++ electron/preload.cjs | 74 +- electron/preload/api.cjs | 16 +- electron/preload/terminalDataBacklog.cjs | 33 +- electron/preload/terminalDataMeta.cjs | 25 + electron/preload/terminalOutputPorts.cjs | 7 +- electron/preloadDataBacklog.test.cjs | 243 +++++ electron/scripts/scriptCodegen.cjs | 4 +- electron/scripts/scriptRuntime.cjs | 29 +- electron/scripts/scriptRuntime.test.cjs | 45 + electron/scripts/sessionOutputBuffer.test.cjs | 4 +- electron/terminalWorker/process.cjs | 15 +- electron/terminalWorker/process.test.cjs | 6 +- electron/terminalWorker/runtime.cjs | 305 ++++-- electron/terminalWorker/runtime.test.cjs | 623 ++++++++++++ .../terminalWorker/terminalDataPipeline.cjs | 416 ++++++++ .../terminalDataPipeline.test.cjs | 459 +++++++++ packages/plugin-cli/src/manifest.ts | 7 + .../schema/plugin-contract.schema.json | 167 +++- packages/plugin-contract/src/contract.test.ts | 111 ++- .../src/generated/plugin-contract-limits.ts | 2 + .../src/generated/plugin-contract.ts | 87 +- packages/plugin-contract/src/index.ts | 2 + packages/plugin-sdk/src/index.test.ts | 16 + packages/plugin-sdk/src/index.ts | 54 +- scripts/generate-plugin-contract.mjs | 21 + types/global/netcatty-bridge-script.d.ts | 1 + types/global/netcatty-bridge-session.d.ts | 20 + 101 files changed, 8475 insertions(+), 396 deletions(-) create mode 100644 components/terminal/runtime/terminalInterceptorInputSafety.test.ts create mode 100644 components/terminal/runtime/terminalSensitiveInputRegistry.ts create mode 100644 electron/bridges/terminalBridge.terminalInterceptor.test.cjs create mode 100644 electron/bridges/terminalReportSequence.cjs create mode 100644 electron/bridges/terminalReportSequence.test.cjs create mode 100644 electron/plugins/runtime/runtimePeer.terminalInterceptor.test.cjs create mode 100644 electron/plugins/terminalDataPipelineService.cjs create mode 100644 electron/plugins/terminalDataPipelineService.test.cjs create mode 100644 electron/plugins/terminalInterceptorMessages.cjs create mode 100644 electron/plugins/terminalInterceptorMessages.test.cjs create mode 100644 electron/plugins/terminalInterceptorTransport.cjs create mode 100644 electron/plugins/terminalInterceptorTransport.test.cjs create mode 100644 electron/terminalWorker/terminalDataPipeline.cjs create mode 100644 electron/terminalWorker/terminalDataPipeline.test.cjs diff --git a/application/state/usePluginTerminalSessionLifecycle.test.ts b/application/state/usePluginTerminalSessionLifecycle.test.ts index 640ada7cf..5dae4957e 100644 --- a/application/state/usePluginTerminalSessionLifecycle.test.ts +++ b/application/state/usePluginTerminalSessionLifecycle.test.ts @@ -2,10 +2,24 @@ import assert from 'node:assert/strict'; import test from 'node:test'; import { + beginPluginTerminalSessionMountLifecycle, normalizePluginTerminalProtocol, + ownsPluginTerminalBackendLifecycle, + shouldPublishPluginTerminalSessionMountLifecycle, + shouldPublishPluginTerminalEvent, transitionPluginTerminalConnectionState, } from './usePluginTerminalSessionLifecycle.ts'; +test('an attached renderer does not claim creation or disposal of the reused backend session', () => { + assert.equal(ownsPluginTerminalBackendLifecycle(undefined), true); + assert.equal(ownsPluginTerminalBackendLifecycle(true), true); + assert.equal(ownsPluginTerminalBackendLifecycle(false), false); + for (const type of ['created', 'connected', 'reconnected', 'disconnected', 'disposed'] as const) { + assert.equal(shouldPublishPluginTerminalEvent(type, false), false); + } + assert.equal(shouldPublishPluginTerminalEvent('resized', false), true); +}); + const connectedState = { cwd: '/srv/old', title: 'old backend', @@ -90,3 +104,25 @@ test('terminal lifecycle snapshots preserve dynamic protocol identifiers', () => assert.equal(normalizePluginTerminalProtocol('mosh'), 'mosh'); assert.equal(normalizePluginTerminalProtocol(undefined), 'ssh'); }); + +test('an attach popup does not publish backend session mount or disposal lifecycle', () => { + assert.equal(shouldPublishPluginTerminalSessionMountLifecycle(true), false); + assert.equal(shouldPublishPluginTerminalSessionMountLifecycle(false), true); + + const events: string[] = []; + const cleanup = beginPluginTerminalSessionMountLifecycle( + shouldPublishPluginTerminalSessionMountLifecycle(true), + () => events.push('created'), + () => events.push('disposed'), + ); + cleanup?.(); + assert.deepEqual(events, []); + + const ownerCleanup = beginPluginTerminalSessionMountLifecycle( + shouldPublishPluginTerminalSessionMountLifecycle(false), + () => events.push('created'), + () => events.push('disposed'), + ); + ownerCleanup?.(); + assert.deepEqual(events, ['created', 'disposed']); +}); diff --git a/application/state/usePluginTerminalSessionLifecycle.ts b/application/state/usePluginTerminalSessionLifecycle.ts index 0a9fa921d..c1d5a5cba 100644 --- a/application/state/usePluginTerminalSessionLifecycle.ts +++ b/application/state/usePluginTerminalSessionLifecycle.ts @@ -10,6 +10,7 @@ interface PluginTerminalSessionLifecycleOptions { status: 'connecting' | 'connected' | 'disconnected'; shellType?: string; initialCwd?: string; + ownsBackendLifecycle?: boolean; } export interface PluginTerminalSnapshotState { @@ -68,6 +69,38 @@ export function normalizePluginTerminalProtocol( return normalized || 'ssh'; } +export function shouldPublishPluginTerminalSessionMountLifecycle( + attachExistingSession: boolean, +): boolean { + return !attachExistingSession; +} + +export function beginPluginTerminalSessionMountLifecycle( + ownsBackendSessionMount: boolean, + publishCreated: () => void, + disposeBackendSession: () => void, +): (() => void) | undefined { + if (!ownsBackendSessionMount) return undefined; + publishCreated(); + return disposeBackendSession; +} + +export function ownsPluginTerminalBackendLifecycle(value: boolean | undefined): boolean { + return value !== false; +} + +const BACKEND_LIFECYCLE_EVENTS = new Set([ + 'created', 'connected', 'reconnected', 'disconnected', 'disposed', +]); + +export function shouldPublishPluginTerminalEvent( + type: NetcattyTerminalSessionEvent['type'], + ownsBackendLifecycle: boolean | undefined, +): boolean { + return ownsPluginTerminalBackendLifecycle(ownsBackendLifecycle) + || !BACKEND_LIFECYCLE_EVENTS.has(type); +} + function normalizeShellType(shellType: string | undefined): NetcattyTerminalSessionSnapshot['shellType'] | undefined { if (shellType === 'posix' || shellType === 'fish' || shellType === 'powershell' || shellType === 'cmd') { return shellType; @@ -108,6 +141,7 @@ export function usePluginTerminalSessionLifecycle(options: PluginTerminalSession sessionOverrides: Partial = {}, ) => { if (!registry) return; + if (!shouldPublishPluginTerminalEvent(type, metadataRef.current.ownsBackendLifecycle)) return; void registry.publishSessionEvent({ type, session: { ...snapshot(), ...sessionOverrides }, @@ -116,12 +150,15 @@ export function usePluginTerminalSessionLifecycle(options: PluginTerminalSession }, [registry, snapshot]); useEffect(() => { - publish('created'); - return () => { - publish('disposed'); - registry?.cancelSession(metadataRef.current.sessionId); - }; - }, [publish, registry]); + return beginPluginTerminalSessionMountLifecycle( + ownsPluginTerminalBackendLifecycle(options.ownsBackendLifecycle), + () => publish('created'), + () => { + publish('disposed'); + registry?.cancelSession(metadataRef.current.sessionId); + }, + ); + }, [options.ownsBackendLifecycle, publish, registry]); useEffect(() => { const transition = transitionPluginTerminalConnectionState( diff --git a/components/Terminal.tsx b/components/Terminal.tsx index 0d376acff..d5b98d638 100644 --- a/components/Terminal.tsx +++ b/components/Terminal.tsx @@ -64,7 +64,10 @@ import { useStoredBoolean } from "../application/state/useStoredBoolean"; import { readOptionalStoredStringValue, useStoredString } from "../application/state/useStoredString"; import { useSessionLogBackend } from "../application/state/useSessionLogBackend"; import { useTerminalLayoutSuppressActive } from "../application/state/terminalLayoutSuppressStore"; -import { usePluginTerminalSessionLifecycle } from "../application/state/usePluginTerminalSessionLifecycle"; +import { + shouldPublishPluginTerminalSessionMountLifecycle, + usePluginTerminalSessionLifecycle, +} from "../application/state/usePluginTerminalSessionLifecycle"; import { usePluginTerminalProviders } from "../application/state/usePluginTerminalProviders"; import type { PluginTerminalDecorationRule } from "../domain/pluginTerminalProviders"; import { terminalReconnectRegistry } from "../application/state/terminalReconnectRegistry"; @@ -128,6 +131,7 @@ import { type XTermRuntime, } from "./terminal/runtime/createXTermRuntime"; import { clearKittyKeyboardBroadcastSession } from "./terminal/runtime/kittyKeyboardBroadcast"; +import { registerTerminalSensitiveInputReader } from "./terminal/runtime/terminalSensitiveInputRegistry"; import { applyUserCursorPreference } from "./terminal/runtime/cursorPreference"; import { terminalAltKeyOptions } from "./terminal/runtime/altKeyOptions"; import { @@ -334,6 +338,12 @@ const TerminalComponent: React.FC = ({ const recorderRef = useRef(recorder); recorderRef.current = recorder; const passwordPromptActiveRef = useRef(false); + const terminalTitleRef = useRef(undefined); + const pluginTerminalLifecycleRef = useRef | null>(null); + useEffect(() => registerTerminalSensitiveInputReader( + sessionId, + () => passwordPromptActiveRef.current, + ), [sessionId]); const sensitivePromptOutputTailRef = useRef(""); const [activeScriptRun, setActiveScriptRun] = useState(undefined); const dismissedScriptRunIdRef = useRef(null); @@ -782,6 +792,7 @@ const TerminalComponent: React.FC = ({ autocompleteAcceptTextRef.current = (text: string) => { const id = sessionRef.current; if (id && text) { + const sensitive = passwordPromptActiveRef.current; let textToWrite = text; let handledSubmittedInput = false; if ( @@ -799,7 +810,7 @@ const TerminalComponent: React.FC = ({ for (const ch of text) { if (ch === "\r") { const line = serialLineBufferRef.current + "\r"; - terminalBackend.writeToSession(id, line); + terminalBackend.writeToSession(id, line, { sensitive }); serialLineBufferRef.current = ""; if (serialConfig?.localEcho) writeLocalTerminalData("\r\n"); } else if (ch === "\x15") { @@ -821,7 +832,7 @@ const TerminalComponent: React.FC = ({ // (fall through to shared bookkeeping below — don't return early) } else if (host.protocol === "serial" && serialConfig?.localEcho) { // Serial character mode with local echo: echo accepted text locally - terminalBackend.writeToSession(id, textToWrite); + terminalBackend.writeToSession(id, textToWrite, { sensitive }); for (const ch of text) { if (ch === "\r") { writeLocalTerminalData("\r\n"); @@ -830,11 +841,11 @@ const TerminalComponent: React.FC = ({ } } } else { - terminalBackend.writeToSession(id, textToWrite); + terminalBackend.writeToSession(id, textToWrite, { sensitive }); } // Broadcast to other sessions if broadcast mode is enabled - if (isBroadcastEnabledRef.current && onBroadcastInputRef.current) { + if (!sensitive && isBroadcastEnabledRef.current && onBroadcastInputRef.current) { onBroadcastInputRef.current(text, sessionId); } @@ -1311,6 +1322,9 @@ const TerminalComponent: React.FC = ({ xtermRuntimeRef.current?.getKittyKeyboardModeState(), xtermRuntimeRef.current?.getKittyKeyboardProtocolEnabled() ?? kittyKeyboardProtocolEnabledForSession, + passwordPromptActiveRef.current, + knownCwdRef.current ?? null, + terminalTitleRef.current ?? null, ); })); } @@ -1330,6 +1344,21 @@ const TerminalComponent: React.FC = ({ payload.kittyKeyboardProtocolEnabled, ); } + if (typeof payload.passwordPromptActive === "boolean") { + passwordPromptActiveRef.current = payload.passwordPromptActive; + } + if (payload.cwd !== undefined) { + const cwd = terminalCwdTracker.setRendererCwd(payload.cwd); + knownCwdRef.current = cwd; + pluginTerminalLifecycleRef.current?.onCwdChanged(cwd ?? null); + onTerminalCwdChange?.(sessionId, cwd ?? null); + } + if (payload.title !== undefined) { + const title = payload.title || null; + terminalTitleRef.current = title ?? undefined; + pluginTerminalLifecycleRef.current?.onTitleChanged(title); + onTerminalTitleChange?.(sessionId, title); + } if (payload.kittyKeyboardModeState) { xtermRuntimeRef.current?.restoreKittyKeyboardModeState( payload.kittyKeyboardModeState, @@ -1447,6 +1476,9 @@ const TerminalComponent: React.FC = ({ kittyKeyboardModeState: xtermRuntimeRef.current?.getKittyKeyboardModeState(), kittyKeyboardProtocolEnabled: xtermRuntimeRef.current?.getKittyKeyboardProtocolEnabled(), + passwordPromptActive: passwordPromptActiveRef.current, + cwd: knownCwdRef.current ?? null, + title: terminalTitleRef.current ?? null, }, attachAuthorization || "", ); @@ -1587,6 +1619,37 @@ const TerminalComponent: React.FC = ({ clearHibernateRuntimeState(); }, [attachAuthorization, attachExistingSession, clearHibernateRuntimeState, handleTerminalDataCaptureOnce, sessionId, terminalBackend]); + const observeTerminalInputPrompt = useCallback(( + chunk: string, + meta?: TerminalSessionDataMeta, + ) => { + sensitivePromptOutputTailRef.current = appendTerminalPromptSecurityTail( + sensitivePromptOutputTailRef.current, + chunk, + ); + const promptSecurityOptions = { allowHostStyleGreaterThan: isNetworkDevice }; + if (typeof meta?.pluginPipelineSensitiveInput === "boolean") { + passwordPromptActiveRef.current = meta.pluginPipelineSensitiveInput; + if (meta.pluginPipelineSensitiveInput) { + autocompleteCloseRef.current?.(); + } else { + sensitivePromptOutputTailRef.current = ""; + } + return; + } else if (isUntrustedTerminalInputPrompt( + sensitivePromptOutputTailRef.current, + promptSecurityOptions, + )) { + passwordPromptActiveRef.current = true; + autocompleteCloseRef.current?.(); + } else if (isConfirmedTerminalShellPrompt( + sensitivePromptOutputTailRef.current, + promptSecurityOptions, + )) { + passwordPromptActiveRef.current = false; + } + }, [isNetworkDevice]); + const beginHibernatedSessionListeners = useCallback((backendId: string) => { disposeDataRef.current?.(); flushTerminalSessionFlowAck(backendId); @@ -1594,12 +1657,16 @@ const TerminalComponent: React.FC = ({ hibernatePendingBufferRef.current = ""; disposeDataRef.current = terminalBackend.onSessionData( backendId, - (chunk) => { + (chunk, meta) => { + observeTerminalInputPrompt(chunk, meta); hibernatePendingBufferRef.current = appendHibernatePendingBuffer( hibernatePendingBufferRef.current, chunk, ); - ackTerminalSessionFlow(terminalBackend, backendId, chunk.length); + const pluginPipelineIngressBytes = Number.isFinite(meta?.pluginPipelineIngressBytes) + ? Math.max(0, Number(meta.pluginPipelineIngressBytes)) + : chunk.length; + ackTerminalSessionFlow(terminalBackend, backendId, pluginPipelineIngressBytes); }, { replayBacklog: true }, ); @@ -1622,7 +1689,7 @@ const TerminalComponent: React.FC = ({ onSessionExitRef.current?.(sessionId, evt); scheduleAutoReconnect({ evt }); }); - }, [scheduleAutoReconnect, sessionId, terminalBackend]); + }, [observeTerminalInputPrompt, scheduleAutoReconnect, sessionId, terminalBackend]); const clearHibernateRetry = useCallback(() => { if (hibernateRetryTimerRef.current === null) return; @@ -1829,7 +1896,9 @@ const TerminalComponent: React.FC = ({ status, shellType, initialCwd: knownCwdRef.current ?? lastCwd, + ownsBackendLifecycle: shouldPublishPluginTerminalSessionMountLifecycle(attachExistingSession), }); + pluginTerminalLifecycleRef.current = pluginTerminalLifecycle; pluginTerminalSessionExitRef.current = pluginTerminalLifecycle.onSessionExited; const getPluginTerminalSnapshotState = useCallback((): Partial => { const term = termRef.current; @@ -1888,6 +1957,7 @@ const TerminalComponent: React.FC = ({ void refreshProviderOutputs('cwd-changed'); }, [pluginAwareOnTerminalCwdChange, refreshProviderOutputs, sessionId, terminalCwdTracker]); const pluginAwareOnTerminalTitleChange = useCallback((changedSessionId: string, title: string | null) => { + terminalTitleRef.current = title || undefined; pluginTerminalLifecycle.onTitleChanged(title); onTerminalTitleChange?.(changedSessionId, title); }, [onTerminalTitleChange, pluginTerminalLifecycle]); @@ -1986,23 +2056,7 @@ const TerminalComponent: React.FC = ({ }, onTerminalDataCapture: handleTerminalDataCaptureOnce, onTerminalOutput: (chunk: string, meta?: TerminalSessionDataMeta) => { - sensitivePromptOutputTailRef.current = appendTerminalPromptSecurityTail( - sensitivePromptOutputTailRef.current, - chunk, - ); - const promptSecurityOptions = { allowHostStyleGreaterThan: isNetworkDevice }; - if (isUntrustedTerminalInputPrompt( - sensitivePromptOutputTailRef.current, - promptSecurityOptions, - )) { - passwordPromptActiveRef.current = true; - autocompleteCloseRef.current?.(); - } else if (isConfirmedTerminalShellPrompt( - sensitivePromptOutputTailRef.current, - promptSecurityOptions, - )) { - passwordPromptActiveRef.current = false; - } + observeTerminalInputPrompt(chunk, meta); appendOutputTriggerOutputRef.current(chunk, meta); if (onTerminalOutput) { onTerminalOutput(sessionId, chunk); @@ -2442,7 +2496,12 @@ const TerminalComponent: React.FC = ({ }, [activeScriptRun]); const broadcastUserPasteData = useCallback((data: string) => { - if (sessionRef.current && isBroadcastEnabledRef.current && onBroadcastInputRef.current) { + if ( + !passwordPromptActiveRef.current + && sessionRef.current + && isBroadcastEnabledRef.current + && onBroadcastInputRef.current + ) { onBroadcastInputRef.current(data, sessionId); return true; } @@ -2481,7 +2540,8 @@ const TerminalComponent: React.FC = ({ // without re-wrapping. Without broadcasting at all, accepting a snippet in // broadcast mode would clear peer input (the clear keystrokes already go // through the broadcast-aware path) but never send the command. - if (options?.broadcast !== false && isBroadcastEnabledRef.current && onBroadcastInputRef.current) { + const sensitive = passwordPromptActiveRef.current; + if (!sensitive && options?.broadcast !== false && isBroadcastEnabledRef.current && onBroadcastInputRef.current) { onBroadcastInputRef.current(data, sessionId, { noAutoRun, ...(lineDelayMs ? { lineDelayMs } : {}), @@ -2491,6 +2551,7 @@ const TerminalComponent: React.FC = ({ data = prepareProgrammaticSudoInput(data); terminalBackend.writeToSession(id, data, { automated: true, + sensitive, ...(lineDelayMs ? { lineDelayMs } : {}), }); scrollToBottomAfterProgrammaticInput(data); @@ -2532,6 +2593,7 @@ const TerminalComponent: React.FC = ({ normalizeTextOnCopyRef, isBroadcastEnabledRef, onBroadcastInputRef, + passwordPromptActiveRef, isLocalConnection, supportsRemoteImagePaste, terminalBackend, @@ -2906,6 +2968,7 @@ const TerminalComponent: React.FC = ({ status, t, terminalBackend, + isSensitiveInput: () => passwordPromptActiveRef.current, termRef, }); @@ -2915,6 +2978,7 @@ const TerminalComponent: React.FC = ({ termRef, sessionRef, terminalBackend, + isSensitiveInput: () => passwordPromptActiveRef.current, scrollOnPasteRef, onPasteData: broadcastUserPasteData, scrollToBottomAfterProgrammaticInput, @@ -3345,7 +3409,7 @@ const TerminalComponent: React.FC = ({ onWake: wakeFromHibernateRuntime, }); - useTerminalEffects({ CONNECTION_TIMEOUT, Error, XTERM_PERFORMANCE_CONFIG, applyUserCursorPreference, auth, autocompleteCloseRef, autocompleteInputRef, autocompleteKeyEventRef, captureTerminalLogData, chainHosts: resolvedChainHosts, chainProgress, clearTerminalCwd, commandBufferRef, connectionLogBufferRef, containerRef, createPromptLineBreakState, createReplaySafeTerminalLogSanitizer, createXTermRuntime, deferTerminalResizeRef, disableTerminalFontZoomRef, effectiveFontSize, effectiveFontWeight, effectiveTheme, error, executeSnippetCommand, finalizeTerminalLogData, fitAddonRef, fontFamilyId, fontSize, fontWeightFixupDoneRef, forceCloseHibernatedSession, forceSyncRenderAfterResize, handleOsc52ReadRequest, handleTerminalDataCaptureOnce, hasConnectedRef, hasRuntimeRef, host, hotkeySchemeRef, hibernatedRef, identities, inWorkspace, isBootActiveRef, isBroadcastEnabledRef, isComposeBarOpen: effectiveComposeBarOpen, isConnectionAwaitingUserInput, isConnectionPastTcpDial, isFocusMode, isFocused, isLocalConnection, isNetworkDevice, isResizing: deferTerminalResize, isRestoringSelectionRef, isSearchOpen, isSerialConnection, isVisible, isVisibleRef, keyBindingsRef, keys, kittyKeyboardProtocolEnabledForSession, knownCwdRef, lastFittedSizeRef, lastToastedErrorRef, logger, mouseTrackingRef, needsHostKeyVerification, onBroadcastInputRef, onBroadcastInterruptPriorityChange, onCommandExecuted, onCommandSubmitted, onHotkeyActionRef, onOutputTriggerUserInputRef: noteOutputTriggerUserInputRef, onPluginRuntimeCwdChange: pluginAwareOnRuntimeCwdChange, onSnippetShortkeyRef, onSnippetExecutorChange, onTerminalCwdChange, onTerminalTitleChange, onTerminalBell, onTerminalFontSizeChange, paneLayoutKey, passwordPromptActiveRef, pendingAuthRef, pendingOutputScrollRef, pluginDecorationRefreshRef, pluginDecorationRules, pluginDecorationRulesRef, pluginTerminalLifecycle, pluginTerminalProviderRevision, isPluginTerminalProviderAvailable, requestPluginTerminalProviders, prepareRestoredReconnect, prevIsResizingRef, promptLineBreakStateRef, resizeSession, resolveHostAuth, resolvedFontFamily, safeFit, scriptRecorderRef: recorderRef, searchAddonRef, serialConfig, serialLineBufferRef, serializeAddonRef, sessionId, sessionRef, sessionStarters, setError, setHasMouseTracking, setHasSelection, setIsCancelling, setIsDisconnectedDialogDismissed, requestSearchFocus, setNeedsHostKeyVerification, setPendingHostKeyInfo, setPendingHostKeyRequestId, setProgressLogs, setProgressValue, setSelectionOverlayPosition, setShowLogs, setStatus, setTimeLeft, shellType, shouldEnableNativeUserInputAutoScroll, shouldProbeSessionCwd, shouldStartTerminalBackend, attachExistingSession, attachAuthorization, attachHomeWebContentsIdRef, snippetsRef, splitResizeActive: isResizing, status, statusRef, sudoAutofillRef, t, teardown, telnetLocalEchoRef, termRef, terminalAltKeyOptions, terminalBackend, terminalContextActionsRef, terminalCwdTracker, terminalDataCapturedRef, terminalLogSanitizerRef, terminalSettings, terminalSettingsRef, toHostKeyInfo, toast, updateStatus, useEffect, useLayoutEffect, workspaceId, xtermRuntimeRef, zmodem, zmodemToastedRef, restoreState }); + useTerminalEffects({ CONNECTION_TIMEOUT, Error, XTERM_PERFORMANCE_CONFIG, applyUserCursorPreference, auth, autocompleteCloseRef, autocompleteInputRef, autocompleteKeyEventRef, captureTerminalLogData, chainHosts: resolvedChainHosts, chainProgress, clearTerminalCwd, commandBufferRef, connectionLogBufferRef, containerRef, createPromptLineBreakState, createReplaySafeTerminalLogSanitizer, createXTermRuntime, deferTerminalResizeRef, disableTerminalFontZoomRef, effectiveFontSize, effectiveFontWeight, effectiveTheme, error, executeSnippetCommand, finalizeTerminalLogData, fitAddonRef, fontFamilyId, fontSize, fontWeightFixupDoneRef, forceCloseHibernatedSession, forceSyncRenderAfterResize, handleOsc52ReadRequest, handleTerminalDataCaptureOnce, hasConnectedRef, hasRuntimeRef, host, hotkeySchemeRef, hibernatedRef, identities, inWorkspace, isBootActiveRef, isBroadcastEnabledRef, isComposeBarOpen: effectiveComposeBarOpen, isConnectionAwaitingUserInput, isConnectionPastTcpDial, isFocusMode, isFocused, isLocalConnection, isNetworkDevice, isResizing: deferTerminalResize, isRestoringSelectionRef, isSearchOpen, isSerialConnection, isVisible, isVisibleRef, keyBindingsRef, keys, kittyKeyboardProtocolEnabledForSession, knownCwdRef, lastFittedSizeRef, lastToastedErrorRef, logger, mouseTrackingRef, needsHostKeyVerification, onBroadcastInputRef, onBroadcastInterruptPriorityChange, onCommandExecuted, onCommandSubmitted, onHotkeyActionRef, onOutputTriggerUserInputRef: noteOutputTriggerUserInputRef, onPluginRuntimeCwdChange: pluginAwareOnRuntimeCwdChange, onSnippetShortkeyRef, onSnippetExecutorChange, onTerminalCwdChange, onTerminalTitleChange, onTerminalBell, onTerminalFontSizeChange, paneLayoutKey, passwordPromptActiveRef, pendingAuthRef, pendingOutputScrollRef, pluginDecorationRefreshRef, pluginDecorationRules, pluginDecorationRulesRef, pluginTerminalLifecycle, pluginTerminalProviderRevision, isPluginTerminalProviderAvailable, requestPluginTerminalProviders, prepareRestoredReconnect, prevIsResizingRef, promptLineBreakStateRef, resizeSession, resolveHostAuth, resolvedFontFamily, safeFit, scriptRecorderRef: recorderRef, searchAddonRef, serialConfig, serialLineBufferRef, serializeAddonRef, sessionId, sessionRef, sessionStarters, setError, setHasMouseTracking, setHasSelection, setIsCancelling, setIsDisconnectedDialogDismissed, requestSearchFocus, setNeedsHostKeyVerification, setPendingHostKeyInfo, setPendingHostKeyRequestId, setProgressLogs, setProgressValue, setSelectionOverlayPosition, setShowLogs, setStatus, setTimeLeft, shellType, shouldEnableNativeUserInputAutoScroll, shouldProbeSessionCwd, shouldStartTerminalBackend, attachExistingSession, attachAuthorization, attachHomeWebContentsIdRef, snippetsRef, splitResizeActive: isResizing, status, statusRef, sudoAutofillRef, t, teardown, telnetLocalEchoRef, termRef, terminalAltKeyOptions, terminalBackend, terminalContextActionsRef, terminalCwdTracker, terminalDataCapturedRef, terminalLogSanitizerRef, terminalSettings, terminalSettingsRef, terminalTitleRef, toHostKeyInfo, toast, updateStatus, useEffect, useLayoutEffect, workspaceId, xtermRuntimeRef, zmodem, zmodemToastedRef, restoreState }); return ( <> diff --git a/components/TerminalLayer.tsx b/components/TerminalLayer.tsx index 69a92d9c5..f402759d6 100644 --- a/components/TerminalLayer.tsx +++ b/components/TerminalLayer.tsx @@ -39,6 +39,7 @@ import { Host, KnownHost, TerminalSession, Workspace } from '../types'; import { applySessionFontSizeToHost } from '../domain/terminalAppearance'; import { resolveHostAutofillPassword } from '../domain/sshAuth'; import { listPasswordPromptFillCandidates } from '../domain/passwordPromptAssist'; +import { isTerminalSensitiveInputActive } from './terminal/runtime/terminalSensitiveInputRegistry'; import { resolveEffectiveTerminalHost, resolveTerminalChainHosts, @@ -948,8 +949,10 @@ const TerminalLayerInner: React.FC = ({ terminalBackend.interruptSession(session.id); continue; } + if (isTerminalSensitiveInputActive(session.id)) continue; terminalBackend.writeToSession(session.id, data, { automated: true, + sensitive: false, ...(lineDelayMs ? { lineDelayMs } : {}), }); deliveredSessionIds.push(session.id); @@ -1538,6 +1541,7 @@ const TerminalLayerInner: React.FC = ({ : undefined; terminalBackend.writeToSession(sessionId, data, { automated: true, + sensitive: isTerminalSensitiveInputActive(sessionId), ...(lineDelayMs ? { lineDelayMs } : {}), }); // Re-focus the terminal so the user can interact immediately @@ -1688,19 +1692,23 @@ const TerminalLayerInner: React.FC = ({ const payload = text + '\r'; const broadcastEnabled = isBroadcastEnabled?.(activeWorkspace.id); const focusedSessionId = activeWorkspace.focusedSessionId; + const focusedSensitive = focusedSessionId + ? isTerminalSensitiveInputActive(focusedSessionId) + : false; - if (broadcastEnabled) { + if (broadcastEnabled && !focusedSensitive) { const allSessionIds = sessionsRef.current .filter((session) => session.workspaceId === activeWorkspace.id) .map((session) => session.id); for (const sid of allSessionIds) { + if (isTerminalSensitiveInputActive(sid)) continue; const executor = snippetExecutorsRef.current.get(sid); if (executor) { executor(text, false, { broadcast: false }); } else { const session = sessionsRef.current.find((candidate) => candidate.id === sid); if (!session || !canUseDirectSessionWriteFallback(session)) continue; - terminalBackend.writeToSession(sid, payload); + terminalBackend.writeToSession(sid, payload, { sensitive: false }); } } } else { @@ -1716,7 +1724,9 @@ const TerminalLayerInner: React.FC = ({ } else { const session = sessionsRef.current.find((candidate) => candidate.id === targetId); if (!session || !canUseDirectSessionWriteFallback(session)) return; - terminalBackend.writeToSession(targetId, payload); + terminalBackend.writeToSession(targetId, payload, { + sensitive: isTerminalSensitiveInputActive(targetId), + }); } } } diff --git a/components/scripts/ScriptDialogHost.tsx b/components/scripts/ScriptDialogHost.tsx index 507c2dbf0..9a629cfc0 100644 --- a/components/scripts/ScriptDialogHost.tsx +++ b/components/scripts/ScriptDialogHost.tsx @@ -494,6 +494,7 @@ export function ScriptDialogHost() { {request.type === 'prompt' ? ( setPromptValue(event.target.value)} autoFocus diff --git a/components/terminal/clipboardImagePaste.test.ts b/components/terminal/clipboardImagePaste.test.ts index 745c4926b..1fb6fed9d 100644 --- a/components/terminal/clipboardImagePaste.test.ts +++ b/components/terminal/clipboardImagePaste.test.ts @@ -30,7 +30,7 @@ test("remote paths are quoted for shell-safe insertion", () => { }); test("remote clipboard image upload inserts the remote image path without broadcasting", async () => { - const writes: Array<{ sessionId: string; data: string }> = []; + const writes: Array<{ sessionId: string; data: string; sensitive?: boolean }> = []; const scrolled: string[] = []; let focused = false; let closedSftpId: string | undefined; @@ -64,9 +64,14 @@ test("remote clipboard image upload inserts the remote image path without broadc }, createTransferId: () => "transfer-1", getRemoteCwd: async () => "/home/alice/project", + isSensitiveInput: () => true, sessionId: "session-1", terminalBackend: { - writeToSession: (sessionId, data) => writes.push({ sessionId, data }), + writeToSession: (sessionId, data, options) => writes.push({ + sessionId, + data, + sensitive: options?.sensitive, + }), }, term: { focus: () => { @@ -96,6 +101,7 @@ test("remote clipboard image upload inserts the remote image path without broadc { sessionId: "session-1", data: "/home/alice/project/.netcatty-paste-images/shot_1.png", + sensitive: true, }, ]); assert.deepEqual(scrolled, ["/home/alice/project/.netcatty-paste-images/shot_1.png"]); diff --git a/components/terminal/clipboardImagePaste.ts b/components/terminal/clipboardImagePaste.ts index 070c90547..da21b1bce 100644 --- a/components/terminal/clipboardImagePaste.ts +++ b/components/terminal/clipboardImagePaste.ts @@ -20,10 +20,11 @@ type HandleRemoteClipboardImagePasteOptions = { bridge?: RemoteClipboardImageBridge; createTransferId?: () => string; getRemoteCwd: () => Promise; + isSensitiveInput?: () => boolean; scrollToBottomAfterProgrammaticInput?: (data: string) => void; sessionId: string | null | undefined; terminalBackend: { - writeToSession: (sessionId: string, data: string, options?: { automated?: boolean }) => void; + writeToSession: (sessionId: string, data: string, options?: { automated?: boolean; sensitive?: boolean }) => void; }; term?: TerminalLike | null; }; @@ -82,6 +83,7 @@ export async function handleRemoteClipboardImageUpload({ bridge, createTransferId = defaultTransferId, getRemoteCwd, + isSensitiveInput, scrollToBottomAfterProgrammaticInput, sessionId, terminalBackend, @@ -115,7 +117,9 @@ export async function handleRemoteClipboardImageUpload({ if (!transferResult || transferResult.error) return { ok: false, reason: "upload-failed" }; const pastedPath = quoteRemotePathForShell(targetPath); - terminalBackend.writeToSession(sessionId, pastedPath); + terminalBackend.writeToSession(sessionId, pastedPath, { + sensitive: isSensitiveInput?.() === true, + }); scrollToBottomAfterProgrammaticInput?.(pastedPath); term?.focus?.(); return { ok: true, remotePath: targetPath, pastedPath }; diff --git a/components/terminal/hooks/useTerminalContextActions.ts b/components/terminal/hooks/useTerminalContextActions.ts index 47e586b3d..6665a18d9 100644 --- a/components/terminal/hooks/useTerminalContextActions.ts +++ b/components/terminal/hooks/useTerminalContextActions.ts @@ -17,13 +17,25 @@ type BroadcastPasteRefs = { sessionRef: RefObject; isBroadcastEnabledRef?: RefObject; onBroadcastInputRef?: RefObject<((data: string, sourceSessionId: string) => void) | undefined>; + passwordPromptActiveRef?: RefObject; }; export const broadcastTerminalPasteData = ( data: string, - { sourceSessionId, sessionRef, isBroadcastEnabledRef, onBroadcastInputRef }: BroadcastPasteRefs, + { + sourceSessionId, + sessionRef, + isBroadcastEnabledRef, + onBroadcastInputRef, + passwordPromptActiveRef, + }: BroadcastPasteRefs, ): boolean => { - if (sessionRef.current && isBroadcastEnabledRef?.current && onBroadcastInputRef?.current) { + if ( + passwordPromptActiveRef?.current !== true + && sessionRef.current + && isBroadcastEnabledRef?.current + && onBroadcastInputRef?.current + ) { onBroadcastInputRef.current(data, sourceSessionId); return true; } @@ -38,6 +50,7 @@ export const useTerminalContextActions = ({ scrollOnPasteRef, isBroadcastEnabledRef, onBroadcastInputRef, + passwordPromptActiveRef, isLocalConnection, supportsRemoteImagePaste, clearWipesScrollbackRef, @@ -54,6 +67,7 @@ export const useTerminalContextActions = ({ scrollOnPasteRef?: RefObject; isBroadcastEnabledRef?: RefObject; onBroadcastInputRef?: RefObject<((data: string, sourceSessionId: string) => void) | undefined>; + passwordPromptActiveRef?: RefObject; isLocalConnection: boolean; supportsRemoteImagePaste: boolean; clearWipesScrollbackRef?: RefObject; @@ -72,8 +86,9 @@ export const useTerminalContextActions = ({ sessionRef, isBroadcastEnabledRef, onBroadcastInputRef, + passwordPromptActiveRef, }); - }, [isBroadcastEnabledRef, onBroadcastInputRef, sessionRef, sourceSessionId]); + }, [isBroadcastEnabledRef, onBroadcastInputRef, passwordPromptActiveRef, sessionRef, sourceSessionId]); const onCopy = useCallback(() => { const term = termRef.current; @@ -95,6 +110,7 @@ export const useTerminalContextActions = ({ await handleTerminalClipboardPaste({ bridge, isLocalConnection, + isSensitiveInput: () => passwordPromptActiveRef?.current === true, readClipboardText: () => navigator.clipboard.readText(), scrollOnPaste: scrollOnPasteRef?.current ?? false, onPasteData: broadcastUserPasteData, @@ -108,6 +124,7 @@ export const useTerminalContextActions = ({ }, [ broadcastUserPasteData, isLocalConnection, + passwordPromptActiveRef, sessionRef, termRef, scrollOnPasteRef, @@ -122,6 +139,7 @@ export const useTerminalContextActions = ({ const result = await handleRemoteClipboardImageUpload({ bridge, getRemoteCwd: getRemoteCwd ?? (async () => undefined), + isSensitiveInput: () => passwordPromptActiveRef?.current === true, sessionId: supportsRemoteImagePaste ? sessionRef.current : null, terminalBackend, term, @@ -134,6 +152,7 @@ export const useTerminalContextActions = ({ } }, [ getRemoteCwd, + passwordPromptActiveRef, onClipboardImageUploadResult, scrollToBottomAfterProgrammaticInput, sessionRef, diff --git a/components/terminal/hooks/useTerminalDragDrop.ts b/components/terminal/hooks/useTerminalDragDrop.ts index 4091e50ec..9840a9707 100644 --- a/components/terminal/hooks/useTerminalDragDrop.ts +++ b/components/terminal/hooks/useTerminalDragDrop.ts @@ -32,7 +32,7 @@ interface UseTerminalDragDropOptions { status: TerminalSession["status"]; t: (key: string) => string; terminalBackend: { - writeToSession: (sessionId: string, data: string, options?: { automated?: boolean }) => void; + writeToSession: (sessionId: string, data: string, options?: { automated?: boolean; sensitive?: boolean }) => void; cancelZmodem?: (sessionId: string, options?: { interrupt?: boolean }) => void; onSessionData?: (sessionId: string, cb: (chunk: string) => void) => () => void; onZmodemEvent?: ( @@ -45,6 +45,7 @@ interface UseTerminalDragDropOptions { uploadCommand?: string, ) => Promise<{ success: boolean; error?: string }>; }; + isSensitiveInput?: () => boolean; rzMissingFallbackTimeoutMs?: number; termRef: React.MutableRefObject; } @@ -125,6 +126,7 @@ export async function handleTerminalDropEntries({ sessionId, sessionRef, terminalBackend, + isSensitiveInput, rzMissingFallbackTimeoutMs, termRef, }: Pick< @@ -138,6 +140,7 @@ export async function handleTerminalDropEntries({ | "sessionId" | "sessionRef" | "terminalBackend" + | "isSensitiveInput" | "rzMissingFallbackTimeoutMs" | "termRef" > & { @@ -152,7 +155,9 @@ export async function handleTerminalDropEntries({ if (paths.length > 0 && termRef.current && sessionRef.current) { const pathsText = paths.join(" "); - terminalBackend.writeToSession(sessionRef.current, pathsText); + terminalBackend.writeToSession(sessionRef.current, pathsText, { + sensitive: isSensitiveInput?.() === true, + }); scrollToBottomAfterProgrammaticInput(pathsText); termRef.current.focus(); } @@ -237,6 +242,7 @@ export function useTerminalDragDrop({ status, t, terminalBackend, + isSensitiveInput, rzMissingFallbackTimeoutMs, termRef, }: UseTerminalDragDropOptions) { @@ -297,6 +303,7 @@ export function useTerminalDragDrop({ sessionId, sessionRef, terminalBackend, + isSensitiveInput, rzMissingFallbackTimeoutMs, termRef, }); diff --git a/components/terminal/hooks/useTerminalFilePaste.ts b/components/terminal/hooks/useTerminalFilePaste.ts index 80454d6a9..6fb4efeae 100644 --- a/components/terminal/hooks/useTerminalFilePaste.ts +++ b/components/terminal/hooks/useTerminalFilePaste.ts @@ -13,8 +13,9 @@ interface UseTerminalFilePasteOptions { termRef: React.MutableRefObject; sessionRef: React.MutableRefObject; terminalBackend: { - writeToSession: (sessionId: string, data: string, options?: { automated?: boolean }) => void; + writeToSession: (sessionId: string, data: string, options?: { automated?: boolean; sensitive?: boolean }) => void; }; + isSensitiveInput?: () => boolean; scrollOnPasteRef?: React.RefObject; onPasteData?: (data: string) => boolean | void; scrollToBottomAfterProgrammaticInput: (data: string) => void; @@ -27,6 +28,7 @@ export function useTerminalFilePaste({ termRef, sessionRef, terminalBackend, + isSensitiveInput, scrollOnPasteRef, onPasteData, scrollToBottomAfterProgrammaticInput, @@ -56,6 +58,7 @@ export function useTerminalFilePaste({ await handleTerminalClipboardPaste({ bridge, isLocalConnection, + isSensitiveInput, readClipboardText: () => navigator.clipboard.readText(), scrollOnPaste: scrollOnPasteRef?.current ?? false, onPasteData, @@ -77,6 +80,7 @@ export function useTerminalFilePaste({ }, [ containerRef, isLocalConnection, + isSensitiveInput, onPasteData, scrollOnPasteRef, scrollToBottomAfterProgrammaticInput, diff --git a/components/terminal/runtime/createTerminalSessionStarters.test.ts b/components/terminal/runtime/createTerminalSessionStarters.test.ts index f4d3ac51c..9b467cfda 100644 --- a/components/terminal/runtime/createTerminalSessionStarters.test.ts +++ b/components/terminal/runtime/createTerminalSessionStarters.test.ts @@ -1967,6 +1967,49 @@ test("local session captures paste cleanup writes in terminal log data", async ( assert.deepEqual(capturedLogData, ["line 3 with enough content", "\x1b[K"]); }); +test("local session acknowledges metadata-only plugin output immediately", async () => { + let onData: ((data: string, meta?: { pluginPipelineIngressBytes?: number }) => void) | null = null; + const acknowledgements: Array<{ sessionId: string; bytes: number }> = []; + const paused: Array<{ sessionId: string; paused: boolean }> = []; + const terminalBackend = { + localAvailable: () => true, + startLocalSession: async () => "local-session", + onSessionData: ( + _id: string, + cb: (data: string, meta?: { pluginPipelineIngressBytes?: number }) => void, + ) => { + onData = cb; + return noop; + }, + onSessionExit: () => noop, + onChainProgress: () => noop, + writeToSession: noop, + resizeSession: noop, + ackSessionFlow: (sessionId: string, bytes: number) => { + acknowledgements.push({ sessionId, bytes }); + }, + setSessionFlowPaused: (sessionId: string, isPaused: boolean) => { + paused.push({ sessionId, paused: isPaused }); + }, + }; + const ctx = createStarterContext({ + host: { + id: "local-host", + label: "Local", + hostname: "local", + username: "", + protocol: "local", + }, + terminalBackend, + }); + + await createTerminalSessionStarters(ctx as never).startLocal(createTermStub() as never); + onData?.("", { pluginPipelineIngressBytes: 12 }); + + assert.deepEqual(acknowledgements, [{ sessionId: "local-session", bytes: 12 }]); + assert.deepEqual(paused.at(-1), { sessionId: "local-session", paused: false }); +}); + test("local session runs startup command after attaching", async () => { const sessionWrites: Array<{ id: string; data: string; automated?: boolean }> = []; const attached: string[] = []; diff --git a/components/terminal/runtime/createTerminalSessionStarters.ts b/components/terminal/runtime/createTerminalSessionStarters.ts index 9ff31c3ae..fd2d88a76 100644 --- a/components/terminal/runtime/createTerminalSessionStarters.ts +++ b/components/terminal/runtime/createTerminalSessionStarters.ts @@ -10,6 +10,7 @@ export type { } from "./createTerminalSessionStarters.types"; export { normalizeStartupCommandDelay, splitStartupCommandLines } from "./terminalStartupCommands"; import { + acknowledgeDroppedTerminalDisplayBytes, attachSessionToTerminal, buildTermEnv, closeOrphanBackendSession, @@ -1459,7 +1460,14 @@ export const createTerminalSessionStarters = (ctx: TerminalSessionStartersContex ctx.disposeDataRef.current = ctx.terminalBackend.onSessionData( id, (chunk, meta) => { - writeSessionData(ctx, term, chunk, chunk.length, meta); + const pluginPipelineIngressBytes = Number.isFinite(meta?.pluginPipelineIngressBytes) + ? Math.max(0, Number(meta.pluginPipelineIngressBytes)) + : chunk.length; + if (!chunk && pluginPipelineIngressBytes > 0) { + acknowledgeDroppedTerminalDisplayBytes(ctx, pluginPipelineIngressBytes); + } else { + writeSessionData(ctx, term, chunk, pluginPipelineIngressBytes, meta); + } ctx.onTerminalOutput?.(chunk, meta); if (!ctx.hasConnectedRef.current) { ctx.updateStatus("connected"); diff --git a/components/terminal/runtime/createTerminalSessionStarters.types.ts b/components/terminal/runtime/createTerminalSessionStarters.types.ts index c338819ff..7fc279e0d 100644 --- a/components/terminal/runtime/createTerminalSessionStarters.types.ts +++ b/components/terminal/runtime/createTerminalSessionStarters.types.ts @@ -87,7 +87,7 @@ export type TerminalBackendApi = { onConnectionReuseFallback?: ( cb: (sessionId: string, sourceSessionId?: string) => void, ) => (() => void) | undefined; - writeToSession: (sessionId: string, data: string, options?: { automated?: boolean; lineDelayMs?: number; logRewrite?: ProgrammaticCommandLogRewrite }) => void; + writeToSession: (sessionId: string, data: string, options?: { automated?: boolean; sensitive?: boolean; lineDelayMs?: number; logRewrite?: ProgrammaticCommandLogRewrite }) => void; interruptSession?: (sessionId: string, trace?: NetcattyTerminalInterruptTrace) => void; resizeSession: (sessionId: string, cols: number, rows: number) => void; closeSession: (sessionId: string) => void | Promise; @@ -213,4 +213,10 @@ export type TerminalSessionDataMeta = { /** True while Mosh is still on the ephemeral SSH handshake PTY. */ moshHandshake?: boolean; terminalPerf?: NetcattyTerminalOutputPerfMeta; + /** Original host output units acknowledged even when an interceptor changes display length. */ + pluginPipelineIngressBytes?: number; + /** Host-owned provenance marker for output already processed by an interceptor. */ + pluginPipelineProcessed?: boolean; + /** Host-owned classification from original output; plugins cannot mask it. */ + pluginPipelineSensitiveInput?: boolean; }; diff --git a/components/terminal/runtime/createXTermRuntime.ts b/components/terminal/runtime/createXTermRuntime.ts index e18077b20..ecb3b4387 100644 --- a/components/terminal/runtime/createXTermRuntime.ts +++ b/components/terminal/runtime/createXTermRuntime.ts @@ -778,7 +778,11 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime const appLevelActions = getAppLevelActions(); const terminalActions = getTerminalPassthroughActions(); const broadcastUserPasteData = (data: string) => { - if (ctx.isBroadcastEnabledRef.current && ctx.onBroadcastInputRef.current) { + if ( + ctx.passwordPromptActiveRef?.current !== true + && ctx.isBroadcastEnabledRef.current + && ctx.onBroadcastInputRef.current + ) { ctx.onBroadcastInputRef.current(data, ctx.sessionId); return true; } @@ -920,6 +924,7 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime const inputSource = options?.source ?? "terminal"; const id = ctx.sessionRef.current; const dataToWrite = data; + const sensitive = ctx.passwordPromptActiveRef?.current === true; let handledSubmittedInput = false; const submittedInput: { text: string; lineEnding: "\r\n" | "\r" | "\n" } | null = inputSource === "shift-enter" @@ -931,7 +936,8 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime const broadcastDataBeforeSudo = mapTerminalBackspaceInput(data, ctx.host.backspaceBehavior); const suppressTerminalBroadcast = inputSource === "terminal" && suppressNextTerminalDataBroadcast; if (suppressTerminalBroadcast) suppressNextTerminalDataBroadcast = false; - const willBroadcastInput = inputSource !== "kitty" && + const willBroadcastInput = !sensitive && + inputSource !== "kitty" && !handlingKittyBroadcast && !suppressTerminalBroadcast && !!id && shouldBroadcastTerminalUserInput(term, broadcastDataBeforeSudo, { @@ -939,7 +945,6 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime hasBroadcastInputHandler: !!onBroadcastInput, }); if (ctx.statusRef.current === "connected" && submittedInput) { - const sensitive = ctx.passwordPromptActiveRef?.current === true; if (submittedInput.text) { ctx.commandBufferRef.current += submittedInput.text; ctx.scriptRecorderRef?.current?.recordInput(submittedInput.text); @@ -971,7 +976,6 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime ) { const pastedCommand = getSinglePastedCommand(data); if (pastedCommand) { - const sensitive = ctx.passwordPromptActiveRef?.current === true; if (ctx.passwordPromptActiveRef) ctx.passwordPromptActiveRef.current = false; const recordedCommand = recordTerminalCommandExecution( `${ctx.commandBufferRef.current}${pastedCommand.command}`, @@ -1010,7 +1014,7 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime localEcho: ctx.serialLocalEcho, writeToSession: (nextData) => { ctx.onOutputTriggerUserInputRef?.current?.(nextData); - ctx.terminalBackend.writeToSession(id, nextData); + ctx.terminalBackend.writeToSession(id, nextData, { sensitive }); }, writeToTerminal: writeLocalTerminalData, }); @@ -1019,7 +1023,7 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime // When backspaceBehavior is configured, remap the Backspace key output const outData = mapTerminalBackspaceInput(dataToWrite, ctx.host.backspaceBehavior); ctx.onOutputTriggerUserInputRef?.current?.(outData); - ctx.terminalBackend.writeToSession(id, outData); + ctx.terminalBackend.writeToSession(id, outData, { sensitive }); // Local echo for serial connections only when explicitly enabled if (inputSource !== "kitty" && ctx.host.protocol === "serial" && ctx.serialLocalEcho) { @@ -1111,6 +1115,7 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime sourceSessionId: ctx.sessionId, isHandlingBroadcast: () => handlingKittyBroadcast, isBroadcastEnabled: () => ctx.isBroadcastEnabledRef.current, + isSensitiveInput: () => ctx.passwordPromptActiveRef?.current === true, getDispatcher: () => ctx.onBroadcastInputRef.current, }); @@ -1327,6 +1332,9 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime serialLineBufferRef: ctx.serialLineBufferRef, onAutocompleteInput: ctx.onAutocompleteInput, }); + if (ctx.passwordPromptActiveRef) { + ctx.passwordPromptActiveRef.current = false; + } if (ctx.terminalBackend.interruptSession) { ctx.terminalBackend.interruptSession(id, interruptTrace); } else { @@ -1543,11 +1551,7 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime if (id) { e.preventDefault(); e.stopPropagation(); - ctx.onAutocompleteInput?.(wordJumpSequence); - ctx.terminalBackend.writeToSession(id, wordJumpSequence); - if (ctx.isBroadcastEnabledRef.current && ctx.onBroadcastInputRef.current) { - ctx.onBroadcastInputRef.current(wordJumpSequence, ctx.sessionId); - } + handleTerminalInputData(wordJumpSequence); scrollToBottomAfterInput(wordJumpSequence); return false; } @@ -1737,6 +1741,7 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime legacySuppressedKeys: broadcastLegacySuppressedKeys, }), getSessionId: () => ctx.sessionRef.current, + isSensitiveInput: () => ctx.passwordPromptActiveRef?.current === true, isConnected: () => ctx.statusRef.current === "connected", isRuntimeDisposed: () => runtimeDisposed, interruptSession: ctx.terminalBackend.interruptSession @@ -1745,6 +1750,7 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime writeDisposed: (id, data) => ctx.terminalBackend.writeToSession( id, mapTerminalBackspaceInput(data, ctx.host.backspaceBehavior), + { sensitive: ctx.passwordPromptActiveRef?.current === true }, ), writeActive: (data) => handleTerminalInputData(data, { source: "kitty" }), }); @@ -1909,7 +1915,15 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime binary += String.fromCharCode(...bytes.subarray(i, i + 8192)); } const b64 = btoa(binary); - ctx.terminalBackend.writeToSession(sessionId, `\x1b]52;${target};${b64}\x07`); + // This host-generated protocol reply contains clipboard contents. It + // must bypass plugin input interceptors just like password/OTP data; + // otherwise terminal interception would become an undeclared + // clipboard-read capability. + ctx.terminalBackend.writeToSession( + sessionId, + `\x1b]52;${target};${b64}\x07`, + { sensitive: true }, + ); }; doRead().catch((err) => { logger.warn('[XTerm] OSC 52 clipboard read failed:', err); diff --git a/components/terminal/runtime/kittyKeyboardBroadcast.test.ts b/components/terminal/runtime/kittyKeyboardBroadcast.test.ts index cea301f9f..b4718d38f 100644 --- a/components/terminal/runtime/kittyKeyboardBroadcast.test.ts +++ b/components/terminal/runtime/kittyKeyboardBroadcast.test.ts @@ -97,6 +97,37 @@ test("a paired release is forwarded after broadcast is disabled", () => { ]); }); +test("sensitive input is never broadcast while an earlier paired release can still finish", () => { + let sensitive = true; + const forwarded: KittyKeyboardBroadcastInput[] = []; + const forward = createKittyKeyboardBroadcastForwarder({ + sourceSessionId: "source", + isHandlingBroadcast: () => false, + isBroadcastEnabled: () => true, + isSensitiveInput: () => sensitive, + getDispatcher: () => (_data, _sourceSessionId, options) => { + forwarded.push(options.kittyKeyboardInput); + return ["target-a"]; + }, + }); + const secretPress: KittyKeyboardBroadcastInput = { + kind: "key", + event: { type: "keydown", key: "x", code: "KeyX" }, + }; + const priorRelease: KittyKeyboardBroadcastInput = { + kind: "key", + event: { type: "keyup", key: "Shift", code: "ShiftLeft" }, + }; + + assert.equal(forward(secretPress), null); + assert.deepEqual(forward(priorRelease, true, ["target-a"]), { + targetSessionIds: ["target-a"], + }); + sensitive = false; + assert.deepEqual(forward(secretPress), { targetSessionIds: ["target-a"] }); + assert.deepEqual(forwarded, [priorRelease, secretPress]); +}); + test("blur flushes every forwarded press as a synthetic release", () => { const forwarded: KittyKeyboardBroadcastInput[] = []; const forward = createKittyKeyboardBroadcastForwarder({ diff --git a/components/terminal/runtime/kittyKeyboardBroadcast.ts b/components/terminal/runtime/kittyKeyboardBroadcast.ts index 4d6daa5c0..be607211a 100644 --- a/components/terminal/runtime/kittyKeyboardBroadcast.ts +++ b/components/terminal/runtime/kittyKeyboardBroadcast.ts @@ -36,6 +36,7 @@ export const createKittyKeyboardBroadcastForwarder = (options: { sourceSessionId: string; isHandlingBroadcast: () => boolean; isBroadcastEnabled: () => boolean; + isSensitiveInput?: () => boolean; getDispatcher: () => (( data: string, sourceSessionId: string, @@ -56,6 +57,7 @@ export const createKittyKeyboardBroadcastForwarder = (options: { const dispatcher = currentDispatcher ?? (forcePairedRelease ? lastDispatcher : undefined); if ( options.isHandlingBroadcast() || + (!forcePairedRelease && options.isSensitiveInput?.() === true) || (!forcePairedRelease && !options.isBroadcastEnabled()) || !dispatcher ) return null; @@ -258,6 +260,7 @@ export const createKittyKeyboardBroadcastHandler = (options: { legacySuppressedKeys?: Set; }; getSessionId: () => string | null; + isSensitiveInput?: () => boolean; isConnected: () => boolean; isRuntimeDisposed: () => boolean; interruptSession?: (sessionId: string) => void; @@ -266,6 +269,8 @@ export const createKittyKeyboardBroadcastHandler = (options: { }): KittyKeyboardBroadcastHandler => (input, dispatchOptions) => { const sessionId = options.getSessionId(); if (!sessionId || !options.isConnected()) return; + const isPairedRelease = input.kind === "key" && input.event.type === "keyup"; + if (!isPairedRelease && options.isSensitiveInput?.() === true) return; const resolved = resolveKittyKeyboardBroadcastInput(input, options.resolveOptions()); if (!resolved) return; if (resolved.urgentInterrupt && options.interruptSession) { diff --git a/components/terminal/runtime/terminalInterceptorInputSafety.test.ts b/components/terminal/runtime/terminalInterceptorInputSafety.test.ts new file mode 100644 index 000000000..8fcc01763 --- /dev/null +++ b/components/terminal/runtime/terminalInterceptorInputSafety.test.ts @@ -0,0 +1,133 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import test from "node:test"; + +const runtimeSource = readFileSync(new URL("./createXTermRuntime.ts", import.meta.url), "utf8"); +const attachmentSource = readFileSync(new URL("./terminalSessionAttachment.ts", import.meta.url), "utf8"); +const terminalSource = readFileSync(new URL("../../Terminal.tsx", import.meta.url), "utf8"); +const terminalLayerSource = readFileSync(new URL("../../TerminalLayer.tsx", import.meta.url), "utf8"); +const preloadSource = readFileSync( + new URL("../../../electron/preload/api.cjs", import.meta.url), + "utf8", +); +const scriptBridgeSource = readFileSync( + new URL("../../../electron/bridges/scriptBridge.cjs", import.meta.url), + "utf8", +); +const scriptCodegenSource = readFileSync( + new URL("../../../electron/scripts/scriptCodegen.cjs", import.meta.url), + "utf8", +); +const scriptDialogSource = readFileSync( + new URL("../../scripts/ScriptDialogHost.tsx", import.meta.url), + "utf8", +); + +test("password-prompt input is classified before prompt state reset and cannot broadcast", () => { + assert.match( + attachmentSource, + /typeof meta\?\.pluginPipelineSensitiveInput === "boolean"[\s\S]*?passwordPromptActiveRef\.current = meta\.pluginPipelineSensitiveInput/u, + ); + assert.match( + terminalSource, + /typeof meta\?\.pluginPipelineSensitiveInput === "boolean"[\s\S]*?passwordPromptActiveRef\.current = meta\.pluginPipelineSensitiveInput[\s\S]*?sensitivePromptOutputTailRef\.current = "";[\s\S]*?return;[\s\S]*?else if \(isUntrustedTerminalInputPrompt/u, + ); + assert.match( + runtimeSource, + /const sensitive = ctx\.passwordPromptActiveRef\?\.current === true;[\s\S]*?const willBroadcastInput = !sensitive &&/u, + ); + assert.match( + runtimeSource, + /writeToSession\(id, outData, \{ sensitive \}\)/u, + ); + assert.match( + runtimeSource, + /writeToSession\(id, nextData, \{ sensitive \}\)/u, + ); + assert.match( + runtimeSource, + /const broadcastUserPasteData = \(data: string\) => \{[\s\S]*?passwordPromptActiveRef\?\.current !== true[\s\S]*?onBroadcastInputRef\.current/u, + ); + assert.match( + terminalSource, + /const sensitive = passwordPromptActiveRef\.current;[\s\S]*?!sensitive && isBroadcastEnabledRef\.current[\s\S]*?writeToSession\(id, data, \{[\s\S]*?sensitive,/u, + ); +}); + +test("Ctrl+C clears renderer password-prompt classification before the next input", () => { + assert.match( + runtimeSource, + /clearTerminalInputStateForInterrupt\(\{[\s\S]*?passwordPromptActiveRef\.current = false;[\s\S]*?interruptSession/u, + ); +}); + +test("confirmed sudo credentials and preload transport preserve the sensitive marker", () => { + assert.match( + attachmentSource, + /writeToSession\(id, data, \{ automated: true, sensitive: true \}\)/u, + ); + assert.match(preloadSource, /sensitive: options\?\.sensitive === true/u); +}); + +test("OSC 52 clipboard replies bypass plugin input interception as sensitive host data", () => { + assert.match( + runtimeSource, + /writeToSession\(\s*sessionId,\s*`\\x1b\]52;\$\{target\};\$\{b64\}\\x07`,\s*\{ sensitive: true \},\s*\)/u, + ); +}); + +test("generated script credentials stay masked and preserve the sensitive marker", () => { + assert.match(scriptCodegenSource, /dialog\.prompt\([\s\S]*?\{ sensitive: true \}\)/u); + assert.match(scriptCodegenSource, /screen\.sendLine\([\s\S]*?\{ sensitive: true \}\)/u); + assert.match(scriptBridgeSource, /options\.sensitive === true \? \{ sensitive: true \} : \{\}/u); + assert.match(scriptDialogSource, /type=\{request\.sensitive \? 'password' : 'text'\}/u); +}); + +test("renderer flow control acknowledges host ingress rather than transformed display length", () => { + assert.match( + attachmentSource, + /const pluginPipelineIngressBytes = Number\.isFinite\(meta\?\.pluginPipelineIngressBytes\)[\s\S]*?const ingressBytes = pluginPipelineIngressBytes[\s\S]*?\?\? filtered\.acceptedBytes/u, + ); + assert.match( + attachmentSource, + /filtered\.accepted && !filtered\.data && pluginPipelineIngressBytes != null[\s\S]*?acknowledgeDroppedTerminalDisplayBytes\(ctx, pluginPipelineIngressBytes\)/u, + ); + assert.match( + attachmentSource, + /!filtered\.accepted && pluginPipelineIngressBytes != null[\s\S]*?\? pluginPipelineIngressBytes[\s\S]*?: pluginPipelineIngressBytes != null[\s\S]*?\? 0[\s\S]*?: filtered\.droppedBytes/u, + ); + assert.match( + attachmentSource, + /const displayBytes = data\.length;[\s\S]*?enqueueTerminalWrite\(term, displayBytes,[\s\S]*?dropBytes: ingressBytes/u, + ); + assert.match( + readFileSync(new URL("./createTerminalSessionStarters.ts", import.meta.url), "utf8"), + /const pluginPipelineIngressBytes = Number\.isFinite\(meta\?\.pluginPipelineIngressBytes\)[\s\S]*?!chunk && pluginPipelineIngressBytes > 0[\s\S]*?acknowledgeDroppedTerminalDisplayBytes\(ctx, pluginPipelineIngressBytes\)[\s\S]*?writeSessionData\(ctx, term, chunk, pluginPipelineIngressBytes, meta\)/u, + ); + assert.match( + terminalSource, + /beginHibernatedSessionListeners[\s\S]*?\(chunk, meta\) =>[\s\S]*?observeTerminalInputPrompt\(chunk, meta\)[\s\S]*?Number\.isFinite\(meta\?\.pluginPipelineIngressBytes\)[\s\S]*?ackTerminalSessionFlow\(terminalBackend, backendId, pluginPipelineIngressBytes\)/u, + ); +}); + +test("active and hibernated output share host-owned sensitive prompt classification", () => { + assert.match( + terminalSource, + /const observeTerminalInputPrompt = useCallback[\s\S]*?typeof meta\?\.pluginPipelineSensitiveInput === "boolean"[\s\S]*?passwordPromptActiveRef\.current = meta\.pluginPipelineSensitiveInput[\s\S]*?sensitivePromptOutputTailRef\.current = "";[\s\S]*?return;[\s\S]*?isConfirmedTerminalShellPrompt[\s\S]*?passwordPromptActiveRef\.current = false/u, + ); + assert.match( + terminalSource, + /beginHibernatedSessionListeners[\s\S]*?observeTerminalInputPrompt\(chunk, meta\)/u, + ); + assert.match( + terminalSource, + /onTerminalOutput: \(chunk: string, meta\?: TerminalSessionDataMeta\) => \{\s*observeTerminalInputPrompt\(chunk, meta\)/u, + ); +}); + +test("ordinary broadcast skips targets that are waiting for sensitive input", () => { + assert.match( + terminalLayerSource, + /if \(isTerminalSensitiveInputActive\(session\.id\)\) continue;[\s\S]*?writeToSession\(session\.id, data/u, + ); +}); diff --git a/components/terminal/runtime/terminalSensitiveInputRegistry.ts b/components/terminal/runtime/terminalSensitiveInputRegistry.ts new file mode 100644 index 000000000..8d92d79e6 --- /dev/null +++ b/components/terminal/runtime/terminalSensitiveInputRegistry.ts @@ -0,0 +1,15 @@ +const sensitiveInputReaders = new Map boolean>(); + +export function registerTerminalSensitiveInputReader( + sessionId: string, + reader: () => boolean, +): () => void { + sensitiveInputReaders.set(sessionId, reader); + return () => { + if (sensitiveInputReaders.get(sessionId) === reader) sensitiveInputReaders.delete(sessionId); + }; +} + +export function isTerminalSensitiveInputActive(sessionId: string): boolean { + return sensitiveInputReaders.get(sessionId)?.() === true; +} diff --git a/components/terminal/runtime/terminalSessionAttachment.test.ts b/components/terminal/runtime/terminalSessionAttachment.test.ts index db0f8f258..414562a3e 100644 --- a/components/terminal/runtime/terminalSessionAttachment.test.ts +++ b/components/terminal/runtime/terminalSessionAttachment.test.ts @@ -1366,10 +1366,15 @@ test("tryAttachSessionToTerminal closes orphan sessions after unmount", () => { assert.equal(ctx.sessionRef.current, null); }); -test("attachSessionToTerminal marks connected on first output including mosh handshake", () => { +test("attachSessionToTerminal marks connected on metadata-only or visible first output", () => { const { term } = createFakeTerm(); const statuses: string[] = []; - let onData: ((data: string, meta?: { moshHandshake?: boolean }) => void) | null = null; + const output: Array<{ data: string; sensitive: boolean }> = []; + let onData: ((data: string, meta?: { + moshHandshake?: boolean; + pluginPipelineIngressBytes?: number; + pluginPipelineSensitiveInput?: boolean; + }) => void) | null = null; const ctx = { ...createContext(false), @@ -1382,10 +1387,17 @@ test("attachSessionToTerminal marks connected on first output including mosh han fitAddonRef: { current: null }, serializeAddonRef: { current: null }, pendingAuthRef: { current: null }, + onTerminalOutput: (data: string, meta?: { pluginPipelineSensitiveInput?: boolean }) => { + output.push({ data, sensitive: meta?.pluginPipelineSensitiveInput === true }); + }, terminalBackend: { onSessionData: ( _id: string, - cb: (data: string, meta?: { moshHandshake?: boolean }) => void, + cb: (data: string, meta?: { + moshHandshake?: boolean; + pluginPipelineIngressBytes?: number; + pluginPipelineSensitiveInput?: boolean; + }) => void, ) => { onData = cb; return () => {}; @@ -1405,6 +1417,11 @@ test("attachSessionToTerminal marks connected on first output including mosh han }; attachSessionToTerminal(ctx as never, term, "session-1"); + // A plugin may suppress the first banner while still consuming host ingress. + onData?.("", { pluginPipelineIngressBytes: 12, pluginPipelineSensitiveInput: true }); + assert.deepEqual(statuses, ["connected"]); + assert.equal(ctx.hasConnectedRef.current, true); + assert.deepEqual(output, [{ data: "", sensitive: true }]); // Handshake output must dismiss the overlay so interactive prompts are reachable. onData?.("ssh handshake banner\r\n", { moshHandshake: true }); assert.deepEqual(statuses, ["connected"]); diff --git a/components/terminal/runtime/terminalSessionAttachment.ts b/components/terminal/runtime/terminalSessionAttachment.ts index 96fe11517..ee540c2e0 100644 --- a/components/terminal/runtime/terminalSessionAttachment.ts +++ b/components/terminal/runtime/terminalSessionAttachment.ts @@ -347,7 +347,7 @@ export const getFlowController = ( export const resetTerminalLineTimestampState = resetTerminalLineTimestamps; -const acknowledgeDroppedTerminalDisplayBytes = ( +export const acknowledgeDroppedTerminalDisplayBytes = ( ctx: TerminalSessionStartersContext, bytes: number, ): void => { @@ -443,9 +443,10 @@ const writeSessionDataImmediate = ( // Tabby-like: under bulk pressure, force a yield after sizable shards so the // event loop can paint/input between xterm parses (serial queue otherwise // chains the next write the moment the callback fires). + const displayBytes = data.length; const bulkYieldAfter = shouldDegradeTerminalSideWork(term) - && ingressBytes >= XTERM_WRITE_CALLBACK_FAST_PATH_MAX_BYTES; - enqueueTerminalWrite(term, ingressBytes, (done) => { + && displayBytes >= XTERM_WRITE_CALLBACK_FAST_PATH_MAX_BYTES; + enqueueTerminalWrite(term, displayBytes, (done) => { const shouldMeasurePerf = Boolean(writeOptions.perfTrace); const queueItemStartedAt = shouldMeasurePerf ? performance.now() : 0; const prepareStartedAt = shouldMeasurePerf ? performance.now() : 0; @@ -620,6 +621,7 @@ const writeSessionDataImmediate = ( } }); }, { + dropBytes: ingressBytes, deferStart: writeOptions.deferStart, // Intermediate plain shards set yieldAfter via writeLargeTerminalBatch; // bulk pressure also yields after sizable items (Tabby FlowControl intent). @@ -743,7 +745,7 @@ export const attachSessionToTerminal = ( mode: assistMode, password, candidates, - write: (data) => ctx.terminalBackend.writeToSession(id, data, { automated: true }), + write: (data) => ctx.terminalBackend.writeToSession(id, data, { automated: true, sensitive: true }), onHint: (active) => ctx.onSudoHint?.(active) ?? false, onPicker: (active, state) => ctx.onPasswordPromptPicker?.(active, state) ?? false, }); @@ -751,14 +753,58 @@ export const attachSessionToTerminal = ( ctx.sudoAutofillRef.current = sudoAutofill; } + const markConnectedOnFirstOutput = () => { + if (ctx.hasConnectedRef.current) return; + ctx.updateStatus("connected"); + opts?.onConnected?.(); + setTimeout(() => { + if (ctx.isVisibleRef?.current === false) { + notePendingOutputScrollIfEnabled(ctx); + return; + } + if (!ctx.fitAddonRef.current) return; + try { + ctx.fitAddonRef.current.fit(); + if (ctx.sessionRef.current) { + ctx.terminalBackend.resizeSession(ctx.sessionRef.current, term.cols, term.rows); + } + } catch (err) { + logger.warn("Post-connect fit failed", err); + } + }, 100); + }; + ctx.disposeDataRef.current = ctx.terminalBackend.onSessionData( id, (chunk, meta) => { + if (typeof meta?.pluginPipelineSensitiveInput === "boolean" && ctx.passwordPromptActiveRef) { + ctx.passwordPromptActiveRef.current = meta.pluginPipelineSensitiveInput; + } const filtered = filterTerminalInterruptDisplayOutput(term, chunk); - acknowledgeDroppedTerminalDisplayBytes(ctx, filtered.droppedBytes); + const pluginPipelineIngressBytes = Number.isFinite(meta?.pluginPipelineIngressBytes) + ? Math.max(0, Number(meta?.pluginPipelineIngressBytes)) + : null; + if (filtered.accepted && !filtered.data && pluginPipelineIngressBytes != null) { + markConnectedOnFirstOutput(); + if (typeof meta?.pluginPipelineSensitiveInput === "boolean") { + ctx.onTerminalOutput?.("", meta); + } + acknowledgeDroppedTerminalDisplayBytes(ctx, pluginPipelineIngressBytes); + return; + } + acknowledgeDroppedTerminalDisplayBytes( + ctx, + !filtered.accepted && pluginPipelineIngressBytes != null + ? pluginPipelineIngressBytes + : pluginPipelineIngressBytes != null + ? 0 + : filtered.droppedBytes, + ); if (!filtered.accepted) return; - const ingressBytes = filtered.acceptedBytes ?? filtered.data.length; + const ingressBytes = pluginPipelineIngressBytes + ?? filtered.acceptedBytes + ?? filtered.data.length; let data = filtered.data; if (opts?.convertLfToCrlf) { data = data.replace(/(? { - if (ctx.isVisibleRef?.current === false) { - notePendingOutputScrollIfEnabled(ctx); - return; - } - if (!ctx.fitAddonRef.current) return; - try { - ctx.fitAddonRef.current.fit(); - if (ctx.sessionRef.current) { - ctx.terminalBackend.resizeSession(ctx.sessionRef.current, term.cols, term.rows); - } - } catch (err) { - logger.warn("Post-connect fit failed", err); - } - }, 100); - } + markConnectedOnFirstOutput(); }, { replayBacklog: true }, ); diff --git a/components/terminal/runtime/terminalWriteQueue.test.ts b/components/terminal/runtime/terminalWriteQueue.test.ts index 027ee467b..654058306 100644 --- a/components/terminal/runtime/terminalWriteQueue.test.ts +++ b/components/terminal/runtime/terminalWriteQueue.test.ts @@ -393,3 +393,17 @@ test("abortTerminalWriteQueue drops pending bytes and reports dropped count", () assert.equal(started, true); assert.deepEqual(dropped, [60]); }); + +test("abortTerminalWriteQueue reports ingress accounting instead of display scheduling bytes", () => { + const term = createFakeTerm(); + const dropped: number[] = []; + + enqueueTerminalWrite(term, 10, () => {}); + enqueueTerminalWrite(term, 3, () => {}, { + dropBytes: 80, + onDropped: (bytes) => dropped.push(bytes), + }); + abortTerminalWriteQueue(term); + + assert.deepEqual(dropped, [80]); +}); diff --git a/components/terminal/runtime/terminalWriteQueue.ts b/components/terminal/runtime/terminalWriteQueue.ts index bb25d376d..f1e8c9dad 100644 --- a/components/terminal/runtime/terminalWriteQueue.ts +++ b/components/terminal/runtime/terminalWriteQueue.ts @@ -14,6 +14,7 @@ export const WRITE_QUEUE_TURN_BUDGET_MS = 10; export type TerminalWriteQueueOptions = { onDropped?: (bytes: number) => void; + dropBytes?: number; deferStart?: boolean; yieldAfter?: boolean; maxDrainBytes?: number; @@ -21,6 +22,7 @@ export type TerminalWriteQueueOptions = { type QueuedWrite = { bytes: number; + dropBytes: number; steps: QueuedWriteStep[]; nextIndex: number; cancelled: boolean; @@ -30,6 +32,7 @@ type QueuedWrite = { type QueuedWriteStep = { bytes: number; + dropBytes: number; write: (done: () => void) => void; yieldAfter: boolean; }; @@ -290,12 +293,14 @@ const mergePendingWrites = (queue: TerminalWriteQueue): void => { const steps: QueuedWriteStep[] = []; let bytes = 0; + let dropBytes = 0; // Keep a post-item yield if any source item asked for one; inter-step yields // come only from per-step yieldAfter / maxDrainBytes (not a forced every-step // pause). writeLargeTerminalBatch sets yieldAfter only every drain budget. let yieldAfterItem = false; for (const item of queue.pending) { bytes += item.bytes; + dropBytes += item.dropBytes; if (item.yieldAfter) { yieldAfterItem = true; } @@ -303,6 +308,7 @@ const mergePendingWrites = (queue: TerminalWriteQueue): void => { } queue.pending = [{ bytes, + dropBytes, steps, nextIndex: 0, cancelled: false, @@ -391,6 +397,9 @@ export const enqueueTerminalWrite = ( options: TerminalWriteQueueOptions = {}, ): void => { const queue = getOrCreateQueue(term); + const dropBytes = Number.isFinite(options.dropBytes) + ? Math.max(0, Number(options.dropBytes)) + : bytes; if (options.onDropped) { queue.onDropped = options.onDropped; } else if (!queue.onDropped) { @@ -401,7 +410,8 @@ export const enqueueTerminalWrite = ( queue.pending.push({ bytes, - steps: [{ bytes, write, yieldAfter: Boolean(options.yieldAfter) }], + dropBytes, + steps: [{ bytes, dropBytes, write, yieldAfter: Boolean(options.yieldAfter) }], nextIndex: 0, cancelled: false, yieldAfter: Boolean(options.yieldAfter), @@ -429,12 +439,12 @@ export const abortTerminalWriteQueue = ( const queue = terminalWriteQueues.get(term); if (!queue) return; - let droppedBytes = queue.pendingBytes; + let droppedBytes = queue.pending.reduce((sum, item) => sum + item.dropBytes, 0); if (queue.active) { queue.active.cancelled = true; droppedBytes += queue.active.steps .slice(queue.active.nextIndex) - .reduce((sum, step) => sum + step.bytes, 0); + .reduce((sum, step) => sum + step.dropBytes, 0); } queue.pending = []; diff --git a/components/terminal/terminalClipboardPaste.test.ts b/components/terminal/terminalClipboardPaste.test.ts index 686951e98..af4b32022 100644 --- a/components/terminal/terminalClipboardPaste.test.ts +++ b/components/terminal/terminalClipboardPaste.test.ts @@ -33,7 +33,7 @@ test("terminal user paste does not inspect or upload remote clipboard images", a }); test("terminal user paste still inserts local clipboard file paths", async () => { - const writes: string[] = []; + const writes: Array<{ data: string; sensitive?: boolean }> = []; const scrolled: string[] = []; let focused = false; @@ -45,11 +45,15 @@ test("terminal user paste still inserts local clipboard file paths", async () => ], }, isLocalConnection: true, + isSensitiveInput: () => true, readClipboardText: async () => assert.fail("local file paste should not fall through to text"), scrollToBottomAfterProgrammaticInput: (data) => scrolled.push(data), sessionId: "session-1", terminalBackend: { - writeToSession: (_sessionId, data) => writes.push(data), + writeToSession: (_sessionId, data, options) => writes.push({ + data, + sensitive: options?.sensitive, + }), }, term: { focus: () => { @@ -60,7 +64,10 @@ test("terminal user paste still inserts local clipboard file paths", async () => }, }); - assert.deepEqual(writes, ["/Users/alice/shot.png /Users/alice/report.txt"]); + assert.deepEqual(writes, [{ + data: "/Users/alice/shot.png /Users/alice/report.txt", + sensitive: true, + }]); assert.deepEqual(scrolled, ["/Users/alice/shot.png /Users/alice/report.txt"]); assert.equal(focused, true); }); diff --git a/components/terminal/terminalClipboardPaste.ts b/components/terminal/terminalClipboardPaste.ts index 1c875e2f8..3788d2a3d 100644 --- a/components/terminal/terminalClipboardPaste.ts +++ b/components/terminal/terminalClipboardPaste.ts @@ -8,13 +8,14 @@ type ClipboardFileBridge = Pick, "readClipboardFiles">; type TerminalClipboardPasteOptions = { bridge?: ClipboardFileBridge; isLocalConnection: boolean; + isSensitiveInput?: () => boolean; onPasteData?: (data: string) => boolean | void; readClipboardText: () => Promise; scrollOnPaste?: boolean; scrollToBottomAfterProgrammaticInput?: (data: string) => void; sessionId: string | null | undefined; terminalBackend: { - writeToSession: (sessionId: string, data: string, options?: { automated?: boolean }) => void; + writeToSession: (sessionId: string, data: string, options?: { automated?: boolean; sensitive?: boolean }) => void; }; term: Pick & Partial>; }; @@ -22,6 +23,7 @@ type TerminalClipboardPasteOptions = { export async function handleTerminalClipboardPaste({ bridge, isLocalConnection, + isSensitiveInput, onPasteData, readClipboardText, scrollOnPaste = false, @@ -38,7 +40,9 @@ export async function handleTerminalClipboardPaste({ const paths = extractRootPathsFromClipboardFiles(files); if (paths.length > 0) { const pathsText = paths.join(" "); - terminalBackend.writeToSession(sessionId, pathsText); + terminalBackend.writeToSession(sessionId, pathsText, { + sensitive: isSensitiveInput?.() === true, + }); scrollToBottomAfterProgrammaticInput?.(pathsText); term.focus?.(); return; diff --git a/components/terminal/useTerminalContextActions.test.ts b/components/terminal/useTerminalContextActions.test.ts index a9e56a5ad..70e01fb84 100644 --- a/components/terminal/useTerminalContextActions.test.ts +++ b/components/terminal/useTerminalContextActions.test.ts @@ -35,3 +35,19 @@ test("terminal context paste reports false when broadcast is disabled", () => { assert.equal(didBroadcast, false); }); + +test("terminal context paste never broadcasts password-prompt input", () => { + const didBroadcast = broadcastTerminalPasteData("secret", { + sourceSessionId: "workspace-session-1", + sessionRef: { current: "session-1" }, + isBroadcastEnabledRef: { current: true }, + passwordPromptActiveRef: { current: true }, + onBroadcastInputRef: { + current: () => { + throw new Error("sensitive paste must not broadcast"); + }, + }, + }); + + assert.equal(didBroadcast, false); +}); diff --git a/components/terminal/useTerminalEffects.ts b/components/terminal/useTerminalEffects.ts index aa6c77eef..8ecde8456 100644 --- a/components/terminal/useTerminalEffects.ts +++ b/components/terminal/useTerminalEffects.ts @@ -169,7 +169,7 @@ export function resolveSelectionOverlayPosition(term: any, container: HTMLElemen } export function useTerminalEffects(ctx: TerminalEffectsContext) { - const { CONNECTION_TIMEOUT, Error, XTERM_PERFORMANCE_CONFIG, applyUserCursorPreference, auth, autocompleteCloseRef, autocompleteInputRef, autocompleteKeyEventRef, captureTerminalLogData, chainHosts, chainProgress, clearTerminalCwd, commandBufferRef, connectionLogBufferRef, containerRef, createPromptLineBreakState, createReplaySafeTerminalLogSanitizer, createXTermRuntime, deferTerminalResizeRef, disableTerminalFontZoomRef, effectiveFontSize, effectiveFontWeight, effectiveTheme, error, executeSnippetCommand, finalizeTerminalLogData, fitAddonRef, fontFamilyId, fontSize, fontWeightFixupDoneRef, forceCloseHibernatedSession, forceSyncRenderAfterResize, handleOsc52ReadRequest, handleTerminalDataCaptureOnce, hasConnectedRef, hasRuntimeRef, host, hotkeySchemeRef, hibernatedRef, identities, inWorkspace, isBootActiveRef, isBroadcastEnabledRef, isComposeBarOpen, isConnectionAwaitingUserInput, isConnectionPastTcpDial, isFocusMode, isFocused, isLocalConnection, isNetworkDevice, isResizing, isRestoringSelectionRef, isSearchOpen, isSerialConnection, isVisible, isVisibleRef, keyBindingsRef, keys, kittyKeyboardProtocolEnabledForSession, knownCwdRef, lastFittedSizeRef, lastToastedErrorRef, logger, mouseTrackingRef, needsHostKeyVerification, onBroadcastInputRef, onBroadcastInterruptPriorityChange, onCommandExecuted, onCommandSubmitted, onHotkeyActionRef, onOutputTriggerUserInputRef, onPluginRuntimeCwdChange, onSnippetExecutorChange, onTerminalTitleChange, onTerminalBell, onTerminalFontSizeChange, paneLayoutKey, passwordPromptActiveRef, pendingAuthRef, pendingOutputScrollRef, pluginDecorationRules, pluginTerminalLifecycle, pluginTerminalProviderRevision, isPluginTerminalProviderAvailable, requestPluginTerminalProviders, prepareRestoredReconnect, prevIsResizingRef, promptLineBreakStateRef, resizeSession, resolveHostAuth, resolvedFontFamily, safeFit, scriptRecorderRef, searchAddonRef, serialConfig, serialLineBufferRef, serializeAddonRef, sessionId, sessionRef, sessionStarters, setError, setHasMouseTracking, setHasSelection, setIsCancelling, setIsDisconnectedDialogDismissed, requestSearchFocus, setNeedsHostKeyVerification, setPendingHostKeyInfo, setPendingHostKeyRequestId, setProgressLogs, setProgressValue, setSelectionOverlayPosition, setShowLogs, setStatus, setTimeLeft, shouldEnableNativeUserInputAutoScroll, shouldProbeSessionCwd, shouldStartTerminalBackend, attachExistingSession, attachAuthorization, attachHomeWebContentsIdRef, onSnippetShortkeyRef, snippetsRef, splitResizeActive, status, statusRef, sudoAutofillRef, t, teardown, telnetLocalEchoRef, termRef, terminalAltKeyOptions, terminalBackend, terminalContextActionsRef, terminalCwdTracker, terminalDataCapturedRef, terminalLogSanitizerRef, terminalSettings, terminalSettingsRef, toHostKeyInfo, toast, updateStatus, useEffect, useLayoutEffect, xtermRuntimeRef, zmodem, zmodemToastedRef, restoreState } = ctx; + const { CONNECTION_TIMEOUT, Error, XTERM_PERFORMANCE_CONFIG, applyUserCursorPreference, auth, autocompleteCloseRef, autocompleteInputRef, autocompleteKeyEventRef, captureTerminalLogData, chainHosts, chainProgress, clearTerminalCwd, commandBufferRef, connectionLogBufferRef, containerRef, createPromptLineBreakState, createReplaySafeTerminalLogSanitizer, createXTermRuntime, deferTerminalResizeRef, disableTerminalFontZoomRef, effectiveFontSize, effectiveFontWeight, effectiveTheme, error, executeSnippetCommand, finalizeTerminalLogData, fitAddonRef, fontFamilyId, fontSize, fontWeightFixupDoneRef, forceCloseHibernatedSession, forceSyncRenderAfterResize, handleOsc52ReadRequest, handleTerminalDataCaptureOnce, hasConnectedRef, hasRuntimeRef, host, hotkeySchemeRef, hibernatedRef, identities, inWorkspace, isBootActiveRef, isBroadcastEnabledRef, isComposeBarOpen, isConnectionAwaitingUserInput, isConnectionPastTcpDial, isFocusMode, isFocused, isLocalConnection, isNetworkDevice, isResizing, isRestoringSelectionRef, isSearchOpen, isSerialConnection, isVisible, isVisibleRef, keyBindingsRef, keys, kittyKeyboardProtocolEnabledForSession, knownCwdRef, lastFittedSizeRef, lastToastedErrorRef, logger, mouseTrackingRef, needsHostKeyVerification, onBroadcastInputRef, onBroadcastInterruptPriorityChange, onCommandExecuted, onCommandSubmitted, onHotkeyActionRef, onOutputTriggerUserInputRef, onPluginRuntimeCwdChange, onSnippetExecutorChange, onTerminalCwdChange, onTerminalTitleChange, onTerminalBell, onTerminalFontSizeChange, paneLayoutKey, passwordPromptActiveRef, pendingAuthRef, pendingOutputScrollRef, pluginDecorationRules, pluginTerminalLifecycle, pluginTerminalProviderRevision, isPluginTerminalProviderAvailable, requestPluginTerminalProviders, prepareRestoredReconnect, prevIsResizingRef, promptLineBreakStateRef, resizeSession, resolveHostAuth, resolvedFontFamily, safeFit, scriptRecorderRef, searchAddonRef, serialConfig, serialLineBufferRef, serializeAddonRef, sessionId, sessionRef, sessionStarters, setError, setHasMouseTracking, setHasSelection, setIsCancelling, setIsDisconnectedDialogDismissed, requestSearchFocus, setNeedsHostKeyVerification, setPendingHostKeyInfo, setPendingHostKeyRequestId, setProgressLogs, setProgressValue, setSelectionOverlayPosition, setShowLogs, setStatus, setTimeLeft, shouldEnableNativeUserInputAutoScroll, shouldProbeSessionCwd, shouldStartTerminalBackend, attachExistingSession, attachAuthorization, attachHomeWebContentsIdRef, onSnippetShortkeyRef, snippetsRef, splitResizeActive, status, statusRef, sudoAutofillRef, t, teardown, telnetLocalEchoRef, termRef, terminalAltKeyOptions, terminalBackend, terminalContextActionsRef, terminalCwdTracker, terminalDataCapturedRef, terminalLogSanitizerRef, terminalSettings, terminalSettingsRef, terminalTitleRef, toHostKeyInfo, toast, updateStatus, useEffect, useLayoutEffect, xtermRuntimeRef, zmodem, zmodemToastedRef, restoreState } = ctx; const effectiveTerminalProtocol = resolveEffectiveTerminalProtocol(host); const hibernateHiddenTabs = resolveTerminalHibernateEnabledForProtocol( terminalSettings, @@ -449,6 +449,7 @@ export function useTerminalEffects(ctx: TerminalEffectsContext) { onPluginRuntimeCwdChange(cwd, { source: 'osc7' }); }, onTitleChange: (title: string | null) => { + terminalTitleRef.current = title || undefined; publishPluginTerminalRuntimeLifecycleEvent( pluginTerminalLifecycle, 'titleChanged', @@ -554,6 +555,29 @@ export function useTerminalEffects(ctx: TerminalEffectsContext) { if (typeof snap.kittyKeyboardProtocolEnabled === "boolean") { runtime.setKittyKeyboardProtocolEnabled(snap.kittyKeyboardProtocolEnabled); } + if (typeof snap.passwordPromptActive === "boolean") { + passwordPromptActiveRef.current = snap.passwordPromptActive; + } + if (snap.cwd !== undefined) { + const cwd = terminalCwdTracker.setRendererCwd(snap.cwd); + knownCwdRef.current = cwd; + publishPluginTerminalRuntimeLifecycleEvent( + pluginTerminalLifecycle, + 'cwdChanged', + { ...(cwd ? { cwd } : {}) }, + ); + onTerminalCwdChange?.(sessionId, cwd ?? null); + } + if (snap.title !== undefined) { + const title = snap.title || null; + terminalTitleRef.current = title ?? undefined; + publishPluginTerminalRuntimeLifecycleEvent( + pluginTerminalLifecycle, + 'titleChanged', + { ...(title ? { title } : {}) }, + ); + onTerminalTitleChange?.(sessionId, title); + } if (snap.kittyKeyboardModeState) { runtime.restoreKittyKeyboardModeState(snap.kittyKeyboardModeState); } diff --git a/docs/plugin-platform/contract-and-sdk.md b/docs/plugin-platform/contract-and-sdk.md index f6bfa9d17..ec28a13c7 100644 --- a/docs/plugin-platform/contract-and-sdk.md +++ b/docs/plugin-platform/contract-and-sdk.md @@ -367,8 +367,14 @@ Phase-5 Provider handlers are activation-owned SDK registrations. The host performs immutable enumeration without activation, authorizes the exact Provider permission set at first use, invokes through `RuntimeSupervisor`, and validates the canonical Provider result plus the terminal operation's bounded -result shape before application use. Raw terminal interceptors remain reserved -for the separate phase-6 transport. +result shape before application use. Phase 6 reuses the same declarations and +registration ownership but moves raw terminal bytes onto a dedicated +worker-to-utility MessagePort; they never traverse the JSON-RPC control plane. +The ready, chunk, successful-result, and failed-result frame metadata is owned +by `TerminalInterceptorFrame` in the canonical Schema. Both peers validate the +generated Schema shape and the shared transfer envelope verifies that only +chunk and successful-result frames carry a real attached `ArrayBuffer` whose +length exactly matches the declared bounded `byteLength`. `PluginSecretStore.get()` never returns plaintext. It returns a host-issued `SecretRef`. Its random ID stays opaque; its non-secret `key` binds later lease @@ -531,7 +537,7 @@ The cross-phase contract was checked against every planned consumer: | PR 3 security | principal-bound grants, canonical resources, permission requests/decisions, `SecretRef`/`CredentialRef`/`SecretLeaseRef`, mediated SDK capabilities, stable failures and cancellation | | PR 4 contributions | namespaced settings, commands, menus, views and strict semantic references | | PR 5 terminal providers | namespaced provider IDs, provider request/result envelopes and bounded streams | -| PR 6 data pipeline | MessagePort transfer envelopes, base64 stdio fallback, sequence and receive-window fields | +| PR 6 data pipeline | direct MessagePort transfer envelopes, sequence, per-chunk credit, and bounded receive-window fields | | PR 7 connection/auth/import | provider kinds and configuration schemas, platform-specific companion variants, framing, stable failures and progress | | PR 8 sync | namespaced sync providers and JSON/binary bounded transport | | PR 9 rollout | schema/API selection, compatibility reporting and the final API 1.0 freeze | diff --git a/docs/plugin-platform/isolated-runtime.md b/docs/plugin-platform/isolated-runtime.md index 7a7c16cf4..992d19d9f 100644 --- a/docs/plugin-platform/isolated-runtime.md +++ b/docs/plugin-platform/isolated-runtime.md @@ -113,15 +113,16 @@ migration sources. An installed manifest can declare browser, Node, or both entrypoints. During the internal preview the host uses this deterministic placement rule: -- a manifest that declares native companions is placed in the Node utility - runtime, including when it also declares a browser entrypoint; companion - manifests must provide the Node entrypoint, `runtime.advanced`, and bounded - `companion.execute` resources; +- a manifest that declares native companions or a privileged terminal input or + output interceptor is placed in the Node utility runtime, including when it + also declares a browser entrypoint; these manifests must provide the Node + entrypoint and `runtime.advanced`, while companions additionally require + bounded `companion.execute` resources; - otherwise, a browser entrypoint is preferred whenever it exists; - a Node entrypoint is used when no browser entrypoint exists. The rule keeps ordinary dual-target plugins on the least-privileged runtime -while making the companion exception explicit and fail closed. A later trust +while making the privileged utility exceptions explicit and fail closed. A later trust phase adds verified publisher identity to the advanced Node path; it must not silently upgrade an ordinary plugin. diff --git a/docs/plugin-platform/runtime-extension-boundaries.md b/docs/plugin-platform/runtime-extension-boundaries.md index 78d99cb08..c6f2d4309 100644 --- a/docs/plugin-platform/runtime-extension-boundaries.md +++ b/docs/plugin-platform/runtime-extension-boundaries.md @@ -98,6 +98,13 @@ again after the runtime returns the handle. Browser and utility runtimes implement the same methods over their private router. Later registries do not reach into a runtime window, utility process, MessagePort, or router. +Router requests may carry a reviewed structured-clone transfer list. This is +used to establish privileged terminal interceptor ports while retaining one +owner for correlation, deadlines, cancellation, validation, late responses, +close cleanup, and protocol-failure containment. After the attachment request +is accepted, terminal bytes travel only on the transferred dedicated port and +do not enter the JSON-RPC control plane. + Outgoing requests accept a method-specific result validator. Command and Provider adapters must validate their exact public result schema before using plugin data. The generic JSON boundary remains the first structural limit, not @@ -213,7 +220,7 @@ new protocol route. Plugin packages still cannot add mappings themselves. | PR 6 terminal pipeline | runtime identity and placement policy | direct MessagePort fast path, sensitive-input bypass, circuit breaker | | PR 7 connection/auth/import | requests, validated results, streams, crash containment, `CredentialRef` resolver and `SecretLease` consumer | profiles, challenges, provider lease consumption, importer transactions | | PR 8 sync | streams, lifecycle identity, namespaced storage boundary | dynamic providers, encrypted sidecar, CRDT state and account baselines | -| PR 9 distribution | retained immutable versions, compare-and-set restore, placement resolver, module resources | signatures, trust, health checks, audited update and user rollback policy, API 1.0 | +| PR 9 distribution | retained immutable versions, compare-and-set restore, placement resolver, module resources | signatures, trust, health checks, audited update and user rollback policy, API 1.0, and the reproducible terminal benchmark harness/environment/release gate for the 1% throughput and 4 ms p95 / 8 ms p99 input-latency targets | ## Data-model decisions that must remain explicit diff --git a/docs/plugin-platform/security-and-permissions.md b/docs/plugin-platform/security-and-permissions.md index 53bcd7405..fb5d1e2fc 100644 --- a/docs/plugin-platform/security-and-permissions.md +++ b/docs/plugin-platform/security-and-permissions.md @@ -93,6 +93,8 @@ The first-party placement path selects the utility runtime whenever companions are declared, including manifests that also provide a browser entrypoint. The supervisor repeats the placement check immediately before reserving or spawning a process. Phase 9 adds verified publisher trust to this same boundary. +Privileged Terminal interceptors use the same deterministic utility placement +rule and additionally require their direction-specific interception grant. ### Network diff --git a/docs/plugin-platform/terminal-providers.md b/docs/plugin-platform/terminal-providers.md index 5be35c941..bfb1819b5 100644 --- a/docs/plugin-platform/terminal-providers.md +++ b/docs/plugin-platform/terminal-providers.md @@ -64,6 +64,103 @@ JSON-RPC Provider path is not suitable for hot interception. PR 6 owns the separate permission-gated MessagePort fast path for input/output interceptors, sensitive-input bypass, circuit breaking, and the 4 ms interceptor budget. +## Privileged terminal data pipeline + +PR 6 implements the two declared raw kinds without exposing xterm, Electron +IPC, backend streams, or the general plugin control plane. Only an advanced +utility runtime with `provider.terminal` and the matching +`terminal.intercept.input` or `terminal.intercept.output` grant can be attached. +Authorization is bound to the exact plugin version, runtime ID, runtime kind, +security principal, terminal session, direction, and declared Provider. +Because the transferred port is a long-lived capability, both permissions must +resolve to a session, application, or persistent grant; a one-use grant is +rejected before either port endpoint is published. +Browser runtimes are rejected before a port is transferred. Publisher +signature eligibility remains a distribution-policy decision owned by PR 9; +the advanced runtime and explicit high-risk permission boundary is already +enforced here. + +An activated utility plugin uses the same registration owner and receives a +specialized SDK invocation: + +```ts +context.subscriptions.add(context.providers.register( + "com.example.filter.input", + "terminal.interceptor.input", + async ({ data, session, sequence }) => { + // The transferred UTF-8 Uint8Array is owned by this invocation. + return data; + }, +)); +``` + +For each terminal session, Netcatty permits at most one arbitrary interceptor +per direction. A single candidate can be selected automatically; competing +candidates require an explicit host-owned user choice and "No interceptor" is +the default/cancel action. The choice is session-local and is discarded on +session disposal, contribution withdrawal, runtime replacement, crash, or +quarantine. The requesting renderer must own the terminal session before any +authorization or activation work occurs. + +The main process transfers the two ends of one `MessageChannelMain` directly +to the terminal worker and selected plugin utility process. The utility-side +attachment is established by a transfer-aware `PluginRpcRouter` request, so +the existing router owns correlation, deadline, cancellation, validation, +late-response retirement, close cleanup, and protocol-failure containment. +Only the accepted long-lived byte path leaves the control plane. Data messages +contain a monotonic sequence, direction, bounded credit information, and one +transferable `ArrayBuffer`; the main process never copies terminal payloads. +Ready, chunk, successful-result, and failed-result metadata use the canonical +`TerminalInterceptorFrame` union. Both worker and utility peers validate it +from the generated contract bundle, and the shared MessagePort envelope rejects +missing, unexpected, detached, oversized, or byte-length-mismatched transfers. +The worker serializes chunks, caps each transfer at 64 KiB, and limits queued +output to a 256 KiB credit window. Output remains ordered and host output taps +retain the original data. Renderer flow acknowledgements use the original +ingress count even when a plugin expands, contracts, or completely suppresses +visible output. Host-bypassed sensitive input and protocol replies still wait +behind earlier ordinary input so bypass cannot reorder the terminal stream. + +Input requests have a 4 ms worker-owned deadline. Output requests have a +bounded 50 ms deadline and a 256 KiB queued-output window. A timeout, malformed +response, invalid UTF-8 result, closed port, runtime exit, or credit-window +overflow trips the circuit breaker immediately: the original chunk fails open, +the interceptor is disabled for that session/direction, and Netcatty displays +a host-owned warning. An interceptor cannot suppress that warning or re-enable +itself without a fresh host authorization path. + +These budgets are containment limits, not production performance acceptance +evidence. PR 9 owns the reproducible benchmark harness, supported hardware and +operating-system matrix, and release gate proving no more than 1% no-plugin +throughput regression plus approximately 4 ms p95 / 8 ms p99 added input +latency before the development gate can be removed. + +Credential protection is outside plugin control. Input that the host marks as +sensitive/no-echo bypasses the port before buffer creation, including every +character entered while the password-prompt state is active and confirmed +sudo/su credential autofill. Recorded automation credentials use a password +dialog, remain redacted from script activity/logs, and carry the same sensitive +marker through the script bridge. The terminal worker also recognizes authentication +challenges from bounded original-output tails before output interception, so an +output plugin cannot expose a password by hiding or rewriting its prompt. +Generic PTY protocols do not expose an authoritative live echo-mode signal. +Consequently, a custom or promptless program that disables echo may not be +recognized by the host classifier. The native permission dialog states this +limit before granting input interception, and public enablement remains blocked +until PR 9 restricts the capability to explicitly approved signed advanced +plugins. This is a deliberate limitation of the first terminal data path, not +an absolute no-echo confidentiality guarantee. +Sensitive input is also excluded from terminal broadcast. Terminal protocol replies, urgent interrupts, transfer input gates, +transport encoding, Telnet IAC escaping, host logs, renderer flow accounting, +and marker/safety parsing remain host-owned. Output interceptors may create or +suppress visible byte sequences that affect output-derived lifecycle signals +such as OSC 133. Netcatty owns the parser, marker objects, validation, and +cleanup, but deliberately derives those signals from the transformed visible +stream; credential-prompt classification remains based on bounded original +host output before interception. With no active interceptor, the +worker uses the existing synchronous output path and performs no interceptor +Promise, transfer, or payload allocation. + ## Host adapters Netcatty's built-in autocomplete engine and keyword highlighter use the same diff --git a/docs/plugin-platform/threat-model.md b/docs/plugin-platform/threat-model.md index b903b951f..d496446c9 100644 --- a/docs/plugin-platform/threat-model.md +++ b/docs/plugin-platform/threat-model.md @@ -136,9 +136,15 @@ than only in UI or command registration. ### Secret exfiltration Secret values are never ordinary settings or JSON-RPC results. The credential -broker uses operation-bound, single-use leases. Terminal sensitive-input mode -bypasses third-party hooks unconditionally. Logs, diagnostics, synchronization, -and crash reports redact secret fields before persistence. +broker uses operation-bound, single-use leases. Terminal input that Netcatty +marks sensitive through host-owned state or recognized original-output +credential challenges bypasses third-party hooks unconditionally. Generic PTYs +do not expose a trustworthy live echo-mode signal, so an arbitrary custom or +promptless no-echo program cannot be identified in every protocol. The native +input-interception permission warning discloses this limit, and public use stays +restricted to explicitly approved signed advanced plugins in the final rollout +stage. Logs, diagnostics, synchronization, and crash reports redact secret +fields before persistence. The SDK secret store returns an opaque `SecretRef`, never stored plaintext. Netcatty-owned Vault material uses a distinct opaque `CredentialRef`; its main-process resolver validates availability without materializing plaintext, @@ -192,7 +198,11 @@ The platform is not ready for public enablement unless all of these hold: 2. A declaration is not a grant, and a grant is limited to its declared resource and lifetime. 3. No renderer means interactive permission requests fail closed. -4. Password and no-echo input never reaches plugin hooks. +4. Input marked sensitive by host-owned state or recognized credential-prompt + detection never reaches plugin hooks. Generic input interception warns that + arbitrary custom or promptless no-echo input cannot be detected reliably by + a remote PTY, and remains unavailable to public plugins until the signed + advanced-plugin rollout gate is enforced. 5. The package installed is the package validated and, later, signed. 6. A plugin cannot address another plugin's storage or runtime by changing an identifier in its request. diff --git a/electron/bridges/emitTerminalSessionData.cjs b/electron/bridges/emitTerminalSessionData.cjs index 2b5b18f0f..c41774347 100644 --- a/electron/bridges/emitTerminalSessionData.cjs +++ b/electron/bridges/emitTerminalSessionData.cjs @@ -76,6 +76,8 @@ function getEmitPerfLogDetails(sessionId, terminalPerf, options = {}) { } function emitTerminalSessionData(contents, sessionId, data, options = {}) { + const currentSession = getSession && sessionId ? getSession(sessionId) : null; + if (options.session && currentSession !== options.session) return false; if (sessionId && data && onSessionActivity) { try { onSessionActivity({ sessionId, phase: "touch" }); @@ -83,11 +85,8 @@ function emitTerminalSessionData(contents, sessionId, data, options = {}) { // Session activity tracking is best-effort and must not break output. } } - if (getSession && sessionId && data) { - const session = getSession(sessionId); - if (session) { - trackEmitted(session, typeof data === "string" ? data.length : 0, sessionId); - } + if (currentSession && sessionId && data) { + trackEmitted(currentSession, typeof data === "string" ? data.length : 0, sessionId); } if (sessionId && data) { for (const tap of dataTaps) { @@ -104,8 +103,15 @@ function emitTerminalSessionData(contents, sessionId, data, options = {}) { if (emitPerfDetails) { logTerminalOutputPerf("backend-emit", emitPerfDetails); } - if (outputChannel?.send?.(sessionId, data, meta)) return; - contents?.send("netcatty:data", meta ? { sessionId, data, meta } : { sessionId, data }); + if (outputChannel?.send?.(sessionId, data, meta)) return true; + const generation = options.session?._terminalSessionGeneration; + contents?.send("netcatty:data", { + sessionId, + data, + ...(meta ? { meta } : {}), + ...(Number.isSafeInteger(generation) ? { _terminalSessionGeneration: generation } : {}), + }); + return true; } module.exports = { diff --git a/electron/bridges/emitTerminalSessionData.test.cjs b/electron/bridges/emitTerminalSessionData.test.cjs index 9840b6818..075300c86 100644 --- a/electron/bridges/emitTerminalSessionData.test.cjs +++ b/electron/bridges/emitTerminalSessionData.test.cjs @@ -2,10 +2,56 @@ const assert = require("node:assert/strict"); const test = require("node:test"); const { + addTerminalDataTap, configureTerminalSessionDataEmitter, emitTerminalSessionData, } = require("./emitTerminalSessionData.cjs"); +test("emitTerminalSessionData rejects output from a replaced backend session", () => { + const oldSession = { _terminalSessionGeneration: 0 }; + const newSession = { _terminalSessionGeneration: 1 }; + const sent = []; + const tapped = []; + const removeTap = addTerminalDataTap((sessionId, data) => tapped.push({ sessionId, data })); + configureTerminalSessionDataEmitter({ + getSession: () => newSession, + outputChannel: { send: () => false }, + }); + + const delivered = emitTerminalSessionData({ + send(channel, payload) { sent.push({ channel, payload }); }, + }, "session-1", "old-secret", { session: oldSession }); + + assert.equal(delivered, false); + assert.deepEqual(tapped, []); + assert.deepEqual(sent, []); + removeTap(); + configureTerminalSessionDataEmitter({}); +}); + +test("emitTerminalSessionData binds fallback output to the backend generation", () => { + const session = { _terminalSessionGeneration: 3 }; + const sent = []; + configureTerminalSessionDataEmitter({ + getSession: () => session, + outputChannel: { send: () => false }, + }); + + emitTerminalSessionData({ + send(channel, payload) { sent.push({ channel, payload }); }, + }, "session-1", "hello", { session }); + + assert.deepEqual(sent, [{ + channel: "netcatty:data", + payload: { + sessionId: "session-1", + data: "hello", + _terminalSessionGeneration: 3, + }, + }]); + configureTerminalSessionDataEmitter({}); +}); + test("emitTerminalSessionData prefers the dedicated terminal output channel", () => { const sent = []; const outputChannel = { diff --git a/electron/bridges/scriptBridge.cjs b/electron/bridges/scriptBridge.cjs index 0275ec7b1..bad41037a 100644 --- a/electron/bridges/scriptBridge.cjs +++ b/electron/bridges/scriptBridge.cjs @@ -166,6 +166,7 @@ function writeToSession(sessionId, data, options = {}) { sessionId, data, automated: options.automated !== false, + ...(options.sensitive === true ? { sensitive: true } : {}), }; const webContentsId = getMainWindow?.()?.webContents?.id; if (terminalWorkerManager) { diff --git a/electron/bridges/sshBridge/startSession.cjs b/electron/bridges/sshBridge/startSession.cjs index 26f482d2b..16f5d2e27 100644 --- a/electron/bridges/sshBridge/startSession.cjs +++ b/electron/bridges/sshBridge/startSession.cjs @@ -338,18 +338,19 @@ printf '%s\n' '${scanCompleteMarker}'`; takePendingEntry: takePendingBuffer, discard: discardBuffer, } = createPtyOutputBuffer((data, meta) => { + if (sessions.get(sessionId) !== session) return; const contents = event.sender; - const current = sessions.get(sessionId); emitTerminalSessionData(contents, sessionId, data, { - cols: current?.cols, - rows: current?.rows, + session, + cols: session.cols, + rows: session.rows, meta, }); }, { onPendingBytesChange: (bytes) => { if (sessions.get(sessionId) === session) setBufferedOutputBytes(session, bytes); }, - shouldAcceptOutput: () => shouldAcceptSessionOutput(sessions.get(sessionId)), + shouldAcceptOutput: () => sessions.get(sessionId) === session && shouldAcceptSessionOutput(session), }); session.flushPendingData = flushBufferPaced; session.takePendingData = takePendingBuffer; @@ -369,6 +370,7 @@ printf '%s\n' '${scanCompleteMarker}'`; const sshZmodemSentry = createZmodemSentry({ sessionId, onData(buf) { + if (sessions.get(sessionId) !== session) return; const decoder = getSessionDecoder(sessionId, "stdout"); const decoded = decoder.write(buf); const output = filterTerminalInterruptOutput(session, decoded); @@ -432,19 +434,19 @@ printf '%s\n' '${scanCompleteMarker}'`; return getCurrentSessionWebContents(); }, selectUploadFiles: selectZmodemUploadFiles - ? () => selectZmodemUploadFiles(getCurrentSessionWebContentsId()) + ? () => selectZmodemUploadFiles(getCurrentSessionWebContentsId(), sessionId) : undefined, selectDownloadDirectory: selectZmodemDownloadDirectory - ? () => selectZmodemDownloadDirectory(getCurrentSessionWebContentsId()) + ? () => selectZmodemDownloadDirectory(getCurrentSessionWebContentsId(), sessionId) : undefined, label: "SSH", }); session.zmodemSentry = sshZmodemSentry; stream.on("data", (data) => { - const currentSession = sessions.get(sessionId); - if (!shouldProcessSessionOutput(currentSession, sshZmodemSentry)) { - logTerminalOutputDropSample(currentSession, { + if (sessions.get(sessionId) !== session) return; + if (!shouldProcessSessionOutput(session, sshZmodemSentry)) { + logTerminalOutputDropSample(session, { sessionId, stream: "stdout", bytes: Buffer.isBuffer(data) ? data.length : Buffer.byteLength(String(data)), @@ -457,9 +459,9 @@ printf '%s\n' '${scanCompleteMarker}'`; }); stream.stderr?.on("data", (data) => { - const currentSession = sessions.get(sessionId); - if (!shouldProcessSessionOutput(currentSession)) { - logTerminalOutputDropSample(currentSession, { + if (sessions.get(sessionId) !== session) return; + if (!shouldProcessSessionOutput(session)) { + logTerminalOutputDropSample(session, { sessionId, stream: "stderr", bytes: Buffer.isBuffer(data) ? data.length : Buffer.byteLength(String(data)), @@ -469,9 +471,9 @@ printf '%s\n' '${scanCompleteMarker}'`; // stderr is not used for ZMODEM — decode normally const decoder = getSessionDecoder(sessionId, "stderr"); const decoded = decoder.write(data); - const output = filterTerminalInterruptOutput(currentSession, decoded); + const output = filterTerminalInterruptOutput(session, decoded); if (!output.accepted) { - logTerminalInterruptDrainDropSample(currentSession, { + logTerminalInterruptDrainDropSample(session, { sessionId, stream: "stderr", droppedBytes: output.droppedBytes, @@ -481,7 +483,7 @@ printf '%s\n' '${scanCompleteMarker}'`; return; } if (output.droppedBytes > 0) { - logTerminalInterruptDrainDropSample(currentSession, { + logTerminalInterruptDrainDropSample(session, { sessionId, stream: "stderr", droppedBytes: output.droppedBytes, @@ -490,7 +492,7 @@ printf '%s\n' '${scanCompleteMarker}'`; }); } if (!output.data) return; - const outputMeta = takePendingInterruptOutputMeta(currentSession); + const outputMeta = takePendingInterruptOutputMeta(session); bufferData(output.data, outputMeta); sessionLogStreamManager.appendData(sessionId, output.data); }); @@ -531,14 +533,20 @@ printf '%s\n' '${scanCompleteMarker}'`; // Only send exit if session hasn't already been cleaned up by // conn.once("close") — which fires before stream.on("close") // in ssh2 when the transport drops. - if (sessions.has(sessionId)) { + const liveSession = sessions.get(sessionId); + if (liveSession === session) { const contents = event.sender; - const liveSession = sessions.get(sessionId); const transportError = liveSession?._transportError; if (liveSession?.closed) { // Explicit close already notified every attached renderer. } else if (transportError) { - safeSendSessionExit({ safeSend, electronModule, sessions }, contents, sessionId, { sessionId, exitCode: 1, error: transportError, reason: "error" }); + safeSendSessionExit({ safeSend, electronModule, sessions }, contents, sessionId, { + sessionId, + exitCode: 1, + error: transportError, + reason: "error", + _terminalSessionGeneration: liveSession?._terminalSessionGeneration, + }); } else { // A shell TMOUT auto-logout is a clean exit (numeric code, no // signal) — identical to a user-typed `exit` by code/signal — @@ -547,7 +555,12 @@ printf '%s\n' '${scanCompleteMarker}'`; // for reconnect instead of auto-closing it (#1062 / #977). const idleTimedOut = streamExited && looksLikeIdleAutoLogout(liveSession?._promptTrackTail); const reason = idleTimedOut ? "timeout" : (streamExited ? "exited" : "closed"); - safeSendSessionExit({ safeSend, electronModule, sessions }, contents, sessionId, { sessionId, exitCode: streamExitCode, reason }); + safeSendSessionExit({ safeSend, electronModule, sessions }, contents, sessionId, { + sessionId, + exitCode: streamExitCode, + reason, + _terminalSessionGeneration: liveSession?._terminalSessionGeneration, + }); } liveSession?.zmodemSentry?.cancel(); // Release this channel's hold on the shared connection. The transport @@ -1641,9 +1654,12 @@ printf '%s\n' '${scanCompleteMarker}'`; sendProgress(totalHops, totalHops, options.hostname, 'authenticated'); sendProgress(totalHops, totalHops, options.hostname, 'shell'); + let establishedOwnerSession = null; const sendTerminalMessage = (data) => { const current = sessions.get(sessionId); + if (establishedOwnerSession && current !== establishedOwnerSession) return; emitTerminalSessionData(event.sender, sessionId, data, { + ...(establishedOwnerSession ? { session: establishedOwnerSession } : {}), cols: current?.cols, rows: current?.rows, }); @@ -1717,6 +1733,7 @@ printf '%s\n' '${scanCompleteMarker}'`; chainConnections, isReused: false, }); + establishedOwnerSession = ownerSession; connRef = createConnectionRef(ownerSession, conn, chainConnections); // Capture this connection's log stream token in the closure so // the connection-level handlers below stop the right stream even @@ -1889,9 +1906,20 @@ printf '%s\n' '${scanCompleteMarker}'`; const transportError = session?._transportError; if (transportError) { // A transport error was recorded — report it as an error exit - safeSendSessionExit({ safeSend, electronModule, sessions }, contents, sessionId, { sessionId, exitCode: 1, error: transportError, reason: "error" }); + safeSendSessionExit({ safeSend, electronModule, sessions }, contents, sessionId, { + sessionId, + exitCode: 1, + error: transportError, + reason: "error", + _terminalSessionGeneration: session?._terminalSessionGeneration, + }); } else { - safeSendSessionExit({ safeSend, electronModule, sessions }, contents, sessionId, { sessionId, exitCode: 0, reason: "closed" }); + safeSendSessionExit({ safeSend, electronModule, sessions }, contents, sessionId, { + sessionId, + exitCode: 0, + reason: "closed", + _terminalSessionGeneration: session?._terminalSessionGeneration, + }); } // Use this connection's captured token so a late close from an // old transport can't stop a newer same-sessionId stream (#916). diff --git a/electron/bridges/terminalAttachRestore.cjs b/electron/bridges/terminalAttachRestore.cjs index 86be5425c..d2ce26b58 100644 --- a/electron/bridges/terminalAttachRestore.cjs +++ b/electron/bridges/terminalAttachRestore.cjs @@ -50,12 +50,13 @@ function setRestoreAttachedSessionOutput(fn) { restoreImpl = typeof fn === "function" ? fn : null; } -function restoreAttachedSessionOutput(sessionId, preferredHomeWebContentsId = null) { +async function restoreAttachedSessionOutput(sessionId, preferredHomeWebContentsId = null) { if (!sessionId || typeof restoreImpl !== "function") { return { success: false, restored: false }; } try { - const result = restoreImpl(sessionId, preferredHomeWebContentsId) || { success: true, restored: false }; + const result = await restoreImpl(sessionId, preferredHomeWebContentsId) + || { success: true, restored: false }; if (result.success) pendingAttachRestores.delete(sessionId); else pendingAttachRestores.add(sessionId); return result; @@ -65,15 +66,15 @@ function restoreAttachedSessionOutput(sessionId, preferredHomeWebContentsId = nu } } -function retryPendingAttachedSessionOutputs() { - for (const sessionId of Array.from(pendingAttachRestores)) { - restoreAttachedSessionOutput(sessionId); - } +async function retryPendingAttachedSessionOutputs() { + await Promise.all(Array.from(pendingAttachRestores, (sessionId) => ( + restoreAttachedSessionOutput(sessionId) + ))); } -function retryPendingAttachedSessionOutput(sessionId, preferredHomeWebContentsId = null) { +async function retryPendingAttachedSessionOutput(sessionId, preferredHomeWebContentsId = null) { if (!pendingAttachRestores.has(sessionId)) return { success: true, restored: false }; - return restoreAttachedSessionOutput(sessionId, preferredHomeWebContentsId); + return await restoreAttachedSessionOutput(sessionId, preferredHomeWebContentsId); } function setAttachHomeLookup(fn) { diff --git a/electron/bridges/terminalBridge.cjs b/electron/bridges/terminalBridge.cjs index 23bc40743..fa9ca4e1d 100644 --- a/electron/bridges/terminalBridge.cjs +++ b/electron/bridges/terminalBridge.cjs @@ -63,6 +63,7 @@ const { createPtyOutputBuffer } = require("./ptyOutputBuffer.cjs"); const { enableTcpNoDelay } = require("./tcpNoDelay.cjs"); const { releaseConnectionRef } = require("./sshConnectionPool.cjs"); const { normalizeTerminalEncoding, encodeTerminalInput } = require("./terminalEncoding.cjs"); +const { isTerminalReportSequence } = require("./terminalReportSequence.cjs"); const { receiveYmodemFiles, sendYmodemCancel, sendYmodemFile } = require("./ymodemTransfer.cjs"); const { getNativeOpenSshAgentSocket, @@ -78,6 +79,8 @@ let terminalOutputChannel = null; let selectZmodemUploadFiles = null; let selectZmodemDownloadDirectory = null; let reportOpenedSessionActivity = null; +let terminalDataPipeline = null; +const terminalInputPipelineBarriers = new Map(); const DEFAULT_UTF8_LOCALE = "en_US.UTF-8"; const LOGIN_SHELLS = new Set(["bash", "zsh", "fish", "ksh"]); @@ -117,6 +120,8 @@ function init(deps) { reportOpenedSessionActivity = typeof deps.reportOpenedSessionActivity === "function" ? deps.reportOpenedSessionActivity : null; + terminalDataPipeline = deps.terminalDataPipeline || null; + terminalInputPipelineBarriers.clear(); configureTerminalSessionDataEmitter({ getSession: (sessionId) => sessions?.get(sessionId), outputChannel: terminalOutputChannel, @@ -126,6 +131,11 @@ function init(deps) { } function openTerminalOutputSession(sessionId, webContents) { + const generation = webContents?.claimSessionGeneration?.(sessionId); + const session = sessions?.get?.(sessionId); + if (session && Number.isSafeInteger(generation)) { + session._terminalSessionGeneration = generation; + } terminalOutputChannel?.openSession?.(sessionId, webContents); } @@ -239,6 +249,11 @@ function handleTerminalSessionSnapshotResponse(event, payload) { kittyKeyboardProtocolEnabled: typeof payload?.kittyKeyboardProtocolEnabled === "boolean" ? payload.kittyKeyboardProtocolEnabled : undefined, + passwordPromptActive: typeof payload?.passwordPromptActive === "boolean" + ? payload.passwordPromptActive + : undefined, + cwd: payload?.cwd === null ? null : typeof payload?.cwd === "string" ? payload.cwd : undefined, + title: payload?.title === null ? null : typeof payload?.title === "string" ? payload.title : undefined, }); } @@ -293,6 +308,11 @@ function applyTerminalSessionSnapshot(event, payload, terminalWorkerManager = nu const kittyKeyboardProtocolEnabled = typeof payload?.kittyKeyboardProtocolEnabled === "boolean" ? payload.kittyKeyboardProtocolEnabled : undefined; + const passwordPromptActive = typeof payload?.passwordPromptActive === "boolean" + ? payload.passwordPromptActive + : undefined; + const cwd = payload?.cwd === null ? null : typeof payload?.cwd === "string" ? payload.cwd : undefined; + const title = payload?.title === null ? null : typeof payload?.title === "string" ? payload.title : undefined; if ( !sessionId || !hasSnapshot @@ -338,6 +358,9 @@ function applyTerminalSessionSnapshot(event, payload, terminalWorkerManager = nu alternateScreen, kittyKeyboardModeState, kittyKeyboardProtocolEnabled, + passwordPromptActive, + cwd, + title, requestId, }); } catch (err) { @@ -370,7 +393,7 @@ function handleTerminalSessionApplySnapshotResponse(event, payload) { * by terminalWorkerManager (sessionWebContentsIds + output ports). * In-process mode: sessions Map in this bridge owns webContentsId. */ -function rebindTerminalSessionOutput(event, payload, terminalWorkerManager = null) { +async function rebindTerminalSessionOutput(event, payload, terminalWorkerManager = null) { const sessionId = typeof payload?.sessionId === "string" ? payload.sessionId : ""; if (!sessionId) { return { success: false, error: "Missing sessionId" }; @@ -385,9 +408,9 @@ function rebindTerminalSessionOutput(event, payload, terminalWorkerManager = nul if (terminalWorkerManager) { try { - const result = terminalWorkerManager.rebindOutputSession(sessionId, sender.id); + const result = await terminalWorkerManager.rebindOutputSession(sessionId, sender.id); if (result?.success && sender.isDestroyed?.()) { - restoreAttachedSessionOutput(sessionId, terminalWorkerManager); + await restoreAttachedSessionOutput(sessionId, terminalWorkerManager); return { success: false, error: "Attach window closed during rebind" }; } return result; @@ -413,7 +436,7 @@ function rebindTerminalSessionOutput(event, payload, terminalWorkerManager = nul openTerminalOutputSession(sessionId, sender); session.webContentsId = sender.id; if (sender.isDestroyed?.()) { - restoreAttachedSessionOutput(sessionId, terminalWorkerManager); + await restoreAttachedSessionOutput(sessionId, terminalWorkerManager); return { success: false, error: "Attach window closed during rebind" }; } return { @@ -457,7 +480,13 @@ function pauseSessionOutputFlow(sessionId, terminalWorkerManager = null) { try { setRendererFlowPaused(session, true); } catch {} } -function fanoutSessionLifecycleEvent(sessionId, primaryWebContentsId, channel, payload) { +function fanoutSessionLifecycleEvent( + sessionId, + primaryWebContentsId, + channel, + payload, + terminalSessionGeneration, +) { const targets = new Set(); if (typeof primaryWebContentsId === "number") targets.add(primaryWebContentsId); const homeId = attachHomeWebContentsIds.get(sessionId); @@ -465,7 +494,9 @@ function fanoutSessionLifecycleEvent(sessionId, primaryWebContentsId, channel, p for (const id of targets) { try { const contents = electronModule?.webContents?.fromId?.(id); - contents?.send?.(channel, payload); + contents?.send?.(channel, Number.isSafeInteger(terminalSessionGeneration) + ? { ...payload, _terminalSessionGeneration: terminalSessionGeneration } + : payload); } catch { // ignore destroyed renderers } @@ -495,7 +526,7 @@ function findRegisteredMainWebContents(preferredId) { return null; } -function restoreAttachedSessionOutput( +async function restoreAttachedSessionOutput( sessionId, terminalWorkerManager = null, preferredHomeWebContentsId = null, @@ -504,7 +535,7 @@ function restoreAttachedSessionOutput( pauseSessionOutputFlow(sessionId, terminalWorkerManager); let result; if (terminalWorkerManager?.restoreAttachHome) { - result = terminalWorkerManager.restoreAttachHome(sessionId, preferredHomeWebContentsId); + result = await terminalWorkerManager.restoreAttachHome(sessionId, preferredHomeWebContentsId); } else { const homeId = attachHomeWebContentsIds.get(sessionId); if (homeId == null) { @@ -545,7 +576,7 @@ function restoreAttachedSessionOutput( * Restore output to a previous renderer after an attach popup closes. * Falls back to the first live main-ish window if the home webContents is gone. */ -function restoreTerminalSessionOutput(event, payload, terminalWorkerManager = null) { +async function restoreTerminalSessionOutput(event, payload, terminalWorkerManager = null) { const sessionId = typeof payload?.sessionId === "string" ? payload.sessionId : ""; if (!sessionId) { return { success: false, error: "Missing sessionId" }; @@ -566,7 +597,7 @@ function restoreTerminalSessionOutput(event, payload, terminalWorkerManager = nu return { success: true, restored: false }; } try { - const result = terminalWorkerManager.rebindOutputSession(sessionId, target.id); + const result = await terminalWorkerManager.rebindOutputSession(sessionId, target.id); if (!result?.success) { return { success: false, error: result?.error || "Failed to restore session output" }; } @@ -932,6 +963,7 @@ function startLocalSession(event, payload) { } = createPtyOutputBuffer((data, meta) => { const contents = electronModule.webContents.fromId(session.webContentsId); emitTerminalSessionData(contents, sessionId, data, { + session, cols: session.cols, rows: session.rows, meta, @@ -965,21 +997,23 @@ function startLocalSession(event, payload) { return electronModule.webContents.fromId(session.webContentsId); }, selectUploadFiles: selectZmodemUploadFiles - ? () => selectZmodemUploadFiles(session.webContentsId) + ? () => selectZmodemUploadFiles(session.webContentsId, sessionId) : undefined, selectDownloadDirectory: selectZmodemDownloadDirectory - ? () => selectZmodemDownloadDirectory(session.webContentsId) + ? () => selectZmodemDownloadDirectory(session.webContentsId, sessionId) : undefined, label: "Local", }); session.zmodemSentry = zmodemSentry; proc.onData((data) => { + if (sessions.get(sessionId) !== session) return; if (!shouldProcessSessionOutput(session, zmodemSentry)) return; zmodemSentry.consume(data); }); } else { proc.onData((data) => { + if (sessions.get(sessionId) !== session) return; if (!shouldProcessSessionOutput(session)) return; trackSessionIdlePrompt(session, data); bufferLocalData(data); @@ -993,6 +1027,7 @@ function startLocalSession(event, payload) { if (localExitFinalized) return; localExitFinalized = true; sessionLogStreamManager.stopStream(sessionId, logStreamToken); + if (sessions.get(sessionId) !== session) return; ptyProcessTree.unregisterPid(sessionId); sessions.delete(sessionId); if (session.closed) return; @@ -1005,6 +1040,7 @@ function startLocalSession(event, payload) { session.webContentsId, "netcatty:exit", { sessionId, ...evt, reason }, + session._terminalSessionGeneration, ); }; flushLocalPaced(finalizeExit); @@ -1195,6 +1231,7 @@ async function startSerialSession(event, options) { if (!decoded) return; const contents = electronModule.webContents.fromId(session.webContentsId); emitTerminalSessionData(contents, sessionId, decoded, { + session, cols: session.cols, rows: session.rows, }); @@ -1207,24 +1244,27 @@ async function startSerialSession(event, options) { return electronModule.webContents.fromId(session.webContentsId); }, selectUploadFiles: selectZmodemUploadFiles - ? () => selectZmodemUploadFiles(session.webContentsId) + ? () => selectZmodemUploadFiles(session.webContentsId, sessionId) : undefined, selectDownloadDirectory: selectZmodemDownloadDirectory - ? () => selectZmodemDownloadDirectory(session.webContentsId) + ? () => selectZmodemDownloadDirectory(session.webContentsId, sessionId) : undefined, label: "Serial", }); session.zmodemSentry = serialZmodemSentry; serialPort.on('data', (data) => { + if (sessions.get(sessionId) !== session) return; if (session.ymodemActive) return; if (!shouldProcessSessionOutput(session, serialZmodemSentry)) return; // data is already Buffer from serialport — feed to sentry serialZmodemSentry.consume(data); }); - serialPort.on('error', (err) => { - console.error(`[Serial] Port error: ${err.message}`); + let serialExitFinalized = false; + const finalizeSerialExit = ({ exitCode, error, reason }) => { + if (serialExitFinalized || sessions.get(sessionId) !== session) return; + serialExitFinalized = true; session.zmodemSentry?.cancel(); session.ymodemAbortController?.abort(); sessionLogStreamManager.stopStream(sessionId, logStreamToken); @@ -1236,25 +1276,19 @@ async function startSerialSession(event, options) { sessionId, primaryId, "netcatty:exit", - { sessionId, exitCode: 1, error: err.message, reason: "error" }, + { sessionId, exitCode, ...(error ? { error } : {}), reason }, + session._terminalSessionGeneration, ); + }; + + serialPort.on('error', (err) => { + console.error(`[Serial] Port error: ${err.message}`); + finalizeSerialExit({ exitCode: 1, error: err.message, reason: "error" }); }); serialPort.on('close', () => { console.log(`[Serial] Port closed`); - session.zmodemSentry?.cancel(); - session.ymodemAbortController?.abort(); - sessionLogStreamManager.stopStream(sessionId, logStreamToken); - const primaryId = session.webContentsId; - ptyProcessTree.unregisterPid(sessionId); - sessions.delete(sessionId); - if (session.closed) return; - fanoutSessionLifecycleEvent( - sessionId, - primaryId, - "netcatty:exit", - { sessionId, exitCode: 0, reason: "closed" }, - ); + finalizeSerialExit({ exitCode: 0, reason: "closed" }); }); resolve({ sessionId }); @@ -1314,25 +1348,6 @@ function clearPendingAutomatedWrites(session) { session.pendingAutomatedWriteTimers = []; } -// Terminal-originated automatic replies (cursor position reports, device -// attributes, focus in/out, etc.) travel through the same write path as user -// keystrokes but must NOT be treated as "the user started typing". A terminal -// routinely emits such a reply right after the first line runs; counting it as -// manual input would clear the pending automated line-by-line writes and only -// the first line would ever be sent (multi-line compose-bar input bug). -function isTerminalReportSequence(data) { - if (typeof data !== "string" || data.length === 0) return false; - // Focus in/out reports: ESC [ I / ESC [ O - if (data === "\x1b[I" || data === "\x1b[O") return true; - // CPR / DECXCPR / DA1 / DA2 / DSR: ESC [ (?|>)? digits/semicolons (R|c|n) - if (/^\x1b\[[?>]?[0-9;]*[Rcn]$/.test(data)) return true; - // Kitty keyboard mode query reply: ESC [ ? digits u - if (/^\x1b\[\?[0-9]+u$/.test(data)) return true; - // DCS replies (XTGETTCAP / DECRQSS, etc.): ESC P ... ESC \ - if (/^\x1bP[\s\S]*\x1b\\$/.test(data)) return true; - return false; -} - function splitTerminalInputIntoLineWrites(data) { if (typeof data !== "string") return [data]; const chunks = []; @@ -1467,6 +1482,51 @@ function writeToSessionNow(payload, data, logRewrite = payload.logRewrite) { } } +function writeToSessionWithInterception( + payload, + data, + logRewrite = payload.logRewrite, + expectedSession = sessions.get(payload.sessionId), +) { + const bypass = payload?.sensitive === true || isTerminalReportSequence(data); + const hasInterceptor = Boolean( + terminalDataPipeline?.interceptInput + && terminalDataPipeline.has?.(payload.sessionId, "input"), + ); + const previous = terminalInputPipelineBarriers.get(payload.sessionId); + if (!hasInterceptor && !previous) { + writeToSessionNow(payload, data, logRewrite); + return; + } + const writeIfCurrent = (nextData) => { + const current = sessions.get(payload.sessionId); + if (!current || current !== expectedSession || current.closed) return; + writeToSessionNow(payload, nextData, logRewrite); + }; + const write = async () => { + if (!hasInterceptor) { + writeIfCurrent(data); + return; + } + try { + const transformed = await terminalDataPipeline.interceptInput(payload.sessionId, data, { + sensitive: payload?.sensitive === true, + bypass, + }); + writeIfCurrent(transformed); + } catch { + writeIfCurrent(data); + } + }; + const operation = previous ? previous.then(write, write) : Promise.resolve().then(write); + terminalInputPipelineBarriers.set(payload.sessionId, operation); + void operation.finally(() => { + if (terminalInputPipelineBarriers.get(payload.sessionId) === operation) { + terminalInputPipelineBarriers.delete(payload.sessionId); + } + }); +} + function writeToSession(event, payload) { const session = sessions.get(payload.sessionId); if (!session) return; @@ -1493,10 +1553,11 @@ function writeToSession(event, payload) { const sendChunk = () => { const current = sessions.get(payload.sessionId); if (!current) return; - writeToSessionNow( + writeToSessionWithInterception( { ...payload, lineDelayMs: undefined }, chunk, index === 0 ? payload.logRewrite : undefined, + current, ); }; if (index === 0) { @@ -1509,7 +1570,7 @@ function writeToSession(event, payload) { return; } - writeToSessionNow(payload, payload.data); + writeToSessionWithInterception(payload, payload.data, payload.logRewrite, session); } function drainPendingOutputForInterrupt(sessionId, session, trace) { @@ -1534,6 +1595,7 @@ function drainPendingOutputForInterrupt(sessionId, session, trace) { const outputMeta = takePendingInterruptOutputMeta(session, pendingMeta); const contents = electronModule.webContents.fromId(session.webContentsId); emitTerminalSessionData(contents, sessionId, output.data, { + session, cols: session.cols, rows: session.rows, meta: outputMeta, @@ -1761,7 +1823,9 @@ function closeSession(event, payload) { session.webContentsId, "netcatty:exit", { sessionId: payload.sessionId, exitCode: 0, reason: "closed" }, + session._terminalSessionGeneration, ); + terminalInputPipelineBarriers.delete(payload.sessionId); closeTerminalOutputSession(payload.sessionId); try { diff --git a/electron/bridges/terminalBridge.rebindOutput.test.cjs b/electron/bridges/terminalBridge.rebindOutput.test.cjs index f0d4ca60f..3d0b527ec 100644 --- a/electron/bridges/terminalBridge.rebindOutput.test.cjs +++ b/electron/bridges/terminalBridge.rebindOutput.test.cjs @@ -27,6 +27,9 @@ function loadTerminalBridgeWithMocks() { if (request === "./emitTerminalSessionData.cjs" || request.endsWith("emitTerminalSessionData.cjs")) { return { configureTerminalSessionDataEmitter: () => {} }; } + if (request === "electron") { + return {}; + } return originalRequire.apply(this, arguments); }; @@ -85,8 +88,9 @@ test("worker renderer-event forwarding prefers rebound webContentsId", () => { assert.match(source, /attachHomeWebContentsIds/); assert.match(source, /restoreAttachHome/); // Exit cleanup must not run before we capture display/home targets. - const captureIdx = source.indexOf("const displayWebContentsId ="); - const closeIdx = source.indexOf('if (message.channel === "netcatty:exit"'); + const rendererEventIdx = source.indexOf('if (message.kind === "renderer-event")'); + const captureIdx = source.indexOf("const displayWebContentsId =", rendererEventIdx); + const closeIdx = source.indexOf('if (message.channel === "netcatty:exit" && sessionId)', captureIdx); assert.ok(captureIdx > 0 && closeIdx > captureIdx, "capture targets before closeOutputSession on exit"); assert.match( source, @@ -187,7 +191,39 @@ test("in-process explicit close sends an exit event before dropping the output r assert.match(sshSource, /if \(liveSession\?\.closed\)/, "SSH close callback suppresses duplicate explicit-close exits"); }); -test("in-process explicit close notifies a rebound popup and its home renderer", () => { +test("late backend exits cannot tear down a replacement with the same session id", () => { + const bridgeSource = require("node:fs").readFileSync( + path.join(__dirname, "terminalBridge.cjs"), + "utf8", + ); + const sshSource = require("node:fs").readFileSync( + path.join(__dirname, "sshBridge/startSession.cjs"), + "utf8", + ); + const telnetSource = require("node:fs").readFileSync( + path.join(__dirname, "terminalBridge/telnetSession.cjs"), + "utf8", + ); + const moshSource = require("node:fs").readFileSync( + path.join(__dirname, "terminalBridge/moshSession.cjs"), + "utf8", + ); + const etSource = require("node:fs").readFileSync( + path.join(__dirname, "terminalBridge/etSession.cjs"), + "utf8", + ); + + assert.match(sshSource, /if \(liveSession === session\)/); + assert.match(bridgeSource, /if \(sessions\.get\(sessionId\) !== session\) return;/); + assert.match(bridgeSource, /serialExitFinalized \|\| sessions\.get\(sessionId\) !== session/); + assert.match(telnetSource, /sessions\.get\(sessionId\) !== activeSession/); + assert.match(moshSource, /sessions\.get\(sessionId\) !== session/); + assert.match(etSource, /sessions\.get\(sessionId\) !== session/); + assert.match(sshSource, /establishedOwnerSession && current !== establishedOwnerSession/); + assert.match(sshSource, /establishedOwnerSession \? \{ session: establishedOwnerSession \} : \{\}/); +}); + +test("in-process explicit close notifies a rebound popup and its home renderer", async () => { const { bridge, fakeChannel } = loadTerminalBridgeWithMocks(); const sent = []; const contents = new Map([7, 9].map((id) => [id, { @@ -215,10 +251,10 @@ test("in-process explicit close notifies a rebound popup and its home renderer", }; bridge.registerHandlers(ipcMain); assert.equal( - ipcMain.handlers.get("netcatty:terminal:rebindOutput")( + (await ipcMain.handlers.get("netcatty:terminal:rebindOutput")( { sender: contents.get(9) }, { sessionId: "session-close", authorization: "close-grant" }, - ).success, + )).success, true, ); @@ -267,6 +303,10 @@ test("snapshot apply acknowledgements are emitted only by the matching terminal" assert.match(terminalSource, /\?\? kittyKeyboardProtocolEnabledForSession/); assert.match(terminalSource, /setKittyKeyboardProtocolEnabled/); assert.match(effectsSource, /runtime\.setKittyKeyboardProtocolEnabled\(snap\.kittyKeyboardProtocolEnabled\)/); + assert.match(terminalSource, /passwordPromptActive: passwordPromptActiveRef\.current/u); + assert.match(preloadSource, /typeof passwordPromptActive === "boolean"/u); + assert.match(bridgeSource, /passwordPromptActive: typeof payload\?\.passwordPromptActive/u); + assert.match(effectsSource, /passwordPromptActiveRef\.current = snap\.passwordPromptActive/u); }); test("exit fanout preserves the original renderer before registry wiring", () => { @@ -296,7 +336,7 @@ test("attach authorization is bound to one session and renderer", () => { assert.equal(registry.validateAttachPopupAuthorization("grant-1", "session-1", 42), false); }); -test("failed attach restores retry when a main renderer becomes ready", () => { +test("failed attach restores retry when a main renderer becomes ready", async () => { const registry = require("./terminalAttachRestore.cjs"); let available = false; let calls = 0; @@ -307,15 +347,15 @@ test("failed attach restores retry when a main renderer becomes ready", () => { : { success: false, restored: false, error: "Home renderer unavailable" }; }); - assert.equal(registry.restoreAttachedSessionOutput("session-retry").success, false); + assert.equal((await registry.restoreAttachedSessionOutput("session-retry")).success, false); available = true; - registry.retryPendingAttachedSessionOutputs(); - registry.retryPendingAttachedSessionOutputs(); + await registry.retryPendingAttachedSessionOutputs(); + await registry.retryPendingAttachedSessionOutputs(); assert.equal(calls, 2, "successful retry clears the pending restore"); }); -test("a ready replacement main renderer becomes the explicit restore target", () => { +test("a ready replacement main renderer becomes the explicit restore target", async () => { const registry = require("./terminalAttachRestore.cjs"); const targets = []; registry.setRestoreAttachedSessionOutput((_sessionId, preferredHomeWebContentsId) => { @@ -325,8 +365,8 @@ test("a ready replacement main renderer becomes the explicit restore target", () : { success: true, restored: true }; }); - registry.restoreAttachedSessionOutput("session-replacement"); - registry.retryPendingAttachedSessionOutput("session-replacement", 99); + await registry.restoreAttachedSessionOutput("session-replacement"); + await registry.retryPendingAttachedSessionOutput("session-replacement", 99); assert.deepEqual(targets, [null, 99]); }); @@ -370,3 +410,30 @@ test("attach popup payload field is consumed by terminal popup window", () => { assert.match(source, /attachSessionPopups/); assert.match(source, /reused: true/); }); + +test("attach snapshots preserve cwd and title updates including explicit clears", () => { + const terminalSource = require("node:fs").readFileSync( + path.join(__dirname, "../../components/Terminal.tsx"), + "utf8", + ); + const effectsSource = require("node:fs").readFileSync( + path.join(__dirname, "../../components/terminal/useTerminalEffects.ts"), + "utf8", + ); + assert.match( + terminalSource, + /knownCwdRef\.current \?\? null,[\s\S]*?terminalTitleRef\.current \?\? null/, + ); + assert.match( + effectsSource, + /snap\.cwd !== undefined[\s\S]*?setRendererCwd\(snap\.cwd\)[\s\S]*?snap\.title !== undefined/, + ); + assert.match( + effectsSource, + /onTitleChange: \(title: string \| null\) => \{[\s\S]*?terminalTitleRef\.current = title \|\| undefined/, + ); + assert.match( + terminalSource, + /payload\.cwd !== undefined[\s\S]*?setRendererCwd\(payload\.cwd\)[\s\S]*?payload\.title !== undefined/, + ); +}); diff --git a/electron/bridges/terminalBridge.terminalInterceptor.test.cjs b/electron/bridges/terminalBridge.terminalInterceptor.test.cjs new file mode 100644 index 000000000..5cd6646dd --- /dev/null +++ b/electron/bridges/terminalBridge.terminalInterceptor.test.cjs @@ -0,0 +1,132 @@ +"use strict"; + +const assert = require("node:assert/strict"); +const test = require("node:test"); + +const terminalBridge = require("./terminalBridge.cjs"); + +function createHarness() { + const writes = []; + const intercepted = []; + const sessions = new Map([["session-1", { + type: "local", + proc: { write(data) { writes.push(String(data)); } }, + }]]); + terminalBridge.init({ + sessions, + electronModule: {}, + terminalDataPipeline: { + has(sessionId, direction) { return sessionId === "session-1" && direction === "input"; }, + async interceptInput(sessionId, data, options) { + if (options?.bypass || options?.sensitive) return data; + intercepted.push({ sessionId, data, options }); + return String(data).toUpperCase(); + }, + }, + }); + return { writes, intercepted }; +} + +test("ordinary terminal input uses the worker-owned interceptor before transport encoding", async () => { + const h = createHarness(); + terminalBridge.writeToSession(null, { sessionId: "session-1", data: "hello" }); + await new Promise((resolve) => setImmediate(resolve)); + assert.deepEqual(h.intercepted.map((entry) => entry.data), ["hello"]); + assert.deepEqual(h.writes, ["HELLO"]); +}); + +test("host-classified sensitive input bypasses interceptors and preserves original bytes", async () => { + const h = createHarness(); + terminalBridge.writeToSession(null, { + sessionId: "session-1", + data: "secret\r", + sensitive: true, + }); + await new Promise((resolve) => setImmediate(resolve)); + assert.deepEqual(h.intercepted, []); + assert.deepEqual(h.writes, ["secret\r"]); +}); + +test("host terminal protocol replies bypass third-party interceptors", async () => { + const h = createHarness(); + const reports = [ + "\x1b[1;2R", + "\x1b[?2004;1$y", + "\x1b[8;24;80t", + "\x1b]10;rgb:ffff/ffff/ffff\x1b\\", + ]; + for (const data of reports) { + terminalBridge.writeToSession(null, { sessionId: "session-1", data }); + } + await new Promise((resolve) => setImmediate(resolve)); + assert.deepEqual(h.intercepted, []); + assert.deepEqual(h.writes, reports); +}); + +test("input remains ordered when an interceptor is disabled during an in-flight transform", async () => { + const writes = []; + let enabled = true; + let releaseFirst; + terminalBridge.init({ + sessions: new Map([["session-1", { + type: "local", + proc: { write(data) { writes.push(String(data)); } }, + }]]), + electronModule: {}, + terminalDataPipeline: { + has() { return enabled; }, + interceptInput() { + return new Promise((resolve) => { releaseFirst = resolve; }); + }, + }, + }); + + terminalBridge.writeToSession(null, { sessionId: "session-1", data: "first" }); + await new Promise((resolve) => setImmediate(resolve)); + enabled = false; + terminalBridge.writeToSession(null, { sessionId: "session-1", data: "second" }); + assert.deepEqual(writes, []); + + releaseFirst("FIRST"); + await new Promise((resolve) => setImmediate(resolve)); + assert.deepEqual(writes, ["FIRST", "second"]); +}); + +test("a pending input transform cannot write into a reused session id", async () => { + const oldWrites = []; + const newWrites = []; + let enabled = true; + let releaseOld; + const sessions = new Map([["session-1", { + type: "local", + proc: { + write(data) { oldWrites.push(String(data)); }, + kill() {}, + }, + }]]); + terminalBridge.init({ + sessions, + electronModule: {}, + terminalDataPipeline: { + has() { return enabled; }, + interceptInput() { + return new Promise((resolve) => { releaseOld = resolve; }); + }, + }, + }); + + terminalBridge.writeToSession(null, { sessionId: "session-1", data: "old" }); + await new Promise((resolve) => setImmediate(resolve)); + terminalBridge.closeSession({ sender: {} }, { sessionId: "session-1" }); + sessions.set("session-1", { + type: "local", + proc: { write(data) { newWrites.push(String(data)); } }, + }); + enabled = false; + terminalBridge.writeToSession(null, { sessionId: "session-1", data: "new" }); + releaseOld("STALE"); + await new Promise((resolve) => setImmediate(resolve)); + + assert.deepEqual(oldWrites, []); + assert.deepEqual(newWrites, ["new"]); +}); diff --git a/electron/bridges/terminalBridge/etSession.cjs b/electron/bridges/terminalBridge/etSession.cjs index fd2032a8a..7cc9d2ed6 100644 --- a/electron/bridges/terminalBridge/etSession.cjs +++ b/electron/bridges/terminalBridge/etSession.cjs @@ -1052,13 +1052,14 @@ main(); } = createPtyOutputBuffer((data, meta) => { const contents = electronModule.webContents.fromId(session.webContentsId); emitTerminalSessionData(contents, sessionId, data, { + session, cols: session.cols, rows: session.rows, meta, }); }, { onPendingBytesChange: (bytes) => setBufferedOutputBytes(session, bytes), - shouldAcceptOutput: () => shouldAcceptSessionOutput(session), + shouldAcceptOutput: () => sessions.get(sessionId) === session && shouldAcceptSessionOutput(session), }); session.flushPendingData = flushEtPaced; session.discardPendingData = discardEt; @@ -1081,21 +1082,23 @@ main(); return electronModule.webContents.fromId(session.webContentsId); }, selectUploadFiles: selectZmodemUploadFiles - ? () => selectZmodemUploadFiles(session.webContentsId) + ? () => selectZmodemUploadFiles(session.webContentsId, sessionId) : undefined, selectDownloadDirectory: selectZmodemDownloadDirectory - ? () => selectZmodemDownloadDirectory(session.webContentsId) + ? () => selectZmodemDownloadDirectory(session.webContentsId, sessionId) : undefined, label: "ET", }); session.zmodemSentry = etZmodemSentry; proc.onData((data) => { + if (sessions.get(sessionId) !== session) return; if (!shouldProcessSessionOutput(session, etZmodemSentry)) return; etZmodemSentry.consume(data); }); } else { proc.onData((data) => { + if (sessions.get(sessionId) !== session) return; if (!shouldProcessSessionOutput(session)) return; trackSessionIdlePrompt(session, data); bufferEtData(data); @@ -1107,6 +1110,7 @@ main(); proc.onExit((evt) => { flushEtPaced(() => { if (etExitFinalized) return; + if (sessions.get(sessionId) !== session) return; etExitFinalized = true; try { session.etStatsConn?.end(); } catch { /* ignore */ } cleanupSessionExternalAuthArtifacts(session); @@ -1115,7 +1119,12 @@ main(); sessions.delete(sessionId); if (session.closed) return; const contents = electronModule.webContents.fromId(session.webContentsId); - fanoutSessionExit(sessionId, contents, { sessionId, ...evt, reason: evt.exitCode === 0 ? "exited" : "error" }); + fanoutSessionExit(sessionId, contents, { + sessionId, + ...evt, + reason: evt.exitCode === 0 ? "exited" : "error", + _terminalSessionGeneration: session._terminalSessionGeneration, + }); }); }); diff --git a/electron/bridges/terminalBridge/moshSession.cjs b/electron/bridges/terminalBridge/moshSession.cjs index 6c74cbcca..09eb81e15 100644 --- a/electron/bridges/terminalBridge/moshSession.cjs +++ b/electron/bridges/terminalBridge/moshSession.cjs @@ -499,13 +499,14 @@ function createMoshSessionApi(ctx) { ? { ...(meta || {}), moshHandshake: true } : meta; emitTerminalSessionData(contents, sessionId, data, { + session, cols: session.cols, rows: session.rows, meta: handshakeMeta, }); }, { onPendingBytesChange: (bytes) => setBufferedOutputBytes(session, bytes), - shouldAcceptOutput: () => shouldAcceptSessionOutput(session), + shouldAcceptOutput: () => sessions.get(sessionId) === session && shouldAcceptSessionOutput(session), }); session.flushPendingData = flushPaced; session.discardPendingData = discard; @@ -518,6 +519,7 @@ function createMoshSessionApi(ctx) { // during handshake — it can't appear during ssh login output and // would only complicate the swap. sshPty.onData((chunk) => { + if (sessions.get(sessionId) !== session) return; const { visible, parsed } = sniffer.feed(chunk); if (visible && (visible.length || (typeof visible === "string" && visible))) { const str = Buffer.isBuffer(visible) ? visible.toString("utf8") : visible; @@ -573,12 +575,14 @@ function createMoshSessionApi(ctx) { }); } catch (err) { flushPaced(() => { + if (sessions.get(sessionId) !== session) return; sessionLogStreamManager.stopStream(sessionId, logStreamToken); const contents = electronModule.webContents.fromId(session.webContentsId); fanoutSessionExit(sessionId, contents, { sessionId, reason: "error", error: `Failed to spawn mosh-client: ${err.message}`, + _terminalSessionGeneration: session._terminalSessionGeneration, }); closeTerminalOutputSession?.(sessionId); sessions.delete(sessionId); @@ -604,6 +608,7 @@ function createMoshSessionApi(ctx) { // Best-effort diagnostics; still tear the session down below. } flushPaced(() => { + if (sessions.get(sessionId) !== session) return; sessionLogStreamManager.stopStream(sessionId, logStreamToken); const contents = electronModule.webContents.fromId(session.webContentsId); fanoutSessionExit(sessionId, contents, { @@ -612,6 +617,7 @@ function createMoshSessionApi(ctx) { signal, reason: "error", error: "Mosh SSH startup failed: no MOSH CONNECT from mosh-server (UDP client not started)", + _terminalSessionGeneration: session._terminalSessionGeneration, }); closeTerminalOutputSession?.(sessionId); sessions.delete(sessionId); @@ -752,21 +758,23 @@ function createMoshSessionApi(ctx) { }, getWebContents() { return electronModule.webContents.fromId(session.webContentsId); }, selectUploadFiles: selectZmodemUploadFiles - ? () => selectZmodemUploadFiles(session.webContentsId) + ? () => selectZmodemUploadFiles(session.webContentsId, sessionId) : undefined, selectDownloadDirectory: selectZmodemDownloadDirectory - ? () => selectZmodemDownloadDirectory(session.webContentsId) + ? () => selectZmodemDownloadDirectory(session.webContentsId, sessionId) : undefined, protocolLabel: "Mosh", }); session.zmodemSentry = sentry; mcPty.onData((data) => { + if (sessions.get(sessionId) !== session) return; if (!shouldProcessSessionOutput(session, sentry)) return; sentry.consume(data); }); } else { const decodeMoshOutput = createMoshUtf8Decoder(); mcPty.onData((data) => { + if (sessions.get(sessionId) !== session) return; if (!shouldProcessSessionOutput(session)) return; const str = decodeMoshOutput(data); if (!str) return; @@ -786,6 +794,7 @@ function createMoshSessionApi(ctx) { try { session.moshStatsConn?.end(); } catch { /* ignore */ } bufferData(MOSH_PRIMARY_SCREEN_RESET); flushPaced(() => { + if (sessions.get(sessionId) !== session) return; sessionLogStreamManager.stopStream(sessionId, session.logStreamToken); const contents = electronModule.webContents.fromId(session.webContentsId); fanoutSessionExit(sessionId, contents, { @@ -793,6 +802,7 @@ function createMoshSessionApi(ctx) { exitCode, signal, reason: exitCode !== 0 ? "error" : "exited", + _terminalSessionGeneration: session._terminalSessionGeneration, }); closeTerminalOutputSession?.(sessionId); sessions.delete(sessionId); diff --git a/electron/bridges/terminalBridge/telnetSession.cjs b/electron/bridges/terminalBridge/telnetSession.cjs index 8de8e2eef..a3f286c9c 100644 --- a/electron/bridges/terminalBridge/telnetSession.cjs +++ b/electron/bridges/terminalBridge/telnetSession.cjs @@ -47,6 +47,7 @@ function createTelnetSessionApi(ctx) { const socket = new net.Socket(); enableTcpNoDelay(socket); let connected = false; + let activeSession = null; // Token for the log stream we open on this connection. Captured here so // the close/error handlers below can pass it back to stopStream and // avoid tearing down a fresh stream that a subsequent reconnect on the @@ -223,6 +224,7 @@ function createTelnetSessionApi(ctx) { return telnetProtocolActive; }, }; + activeSession = session; session.flushPendingData = flushTelnetPaced; sessions.set(sessionId, session); openTerminalOutputSession?.(sessionId, event.sender); @@ -252,13 +254,20 @@ function createTelnetSessionApi(ctx) { discard: discardTelnet, } = createPtyOutputBuffer((data, meta) => { const contents = getCurrentTelnetWebContents(); - emitTerminalSessionData(contents, sessionId, data, { cols, rows, meta }); + emitTerminalSessionData(contents, sessionId, data, { + session: activeSession, + cols, + rows, + meta, + }); }, { onPendingBytesChange: (bytes) => { const activeSession = sessions.get(sessionId); if (activeSession?.socket === socket) setBufferedOutputBytes(activeSession, bytes); }, - shouldAcceptOutput: () => shouldAcceptSessionOutput(sessions.get(sessionId)), + shouldAcceptOutput: () => activeSession != null + && sessions.get(sessionId) === activeSession + && shouldAcceptSessionOutput(activeSession), }); const telnetZmodemSentry = createZmodemSentry({ @@ -296,10 +305,10 @@ function createTelnetSessionApi(ctx) { return getCurrentTelnetWebContents(); }, selectUploadFiles: selectZmodemUploadFiles - ? () => selectZmodemUploadFiles(getCurrentTelnetWebContentsId()) + ? () => selectZmodemUploadFiles(getCurrentTelnetWebContentsId(), sessionId) : undefined, selectDownloadDirectory: selectZmodemDownloadDirectory - ? () => selectZmodemDownloadDirectory(getCurrentTelnetWebContentsId()) + ? () => selectZmodemDownloadDirectory(getCurrentTelnetWebContentsId(), sessionId) : undefined, label: "Telnet", }); @@ -341,13 +350,20 @@ function createTelnetSessionApi(ctx) { } flushTelnetPaced(() => { if (telnetExitFinalized) return; + if (!activeSession || sessions.get(sessionId) !== activeSession) return; telnetExitFinalized = true; sessionLogStreamManager.stopStream(sessionId, logStreamToken); - const session = sessions.get(sessionId); + const session = activeSession; if (session) { session.zmodemSentry?.cancel(); const contents = electronModule.webContents.fromId(session.webContentsId); - fanoutSessionExit(sessionId, contents, { sessionId, exitCode: 1, error: err.message, reason: "error" }); + fanoutSessionExit(sessionId, contents, { + sessionId, + exitCode: 1, + error: err.message, + reason: "error", + _terminalSessionGeneration: session._terminalSessionGeneration, + }); } ptyProcessTree.unregisterPid(sessionId); closeTerminalOutputSession?.(sessionId); @@ -367,13 +383,19 @@ function createTelnetSessionApi(ctx) { } flushTelnetPaced(() => { if (telnetExitFinalized) return; + if (!activeSession || sessions.get(sessionId) !== activeSession) return; telnetExitFinalized = true; sessionLogStreamManager.stopStream(sessionId, logStreamToken); - const session = sessions.get(sessionId); + const session = activeSession; if (session) { session.zmodemSentry?.cancel(); const contents = electronModule.webContents.fromId(session.webContentsId); - fanoutSessionExit(sessionId, contents, { sessionId, exitCode: hadError ? 1 : 0, reason: hadError ? "error" : "closed" }); + fanoutSessionExit(sessionId, contents, { + sessionId, + exitCode: hadError ? 1 : 0, + reason: hadError ? "error" : "closed", + _terminalSessionGeneration: session._terminalSessionGeneration, + }); } ptyProcessTree.unregisterPid(sessionId); closeTerminalOutputSession?.(sessionId); diff --git a/electron/bridges/terminalOutputChannel.cjs b/electron/bridges/terminalOutputChannel.cjs index 08e4120f9..25f61ee3b 100644 --- a/electron/bridges/terminalOutputChannel.cjs +++ b/electron/bridges/terminalOutputChannel.cjs @@ -19,15 +19,23 @@ function createTerminalOutputChannel(options = {}) { return false; } - closeSession(sessionId); const { port1, port2 } = new MessageChannelMain(); const transferToWorker = openOptions.transferToWorker === true; - sessions.set(sessionId, { + const replacement = { port: port1, webContentsId: webContents.id, transferToWorker, - }); - webContents.postMessage(TERMINAL_OUTPUT_PORT_CHANNEL, { sessionId }, [port2]); + }; + try { + webContents.postMessage(TERMINAL_OUTPUT_PORT_CHANNEL, { sessionId }, [port2]); + } catch (error) { + closeEntry(replacement); + try { port2?.close?.(); } catch {} + throw error; + } + const previous = sessions.get(sessionId); + sessions.set(sessionId, replacement); + closeEntry(previous); return transferToWorker ? port1 : true; } diff --git a/electron/bridges/terminalOutputChannel.test.cjs b/electron/bridges/terminalOutputChannel.test.cjs index bfe8375a9..2a10a3d42 100644 --- a/electron/bridges/terminalOutputChannel.test.cjs +++ b/electron/bridges/terminalOutputChannel.test.cjs @@ -117,3 +117,24 @@ test("opening a replacement session closes the stale output port", () => { assert.equal(stale.port.closed, true); assert.notEqual(channel.getSessionForTest("session-1"), stale); }); + +test("a failed replacement transfer preserves the existing output route", () => { + const channel = createTerminalOutputChannel({ + MessageChannelMain: FakeMessageChannelMain, + }); + channel.openSession("session-1", { id: 42, postMessage() {} }); + const existing = channel.getSessionForTest("session-1"); + + assert.throws(() => { + channel.openSession("session-1", { + id: 43, + postMessage() { + throw new Error("renderer transfer failed"); + }, + }); + }, /renderer transfer failed/u); + + assert.equal(channel.getSessionForTest("session-1"), existing); + assert.equal(existing.port.closed, false); + assert.equal(channel.send("session-1", "still-routed"), true); +}); diff --git a/electron/bridges/terminalReportSequence.cjs b/electron/bridges/terminalReportSequence.cjs new file mode 100644 index 000000000..a976de95f --- /dev/null +++ b/electron/bridges/terminalReportSequence.cjs @@ -0,0 +1,25 @@ +"use strict"; + +// Terminal-originated automatic replies travel through xterm's public onData +// event alongside user input. Keep the current xterm report families on the +// host-owned bypass path so plugins cannot rewrite terminal negotiation. +function isTerminalReportSequence(data) { + if (typeof data !== "string" || data.length === 0) return false; + // Focus in/out reports: ESC [ I / ESC [ O + if (data === "\x1b[I" || data === "\x1b[O") return true; + // CPR / DECXCPR / DA1 / DA2 / DSR: ESC [ (?|>)? digits/semicolons (R|c|n) + if (/^\x1b\[[?>]?[0-9;]*[Rcn]$/.test(data)) return true; + // Kitty keyboard mode query reply: ESC [ ? digits u + if (/^\x1b\[\?[0-9]+u$/.test(data)) return true; + // ANSI/DEC mode report (DECRPM): ESC [ (?) mode ; state $ y + if (/^\x1b\[\??[0-9]+;[0-4]\$y$/.test(data)) return true; + // Xterm window/cell/character-size reports: ESC [ (4|6|8) ; height ; width t + if (/^\x1b\[(?:4|6|8);[0-9]+;[0-9]+t$/.test(data)) return true; + // Xterm dynamic-color query replies: OSC (4;index|10|11|12) ; rgb:... (BEL|ST) + if (/^\x1b\](?:4;[0-9]{1,3}|1[012]);rgb:[0-9a-f]{1,4}\/[0-9a-f]{1,4}\/[0-9a-f]{1,4}(?:\x07|\x1b\\)$/i.test(data)) return true; + // DCS replies (XTGETTCAP / DECRQSS, etc.): ESC P ... ESC \ + if (/^\x1bP[\s\S]*\x1b\\$/.test(data)) return true; + return false; +} + +module.exports = { isTerminalReportSequence }; diff --git a/electron/bridges/terminalReportSequence.test.cjs b/electron/bridges/terminalReportSequence.test.cjs new file mode 100644 index 000000000..485c23966 --- /dev/null +++ b/electron/bridges/terminalReportSequence.test.cjs @@ -0,0 +1,29 @@ +"use strict"; + +const assert = require("node:assert/strict"); +const test = require("node:test"); + +const { isTerminalReportSequence } = require("./terminalReportSequence.cjs"); + +test("recognizes terminal-generated report families without classifying ordinary input", () => { + for (const report of [ + "\x1b[I", + "\x1b[1;2R", + "\x1b[?1;2c", + "\x1b[?997;1n", + "\x1b[?3u", + "\x1b[?2004;1$y", + "\x1b[8;24;80t", + "\x1b[4;1080;1920t", + "\x1b]10;rgb:ffff/ffff/ffff\x1b\\", + "\x1b]4;255;rgb:ffff/0000/ffff\x1b\\", + "\x1b]11;rgb:0000/0000/0000\x07", + "\x1b]4;7;rgb:1111/2222/3333\x07", + "\x1bP1$r0m\x1b\\", + ]) { + assert.equal(isTerminalReportSequence(report), true, JSON.stringify(report)); + } + for (const input of ["hello", "\r", "\x1b[A", "\x1b[200~paste\x1b[201~"]) { + assert.equal(isTerminalReportSequence(input), false, JSON.stringify(input)); + } +}); diff --git a/electron/bridges/terminalWorkerManager.cjs b/electron/bridges/terminalWorkerManager.cjs index 59dff1ae6..ce2787eaf 100644 --- a/electron/bridges/terminalWorkerManager.cjs +++ b/electron/bridges/terminalWorkerManager.cjs @@ -148,6 +148,23 @@ function mergeTerminalOutputMeta(previous, next) { ), droppedOutputAlternateScreenAction: nextAction, }; + const pluginPipelineIngressBytes = Number(previous?.pluginPipelineIngressBytes ?? 0) + + Number(next.pluginPipelineIngressBytes ?? 0); + if (pluginPipelineIngressBytes > 0) merged.pluginPipelineIngressBytes = pluginPipelineIngressBytes; + else delete merged.pluginPipelineIngressBytes; + if (typeof next.pluginPipelineSensitiveInput === "boolean") { + merged.pluginPipelineSensitiveInput = next.pluginPipelineSensitiveInput; + } else { + delete merged.pluginPipelineSensitiveInput; + } + if (next.pluginPipelineProcessed === true) { + merged.pluginPipelineProcessed = true; + } else { + delete merged.pluginPipelineProcessed; + } + if (!merged.droppedOutputMayAffectTerminalState) { + delete merged.droppedOutputMayAffectTerminalState; + } if (!merged.droppedOutputAlternateScreenAction) { delete merged.droppedOutputAlternateScreenAction; } @@ -161,6 +178,7 @@ const SESSION_START_CHANNELS = new Set([ "netcatty:mosh:start", "netcatty:et:start", "netcatty:serial:start", + "netcatty:local:reconnect", ]); function createTerminalWorkerManager(options = {}) { @@ -179,9 +197,14 @@ function createTerminalWorkerManager(options = {}) { const closedSessions = new Set(); const outputPortPending = new Set(); const outputPortReady = new Set(); + const outputRoutePending = new Map(); const sessionWebContentsIds = new Map(); + const sessionGenerations = new Map(); const urgentInputPorts = new Map(); const outputTaps = new Set(); + const terminalInterceptorWarningListeners = new Set(); + const sessionOwnedListeners = new Set(); + const sessionClosedListeners = new Set(); const maxPendingOutputChunks = Number.isFinite(options.maxPendingOutputChunks) ? Math.max(0, Math.trunc(options.maxPendingOutputChunks)) : 512; @@ -228,11 +251,19 @@ function createTerminalWorkerManager(options = {}) { function getOutputChunkLength(chunk) { const data = getOutputChunkData(chunk); - return typeof data === "string" ? data.length : 0; + const displayLength = typeof data === "string" ? data.length : 0; + // A suppressed interceptor result can carry flow-accounting metadata with + // an empty display string. Count that record as one bounded buffer unit so + // the chunk/byte trimming loop cannot stop on a zero-length head. + return displayLength || (getOutputChunkMeta(chunk) ? 1 : 0); } function withOutputChunkMeta(chunk, meta) { - const mergedMeta = mergeTerminalOutputMeta(getOutputChunkMeta(chunk), meta); + // Dropped metadata describes older chunks. Merge the retained chunk last + // so latest-chunk state such as sensitive-input classification cannot be + // revived by an earlier prompt while additive ingress/state metadata is + // still preserved. + const mergedMeta = mergeTerminalOutputMeta(meta, getOutputChunkMeta(chunk) || {}); if (!mergedMeta) return chunk; return { data: getOutputChunkData(chunk), meta: mergedMeta }; } @@ -277,7 +308,12 @@ function createTerminalWorkerManager(options = {}) { const chunk = chunks[0]; const data = getOutputChunkData(chunk); const dataLength = getOutputChunkLength(chunk); - const dropWholeChunk = chunks.length > maxPendingOutputChunks; + const displayLength = typeof data === "string" ? data.length : 0; + // Metadata-only suppressed output still represents consumed host input. + // Drop it atomically when it contributes virtual ingress bytes; partial + // string slicing cannot safely reduce that metadata accounting. + const dropWholeChunk = chunks.length > maxPendingOutputChunks + || dataLength !== displayLength; const overLimitBytes = Math.max(0, totalBytes - maxPendingOutputBytes); const bytesToDrop = dropWholeChunk ? dataLength : Math.min(dataLength, overLimitBytes); if (bytesToDrop <= 0) break; @@ -285,15 +321,23 @@ function createTerminalWorkerManager(options = {}) { if (typeof data !== "string" || bytesToDrop >= dataLength) { chunks.shift(); totalBytes = Math.max(0, totalBytes - dataLength); - droppedBytes += dataLength; + droppedBytes += displayLength; recordDropped(typeof data === "string" ? data : "", getOutputChunkMeta(chunk)); continue; } const droppedText = data.slice(0, bytesToDrop); const retainedText = data.slice(bytesToDrop); - chunks[0] = getOutputChunkMeta(chunk) - ? { data: retainedText, meta: getOutputChunkMeta(chunk) } + const retainedMeta = getOutputChunkMeta(chunk); + const adjustedRetainedMeta = retainedMeta?.pluginPipelineProcessed !== true + && Number.isFinite(retainedMeta?.pluginPipelineIngressBytes) + ? mergeTerminalOutputMeta( + { pluginPipelineIngressBytes: bytesToDrop }, + retainedMeta, + ) + : retainedMeta; + chunks[0] = adjustedRetainedMeta + ? { data: retainedText, meta: adjustedRetainedMeta } : retainedText; totalBytes = Math.max(0, totalBytes - bytesToDrop); droppedBytes += bytesToDrop; @@ -391,7 +435,7 @@ function createTerminalWorkerManager(options = {}) { } } - function openOutputSession(sessionId, webContentsId) { + async function openOutputSession(sessionId, webContentsId) { if (!sessionId || !webContentsId) return false; if (closedSessions.has(sessionId)) { clearBufferedOutput(sessionId); @@ -401,22 +445,93 @@ function createTerminalWorkerManager(options = {}) { if (!contents || contents.isDestroyed?.()) { return false; } - sessionWebContentsIds.set(sessionId, webContentsId); - openUrgentInputPort(webContentsId, contents); - const outputPort = terminalOutputChannel?.openSession?.(sessionId, contents, { - transferToWorker: true, - }); - if (outputPort && outputPort !== true && child?.postMessage) { - outputPortPending.add(sessionId); - child.postMessage({ - kind: "output-port", - sessionId, - bufferedOutput: takeBufferedOutput(sessionId), - }, [outputPort]); + const previousWebContentsId = sessionWebContentsIds.get(sessionId) ?? null; + const openToken = Object.freeze({ webContentsId }); + outputRoutePending.set(sessionId, openToken); + const onDestroyed = () => { + if (outputRoutePending.get(sessionId) === openToken) { + outputRoutePending.delete(sessionId); + } + }; + contents.once?.("destroyed", onDestroyed); + try { + await Promise.allSettled([...sessionOwnedListeners].map((listener) => ( + Promise.resolve().then(() => listener(Object.freeze({ sessionId, webContentsId }))) + ))); + } finally { + contents.removeListener?.("destroyed", onDestroyed); + } + if (closedSessions.has(sessionId)) return false; + if (outputRoutePending.get(sessionId) !== openToken) { + return outputRoutePending.get(sessionId)?.webContentsId === webContentsId; + } + if (contents.isDestroyed?.()) { + outputRoutePending.delete(sessionId); + if (previousWebContentsId == null) { + send("netcatty:close", { sessionId }, { webContentsId }); + } + return false; + } + let openedUrgentInputPort = false; + let replacedOutputChannel = false; + let transferringBufferedOutput = []; + try { + sessionWebContentsIds.set(sessionId, webContentsId); + openedUrgentInputPort = openUrgentInputPort(webContentsId, contents); + const outputPort = terminalOutputChannel?.openSession?.(sessionId, contents, { + transferToWorker: true, + }); + replacedOutputChannel = Boolean(outputPort); + if (outputPort && outputPort !== true && child?.postMessage) { + outputPortPending.add(sessionId); + transferringBufferedOutput = takeBufferedOutput(sessionId); + child.postMessage({ + kind: "output-port", + sessionId, + bufferedOutput: transferringBufferedOutput, + }, [outputPort]); + transferringBufferedOutput = []; + if (outputRoutePending.get(sessionId) === openToken) { + outputRoutePending.delete(sessionId); + } + return true; + } + if (outputRoutePending.get(sessionId) === openToken) { + outputRoutePending.delete(sessionId); + } + flushBufferedOutput(sessionId); return true; + } catch { + for (const chunk of transferringBufferedOutput) { + bufferOutput(sessionId, chunk); + } + outputPortPending.delete(sessionId); + outputPortReady.delete(sessionId); + if (replacedOutputChannel) { + terminalOutputChannel?.closeSession?.(sessionId); + } + if ( + openedUrgentInputPort + && previousWebContentsId !== webContentsId + ) { + closeUrgentInputPort(webContentsId); + } + if (isLiveWebContentsId(previousWebContentsId)) { + sessionWebContentsIds.set(sessionId, previousWebContentsId); + } else { + sessionWebContentsIds.delete(sessionId); + } + if (outputRoutePending.get(sessionId) === openToken) { + outputRoutePending.delete(sessionId); + } + if (isLiveWebContentsId(previousWebContentsId)) { + flushOutputToWorker(sessionId); + } else { + clearBufferedOutput(sessionId); + send("netcatty:close", { sessionId }, { webContentsId }); + } + return false; } - flushBufferedOutput(sessionId); - return true; } /** @@ -426,7 +541,7 @@ function createTerminalWorkerManager(options = {}) { /** sessionId -> home webContentsId while an attach/observe popup owns display */ const attachHomeWebContentsIds = new Map(); - function rebindOutputSession(sessionId, webContentsId) { + async function rebindOutputSession(sessionId, webContentsId) { if (!sessionId || !webContentsId) { return { success: false, error: "Missing sessionId or webContentsId" }; } @@ -436,15 +551,20 @@ function createTerminalWorkerManager(options = {}) { const previousWebContentsId = sessionWebContentsIds.get(sessionId) ?? null; // Remember the first home target so popup destruction / session exit can // restore or dual-notify the original owner. + let rememberedAttachHome = false; if ( previousWebContentsId != null && previousWebContentsId !== webContentsId && !attachHomeWebContentsIds.has(sessionId) ) { attachHomeWebContentsIds.set(sessionId, previousWebContentsId); + rememberedAttachHome = true; } - const ok = openOutputSession(sessionId, webContentsId); + const ok = await openOutputSession(sessionId, webContentsId); if (!ok) { + if (rememberedAttachHome) { + attachHomeWebContentsIds.delete(sessionId); + } return { success: false, error: "Failed to rebind session output" }; } return { @@ -474,7 +594,7 @@ function createTerminalWorkerManager(options = {}) { return null; } - function restoreAttachHome(sessionId, preferredHomeWebContentsId = null) { + async function restoreAttachHome(sessionId, preferredHomeWebContentsId = null) { if (!sessionId) return { success: false, restored: false }; const savedHomeId = attachHomeWebContentsIds.get(sessionId); if (savedHomeId == null) { @@ -493,7 +613,7 @@ function createTerminalWorkerManager(options = {}) { error: "Home renderer unavailable", }; } - const ok = openOutputSession(sessionId, homeId); + const ok = await openOutputSession(sessionId, homeId); if (ok) { attachHomeWebContentsIds.delete(sessionId); } @@ -505,7 +625,16 @@ function createTerminalWorkerManager(options = {}) { }; } - function resolveDialogWebContentsId(webContentsId) { + function resolveDialogWebContentsId(webContentsId, sessionId) { + // Dialog requests are interactive session work. During attach/rebind the + // pending renderer already owns that interaction even though the committed + // output mapping is intentionally not published until port transfer. + if (typeof sessionId === "string") { + const pending = outputRoutePending.get(sessionId)?.webContentsId; + if (isLiveWebContentsId(pending)) return pending; + const current = sessionWebContentsIds.get(sessionId); + if (isLiveWebContentsId(current)) return current; + } // Worker dialogs often still carry the original home id after rebind. // Prefer the current display route when this id is a remembered attach home. if (typeof webContentsId !== "number") return webContentsId; @@ -530,9 +659,11 @@ function createTerminalWorkerManager(options = {}) { if (!sessionId) return; closedSessions.add(sessionId); clearBufferedOutput(sessionId); + outputRoutePending.delete(sessionId); outputPortPending.delete(sessionId); outputPortReady.delete(sessionId); sessionWebContentsIds.delete(sessionId); + sessionGenerations.delete(sessionId); clearAttachHome(sessionId); try { child?.postMessage?.({ kind: "close-output-port", sessionId }); @@ -562,6 +693,13 @@ function createTerminalWorkerManager(options = {}) { } } + function notifySessionClosed(sessionId, reason) { + if (!sessionId) return; + for (const listener of [...sessionClosedListeners]) { + try { listener(Object.freeze({ sessionId, reason })); } catch {} + } + } + function drainOutputSession(sessionId, requestId) { if (!sessionId || !requestId || !outputPortReady.has(sessionId)) return false; try { @@ -648,13 +786,32 @@ function createTerminalWorkerManager(options = {}) { if (message.kind === "response") { const entry = pending.get(message.requestId); if (!entry) return; - pending.delete(message.requestId); if (message.error) { + pending.delete(message.requestId); entry.reject(new Error(message.error)); } else { const sessionId = message.result?.sessionId; - openOutputSession(sessionId, entry.webContentsId); - entry.resolve(message.result); + if (!entry.opensOutputSession || !sessionId) { + pending.delete(message.requestId); + entry.resolve(message.result); + return; + } + if (Number.isSafeInteger(message.sessionGeneration)) { + sessionGenerations.set(sessionId, message.sessionGeneration); + } + void openOutputSession(sessionId, entry.webContentsId).then((opened) => { + if (pending.get(message.requestId) !== entry) return; + pending.delete(message.requestId); + if (!opened) { + entry.reject(new Error("Terminal session closed before its output route opened")); + return; + } + entry.resolve(message.result); + }, (error) => { + if (pending.get(message.requestId) !== entry) return; + pending.delete(message.requestId); + entry.reject(error); + }); } return; } @@ -668,7 +825,7 @@ function createTerminalWorkerManager(options = {}) { if (!message.tapped) { notifyOutputTaps(message.sessionId, message.data); } - if (outputPortPending.has(message.sessionId)) { + if (outputRoutePending.has(message.sessionId) || outputPortPending.has(message.sessionId)) { bufferOutput(message.sessionId, message.data, message.meta); return; } @@ -695,12 +852,24 @@ function createTerminalWorkerManager(options = {}) { } return; } + if (message.kind === "terminal-interceptor-warning") { + for (const listener of [...terminalInterceptorWarningListeners]) { + try { listener(message.warning); } catch {} + } + return; + } if (message.kind === "renderer-event") { // Prefer the currently rebound display target. Worker-captured // webContentsId is from session start and goes stale after attach/rebind. const sessionId = message.payload?.sessionId; + if (message.channel === "netcatty:exit" + && Number.isSafeInteger(message.sessionGeneration) + && sessionGenerations.get(sessionId) !== message.sessionGeneration) { + return; + } const displayWebContentsId = - (typeof sessionId === "string" && sessionWebContentsIds.get(sessionId)) + (typeof sessionId === "string" && outputRoutePending.get(sessionId)?.webContentsId) + || (typeof sessionId === "string" && sessionWebContentsIds.get(sessionId)) || message.webContentsId; const homeWebContentsId = (typeof sessionId === "string" && attachHomeWebContentsIds.get(sessionId)) @@ -711,6 +880,9 @@ function createTerminalWorkerManager(options = {}) { && closedSessions.has(sessionId), ); if (message.channel === "netcatty:exit" && sessionId) { + if (!wasExplicitlyClosed) { + notifySessionClosed(sessionId, message.payload?.reason); + } closeOutputSession(sessionId); clearAttachHome(sessionId); } @@ -753,7 +925,7 @@ function createTerminalWorkerManager(options = {}) { async function handleZmodemUploadDialogRequest(message) { try { - const webContentsId = resolveDialogWebContentsId(message.webContentsId); + const webContentsId = resolveDialogWebContentsId(message.webContentsId, message.sessionId); const contents = electronModule?.webContents?.fromId?.(webContentsId); const win = contents && electronModule?.BrowserWindow?.fromWebContents ? electronModule.BrowserWindow.fromWebContents(contents) @@ -778,7 +950,7 @@ function createTerminalWorkerManager(options = {}) { async function handleZmodemDownloadDialogRequest(message) { try { - const webContentsId = resolveDialogWebContentsId(message.webContentsId); + const webContentsId = resolveDialogWebContentsId(message.webContentsId, message.sessionId); const contents = electronModule?.webContents?.fromId?.(webContentsId); const win = contents && electronModule?.BrowserWindow?.fromWebContents ? electronModule.BrowserWindow.fromWebContents(contents) @@ -804,6 +976,11 @@ function createTerminalWorkerManager(options = {}) { function handleExit(code) { const error = new Error(`Terminal worker exited${Number.isFinite(code) ? ` with code ${code}` : ""}`); const exitCode = Number.isFinite(code) ? code : 1; + for (const listener of [...terminalInterceptorWarningListeners]) { + try { + listener(Object.freeze({ code: "worker-exit", message: error.message })); + } catch {} + } for (const [sessionId, webContentsId] of sessionWebContentsIds.entries()) { const targets = new Set(); if (webContentsId != null) targets.add(webContentsId); @@ -829,7 +1006,9 @@ function createTerminalWorkerManager(options = {}) { closedSessions.clear(); outputPortPending.clear(); outputPortReady.clear(); + outputRoutePending.clear(); sessionWebContentsIds.clear(); + sessionGenerations.clear(); attachHomeWebContentsIds.clear(); closeAllUrgentInputPorts(); terminalOutputChannel?.closeAll?.(); @@ -851,10 +1030,18 @@ function createTerminalWorkerManager(options = {}) { const requestId = randomUUID(); const worker = ensureStarted(); const promise = new Promise((resolve, reject) => { - pending.set(requestId, { resolve, reject, webContentsId: optionsForRequest.webContentsId }); + pending.set(requestId, { + resolve, + reject, + webContentsId: optionsForRequest.webContentsId, + opensOutputSession: channel === "netcatty:start" + || channel === "netcatty:local:reconnect" + || /^(?:netcatty:)(?:local|telnet|mosh|et|serial):start$/u.test(channel), + }); }); if (channel === "netcatty:close:await" && payload?.sessionId) { notifyExplicitSessionClose(payload.sessionId); + if (!closedSessions.has(payload.sessionId)) notifySessionClosed(payload.sessionId, "closed"); closeOutputSession(payload.sessionId); } else if (payload?.sessionId && SESSION_START_CHANNELS.has(channel)) { closedSessions.delete(payload.sessionId); @@ -872,6 +1059,7 @@ function createTerminalWorkerManager(options = {}) { function send(channel, payload, optionsForSend = {}) { if (channel === "netcatty:close" && payload?.sessionId) { notifyExplicitSessionClose(payload.sessionId); + if (!closedSessions.has(payload.sessionId)) notifySessionClosed(payload.sessionId, "closed"); closeOutputSession(payload.sessionId); } if (channel === "netcatty:interrupt") { @@ -890,6 +1078,37 @@ function createTerminalWorkerManager(options = {}) { }); } + function attachTerminalInterceptor(descriptor, port) { + if (!port) throw new TypeError("Terminal interceptor port is required"); + ensureStarted().postMessage({ + kind: "terminal-interceptor-port", + ...descriptor, + }, [port]); + } + + function detachTerminalInterceptor(sessionId, direction) { + if (!child) return; + child.postMessage({ kind: "terminal-interceptor-detach", sessionId, direction }); + } + + function onTerminalInterceptorWarning(listener) { + if (typeof listener !== "function") throw new TypeError("Terminal interceptor warning listener is required"); + terminalInterceptorWarningListeners.add(listener); + return Object.freeze({ dispose: () => terminalInterceptorWarningListeners.delete(listener) }); + } + + function onSessionOwned(listener) { + if (typeof listener !== "function") throw new TypeError("Terminal session owner listener is required"); + sessionOwnedListeners.add(listener); + return Object.freeze({ dispose: () => sessionOwnedListeners.delete(listener) }); + } + + function onSessionClosed(listener) { + if (typeof listener !== "function") throw new TypeError("Terminal session close listener is required"); + sessionClosedListeners.add(listener); + return Object.freeze({ dispose: () => sessionClosedListeners.delete(listener) }); + } + function stop() { if (!child) return; const current = child; @@ -902,8 +1121,13 @@ function createTerminalWorkerManager(options = {}) { closedSessions.clear(); outputPortPending.clear(); outputPortReady.clear(); + outputRoutePending.clear(); sessionWebContentsIds.clear(); + sessionGenerations.clear(); closeAllUrgentInputPorts(); + terminalInterceptorWarningListeners.clear(); + sessionOwnedListeners.clear(); + sessionClosedListeners.clear(); terminalOutputChannel?.closeAll?.(); rejectAllPending(new Error("Terminal worker stopped")); } @@ -919,6 +1143,11 @@ function createTerminalWorkerManager(options = {}) { restoreAttachHome, getAttachHomeWebContentsId, clearAttachHome, + attachTerminalInterceptor, + detachTerminalInterceptor, + onTerminalInterceptorWarning, + onSessionOwned, + onSessionClosed, hasOpenSession(sessionId) { return Boolean( sessionId @@ -930,6 +1159,27 @@ function createTerminalWorkerManager(options = {}) { if (!sessionId) return null; return sessionWebContentsIds.get(sessionId) ?? null; }, + getSessionOwnerWebContentsId(sessionId) { + if (!sessionId || closedSessions.has(sessionId)) return null; + const pendingWebContentsId = outputRoutePending.get(sessionId)?.webContentsId; + if (isLiveWebContentsId(pendingWebContentsId)) return pendingWebContentsId; + const currentWebContentsId = sessionWebContentsIds.get(sessionId); + return isLiveWebContentsId(currentWebContentsId) ? currentWebContentsId : null; + }, + ownsSession(sessionId, webContentsId) { + const pendingWebContentsId = outputRoutePending.get(sessionId)?.webContentsId; + return Boolean( + sessionId + && Number.isSafeInteger(webContentsId) + && ( + (sessionWebContentsIds.get(sessionId) === webContentsId + && isLiveWebContentsId(webContentsId)) + || (pendingWebContentsId === webContentsId + && isLiveWebContentsId(webContentsId)) + ) + && !closedSessions.has(sessionId), + ); + }, addOutputTap(listener) { if (typeof listener !== "function") return () => {}; outputTaps.add(listener); diff --git a/electron/bridges/terminalWorkerManager.test.cjs b/electron/bridges/terminalWorkerManager.test.cjs index 0a4e10c78..635f4b0be 100644 --- a/electron/bridges/terminalWorkerManager.test.cjs +++ b/electron/bridges/terminalWorkerManager.test.cjs @@ -67,6 +67,7 @@ test("request sends a worker command and resolves matching response", async () = return child; }, }, + electronModule: { webContents: { fromId(id) { return { id }; } } }, workerScriptPath: "/worker.cjs", }); @@ -86,6 +87,224 @@ test("request sends a worker command and resolves matching response", async () = assert.deepEqual(await promise, { sessionId: "local-1" }); }); +test("session ownership listeners finish before buffered output is released", async () => { + const child = new FakeChild(); + const routed = []; + let releaseOwnership; + let outputOpen = false; + const manager = createTerminalWorkerManager({ + utilityProcess: { fork: () => child }, + terminalOutputChannel: { + openSession() { outputOpen = true; }, + send(sessionId, data) { + if (!outputOpen) return false; + routed.push({ sessionId, data }); + return true; + }, + }, + electronModule: { webContents: { fromId(id) { return { id }; } } }, + workerScriptPath: "/worker.cjs", + }); + manager.onSessionOwned(() => new Promise((resolve) => { releaseOwnership = resolve; })); + + const promise = manager.request("netcatty:local:start", {}, { webContentsId: 7 }); + child.emit("message", { + kind: "response", + requestId: child.messages[0].requestId, + result: { sessionId: "local-1" }, + }); + await new Promise((resolve) => setImmediate(resolve)); + child.emit("message", { kind: "output", sessionId: "local-1", data: "banner" }); + assert.deepEqual(routed, []); + + releaseOwnership(); + assert.deepEqual(await promise, { sessionId: "local-1" }); + assert.deepEqual(routed, [{ sessionId: "local-1", data: "banner" }]); +}); + +test("destroying a renderer immediately cancels its pending session ownership", async () => { + const child = new FakeChild(); + const contents = new EventEmitter(); + contents.id = 7; + contents.destroyed = false; + contents.isDestroyed = () => contents.destroyed; + let releaseOwnership; + let outputOpened = false; + const manager = createTerminalWorkerManager({ + utilityProcess: { fork: () => child }, + terminalOutputChannel: { + openSession() { outputOpened = true; }, + }, + electronModule: { webContents: { fromId: () => contents } }, + workerScriptPath: "/worker.cjs", + }); + manager.onSessionOwned(() => new Promise((resolve) => { releaseOwnership = resolve; })); + + const start = manager.request("netcatty:local:start", {}, { webContentsId: 7 }); + child.emit("message", { + kind: "response", + requestId: child.messages[0].requestId, + result: { sessionId: "local-1" }, + }); + while (!releaseOwnership) await new Promise((resolve) => setImmediate(resolve)); + assert.equal(manager.ownsSession("local-1", 7), true); + + contents.destroyed = true; + contents.emit("destroyed"); + assert.equal(manager.ownsSession("local-1", 7), false); + assert.equal(manager.getSessionOwnerWebContentsId("local-1"), null); + releaseOwnership(); + + await assert.rejects(start, /output route opened/u); + assert.equal(outputOpened, false); +}); + +test("a start closed while ownership is pending rejects instead of creating a ghost session", async () => { + const child = new FakeChild(); + let releaseOwnership; + let outputOpened = false; + const manager = createTerminalWorkerManager({ + utilityProcess: { fork: () => child }, + terminalOutputChannel: { + openSession() { + outputOpened = true; + }, + }, + electronModule: { webContents: { fromId(id) { return { id }; } } }, + workerScriptPath: "/worker.cjs", + }); + manager.onSessionOwned(() => new Promise((resolve) => { releaseOwnership = resolve; })); + + const start = manager.request("netcatty:local:start", {}, { webContentsId: 7 }); + child.emit("message", { + kind: "response", + requestId: child.messages[0].requestId, + result: { sessionId: "local-1" }, + }); + await new Promise((resolve) => setImmediate(resolve)); + + manager.send("netcatty:close", { sessionId: "local-1" }, { webContentsId: 7 }); + releaseOwnership(); + + await assert.rejects(start, /closed before its output route opened/u); + assert.equal(outputOpened, false); + assert.equal(manager.hasOpenSession("local-1"), false); +}); + +test("a worker exit while ownership is pending rejects instead of creating a ghost session", async () => { + const child = new FakeChild(); + let releaseOwnership; + let outputOpened = false; + const manager = createTerminalWorkerManager({ + utilityProcess: { fork: () => child }, + terminalOutputChannel: { + openSession() { + outputOpened = true; + }, + }, + electronModule: { webContents: { fromId(id) { return { id }; } } }, + workerScriptPath: "/worker.cjs", + }); + manager.onSessionOwned(() => new Promise((resolve) => { releaseOwnership = resolve; })); + + const start = manager.request("netcatty:local:start", {}, { webContentsId: 7 }); + child.emit("message", { + kind: "response", + requestId: child.messages[0].requestId, + result: { sessionId: "local-1" }, + }); + await new Promise((resolve) => setImmediate(resolve)); + + child.emit("exit", 1); + await assert.rejects(start, /Terminal worker exited with code 1/u); + releaseOwnership(); + await new Promise((resolve) => setImmediate(resolve)); + + assert.equal(outputOpened, false); + assert.equal(manager.hasOpenSession("local-1"), false); +}); + +test("an older ownership waiter cannot release a newer output route", async () => { + const child = new FakeChild(); + const routed = []; + const releaseOwnership = []; + let outputOpen = false; + const manager = createTerminalWorkerManager({ + utilityProcess: { fork: () => child }, + terminalOutputChannel: { + openSession() { outputOpen = true; }, + send(sessionId, data) { + if (!outputOpen) return false; + routed.push({ sessionId, data }); + return true; + }, + }, + electronModule: { webContents: { fromId(id) { return { id }; } } }, + workerScriptPath: "/worker.cjs", + }); + manager.onSessionOwned(() => new Promise((resolve) => { releaseOwnership.push(resolve); })); + + const first = manager.request("netcatty:local:start", {}, { webContentsId: 7 }); + child.emit("message", { + kind: "response", + requestId: child.messages[0].requestId, + result: { sessionId: "local-1" }, + }); + await new Promise((resolve) => setImmediate(resolve)); + + const second = manager.request("netcatty:local:reconnect", { sessionId: "local-1" }, { + webContentsId: 7, + }); + child.emit("message", { + kind: "response", + requestId: child.messages[1].requestId, + result: { sessionId: "local-1" }, + }); + await new Promise((resolve) => setImmediate(resolve)); + assert.equal(releaseOwnership.length, 2); + + child.emit("message", { kind: "output", sessionId: "local-1", data: "new-banner" }); + releaseOwnership[0](); + await new Promise((resolve) => setImmediate(resolve)); + assert.equal(outputOpen, false); + assert.deepEqual(routed, []); + + releaseOwnership[1](); + assert.deepEqual(await first, { sessionId: "local-1" }); + assert.deepEqual(await second, { sessionId: "local-1" }); + assert.deepEqual(routed, [{ sessionId: "local-1", data: "new-banner" }]); +}); + +test("terminal interceptor ports transfer directly to the worker and warnings stay host-owned", () => { + const child = new FakeChild(); + const manager = createTerminalWorkerManager({ + utilityProcess: { fork: () => child }, + workerScriptPath: "/worker.cjs", + }); + const port = new FakePort("interceptor"); + const warnings = []; + manager.onTerminalInterceptorWarning((warning) => warnings.push(warning)); + manager.attachTerminalInterceptor({ + sessionId: "session-1", + direction: "input", + providerId: "com.example.input", + }, port); + assert.equal(child.messages[0].kind, "terminal-interceptor-port"); + assert.deepEqual(child.transferLists[0], [port]); + child.emit("message", { + kind: "terminal-interceptor-warning", + warning: { sessionId: "session-1", direction: "input", code: "timeout" }, + }); + assert.equal(warnings[0].code, "timeout"); + manager.detachTerminalInterceptor("session-1", "input"); + assert.equal(child.messages[1].kind, "terminal-interceptor-detach"); + child.emit("exit", 9); + assert.deepEqual(warnings[1], { + code: "worker-exit", + message: "Terminal worker exited with code 9", + }); +}); + test("request opens a terminal output port when a session starts", async () => { const child = new FakeChild(); const opened = []; @@ -536,6 +755,121 @@ test("worker buffered output chunk cap carries dropped metadata to retained outp }); }); +test("metadata-only interceptor output obeys the pending chunk cap", async () => { + const child = new FakeChild(); + const outputPort = { label: "worker-output-port" }; + const manager = createTerminalWorkerManager({ + utilityProcess: { fork() { return child; } }, + terminalOutputChannel: { openSession() { return outputPort; } }, + electronModule: { webContents: { fromId(id) { return { id }; } } }, + maxPendingOutputChunks: 1, + workerScriptPath: "/worker.cjs", + }); + + const promise = manager.request("netcatty:local:start", {}, { webContentsId: 7 }); + child.emit("message", { + kind: "response", + requestId: child.messages[0].requestId, + result: { sessionId: "local-1" }, + }); + await promise; + for (let index = 0; index < 3; index += 1) { + child.emit("message", { + kind: "output", + sessionId: "local-1", + data: "", + meta: { pluginPipelineIngressBytes: 1 }, + }); + } + child.emit("message", { kind: "output-port-ready", sessionId: "local-1" }); + + assert.deepEqual(child.messages[2], { + kind: "output-flush", + sessionId: "local-1", + chunks: [{ data: "", meta: { pluginPipelineIngressBytes: 3 } }], + }); +}); + +test("pending output merge keeps state and provenance from only the latest raw chunk", async () => { + const child = new FakeChild(); + const outputPort = { label: "worker-output-port" }; + const manager = createTerminalWorkerManager({ + utilityProcess: { fork() { return child; } }, + terminalOutputChannel: { openSession() { return outputPort; } }, + electronModule: { webContents: { fromId(id) { return { id }; } } }, + maxPendingOutputChunks: 1, + workerScriptPath: "/worker.cjs", + }); + + const promise = manager.request("netcatty:local:start", {}, { webContentsId: 7 }); + child.emit("message", { + kind: "response", + requestId: child.messages[0].requestId, + result: { sessionId: "local-1" }, + }); + await promise; + child.emit("message", { + kind: "output", + sessionId: "local-1", + data: "Password: ", + meta: { + pluginPipelineIngressBytes: 10, + pluginPipelineProcessed: true, + pluginPipelineSensitiveInput: true, + }, + }); + child.emit("message", { + kind: "output", + sessionId: "local-1", + data: "READY", + }); + child.emit("message", { kind: "output-port-ready", sessionId: "local-1" }); + + assert.deepEqual(child.messages[2], { + kind: "output-flush", + sessionId: "local-1", + chunks: [{ data: "READY", meta: { pluginPipelineIngressBytes: 10 } }], + }); +}); + +test("partial trimming carries sliced raw ingress into inherited flow accounting", async () => { + const child = new FakeChild(); + const outputPort = { label: "worker-output-port" }; + const manager = createTerminalWorkerManager({ + utilityProcess: { fork() { return child; } }, + terminalOutputChannel: { openSession() { return outputPort; } }, + electronModule: { webContents: { fromId(id) { return { id }; } } }, + maxPendingOutputBytes: 5, + workerScriptPath: "/worker.cjs", + }); + + const promise = manager.request("netcatty:local:start", {}, { webContentsId: 7 }); + child.emit("message", { + kind: "response", + requestId: child.messages[0].requestId, + result: { sessionId: "local-1" }, + }); + await promise; + child.emit("message", { + kind: "output", + sessionId: "local-1", + data: "", + meta: { pluginPipelineIngressBytes: 10, pluginPipelineProcessed: true }, + }); + child.emit("message", { kind: "output", sessionId: "local-1", data: "abcde" }); + child.emit("message", { kind: "output", sessionId: "local-1", data: "Z" }); + child.emit("message", { kind: "output-port-ready", sessionId: "local-1" }); + + assert.deepEqual(child.messages[2], { + kind: "output-flush", + sessionId: "local-1", + chunks: [ + { data: "bcde", meta: { pluginPipelineIngressBytes: 11 } }, + "Z", + ], + }); +}); + test("worker fallback output after a ready output port is delivered over legacy IPC", async () => { const child = new FakeChild(); const sent = []; @@ -904,7 +1238,7 @@ test("close immediately clears the output route and drops pending output", async requestId: child.messages[0].requestId, result: { sessionId: "session-1" }, }); - await promise; + await assert.rejects(promise, /closed before its output route opened/u); child.emit("message", { kind: "output", sessionId: "session-1", @@ -1069,6 +1403,114 @@ test("worker renderer events wrapped in MessageEvent data are forwarded", () => ]); }); +test("worker terminal exit notifies host session lifecycle listeners", async () => { + const child = new FakeChild(); + const closed = []; + const manager = createTerminalWorkerManager({ + utilityProcess: { fork: () => child }, + terminalOutputChannel: { openSession: () => true, closeSession() {} }, + electronModule: { webContents: { fromId: (id) => ({ id, isDestroyed: () => false, send() {} }) } }, + workerScriptPath: "/worker.cjs", + }); + manager.onSessionClosed((event) => closed.push(event)); + const start = manager.request("netcatty:local:start", {}, { webContentsId: 7 }); + child.emit("message", { + kind: "response", + requestId: child.messages[0].requestId, + result: { sessionId: "session-1" }, + }); + await start; + + child.emit("message", { + kind: "renderer-event", + webContentsId: 7, + channel: "netcatty:exit", + payload: { sessionId: "session-1", reason: "exited" }, + }); + + assert.deepEqual(closed, [{ sessionId: "session-1", reason: "exited" }]); +}); + +test("explicit close notifies host session lifecycle exactly once before the worker exit", async () => { + const child = new FakeChild(); + const closed = []; + const manager = createTerminalWorkerManager({ + utilityProcess: { fork: () => child }, + terminalOutputChannel: { openSession: () => true, closeSession() {} }, + electronModule: { webContents: { fromId: (id) => ({ id, isDestroyed: () => false, send() {} }) } }, + workerScriptPath: "/worker.cjs", + }); + manager.onSessionClosed((event) => closed.push(event)); + const start = manager.request("netcatty:local:start", {}, { webContentsId: 7 }); + child.emit("message", { + kind: "response", + requestId: child.messages[0].requestId, + result: { sessionId: "session-1" }, + }); + await start; + + manager.send("netcatty:close", { sessionId: "session-1" }, { webContentsId: 7 }); + assert.deepEqual(closed, [{ sessionId: "session-1", reason: "closed" }]); + child.emit("message", { + kind: "renderer-event", + webContentsId: 7, + channel: "netcatty:exit", + payload: { sessionId: "session-1", reason: "exited" }, + }); + assert.deepEqual(closed, [{ sessionId: "session-1", reason: "closed" }]); +}); + +test("a duplicate exit from an old session generation cannot close a reconnected session", async () => { + const child = new FakeChild(); + const closed = []; + const manager = createTerminalWorkerManager({ + utilityProcess: { fork: () => child }, + terminalOutputChannel: { openSession: () => true, closeSession() {} }, + electronModule: { webContents: { fromId: (id) => ({ id, isDestroyed: () => false, send() {} }) } }, + workerScriptPath: "/worker.cjs", + }); + manager.onSessionClosed((event) => closed.push(event)); + + const first = manager.request("netcatty:local:start", {}, { webContentsId: 7 }); + child.emit("message", { + kind: "response", + requestId: child.messages[0].requestId, + result: { sessionId: "session-1" }, + sessionGeneration: 0, + }); + await first; + child.emit("message", { + kind: "renderer-event", + webContentsId: 7, + channel: "netcatty:exit", + payload: { sessionId: "session-1", reason: "error" }, + sessionGeneration: 0, + }); + + const reconnect = manager.request("netcatty:local:reconnect", { sessionId: "session-1" }, { + webContentsId: 7, + }); + child.emit("message", { + kind: "response", + requestId: child.messages.at(-1).requestId, + result: { sessionId: "session-1" }, + sessionGeneration: 1, + }); + await reconnect; + assert.equal(manager.hasOpenSession("session-1"), true); + + child.emit("message", { + kind: "renderer-event", + webContentsId: 7, + channel: "netcatty:exit", + payload: { sessionId: "session-1", reason: "close" }, + sessionGeneration: 0, + }); + + assert.equal(manager.hasOpenSession("session-1"), true); + assert.deepEqual(closed, [{ sessionId: "session-1", reason: "error" }]); +}); + test("rebound interactive events target only the popup while exit also reaches home", async () => { const child = new FakeChild(); const forwarded = []; @@ -1099,7 +1541,7 @@ test("rebound interactive events target only the popup while exit also reaches h result: { sessionId: "session-1" }, }); await started; - assert.equal(manager.rebindOutputSession("session-1", 9).success, true); + assert.equal((await manager.rebindOutputSession("session-1", 9)).success, true); child.emit("message", { kind: "renderer-event", @@ -1126,6 +1568,162 @@ test("rebound interactive events target only the popup while exit also reaches h ]); }); +test("rebind waits for ownership and routes interactive events to the pending renderer", async () => { + const child = new FakeChild(); + const forwarded = []; + const dialogOwners = []; + let releaseRebind; + const manager = createTerminalWorkerManager({ + utilityProcess: { fork() { return child; } }, + terminalOutputChannel: { openSession() { return true; }, closeSession() {} }, + electronModule: { + webContents: { + fromId(id) { + return { + id, + isDestroyed() { return false; }, + send(channel, payload) { forwarded.push({ id, channel, payload }); }, + }; + }, + }, + BrowserWindow: { + fromWebContents(contents) { return { webContentsId: contents.id }; }, + }, + dialog: { + async showOpenDialog(owner) { + dialogOwners.push(owner?.webContentsId ?? null); + return { canceled: true, filePaths: [] }; + }, + }, + }, + workerScriptPath: "/worker.cjs", + }); + manager.onSessionOwned(({ webContentsId }) => ( + webContentsId === 9 + ? new Promise((resolve) => { releaseRebind = resolve; }) + : undefined + )); + + const started = manager.request("netcatty:local:start", {}, { webContentsId: 7 }); + child.emit("message", { + kind: "response", + requestId: child.messages[0].requestId, + result: { sessionId: "session-1" }, + }); + await started; + + let settled = false; + const rebound = manager.rebindOutputSession("session-1", 9).then((result) => { + settled = true; + return result; + }); + await new Promise((resolve) => setImmediate(resolve)); + assert.equal(settled, false); + assert.equal(manager.getSessionWebContentsId("session-1"), 7); + assert.equal(manager.getSessionOwnerWebContentsId("session-1"), 9); + + child.emit("message", { + kind: "renderer-event", + webContentsId: 7, + channel: "netcatty:zmodem:overwrite-request", + payload: { sessionId: "session-1", requestId: "request-1" }, + }); + assert.deepEqual(forwarded, [{ + id: 9, + channel: "netcatty:zmodem:overwrite-request", + payload: { sessionId: "session-1", requestId: "request-1" }, + }]); + + child.emit("message", { + kind: "zmodem-upload-dialog", + requestId: "upload-dialog-1", + sessionId: "session-1", + webContentsId: 7, + }); + child.emit("message", { + kind: "zmodem-download-dialog", + requestId: "download-dialog-1", + sessionId: "session-1", + webContentsId: 7, + }); + await new Promise((resolve) => setImmediate(resolve)); + assert.deepEqual(dialogOwners, [9, 9]); + + releaseRebind(); + assert.equal((await rebound).success, true); + assert.equal(manager.getSessionWebContentsId("session-1"), 9); + assert.equal(manager.getSessionOwnerWebContentsId("session-1"), 9); +}); + +test("failed output-port transfer clears pending state and restores the previous route", async () => { + const child = new FakeChild(); + const postMessage = child.postMessage.bind(child); + child.postMessage = (message, transferList) => { + if (message?.kind === "output-port") { + throw new Error("worker transfer failed"); + } + postMessage(message, transferList); + }; + const forwarded = []; + let openCount = 0; + const manager = createTerminalWorkerManager({ + utilityProcess: { fork() { return child; } }, + terminalOutputChannel: { + openSession() { + openCount += 1; + return openCount === 1 ? true : { label: "worker-output-port" }; + }, + send() { return false; }, + closeSession() {}, + }, + electronModule: { + webContents: { + fromId(id) { + return { + id, + isDestroyed() { return false; }, + send(channel, payload) { forwarded.push({ id, channel, payload }); }, + }; + }, + }, + }, + workerScriptPath: "/worker.cjs", + }); + + const started = manager.request("netcatty:local:start", {}, { webContentsId: 7 }); + child.emit("message", { + kind: "response", + requestId: child.messages[0].requestId, + result: { sessionId: "session-1" }, + }); + await started; + + const rebound = manager.rebindOutputSession("session-1", 9); + child.emit("message", { kind: "output", sessionId: "session-1", data: "buffered" }); + assert.deepEqual(await rebound, { + success: false, + error: "Failed to rebind session output", + }); + assert.equal(manager.getSessionWebContentsId("session-1"), 7); + assert.equal(manager.getAttachHomeWebContentsId("session-1"), null); + + child.emit("message", { + kind: "renderer-event", + webContentsId: 7, + channel: "netcatty:zmodem:overwrite-request", + payload: { sessionId: "session-1", requestId: "request-1" }, + }); + assert.deepEqual(forwarded, [{ + id: 7, + channel: "netcatty:zmodem:overwrite-request", + payload: { sessionId: "session-1", requestId: "request-1" }, + }]); + assert.equal( + child.messages.some((message) => message.kind === "output-flush" && message.sessionId === "session-1"), + true, + ); +}); + test("explicit close notifies both a rebound popup and its home renderer", async () => { const child = new FakeChild(); const forwarded = []; @@ -1151,7 +1749,7 @@ test("explicit close notifies both a rebound popup and its home renderer", async result: { sessionId: "session-1" }, }); await started; - assert.equal(manager.rebindOutputSession("session-1", 9).success, true); + assert.equal((await manager.rebindOutputSession("session-1", 9)).success, true); const closing = manager.request( "netcatty:close:await", diff --git a/electron/main/registerBridges.cjs b/electron/main/registerBridges.cjs index 9478cfac0..a864d6674 100644 --- a/electron/main/registerBridges.cjs +++ b/electron/main/registerBridges.cjs @@ -102,6 +102,11 @@ function createBridgeRegistrar(context) { const { createNativePermissionDecisionProvider, } = require("../plugins/nativePermissionDecision.cjs"); + const { + terminalInterceptorChoiceLabel, + terminalInterceptorIdentifier, + terminalInterceptorMessages, + } = require("../plugins/terminalInterceptorMessages.cjs"); return createPluginHostService({ app, electron: electronModule, @@ -111,6 +116,36 @@ function createBridgeRegistrar(context) { window: win, }), getLocale: () => getWindowManager().getCurrentLanguage?.() ?? "en", + requestTerminalInterceptorSelection: async ({ direction, providers }) => { + const messages = terminalInterceptorMessages(getWindowManager().getCurrentLanguage?.() ?? "en"); + const buttons = [ + ...providers.map(terminalInterceptorChoiceLabel), + messages.noInterceptor, + ]; + const result = await electronModule.dialog.showMessageBox(win, { + type: "question", + title: messages.selectTitle(direction), + message: messages.selectMessage(direction), + buttons, + cancelId: buttons.length - 1, + defaultId: buttons.length - 1, + noLink: true, + }); + return result.response >= 0 && result.response < providers.length + ? providers[result.response].provider.id + : null; + }, + showTerminalInterceptorWarning: (warning) => { + const messages = terminalInterceptorMessages(getWindowManager().getCurrentLanguage?.() ?? "en"); + void electronModule.dialog.showMessageBox(win, { + type: "warning", + title: messages.warningTitle, + message: messages.warningMessage, + detail: warning?.providerId + ? `${messages.warningDetail}\n${terminalInterceptorIdentifier(warning.providerId)}` + : messages.warningDetail, + }).catch(() => {}); + }, }); }, registerShutdown: (handler) => { @@ -123,6 +158,7 @@ function createBridgeRegistrar(context) { manager: pluginHostService?.manager, contributionService: pluginHostService?.contributionService, terminalProviderService: pluginHostService?.terminalProviderService, + terminalDataPipelineService: pluginHostService?.terminalDataPipelineService, resolveContributionIcon: (payload) => pluginHostService?.contributionIconService?.resolve(payload), viewHost: pluginHostService?.viewHost, env: process.env, @@ -290,6 +326,19 @@ function createBridgeRegistrar(context) { MessageChannelMain: electronModule.MessageChannelMain, }) : null; + const terminalPipelineSessionManager = terminalWorkerManager ?? { + getSessionOwnerWebContentsId(sessionId) { + const owner = sessions.get(sessionId)?.webContentsId; + return Number.isSafeInteger(owner) ? owner : null; + }, + ownsSession(sessionId, webContentsId) { + return Number.isSafeInteger(webContentsId) + && sessions.get(sessionId)?.webContentsId === webContentsId; + }, + }; + pluginHostService?.terminalDataPipelineService?.bindTerminalWorkerManager( + terminalPipelineSessionManager, + ); const reportOpenedSessionActivity = (event) => aiBridge.reportOpenedSessionActivity?.(event); terminalWorkerManager?.addOutputTap?.((sessionId) => { reportOpenedSessionActivity({ sessionId, phase: "touch" }); diff --git a/electron/plugins/contractValidator.cjs b/electron/plugins/contractValidator.cjs index 60c1e06b2..cab08ba36 100644 --- a/electron/plugins/contractValidator.cjs +++ b/electron/plugins/contractValidator.cjs @@ -28,6 +28,9 @@ function formatValidationErrors(errors) { const rpcMessageValidator = createDefinitionValidator("RpcMessage"); const initializeResultValidator = createDefinitionValidator("RuntimeInitializeResult"); +const terminalInterceptorAttachmentParamsValidator = createDefinitionValidator("TerminalInterceptorAttachmentParams"); +const terminalInterceptorAttachmentResultValidator = createDefinitionValidator("TerminalInterceptorAttachmentResult"); +const terminalInterceptorFrameValidator = createDefinitionValidator("TerminalInterceptorFrame"); const providerRequestValidator = createDefinitionValidator("ProviderRequest"); const providerResultValidator = createDefinitionValidator("ProviderResult"); const streamFrameValidator = createDefinitionValidator("StreamFrame"); @@ -49,6 +52,32 @@ function assertInitializeResult(value) { return assertContractValue(initializeResultValidator, value, "Initialize result"); } +function assertTerminalInterceptorAttachmentParams(value) { + assertPluginJsonValue(value, { maxBytes: PLUGIN_RPC_MAX_JSON_BYTES }); + return assertContractValue( + terminalInterceptorAttachmentParamsValidator, + value, + "Terminal interceptor attachment params", + ); +} + +function assertTerminalInterceptorAttachmentResult(value) { + assertPluginJsonValue(value, { maxBytes: PLUGIN_RPC_MAX_JSON_BYTES }); + return assertContractValue( + terminalInterceptorAttachmentResultValidator, + value, + "Terminal interceptor attachment result", + ); +} + +function assertTerminalInterceptorFrameSchema(value) { + return assertContractValue( + terminalInterceptorFrameValidator, + value, + "Terminal interceptor frame", + ); +} + function assertProviderRequest(value) { assertPluginJsonValue(value, { maxBytes: PLUGIN_RPC_MAX_JSON_BYTES }); return assertContractValue(providerRequestValidator, value, "Provider request"); @@ -70,6 +99,9 @@ function resolveContractRuntimePath(...segments) { module.exports = { assertInitializeResult, + assertTerminalInterceptorAttachmentParams, + assertTerminalInterceptorAttachmentResult, + assertTerminalInterceptorFrameSchema, assertProviderRequest, assertProviderResult, assertRpcMessage, diff --git a/electron/plugins/generated/plugin-contract.schema.json b/electron/plugins/generated/plugin-contract.schema.json index 73752dd12..371751ee2 100644 --- a/electron/plugins/generated/plugin-contract.schema.json +++ b/electron/plugins/generated/plugin-contract.schema.json @@ -80,6 +80,13 @@ "maxCreditBytes": 16777216 } }, + "TerminalInterceptorLimits": { + "description": "Host-enforced byte and receive-window limits for the privileged direct terminal interceptor MessagePort.", + "const": { + "maxChunkBytes": 65536, + "maxWindowBytes": 262144 + } + }, "StreamId": { "type": "string", "minLength": 1, @@ -1209,6 +1216,7 @@ "method": { "enum": [ "plugin.initialize", + "plugin.terminal.interceptor.attach", "$/cancelRequest", "$/progress" ] @@ -1245,6 +1253,7 @@ "method": { "enum": [ "plugin.initialize", + "plugin.terminal.interceptor.attach", "$/cancelRequest", "$/progress" ] @@ -1738,6 +1747,147 @@ } ] }, + "TerminalInterceptorDirection": { + "type": "string", + "enum": [ + "input", + "output" + ] + }, + "TerminalInterceptorChunkByteLength": { + "type": "integer", + "minimum": 0, + "maximum": 65536 + }, + "TerminalInterceptorWindowBytes": { + "type": "integer", + "minimum": 1, + "maximum": 262144 + }, + "TerminalInterceptorCreditBytes": { + "type": "integer", + "minimum": 0, + "maximum": 262144 + }, + "TerminalInterceptorReadyFrame": { + "type": "object", + "required": [ + "type", + "sessionId", + "direction", + "windowBytes" + ], + "properties": { + "type": { + "const": "netcatty:terminal-interceptor:ready" + }, + "sessionId": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "pattern": "^[^\\u0000]+$" + }, + "direction": { + "$ref": "#/$defs/TerminalInterceptorDirection" + }, + "windowBytes": { + "$ref": "#/$defs/TerminalInterceptorWindowBytes" + } + }, + "additionalProperties": false + }, + "TerminalInterceptorChunkFrame": { + "type": "object", + "required": [ + "type", + "sequence", + "direction", + "creditBytes", + "byteLength" + ], + "properties": { + "type": { + "const": "netcatty:terminal-interceptor:chunk" + }, + "sequence": { + "$ref": "#/$defs/SafePositiveInteger" + }, + "direction": { + "$ref": "#/$defs/TerminalInterceptorDirection" + }, + "creditBytes": { + "$ref": "#/$defs/TerminalInterceptorCreditBytes" + }, + "byteLength": { + "$ref": "#/$defs/TerminalInterceptorChunkByteLength" + } + }, + "additionalProperties": false + }, + "TerminalInterceptorOkResultFrame": { + "type": "object", + "required": [ + "type", + "sequence", + "status", + "creditBytes", + "byteLength" + ], + "properties": { + "type": { + "const": "netcatty:terminal-interceptor:result" + }, + "sequence": { + "$ref": "#/$defs/SafePositiveInteger" + }, + "status": { + "const": "ok" + }, + "creditBytes": { + "$ref": "#/$defs/TerminalInterceptorChunkByteLength" + }, + "byteLength": { + "$ref": "#/$defs/TerminalInterceptorChunkByteLength" + } + }, + "additionalProperties": false + }, + "TerminalInterceptorFailedResultFrame": { + "type": "object", + "required": [ + "type", + "sequence", + "status" + ], + "properties": { + "type": { + "const": "netcatty:terminal-interceptor:result" + }, + "sequence": { + "$ref": "#/$defs/SafePositiveInteger" + }, + "status": { + "const": "failed" + } + }, + "additionalProperties": false + }, + "TerminalInterceptorFrame": { + "oneOf": [ + { + "$ref": "#/$defs/TerminalInterceptorReadyFrame" + }, + { + "$ref": "#/$defs/TerminalInterceptorChunkFrame" + }, + { + "$ref": "#/$defs/TerminalInterceptorOkResultFrame" + }, + { + "$ref": "#/$defs/TerminalInterceptorFailedResultFrame" + } + ] + }, "RuntimeInitializeParams": { "type": "object", "required": [ @@ -1846,6 +1996,186 @@ }, "additionalProperties": false }, + "TerminalSessionSnapshot": { + "type": "object", + "required": [ + "sessionId", + "protocol", + "status" + ], + "properties": { + "sessionId": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "pattern": "^[^\\u0000]+$" + }, + "hostId": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "pattern": "^[^\\u0000]+$" + }, + "workspaceId": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "pattern": "^[^\\u0000]+$" + }, + "protocol": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]*$" + }, + "status": { + "type": "string", + "enum": [ + "connecting", + "connected", + "disconnected" + ] + }, + "cwd": { + "type": "string", + "minLength": 1, + "maxLength": 4096, + "pattern": "^[^\\u0000]+$" + }, + "title": { + "type": "string", + "minLength": 1, + "maxLength": 1024, + "pattern": "^[^\\u0000]+$" + }, + "shellType": { + "type": "string", + "enum": [ + "posix", + "fish", + "powershell", + "cmd", + "unknown" + ] + }, + "cols": { + "type": "integer", + "minimum": 1, + "maximum": 16384 + }, + "rows": { + "type": "integer", + "minimum": 1, + "maximum": 16384 + }, + "alternateScreen": { + "type": "boolean" + } + }, + "additionalProperties": false + }, + "TerminalInterceptorAttachmentDescriptor": { + "type": "object", + "required": [ + "providerId", + "direction", + "session" + ], + "properties": { + "providerId": { + "$ref": "#/$defs/ContributionId" + }, + "direction": { + "type": "string", + "enum": [ + "input", + "output" + ] + }, + "session": { + "$ref": "#/$defs/TerminalSessionSnapshot" + } + }, + "additionalProperties": false + }, + "TerminalInterceptorAttachmentParams": { + "type": "object", + "required": [ + "descriptor" + ], + "properties": { + "descriptor": { + "$ref": "#/$defs/TerminalInterceptorAttachmentDescriptor" + } + }, + "additionalProperties": false + }, + "TerminalInterceptorAttachmentResult": { + "type": "object", + "required": [ + "accepted" + ], + "properties": { + "accepted": { + "const": true + } + }, + "additionalProperties": false + }, + "TerminalInterceptorAttachmentRequest": { + "type": "object", + "required": [ + "jsonrpc", + "id", + "method", + "params" + ], + "properties": { + "jsonrpc": { + "const": "2.0" + }, + "id": { + "$ref": "#/$defs/RpcId" + }, + "method": { + "const": "plugin.terminal.interceptor.attach" + }, + "params": { + "$ref": "#/$defs/TerminalInterceptorAttachmentParams" + }, + "deadlineMs": { + "type": "integer", + "minimum": 1, + "maximum": 300000 + }, + "cancellationId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + } + }, + "additionalProperties": false + }, + "TerminalInterceptorAttachmentSuccess": { + "type": "object", + "required": [ + "jsonrpc", + "id", + "result" + ], + "properties": { + "jsonrpc": { + "const": "2.0" + }, + "id": { + "$ref": "#/$defs/RpcId" + }, + "result": { + "$ref": "#/$defs/TerminalInterceptorAttachmentResult" + } + }, + "additionalProperties": false + }, "RpcMessage": { "description": "A mutually exclusive RPC wire envelope. Reserved inbound methods use their exact schemas. Successful responses require method-specific validation through request correlation.", "oneOf": [ @@ -1869,6 +2199,9 @@ }, { "$ref": "#/$defs/RuntimeInitializeRequest" + }, + { + "$ref": "#/$defs/TerminalInterceptorAttachmentRequest" } ] }, @@ -1962,6 +2295,15 @@ "type": "string", "minLength": 1, "maxLength": 128 + }, + "allowedScopes": { + "type": "array", + "minItems": 1, + "maxItems": 4, + "uniqueItems": true, + "items": { + "$ref": "#/$defs/PermissionGrantScope" + } } }, "additionalProperties": false diff --git a/electron/plugins/hostService.cjs b/electron/plugins/hostService.cjs index 249162644..d2234db9f 100644 --- a/electron/plugins/hostService.cjs +++ b/electron/plugins/hostService.cjs @@ -32,6 +32,7 @@ const { registerSecurePluginCapabilities } = require("./secureCapabilities.cjs") const { PluginSecretStore } = require("./secretStore.cjs"); const { SecretLeaseStore } = require("./secretLease.cjs"); const { PluginTerminalProviderService } = require("./terminalProviderService.cjs"); +const { PluginTerminalDataPipelineService } = require("./terminalDataPipelineService.cjs"); function getElectronProcessMetrics(app, pid) { const metric = app.getAppMetrics?.().find((candidate) => candidate.pid === pid); @@ -200,6 +201,16 @@ function createPluginHostService(options) { permissionEngine, runtimeSupervisor, }); + const terminalDataPipelineService = options.electron.MessageChannelMain + ? new PluginTerminalDataPipelineService({ + contributionService, + permissionEngine, + runtimeSupervisor, + MessageChannelMain: options.electron.MessageChannelMain, + requestSelection: options.requestTerminalInterceptorSelection, + showWarning: options.showTerminalInterceptorWarning, + }) + : null; quotaManager.setViolationHandler((identity, error) => ( runtimeSupervisor.enforcePolicyViolation(identity, error) )); @@ -218,6 +229,7 @@ function createPluginHostService(options) { runtimeSupervisor, contributionService, beforeClose: async () => { + terminalDataPipelineService?.shutdown(); await viewHost?.shutdown(); await companionSupervisor.shutdown(); leaseStore.shutdown(); @@ -245,6 +257,7 @@ function createPluginHostService(options) { runtimeSupervisor, secretStore, terminalProviderService, + terminalDataPipelineService, viewHost, }; } catch (error) { diff --git a/electron/plugins/hostService.test.cjs b/electron/plugins/hostService.test.cjs index 57fe2459b..18397b288 100644 --- a/electron/plugins/hostService.test.cjs +++ b/electron/plugins/hostService.test.cjs @@ -200,6 +200,54 @@ test("first-party placement selects the utility runtime for companion manifests" assert.deepEqual(requested, ["companion.execute", "runtime.advanced"]); }); +test("first-party placement selects utility for dual-entrypoint terminal interceptors", async (context) => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "netcatty-plugin-host-service-")); + context.after(() => fs.rmSync(root, { recursive: true, force: true })); + const requested = []; + const service = createPluginHostService({ + ...createOptions(root), + requestPermissionDecision: async (request) => { + requested.push(request); + return { requestId: request.requestId, decision: "allow", scope: "application" }; + }, + }); + context.after(() => service.manager.shutdown()); + const manifest = { + manifestVersion: 1, + id: "com.example.interceptor-placement", + name: "interceptor-placement", + version: "1.0.0", + publisher: "example", + engines: { netcatty: ">=0.0.0", api: ">=0.1.0-internal <0.2.0" }, + main: { browser: "browser.js", node: "node.js" }, + permissions: { + required: ["runtime.advanced", "provider.terminal", "terminal.intercept.input"], + }, + contributes: { + providers: [{ + id: "com.example.interceptor-placement.input", + label: "Input filter", + kind: "terminal.interceptor.input", + }], + }, + }; + assert.equal(await service.runtimeSupervisor.resolveRuntimeKind({ + plugin: { id: manifest.id, activeVersion: manifest.version, manifest }, + availableKinds: ["browser", "utility"], + securityPrincipal: "unsigned-package:interceptor-placement", + signal: new AbortController().signal, + }), "utility"); + assert.deepEqual(requested.map((request) => request.permission), [ + "provider.terminal", + "terminal.intercept.input", + "runtime.advanced", + ]); + assert.match( + requested.find((request) => request.permission === "terminal.intercept.input")?.reason ?? "", + /arbitrary no-echo input may not be detectable/u, + ); +}); + test("secure host methods fail closed without an approver while public logging remains available", async (context) => { const root = fs.mkdtempSync(path.join(os.tmpdir(), "netcatty-plugin-host-service-")); context.after(() => fs.rmSync(root, { recursive: true, force: true })); diff --git a/electron/plugins/nativePermissionDecision.cjs b/electron/plugins/nativePermissionDecision.cjs index 85c0c749d..f8c00f43e 100644 --- a/electron/plugins/nativePermissionDecision.cjs +++ b/electron/plugins/nativePermissionDecision.cjs @@ -44,14 +44,22 @@ function createNativePermissionDecisionProvider(options) { const window = options.window; return async (request, context = {}) => { context.signal?.throwIfAborted(); + const allowedScopes = Array.isArray(request.allowedScopes) + ? new Set(request.allowedScopes) + : null; + const supportsScope = (scope) => allowedScopes == null || allowedScopes.has(scope); const choices = [ { label: "Deny", decision: "deny" }, - { label: "Allow Once", decision: "allow", scope: "once" }, - ...(request.sessionId + ...(supportsScope("once") ? [{ label: "Allow Once", decision: "allow", scope: "once" }] : []), + ...(request.sessionId && supportsScope("session") ? [{ label: "Allow for Session", decision: "allow", scope: "session" }] : []), - { label: "Allow for Application", decision: "allow", scope: "application" }, - { label: "Always Allow", decision: "allow", scope: "always" }, + ...(supportsScope("application") + ? [{ label: "Allow for Application", decision: "allow", scope: "application" }] + : []), + ...(supportsScope("always") + ? [{ label: "Always Allow", decision: "allow", scope: "always" }] + : []), ]; const messageBoxOptions = { type: "warning", diff --git a/electron/plugins/nativePermissionDecision.test.cjs b/electron/plugins/nativePermissionDecision.test.cjs index c04c4d268..90b5c8567 100644 --- a/electron/plugins/nativePermissionDecision.test.cjs +++ b/electron/plugins/nativePermissionDecision.test.cjs @@ -70,6 +70,33 @@ test("native permission decisions fail closed on cancellation and abort", async await assert.rejects(provider(permissionRequest(), { signal: controller.signal }), /runtime stopped/); }); +test("terminal interceptor permission prompts omit the unsupported one-use choice", async () => { + let captured; + const provider = createNativePermissionDecisionProvider({ + dialog: { + async showMessageBox(options) { + captured = options; + return { response: 1 }; + }, + }, + }); + assert.deepEqual(await provider(permissionRequest({ + sessionId: "session-1", + operationId: `terminal.interceptor.input:com.example.${"x".repeat(170)}`, + allowedScopes: ["session", "application", "always"], + })), { + requestId: "request-1", + decision: "allow", + scope: "session", + }); + assert.deepEqual(captured.buttons, [ + "Deny", + "Allow for Session", + "Allow for Application", + "Always Allow", + ]); +}); + test("native permission request details are bounded and preserve resource kinds", () => { const resources = Array.from({ length: MAX_VISIBLE_RESOURCES + 5 }, (_, index) => `/path/${index}`); const detail = describePermissionRequest(permissionRequest({ diff --git a/electron/plugins/permissionEngine.cjs b/electron/plugins/permissionEngine.cjs index efb9d4193..5189eb374 100644 --- a/electron/plugins/permissionEngine.cjs +++ b/electron/plugins/permissionEngine.cjs @@ -27,6 +27,10 @@ const AUDITED_PERMISSION_USES = new Set([ "terminal.intercept.output", ]); const PROMPT_TIMEOUT_MS = 30_000; +const PERMISSION_GRANT_SCOPES = new Set(["once", "session", "application", "always"]); +const HOST_PERMISSION_REASONS = Object.freeze({ + "terminal.intercept.input": "This plugin can inspect and rewrite Terminal input. Netcatty bypasses host-recognized credential input, but arbitrary no-echo input may not be detectable.", +}); function normalizePermissionOperationId(value) { if (value === undefined || value === null) return undefined; @@ -54,6 +58,18 @@ function normalizePermissionSessionId(value) { return value; } +function normalizePermissionAllowedScopes(value) { + if (value === undefined) return undefined; + if (!Array.isArray(value) || value.length === 0) { + throw permissionDenied("Plugin permission grant scopes are invalid"); + } + const scopes = [...new Set(value)]; + if (scopes.some((scope) => !PERMISSION_GRANT_SCOPES.has(scope))) { + throw permissionDenied("Plugin permission grant scopes are invalid"); + } + return Object.freeze(scopes); +} + function normalizePermissionResources(permission, values, label = "Plugin permission resources") { return normalizePermissionResourceDescriptors(permission, values, undefined, label) .map(({ resource }) => resource); @@ -155,10 +171,35 @@ class PluginPermissionEngine { this.applicationGrants = new Map(); this.sessionGrants = new Map(); this.pending = new Map(); + this.sessionPromptControllers = new Map(); + this.promptControllers = new Set(); + this.revocationListeners = new Set(); this.closed = false; this.shutdownController = new AbortController(); } + onDidRevoke(listener) { + if (typeof listener !== "function") throw new TypeError("Permission revocation listener is required"); + this.revocationListeners.add(listener); + return Object.freeze({ dispose: () => this.revocationListeners.delete(listener) }); + } + + #emitRevocation(event) { + const frozen = Object.freeze({ ...event }); + for (const listener of this.revocationListeners) { + try { listener(frozen); } catch {} + } + } + + #abortPrompts(pluginId, permission, resource) { + for (const entry of this.promptControllers) { + if (entry.pluginId !== pluginId) continue; + if (permission !== undefined && entry.permission !== permission) continue; + if (resource !== undefined && !entry.resources.includes(resource)) continue; + entry.controller.abort(permissionDenied("Plugin permission was revoked")); + } + } + #grantKey(pluginId, permission, declarationHash, resource) { return `${pluginId}\0${permission}\0${declarationHash}\0${resource}`; } @@ -298,9 +339,13 @@ class PluginPermissionEngine { ) throw permissionDenied("Plugin permission resource kinds are invalid"); descriptor = Object.freeze({ ...descriptor, - reason: normalizePermissionReason(descriptor.reason, permission), + reason: normalizePermissionReason( + HOST_PERMISSION_REASONS[permission] ?? descriptor.reason, + permission, + ), operationId: normalizePermissionOperationId(descriptor.operationId), sessionId: normalizePermissionSessionId(descriptor.sessionId), + allowedScopes: normalizePermissionAllowedScopes(descriptor.allowedScopes), }); const resourceDescriptors = normalizePermissionResourceDescriptors( permission, @@ -349,6 +394,7 @@ class PluginPermissionEngine { resourceKinds, descriptor.operationId ?? null, descriptor.sessionId ?? null, + descriptor.allowedScopes ?? null, ]); let pending = this.pending.get(pendingKey); let ownsPrompt = false; @@ -396,8 +442,21 @@ class PluginPermissionEngine { reason: descriptor.reason, ...(descriptor.operationId === undefined ? {} : { operationId: descriptor.operationId }), ...(descriptor.sessionId === undefined ? {} : { sessionId: descriptor.sessionId }), + ...(descriptor.allowedScopes === undefined ? {} : { allowedScopes: descriptor.allowedScopes }), }); const controller = new AbortController(); + const promptEntry = Object.freeze({ + controller, + pluginId: context.pluginId, + permission: descriptor.permission, + resources: Object.freeze([...resources]), + }); + this.promptControllers.add(promptEntry); + if (descriptor.sessionId) { + const controllers = this.sessionPromptControllers.get(descriptor.sessionId) ?? new Set(); + controllers.add(controller); + this.sessionPromptControllers.set(descriptor.sessionId, controllers); + } const timer = setTimeout(() => controller.abort(permissionDenied( "Plugin permission request timed out", )), this.promptTimeoutMs); @@ -424,8 +483,14 @@ class PluginPermissionEngine { }); } finally { clearTimeout(timer); + this.promptControllers.delete(promptEntry); context.signal?.removeEventListener("abort", onAbort); this.shutdownController.signal.removeEventListener("abort", onShutdown); + if (descriptor.sessionId) { + const controllers = this.sessionPromptControllers.get(descriptor.sessionId); + controllers?.delete(controller); + if (controllers?.size === 0) this.sessionPromptControllers.delete(descriptor.sessionId); + } } if (this.closed) throw permissionDenied("Plugin permission engine is unavailable"); let decision; @@ -448,6 +513,9 @@ class PluginPermissionEngine { const outcome = decision.decision === "deny" ? "denied" : "cancelled"; throw permissionDenied(`Plugin permission was ${outcome}: ${descriptor.permission}`); } + if (descriptor.allowedScopes && !descriptor.allowedScopes.includes(decision.scope)) { + throw permissionDenied(`Plugin permission scope is not supported for this operation: ${decision.scope}`); + } let decisionResources; try { decisionResources = normalizePermissionResources( @@ -487,6 +555,8 @@ class PluginPermissionEngine { if (decision.scope === "session" && !descriptor.sessionId) { throw permissionDenied("Session-scoped plugin permission requires a host-owned session"); } + context.signal?.throwIfAborted(); + descriptor.validateBeforeGrant?.(); for (const { resource, resourceKind } of decisionResourceDescriptors) { const grantKey = this.#grantKey( context.pluginId, @@ -603,6 +673,8 @@ class PluginPermissionEngine { permission, resource: canonicalResource, }); + this.#abortPrompts(pluginId, permission, canonicalResource); + this.#emitRevocation({ pluginId, permission, resource: canonicalResource, scope: "always" }); } revokeApplication(pluginId, permission, resource) { @@ -625,9 +697,21 @@ class PluginPermissionEngine { ...(permission === undefined ? {} : { permission }), ...(canonicalResource === undefined ? {} : { resource: canonicalResource }), }); + this.#abortPrompts(pluginId, permission, canonicalResource); + this.#emitRevocation({ + pluginId, + ...(permission === undefined ? {} : { permission }), + ...(canonicalResource === undefined ? {} : { resource: canonicalResource }), + scope: "application", + }); } revokeSession(sessionId) { + const controllers = this.sessionPromptControllers.get(sessionId); + this.sessionPromptControllers.delete(sessionId); + for (const controller of controllers ?? []) { + controller.abort(permissionDenied("Plugin permission request session ended")); + } for (const key of [...this.sessionGrants.keys()]) { if (key.startsWith(`${sessionId}\0`)) this.sessionGrants.delete(key); } @@ -642,6 +726,8 @@ class PluginPermissionEngine { if (grant.pluginId === pluginId) this.sessionGrants.delete(key); } this.database.recordSecurityAudit(pluginId, "permission.revoked", { scope: "all" }); + this.#abortPrompts(pluginId); + this.#emitRevocation({ pluginId, scope: "all" }); } shutdown() { @@ -650,6 +736,8 @@ class PluginPermissionEngine { this.shutdownController.abort(permissionDenied("Plugin permission engine is unavailable")); this.applicationGrants.clear(); this.sessionGrants.clear(); + this.promptControllers.clear(); + this.revocationListeners.clear(); } } diff --git a/electron/plugins/permissionEngine.test.cjs b/electron/plugins/permissionEngine.test.cjs index eebb6b6f4..f83b280d5 100644 --- a/electron/plugins/permissionEngine.test.cjs +++ b/electron/plugins/permissionEngine.test.cjs @@ -447,6 +447,84 @@ test("session grants require a host-owned session identifier", async (context) = database.close(); }); +test("revoking a session aborts its pending permission prompt before it can grant", async (context) => { + const database = createDatabase(context); + let promptStarted; + const started = new Promise((resolve) => { promptStarted = resolve; }); + const engine = new PluginPermissionEngine({ + database, + requestDecision: (_request, { signal }) => new Promise((_resolve, reject) => { + promptStarted(); + signal.addEventListener("abort", () => reject(signal.reason), { once: true }); + }), + }); + const pluginManifest = manifest({ optional: ["terminal.metadata"] }); + const pending = engine.authorize(runtimeContext(pluginManifest), { + permission: "terminal.metadata", + resources: ["*"], + reason: "Read terminal metadata", + sessionId: "terminal-session-pending", + allowedScopes: ["session"], + }); + await started; + engine.revokeSession("terminal-session-pending"); + await assert.rejects(pending, /session ended/u); + assert.equal(engine.sessionGrants.size, 0); + database.close(); +}); + +test("host state is revalidated before a permission decision can persist", async (context) => { + const database = createDatabase(context); + const engine = new PluginPermissionEngine({ + database, + requestDecision: async (request) => ({ + requestId: request.requestId, + decision: "allow", + scope: "application", + }), + }); + const pluginManifest = manifest({ optional: ["terminal.metadata"] }); + await assert.rejects(engine.authorize(runtimeContext(pluginManifest), { + permission: "terminal.metadata", + resources: ["*"], + reason: "Read terminal metadata", + validateBeforeGrant: () => { throw new Error("runtime changed"); }, + }), /runtime changed/u); + assert.equal(engine.applicationGrants.size, 0); + database.close(); +}); + +test("permission revocation aborts matching prompts and publishes a revocation event", async (context) => { + const database = createDatabase(context); + let started; + const promptStarted = new Promise((resolve) => { started = resolve; }); + const engine = new PluginPermissionEngine({ + database, + requestDecision: (_request, { signal }) => new Promise((_resolve, reject) => { + started(); + signal.addEventListener("abort", () => reject(signal.reason), { once: true }); + }), + }); + const events = []; + engine.onDidRevoke((event) => events.push(event)); + const pluginManifest = manifest({ optional: ["terminal.metadata"] }); + const pending = engine.authorize(runtimeContext(pluginManifest), { + permission: "terminal.metadata", + resources: ["*"], + reason: "Read terminal metadata", + }); + await promptStarted; + engine.revokeApplication(pluginManifest.id, "terminal.metadata", "*"); + await assert.rejects(pending, /revoked/u); + assert.deepEqual(events, [{ + pluginId: pluginManifest.id, + permission: "terminal.metadata", + resource: "*", + scope: "application", + }]); + database.close(); +}); + test("required preflight rejects missing or wildcard resource-scoped activation bounds", async (context) => { const database = createDatabase(context); const requested = []; diff --git a/electron/plugins/pluginBridge.cjs b/electron/plugins/pluginBridge.cjs index 6e556d1f6..57cbe4d80 100644 --- a/electron/plugins/pluginBridge.cjs +++ b/electron/plugins/pluginBridge.cjs @@ -94,6 +94,7 @@ function registerPluginBridge(ipcMain, options) { const manager = options.manager; const contributionService = options.contributionService; const terminalProviderService = options.terminalProviderService; + const terminalDataPipelineService = options.terminalDataPipelineService; const viewHost = options.viewHost; const env = options.env ?? process.env; const isTrustedSender = options.isTrustedSender; @@ -253,9 +254,19 @@ function registerPluginBridge(ipcMain, options) { controller?.abort(); return controller != null; }); - handle(CHANNELS.terminalSessionEvent, async (_activeManager, payload) => { + handle(CHANNELS.terminalSessionEvent, async (_activeManager, payload, event) => { if (!terminalProviderService) throw new Error("Plugin Terminal Providers are unavailable"); - return terminalProviderService.publishSessionEvent(payload); + if (terminalDataPipelineService?.acceptsSessionEvent + && !terminalDataPipelineService.acceptsSessionEvent(payload, event?.sender?.id)) { + return []; + } + const [providers] = await Promise.all([ + terminalProviderService.publishSessionEvent(payload), + terminalDataPipelineService?.handleSessionEvent?.(payload, { + webContentsId: event?.sender?.id, + }) ?? [], + ]); + return providers; }); handle(CHANNELS.openView, async (_activeManager, payload, event) => { if (!viewHost) throw new Error("Plugin views are unavailable"); diff --git a/electron/plugins/pluginBridge.test.cjs b/electron/plugins/pluginBridge.test.cjs index 72e2cba18..02dd6dd00 100644 --- a/electron/plugins/pluginBridge.test.cjs +++ b/electron/plugins/pluginBridge.test.cjs @@ -198,6 +198,7 @@ test("plugin setting scope catalogs are bounded, sender-owned, and merged for se test("plugin terminal Provider bridge owns cancellation by renderer sender", async () => { const ipcMain = createIpcMain(); const calls = []; + const pipelineCalls = []; let destroyed; const terminalProviderService = { listProviders(options) { @@ -218,6 +219,12 @@ test("plugin terminal Provider bridge owns cancellation by renderer sender", asy registerPluginBridge(ipcMain, { manager: { initialize: async () => {} }, terminalProviderService, + terminalDataPipelineService: { + async handleSessionEvent(payload, options) { + pipelineCalls.push([payload, options]); + return [{ direction: "input", attached: true }]; + }, + }, env: { NETCATTY_PLUGIN_DEV: "1" }, isTrustedSender: () => true, }); @@ -249,6 +256,10 @@ test("plugin terminal Provider bridge owns cancellation by renderer sender", asy type: "created", session: { sessionId: "session-1" }, }), [{ pluginId: "com.example", delivered: true }]); + assert.deepEqual(pipelineCalls, [[ + { type: "created", session: { sessionId: "session-1" } }, + { webContentsId: 42 }, + ]]); assert.equal(typeof destroyed, "function"); const destroyedPending = ipcMain.handlers.get(CHANNELS.terminalProvide)(event, { requestId: "renderer-request-destroyed", diff --git a/electron/plugins/rpcRouter.cjs b/electron/plugins/rpcRouter.cjs index d7500891d..0f66362d7 100644 --- a/electron/plugins/rpcRouter.cjs +++ b/electron/plugins/rpcRouter.cjs @@ -106,9 +106,12 @@ class PluginRpcRouter { this.streamChains = new Map(); } - #sendRpc(message) { + #sendRpc(message, transfer = []) { assertRpcMessage(message); - this.send(message); + if (!Array.isArray(transfer)) { + throw new TypeError("Plugin RPC transfer list must be an array"); + } + this.send(message, transfer); } #sendFailure(id, error) { @@ -343,6 +346,9 @@ class PluginRpcRouter { if (options.validateResult != null && typeof options.validateResult !== "function") { return Promise.reject(new TypeError("Plugin RPC result validator must be a function")); } + if (options.transfer != null && !Array.isArray(options.transfer)) { + return Promise.reject(new TypeError("Plugin RPC transfer list must be an array")); + } const message = { jsonrpc: "2.0", id, @@ -392,7 +398,7 @@ class PluginRpcRouter { this.pending.set(rpcIdKey(id), pending); this.pendingCancellationIds.add(cancellationId); try { - this.#sendRpc(message); + this.#sendRpc(message, options.transfer ?? []); } catch (error) { this.#forgetPending(id, pending); reject(error); diff --git a/electron/plugins/rpcRouter.test.cjs b/electron/plugins/rpcRouter.test.cjs index 10c2faad9..5f278f749 100644 --- a/electron/plugins/rpcRouter.test.cjs +++ b/electron/plugins/rpcRouter.test.cjs @@ -8,12 +8,14 @@ const { PLUGIN_RPC_MAX_JSON_BYTES } = require("./constants.cjs"); function createRouter(options = {}) { const sent = []; + const transfers = []; const protocolErrors = []; const router = new PluginRpcRouter({ pluginId: "com.example.test", - send(message) { - options.send?.(message); + send(message, transfer = []) { + options.send?.(message, transfer); sent.push(message); + transfers.push(transfer); }, handlers: options.handlers, requestHandlers: options.requestHandlers, @@ -24,7 +26,7 @@ function createRouter(options = {}) { onIncomingStream: options.onIncomingStream, onProtocolError(error) { protocolErrors.push(error); }, }); - return { router, sent, protocolErrors }; + return { router, sent, transfers, protocolErrors }; } test("raw message guards run before schema work and can contain every transport message class", async () => { @@ -372,6 +374,35 @@ test("outgoing requests validate method-specific plugin results before resolving ); }); +test("outgoing requests keep transferable setup under router correlation and validation", async () => { + const fixture = createRouter(); + const port = { postMessage() {} }; + const response = fixture.router.request("plugin.terminal.interceptor.attach", { + descriptor: { + providerId: "com.example.input", + direction: "input", + session: { sessionId: "session-1", protocol: "ssh", status: "connected" }, + }, + }, { + transfer: [port], + validateResult(result) { + if (result?.accepted !== true) throw new TypeError("Invalid attachment result"); + return undefined; + }, + }); + assert.deepEqual(fixture.transfers[0], [port]); + await fixture.router.accept({ + jsonrpc: "2.0", + id: fixture.sent[0].id, + result: { accepted: true }, + }); + assert.equal(await response, undefined); + await assert.rejects( + fixture.router.request("plugin.terminal.interceptor.attach", {}, { transfer: port }), + /transfer list must be an array/, + ); +}); + test("malformed RPC closes the peer instead of accepting a near-match", async () => { const fixture = createRouter(); await fixture.router.accept({ jsonrpc: "2.0", id: -1, method: "plugin.activate" }); diff --git a/electron/plugins/runtime/runtimePeer.mjs b/electron/plugins/runtime/runtimePeer.mjs index cdc5728c4..273e95f21 100644 --- a/electron/plugins/runtime/runtimePeer.mjs +++ b/electron/plugins/runtime/runtimePeer.mjs @@ -7,6 +7,14 @@ import { } from "@netcatty/plugin-sdk"; import { createMessagePortStreamEnvelope } from "@netcatty/plugin-contract"; +let terminalInterceptorTransportPromise; + +function loadTerminalInterceptorTransport() { + terminalInterceptorTransportPromise ??= import("../terminalInterceptorTransport.cjs") + .then((module) => module.default); + return terminalInterceptorTransportPromise; +} + const RPC_ERRORS = { methodNotFound: -32601, invalidParams: -32602, @@ -59,11 +67,15 @@ function messageData(value) { return value && typeof value === "object" && "data" in value ? value.data : value; } +function closeTransferredPorts(ports) { + for (const port of ports ?? []) port?.close?.(); +} + function createTransportAdapter(port) { const listeners = new Set(); const handle = (event) => { const value = messageData(event); - for (const listener of listeners) listener(value); + for (const listener of listeners) listener(value, event?.ports ?? []); }; if (typeof port.addEventListener === "function") port.addEventListener("message", handle); else port.on("message", handle); @@ -469,7 +481,12 @@ function createPluginContext(config, client, runtimeApi) { }; } -export async function startPluginRuntime({ port, config, loadPlugin }) { +export async function startPluginRuntime({ + port, + config, + loadPlugin, + loadTerminalInterceptorTransport: loadTerminalInterceptorTransportForRuntime = loadTerminalInterceptorTransport, +}) { const transport = createTransportAdapter(port); const client = createHostClient(transport); const cancellation = new Map(); @@ -485,6 +502,7 @@ export async function startPluginRuntime({ port, config, loadPlugin }) { terminalEvents: createEmitter(), environment: normalizeRuntimeEnvironment(config.environment), viewMessages: new Map(), + terminalInterceptorPorts: new Set(), }; const pluginModule = await loadPlugin(config.entryUrl); plugin = pluginModule?.default; @@ -492,7 +510,9 @@ export async function startPluginRuntime({ port, config, loadPlugin }) { throw new Error("Plugin entrypoint must default-export a plugin with activate(context)"); } - async function handleRequest(message, cancellationToken) { + async function handleRequest(message, cancellationToken, ports = []) { + const isTerminalAttachment = message.method === "plugin.terminal.interceptor.attach"; + if (!isTerminalAttachment) closeTransferredPorts(ports); if (message.method === "plugin.initialize") { if (context) throw new PluginError("failed_precondition", "Plugin is already initialized"); context = createPluginContext(config, client, runtimeApi); @@ -524,6 +544,19 @@ export async function startPluginRuntime({ port, config, loadPlugin }) { } return null; } + if (message.method === "plugin.terminal.interceptor.attach") { + if (ports.length !== 1) { + closeTransferredPorts(ports); + throw new PluginError("invalid_argument", "Terminal interceptor attachment requires exactly one port"); + } + try { + await attachTerminalInterceptor(message.params, ports, cancellationToken); + return { accepted: true }; + } catch (error) { + closeTransferredPorts(ports); + throw error; + } + } if (message.method === "plugin.command.execute") { if (!activated || !context) throw new PluginError("failed_precondition", "Plugin is not activated"); const command = assertOwnedContributionId(config.pluginId, message.params?.command, "Plugin command"); @@ -607,26 +640,142 @@ export async function startPluginRuntime({ port, config, loadPlugin }) { return false; } - const dispose = transport.onMessage((message) => { + const attachTerminalInterceptor = async (message, ports, cancellationToken) => { + const descriptor = message?.descriptor; + const providerId = assertOwnedContributionId(config.pluginId, descriptor?.providerId, "Terminal interceptor"); + const direction = descriptor?.direction; + const kind = direction === "input" ? "terminal.interceptor.input" + : direction === "output" ? "terminal.interceptor.output" : null; + const sessionId = descriptor?.session?.sessionId; + if (!kind || typeof sessionId !== "string" || sessionId.length < 1 || sessionId.length > 256) { + throw new PluginError("invalid_argument", "Terminal interceptor descriptor is invalid"); + } + const registration = runtimeApi.providerHandlers.get(providerId); + const interceptorPort = ports?.[0]; + if (!activated || registration?.kind !== kind || !interceptorPort?.postMessage) { + interceptorPort?.close?.(); + throw new PluginError("failed_precondition", "Terminal interceptor provider is not registered"); + } + runtimeApi.terminalInterceptorPorts.add(interceptorPort); + let attached = false; + try { + const { + TERMINAL_INTERCEPTOR_MAX_CHUNK_BYTES, + createTerminalInterceptorEnvelope, + } = await loadTerminalInterceptorTransportForRuntime(); + if (cancellationToken?.isCancellationRequested + || deactivated + || !activated + || !runtimeApi.terminalInterceptorPorts.has(interceptorPort) + || runtimeApi.providerHandlers.get(providerId) !== registration) { + throw new PluginError("failed_precondition", "Terminal interceptor attachment was cancelled or became stale"); + } + const handleChunk = (event) => { + let envelope; + try { + const message = messageData(event); + envelope = createTerminalInterceptorEnvelope(message?.frame, message?.transfer); + } catch { + interceptorPort.close?.(); + return; + } + const chunk = envelope.frame; + if (chunk?.type === "netcatty:terminal-interceptor:ready") return; + if (chunk.type !== "netcatty:terminal-interceptor:chunk" + || chunk.direction !== direction) { + interceptorPort.close?.(); + return; + } + const invocation = Object.freeze({ + providerId, + kind, + direction, + sequence: chunk.sequence, + session: freezeRuntimeJson(descriptor.session), + data: new Uint8Array(envelope.transfer), + }); + // Resolve the registration for every chunk so disposal/re-registration + // cannot keep a captured stale handler alive. Starting from a resolved + // promise also converts synchronous handler throws into the ordinary + // failed response path instead of tearing down the utility runtime. + void Promise.resolve().then(() => { + const currentRegistration = runtimeApi.providerHandlers.get(providerId); + if (currentRegistration?.kind !== kind) { + throw new PluginError("failed_precondition", "Terminal interceptor provider is no longer registered"); + } + return currentRegistration.handler(invocation); + }).then( + (result) => { + let bytes; + if (result instanceof Uint8Array) bytes = result; + else if (result instanceof ArrayBuffer) bytes = new Uint8Array(result); + else throw new PluginError("data_loss", "Terminal interceptor must return Uint8Array or ArrayBuffer"); + if (bytes.byteLength > TERMINAL_INTERCEPTOR_MAX_CHUNK_BYTES) { + throw new PluginError("resource_exhausted", "Terminal interceptor result is too large"); + } + const copy = new Uint8Array(bytes.byteLength); + copy.set(bytes); + const resultEnvelope = createTerminalInterceptorEnvelope({ + type: "netcatty:terminal-interceptor:result", + sequence: chunk.sequence, + status: "ok", + creditBytes: chunk.byteLength, + byteLength: copy.byteLength, + }, copy.buffer); + interceptorPort.postMessage(resultEnvelope, [copy.buffer]); + }, + () => interceptorPort.postMessage(createTerminalInterceptorEnvelope({ + type: "netcatty:terminal-interceptor:result", + sequence: chunk.sequence, + status: "failed", + })), + ).catch(() => interceptorPort.close?.()); + }; + if (typeof interceptorPort.addEventListener === "function") { + interceptorPort.addEventListener("message", handleChunk); + } else { + interceptorPort.on("message", handleChunk); + } + interceptorPort.start?.(); + interceptorPort.on?.("close", () => runtimeApi.terminalInterceptorPorts.delete(interceptorPort)); + attached = true; + } finally { + if (!attached) { + runtimeApi.terminalInterceptorPorts.delete(interceptorPort); + interceptorPort.close?.(); + } + } + }; + + const dispose = transport.onMessage((message, ports) => { if (message && typeof message === "object" && Object.hasOwn(message, "frame")) { + for (const port of ports) port?.close?.(); try { cancelUnhandledStream(transport, message); } catch { transport.close(); } return; } - if (client.accept(message)) return; - if (!message || message.jsonrpc !== "2.0") return; + if (client.accept(message)) { + for (const port of ports) port?.close?.(); + return; + } + if (!message || message.jsonrpc !== "2.0") { + for (const port of ports) port?.close?.(); + return; + } if (message.method === "$/cancelRequest") { + for (const port of ports) port?.close?.(); cancellation.get(message.params?.cancellationId)?.cancel(); return; } if (!Object.hasOwn(message, "id")) { + for (const port of ports) port?.close?.(); try { handleNotification(message); } catch { transport.close(); } return; } const cancellationId = message.cancellationId; const source = new CancellationTokenSource(); if (cancellationId) cancellation.set(cancellationId, source); - void handleRequest(message, source.token).then( + void handleRequest(message, source.token, ports).then( (result) => transport.post({ jsonrpc: "2.0", id: message.id, @@ -652,6 +801,8 @@ export async function startPluginRuntime({ port, config, loadPlugin }) { runtimeApi.settingsChanged.clear(); runtimeApi.environmentChanged.clear(); runtimeApi.terminalEvents.clear(); + for (const interceptorPort of runtimeApi.terminalInterceptorPorts) interceptorPort.close?.(); + runtimeApi.terminalInterceptorPorts.clear(); for (const emitter of runtimeApi.viewMessages.values()) emitter.clear(); cancellation.clear(); if (!deactivated) { diff --git a/electron/plugins/runtime/runtimePeer.terminalInterceptor.test.cjs b/electron/plugins/runtime/runtimePeer.terminalInterceptor.test.cjs new file mode 100644 index 000000000..d7c53c31c --- /dev/null +++ b/electron/plugins/runtime/runtimePeer.terminalInterceptor.test.cjs @@ -0,0 +1,476 @@ +"use strict"; + +const assert = require("node:assert/strict"); +const test = require("node:test"); +const { + createTerminalInterceptorEnvelope, +} = require("../terminalInterceptorTransport.cjs"); + +class FakePort { + constructor() { + this.listeners = new Set(); + this.messages = []; + this.closed = false; + } + + addEventListener(type, listener) { + if (type === "message") this.listeners.add(listener); + } + + removeEventListener(type, listener) { + if (type === "message") this.listeners.delete(listener); + } + + postMessage(message, transfer = []) { + this.messages.push({ message, transfer }); + } + + start() {} + + close() { this.closed = true; } + + emit(data, ports = []) { + for (const listener of this.listeners) listener({ data, ports }); + } +} + +async function tick() { + await new Promise((resolve) => setImmediate(resolve)); +} + +test("utility runtime dispatches dedicated terminal ports to the exact registered interceptor", async () => { + const { startPluginRuntime } = await import("./runtimePeer.mjs"); + const control = new FakePort(); + const runtime = await startPluginRuntime({ + port: control, + config: { + pluginId: "com.example", + pluginVersion: "1.0.0", + netcattyVersion: "1.0.0", + apiVersion: "1.0.0", + enabledFeatures: [], + environment: {}, + entryUrl: "file:///plugin.js", + }, + loadPlugin: async () => ({ + default: { + activate(context) { + context.providers.register( + "com.example.input", + "terminal.interceptor.input", + ({ data }) => Uint8Array.from([...data].map((byte) => byte >= 97 && byte <= 122 ? byte - 32 : byte)), + ); + }, + }, + }), + }); + control.emit({ jsonrpc: "2.0", id: 1, method: "plugin.initialize", params: {} }); + await tick(); + control.emit({ jsonrpc: "2.0", id: 2, method: "plugin.activate", params: {} }); + await tick(); + + const dataPort = new FakePort(); + control.emit({ + jsonrpc: "2.0", + id: 3, + method: "plugin.terminal.interceptor.attach", + params: { + descriptor: { + providerId: "com.example.input", + direction: "input", + session: { sessionId: "session-1", protocol: "ssh", status: "connected" }, + }, + }, + }, [dataPort]); + await tick(); + assert.equal( + control.messages.some(({ message }) => ( + message.jsonrpc === "2.0" + && message.id === 3 + && message.result?.accepted === true + )), + true, + ); + dataPort.emit(createTerminalInterceptorEnvelope({ + type: "netcatty:terminal-interceptor:ready", + sessionId: "session-1", + direction: "input", + windowBytes: 64 * 1024, + })); + assert.equal(dataPort.closed, false); + const data = Uint8Array.from(Buffer.from("hello")).buffer; + dataPort.emit(createTerminalInterceptorEnvelope({ + type: "netcatty:terminal-interceptor:chunk", + sequence: 1, + direction: "input", + creditBytes: 64 * 1024, + byteLength: data.byteLength, + }, data)); + await tick(); + assert.equal(dataPort.messages.length, 1); + const result = createTerminalInterceptorEnvelope( + dataPort.messages[0].message.frame, + dataPort.messages[0].message.transfer, + ); + assert.equal(result.frame.status, "ok"); + assert.equal(result.frame.creditBytes, 5); + assert.equal(Buffer.from(result.transfer).toString("utf8"), "HELLO"); + assert.deepEqual(dataPort.messages[0].transfer, [result.transfer]); + await runtime.dispose(); +}); + +test("utility runtime closes a terminal port when provider ownership or kind is invalid", async () => { + const { startPluginRuntime } = await import("./runtimePeer.mjs"); + const control = new FakePort(); + const runtime = await startPluginRuntime({ + port: control, + config: { + pluginId: "com.example", + pluginVersion: "1.0.0", + netcattyVersion: "1.0.0", + apiVersion: "1.0.0", + enabledFeatures: [], + environment: {}, + entryUrl: "file:///plugin.js", + }, + loadPlugin: async () => ({ default: { activate() {} } }), + }); + control.emit({ jsonrpc: "2.0", id: 1, method: "plugin.initialize", params: {} }); + await tick(); + control.emit({ jsonrpc: "2.0", id: 2, method: "plugin.activate", params: {} }); + await tick(); + const dataPort = new FakePort(); + control.emit({ + jsonrpc: "2.0", + id: 3, + method: "plugin.terminal.interceptor.attach", + params: { + descriptor: { + providerId: "com.example.missing", + direction: "input", + session: { sessionId: "session-1" }, + }, + }, + }, [dataPort]); + await tick(); + assert.equal(dataPort.closed, true); + assert.equal( + control.messages.some(({ message }) => ( + message.jsonrpc === "2.0" + && message.id === 3 + && message.error?.code === -32009 + )), + true, + ); + await runtime.dispose(); +}); + +test("utility runtime closes the transferred terminal port when the provider belongs to another plugin", async () => { + const { startPluginRuntime } = await import("./runtimePeer.mjs"); + const control = new FakePort(); + const runtime = await startPluginRuntime({ + port: control, + config: { + pluginId: "com.example", + pluginVersion: "1.0.0", + netcattyVersion: "1.0.0", + apiVersion: "1.0.0", + enabledFeatures: [], + environment: {}, + entryUrl: "file:///plugin.js", + }, + loadPlugin: async () => ({ default: { activate() {} } }), + }); + control.emit({ jsonrpc: "2.0", id: 1, method: "plugin.initialize", params: {} }); + await tick(); + control.emit({ jsonrpc: "2.0", id: 2, method: "plugin.activate", params: {} }); + await tick(); + const dataPort = new FakePort(); + control.emit({ + jsonrpc: "2.0", + id: 3, + method: "plugin.terminal.interceptor.attach", + params: { + descriptor: { + providerId: "other.plugin.input", + direction: "input", + session: { sessionId: "session-1", protocol: "ssh", status: "connected" }, + }, + }, + }, [dataPort]); + await tick(); + assert.equal(dataPort.closed, true); + assert.equal( + control.messages.some(({ message }) => ( + message.jsonrpc === "2.0" + && message.id === 3 + && message.error?.code === -32003 + )), + true, + ); + await runtime.dispose(); +}); + +test("utility runtime closes unexpected transferred ports on every lifecycle request", async () => { + const { startPluginRuntime } = await import("./runtimePeer.mjs"); + const control = new FakePort(); + const runtime = await startPluginRuntime({ + port: control, + config: { + pluginId: "com.example", + pluginVersion: "1.0.0", + netcattyVersion: "1.0.0", + apiVersion: "1.0.0", + enabledFeatures: [], + environment: {}, + entryUrl: "file:///plugin.js", + }, + loadPlugin: async () => ({ default: { activate() {} } }), + }); + const lifecycleRequests = [ + { id: 1, method: "plugin.initialize", params: {} }, + { id: 2, method: "plugin.activate", params: {} }, + { id: 3, method: "plugin.deactivate", params: {} }, + ]; + for (const request of lifecycleRequests) { + const unexpectedPort = new FakePort(); + control.emit({ jsonrpc: "2.0", ...request }, [unexpectedPort]); + await tick(); + assert.equal(unexpectedPort.closed, true, `${request.method} retained an unexpected port`); + assert.equal( + control.messages.some(({ message }) => ( + message.jsonrpc === "2.0" + && message.id === request.id + && Object.hasOwn(message, "result") + )), + true, + `${request.method} did not complete after closing its unexpected port`, + ); + } + await runtime.dispose(); +}); + +test("utility runtime rejects the retired private terminal attachment protocol", async () => { + const { startPluginRuntime } = await import("./runtimePeer.mjs"); + const control = new FakePort(); + const runtime = await startPluginRuntime({ + port: control, + config: { + pluginId: "com.example", + pluginVersion: "1.0.0", + netcattyVersion: "1.0.0", + apiVersion: "1.0.0", + enabledFeatures: [], + environment: {}, + entryUrl: "file:///plugin.js", + }, + loadPlugin: async () => ({ default: { activate() {} } }), + }); + const dataPort = new FakePort(); + control.emit({ + type: "netcatty-plugin:terminal-interceptor:attach", + attachmentId: 1, + descriptor: { providerId: "com.example.input", direction: "input" }, + }, [dataPort]); + assert.equal(dataPort.closed, true); + assert.equal(control.messages.length, 0); + await runtime.dispose(); +}); + +test("terminal ports convert synchronous throws to failures and stop using disposed handlers", async () => { + const { startPluginRuntime } = await import("./runtimePeer.mjs"); + const control = new FakePort(); + let registration; + let calls = 0; + const runtime = await startPluginRuntime({ + port: control, + config: { + pluginId: "com.example", + pluginVersion: "1.0.0", + netcattyVersion: "1.0.0", + apiVersion: "1.0.0", + enabledFeatures: [], + environment: {}, + entryUrl: "file:///plugin.js", + }, + loadPlugin: async () => ({ + default: { + activate(context) { + registration = context.providers.register( + "com.example.input", + "terminal.interceptor.input", + () => { + calls += 1; + throw new Error("synchronous failure"); + }, + ); + }, + }, + }), + }); + control.emit({ jsonrpc: "2.0", id: 1, method: "plugin.initialize", params: {} }); + await tick(); + control.emit({ jsonrpc: "2.0", id: 2, method: "plugin.activate", params: {} }); + await tick(); + + const dataPort = new FakePort(); + control.emit({ + jsonrpc: "2.0", + id: 3, + method: "plugin.terminal.interceptor.attach", + params: { + descriptor: { + providerId: "com.example.input", + direction: "input", + session: { sessionId: "session-1", protocol: "ssh", status: "connected" }, + }, + }, + }, [dataPort]); + await tick(); + const send = (sequence) => { + const data = Uint8Array.from([sequence]).buffer; + dataPort.emit(createTerminalInterceptorEnvelope({ + type: "netcatty:terminal-interceptor:chunk", + sequence, + direction: "input", + creditBytes: 64 * 1024, + byteLength: data.byteLength, + }, data)); + }; + send(1); + await tick(); + assert.equal(dataPort.messages[0].message.frame.status, "failed"); + assert.equal(calls, 1); + + registration.dispose(); + send(2); + await tick(); + assert.equal(dataPort.messages[1].message.frame.status, "failed"); + assert.equal(calls, 1); + await runtime.dispose(); +}); + +test("the utility peer closes a port whose chunk bypasses the canonical terminal frame schema", async () => { + const { startPluginRuntime } = await import("./runtimePeer.mjs"); + const control = new FakePort(); + const runtime = await startPluginRuntime({ + port: control, + config: { + pluginId: "com.example", + pluginVersion: "1.0.0", + netcattyVersion: "1.0.0", + apiVersion: "1.0.0", + enabledFeatures: [], + environment: {}, + entryUrl: "file:///plugin.js", + }, + loadPlugin: async () => ({ + default: { + activate(context) { + context.providers.register( + "com.example.input", + "terminal.interceptor.input", + ({ data }) => data, + ); + }, + }, + }), + }); + control.emit({ jsonrpc: "2.0", id: 1, method: "plugin.initialize", params: {} }); + await tick(); + control.emit({ jsonrpc: "2.0", id: 2, method: "plugin.activate", params: {} }); + await tick(); + const dataPort = new FakePort(); + control.emit({ + jsonrpc: "2.0", + id: 3, + method: "plugin.terminal.interceptor.attach", + params: { + descriptor: { + providerId: "com.example.input", + direction: "input", + session: { sessionId: "session-1", protocol: "ssh", status: "connected" }, + }, + }, + }, [dataPort]); + await tick(); + const data = Uint8Array.from(Buffer.from("unsafe")).buffer; + dataPort.emit({ + frame: { + type: "netcatty:terminal-interceptor:chunk", + sequence: 1, + direction: "input", + creditBytes: 64 * 1024, + byteLength: data.byteLength, + extra: true, + }, + transfer: data, + }); + assert.equal(dataPort.closed, true); + assert.equal(dataPort.messages.length, 0); + await runtime.dispose(); +}); + +test("utility runtime disposal closes a terminal port while its transport helper is loading", async () => { + const { startPluginRuntime } = await import("./runtimePeer.mjs"); + const control = new FakePort(); + let resolveTransport; + const transportLoading = new Promise((resolve) => { resolveTransport = resolve; }); + const runtime = await startPluginRuntime({ + port: control, + config: { + pluginId: "com.example", + pluginVersion: "1.0.0", + netcattyVersion: "1.0.0", + apiVersion: "1.0.0", + enabledFeatures: [], + environment: {}, + entryUrl: "file:///plugin.js", + }, + loadPlugin: async () => ({ + default: { + activate(context) { + context.providers.register( + "com.example.input", + "terminal.interceptor.input", + ({ data }) => data, + ); + }, + }, + }), + loadTerminalInterceptorTransport: () => transportLoading, + }); + control.emit({ jsonrpc: "2.0", id: 1, method: "plugin.initialize", params: {} }); + await tick(); + control.emit({ jsonrpc: "2.0", id: 2, method: "plugin.activate", params: {} }); + await tick(); + + const dataPort = new FakePort(); + control.emit({ + jsonrpc: "2.0", + id: 3, + method: "plugin.terminal.interceptor.attach", + params: { + descriptor: { + providerId: "com.example.input", + direction: "input", + session: { sessionId: "session-1", protocol: "ssh", status: "connected" }, + }, + }, + }, [dataPort]); + await tick(); + assert.equal(dataPort.closed, false); + + await runtime.dispose(); + assert.equal(dataPort.closed, true); + resolveTransport({ + TERMINAL_INTERCEPTOR_MAX_CHUNK_BYTES: 64 * 1024, + createTerminalInterceptorEnvelope, + }); + await tick(); + assert.equal( + control.messages.some(({ message }) => message.id === 3 && message.result?.accepted === true), + false, + ); + assert.equal(dataPort.closed, true); +}); diff --git a/electron/plugins/runtimeSupervisor.cjs b/electron/plugins/runtimeSupervisor.cjs index aa27efed1..9a83a7015 100644 --- a/electron/plugins/runtimeSupervisor.cjs +++ b/electron/plugins/runtimeSupervisor.cjs @@ -43,7 +43,13 @@ function freezeJson(value) { } function resolveDefaultRuntimeKind({ plugin }) { - if (plugin.manifest.companionExecutables?.length) return "utility"; + const requiresPrivilegedTerminalPipeline = plugin.manifest.contributes?.providers?.some((provider) => ( + provider.kind === "terminal.interceptor.input" + || provider.kind === "terminal.interceptor.output" + )); + if (plugin.manifest.companionExecutables?.length || requiresPrivilegedTerminalPipeline) { + return "utility"; + } return plugin.manifest.main.browser ? "browser" : "utility"; } @@ -662,6 +668,18 @@ class RuntimeSupervisor { } } + async attachTerminalInterceptor(pluginId, descriptor, port, options) { + const { identity, runtime } = await this.#getRunningRuntime(pluginId); + this.#assertExpectedRuntimeIdentity(identity, options?.expectedIdentity); + if (identity.runtimeKind !== "utility" || typeof runtime.attachTerminalInterceptor !== "function") { + throw new PluginRpcError( + RPC_ERRORS.failedPrecondition, + `Terminal interceptors require an advanced utility runtime: ${pluginId}`, + ); + } + await runtime.attachTerminalInterceptor(descriptor, port); + } + shutdown() { this.shutdownPromise ??= this.#shutdown(); return this.shutdownPromise; diff --git a/electron/plugins/runtimeSupervisor.test.cjs b/electron/plugins/runtimeSupervisor.test.cjs index 6addd47fa..df33b9284 100644 --- a/electron/plugins/runtimeSupervisor.test.cjs +++ b/electron/plugins/runtimeSupervisor.test.cjs @@ -425,6 +425,53 @@ test("runtime placement and state events are injectable without changing lifecyc assert.equal(events[0].runtimeId, events[2].runtimeId); }); +test("supervisor transfers privileged terminal ports only to the exact utility runtime identity", async (context) => { + const attached = []; + let releaseAttachment; + const fixture = createFixture(context, () => ({ + async start(config) { + return { + pluginId: config.pluginId, + pluginVersion: config.pluginVersion, + apiVersion: config.apiVersion, + enabledFeatures: config.enabledFeatures, + }; + }, + async stop() {}, + attachTerminalInterceptor(descriptor, port) { + attached.push({ descriptor, port }); + return new Promise((resolve) => { releaseAttachment = resolve; }); + }, + }), { + resolveRuntimeKind: () => "utility", + }); + await fixture.supervisor.start(fixture.manifest.id); + const identity = fixture.supervisor.getRuntimeIdentity(fixture.manifest.id); + const port = { close() {} }; + let attachmentFinished = false; + const attachment = fixture.supervisor.attachTerminalInterceptor( + fixture.manifest.id, + { providerId: "com.example.input", direction: "input" }, + port, + { expectedIdentity: identity }, + ).then(() => { attachmentFinished = true; }); + await new Promise((resolve) => setImmediate(resolve)); + assert.equal(attached[0].port, port); + assert.equal(attachmentFinished, false); + releaseAttachment(); + await attachment; + assert.equal(attachmentFinished, true); + await assert.rejects( + fixture.supervisor.attachTerminalInterceptor( + fixture.manifest.id, + { providerId: "com.example.input", direction: "input" }, + port, + { expectedIdentity: { ...identity, runtimeId: "stale-runtime" } }, + ), + (error) => error?.code === RPC_ERRORS.unavailable, + ); +}); + test("progress events carry immutable activation identity for downstream provider correlation", async (context) => { let runtimeOptions; const fixture = createFixture(context, (options) => { diff --git a/electron/plugins/terminalDataPipelineService.cjs b/electron/plugins/terminalDataPipelineService.cjs new file mode 100644 index 000000000..119e12e8d --- /dev/null +++ b/electron/plugins/terminalDataPipelineService.cjs @@ -0,0 +1,729 @@ +"use strict"; + +const { PluginRpcError, RPC_ERRORS } = require("./rpcRouter.cjs"); +const { normalizeTerminalSessionSnapshot } = require("./terminalProviderService.cjs"); + +const DIRECTIONS = Object.freeze(["input", "output"]); + +function runtimeIdentityMatches(left, right) { + return left?.pluginId === right?.pluginId + && left?.pluginVersion === right?.pluginVersion + && left?.runtimeId === right?.runtimeId + && left?.runtimeKind === right?.runtimeKind + && left?.securityPrincipal === right?.securityPrincipal; +} + +function normalizeActivationIdentity(activation) { + const identity = activation?.identity; + if (!identity + || identity.pluginId !== activation?.plugin?.id + || identity.pluginVersion !== activation?.plugin?.activeVersion + || typeof identity.runtimeId !== "string" || identity.runtimeId.length < 1 + || identity.runtimeKind !== "utility" + || typeof identity.securityPrincipal !== "string" || identity.securityPrincipal.length < 1) { + throw new PluginRpcError( + RPC_ERRORS.unavailable, + "Terminal interceptor activation identity is unavailable, stale, or not an advanced utility runtime", + ); + } + return Object.freeze({ + pluginId: identity.pluginId, + pluginVersion: identity.pluginVersion, + runtimeId: identity.runtimeId, + runtimeKind: identity.runtimeKind, + securityPrincipal: identity.securityPrincipal, + }); +} + +function terminalSessionSnapshotsEqual(left, right) { + return left?.sessionId === right?.sessionId + && left?.hostId === right?.hostId + && left?.workspaceId === right?.workspaceId + && left?.protocol === right?.protocol + && left?.status === right?.status + && left?.cwd === right?.cwd + && left?.title === right?.title + && left?.shellType === right?.shellType + && left?.cols === right?.cols + && left?.rows === right?.rows + && left?.alternateScreen === right?.alternateScreen; +} + +class PluginTerminalDataPipelineService { + constructor(options) { + if (!options?.contributionService || !options?.permissionEngine + || !options?.runtimeSupervisor || !options?.MessageChannelMain) { + throw new TypeError("Terminal data pipeline requires contribution, permission, runtime, and MessagePort services"); + } + this.contributionService = options.contributionService; + this.permissionEngine = options.permissionEngine; + this.runtimeSupervisor = options.runtimeSupervisor; + this.MessageChannelMain = options.MessageChannelMain; + this.requestSelection = options.requestSelection ?? (async () => null); + this.showWarning = options.showWarning ?? (() => {}); + this.terminalWorkerManager = null; + this.workerWarningSubscription = null; + this.sessionOwnedSubscription = null; + this.sessionClosedSubscription = null; + this.active = new Map(); + this.declined = new Set(); + this.quarantined = new Set(); + this.selectedProviders = new Map(); + this.operations = new Map(); + this.pendingActivations = new Map(); + this.failedActivations = new Map(); + this.finalizedActivations = new WeakSet(); + this.permissionGenerations = new Map(); + this.sessionEpochs = new Map(); + this.pendingOwnership = new Map(); + this.closed = false; + this.permissionRevocationSubscription = this.permissionEngine.onDidRevoke?.((event) => { + const pluginId = event?.pluginId; + if (typeof pluginId !== "string") return; + this.permissionGenerations.set(pluginId, (this.permissionGenerations.get(pluginId) ?? 0) + 1); + const affectedDirections = event.permission === "terminal.intercept.input" + ? new Set(["input"]) + : event.permission === "terminal.intercept.output" + ? new Set(["output"]) + : event.permission === undefined || event.permission === "provider.terminal" + ? new Set(DIRECTIONS) + : new Set(); + if (affectedDirections.size === 0) return; + for (const [key, binding] of [...this.active]) { + if (binding.identity.pluginId === pluginId && affectedDirections.has(binding.direction)) { + this.#detachKey(key, "permission-revoked"); + } + } + for (const [key, selection] of [...this.selectedProviders]) { + const direction = key.slice(key.lastIndexOf("\0") + 1); + if (selection.pluginId === pluginId && affectedDirections.has(direction)) { + this.selectedProviders.delete(key); + } + } + }) ?? null; + this.runtimeSupervisor.onDidChangeRuntime?.((event) => { + if (event.status === "running") return; + const failed = event.status === "error" || event.status === "quarantined"; + const warnedKeys = new Set(); + for (const [key, selection] of this.selectedProviders) { + if (selection.pluginId === event.pluginId) { + this.selectedProviders.delete(key); + } + } + for (const [key, binding] of this.active) { + if (binding.identity.pluginId === event.pluginId + && (event.runtimeId == null || binding.identity.runtimeId === event.runtimeId)) { + if (failed) { + this.declined.add(key); + this.quarantined.add(key); + this.showWarning(Object.freeze({ + sessionId: binding.sessionId, + direction: binding.direction, + providerId: binding.providerId, + code: `runtime-${event.status}`, + message: event.error + ?? `Terminal interceptor runtime ${event.status}`, + })); + warnedKeys.add(key); + } + this.#detachKey(key, failed ? `runtime-${event.status}` : "runtime-stopped"); + } + } + for (const [key, pending] of [ + ...this.pendingActivations, + ...this.failedActivations, + ]) { + if ((this.sessionEpochs.get(pending.sessionId) ?? 0) !== pending.sessionEpoch) { + if (this.failedActivations.get(key) === pending) this.failedActivations.delete(key); + continue; + } + if (pending.identity.pluginId !== event.pluginId + || (event.runtimeId != null + && pending.identity.runtimeId != null + && pending.identity.runtimeId !== event.runtimeId)) { + continue; + } + this.finalizedActivations.add(pending); + this.selectedProviders.delete(key); + if (!failed) continue; + this.declined.add(key); + this.quarantined.add(key); + if (!warnedKeys.has(key)) { + this.showWarning(Object.freeze({ + sessionId: pending.sessionId, + direction: pending.direction, + providerId: pending.providerId, + code: `runtime-${event.status}`, + message: event.error + ?? `Terminal interceptor runtime ${event.status}`, + })); + } + } + for (const [key, pending] of this.failedActivations) { + if (pending.identity.pluginId === event.pluginId + && (event.runtimeId == null + || pending.identity.runtimeId == null + || pending.identity.runtimeId === event.runtimeId)) { + this.failedActivations.delete(key); + } + } + }); + this.contributionService.onDidChange?.(() => this.#pruneContributions()); + } + + bindTerminalWorkerManager(manager) { + this.workerWarningSubscription?.dispose?.(); + this.sessionOwnedSubscription?.dispose?.(); + this.sessionClosedSubscription?.dispose?.(); + this.workerWarningSubscription = null; + this.sessionOwnedSubscription = null; + this.sessionClosedSubscription = null; + this.terminalWorkerManager = manager ?? null; + if (manager?.onTerminalInterceptorWarning) { + this.workerWarningSubscription = manager.onTerminalInterceptorWarning((warning) => { + if (warning?.code === "worker-exit") { + this.active.clear(); + return; + } + const key = `${warning?.sessionId}\0${warning?.direction}`; + const binding = this.active.get(key); + if (!binding) return; + if (warning?.code === "closed" && !runtimeIdentityMatches( + this.runtimeSupervisor.getRuntimeIdentity(binding.identity.pluginId), + binding.identity, + )) { + // RuntimeSupervisor removes the identity before an expected stop + // closes the utility port, then publishes the authoritative stopped, + // error, or quarantined state. Defer classification to that event so + // planned restarts are not quarantined while crashes still are. + return; + } + this.active.delete(key); + if (!["detached", "replaced", "shutdown"].includes(warning?.code)) { + // A circuit-breaker or protocol failure quarantines this direction + // for the rest of the session. Keeping the cached provider would let + // the next connected/snapshot event silently reattach the same + // broken interceptor with its existing grants. + this.selectedProviders.delete(key); + this.declined.add(key); + this.quarantined.add(key); + this.showWarning(warning); + } + }); + } + if (manager?.onSessionOwned) { + this.sessionOwnedSubscription = manager.onSessionOwned((event) => ( + this.#handleSessionOwned(event) + )); + } + if (manager?.onSessionClosed) { + this.sessionClosedSubscription = manager.onSessionClosed((event) => { + if (typeof event?.sessionId === "string") this.#disposeSession(event.sessionId); + }); + } + } + + #disposeSession(sessionId) { + this.permissionEngine.revokeSession?.(sessionId); + this.pendingOwnership.delete(sessionId); + this.sessionEpochs.set(sessionId, (this.sessionEpochs.get(sessionId) ?? 0) + 1); + this.detachSession(sessionId); + for (const direction of DIRECTIONS) { + const key = this.#key(sessionId, direction); + this.declined.delete(key); + this.quarantined.delete(key); + this.selectedProviders.delete(key); + this.failedActivations.delete(key); + } + } + + async #handleSessionOwned(event) { + const pending = this.pendingOwnership.get(event?.sessionId); + if (!pending || pending.webContentsId !== event?.webContentsId) return; + this.pendingOwnership.delete(event.sessionId); + if (this.closed + || (this.sessionEpochs.get(event.sessionId) ?? 0) !== pending.sessionEpoch + || !this.terminalWorkerManager?.ownsSession?.(event.sessionId, event.webContentsId)) { + return; + } + await this.handleSessionEvent({ type: "snapshot", session: pending.session }, { + webContentsId: pending.webContentsId, + locale: pending.locale, + }); + } + + #key(sessionId, direction) { + return `${sessionId}\0${direction}`; + } + + #providers(direction, locale) { + const kind = `terminal.interceptor.${direction}`; + return this.contributionService.listProviders({ kind, locale }); + } + + #pruneContributions() { + for (const [key, selection] of this.selectedProviders) { + const direction = key.slice(key.lastIndexOf("\0") + 1); + if (!this.#providers(direction).some((entry) => ( + entry.provider.id === selection.providerId && entry.pluginId === selection.pluginId + ))) { + this.selectedProviders.delete(key); + } + } + for (const [key, binding] of this.active) { + const providers = this.#providers(binding.direction); + if (!providers.some((entry) => entry.provider.id === binding.providerId + && entry.pluginId === binding.identity.pluginId + && entry.pluginVersion === binding.identity.pluginVersion)) { + this.#detachKey(key, "contribution-removed"); + } + } + } + + #detachKey(key, reason) { + const binding = this.active.get(key); + if (!binding) return; + this.active.delete(key); + this.terminalWorkerManager?.detachTerminalInterceptor?.( + binding.sessionId, + binding.direction, + reason, + ); + } + + detachSession(sessionId, reason = "session-disposed") { + for (const direction of DIRECTIONS) this.#detachKey(this.#key(sessionId, direction), reason); + } + + async configureDirection(sessionValue, direction, options = {}) { + const session = normalizeTerminalSessionSnapshot(sessionValue); + if (!DIRECTIONS.includes(direction)) throw new TypeError("Terminal interceptor direction is invalid"); + const key = this.#key(session.sessionId, direction); + const epoch = options.sessionEpoch ?? this.sessionEpochs.get(session.sessionId) ?? 0; + const previous = this.operations.get(key) ?? Promise.resolve(); + const operation = previous.catch(() => {}).then(() => ( + this.#configureDirection(session, direction, { ...options, sessionEpoch: epoch }) + )); + this.operations.set(key, operation); + try { return await operation; } + finally { + if (this.operations.get(key) === operation) this.operations.delete(key); + } + } + + #assertSessionCurrent(sessionId, epoch) { + if (this.closed || (this.sessionEpochs.get(sessionId) ?? 0) !== epoch) { + throw new PluginRpcError(RPC_ERRORS.unavailable, "Terminal session changed during interceptor activation"); + } + } + + #assertAttachmentCurrent(session, direction, providerId, identity, options) { + this.#assertSessionCurrent(session.sessionId, options.sessionEpoch); + if (options.webContentsId != null + && !this.terminalWorkerManager?.ownsSession?.(session.sessionId, options.webContentsId)) { + throw new PluginRpcError( + RPC_ERRORS.permissionDenied, + "Terminal interceptor session ownership changed during activation", + ); + } + const declared = this.#providers(direction).some((entry) => ( + entry.provider.id === providerId + && entry.pluginId === identity.pluginId + && entry.pluginVersion === identity.pluginVersion + )); + if (!declared) { + throw new PluginRpcError( + RPC_ERRORS.unavailable, + "Terminal interceptor contribution changed during activation", + ); + } + } + + acceptsSessionEvent(event, webContentsId) { + const sessionId = event?.session?.sessionId; + if (typeof sessionId !== "string" || !Number.isSafeInteger(webContentsId)) return true; + const currentOwner = this.terminalWorkerManager?.getSessionOwnerWebContentsId?.(sessionId); + return !Number.isSafeInteger(currentOwner) || currentOwner === webContentsId; + } + + async #configureDirection(session, direction, options) { + this.#assertSessionCurrent(session.sessionId, options.sessionEpoch); + if (!this.terminalWorkerManager?.attachTerminalInterceptor) { + return Object.freeze({ status: "unavailable", direction }); + } + if (options.webContentsId != null + && !this.terminalWorkerManager.ownsSession?.(session.sessionId, options.webContentsId)) { + if (options.deferUntilOwned === true) { + return Object.freeze({ status: "pending-session", direction }); + } + throw new PluginRpcError( + RPC_ERRORS.permissionDenied, + "Terminal interceptor session is not owned by the requesting window", + ); + } + const providers = this.#providers(direction, options.locale); + if (providers.length === 0) return Object.freeze({ status: "none", direction }); + const key = this.#key(session.sessionId, direction); + if (this.quarantined.has(key)) { + return Object.freeze({ status: "declined", direction }); + } + if (options.providerId == null && this.declined.has(key)) { + return Object.freeze({ status: "declined", direction }); + } + const existing = this.active.get(key); + if (existing && existing.sessionEpoch === options.sessionEpoch + && terminalSessionSnapshotsEqual(existing.session, session) + && providers.some((entry) => entry.provider.id === existing.providerId) + && runtimeIdentityMatches( + this.runtimeSupervisor.getRuntimeIdentity(existing.identity.pluginId), + existing.identity, + )) { + return Object.freeze({ + status: "active", + direction, + providerId: existing.providerId, + pluginId: existing.identity.pluginId, + }); + } + const cachedSelection = this.selectedProviders.get(key); + let providerId = options.providerId ?? cachedSelection?.providerId; + if (providerId != null && !providers.some((entry) => entry.provider.id === providerId)) { + this.selectedProviders.delete(key); + providerId = options.providerId; + } + if (providerId == null && providers.length === 1) providerId = providers[0].provider.id; + if (providerId == null) { + providerId = await this.requestSelection(Object.freeze({ session, direction, providers })); + this.#assertSessionCurrent(session.sessionId, options.sessionEpoch); + if (options.webContentsId != null + && !this.terminalWorkerManager?.ownsSession?.(session.sessionId, options.webContentsId)) { + throw new PluginRpcError( + RPC_ERRORS.permissionDenied, + "Terminal interceptor session ownership changed during selection", + ); + } + } + if (providerId == null) { + this.declined.add(key); + this.selectedProviders.delete(key); + return Object.freeze({ status: "declined", direction }); + } + const selected = providers.find((entry) => entry.provider.id === providerId); + if (!selected) throw new PluginRpcError(RPC_ERRORS.invalidArgument, "Selected Terminal interceptor is unavailable"); + + const permissionGeneration = this.permissionGenerations.get(selected.pluginId) ?? 0; + let pendingActivation = Object.freeze({ + sessionId: session.sessionId, + sessionEpoch: options.sessionEpoch, + direction, + providerId, + identity: Object.freeze({ + pluginId: selected.pluginId, + pluginVersion: selected.pluginVersion, + runtimeId: null, + }), + }); + this.failedActivations.delete(key); + this.pendingActivations.set(key, pendingActivation); + try { + let activation; + try { + activation = await this.contributionService.activateProvider(providerId); + } catch (error) { + if ((this.sessionEpochs.get(session.sessionId) ?? 0) === options.sessionEpoch + && !this.quarantined.has(key) + && !this.finalizedActivations.has(pendingActivation)) { + this.failedActivations.set(key, pendingActivation); + } + if (this.finalizedActivations.has(pendingActivation) && !this.quarantined.has(key)) { + throw new PluginRpcError(RPC_ERRORS.cancelled, "Terminal interceptor activation was cancelled"); + } + throw error; + } + this.#assertSessionCurrent(session.sessionId, options.sessionEpoch); + const identity = normalizeActivationIdentity(activation); + pendingActivation = Object.freeze({ + sessionId: session.sessionId, + sessionEpoch: options.sessionEpoch, + direction, + providerId, + identity, + }); + this.pendingActivations.set(key, pendingActivation); + if (this.quarantined.has(key)) { + throw new PluginRpcError( + RPC_ERRORS.unavailable, + "Terminal interceptor was disabled after a runtime failure", + ); + } + if (activation.plugin.manifest.main?.node == null + || activation.provider.kind !== `terminal.interceptor.${direction}`) { + throw new PluginRpcError( + RPC_ERRORS.failedPrecondition, + "Terminal interceptors require an active advanced utility plugin", + ); + } + const context = { + pluginId: activation.plugin.id, + pluginVersion: activation.plugin.activeVersion, + runtimeId: identity.runtimeId, + runtimeKind: identity.runtimeKind, + manifest: activation.plugin.manifest, + securityPrincipal: identity.securityPrincipal, + }; + try { + for (const permission of ["provider.terminal", `terminal.intercept.${direction}`]) { + const grant = await this.permissionEngine.authorize(context, { + permission, + resources: ["*"], + sessionId: session.sessionId, + reason: `Use ${providerId} to intercept Terminal ${direction} data`, + operationId: `terminal.interceptor.${direction}:${providerId}`, + allowedScopes: ["session", "application", "always"], + validateBeforeGrant: () => { + if ((this.permissionGenerations.get(identity.pluginId) ?? 0) !== permissionGeneration) { + throw new PluginRpcError( + RPC_ERRORS.permissionDenied, + "Terminal interceptor permission changed during authorization", + ); + } + if (!runtimeIdentityMatches( + this.runtimeSupervisor.getRuntimeIdentity(identity.pluginId), + identity, + )) { + throw new PluginRpcError( + RPC_ERRORS.unavailable, + "Terminal interceptor runtime changed during authorization", + ); + } + this.#assertAttachmentCurrent(session, direction, providerId, identity, options); + }, + }); + if (!["existing", "session", "application", "always"].includes(grant?.scope)) { + throw new PluginRpcError( + RPC_ERRORS.permissionDenied, + "Terminal interceptor streams require a session, application, or persistent permission grant", + ); + } + this.#assertSessionCurrent(session.sessionId, options.sessionEpoch); + } + } catch (error) { + if (error?.code === RPC_ERRORS.permissionDenied) { + this.declined.add(key); + this.selectedProviders.delete(key); + } + throw error; + } + const currentIdentity = this.runtimeSupervisor.getRuntimeIdentity(activation.plugin.id); + if ((this.permissionGenerations.get(identity.pluginId) ?? 0) !== permissionGeneration) { + throw new PluginRpcError( + RPC_ERRORS.permissionDenied, + "Terminal interceptor permission changed during activation", + ); + } + if (!runtimeIdentityMatches(currentIdentity, identity)) { + throw new PluginRpcError(RPC_ERRORS.unavailable, "Terminal interceptor runtime changed during authorization"); + } + this.#assertAttachmentCurrent(session, direction, providerId, identity, options); + + if (existing?.sessionEpoch === options.sessionEpoch + && existing.providerId === providerId + && terminalSessionSnapshotsEqual(existing.session, session) + && runtimeIdentityMatches(existing.identity, identity)) { + return Object.freeze({ status: "active", direction, providerId, pluginId: identity.pluginId }); + } + const channel = new this.MessageChannelMain(); + const utilityDescriptor = Object.freeze({ providerId, direction, session }); + const workerDescriptor = Object.freeze({ + sessionId: session.sessionId, + direction, + providerId, + pluginId: identity.pluginId, + pluginVersion: identity.pluginVersion, + runtimeId: identity.runtimeId, + runtimeKind: identity.runtimeKind, + securityPrincipal: identity.securityPrincipal, + session, + }); + let workerAttached = false; + try { + await this.runtimeSupervisor.attachTerminalInterceptor( + identity.pluginId, + utilityDescriptor, + channel.port2, + { expectedIdentity: identity }, + ); + if (!runtimeIdentityMatches( + this.runtimeSupervisor.getRuntimeIdentity(identity.pluginId), + identity, + )) { + throw new PluginRpcError( + RPC_ERRORS.unavailable, + "Terminal interceptor runtime changed during port attachment", + ); + } + if ((this.permissionGenerations.get(identity.pluginId) ?? 0) !== permissionGeneration) { + throw new PluginRpcError( + RPC_ERRORS.permissionDenied, + "Terminal interceptor permission changed during port attachment", + ); + } + if (this.quarantined.has(key)) { + throw new PluginRpcError( + RPC_ERRORS.unavailable, + "Terminal interceptor was disabled after a runtime failure", + ); + } + this.#assertAttachmentCurrent(session, direction, providerId, identity, options); + this.terminalWorkerManager.attachTerminalInterceptor(workerDescriptor, channel.port1); + workerAttached = true; + } catch (error) { + if (!this.finalizedActivations.has(pendingActivation)) { + this.failedActivations.set(key, pendingActivation); + } + if (workerAttached) { + this.terminalWorkerManager.detachTerminalInterceptor(session.sessionId, direction); + } + try { channel.port1.close?.(); } catch {} + try { channel.port2.close?.(); } catch {} + if (this.finalizedActivations.has(pendingActivation) && !this.quarantined.has(key)) { + throw new PluginRpcError(RPC_ERRORS.cancelled, "Terminal interceptor activation was cancelled"); + } + throw error; + } + this.active.set(key, Object.freeze({ + sessionId: session.sessionId, + direction, + providerId, + identity: Object.freeze({ ...identity }), + sessionEpoch: options.sessionEpoch, + session, + })); + this.failedActivations.delete(key); + this.declined.delete(key); + this.selectedProviders.set(key, Object.freeze({ + providerId, + pluginId: identity.pluginId, + })); + return Object.freeze({ status: "active", direction, providerId, pluginId: identity.pluginId }); + } finally { + if (this.pendingActivations.get(key) === pendingActivation) { + this.pendingActivations.delete(key); + } + } + } + + async handleSessionEvent(event, options = {}) { + const session = normalizeTerminalSessionSnapshot(event?.session); + if (!this.acceptsSessionEvent(event, options.webContentsId)) return Object.freeze([]); + if (event?.type === "disposed") { + this.#disposeSession(session.sessionId); + return Object.freeze([]); + } + if (event?.type === "disconnected") { + const sessionEpoch = (this.sessionEpochs.get(session.sessionId) ?? 0) + 1; + this.sessionEpochs.set(session.sessionId, sessionEpoch); + this.detachSession(session.sessionId, "session-disconnected"); + if (Number.isSafeInteger(options.webContentsId)) { + this.pendingOwnership.set(session.sessionId, Object.freeze({ + session, + sessionEpoch, + webContentsId: options.webContentsId, + locale: options.locale, + })); + } else { + this.pendingOwnership.delete(session.sessionId); + } + return Object.freeze([]); + } + if (!["created", "connected", "reconnected", "snapshot", "cwdChanged", "titleChanged", + "resized", "alternateScreenChanged"].includes(event?.type)) { + return Object.freeze([]); + } + if (event.type === "created") { + this.detachSession(session.sessionId, "session-replaced"); + for (const direction of DIRECTIONS) { + const key = this.#key(session.sessionId, direction); + this.declined.delete(key); + this.quarantined.delete(key); + this.selectedProviders.delete(key); + this.failedActivations.delete(key); + } + this.sessionEpochs.set(session.sessionId, (this.sessionEpochs.get(session.sessionId) ?? 0) + 1); + } + if (!this.sessionEpochs.has(session.sessionId)) this.sessionEpochs.set(session.sessionId, 0); + const sessionEpoch = this.sessionEpochs.get(session.sessionId) ?? 0; + if (event.type === "created" && options.webContentsId != null) { + this.pendingOwnership.set(session.sessionId, Object.freeze({ + session, + sessionEpoch, + webContentsId: options.webContentsId, + locale: options.locale, + })); + } + const results = []; + for (const direction of DIRECTIONS) { + try { + results.push(await this.configureDirection(session, direction, { + ...options, + sessionEpoch, + deferUntilOwned: event.type === "created", + })); + } + catch (error) { + if (error?.code === RPC_ERRORS.permissionDenied) { + results.push(Object.freeze({ status: "declined", direction })); + continue; + } + const key = this.#key(session.sessionId, direction); + if (error?.code === RPC_ERRORS.cancelled + || (this.sessionEpochs.get(session.sessionId) ?? 0) !== sessionEpoch + || this.quarantined.has(key)) { + results.push(Object.freeze({ status: "cancelled", direction })); + continue; + } + this.showWarning(Object.freeze({ + sessionId: session.sessionId, + direction, + code: "activation", + message: error?.message ?? String(error), + })); + results.push(Object.freeze({ status: "failed", direction })); + } + } + if (event.type === "created" + && !results.some((result) => result.status === "pending-session")) { + this.pendingOwnership.delete(session.sessionId); + } + return Object.freeze(results); + } + + shutdown() { + this.closed = true; + for (const sessionId of this.sessionEpochs.keys()) { + this.sessionEpochs.set(sessionId, (this.sessionEpochs.get(sessionId) ?? 0) + 1); + } + for (const key of [...this.active.keys()]) this.#detachKey(key, "shutdown"); + this.declined.clear(); + this.quarantined.clear(); + this.selectedProviders.clear(); + this.pendingActivations.clear(); + this.failedActivations.clear(); + this.pendingOwnership.clear(); + this.workerWarningSubscription?.dispose?.(); + this.sessionOwnedSubscription?.dispose?.(); + this.sessionClosedSubscription?.dispose?.(); + this.workerWarningSubscription = null; + this.sessionOwnedSubscription = null; + this.sessionClosedSubscription = null; + this.permissionRevocationSubscription?.dispose?.(); + this.permissionRevocationSubscription = null; + } +} + +module.exports = { + DIRECTIONS, + PluginTerminalDataPipelineService, + normalizeActivationIdentity, + runtimeIdentityMatches, +}; diff --git a/electron/plugins/terminalDataPipelineService.test.cjs b/electron/plugins/terminalDataPipelineService.test.cjs new file mode 100644 index 000000000..0df3be8dc --- /dev/null +++ b/electron/plugins/terminalDataPipelineService.test.cjs @@ -0,0 +1,920 @@ +"use strict"; + +const assert = require("node:assert/strict"); +const { MessageChannel } = require("node:worker_threads"); +const test = require("node:test"); + +const { PluginRpcError, RPC_ERRORS } = require("./rpcRouter.cjs"); +const { PluginTerminalDataPipelineService } = require("./terminalDataPipelineService.cjs"); + +function provider(pluginId, id, direction) { + return Object.freeze({ + pluginId, + pluginVersion: "1.0.0", + pluginDisplayName: pluginId, + provider: Object.freeze({ id, kind: `terminal.interceptor.${direction}`, label: id }), + }); +} + +function harness(options = {}) { + const providers = options.providers ?? [provider("com.example", "com.example.input", "input")]; + const identity = Object.freeze({ + pluginId: "com.example", + pluginVersion: "1.0.0", + runtimeId: "runtime-1", + runtimeKind: options.runtimeKind ?? "utility", + securityPrincipal: "principal-1", + }); + const attached = []; + const detached = []; + const authorized = []; + const activationCalls = []; + const revokedSessions = []; + let permissionRevocationListener = null; + const contributionListeners = []; + const runtimeListeners = []; + const contributionService = { + listProviders({ kind }) { return providers.filter((entry) => entry.provider.kind === kind); }, + async activateProvider(providerId) { + activationCalls.push(providerId); + await options.onActivateProvider?.(); + const entry = providers.find((candidate) => candidate.provider.id === providerId); + if (!entry) throw new Error("missing provider"); + return { + plugin: { + id: entry.pluginId, + activeVersion: entry.pluginVersion, + manifest: { main: { node: "dist/index.js" }, permissions: { required: ["runtime.advanced"] } }, + }, + provider: entry.provider, + identity: options.activationIdentity ?? identity, + }; + }, + onDidChange(listener) { contributionListeners.push(listener); }, + }; + const runtimeSupervisor = { + getRuntimeIdentity() { return options.getRuntimeIdentity ? options.getRuntimeIdentity() : identity; }, + onDidChangeRuntime(listener) { runtimeListeners.push(listener); }, + async attachTerminalInterceptor(pluginId, descriptor, port, attachOptions) { + port.unref?.(); + attached.push({ side: "plugin", pluginId, descriptor, port, attachOptions }); + await options.onAttachTerminalInterceptor?.(); + }, + }; + const permissionEngine = { + async authorize(context, request) { + authorized.push({ context, request }); + await options.onAuthorize?.({ context, request, providers }); + request.validateBeforeGrant?.(); + const scope = typeof options.permissionScope === "function" + ? options.permissionScope({ context, request, call: authorized.length }) + : options.permissionScope ?? "session"; + return { scope }; + }, + revokeSession(sessionId) { revokedSessions.push(sessionId); }, + onDidRevoke(listener) { + permissionRevocationListener = listener; + return { dispose: () => { permissionRevocationListener = null; } }; + }, + }; + const worker = { + warningListener: null, + ownedListener: null, + closedListener: null, + ownsSession() { return true; }, + getSessionOwnerWebContentsId() { + return options.sessionOwnerWebContentsId ?? null; + }, + attachTerminalInterceptor(descriptor, port) { + port.unref?.(); + attached.push({ side: "worker", descriptor, port }); + }, + detachTerminalInterceptor(sessionId, direction) { detached.push({ sessionId, direction }); }, + onTerminalInterceptorWarning(listener) { + this.warningListener = listener; + return { dispose: () => { this.warningListener = null; } }; + }, + onSessionOwned(listener) { + this.ownedListener = listener; + return { dispose: () => { this.ownedListener = null; } }; + }, + onSessionClosed(listener) { + this.closedListener = listener; + return { dispose: () => { this.closedListener = null; } }; + }, + }; + const selections = []; + const warnings = []; + const service = new PluginTerminalDataPipelineService({ + contributionService, + permissionEngine, + runtimeSupervisor, + MessageChannelMain: MessageChannel, + requestSelection: async (request) => { + selections.push(request); + return Object.hasOwn(options, "selectedProviderId") + ? options.selectedProviderId + : request.providers[0].provider.id; + }, + showWarning: (warning) => warnings.push(warning), + }); + service.bindTerminalWorkerManager(worker); + return { + service, + worker, + identity, + attached, + detached, + authorized, + activationCalls, + revokedSessions, + selections, + warnings, + runtimeListeners, + revokePermission(event) { permissionRevocationListener?.(event); }, + contributionListeners, + contributionService, + }; +} + +const session = Object.freeze({ + sessionId: "session-1", + protocol: "ssh", + status: "connected", +}); + +test("pipeline activation requires exact session permissions and transfers one port to each process", async () => { + const h = harness(); + const result = await h.service.configureDirection(session, "input"); + assert.deepEqual(result, { + status: "active", + direction: "input", + providerId: "com.example.input", + pluginId: "com.example", + }); + assert.deepEqual(h.authorized.map((entry) => entry.request.permission), [ + "provider.terminal", + "terminal.intercept.input", + ]); + assert.ok(h.authorized.every((entry) => entry.request.sessionId === "session-1")); + assert.ok(h.authorized.every((entry) => ( + JSON.stringify(entry.request.allowedScopes) === JSON.stringify(["session", "application", "always"]) + ))); + assert.deepEqual(h.attached.map((entry) => entry.side), ["plugin", "worker"]); + assert.deepEqual(h.attached[0].attachOptions.expectedIdentity, h.identity); + assert.deepEqual(h.attached[0].descriptor, { + providerId: "com.example.input", + direction: "input", + session, + }); + assert.deepEqual(h.attached[1].descriptor, { + sessionId: "session-1", + direction: "input", + providerId: "com.example.input", + pluginId: "com.example", + pluginVersion: "1.0.0", + runtimeId: "runtime-1", + runtimeKind: "utility", + securityPrincipal: "principal-1", + session, + }); +}); + +test("pipeline rejects one-use permission grants before opening a streaming port", async () => { + const h = harness({ permissionScope: "once" }); + await assert.rejects( + () => h.service.configureDirection(session, "input"), + /require a session, application, or persistent permission grant/, + ); + assert.equal(h.authorized.length, 1); + assert.equal(h.attached.length, 0); + + const laterOnce = harness({ + permissionScope: ({ call }) => (call === 2 ? "once" : "session"), + }); + await assert.rejects( + () => laterOnce.service.configureDirection(session, "input"), + /require a session, application, or persistent permission grant/, + ); + assert.equal(laterOnce.authorized.length, 2); + assert.equal(laterOnce.attached.length, 0); +}); + +test("permission denial is remembered for the session instead of prompting again", async () => { + const h = harness({ + onAuthorize() { + throw new PluginRpcError(RPC_ERRORS.permissionDenied, "permission denied"); + }, + }); + await assert.rejects( + () => h.service.configureDirection(session, "input"), + (error) => error?.code === RPC_ERRORS.permissionDenied, + ); + h.contributionListeners[0](); + assert.equal((await h.service.configureDirection(session, "input")).status, "declined"); + assert.equal(h.authorized.length, 1); + assert.equal(h.attached.length, 0); +}); + +test("session event permission denial is a quiet declined result", async () => { + const h = harness({ + onAuthorize() { + throw new PluginRpcError(RPC_ERRORS.permissionDenied, "permission denied"); + }, + }); + const results = await h.service.handleSessionEvent({ type: "connected", session }, { + webContentsId: 99, + }); + assert.deepEqual(results, [ + { status: "declined", direction: "input" }, + { status: "none", direction: "output" }, + ]); + assert.deepEqual(h.warnings, []); +}); + +test("pipeline accepts an existing long-lived permission grant", async () => { + const h = harness({ permissionScope: "existing" }); + const result = await h.service.configureDirection(session, "input"); + assert.equal(result.status, "active"); + assert.equal(h.authorized.length, 2); + assert.deepEqual(h.attached.map((entry) => entry.side), ["plugin", "worker"]); +}); + +test("multiple interceptors require an explicit per-session selection", async () => { + const h = harness({ + providers: [ + provider("com.example", "com.example.input", "input"), + provider("com.other", "com.other.input", "input"), + ], + selectedProviderId: "com.example.input", + }); + await h.service.configureDirection(session, "input"); + assert.equal(h.selections.length, 1); + assert.equal(h.selections[0].providers.length, 2); + await h.service.configureDirection(session, "input"); + assert.equal(h.selections.length, 1, "an active session binding must not prompt again"); +}); + +test("declining competing interceptors is remembered for the session and reset on disposal", async () => { + const h = harness({ + providers: [ + provider("com.example", "com.example.input", "input"), + provider("com.other", "com.other.input", "input"), + ], + selectedProviderId: null, + }); + assert.equal((await h.service.configureDirection(session, "input")).status, "declined"); + assert.equal((await h.service.configureDirection(session, "input")).status, "declined"); + assert.equal(h.selections.length, 1); + + await h.service.handleSessionEvent({ + type: "disposed", + session: { ...session, status: "disconnected" }, + }); + await h.service.configureDirection(session, "input"); + assert.equal(h.selections.length, 2); +}); + +test("concurrent snapshots serialize to one authorization and one port pair", async () => { + const h = harness(); + const [first, second] = await Promise.all([ + h.service.configureDirection(session, "input"), + h.service.configureDirection(session, "input"), + ]); + assert.equal(first.status, "active"); + assert.equal(second.status, "active"); + assert.equal(h.authorized.length, 2); + assert.equal(h.attached.length, 2); +}); + +test("browser runtimes cannot receive privileged terminal ports", async () => { + const h = harness({ runtimeKind: "browser" }); + await assert.rejects( + () => h.service.configureDirection(session, "input"), + /advanced utility runtime/, + ); + assert.equal(h.attached.length, 0); +}); + +test("stale activation identity fails before permissions or port transfer", async () => { + const h = harness({ + activationIdentity: { + pluginId: "com.example", + pluginVersion: "0.9.0", + runtimeId: "stale-runtime", + runtimeKind: "utility", + securityPrincipal: "principal-1", + }, + }); + await assert.rejects( + () => h.service.configureDirection(session, "input"), + /identity is unavailable, stale/, + ); + assert.equal(h.authorized.length, 0); + assert.equal(h.attached.length, 0); +}); + +test("worker transfer starts only after the plugin port is ready", async () => { + const h = harness(); + h.worker.attachTerminalInterceptor = () => { throw new Error("worker unavailable"); }; + await assert.rejects( + () => h.service.configureDirection(session, "input"), + /worker unavailable/, + ); + assert.deepEqual(h.attached.map((entry) => entry.side), ["plugin"]); +}); + +test("contribution withdrawal during authorization prevents stale port publication", async () => { + let withdrawn = false; + const h = harness({ + onAuthorize({ providers }) { + if (withdrawn) return; + withdrawn = true; + providers.splice(0, providers.length); + }, + }); + await assert.rejects( + () => h.service.configureDirection(session, "input"), + /contribution changed/, + ); + assert.equal(h.attached.length, 0); +}); + +test("runtime replacement during port attachment cannot publish a stale active binding", async () => { + let runtimeId = "runtime-1"; + const h = harness({ + getRuntimeIdentity: () => ({ + pluginId: "com.example", + pluginVersion: "1.0.0", + runtimeId, + runtimeKind: "utility", + securityPrincipal: "principal-1", + }), + onAttachTerminalInterceptor() { runtimeId = "runtime-2"; }, + }); + await assert.rejects( + () => h.service.configureDirection(session, "input"), + /runtime changed during port attachment/, + ); + assert.deepEqual(h.attached.map((entry) => entry.side), ["plugin"]); + assert.deepEqual(h.detached, []); + assert.equal(h.service.active.size, 0); +}); + +test("disconnect detaches and reconnect restores the remembered session interceptor", async () => { + const h = harness({ + providers: [ + provider("com.example", "com.example.input", "input"), + provider("com.other", "com.other.input", "input"), + ], + selectedProviderId: "com.example.input", + }); + await h.service.handleSessionEvent({ type: "connected", session }); + assert.equal(h.selections.length, 1); + assert.deepEqual(h.attached.map((entry) => entry.side), ["plugin", "worker"]); + + await h.service.handleSessionEvent({ + type: "disconnected", + session: { ...session, status: "disconnected" }, + }, { webContentsId: 99 }); + assert.deepEqual(h.detached, [{ sessionId: "session-1", direction: "input" }]); + + await h.worker.ownedListener({ sessionId: session.sessionId, webContentsId: 99 }); + assert.equal(h.selections.length, 1, "reconnect ownership must reuse the session-local choice"); + assert.deepEqual(h.attached.map((entry) => entry.side), [ + "plugin", "worker", "plugin", "worker", + ]); + + await h.service.handleSessionEvent({ type: "reconnected", session }); + assert.equal(h.selections.length, 1, "reconnect must reuse the session-local choice"); + assert.deepEqual(h.attached.map((entry) => entry.side), [ + "plugin", "worker", "plugin", "worker", "plugin", "worker", + ]); + assert.equal(h.attached.at(-1).descriptor.session.status, "connected"); +}); + +test("session metadata changes refresh the interceptor invocation snapshot", async () => { + const h = harness(); + await h.service.handleSessionEvent({ type: "connected", session }); + await h.service.handleSessionEvent({ + type: "cwdChanged", + session: { ...session, cwd: "/srv/current" }, + }); + assert.equal(h.attached.at(-1).descriptor.session.cwd, "/srv/current"); + assert.deepEqual(h.attached.map((entry) => entry.side), [ + "plugin", "worker", "plugin", "worker", + ]); + assert.deepEqual(h.detached, [], "snapshot refresh must replace the worker port atomically"); +}); + +test("revoking a terminal permission immediately detaches the matching active interceptor", async () => { + const h = harness(); + await h.service.configureDirection(session, "input"); + h.revokePermission({ + pluginId: "com.example", + permission: "terminal.intercept.input", + resource: "*", + scope: "application", + }); + assert.equal(h.service.active.size, 0); + assert.deepEqual(h.detached, [{ sessionId: "session-1", direction: "input" }]); +}); + +test("a worker-confirmed terminal exit revokes session grants and clears pipeline state", async () => { + const h = harness(); + await h.service.configureDirection(session, "input"); + + h.worker.closedListener({ sessionId: session.sessionId, reason: "exited" }); + + assert.deepEqual(h.revokedSessions, [session.sessionId]); + assert.equal(h.service.active.size, 0); + assert.deepEqual(h.detached, [{ sessionId: session.sessionId, direction: "input" }]); +}); + +test("a renderer cannot attach an interceptor to another window's terminal session", async () => { + const h = harness(); + h.worker.ownsSession = () => false; + await assert.rejects( + () => h.service.configureDirection(session, "input", { webContentsId: 99 }), + /not owned by the requesting window/, + ); + assert.equal(h.authorized.length, 0); + assert.equal(h.attached.length, 0); +}); + +test("renderer loss during provider selection prevents authorization", async () => { + const h = harness({ + providers: [ + provider("com.example", "com.example.input", "input"), + provider("com.other", "com.other.input", "input"), + ], + }); + let owned = true; + let releaseSelection; + h.worker.ownsSession = () => owned; + h.service.requestSelection = async () => { + await new Promise((resolve) => { releaseSelection = resolve; }); + return "com.example.input"; + }; + + const activation = h.service.configureDirection(session, "input", { webContentsId: 99 }); + while (!releaseSelection) await new Promise((resolve) => setImmediate(resolve)); + owned = false; + releaseSelection(); + + await assert.rejects(() => activation, /ownership changed during selection/); + assert.equal(h.authorized.length, 0); + assert.equal(h.attached.length, 0); +}); + +test("renderer loss during permission approval prevents a lasting grant", async () => { + let owned = true; + let releaseAuthorization; + const h = harness({ + onAuthorize: () => new Promise((resolve) => { releaseAuthorization = resolve; }), + }); + h.worker.ownsSession = () => owned; + + const activation = h.service.configureDirection(session, "input", { webContentsId: 99 }); + while (!releaseAuthorization) await new Promise((resolve) => setImmediate(resolve)); + owned = false; + releaseAuthorization(); + + await assert.rejects(() => activation, /ownership changed during activation/); + assert.equal(h.authorized.length, 1); + assert.equal(h.attached.length, 0); +}); + +test("renderer loss during port attachment prevents worker publication", async () => { + let owned = true; + let releaseAttach; + const h = harness({ + onAttachTerminalInterceptor: () => new Promise((resolve) => { releaseAttach = resolve; }), + }); + h.worker.ownsSession = () => owned; + + const activation = h.service.configureDirection(session, "input", { webContentsId: 99 }); + while (!releaseAttach) await new Promise((resolve) => setImmediate(resolve)); + owned = false; + releaseAttach(); + + await assert.rejects(() => activation, /ownership changed during activation/); + assert.deepEqual(h.attached.map((entry) => entry.side), ["plugin"]); +}); + +test("created events defer silently until the worker has recorded session ownership", async () => { + const h = harness(); + let owned = false; + h.worker.ownsSession = () => owned; + const results = await h.service.handleSessionEvent({ type: "created", session }, { + webContentsId: 99, + }); + assert.deepEqual(results, [ + { status: "pending-session", direction: "input" }, + { status: "pending-session", direction: "output" }, + ]); + assert.equal(h.authorized.length, 0); + assert.equal(h.attached.length, 0); + + owned = true; + await h.worker.ownedListener({ sessionId: session.sessionId, webContentsId: 99 }); + assert.deepEqual(h.attached.map((entry) => entry.side), ["plugin", "worker"]); + assert.equal(h.authorized.length, 2); +}); + +test("session disposal invalidates an in-flight lazy activation before port transfer", async () => { + const h = harness(); + const originalActivate = h.contributionService.activateProvider; + let releaseActivation; + h.contributionService.activateProvider = async (...args) => { + await new Promise((resolve) => { releaseActivation = resolve; }); + return originalActivate(...args); + }; + const pending = h.service.configureDirection(session, "input"); + await new Promise((resolve) => setImmediate(resolve)); + await h.service.handleSessionEvent({ + type: "disposed", + session: { ...session, status: "disconnected" }, + }); + releaseActivation(); + await assert.rejects(pending, /session changed/); + assert.equal(h.attached.length, 0); +}); + +test("a stale renderer disposal cannot detach the current owner's interceptor", async () => { + const h = harness({ sessionOwnerWebContentsId: 9 }); + await h.service.configureDirection(session, "input", { webContentsId: 9 }); + + await h.service.handleSessionEvent({ + type: "disposed", + session: { ...session, status: "disconnected" }, + }, { webContentsId: 7 }); + + assert.equal(h.service.active.size, 1); + assert.deepEqual(h.detached, []); + assert.deepEqual(h.revokedSessions, []); + + await h.service.handleSessionEvent({ + type: "disposed", + session: { ...session, status: "disconnected" }, + }, { webContentsId: 9 }); + assert.equal(h.service.active.size, 0); + assert.deepEqual(h.detached, [{ sessionId: "session-1", direction: "input" }]); + assert.deepEqual(h.revokedSessions, ["session-1"]); +}); + +test("a stale renderer cannot publish any lifecycle event for the current owner's session", async () => { + const h = harness({ sessionOwnerWebContentsId: 9 }); + await h.service.configureDirection(session, "input", { webContentsId: 9 }); + for (const type of ["created", "disconnected", "connected", "cwdChanged"]) { + const result = await h.service.handleSessionEvent({ type, session }, { webContentsId: 7 }); + assert.deepEqual(result, []); + } + assert.equal(h.service.active.size, 1); + assert.deepEqual(h.detached, []); + assert.deepEqual(h.revokedSessions, []); +}); + +test("runtime failure statuses quarantine both directions before detaching", async () => { + for (const status of ["error", "quarantined"]) { + const h = harness({ + providers: [ + provider("com.example", "com.example.input", "input"), + provider("com.example", "com.example.output", "output"), + ], + }); + await h.service.handleSessionEvent({ type: "connected", session }); + h.runtimeListeners[0]({ + status, + pluginId: "com.example", + runtimeId: "runtime-1", + error: "utility runtime crashed", + }); + assert.deepEqual(h.detached.map((entry) => entry.direction).sort(), ["input", "output"]); + assert.deepEqual(h.warnings.map((warning) => warning.code).sort(), [ + `runtime-${status}`, + `runtime-${status}`, + ]); + const reconnect = await h.service.handleSessionEvent({ type: "connected", session }); + assert.deepEqual(reconnect.map((result) => result.status), ["declined", "declined"]); + assert.equal(h.authorized.length, 4, "a crashed runtime must not be authorized again"); + assert.equal(h.attached.length, 4, "a crashed runtime must not be reattached"); + await h.service.handleSessionEvent({ + type: "disposed", + session: { ...session, status: "disconnected" }, + }); + } +}); + +test("runtime exit clears the cached provider choice but ordinary reconnect preserves it", async () => { + const providers = [ + provider("com.example", "com.example.input", "input"), + provider("com.other", "com.other.input", "input"), + ]; + const h = harness({ + providers, + selectedProviderId: "com.example.input", + }); + await h.service.configureDirection(session, "input"); + assert.equal(h.selections.length, 1); + + const withdrawn = providers.splice(0); + h.runtimeListeners[0]({ + status: "stopped", + pluginId: "com.example", + runtimeId: "runtime-1", + }); + providers.push(...withdrawn); + await h.service.configureDirection(session, "input"); + assert.equal(h.selections.length, 2, "a stopped runtime must discard its session-local choice"); +}); + +test("an expected runtime close waits for the stopped event instead of quarantining", async () => { + let currentIdentity; + const h = harness({ getRuntimeIdentity: () => currentIdentity }); + currentIdentity = h.identity; + assert.equal((await h.service.configureDirection(session, "input")).status, "active"); + + currentIdentity = null; + h.worker.warningListener({ + sessionId: session.sessionId, + direction: "input", + code: "closed", + message: "Terminal interceptor stopped and was disabled", + }); + assert.equal(h.warnings.length, 0); + + h.runtimeListeners[0]({ + status: "stopped", + pluginId: "com.example", + runtimeId: "runtime-1", + }); + currentIdentity = h.identity; + assert.equal((await h.service.configureDirection(session, "input")).status, "active"); + assert.equal(h.warnings.length, 0); + assert.equal(h.authorized.length, 4); + assert.equal(h.attached.length, 4); +}); + +test("a close during runtime failure is quarantined by the authoritative error event", async () => { + let currentIdentity; + const h = harness({ getRuntimeIdentity: () => currentIdentity }); + currentIdentity = h.identity; + assert.equal((await h.service.configureDirection(session, "input")).status, "active"); + + currentIdentity = null; + h.worker.warningListener({ + sessionId: session.sessionId, + direction: "input", + code: "closed", + message: "Terminal interceptor stopped and was disabled", + }); + h.runtimeListeners[0]({ + status: "error", + pluginId: "com.example", + runtimeId: "runtime-1", + error: "utility runtime crashed", + }); + + const [result] = await h.service.handleSessionEvent({ type: "connected", session }); + assert.equal(result.status, "declined"); + assert.deepEqual(h.warnings.map((warning) => warning.code), ["runtime-error"]); + assert.equal(h.authorized.length, 2); + assert.equal(h.attached.length, 2); +}); + +test("terminal worker exit invalidates active bindings before worker restart", async () => { + const h = harness(); + await h.service.configureDirection(session, "input"); + h.worker.warningListener({ code: "worker-exit", message: "Terminal worker exited" }); + await h.service.configureDirection(session, "input"); + assert.equal(h.authorized.length, 4); + assert.equal(h.attached.length, 4); +}); + +test("a failed interceptor stays quarantined for the rest of the session", async () => { + const h = harness(); + assert.equal((await h.service.configureDirection(session, "input")).status, "active"); + + h.worker.warningListener({ + sessionId: session.sessionId, + direction: "input", + code: "timeout", + message: "Interceptor timed out", + }); + + const [result] = await h.service.handleSessionEvent({ type: "connected", session }); + assert.equal(result.status, "declined"); + assert.equal(h.authorized.length, 2, "the quarantined provider must not be authorized again"); + assert.equal(h.attached.length, 2, "the quarantined provider must not be reattached"); + assert.equal(h.warnings.length, 1); +}); + +test("permission revocation while a port is attaching prevents the worker attachment", async () => { + let releaseAttach; + const attachGate = new Promise((resolve) => { releaseAttach = resolve; }); + const h = harness({ onAttachTerminalInterceptor: () => attachGate }); + + const activation = h.service.configureDirection(session, "input"); + while (h.attached.length === 0) await new Promise((resolve) => setImmediate(resolve)); + h.revokePermission({ pluginId: "com.example", permission: "terminal.intercept.input" }); + releaseAttach(); + + await assert.rejects( + () => activation, + (error) => error?.code === RPC_ERRORS.permissionDenied, + ); + assert.deepEqual(h.attached.map((entry) => entry.side), ["plugin"]); +}); + +test("a concurrent metadata refresh cannot revive a quarantined interceptor", async () => { + let attachCalls = 0; + let releaseRefresh; + const refreshGate = new Promise((resolve) => { releaseRefresh = resolve; }); + const h = harness({ + onAttachTerminalInterceptor() { + attachCalls += 1; + return attachCalls === 2 ? refreshGate : undefined; + }, + }); + assert.equal((await h.service.configureDirection(session, "input")).status, "active"); + + const refresh = h.service.configureDirection({ ...session, title: "new title" }, "input"); + while (h.attached.length < 3) await new Promise((resolve) => setImmediate(resolve)); + h.worker.warningListener({ + sessionId: session.sessionId, + direction: "input", + code: "timeout", + message: "Interceptor timed out", + }); + releaseRefresh(); + + await assert.rejects( + () => refresh, + (error) => error?.code === RPC_ERRORS.unavailable, + ); + assert.deepEqual(h.attached.map((entry) => entry.side), ["plugin", "worker", "plugin"]); + assert.equal((await h.service.configureDirection(session, "input")).status, "declined"); +}); + +test("a runtime crash reported after its first port attachment fails still quarantines the interceptor", async () => { + let rejectAttach; + const attachGate = new Promise((_resolve, reject) => { rejectAttach = reject; }); + const h = harness({ onAttachTerminalInterceptor: () => attachGate }); + + const activation = h.service.configureDirection(session, "input"); + while (h.attached.length === 0) await new Promise((resolve) => setImmediate(resolve)); + rejectAttach(new Error("plugin runtime transport closed")); + await assert.rejects(() => activation, /transport closed/); + + h.runtimeListeners[0]({ + status: "error", + pluginId: "com.example", + runtimeId: h.identity.runtimeId, + error: "utility runtime crashed during attachment", + }); + assert.deepEqual(h.attached.map((entry) => entry.side), ["plugin"]); + assert.equal((await h.service.configureDirection(session, "input")).status, "declined"); + assert.equal(h.authorized.length, 2); + assert.deepEqual(h.warnings.map((warning) => warning.code), ["runtime-error"]); +}); + +test("a runtime crash during first provider activation prevents automatic retry", async () => { + let rejectActivation; + const activationGate = new Promise((_resolve, reject) => { rejectActivation = reject; }); + const h = harness({ onActivateProvider: () => activationGate }); + + const activation = h.service.configureDirection(session, "input"); + while (h.activationCalls.length === 0) await new Promise((resolve) => setImmediate(resolve)); + h.runtimeListeners[0]({ + status: "error", + pluginId: "com.example", + runtimeId: h.identity.runtimeId, + error: "utility runtime crashed during activation", + }); + rejectActivation(new Error("plugin activation transport closed")); + + await assert.rejects(() => activation, /transport closed/); + assert.equal((await h.service.configureDirection(session, "input")).status, "declined"); + assert.equal(h.activationCalls.length, 1); + assert.equal(h.authorized.length, 0); + assert.deepEqual(h.warnings.map((warning) => warning.code), ["runtime-error"]); +}); + +test("a late crash from an old session generation cannot quarantine a reused session id", async () => { + let rejectOldActivation; + let activationCalls = 0; + const oldActivationGate = new Promise((_resolve, reject) => { rejectOldActivation = reject; }); + const h = harness({ + onActivateProvider() { + activationCalls += 1; + return activationCalls === 1 ? oldActivationGate : undefined; + }, + }); + + const oldActivation = h.service.handleSessionEvent({ type: "snapshot", session }); + while (h.activationCalls.length === 0) await new Promise((resolve) => setImmediate(resolve)); + await h.service.handleSessionEvent({ type: "disposed", session }); + const newActivation = h.service.handleSessionEvent({ type: "created", session }); + + h.runtimeListeners[0]({ + status: "error", + pluginId: "com.example", + runtimeId: h.identity.runtimeId, + error: "old utility runtime crashed late", + }); + rejectOldActivation(new Error("old plugin activation transport closed")); + + const oldResult = await oldActivation; + const newResult = await newActivation; + assert.equal(oldResult[0].status, "cancelled"); + assert.notEqual(newResult[0].status, "declined"); + assert.equal(h.activationCalls.length, 2); + assert.deepEqual(h.warnings.filter((warning) => warning.code === "runtime-error"), []); +}); + +test("a normal stop before provider activation rejects cannot become a later crash record", async () => { + let rejectActivation; + let activationCalls = 0; + const activationGate = new Promise((_resolve, reject) => { rejectActivation = reject; }); + const h = harness({ + onActivateProvider() { + activationCalls += 1; + return activationCalls === 1 ? activationGate : undefined; + }, + }); + + const first = h.service.configureDirection(session, "input"); + while (h.activationCalls.length === 0) await new Promise((resolve) => setImmediate(resolve)); + h.runtimeListeners[0]({ + status: "stopped", + pluginId: "com.example", + runtimeId: h.identity.runtimeId, + }); + rejectActivation(new Error("plugin stopped during activation")); + await assert.rejects( + () => first, + (error) => error?.code === RPC_ERRORS.cancelled, + ); + + h.runtimeListeners[0]({ + status: "error", + pluginId: "com.example", + runtimeId: h.identity.runtimeId, + error: "unrelated later crash", + }); + assert.equal((await h.service.configureDirection(session, "input")).status, "active"); + assert.equal(h.activationCalls.length, 2); + assert.deepEqual(h.warnings, []); +}); + +test("normal cancellation and an already-reported crash do not emit duplicate activation warnings", async () => { + let rejectActivation; + const activationGate = new Promise((_resolve, reject) => { rejectActivation = reject; }); + const normal = harness({ onActivateProvider: () => activationGate }); + const normalEvent = normal.service.handleSessionEvent({ type: "snapshot", session }); + while (normal.activationCalls.length === 0) await new Promise((resolve) => setImmediate(resolve)); + normal.runtimeListeners[0]({ + status: "stopped", + pluginId: "com.example", + runtimeId: normal.identity.runtimeId, + }); + rejectActivation(new Error("runtime stopped")); + const normalResults = await normalEvent; + assert.equal(normalResults[0].status, "cancelled"); + assert.deepEqual(normal.warnings, []); + + let rejectCrash; + const crashGate = new Promise((_resolve, reject) => { rejectCrash = reject; }); + const crashed = harness({ onActivateProvider: () => crashGate }); + const crashEvent = crashed.service.handleSessionEvent({ type: "snapshot", session }); + while (crashed.activationCalls.length === 0) await new Promise((resolve) => setImmediate(resolve)); + crashed.runtimeListeners[0]({ + status: "error", + pluginId: "com.example", + runtimeId: crashed.identity.runtimeId, + error: "runtime crashed", + }); + rejectCrash(new Error("transport closed")); + const crashResults = await crashEvent; + assert.equal(crashResults[0].status, "cancelled"); + assert.deepEqual(crashed.warnings.map((warning) => warning.code), ["runtime-error"]); +}); + +test("contribution changes do not clear a failed interceptor quarantine", async () => { + const h = harness(); + assert.equal((await h.service.configureDirection(session, "input")).status, "active"); + + h.worker.warningListener({ + sessionId: session.sessionId, + direction: "input", + code: "protocol", + message: "Interceptor returned an invalid frame", + }); + h.contributionListeners[0](); + + const [result] = await h.service.handleSessionEvent({ type: "snapshot", session }); + assert.equal(result.status, "declined"); + assert.equal(h.authorized.length, 2); + assert.equal(h.attached.length, 2); +}); diff --git a/electron/plugins/terminalInterceptorMessages.cjs b/electron/plugins/terminalInterceptorMessages.cjs new file mode 100644 index 000000000..d21c7b58c --- /dev/null +++ b/electron/plugins/terminalInterceptorMessages.cjs @@ -0,0 +1,63 @@ +"use strict"; + +const { escapePermissionText } = require("./nativePermissionDecision.cjs"); + +const MESSAGES = Object.freeze({ + en: Object.freeze({ + noInterceptor: "No interceptor", + selectTitle: (direction) => `Terminal ${direction} interceptor`, + selectMessage: (direction) => `Multiple plugins can intercept Terminal ${direction} data. Choose one for this session.`, + warningTitle: "Terminal interceptor disabled", + warningMessage: "A Terminal interceptor was disabled for this session.", + warningDetail: "The plugin failed or exceeded its data-path budget.", + }), + "zh-CN": Object.freeze({ + noInterceptor: "不使用拦截器", + selectTitle: (direction) => `终端${direction === "input" ? "输入" : "输出"}拦截器`, + selectMessage: (direction) => `多个插件可以拦截终端${direction === "input" ? "输入" : "输出"}数据。请选择本会话使用的插件。`, + warningTitle: "终端拦截器已停用", + warningMessage: "本会话的一个终端拦截器已被停用。", + warningDetail: "插件失败或超过了数据通道预算。", + }), + "zh-TW": Object.freeze({ + noInterceptor: "不使用攔截器", + selectTitle: (direction) => `終端${direction === "input" ? "輸入" : "輸出"}攔截器`, + selectMessage: (direction) => `多個外掛程式可以攔截終端${direction === "input" ? "輸入" : "輸出"}資料。請選擇本工作階段使用的外掛程式。`, + warningTitle: "終端攔截器已停用", + warningMessage: "本工作階段的一個終端攔截器已被停用。", + warningDetail: "外掛程式失敗或超過資料通道預算。", + }), + ru: Object.freeze({ + noInterceptor: "Без перехватчика", + selectTitle: (direction) => `Перехватчик ${direction === "input" ? "ввода" : "вывода"} терминала`, + selectMessage: (direction) => `Несколько плагинов могут перехватывать ${direction === "input" ? "ввод" : "вывод"} терминала. Выберите один для этого сеанса.`, + warningTitle: "Перехватчик терминала отключён", + warningMessage: "Перехватчик терминала был отключён для этого сеанса.", + warningDetail: "Плагин завершился с ошибкой или превысил бюджет канала данных.", + }), +}); + +function terminalInterceptorMessages(locale) { + return MESSAGES[locale] ?? MESSAGES[String(locale).split("-")[0]] ?? MESSAGES.en; +} + +function terminalInterceptorChoiceLabel(entry) { + const plugin = escapePermissionText( + entry?.pluginDisplayName ?? entry?.pluginId ?? "Plugin", + 160, + ); + const provider = escapePermissionText(entry?.provider?.label ?? entry?.provider?.id ?? "Provider", 160); + const pluginId = escapePermissionText(entry?.pluginId ?? "unknown-plugin", 128); + const providerId = escapePermissionText(entry?.provider?.id ?? "unknown-provider", 192); + return `${plugin} (${pluginId}): ${provider} (${providerId})`; +} + +function terminalInterceptorIdentifier(value) { + return escapePermissionText(value ?? "", 256); +} + +module.exports = { + terminalInterceptorChoiceLabel, + terminalInterceptorIdentifier, + terminalInterceptorMessages, +}; diff --git a/electron/plugins/terminalInterceptorMessages.test.cjs b/electron/plugins/terminalInterceptorMessages.test.cjs new file mode 100644 index 000000000..a921d6856 --- /dev/null +++ b/electron/plugins/terminalInterceptorMessages.test.cjs @@ -0,0 +1,47 @@ +"use strict"; + +const assert = require("node:assert/strict"); +const test = require("node:test"); + +const { + terminalInterceptorChoiceLabel, + terminalInterceptorIdentifier, + terminalInterceptorMessages, +} = require("./terminalInterceptorMessages.cjs"); + +test("terminal interceptor native prompts cover every application locale and fall back to English", () => { + for (const locale of ["en", "zh-CN", "zh-TW", "ru"]) { + const messages = terminalInterceptorMessages(locale); + assert.ok(messages.noInterceptor); + assert.ok(messages.selectTitle("input")); + assert.ok(messages.selectMessage("output")); + assert.ok(messages.warningTitle); + } + assert.equal(terminalInterceptorMessages("fr").noInterceptor, "No interceptor"); +}); + +test("plugin-controlled native selection labels visibly escape control and bidi text", () => { + assert.equal(terminalInterceptorChoiceLabel({ + pluginId: "com.example.safe", + pluginDisplayName: "safe\nname\u202e", + provider: { id: "com.example.input", label: "input\tfilter" }, + }), "safe\\nname\\u202e (com.example.safe): input\\tfilter (com.example.input)"); + assert.equal(terminalInterceptorIdentifier("provider\r\u2066"), "provider\\r\\u2066"); +}); + +test("selection labels keep distinct valid provider identifiers visible in full", () => { + const shared = `com.example.${"a".repeat(170)}`; + const first = terminalInterceptorChoiceLabel({ + pluginId: "com.example", + pluginDisplayName: "Plugin", + provider: { id: `${shared}.first`, label: "Filter" }, + }); + const second = terminalInterceptorChoiceLabel({ + pluginId: "com.example", + pluginDisplayName: "Plugin", + provider: { id: `${shared}.other`, label: "Filter" }, + }); + assert.notEqual(first, second); + assert.match(first, /\.first\)$/u); + assert.match(second, /\.other\)$/u); +}); diff --git a/electron/plugins/terminalInterceptorTransport.cjs b/electron/plugins/terminalInterceptorTransport.cjs new file mode 100644 index 000000000..77cbeb7a4 --- /dev/null +++ b/electron/plugins/terminalInterceptorTransport.cjs @@ -0,0 +1,70 @@ +"use strict"; + +const schema = require("./generated/plugin-contract.schema.json"); +const { assertTerminalInterceptorFrameSchema } = require("./contractValidator.cjs"); + +const limits = schema.$defs.TerminalInterceptorLimits.const; +const TERMINAL_INTERCEPTOR_MAX_CHUNK_BYTES = limits.maxChunkBytes; +const TERMINAL_INTERCEPTOR_MAX_WINDOW_BYTES = limits.maxWindowBytes; +const arrayBufferByteLength = Object.getOwnPropertyDescriptor( + ArrayBuffer.prototype, + "byteLength", +)?.get; + +function copyOwnDataRecord(value, label) { + if (value === null || typeof value !== "object" || Array.isArray(value)) { + throw new TypeError(`${label} must be a plain object`); + } + const copy = {}; + for (const key of Object.keys(value)) { + const descriptor = Object.getOwnPropertyDescriptor(value, key); + if (!descriptor || !("value" in descriptor)) { + throw new TypeError(`${label} must contain data properties only`); + } + copy[key] = descriptor.value; + } + return copy; +} + +function transferredByteLength(value) { + if (!arrayBufferByteLength) throw new TypeError("ArrayBuffer byteLength getter is unavailable"); + try { + const byteLength = arrayBufferByteLength.call(value); + // The intrinsic getter reports zero for a detached zero-length buffer as + // well as for a valid empty buffer. Constructing a view distinguishes the + // two and also works for ArrayBuffers created in another realm. + new Uint8Array(value); + return byteLength; + } catch { + throw new TypeError("Terminal interceptor transfer requires a real, attached ArrayBuffer"); + } +} + +function createTerminalInterceptorEnvelope(frameValue, transfer) { + const frame = copyOwnDataRecord(frameValue, "Terminal interceptor frame"); + assertTerminalInterceptorFrameSchema(frame); + const requiresTransfer = frame.type === "netcatty:terminal-interceptor:chunk" + || (frame.type === "netcatty:terminal-interceptor:result" && frame.status === "ok"); + if (!requiresTransfer) { + if (transfer !== undefined) { + throw new TypeError("This terminal interceptor frame must not include a transferred buffer"); + } + return Object.freeze({ frame: Object.freeze(frame) }); + } + if (transfer === undefined) { + throw new TypeError("This terminal interceptor frame requires a transferred ArrayBuffer"); + } + const byteLength = transferredByteLength(transfer); + if (byteLength !== frame.byteLength) { + throw new RangeError( + `Terminal interceptor byteLength mismatch: declared ${frame.byteLength}, received ${byteLength}`, + ); + } + return Object.freeze({ frame: Object.freeze(frame), transfer }); +} + +module.exports = { + TERMINAL_INTERCEPTOR_MAX_CHUNK_BYTES, + TERMINAL_INTERCEPTOR_MAX_WINDOW_BYTES, + createTerminalInterceptorEnvelope, +}; diff --git a/electron/plugins/terminalInterceptorTransport.test.cjs b/electron/plugins/terminalInterceptorTransport.test.cjs new file mode 100644 index 000000000..6d49a8519 --- /dev/null +++ b/electron/plugins/terminalInterceptorTransport.test.cjs @@ -0,0 +1,124 @@ +"use strict"; + +const assert = require("node:assert/strict"); +const test = require("node:test"); +const { runInNewContext } = require("node:vm"); + +const { + TERMINAL_INTERCEPTOR_MAX_CHUNK_BYTES, + TERMINAL_INTERCEPTOR_MAX_WINDOW_BYTES, + createTerminalInterceptorEnvelope, +} = require("./terminalInterceptorTransport.cjs"); + +test("terminal interceptor envelopes validate canonical ready, chunk, and result frames", () => { + assert.deepEqual(createTerminalInterceptorEnvelope({ + type: "netcatty:terminal-interceptor:ready", + sessionId: "session-1", + direction: "output", + windowBytes: TERMINAL_INTERCEPTOR_MAX_WINDOW_BYTES, + }), { + frame: { + type: "netcatty:terminal-interceptor:ready", + sessionId: "session-1", + direction: "output", + windowBytes: TERMINAL_INTERCEPTOR_MAX_WINDOW_BYTES, + }, + }); + + const chunkData = new Uint8Array([1, 2, 3]).buffer; + const chunk = createTerminalInterceptorEnvelope({ + type: "netcatty:terminal-interceptor:chunk", + sequence: 1, + direction: "input", + creditBytes: TERMINAL_INTERCEPTOR_MAX_CHUNK_BYTES, + byteLength: 3, + }, chunkData); + assert.equal(chunk.transfer, chunkData); + + const resultData = runInNewContext("new Uint8Array([4, 5]).buffer"); + const result = createTerminalInterceptorEnvelope({ + type: "netcatty:terminal-interceptor:result", + sequence: Number.MAX_SAFE_INTEGER, + status: "ok", + creditBytes: 3, + byteLength: 2, + }, resultData); + assert.equal(result.transfer, resultData); + + assert.deepEqual(createTerminalInterceptorEnvelope({ + type: "netcatty:terminal-interceptor:result", + sequence: 2, + status: "failed", + }), { + frame: { + type: "netcatty:terminal-interceptor:result", + sequence: 2, + status: "failed", + }, + }); +}); + +test("terminal interceptor envelopes fail closed on schema or transfer mismatches", () => { + const data = new ArrayBuffer(4); + assert.throws( + () => createTerminalInterceptorEnvelope({ + type: "netcatty:terminal-interceptor:chunk", + sequence: 0, + direction: "input", + creditBytes: 1, + byteLength: 4, + }, data), + /violates the plugin contract/, + ); + assert.throws( + () => createTerminalInterceptorEnvelope({ + type: "netcatty:terminal-interceptor:chunk", + sequence: 1, + direction: "input", + creditBytes: 1, + byteLength: 3, + }, data), + /byteLength mismatch/, + ); + assert.throws( + () => createTerminalInterceptorEnvelope({ + type: "netcatty:terminal-interceptor:result", + sequence: 1, + status: "ok", + creditBytes: 4, + byteLength: 4, + }), + /requires a transferred ArrayBuffer/, + ); + assert.throws( + () => createTerminalInterceptorEnvelope({ + type: "netcatty:terminal-interceptor:ready", + sessionId: "session-1", + direction: "input", + windowBytes: TERMINAL_INTERCEPTOR_MAX_CHUNK_BYTES, + extra: true, + }), + /violates the plugin contract/, + ); + assert.throws( + () => createTerminalInterceptorEnvelope({ + type: "netcatty:terminal-interceptor:result", + sequence: 1, + status: "failed", + }, data), + /must not include a transferred buffer/, + ); + + const detached = new ArrayBuffer(0); + structuredClone(detached, { transfer: [detached] }); + assert.throws( + () => createTerminalInterceptorEnvelope({ + type: "netcatty:terminal-interceptor:chunk", + sequence: 1, + direction: "input", + creditBytes: 1, + byteLength: 0, + }, detached), + /requires a real, attached ArrayBuffer/, + ); +}); diff --git a/electron/plugins/utilityPluginRuntime.cjs b/electron/plugins/utilityPluginRuntime.cjs index f407e1baa..7abe63c80 100644 --- a/electron/plugins/utilityPluginRuntime.cjs +++ b/electron/plugins/utilityPluginRuntime.cjs @@ -11,6 +11,10 @@ const { PLUGIN_UTILITY_TERMINATION_GRACE_MS, } = require("./constants.cjs"); const { PluginRpcRouter } = require("./rpcRouter.cjs"); +const { + assertTerminalInterceptorAttachmentParams, + assertTerminalInterceptorAttachmentResult, +} = require("./contractValidator.cjs"); const { isPathInside } = require("./paths.cjs"); const PLUGIN_CONTAINMENT_ERROR_CODE = "ERR_PLUGIN_RUNTIME_CONTAINMENT_FAILED"; @@ -209,6 +213,20 @@ class UtilityPluginRuntime { return this.router.streams.openOutgoing(streamId, windowBytes); } + attachTerminalInterceptor(descriptor, port) { + if (!this.router) throw new Error("Plugin utility runtime is not connected"); + if (!port) throw new TypeError("Terminal interceptor port is required"); + const params = assertTerminalInterceptorAttachmentParams({ descriptor }); + return this.router.request("plugin.terminal.interceptor.attach", params, { + timeoutMs: PLUGIN_ACTIVATION_TIMEOUT_MS, + transfer: [port], + validateResult(result) { + assertTerminalInterceptorAttachmentResult(result); + return undefined; + }, + }); + } + getProcessId() { return this.child?.pid ?? null; } @@ -275,6 +293,7 @@ class UtilityPluginRuntime { router?.close(error); this.onExit({ expected: false, error }); } + } module.exports = { diff --git a/electron/plugins/utilityPluginRuntime.test.cjs b/electron/plugins/utilityPluginRuntime.test.cjs index 7eb3cea59..4feffc79d 100644 --- a/electron/plugins/utilityPluginRuntime.test.cjs +++ b/electron/plugins/utilityPluginRuntime.test.cjs @@ -9,6 +9,82 @@ const { EventEmitter } = require("node:events"); const { UtilityPluginRuntime, resolveUtilityEntrypoint } = require("./utilityPluginRuntime.cjs"); +test("utility runtime waits for acceptance of a dedicated terminal interceptor port", async () => { + const requests = []; + const runtime = new UtilityPluginRuntime({ + utilityProcess: {}, + plugin: { id: "com.example", manifest: { main: { node: "dist/index.js" } } }, + packageRoot: "/tmp/plugin", + bootstrapPath: "/runtime.mjs", + moduleMappings: {}, + }); + runtime.router = { + request(method, params, options) { + requests.push({ method, params, options }); + return Promise.resolve(options.validateResult({ accepted: true })); + }, + }; + const port = { close() {} }; + await runtime.attachTerminalInterceptor( + { + providerId: "com.example.input", + direction: "input", + session: { sessionId: "session-1", protocol: "ssh", status: "connected" }, + }, + port, + ); + assert.equal(requests[0].method, "plugin.terminal.interceptor.attach"); + assert.deepEqual(requests[0].params, { + descriptor: { + providerId: "com.example.input", + direction: "input", + session: { sessionId: "session-1", protocol: "ssh", status: "connected" }, + }, + }); + assert.deepEqual(requests[0].options.transfer, [port]); + assert.equal(requests[0].options.timeoutMs > 0, true); +}); + +test("utility runtime validates terminal attachment params and results against the canonical contract", async () => { + const runtime = new UtilityPluginRuntime({ + utilityProcess: {}, + plugin: { id: "com.example", manifest: { main: { node: "dist/index.js" } } }, + packageRoot: "/tmp/plugin", + bootstrapPath: "/runtime.mjs", + moduleMappings: {}, + }); + let requests = 0; + runtime.router = { + request(_method, _params, options) { + requests += 1; + return Promise.resolve().then(() => ( + options.validateResult({ accepted: true, unexpected: true }) + )); + }, + }; + const port = { close() {} }; + assert.throws( + () => runtime.attachTerminalInterceptor( + { providerId: "com.example.input", direction: "input", session: { sessionId: "session-1" } }, + port, + ), + /attachment params violates the plugin contract/, + ); + assert.equal(requests, 0); + await assert.rejects( + runtime.attachTerminalInterceptor( + { + providerId: "com.example.input", + direction: "input", + session: { sessionId: "session-1", protocol: "ssh", status: "connected" }, + }, + port, + ), + /attachment result violates the plugin contract/, + ); + assert.equal(requests, 1); +}); + test("utility entrypoint is realpath-contained at the moment of launch", async (context) => { const root = fs.mkdtempSync(path.join(os.tmpdir(), "netcatty-plugin-utility-entry-")); context.after(() => fs.rmSync(root, { recursive: true, force: true })); @@ -63,6 +139,12 @@ test("utility runtime launches without a shell using a minimal environment", asy })); } else if (message.method === "plugin.activate") { queueMicrotask(() => this.emit("message", { jsonrpc: "2.0", id: message.id, result: null })); + } else if (message.method === "plugin.terminal.interceptor.attach") { + queueMicrotask(() => this.emit("message", { + jsonrpc: "2.0", + id: message.id, + result: { accepted: true }, + })); } } kill() { return true; } @@ -103,6 +185,16 @@ test("utility runtime launches without a shell using a minimal environment", asy assert.deepEqual(messages.find((message) => message.method === "plugin.activate").params, { environment: { locale: "zh-CN", theme: "dark" }, }); + const interceptorPort = { close() {} }; + await runtime.attachTerminalInterceptor( + { + providerId: "com.example.input", + direction: "input", + session: { sessionId: "session-1", protocol: "ssh", status: "connected" }, + }, + interceptorPort, + ); + assert.deepEqual(transferLists.at(-1), [interceptorPort]); const transferable = new ArrayBuffer(8); runtime.router.send({ type: "transfer-test", transferable }, [transferable]); assert.deepEqual(transferLists.at(-1), [transferable]); diff --git a/electron/preload.cjs b/electron/preload.cjs index 66a9a432d..e35752cb2 100644 --- a/electron/preload.cjs +++ b/electron/preload.cjs @@ -7,6 +7,7 @@ const { clearTerminalDataSession, createTerminalDataBacklog, createTerminalDataDispatcher, + hasPluginPipelineIngress, } = require("./preload/terminalDataBacklog.cjs"); const { createTerminalOutputPortRegistry, @@ -100,6 +101,7 @@ function filterMcpChunk(sessionId, chunk, meta) { // Prepend any buffered fragment from the previous chunk const held = _mcpLineBufs.get(sessionId) || ""; const heldMeta = _mcpLineMetas.get(sessionId); + const heldIngressAlreadyAcknowledged = heldMeta?.pluginPipelineIngressBytes === 0; const pendingMeta = _mcpPendingMetas.get(sessionId); const stateMeta = mergeTerminalDataMeta(mergeTerminalDataMeta(pendingMeta, heldMeta), meta); const sameChunkMeta = mergeTerminalDataMeta(mergeTerminalDataMeta(pendingMeta, heldMeta), meta, { @@ -112,7 +114,18 @@ function filterMcpChunk(sessionId, chunk, meta) { // Fast path: nothing suspicious in the combined data if (!_mcpDroppingWrappedLine.has(sessionId) && !data.includes("__NCMCP_") && !_endsWithMarkerPrefix(data)) { - return { data, meta: held ? stateMeta : sameChunkMeta }; + const deliveryMeta = held ? stateMeta : sameChunkMeta; + return { + data, + meta: heldIngressAlreadyAcknowledged + ? { + ...(deliveryMeta || {}), + pluginPipelineIngressBytes: Number.isFinite(meta?.pluginPipelineIngressBytes) + ? Math.max(0, Number(meta.pluginPipelineIngressBytes)) + : chunk.length, + } + : deliveryMeta, + }; } // Slow path: scan line by line @@ -130,7 +143,10 @@ function filterMcpChunk(sessionId, chunk, meta) { const tail = data.slice(pos); if (droppedAny || tail.includes("__NCMCP_") || _endsWithMarkerPrefix(tail)) { _mcpLineBufs.set(sessionId, tail); - const tailMeta = !held && tail === chunk ? sameChunkMeta : stateMeta; + let tailMeta = !held && tail === chunk ? sameChunkMeta : stateMeta; + if (heldIngressAlreadyAcknowledged && !hasPluginPipelineIngress(tailMeta)) { + tailMeta = { ...(tailMeta || {}), pluginPipelineIngressBytes: 0 }; + } if (tailMeta) _mcpLineMetas.set(sessionId, tailMeta); if (droppedAny) _mcpDroppingWrappedLine.add(sessionId); } else { @@ -148,7 +164,26 @@ function filterMcpChunk(sessionId, chunk, meta) { pos = nlIdx + 1; } - return { data: result, meta: !held && result === chunk ? sameChunkMeta : stateMeta }; + const deliveryMeta = !held && result === chunk ? sameChunkMeta : stateMeta; + return { + data: result, + meta: heldIngressAlreadyAcknowledged + ? { + ...(deliveryMeta || {}), + pluginPipelineIngressBytes: Number.isFinite(meta?.pluginPipelineIngressBytes) + ? Math.max(0, Number(meta.pluginPipelineIngressBytes)) + : chunk.length, + } + : deliveryMeta, + }; +} + +function consumeBufferedMcpIngress(sessionId) { + const heldMeta = _mcpLineMetas.get(sessionId); + if (!hasPluginPipelineIngress(heldMeta)) return; + // Retain an explicit zero so a later safe flush does not fall back to the + // visible chunk length and acknowledge the already-credited prefix twice. + _mcpLineMetas.set(sessionId, { ...heldMeta, pluginPipelineIngressBytes: 0 }); } /** @@ -176,9 +211,13 @@ function flushMcpBufferedOutput(sessionId) { return; } if (held) { - _deliverToListeners(sessionId, held, mergeTerminalDataMeta(_mcpPendingMetas.get(sessionId), heldMeta, { + let deliveryMeta = mergeTerminalDataMeta(_mcpPendingMetas.get(sessionId), heldMeta, { preserveTerminalPerf: true, - })); + }); + if (heldMeta?.pluginPipelineIngressBytes === 0 && !hasPluginPipelineIngress(deliveryMeta)) { + deliveryMeta = { ...(deliveryMeta || {}), pluginPipelineIngressBytes: 0 }; + } + _deliverToListeners(sessionId, held, deliveryMeta); _mcpPendingMetas.delete(sessionId); } } @@ -189,8 +228,12 @@ function scheduleMcpBufferedFlush(sessionId) { } function deliverTerminalData(sessionId, data, options = {}) { - if (!sessionId || !data) return; + if (!sessionId || (!data && !hasPluginPipelineIngress(options.meta))) return; if (closedTerminalDataSessions.has(sessionId)) return; + if (!data) { + _deliverToListeners(sessionId, "", options.meta); + return; + } if (options.syntheticEcho) { _deliverToListeners(sessionId, data, options.meta); return; @@ -198,8 +241,17 @@ function deliverTerminalData(sessionId, data, options = {}) { const filtered = filterMcpChunk(sessionId, data, options.meta); if (filtered?.data) { _deliverToListeners(sessionId, filtered.data, filtered.meta); + if (hasPluginPipelineIngress(filtered.meta)) consumeBufferedMcpIngress(sessionId); } else if (filtered?.meta) { - _mcpPendingMetas.set(sessionId, mergeTerminalDataMeta(_mcpPendingMetas.get(sessionId), filtered.meta)); + if (hasPluginPipelineIngress(filtered.meta)) { + // The legacy path must return flow credit even when MCP marker filtering + // removes every display byte. Waiting for unrelated visible output can + // otherwise leave a fully suppressed stream paused indefinitely. + _deliverToListeners(sessionId, "", filtered.meta); + consumeBufferedMcpIngress(sessionId); + } else { + _mcpPendingMetas.set(sessionId, mergeTerminalDataMeta(_mcpPendingMetas.get(sessionId), filtered.meta)); + } } // If there is buffered content waiting for more data (e.g. a prompt // right after a dropped marker line), schedule a delayed flush so it @@ -214,7 +266,13 @@ const terminalOutputPorts = createTerminalOutputPortRegistry({ filterData(sessionId, data, message) { if (message?.syntheticEcho) return data; const filtered = filterMcpChunk(sessionId, data, message.meta); - if (!filtered?.data && filtered?.meta) { + // Metadata-only plugin output is delivered immediately by the output-port + // registry so renderer flow credit can be returned. Do not retain the same + // ingress metadata for the next visible chunk or it would be acknowledged + // twice. Non-ingress terminal-state metadata still follows the next output. + if (hasPluginPipelineIngress(filtered?.meta)) { + consumeBufferedMcpIngress(sessionId); + } else if (!filtered?.data && filtered?.meta) { _mcpPendingMetas.set(sessionId, mergeTerminalDataMeta(_mcpPendingMetas.get(sessionId), filtered.meta)); } scheduleMcpBufferedFlush(sessionId); diff --git a/electron/preload/api.cjs b/electron/preload/api.cjs index 72474340f..871dfe2dc 100644 --- a/electron/preload/api.cjs +++ b/electron/preload/api.cjs @@ -199,6 +199,7 @@ function createPreloadApi(ctx) { sessionId, data, automated: Boolean(options?.automated), + sensitive: options?.sensitive === true, lineDelayMs: Number.isFinite(lineDelayMs) && lineDelayMs > 0 ? lineDelayMs : undefined, logRewrite: options?.logRewrite && typeof options.logRewrite === "object" ? { @@ -382,6 +383,9 @@ function createPreloadApi(ctx) { snapshot, kittyKeyboardModeState, kittyKeyboardProtocolEnabled, + passwordPromptActive, + cwd, + title, ) => { ipcRenderer.send("netcatty:terminal:snapshot-response", { requestId, @@ -390,6 +394,11 @@ function createPreloadApi(ctx) { kittyKeyboardProtocolEnabled: typeof kittyKeyboardProtocolEnabled === "boolean" ? kittyKeyboardProtocolEnabled : undefined, + passwordPromptActive: typeof passwordPromptActive === "boolean" + ? passwordPromptActive + : undefined, + cwd: cwd === null ? null : typeof cwd === "string" ? cwd : undefined, + title: title === null ? null : typeof title === "string" ? title : undefined, }); }, applyTerminalSessionSnapshot: (sessionId, snapshot, context, authorization) => @@ -408,6 +417,11 @@ function createPreloadApi(ctx) { kittyKeyboardProtocolEnabled: typeof context?.kittyKeyboardProtocolEnabled === "boolean" ? context.kittyKeyboardProtocolEnabled : undefined, + passwordPromptActive: typeof context?.passwordPromptActive === "boolean" + ? context.passwordPromptActive + : undefined, + cwd: context?.cwd === null ? null : typeof context?.cwd === "string" ? context.cwd : undefined, + title: context?.title === null ? null : typeof context?.title === "string" ? context.title : undefined, authorization, }), markAttachPopupClosePrepared: (sessionId, authorization) => @@ -487,7 +501,7 @@ function createPreloadApi(ctx) { displayDataListeners.get(sessionId).add(cb); const pendingEntry = terminalDataBacklog?.takeEntry?.(sessionId) ?? { data: terminalDataBacklog?.take?.(sessionId) || "", meta: undefined }; - if (pendingEntry.data) { + if (pendingEntry.data || Number(pendingEntry.meta?.pluginPipelineIngressBytes) > 0) { try { cb(pendingEntry.data, pendingEntry.meta); } catch (err) { diff --git a/electron/preload/terminalDataBacklog.cjs b/electron/preload/terminalDataBacklog.cjs index a5df1bf03..68011262f 100644 --- a/electron/preload/terminalDataBacklog.cjs +++ b/electron/preload/terminalDataBacklog.cjs @@ -2,6 +2,11 @@ const { mergeTerminalDataMeta } = require("./terminalDataMeta.cjs"); +function hasPluginPipelineIngress(meta) { + return Number.isFinite(meta?.pluginPipelineIngressBytes) + && Number(meta.pluginPipelineIngressBytes) > 0; +} + function createTerminalDataBacklog(options = {}) { const maxBytesPerSession = options.maxBytesPerSession ?? 64 * 1024; const pendingBySession = new Map(); @@ -12,11 +17,32 @@ function createTerminalDataBacklog(options = {}) { } function append(sessionId, data, meta) { - if (!sessionId || !data) return; + if (!sessionId || (!data && !hasPluginPipelineIngress(meta))) return; const previous = pendingBySession.get(sessionId) || { data: "", meta: undefined }; const nextData = trimToLimit(previous.data + data); const preserveTerminalPerf = previous.data.length === 0 && nextData === data; - const nextMeta = mergeTerminalDataMeta(previous.meta, meta, { preserveTerminalPerf }); + let previousMeta = previous.meta; + let nextChunkMeta = meta; + const previousHasIngress = Number.isFinite(previousMeta?.pluginPipelineIngressBytes); + const nextChunkHasIngress = Number.isFinite(nextChunkMeta?.pluginPipelineIngressBytes); + // Once one merged chunk carries explicit original-ingress accounting, the + // metadata must cover every raw flow unit in the same replay entry. Flow + // control is intentionally charged in JavaScript string length, not UTF-8 + // bytes, throughout the terminal renderer/worker path. Otherwise a + // processed chunk followed or preceded by ordinary output would cause the + // renderer to acknowledge only the annotated subset. + if (previousHasIngress && !nextChunkHasIngress && data) { + nextChunkMeta = { + ...(nextChunkMeta || {}), + pluginPipelineIngressBytes: data.length, + }; + } else if (!previousHasIngress && nextChunkHasIngress && previous.data) { + previousMeta = { + ...(previousMeta || {}), + pluginPipelineIngressBytes: previous.data.length, + }; + } + const nextMeta = mergeTerminalDataMeta(previousMeta, nextChunkMeta, { preserveTerminalPerf }); pendingBySession.set(sessionId, { data: nextData, meta: nextMeta, @@ -62,7 +88,7 @@ function createTerminalDataDispatcher({ shouldDropSession = () => false, }) { return function deliverToListeners(sessionId, data, meta) { - if (!data) return; + if (!data && !hasPluginPipelineIngress(meta)) return; if (shouldDropSession(sessionId)) return; if (!hasSessionListeners(displayDataListeners, sessionId)) { @@ -103,4 +129,5 @@ module.exports = { createTerminalDataBacklog, createTerminalDataDispatcher, clearTerminalDataSession, + hasPluginPipelineIngress, }; diff --git a/electron/preload/terminalDataMeta.cjs b/electron/preload/terminalDataMeta.cjs index 1b5354227..db6d24467 100644 --- a/electron/preload/terminalDataMeta.cjs +++ b/electron/preload/terminalDataMeta.cjs @@ -26,6 +26,25 @@ function mergeTerminalDataMeta(first, second, options = {}) { const droppedOutputAlternateScreenAction = second?.droppedOutputMayAffectTerminalState ? second?.droppedOutputAlternateScreenAction : (second?.droppedOutputAlternateScreenAction ?? first?.droppedOutputAlternateScreenAction); + const firstHasPluginPipelineIngress = Number.isFinite(first?.pluginPipelineIngressBytes); + const secondHasPluginPipelineIngress = Number.isFinite(second?.pluginPipelineIngressBytes); + const pluginPipelineIngressBytes = Math.max( + 0, + Number(first?.pluginPipelineIngressBytes ?? 0) + + Number(second?.pluginPipelineIngressBytes ?? 0), + ); + + if (typeof second?.pluginPipelineSensitiveInput === "boolean") { + merged.pluginPipelineSensitiveInput = second.pluginPipelineSensitiveInput; + } else { + delete merged.pluginPipelineSensitiveInput; + } + + if (second?.pluginPipelineProcessed === true) { + merged.pluginPipelineProcessed = true; + } else { + delete merged.pluginPipelineProcessed; + } if (droppedOutputMayAffectTerminalState) { merged.droppedOutputMayAffectTerminalState = true; @@ -39,6 +58,12 @@ function mergeTerminalDataMeta(first, second, options = {}) { delete merged.droppedOutputAlternateScreenAction; } + if (firstHasPluginPipelineIngress || secondHasPluginPipelineIngress) { + merged.pluginPipelineIngressBytes = pluginPipelineIngressBytes; + } else { + delete merged.pluginPipelineIngressBytes; + } + if (options.preserveTerminalPerf !== true) { delete merged.terminalPerf; } diff --git a/electron/preload/terminalOutputPorts.cjs b/electron/preload/terminalOutputPorts.cjs index 4286decfb..a1eb6f7c9 100644 --- a/electron/preload/terminalOutputPorts.cjs +++ b/electron/preload/terminalOutputPorts.cjs @@ -1,6 +1,7 @@ "use strict"; const { TERMINAL_OUTPUT_PORT_CHANNEL } = require("../bridges/terminalOutputChannel.cjs"); +const { hasPluginPipelineIngress } = require("./terminalDataBacklog.cjs"); function createTerminalOutputPortRegistry(options = {}) { const { @@ -36,7 +37,7 @@ function createTerminalOutputPortRegistry(options = {}) { return; } if (closedTerminalDataSessions.has(targetSessionId)) return; - if (!message.data) return; + if (!message.data && !hasPluginPipelineIngress(message.meta)) return; try { const filtered = typeof filterData === "function" ? filterData(targetSessionId, message.data, message) @@ -47,7 +48,9 @@ function createTerminalOutputPortRegistry(options = {}) { const meta = filtered && typeof filtered === "object" && "data" in filtered ? filtered.meta : message.meta; - if (data) deliverToListeners?.(targetSessionId, data, meta); + if (data || hasPluginPipelineIngress(meta)) { + deliverToListeners?.(targetSessionId, data ?? "", meta); + } } catch (err) { onPortError("Terminal output port callback failed", err); } diff --git a/electron/preloadDataBacklog.test.cjs b/electron/preloadDataBacklog.test.cjs index 9ca933afb..33d4d6114 100644 --- a/electron/preloadDataBacklog.test.cjs +++ b/electron/preloadDataBacklog.test.cjs @@ -163,6 +163,78 @@ test("drops terminal perf metadata after backlog data is merged or trimmed", () }); }); +test("sums original plugin-pipeline ingress counts when display chunks are merged", () => { + const backlog = createTerminalDataBacklog({ maxBytesPerSession: 8 }); + backlog.append("session-1", "expanded", { pluginPipelineIngressBytes: 3 }); + backlog.append("session-1", "!", { pluginPipelineIngressBytes: 2 }); + assert.deepEqual(backlog.takeEntry("session-1"), { + data: "xpanded!", + meta: { pluginPipelineIngressBytes: 5 }, + }); +}); + +test("mixed processed and raw backlog uses the renderer flow-control unit", () => { + const processedThenRaw = createTerminalDataBacklog({ maxBytesPerSession: 64 }); + processedThenRaw.append("session-1", "expanded", { pluginPipelineIngressBytes: 3 }); + processedThenRaw.append("session-1", "普通"); + assert.deepEqual(processedThenRaw.takeEntry("session-1"), { + data: "expanded普通", + meta: { pluginPipelineIngressBytes: 5 }, + }); + + const rawThenProcessed = createTerminalDataBacklog({ maxBytesPerSession: 64 }); + rawThenProcessed.append("session-1", "普通"); + rawThenProcessed.append("session-1", "expanded", { pluginPipelineIngressBytes: 3 }); + assert.deepEqual(rawThenProcessed.takeEntry("session-1"), { + data: "普通expanded", + meta: { pluginPipelineIngressBytes: 5 }, + }); +}); + +test("backlog preserves already-acknowledged replay state and charges only later raw data", () => { + const backlog = createTerminalDataBacklog({ maxBytesPerSession: 64 }); + backlog.append("session-1", "prompt __NCM", { pluginPipelineIngressBytes: 0 }); + assert.deepEqual(backlog.takeEntry("session-1"), { + data: "prompt __NCM", + meta: { pluginPipelineIngressBytes: 0 }, + }); + + backlog.append("session-1", "prompt __NCM", { pluginPipelineIngressBytes: 0 }); + backlog.append("session-1", "普通"); + assert.deepEqual(backlog.takeEntry("session-1"), { + data: "prompt __NCM普通", + meta: { pluginPipelineIngressBytes: 2 }, + }); +}); + +test("sensitive prompt metadata follows the latest merged output chunk", () => { + const backlog = createTerminalDataBacklog({ maxBytesPerSession: 64 }); + backlog.append("session-1", "Password: ", { + pluginPipelineIngressBytes: 10, + pluginPipelineSensitiveInput: true, + }); + backlog.append("session-1", "user@host$ ", { + pluginPipelineIngressBytes: 11, + pluginPipelineSensitiveInput: false, + }); + assert.deepEqual(backlog.takeEntry("session-1"), { + data: "Password: user@host$ ", + meta: { + pluginPipelineIngressBytes: 21, + pluginPipelineSensitiveInput: false, + }, + }); +}); + +test("retains metadata-only plugin output so suppressed data can still be acknowledged", () => { + const backlog = createTerminalDataBacklog(); + backlog.append("session-1", "", { pluginPipelineIngressBytes: 9 }); + assert.deepEqual(backlog.takeEntry("session-1"), { + data: "", + meta: { pluginPipelineIngressBytes: 9 }, + }); +}); + test("keeps latest alternate-screen metadata while trimming backlog data", () => { const backlog = createTerminalDataBacklog({ maxBytesPerSession: 5 }); @@ -300,6 +372,28 @@ test("onSessionData replays pending terminal data metadata on subscribe", () => }]); }); +test("onSessionData replays metadata-only plugin output on subscribe", () => { + const dataListeners = new Map(); + const displayDataListeners = new Map(); + const terminalDataBacklog = createTerminalDataBacklog(); + terminalDataBacklog.append("session-1", "", { pluginPipelineIngressBytes: 7 }); + const api = createPreloadApi({ + ipcRenderer: { invoke() {}, send() {}, on() {}, removeListener() {} }, + os: { release: () => "10.0.19045" }, + dataListeners, + displayDataListeners, + terminalDataBacklog, + }); + const received = []; + api.onSessionData("session-1", (chunk, meta) => received.push({ chunk, meta }), { + replayBacklog: true, + }); + assert.deepEqual(received, [{ + chunk: "", + meta: { pluginPipelineIngressBytes: 7 }, + }]); +}); + test("legacy terminal data delivery preserves terminal perf metadata", () => { const preload = loadPreloadWithFakeElectron(); try { @@ -324,6 +418,50 @@ test("legacy terminal data delivery preserves terminal perf metadata", () => { } }); +test("legacy terminal data delivery preserves metadata-only plugin output", () => { + const preload = loadPreloadWithFakeElectron(); + try { + const received = []; + preload.api.onSessionData("session-1", (chunk, meta) => received.push({ chunk, meta })); + + preload.handlers.get("netcatty:data")?.({}, { + sessionId: "session-1", + data: "", + meta: { pluginPipelineIngressBytes: 11 }, + }); + + assert.deepEqual(received, [{ + chunk: "", + meta: { pluginPipelineIngressBytes: 11 }, + }]); + } finally { + preload.cleanup(); + } +}); + +test("legacy MCP-filtered plugin output returns ingress credit immediately", () => { + const preload = loadPreloadWithFakeElectron(); + try { + const received = []; + preload.api.onSessionData("session-1", (chunk, meta) => received.push({ chunk, meta })); + preload.handlers.get("netcatty:data")?.({}, { + sessionId: "session-1", + data: "__NCMCP_TEST", + meta: { pluginPipelineIngressBytes: 13 }, + }); + preload.handlers.get("netcatty:data")?.({}, { + sessionId: "session-1", + data: "\nREADY\n", + }); + assert.deepEqual(received, [ + { chunk: "", meta: { pluginPipelineIngressBytes: 13 } }, + { chunk: "READY\n", meta: { pluginPipelineIngressBytes: 7 } }, + ]); + } finally { + preload.cleanup(); + } +}); + test("terminal output port delivery preserves terminal perf metadata", () => { const preload = loadPreloadWithFakeElectron(); try { @@ -350,6 +488,58 @@ test("terminal output port delivery preserves terminal perf metadata", () => { } }); +test("terminal output port delivers metadata-only plugin output for flow acknowledgement", () => { + const preload = loadPreloadWithFakeElectron(); + try { + const received = []; + const port = createFakePort(); + preload.api.onSessionData("session-1", (chunk, meta) => received.push({ chunk, meta })); + preload.handlers.get("netcatty:terminal-output-port")?.( + { ports: [port] }, + { sessionId: "session-1" }, + ); + port.emit({ + sessionId: "session-1", + data: "", + meta: { pluginPipelineIngressBytes: 11 }, + }); + assert.deepEqual(received, [{ + chunk: "", + meta: { pluginPipelineIngressBytes: 11 }, + }]); + } finally { + preload.cleanup(); + } +}); + +test("MCP-filtered metadata-only plugin output is not applied to the next visible chunk", () => { + const preload = loadPreloadWithFakeElectron(); + try { + const received = []; + const port = createFakePort(); + preload.api.onSessionData("session-1", (chunk, meta) => received.push({ chunk, meta })); + preload.handlers.get("netcatty:terminal-output-port")?.( + { ports: [port] }, + { sessionId: "session-1" }, + ); + port.emit({ + sessionId: "session-1", + data: "__NCMCP_TEST", + meta: { pluginPipelineIngressBytes: 13 }, + }); + port.emit({ + sessionId: "session-1", + data: "\nREADY\n", + }); + assert.deepEqual(received, [ + { chunk: "", meta: { pluginPipelineIngressBytes: 13 } }, + { chunk: "READY\n", meta: { pluginPipelineIngressBytes: 7 } }, + ]); + } finally { + preload.cleanup(); + } +}); + test("MCP-filtered terminal perf metadata is not carried to later output", () => { const preload = loadPreloadWithFakeElectron(); try { @@ -403,6 +593,59 @@ test("delayed MCP terminal data flush preserves metadata", async () => { } }); +test("already-acknowledged MCP prefix flushes visible text with explicit zero credit", async () => { + const preload = loadPreloadWithFakeElectron(); + try { + const received = []; + preload.api.onSessionData("session-1", (chunk, meta) => { + received.push({ chunk, meta }); + }); + + preload.handlers.get("netcatty:data")?.({}, { + sessionId: "session-1", + data: "prompt __NCM", + meta: { pluginPipelineIngressBytes: 13 }, + }); + + assert.deepEqual(received, [{ + chunk: "", + meta: { pluginPipelineIngressBytes: 13 }, + }]); + await sleep(100); + + assert.deepEqual(received, [ + { chunk: "", meta: { pluginPipelineIngressBytes: 13 } }, + { chunk: "prompt __NCM", meta: { pluginPipelineIngressBytes: 0 } }, + ]); + } finally { + preload.cleanup(); + } +}); + +test("already-acknowledged MCP prefix charges only a later safe continuation", () => { + const preload = loadPreloadWithFakeElectron(); + try { + const received = []; + preload.api.onSessionData("session-1", (chunk, meta) => received.push({ chunk, meta })); + preload.handlers.get("netcatty:data")?.({}, { + sessionId: "session-1", + data: "prompt __NCM", + meta: { pluginPipelineIngressBytes: 13 }, + }); + preload.handlers.get("netcatty:data")?.({}, { + sessionId: "session-1", + data: "X\n", + }); + + assert.deepEqual(received, [ + { chunk: "", meta: { pluginPipelineIngressBytes: 13 } }, + { chunk: "prompt __NCMX\n", meta: { pluginPipelineIngressBytes: 2 } }, + ]); + } finally { + preload.cleanup(); + } +}); + test("MCP-filtered empty terminal data carries metadata to next visible output", () => { const preload = loadPreloadWithFakeElectron(); try { diff --git a/electron/scripts/scriptCodegen.cjs b/electron/scripts/scriptCodegen.cjs index 4952d7d54..26b697136 100644 --- a/electron/scripts/scriptCodegen.cjs +++ b/electron/scripts/scriptCodegen.cjs @@ -18,8 +18,8 @@ function stepsToJavaScript(steps, recordedAt) { const step = steps[index]; if (step.type === "send") { if (step.sensitive) { - lines.push(` const sensitiveValue${index} = await nct.dialog.prompt("Enter sensitive value", "");`); - lines.push(` await nct.screen.sendLine(sensitiveValue${index});`); + lines.push(` const sensitiveValue${index} = await nct.dialog.prompt("Enter sensitive value", "", { sensitive: true });`); + lines.push(` await nct.screen.sendLine(sensitiveValue${index}, { sensitive: true });`); continue; } lines.push(` await nct.screen.sendLine(${escapeJsString(step.value)});`); diff --git a/electron/scripts/scriptRuntime.cjs b/electron/scripts/scriptRuntime.cjs index 1f84aa384..06f791783 100644 --- a/electron/scripts/scriptRuntime.cjs +++ b/electron/scripts/scriptRuntime.cjs @@ -608,27 +608,31 @@ function createScriptRuntime(deps) { }; const screenApi = { - send(text) { + send(text, options = {}) { return markHandled(ignoreIfStopped(async () => { if (deps.isAborted?.()) return; assertWriteAllowed("screen.send"); await waitIfPaused(); const payload = String(text ?? ""); - await trackStep(`send: ${truncateActivityLabel(formatScriptInputForLog(payload), 60)}`); + const sensitive = options?.sensitive === true; + const visiblePayload = sensitive ? "[sensitive]" : formatScriptInputForLog(payload); + await trackStep(`send: ${truncateActivityLabel(visiblePayload, 60)}`); if (deps.isAborted?.()) return; - appendLog(runId, `→ ${formatScriptInputForLog(payload)}`); - writeToSession(sessionId, payload, { automated: true }); + appendLog(runId, `→ ${visiblePayload}`); + writeToSession(sessionId, payload, { automated: true, sensitive }); })); }, - sendLine(text) { + sendLine(text, options = {}) { return markHandled(ignoreIfStopped(async () => { if (deps.isAborted?.()) return; assertWriteAllowed("screen.sendLine"); await waitIfPaused(); const line = String(text ?? ""); - await trackStep(`sendLine: ${truncateActivityLabel(line, 60)}`); + const sensitive = options?.sensitive === true; + const visibleLine = sensitive ? "[sensitive]" : line; + await trackStep(`sendLine: ${truncateActivityLabel(visibleLine, 60)}`); if (deps.isAborted?.()) return; - appendLog(runId, `→ ${line}`); + appendLog(runId, `→ ${visibleLine}`); // Bastion menus can ignore a single "line\r" packet even when // stream.write succeeds. Match xterm: body, then Enter (#1960). // Consume only pre-send buffer length so prompts that arrive between @@ -638,6 +642,7 @@ function createScriptRuntime(deps) { if (line.length > 0) { writeToSession(sessionId, line, { automated: true, + sensitive, invalidateStartupSeed: false, }); await interruptibleSleep(30, deps.isAborted); @@ -645,6 +650,7 @@ function createScriptRuntime(deps) { } writeToSession(sessionId, "\r", { automated: true, + sensitive, invalidateStartupSeed: false, }); buffer.consumeThroughAbsolute(lengthBeforeSend); @@ -713,9 +719,14 @@ function createScriptRuntime(deps) { assertNotAborted(); return markHandled(showDialog("confirm", String(message ?? ""))); }, - prompt(message, defaultValue = "") { + prompt(message, defaultValue = "", options = {}) { assertNotAborted(); - return markHandled(showDialog("prompt", String(message ?? ""), String(defaultValue ?? ""))); + return markHandled(showDialog( + "prompt", + String(message ?? ""), + String(defaultValue ?? ""), + { sensitive: options?.sensitive === true }, + )); }, form(spec) { assertNotAborted(); diff --git a/electron/scripts/scriptRuntime.test.cjs b/electron/scripts/scriptRuntime.test.cjs index fb4eedd2e..7fcd28465 100644 --- a/electron/scripts/scriptRuntime.test.cjs +++ b/electron/scripts/scriptRuntime.test.cjs @@ -89,6 +89,51 @@ test("createScriptRuntime executes simple log script", async () => { assert.deepEqual(logs, ["hello"]); }); +test("sensitive script input is masked in UI and logs and remains host-bypassed", async () => { + const logs = []; + const writes = []; + const dialogs = []; + const runtime = createScriptRuntime({ + sessionId: "s1", + runId: "r-sensitive", + appendLog: (_id, message) => logs.push(message), + writeToSession: (sessionId, data, options) => writes.push({ sessionId, data, options }), + getOutputBuffer: () => ({ + getText: () => "", + consumeThroughAbsolute() {}, + }), + getSessionMeta: () => ({ connected: true, hostname: "host", username: "user" }), + showDialog: async (...args) => { + dialogs.push(args); + return "super-secret"; + }, + isPaused: () => false, + isAborted: () => false, + onStatusChange: () => {}, + }); + + await runtime.execute(` + const value = await nct.dialog.prompt("Secret", "", { sensitive: true }); + await nct.screen.sendLine(value, { sensitive: true }); + `); + + assert.deepEqual(dialogs[0], ["prompt", "Secret", "", { sensitive: true }]); + assert.deepEqual(writes, [ + { + sessionId: "s1", + data: "super-secret", + options: { automated: true, sensitive: true, invalidateStartupSeed: false }, + }, + { + sessionId: "s1", + data: "\r", + options: { automated: true, sensitive: true, invalidateStartupSeed: false }, + }, + ]); + assert.equal(logs.some((entry) => entry.includes("super-secret")), false); + assert.equal(logs.some((entry) => entry.includes("[sensitive]")), true); +}); + test("createScriptRuntime supports regex waits over multiline output", async () => { const logs = []; const buffer = new SessionOutputBuffer("s1"); diff --git a/electron/scripts/sessionOutputBuffer.test.cjs b/electron/scripts/sessionOutputBuffer.test.cjs index 4e0a98d2d..bdbe43ea2 100644 --- a/electron/scripts/sessionOutputBuffer.test.cjs +++ b/electron/scripts/sessionOutputBuffer.test.cjs @@ -804,8 +804,8 @@ test("stepsToJavaScript sends sensitive prompt result", () => { { type: "send", value: "secret", sensitive: true }, { type: "waitForPrompt", timeoutMs: 30000 }, ], "2026-06-27"); - assert.match(code, /const sensitiveValue0 = await nct\.dialog\.prompt\("Enter sensitive value", ""\);/); - assert.match(code, /await nct\.screen\.sendLine\(sensitiveValue0\);/); + assert.match(code, /const sensitiveValue0 = await nct\.dialog\.prompt\("Enter sensitive value", "", \{ sensitive: true \}\);/); + assert.match(code, /await nct\.screen\.sendLine\(sensitiveValue0, \{ sensitive: true \}\);/); }); test("stepsToJavaScript generates sendLine and waitForPrompt steps", () => { diff --git a/electron/terminalWorker/process.cjs b/electron/terminalWorker/process.cjs index 2c609760a..2496207a3 100644 --- a/electron/terminalWorker/process.cjs +++ b/electron/terminalWorker/process.cjs @@ -61,7 +61,7 @@ function createZmodemUploadFileSelector(parentPort, options = {}) { } }); - return function selectZmodemUploadFiles(webContentsId) { + return function selectZmodemUploadFiles(webContentsId, sessionId) { const requestId = randomUUIDFn(); const promise = new Promise((resolve, reject) => { pendingRequests.set(requestId, { resolve, reject }); @@ -70,6 +70,7 @@ function createZmodemUploadFileSelector(parentPort, options = {}) { kind: "zmodem-upload-dialog", requestId, webContentsId, + sessionId, }); return promise; }; @@ -92,7 +93,7 @@ function createZmodemDownloadDirectorySelector(parentPort, options = {}) { } }); - return function selectZmodemDownloadDirectory(webContentsId) { + return function selectZmodemDownloadDirectory(webContentsId, sessionId) { const requestId = randomUUIDFn(); const promise = new Promise((resolve, reject) => { pendingRequests.set(requestId, { resolve, reject }); @@ -101,6 +102,7 @@ function createZmodemDownloadDirectorySelector(parentPort, options = {}) { kind: "zmodem-download-dialog", requestId, webContentsId, + sessionId, }); return promise; }; @@ -114,6 +116,13 @@ function main() { const sessions = new Map(); const sftpClients = new Map(); + const { createTerminalDataPipeline } = require("./terminalDataPipeline.cjs"); + const terminalDataPipeline = createTerminalDataPipeline({ + onWarning: (warning) => parentPort.postMessage({ + kind: "terminal-interceptor-warning", + warning, + }), + }); let runtime = null; const electronModule = { webContents: { @@ -141,10 +150,12 @@ function main() { electronModule, selectZmodemUploadFiles, selectZmodemDownloadDirectory, + terminalDataPipeline, }; runtime = createTerminalWorkerRuntime({ parentPort, + terminalDataPipeline, registerBridges(ipcMain) { sshBridge.init(deps); terminalBridge.init(deps); diff --git a/electron/terminalWorker/process.test.cjs b/electron/terminalWorker/process.test.cjs index aca0cec58..96a472abb 100644 --- a/electron/terminalWorker/process.test.cjs +++ b/electron/terminalWorker/process.test.cjs @@ -46,11 +46,12 @@ test("ZMODEM upload selector resolves dialog results delivered as MessageEvent d randomUUID: () => "dialog-1", }); - const promise = selectUploadFiles(7); + const promise = selectUploadFiles(7, "session-1"); assert.deepEqual(parentPort.messages, [{ kind: "zmodem-upload-dialog", requestId: "dialog-1", webContentsId: 7, + sessionId: "session-1", }]); parentPort.emitMessage({ @@ -73,11 +74,12 @@ test("ZMODEM download selector resolves directory dialog results delivered as Me randomUUID: () => "download-dialog-1", }); - const promise = selectDownloadDirectory(7); + const promise = selectDownloadDirectory(7, "session-1"); assert.deepEqual(parentPort.messages, [{ kind: "zmodem-download-dialog", requestId: "download-dialog-1", webContentsId: 7, + sessionId: "session-1", }]); parentPort.emitMessage({ diff --git a/electron/terminalWorker/runtime.cjs b/electron/terminalWorker/runtime.cjs index b077b742c..069ff394d 100644 --- a/electron/terminalWorker/runtime.cjs +++ b/electron/terminalWorker/runtime.cjs @@ -33,7 +33,7 @@ function normalizeMessageEvent(eventOrMessage) { }; } -function createOutputPortRegistry(parentPort) { +function createOutputPortRegistry() { const outputPorts = new Map(); function closeSession(sessionId) { @@ -71,7 +71,7 @@ function createOutputPortRegistry(parentPort) { } } - function open(sessionId, port, bufferedOutput = []) { + function open(sessionId, port) { if (!sessionId || !port) return; closeSession(sessionId); outputPorts.set(sessionId, port); @@ -80,29 +80,12 @@ function createOutputPortRegistry(parentPort) { } catch { // Some Electron MessagePort implementations do not require start(). } - for (const chunk of bufferedOutput || []) { - const data = chunk && typeof chunk === "object" && "data" in chunk ? chunk.data : chunk; - const meta = chunk && typeof chunk === "object" ? chunk.meta : undefined; - post(sessionId, data, meta); - } - parentPort.postMessage({ kind: "output-port-ready", sessionId }); - } - - function flush(sessionId, chunks = []) { - for (const chunk of chunks || []) { - const data = chunk && typeof chunk === "object" && "data" in chunk ? chunk.data : chunk; - const meta = chunk && typeof chunk === "object" ? chunk.meta : undefined; - if (!post(sessionId, data, meta)) { - parentPort.postMessage(meta ? { kind: "output", sessionId, data, meta } : { kind: "output", sessionId, data }); - } - } } return { open, post, postControl, - flush, closeSession, }; } @@ -159,47 +142,172 @@ function createUrgentInputPortRegistry(dispatch) { }; } -function createSender(parentPort, webContentsId, outputPorts) { +function createSender( + parentPort, + webContentsId, + outputPorts, + terminalDataPipeline, + pendingOutputBySession = new Map(), + sessionOutputGenerations = new Map(), +) { + const ownedSessionGenerations = new Map(); + const getOwnedSessionGeneration = (sessionId) => { + if (!ownedSessionGenerations.has(sessionId)) { + ownedSessionGenerations.set(sessionId, sessionOutputGenerations.get(sessionId) ?? 0); + } + return ownedSessionGenerations.get(sessionId); + }; + const trackPendingOutput = (sessionId, pending) => { + pendingOutputBySession.set(sessionId, pending); + const clearPending = () => { + if (pendingOutputBySession.get(sessionId) === pending) { + pendingOutputBySession.delete(sessionId); + } + }; + void pending.then(clearPending, clearPending); + }; + const postRendererEvent = (channel, payload) => { + const explicitGeneration = payload?._terminalSessionGeneration; + const sessionGeneration = Number.isSafeInteger(explicitGeneration) + ? explicitGeneration + : payload?.sessionId + ? getOwnedSessionGeneration(payload.sessionId) + : undefined; + const rendererPayload = explicitGeneration === undefined + ? payload + : Object.freeze(Object.fromEntries( + Object.entries(payload).filter(([key]) => key !== "_terminalSessionGeneration"), + )); + if (channel === "netcatty:exit" && payload?.sessionId) { + if ((sessionOutputGenerations.get(payload.sessionId) ?? 0) === sessionGeneration) { + sessionOutputGenerations.set(payload.sessionId, sessionGeneration + 1); + pendingOutputBySession.delete(payload.sessionId); + outputPorts?.closeSession?.(payload.sessionId); + terminalDataPipeline?.detach?.(payload.sessionId, undefined, "session-closed"); + } + } + parentPort.postMessage({ + kind: "renderer-event", + webContentsId, + channel, + payload: rendererPayload, + ...(sessionGeneration === undefined ? {} : { sessionGeneration }), + }); + }; + const deliverTerminalData = (payload) => { + const sessionId = payload?.sessionId; + const explicitGeneration = payload?._terminalSessionGeneration; + const outputGeneration = Number.isSafeInteger(explicitGeneration) + ? explicitGeneration + : getOwnedSessionGeneration(sessionId); + if ((sessionOutputGenerations.get(sessionId) ?? 0) !== outputGeneration) return; + const tapMessage = { + kind: "output-tap", + sessionId: payload?.sessionId, + data: payload?.data, + }; + if (payload?.meta) tapMessage.meta = payload.meta; + if (payload?.tapped !== true) parentPort.postMessage(tapMessage); + const pipelineProcessed = payload?.pipelineProcessed === true; + const pipelineMode = terminalDataPipeline?.getOutputMode?.(payload?.sessionId) ?? 0; + let sensitiveInputState; + if (!pipelineProcessed && pipelineMode !== 0) { + sensitiveInputState = terminalDataPipeline.observeOutput?.( + payload?.sessionId, + payload?.data, + ) === true; + } + const deliver = (data, transformed = false) => { + if ((sessionOutputGenerations.get(sessionId) ?? 0) !== outputGeneration) return; + const inheritedIngressBytes = payload?.meta?.pluginPipelineIngressBytes; + const replayedRawIngressBytes = !transformed + && !pipelineProcessed + && Number.isFinite(inheritedIngressBytes) + ? Math.max(0, Number(inheritedIngressBytes)) + String(payload?.data ?? "").length + : null; + const pipelineMeta = { + ...(payload?.meta ?? {}), + ...(replayedRawIngressBytes == null + ? {} + : { pluginPipelineIngressBytes: replayedRawIngressBytes }), + ...(transformed + ? { + pluginPipelineIngressBytes: + Number(payload?.meta?.pluginPipelineIngressBytes ?? 0) + + String(payload?.data ?? "").length, + pluginPipelineProcessed: true, + } + : {}), + ...(sensitiveInputState === undefined + ? {} + : { pluginPipelineSensitiveInput: sensitiveInputState }), + }; + const meta = Object.keys(pipelineMeta).length > 0 ? pipelineMeta : undefined; + if (outputPorts?.post?.(payload?.sessionId, data, meta)) return; + const outputMessage = { + kind: "output", + sessionId: payload?.sessionId, + data, + tapped: true, + }; + if (meta) outputMessage.meta = meta; + parentPort.postMessage(outputMessage); + }; + const previous = pendingOutputBySession.get(sessionId); + if (pipelineProcessed || !terminalDataPipeline?.interceptOutput || (pipelineMode & 2) === 0) { + if (!previous) { + deliver(payload?.data, false); + return; + } + const pending = previous.then( + () => deliver(payload?.data, false), + () => deliver(payload?.data, false), + ); + trackPendingOutput(sessionId, pending); + return; + } + const interceptAndDeliver = () => { + try { + return Promise.resolve(terminalDataPipeline.interceptOutput(sessionId, payload?.data)).then( + (data) => deliver(data, true), + () => deliver(payload?.data, false), + ); + } catch { + deliver(payload?.data, false); + return undefined; + } + }; + // Invoke the pipeline immediately so its bounded byte window and monotonic + // deadline cover time spent waiting behind earlier transforms. The + // pipeline owns per-session transform ordering; this outer registry only + // retains the latest barrier for direct fail-open output and session exit. + const pending = Promise.resolve(interceptAndDeliver()); + trackPendingOutput(sessionId, pending); + }; return { id: webContentsId, + claimSessionGeneration(sessionId) { + return getOwnedSessionGeneration(sessionId); + }, isDestroyed() { return false; }, send(channel, payload) { if (channel === "netcatty:data") { - const tapMessage = { - kind: "output-tap", - sessionId: payload?.sessionId, - data: payload?.data, - }; - if (payload?.meta) tapMessage.meta = payload.meta; - parentPort.postMessage(tapMessage); - if (outputPorts?.post?.(payload?.sessionId, payload?.data, payload?.meta)) { - return; - } - const outputMessage = { - kind: "output", - sessionId: payload?.sessionId, - data: payload?.data, - // The output-tap message above already notified main-process taps - // for this chunk; flag the fallback delivery so the worker manager - // does not notify them a second time (would double-write session - // logs and script output buffers). - tapped: true, - }; - if (payload?.meta) outputMessage.meta = payload.meta; - parentPort.postMessage(outputMessage); + deliverTerminalData(payload); return; } if (channel === "netcatty:exit" && payload?.sessionId) { - outputPorts?.closeSession?.(payload.sessionId); + const pending = pendingOutputBySession.get(payload.sessionId); + if (pending) { + void pending.then( + () => postRendererEvent(channel, payload), + () => postRendererEvent(channel, payload), + ); + return; + } } - parentPort.postMessage({ - kind: "renderer-event", - webContentsId, - channel, - payload, - }); + postRendererEvent(channel, payload); }, }; } @@ -208,12 +316,51 @@ function createTerminalWorkerRuntime(options = {}) { const { parentPort, registerBridges, + terminalDataPipeline, } = options; const ipcMain = createIpcMainHarness(); let started = false; - const outputPorts = createOutputPortRegistry(parentPort); + const outputPorts = createOutputPortRegistry(); + const pendingOutputBySession = new Map(); + const sessionOutputGenerations = new Map(); let urgentInputPorts = null; + const createWorkerOutputSender = () => createSender( + parentPort, + 0, + outputPorts, + terminalDataPipeline, + pendingOutputBySession, + sessionOutputGenerations, + ); + + function replayWorkerOutput(sessionId, chunks) { + const sender = createWorkerOutputSender(); + for (const chunk of chunks || []) { + const data = chunk && typeof chunk === "object" && "data" in chunk ? chunk.data : chunk; + const meta = chunk && typeof chunk === "object" ? chunk.meta : undefined; + const pipelineProcessed = meta?.pluginPipelineProcessed === true; + sender.send("netcatty:data", { + sessionId, + data, + meta, + tapped: true, + pipelineProcessed, + }); + } + } + + function invalidateSessionOutput(sessionId) { + if (!sessionId) return; + sessionOutputGenerations.set( + sessionId, + (sessionOutputGenerations.get(sessionId) ?? 0) + 1, + ); + pendingOutputBySession.delete(sessionId); + outputPorts.closeSession(sessionId); + terminalDataPipeline?.detach?.(sessionId, undefined, "session-closed"); + } + async function handleRequest(message) { const handler = ipcMain.handlers.get(message.channel); if (!handler) { @@ -226,12 +373,23 @@ function createTerminalWorkerRuntime(options = {}) { } try { const result = await handler({ - sender: createSender(parentPort, message.webContentsId, outputPorts), + sender: createSender( + parentPort, + message.webContentsId, + outputPorts, + terminalDataPipeline, + pendingOutputBySession, + sessionOutputGenerations, + ), }, message.payload); + const sessionId = result?.sessionId; parentPort.postMessage({ kind: "response", requestId: message.requestId, result, + ...(typeof sessionId === "string" + ? { sessionGeneration: sessionOutputGenerations.get(sessionId) ?? 0 } + : {}), }); } catch (err) { parentPort.postMessage({ @@ -246,6 +404,7 @@ function createTerminalWorkerRuntime(options = {}) { const listener = ipcMain.listeners.get(message.channel); if (!listener) return; if (message.channel === "netcatty:interrupt") { + terminalDataPipeline?.clearSensitiveInput?.(message.payload?.sessionId); const trace = normalizeTrace(message.payload); logTerminalInterruptDebug("worker-received-send", { channel: message.channel, @@ -253,10 +412,17 @@ function createTerminalWorkerRuntime(options = {}) { }, trace); } if (message.channel === "netcatty:close" && message.payload?.sessionId) { - outputPorts.closeSession(message.payload.sessionId); + invalidateSessionOutput(message.payload.sessionId); } listener({ - sender: createSender(parentPort, message.webContentsId, outputPorts), + sender: createSender( + parentPort, + message.webContentsId, + outputPorts, + terminalDataPipeline, + pendingOutputBySession, + sessionOutputGenerations, + ), }, message.payload); } @@ -284,15 +450,33 @@ function createTerminalWorkerRuntime(options = {}) { return; } if (message?.kind === "output-port") { - outputPorts.open(message.sessionId, ports?.[0], message.bufferedOutput); + outputPorts.open(message.sessionId, ports?.[0]); + replayWorkerOutput(message.sessionId, message.bufferedOutput); + const pending = pendingOutputBySession.get(message.sessionId); + if (pending) { + void pending.then( + () => parentPort.postMessage({ kind: "output-port-ready", sessionId: message.sessionId }), + () => parentPort.postMessage({ kind: "output-port-ready", sessionId: message.sessionId }), + ); + } else { + parentPort.postMessage({ kind: "output-port-ready", sessionId: message.sessionId }); + } + return; + } + if (message?.kind === "terminal-interceptor-port") { + terminalDataPipeline?.attach?.(message, ports?.[0]); + return; + } + if (message?.kind === "terminal-interceptor-detach") { + terminalDataPipeline?.detach?.(message.sessionId, message.direction, "detached"); return; } if (message?.kind === "output-flush") { - outputPorts.flush(message.sessionId, message.chunks); + replayWorkerOutput(message.sessionId, message.chunks); return; } if (message?.kind === "close-output-port") { - outputPorts.closeSession(message.sessionId); + invalidateSessionOutput(message.sessionId); return; } if (message?.kind === "output-drain") { @@ -323,7 +507,14 @@ function createTerminalWorkerRuntime(options = {}) { start, ipcMain, createSender(webContentsId) { - return createSender(parentPort, webContentsId, outputPorts); + return createSender( + parentPort, + webContentsId, + outputPorts, + terminalDataPipeline, + pendingOutputBySession, + sessionOutputGenerations, + ); }, closeUrgentInputPortsForTest() { urgentInputPorts?.closeAll(); diff --git a/electron/terminalWorker/runtime.test.cjs b/electron/terminalWorker/runtime.test.cjs index 9b3865fa6..c01621e0b 100644 --- a/electron/terminalWorker/runtime.test.cjs +++ b/electron/terminalWorker/runtime.test.cjs @@ -82,6 +82,124 @@ test("runtime invokes registered request handlers and posts responses", async () ]); }); +test("runtime routes interceptor ports to the worker-owned data pipeline", () => { + const parentPort = createParentPort(); + const attached = []; + const detached = []; + const runtime = createTerminalWorkerRuntime({ + parentPort, + terminalDataPipeline: { + attach(message, port) { attached.push({ message, port }); }, + detach(sessionId, direction) { detached.push({ sessionId, direction }); }, + }, + registerBridges() {}, + }); + runtime.start(); + const port = new FakePort(); + parentPort.emitMessage({ + data: { kind: "terminal-interceptor-port", sessionId: "session-1", direction: "output" }, + ports: [port], + }); + assert.equal(attached[0].port, port); + parentPort.emitMessage({ kind: "terminal-interceptor-detach", sessionId: "session-1", direction: "output" }); + assert.deepEqual(detached, [{ sessionId: "session-1", direction: "output" }]); +}); + +test("fresh sender lookups preserve an explicitly bound backend session generation", () => { + const parentPort = createParentPort(); + const detached = []; + const runtime = createTerminalWorkerRuntime({ + parentPort, + terminalDataPipeline: { + detach(sessionId, direction, reason) { detached.push({ sessionId, direction, reason }); }, + }, + registerBridges() {}, + }); + runtime.start(); + + const oldGeneration = runtime.createSender(7).claimSessionGeneration("session-1"); + runtime.createSender(7).send("netcatty:exit", { + sessionId: "session-1", + reason: "error", + _terminalSessionGeneration: oldGeneration, + }); + const newGeneration = runtime.createSender(8).claimSessionGeneration("session-1"); + runtime.createSender(7).send("netcatty:exit", { + sessionId: "session-1", + reason: "close", + _terminalSessionGeneration: oldGeneration, + }); + runtime.createSender(8).send("netcatty:exit", { + sessionId: "session-1", + reason: "exited", + _terminalSessionGeneration: newGeneration, + }); + + assert.deepEqual( + parentPort.messages.map((message) => message.sessionGeneration), + [0, 0, 1], + ); + assert.equal(parentPort.messages.some((message) => ( + Object.hasOwn(message.payload, "_terminalSessionGeneration") + )), false); + assert.deepEqual(detached, [ + { sessionId: "session-1", direction: undefined, reason: "session-closed" }, + { sessionId: "session-1", direction: undefined, reason: "session-closed" }, + ]); +}); + +test("stale backend output is rejected before taps, observation, or interception", async () => { + const parentPort = createParentPort(); + const observed = []; + const intercepted = []; + const runtime = createTerminalWorkerRuntime({ + parentPort, + terminalDataPipeline: { + getOutputMode() { return 3; }, + observeOutput(sessionId, data) { observed.push({ sessionId, data }); return false; }, + async interceptOutput(sessionId, data) { + intercepted.push({ sessionId, data }); + return data; + }, + detach() {}, + }, + registerBridges() {}, + }); + runtime.start(); + + const oldSender = runtime.createSender(7); + const oldGeneration = oldSender.claimSessionGeneration("session-1"); + oldSender.send("netcatty:exit", { + sessionId: "session-1", + reason: "error", + _terminalSessionGeneration: oldGeneration, + }); + const newSender = runtime.createSender(8); + const newGeneration = newSender.claimSessionGeneration("session-1"); + parentPort.messages.length = 0; + + runtime.createSender(7).send("netcatty:data", { + sessionId: "session-1", + data: "old-secret", + _terminalSessionGeneration: oldGeneration, + }); + await new Promise((resolve) => setImmediate(resolve)); + + assert.deepEqual(parentPort.messages, []); + assert.deepEqual(observed, []); + assert.deepEqual(intercepted, []); + + runtime.createSender(8).send("netcatty:data", { + sessionId: "session-1", + data: "new-output", + _terminalSessionGeneration: newGeneration, + }); + await new Promise((resolve) => setImmediate(resolve)); + assert.deepEqual(observed, [{ sessionId: "session-1", data: "new-output" }]); + assert.deepEqual(intercepted, [{ sessionId: "session-1", data: "new-output" }]); + assert.deepEqual(parentPort.messages.map((message) => message.kind), ["output-tap", "output"]); +}); + test("runtime invokes fire-and-forget listeners", () => { const parentPort = createParentPort(); const calls = []; @@ -175,6 +293,30 @@ test("runtime routes urgent input port interrupts to the interrupt listener", () ]); }); +test("runtime clears host-sensitive input state before dispatching an interrupt", () => { + const parentPort = createParentPort(); + const order = []; + const runtime = createTerminalWorkerRuntime({ + parentPort, + terminalDataPipeline: { + clearSensitiveInput(sessionId) { order.push(`clear:${sessionId}`); }, + }, + registerBridges(ipcMain) { + ipcMain.on("netcatty:interrupt", (_event, payload) => order.push(`write:${payload.sessionId}`)); + }, + }); + runtime.start(); + + parentPort.emitMessage({ + kind: "send", + channel: "netcatty:interrupt", + payload: { sessionId: "s1" }, + webContentsId: 7, + }); + + assert.deepEqual(order, ["clear:s1", "write:s1"]); +}); + test("runtime routes terminal data over output messages", async () => { const parentPort = createParentPort(); const runtime = createTerminalWorkerRuntime({ @@ -210,6 +352,276 @@ test("runtime routes terminal data over output messages", async () => { }); }); +test("runtime keeps the no-interceptor output path synchronous and allocation-free", async () => { + const parentPort = createParentPort(); + let interceptCalls = 0; + const runtime = createTerminalWorkerRuntime({ + parentPort, + terminalDataPipeline: { + getOutputMode() { return 0; }, + async interceptOutput() { interceptCalls += 1; return "changed"; }, + }, + registerBridges(ipcMain) { + ipcMain.handle("netcatty:test", (event) => { + event.sender.send("netcatty:data", { sessionId: "s1", data: "hello" }); + assert.equal(parentPort.messages[1]?.data, "hello"); + return null; + }); + }, + }); + runtime.start(); + parentPort.emitMessage({ + kind: "request", + requestId: "req-no-plugin", + channel: "netcatty:test", + payload: {}, + webContentsId: 7, + }); + await new Promise((resolve) => setImmediate(resolve)); + assert.equal(interceptCalls, 0); +}); + +test("runtime sends transformed output to the renderer while host taps retain original data", async () => { + const parentPort = createParentPort(); + const observed = []; + const runtime = createTerminalWorkerRuntime({ + parentPort, + terminalDataPipeline: { + getOutputMode() { return 3; }, + observeOutput(sessionId, data) { observed.push({ sessionId, data }); return true; }, + async interceptOutput(_sessionId, data) { return String(data).toUpperCase(); }, + }, + registerBridges(ipcMain) { + ipcMain.handle("netcatty:test", (event) => { + event.sender.send("netcatty:data", { sessionId: "s1", data: "hello" }); + return null; + }); + }, + }); + runtime.start(); + parentPort.emitMessage({ + kind: "request", + requestId: "req-plugin", + channel: "netcatty:test", + payload: {}, + webContentsId: 7, + }); + await new Promise((resolve) => setImmediate(resolve)); + assert.deepEqual(parentPort.messages[0], { + kind: "output-tap", + sessionId: "s1", + data: "hello", + }); + assert.deepEqual(parentPort.messages[1], { + kind: "output", + sessionId: "s1", + data: "HELLO", + tapped: true, + meta: { + pluginPipelineIngressBytes: 5, + pluginPipelineProcessed: true, + pluginPipelineSensitiveInput: true, + }, + }); + assert.deepEqual(observed, [{ sessionId: "s1", data: "hello" }]); +}); + +test("runtime classifies original prompts when only an output interceptor is active", async () => { + const parentPort = createParentPort(); + const observed = []; + const runtime = createTerminalWorkerRuntime({ + parentPort, + terminalDataPipeline: { + getOutputMode() { return 2; }, + observeOutput(sessionId, data) { observed.push({ sessionId, data }); return true; }, + async interceptOutput() { return "masked> "; }, + }, + registerBridges() {}, + }); + runtime.start(); + + runtime.createSender(7).send("netcatty:data", { sessionId: "s1", data: "Password: " }); + await new Promise((resolve) => setImmediate(resolve)); + + assert.deepEqual(observed, [{ sessionId: "s1", data: "Password: " }]); + assert.deepEqual(parentPort.messages.at(-1), { + kind: "output", + sessionId: "s1", + data: "masked> ", + tapped: true, + meta: { + pluginPipelineIngressBytes: 10, + pluginPipelineProcessed: true, + pluginPipelineSensitiveInput: true, + }, + }); +}); + +test("runtime publishes an explicit sensitive-state clear from original output", async () => { + const parentPort = createParentPort(); + const runtime = createTerminalWorkerRuntime({ + parentPort, + terminalDataPipeline: { + getOutputMode() { return 3; }, + observeOutput() { return false; }, + async interceptOutput() { return "renamed prompt> "; }, + }, + registerBridges() {}, + }); + runtime.start(); + + runtime.createSender(7).send("netcatty:data", { + sessionId: "s1", + data: "\r\nAccess denied\r\n$ ", + }); + await new Promise((resolve) => setImmediate(resolve)); + + assert.equal( + parentPort.messages.at(-1).meta.pluginPipelineSensitiveInput, + false, + ); +}); + +test("runtime delivers pending intercepted output before closing the session", async () => { + const parentPort = createParentPort(); + let releaseOutput; + const detached = []; + const runtime = createTerminalWorkerRuntime({ + parentPort, + terminalDataPipeline: { + getOutputMode() { return 2; }, + observeOutput() { return false; }, + interceptOutput() { + return new Promise((resolve) => { releaseOutput = resolve; }); + }, + detach(sessionId, direction, reason) { detached.push({ sessionId, direction, reason }); }, + }, + registerBridges() {}, + }); + runtime.start(); + runtime.createSender(7).send("netcatty:data", { sessionId: "s1", data: "final" }); + runtime.createSender(7).send("netcatty:exit", { sessionId: "s1", reason: "closed" }); + await new Promise((resolve) => setImmediate(resolve)); + assert.deepEqual(parentPort.messages.map((message) => message.kind), ["output-tap"]); + + releaseOutput("FINAL"); + await new Promise((resolve) => setImmediate(resolve)); + assert.deepEqual(parentPort.messages.map((message) => message.kind), [ + "output-tap", + "output", + "renderer-event", + ]); + assert.equal(parentPort.messages[1].data, "FINAL"); + assert.equal(parentPort.messages[2].channel, "netcatty:exit"); + assert.deepEqual(detached, [{ sessionId: "s1", direction: undefined, reason: "session-closed" }]); +}); + +test("runtime keeps direct output ordered behind a pending chunk after interceptor disable", async () => { + const parentPort = createParentPort(); + let mode = 2; + let releaseOutput; + const runtime = createTerminalWorkerRuntime({ + parentPort, + terminalDataPipeline: { + getOutputMode() { return mode; }, + observeOutput() { return false; }, + interceptOutput() { + mode = 0; + return new Promise((resolve) => { releaseOutput = resolve; }); + }, + }, + registerBridges() {}, + }); + runtime.start(); + + runtime.createSender(7).send("netcatty:data", { sessionId: "s1", data: "first" }); + runtime.createSender(7).send("netcatty:data", { sessionId: "s1", data: "second" }); + await new Promise((resolve) => setImmediate(resolve)); + assert.deepEqual(parentPort.messages.map((message) => message.kind), ["output-tap", "output-tap"]); + + releaseOutput("FIRST"); + await new Promise((resolve) => setImmediate(resolve)); + assert.deepEqual( + parentPort.messages.filter((message) => message.kind === "output").map((message) => message.data), + ["FIRST", "second"], + ); +}); + +test("runtime drops a pending intercepted chunk after the session output route is reused", async () => { + const parentPort = createParentPort(); + const oldPort = new FakePort(); + const newPort = new FakePort(); + const detached = []; + let releaseOutput; + const runtime = createTerminalWorkerRuntime({ + parentPort, + terminalDataPipeline: { + getOutputMode() { return 2; }, + observeOutput() { return false; }, + interceptOutput() { + return new Promise((resolve) => { releaseOutput = resolve; }); + }, + detach(sessionId, direction, reason) { detached.push({ sessionId, direction, reason }); }, + }, + registerBridges() {}, + }); + runtime.start(); + parentPort.emitMessage({ + data: { kind: "output-port", sessionId: "s1", bufferedOutput: [] }, + ports: [oldPort], + }); + runtime.createSender(7).send("netcatty:data", { sessionId: "s1", data: "old" }); + await new Promise((resolve) => setImmediate(resolve)); + + parentPort.emitMessage({ kind: "close-output-port", sessionId: "s1" }); + parentPort.emitMessage({ + data: { kind: "output-port", sessionId: "s1", bufferedOutput: [] }, + ports: [newPort], + }); + releaseOutput("STALE"); + await new Promise((resolve) => setImmediate(resolve)); + + assert.equal(oldPort.closed, true); + assert.deepEqual(newPort.messages, []); + assert.deepEqual(detached, [{ + sessionId: "s1", + direction: undefined, + reason: "session-closed", + }]); +}); + +test("runtime submits queued output to the bounded pipeline before earlier transforms finish", async () => { + const parentPort = createParentPort(); + const releases = []; + const calls = []; + const runtime = createTerminalWorkerRuntime({ + parentPort, + terminalDataPipeline: { + getOutputMode() { return 2; }, + observeOutput() { return false; }, + interceptOutput(_sessionId, data) { + calls.push(data); + return new Promise((resolve) => releases.push(() => resolve(data.toUpperCase()))); + }, + }, + registerBridges() {}, + }); + runtime.start(); + + runtime.createSender(7).send("netcatty:data", { sessionId: "s1", data: "first" }); + runtime.createSender(7).send("netcatty:data", { sessionId: "s1", data: "second" }); + await new Promise((resolve) => setImmediate(resolve)); + assert.deepEqual(calls, ["first", "second"]); + + releases[0](); + releases[1](); + await new Promise((resolve) => setImmediate(resolve)); + assert.deepEqual( + parentPort.messages.filter((message) => message.kind === "output").map((message) => message.data), + ["FIRST", "SECOND"], + ); +}); + test("runtime routes terminal data over a transferred output port", async () => { const parentPort = createParentPort(); const outputPort = new FakePort(); @@ -255,6 +667,216 @@ test("runtime routes terminal data over a transferred output port", async () => assert.equal(parentPort.messages.some((message) => message.kind === "output"), false); }); +test("runtime routes buffered startup output through the selected interceptor", async () => { + const parentPort = createParentPort(); + const outputPort = new FakePort(); + const intercepted = []; + const runtime = createTerminalWorkerRuntime({ + parentPort, + terminalDataPipeline: { + getOutputMode: () => 2, + observeOutput: () => false, + interceptOutput(sessionId, data) { + intercepted.push({ sessionId, data }); + return Promise.resolve(data.toUpperCase()); + }, + }, + registerBridges() {}, + }); + runtime.start(); + + parentPort.emitMessage({ + data: { + kind: "output-port", + sessionId: "s1", + bufferedOutput: [{ data: "early", meta: { source: "startup" } }], + }, + ports: [outputPort], + }); + await new Promise((resolve) => setImmediate(resolve)); + + assert.deepEqual(intercepted, [{ sessionId: "s1", data: "early" }]); + assert.deepEqual(outputPort.messages, [{ + sessionId: "s1", + data: "EARLY", + meta: { + source: "startup", + pluginPipelineIngressBytes: 5, + pluginPipelineProcessed: true, + pluginPipelineSensitiveInput: false, + }, + }]); + assert.deepEqual(parentPort.messages, [{ kind: "output-port-ready", sessionId: "s1" }]); +}); + +test("runtime does not re-intercept already transformed buffered output", async () => { + const parentPort = createParentPort(); + const outputPort = new FakePort(); + const intercepted = []; + const runtime = createTerminalWorkerRuntime({ + parentPort, + terminalDataPipeline: { + getOutputMode: () => 2, + observeOutput: () => false, + interceptOutput(sessionId, data) { + intercepted.push({ sessionId, data }); + return Promise.resolve(`again:${data}`); + }, + }, + registerBridges() {}, + }); + runtime.start(); + + parentPort.emitMessage({ + data: { + kind: "output-port", + sessionId: "s1", + bufferedOutput: [{ + data: "EARLY", + meta: { + pluginPipelineIngressBytes: 5, + pluginPipelineProcessed: true, + pluginPipelineSensitiveInput: true, + }, + }], + }, + ports: [outputPort], + }); + await new Promise((resolve) => setImmediate(resolve)); + + assert.deepEqual(intercepted, []); + assert.deepEqual(outputPort.messages, [{ + sessionId: "s1", + data: "EARLY", + meta: { + pluginPipelineIngressBytes: 5, + pluginPipelineProcessed: true, + pluginPipelineSensitiveInput: true, + }, + }]); + assert.deepEqual(parentPort.messages, [{ kind: "output-port-ready", sessionId: "s1" }]); +}); + +test("runtime re-intercepts raw buffered output that only inherited ingress accounting", async () => { + const parentPort = createParentPort(); + const outputPort = new FakePort(); + const intercepted = []; + const runtime = createTerminalWorkerRuntime({ + parentPort, + terminalDataPipeline: { + getOutputMode: () => 2, + observeOutput: () => false, + interceptOutput(sessionId, data) { + intercepted.push({ sessionId, data }); + return Promise.resolve(`processed:${data}`); + }, + }, + registerBridges() {}, + }); + runtime.start(); + + parentPort.emitMessage({ + data: { + kind: "output-port", + sessionId: "s1", + bufferedOutput: [{ + data: "raw", + meta: { pluginPipelineIngressBytes: 9 }, + }], + }, + ports: [outputPort], + }); + await new Promise((resolve) => setImmediate(resolve)); + + assert.deepEqual(intercepted, [{ sessionId: "s1", data: "raw" }]); + assert.deepEqual(outputPort.messages, [{ + sessionId: "s1", + data: "processed:raw", + meta: { + pluginPipelineIngressBytes: 12, + pluginPipelineProcessed: true, + pluginPipelineSensitiveInput: false, + }, + }]); + assert.deepEqual(parentPort.messages, [{ kind: "output-port-ready", sessionId: "s1" }]); +}); + +test("runtime adds retained raw bytes after manager partial-trim accounting", async () => { + const parentPort = createParentPort(); + const outputPort = new FakePort(); + const intercepted = []; + const runtime = createTerminalWorkerRuntime({ + parentPort, + terminalDataPipeline: { + getOutputMode: () => 2, + observeOutput: () => false, + interceptOutput(sessionId, data) { + intercepted.push({ sessionId, data }); + return Promise.resolve(`processed:${data}`); + }, + }, + registerBridges() {}, + }); + runtime.start(); + + parentPort.emitMessage({ + data: { + kind: "output-port", + sessionId: "s1", + bufferedOutput: [{ + data: "bcde", + meta: { pluginPipelineIngressBytes: 11 }, + }], + }, + ports: [outputPort], + }); + await new Promise((resolve) => setImmediate(resolve)); + + assert.deepEqual(intercepted, [{ sessionId: "s1", data: "bcde" }]); + assert.deepEqual(outputPort.messages, [{ + sessionId: "s1", + data: "processed:bcde", + meta: { + pluginPipelineIngressBytes: 15, + pluginPipelineProcessed: true, + pluginPipelineSensitiveInput: false, + }, + }]); +}); + +test("runtime counts retained raw bytes when replay continues without an interceptor", async () => { + const parentPort = createParentPort(); + const outputPort = new FakePort(); + const runtime = createTerminalWorkerRuntime({ + parentPort, + terminalDataPipeline: { + getOutputMode: () => 0, + observeOutput: () => false, + }, + registerBridges() {}, + }); + runtime.start(); + + parentPort.emitMessage({ + data: { + kind: "output-port", + sessionId: "s1", + bufferedOutput: [{ + data: "raw", + meta: { pluginPipelineIngressBytes: 9 }, + }], + }, + ports: [outputPort], + }); + await new Promise((resolve) => setImmediate(resolve)); + + assert.deepEqual(outputPort.messages, [{ + sessionId: "s1", + data: "raw", + meta: { pluginPipelineIngressBytes: 12 }, + }]); +}); + test("runtime.createSender uses the transferred output port", () => { const parentPort = createParentPort(); const outputPort = new FakePort(); @@ -305,5 +927,6 @@ test("runtime forwards non-output renderer events to the parent", async () => { webContentsId: 7, channel: "netcatty:exit", payload: { sessionId: "s1", reason: "closed" }, + sessionGeneration: 0, }); }); diff --git a/electron/terminalWorker/terminalDataPipeline.cjs b/electron/terminalWorker/terminalDataPipeline.cjs new file mode 100644 index 000000000..1e02756a5 --- /dev/null +++ b/electron/terminalWorker/terminalDataPipeline.cjs @@ -0,0 +1,416 @@ +"use strict"; + +const { TextDecoder, TextEncoder } = require("node:util"); +const { performance } = require("node:perf_hooks"); +const { + TERMINAL_INTERCEPTOR_MAX_CHUNK_BYTES, + TERMINAL_INTERCEPTOR_MAX_WINDOW_BYTES, + createTerminalInterceptorEnvelope, +} = require("../plugins/terminalInterceptorTransport.cjs"); + +const INPUT_DEADLINE_MS = 4; +const OUTPUT_DEADLINE_MS = 50; +const MAX_CHUNK_BYTES = TERMINAL_INTERCEPTOR_MAX_CHUNK_BYTES; +const OUTPUT_WINDOW_BYTES = TERMINAL_INTERCEPTOR_MAX_WINDOW_BYTES; +const PROMPT_TAIL_CHARS = 2_048; +const SENSITIVE_LABELS = [ + "pass(?:word|phrase|code)", "passwd", "one[\\s-]?time", "otp", "verification", + "authentication", "security[\\s-]+(?:code|token|passcode|pin)", "\\bpin\\b", + "\\btoken\\b", "2fa", "two[\\s-]?factor", "multi[\\s-]?factor", "\\bmfa\\b", + "second[\\s-]+factor", "secondary", "re[\\s-]?enter", "confirm", "\\bedr\\b", + "\\bduo\\b", "密码", "密碼", "口令", "动态", "動態", "一次性", "验证码", + "驗證碼", "验证信息", "驗證資訊", "令牌", "双因素", "雙因素", "多因素", + "短信验证", "簡訊驗證", "手机验证", "手機驗證", "二次", "安全密码", "安全密碼", + "挑战码", "挑戰碼", "парол", +].join("|"); +const SENSITIVE_PROMPT = new RegExp( + `(?:${SENSITIVE_LABELS})[^\\r\\n]{0,160}[::?>›»]?\\s*$`, + "iu", +); +const CONFIRMED_SHELL_PROMPT = /^(?:(?:~)?[#$%]|(?:[^\r\n]{1,120}@[^\r\n]{1,120}:[^\r\n]{0,120}[#$%])|(?:PS(?:\s+\S.*)?>))\s*$/u; + +function messageData(value) { + return value && typeof value === "object" && "data" in value ? value.data : value; +} + +function addPortListener(port, listener) { + if (typeof port.addEventListener === "function") { + port.addEventListener("message", listener); + port.start?.(); + return () => port.removeEventListener?.("message", listener); + } + port.on?.("message", listener); + port.start?.(); + return () => port.off?.("message", listener) ?? port.removeListener?.("message", listener); +} + +function toTransferBuffer(bytes) { + const copy = new Uint8Array(bytes.byteLength); + copy.set(bytes); + return copy.buffer; +} + +function nextUtf8ChunkEnd(bytes, offset, maxChunkBytes = MAX_CHUNK_BYTES) { + let end = Math.min(bytes.byteLength, offset + maxChunkBytes); + if (end >= bytes.byteLength) return end; + while (end > offset && (bytes[end] & 0xc0) === 0x80) end -= 1; + if (end > offset) return end; + // TextEncoder output is valid UTF-8 and a code point is at most four bytes, + // so this branch is only reachable with an artificially tiny test limit. + end = Math.min(bytes.byteLength, offset + maxChunkBytes); + while (end < bytes.byteLength && (bytes[end] & 0xc0) === 0x80) end += 1; + return end; +} + +function visibleTerminalTail(value) { + return String(value ?? "") + .replace(/\x1b\][^\x07]*(?:\x07|\x1b\\)/gu, "") + .replace(/\x1b\[[0-?]*[ -/]*[@-~]/gu, "") + .replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/gu, "") + .slice(-PROMPT_TAIL_CHARS); +} + +function createTerminalDataPipeline(options = {}) { + const encoder = options.encoder ?? new TextEncoder(); + const decoder = options.decoder ?? new TextDecoder("utf-8", { fatal: true }); + const now = options.now ?? (() => performance.now()); + const onWarning = options.onWarning ?? (() => {}); + const inputDeadlineMs = options.inputDeadlineMs ?? INPUT_DEADLINE_MS; + const outputDeadlineMs = options.outputDeadlineMs ?? OUTPUT_DEADLINE_MS; + const outputWindowBytes = options.outputWindowBytes ?? OUTPUT_WINDOW_BYTES; + const bindings = new Map(); + const outputModes = new Map(); + const outputRawTails = new Map(); + const sensitiveInputSessions = new Set(); + + const keyOf = (sessionId, direction) => `${sessionId}\0${direction}`; + + function refreshOutputMode(sessionId) { + const input = bindings.has(keyOf(sessionId, "input")); + const output = bindings.has(keyOf(sessionId, "output")); + const mode = (input ? 1 : 0) | (output ? 2 : 0); + if (mode) outputModes.set(sessionId, mode); + else outputModes.delete(sessionId); + if (!mode) { + outputRawTails.delete(sessionId); + sensitiveInputSessions.delete(sessionId); + } else if (!input) { + sensitiveInputSessions.delete(sessionId); + } + } + + function warn(binding, code, message) { + try { + onWarning(Object.freeze({ + sessionId: binding.sessionId, + direction: binding.direction, + providerId: binding.providerId, + pluginId: binding.pluginId, + pluginVersion: binding.pluginVersion, + runtimeId: binding.runtimeId, + runtimeKind: binding.runtimeKind, + securityPrincipal: binding.securityPrincipal, + code, + message, + })); + } catch {} + } + + function disable(binding, code, message) { + if (!binding.active) return; + binding.active = false; + bindings.delete(keyOf(binding.sessionId, binding.direction)); + refreshOutputMode(binding.sessionId); + binding.removeListener?.(); + for (const pending of binding.pending.values()) { + clearTimeout(pending.timer); + pending.resolve(null); + } + binding.pending.clear(); + try { binding.port.close?.(); } catch {} + if (!["detached", "replaced", "shutdown", "session-closed"].includes(code)) { + warn(binding, code, message); + } + } + + function attach(descriptor, port) { + const sessionId = typeof descriptor?.sessionId === "string" ? descriptor.sessionId : ""; + const direction = descriptor?.direction; + const identityFields = [ + descriptor?.pluginId, + descriptor?.pluginVersion, + descriptor?.runtimeId, + descriptor?.securityPrincipal, + descriptor?.providerId, + ]; + if (!sessionId || sessionId.length > 256 + || (direction !== "input" && direction !== "output") + || descriptor?.runtimeKind !== "utility" + || identityFields.some((value) => typeof value !== "string" || value.length < 1 || value.length > 512) + || !port?.postMessage) { + throw new TypeError("Terminal interceptor attachment is invalid"); + } + const key = keyOf(sessionId, direction); + const previous = bindings.get(key); + const previousRawTail = outputRawTails.get(sessionId); + const wasSensitive = sensitiveInputSessions.has(sessionId); + if (previous) disable(previous, "replaced", "Terminal interceptor was replaced for this session"); + const binding = { + sessionId, + direction, + providerId: String(descriptor.providerId ?? ""), + pluginId: String(descriptor.pluginId ?? ""), + pluginVersion: descriptor.pluginVersion, + runtimeId: descriptor.runtimeId, + runtimeKind: descriptor.runtimeKind, + securityPrincipal: descriptor.securityPrincipal, + port, + active: true, + nextSequence: 1, + pending: new Map(), + queuedBytes: 0, + outputExpansionCreditBytes: direction === "output" ? outputWindowBytes : 0, + queue: Promise.resolve(), + removeListener: null, + }; + binding.removeListener = addPortListener(port, (event) => { + let envelope; + try { + const message = messageData(event); + envelope = createTerminalInterceptorEnvelope(message?.frame, message?.transfer); + } catch { + disable(binding, "protocol", "Terminal interceptor returned an invalid response and was disabled"); + return; + } + const message = envelope.frame; + if (message.type !== "netcatty:terminal-interceptor:result") { + disable(binding, "protocol", "Terminal interceptor returned an invalid response and was disabled"); + return; + } + const pending = binding.pending.get(message.sequence); + if (!pending) { + disable(binding, "protocol", "Terminal interceptor returned an unsolicited or duplicate response and was disabled"); + return; + } + binding.pending.delete(message.sequence); + clearTimeout(pending.timer); + if (now() >= pending.deadlineAt) { + pending.resolve(null); + disable(binding, "timeout", `Terminal ${binding.direction} interceptor exceeded its ${pending.deadlineMs} ms budget`); + return; + } + if (message.status !== "ok" || message.creditBytes !== pending.sentBytes) { + pending.resolve(null); + disable(binding, "protocol", "Terminal interceptor returned an invalid response and was disabled"); + return; + } + pending.resolve(new Uint8Array(envelope.transfer)); + }); + port.on?.("close", () => disable(binding, "closed", "Terminal interceptor stopped and was disabled")); + port.postMessage(createTerminalInterceptorEnvelope({ + type: "netcatty:terminal-interceptor:ready", + sessionId, + direction, + windowBytes: direction === "output" ? outputWindowBytes : MAX_CHUNK_BYTES, + })); + bindings.set(key, binding); + refreshOutputMode(sessionId); + if (previousRawTail !== undefined) outputRawTails.set(sessionId, previousRawTail); + if (direction === "input") { + const lastVisibleLine = previousRawTail === undefined + ? "" + : (visibleTerminalTail(previousRawTail).split(/[\r\n]/u).at(-1) ?? ""); + if (wasSensitive || SENSITIVE_PROMPT.test(lastVisibleLine)) { + sensitiveInputSessions.add(sessionId); + } + } + } + + function detach(sessionId, direction, reason = "detached") { + const directions = direction ? [direction] : ["input", "output"]; + for (const item of directions) { + const binding = bindings.get(keyOf(sessionId, item)); + if (binding) disable(binding, reason, "Terminal interceptor was detached from this session"); + } + } + + function requestChunk(binding, bytes, deadlineAt, deadlineMs) { + if (!binding.active) return Promise.resolve(null); + const remainingMs = deadlineAt - now(); + if (remainingMs <= 0) { + disable(binding, "timeout", `Terminal ${binding.direction} interceptor exceeded its ${deadlineMs} ms budget`); + return Promise.resolve(null); + } + const sequence = binding.nextSequence++; + const data = toTransferBuffer(bytes); + return new Promise((resolve) => { + const timer = setTimeout(() => { + binding.pending.delete(sequence); + resolve(null); + disable(binding, "timeout", `Terminal ${binding.direction} interceptor exceeded its ${deadlineMs} ms budget`); + }, remainingMs); + binding.pending.set(sequence, { + resolve, + timer, + deadlineAt, + deadlineMs, + sentBytes: bytes.byteLength, + }); + try { + const envelope = createTerminalInterceptorEnvelope({ + type: "netcatty:terminal-interceptor:chunk", + sequence, + direction: binding.direction, + creditBytes: binding.direction === "output" + ? Math.max(0, outputWindowBytes - binding.queuedBytes) + : MAX_CHUNK_BYTES, + byteLength: data.byteLength, + }, data); + binding.port.postMessage(envelope, [data]); + } catch { + clearTimeout(timer); + binding.pending.delete(sequence); + resolve(null); + disable(binding, "closed", "Terminal interceptor transport failed and was disabled"); + } + }); + } + + function observeOutput(sessionId, data) { + const mode = outputModes.get(sessionId) ?? 0; + let sensitivePrompt = false; + if (mode !== 0) { + // Retain bounded raw output so an ANSI sequence split across chunks can + // be stripped only after its terminating byte arrives. Persisting the + // already-stripped tail would turn an incomplete CSI into visible text + // and could split a password label such as "Pass\x1b[0" + "mword:". + const rawTail = `${outputRawTails.get(sessionId) ?? ""}${data}` + .slice(-(PROMPT_TAIL_CHARS * 2)); + outputRawTails.set(sessionId, rawTail); + const tail = visibleTerminalTail(rawTail); + const lastLine = tail.split(/[\r\n]/u).at(-1) ?? ""; + sensitivePrompt = SENSITIVE_PROMPT.test(lastLine); + if ((mode & 1) !== 0) { + if (sensitivePrompt) sensitiveInputSessions.add(sessionId); + else if (CONFIRMED_SHELL_PROMPT.test(lastLine)) sensitiveInputSessions.delete(sessionId); + } + } + return (mode & 1) !== 0 ? sensitiveInputSessions.has(sessionId) : sensitivePrompt; + } + + async function transform(sessionId, direction, data, options = {}) { + const binding = bindings.get(keyOf(sessionId, direction)); + if (!binding?.active) { + return data; + } + const hostSensitive = direction === "input" && sensitiveInputSessions.has(sessionId); + if (options.bypass === true || (direction === "input" && options.sensitive === true) || hostSensitive) { + const finishPassthrough = () => { + if (hostSensitive && /[\r\n]/u.test(String(data))) { + sensitiveInputSessions.delete(sessionId); + outputRawTails.delete(sessionId); + } + return data; + }; + const passthrough = binding.queue.then(finishPassthrough, finishPassthrough); + binding.queue = passthrough.then(() => undefined, () => undefined); + return passthrough; + } + const bytes = encoder.encode(String(data)); + if (bytes.byteLength === 0) return data; + const deadlineMs = direction === "input" ? inputDeadlineMs : outputDeadlineMs; + const deadlineAt = now() + deadlineMs; + if (direction === "output" && binding.queuedBytes + bytes.byteLength > outputWindowBytes) { + // Chain the fail-open chunk behind all earlier work before disabling the + // binding. disable() releases pending requests, and this queue barrier + // ensures callers cannot deliver the newer chunk first. + const passthrough = binding.queue.then(() => data, () => data); + binding.queue = passthrough.then(() => undefined, () => undefined); + disable(binding, "backpressure", "Terminal output interceptor exceeded its bounded credit window"); + return passthrough; + } + binding.queuedBytes += bytes.byteLength; + const run = async () => { + const output = []; + for (let offset = 0; offset < bytes.byteLength;) { + if (!binding.active) return data; + const end = nextUtf8ChunkEnd(bytes, offset); + const chunk = bytes.subarray(offset, end); + offset = end; + const result = await requestChunk( + binding, + chunk, + deadlineAt, + deadlineMs, + ); + if (!result) return data; + output.push(result); + offset = end; + } + try { + const total = output.reduce((sum, item) => sum + item.byteLength, 0); + if (direction === "output") { + // Each original byte replenishes one byte of expansion credit. This + // permits a bounded 2x steady-state rewrite plus one initial window + // burst, while repeated tiny-to-64-KiB expansion trips fail-open + // before it can outrun the renderer's display-byte queue. + const replenishedCredit = Math.min( + outputWindowBytes, + binding.outputExpansionCreditBytes + bytes.byteLength, + ); + const expansionBytes = Math.max(0, total - bytes.byteLength); + if (total > outputWindowBytes || expansionBytes > replenishedCredit) { + disable( + binding, + "backpressure", + "Terminal output interceptor exceeded its bounded expansion credit", + ); + return data; + } + binding.outputExpansionCreditBytes = replenishedCredit - expansionBytes; + } + const combined = new Uint8Array(total); + let offset = 0; + for (const item of output) { + combined.set(item, offset); + offset += item.byteLength; + } + return decoder.decode(combined); + } catch { + disable(binding, "encoding", "Terminal interceptor returned invalid UTF-8 and was disabled"); + return data; + } + }; + const result = binding.queue.then(run, run); + binding.queue = result.then(() => undefined, () => undefined); + try { return await result; } + finally { binding.queuedBytes = Math.max(0, binding.queuedBytes - bytes.byteLength); } + } + + return Object.freeze({ + attach, + detach, + interceptInput: (sessionId, data, options) => transform(sessionId, "input", data, options), + interceptOutput: (sessionId, data, options) => transform(sessionId, "output", data, options), + has: (sessionId, direction) => bindings.has(keyOf(sessionId, direction)), + getOutputMode: (sessionId) => outputModes.get(sessionId) ?? 0, + observeOutput, + clearSensitiveInput(sessionId) { + sensitiveInputSessions.delete(sessionId); + outputRawTails.delete(sessionId); + }, + shutdown() { + for (const binding of [...bindings.values()]) disable(binding, "shutdown", "Terminal interceptor stopped"); + }, + }); +} + +module.exports = { + INPUT_DEADLINE_MS, + MAX_CHUNK_BYTES, + OUTPUT_DEADLINE_MS, + OUTPUT_WINDOW_BYTES, + nextUtf8ChunkEnd, + visibleTerminalTail, + createTerminalDataPipeline, +}; diff --git a/electron/terminalWorker/terminalDataPipeline.test.cjs b/electron/terminalWorker/terminalDataPipeline.test.cjs new file mode 100644 index 000000000..3e45e0103 --- /dev/null +++ b/electron/terminalWorker/terminalDataPipeline.test.cjs @@ -0,0 +1,459 @@ +"use strict"; + +const assert = require("node:assert/strict"); +const { MessageChannel } = require("node:worker_threads"); +const test = require("node:test"); + +const { + createTerminalDataPipeline, +} = require("./terminalDataPipeline.cjs"); +const { + createTerminalInterceptorEnvelope, +} = require("../plugins/terminalInterceptorTransport.cjs"); + +function listen(port, listener) { + port.on("message", listener); + port.start?.(); +} + +function readFrame(message) { + return createTerminalInterceptorEnvelope(message?.frame, message?.transfer); +} + +function postResult(port, sequence, creditBytes, data) { + const envelope = createTerminalInterceptorEnvelope({ + type: "netcatty:terminal-interceptor:result", + sequence, + status: "ok", + creditBytes, + byteLength: data.byteLength, + }, data); + port.postMessage(envelope, [data]); +} + +function attachTransform(pipeline, options = {}) { + const channel = new MessageChannel(); + channel.port1.unref?.(); + channel.port2.unref?.(); + const seen = []; + listen(channel.port2, (message) => { + const envelope = readFrame(message); + const frame = envelope.frame; + if (frame.type !== "netcatty:terminal-interceptor:chunk") return; + seen.push({ sequence: frame.sequence, data: Buffer.from(envelope.transfer).toString("utf8") }); + if (options.hold) return; + const transformed = Buffer.from(options.transform?.(Buffer.from(envelope.transfer).toString("utf8")) + ?? Buffer.from(envelope.transfer).toString("utf8").toUpperCase()); + const data = Uint8Array.from(transformed).buffer; + postResult(channel.port2, frame.sequence, frame.byteLength, data); + }); + pipeline.attach({ + sessionId: options.sessionId ?? "session-1", + direction: options.direction ?? "input", + providerId: "com.example.interceptor", + pluginId: "com.example", + pluginVersion: "1.0.0", + runtimeId: "runtime-1", + runtimeKind: "utility", + securityPrincipal: "principal-1", + }, channel.port1); + return { channel, seen }; +} + +test("terminal input interception transfers bounded UTF-8 chunks and preserves ordering", async () => { + const pipeline = createTerminalDataPipeline({ inputDeadlineMs: 100 }); + const { seen } = attachTransform(pipeline); + assert.equal(await pipeline.interceptInput("session-1", "hello"), "HELLO"); + assert.equal(await pipeline.interceptInput("session-1", "world"), "WORLD"); + assert.deepEqual(seen, [ + { sequence: 1, data: "hello" }, + { sequence: 2, data: "world" }, + ]); + pipeline.shutdown(); +}); + +test("terminal interception keeps multi-byte UTF-8 characters whole at the chunk boundary", async () => { + for (const direction of ["input", "output"]) { + const pipeline = createTerminalDataPipeline({ inputDeadlineMs: 100, outputDeadlineMs: 100 }); + const { seen } = attachTransform(pipeline, { direction, transform: (value) => value }); + const value = `${"a".repeat(65535)}你b`; + const result = direction === "input" + ? await pipeline.interceptInput("session-1", value) + : await pipeline.interceptOutput("session-1", value); + assert.equal(result, value); + assert.deepEqual(seen.map((entry) => Buffer.byteLength(entry.data)), [65535, 4]); + assert.equal(seen.map((entry) => entry.data).join(""), value); + pipeline.shutdown(); + } +}); + +test("sensitive input bypasses the third-party port unconditionally", async () => { + const pipeline = createTerminalDataPipeline({ inputDeadlineMs: 100 }); + const { seen } = attachTransform(pipeline); + assert.equal(await pipeline.interceptInput("session-1", "password\r", { sensitive: true }), "password\r"); + await new Promise((resolve) => setImmediate(resolve)); + assert.deepEqual(seen, []); + assert.equal(pipeline.has("session-1", "input"), true); + pipeline.shutdown(); +}); + +test("sensitive passthrough stays ordered behind earlier intercepted input", async () => { + const pipeline = createTerminalDataPipeline({ inputDeadlineMs: 100 }); + const channel = new MessageChannel(); + channel.port1.unref?.(); + channel.port2.unref?.(); + let firstChunk; + listen(channel.port2, (message) => { + const envelope = readFrame(message); + if (envelope.frame.type === "netcatty:terminal-interceptor:chunk") firstChunk = envelope.frame; + }); + pipeline.attach({ + sessionId: "session-1", + direction: "input", + providerId: "com.example.interceptor", + pluginId: "com.example", + pluginVersion: "1.0.0", + runtimeId: "runtime-1", + runtimeKind: "utility", + securityPrincipal: "principal-1", + }, channel.port1); + const order = []; + const ordinary = pipeline.interceptInput("session-1", "a").then((value) => order.push(value)); + const sensitive = pipeline.interceptInput("session-1", "secret", { sensitive: true }) + .then((value) => order.push(value)); + await new Promise((resolve) => setImmediate(resolve)); + assert.ok(firstChunk); + assert.deepEqual(order, []); + const result = Uint8Array.from(Buffer.from("A")).buffer; + postResult(channel.port2, firstChunk.sequence, 1, result); + await Promise.all([ordinary, sensitive]); + assert.deepEqual(order, ["A", "secret"]); + pipeline.shutdown(); +}); + +test("replacing an input interceptor preserves host-detected sensitive state", async () => { + const pipeline = createTerminalDataPipeline({ inputDeadlineMs: 100 }); + const first = attachTransform(pipeline, { transform: (data) => data }); + pipeline.observeOutput("session-1", "Password:"); + assert.equal(await pipeline.interceptInput("session-1", "first-secret"), "first-secret"); + + const second = attachTransform(pipeline, { transform: (data) => data }); + assert.equal(await pipeline.interceptInput("session-1", "second-secret"), "second-secret"); + await new Promise((resolve) => setImmediate(resolve)); + assert.equal(second.seen.length, 0); + + pipeline.shutdown(); + first.channel.port2.close(); + second.channel.port2.close(); +}); + +test("original output protects password input even when a plugin could hide the prompt", async () => { + const pipeline = createTerminalDataPipeline({ inputDeadlineMs: 100 }); + const { seen } = attachTransform(pipeline); + assert.equal(pipeline.getOutputMode("session-1"), 1); + pipeline.observeOutput("session-1", "\u001b[31mPass"); + pipeline.observeOutput("session-1", "word:\u001b[0m "); + assert.equal(await pipeline.interceptInput("session-1", "hunter2"), "hunter2"); + assert.equal(await pipeline.interceptInput("session-1", "\r"), "\r"); + assert.deepEqual(seen, []); + assert.equal(await pipeline.interceptInput("session-1", "next"), "NEXT"); + assert.deepEqual(seen, [{ sequence: 1, data: "next" }]); + pipeline.observeOutput("session-1", "Pass\u001b[0"); + assert.equal(pipeline.observeOutput("session-1", "mword: "), true); + assert.equal(await pipeline.interceptInput("session-1", "split-secret\r"), "split-secret\r"); + pipeline.observeOutput("session-1", "Custom authentication> "); + assert.equal(await pipeline.interceptInput("session-1", "opaque\r"), "opaque\r"); + pipeline.observeOutput("session-1", "请输入验证码:"); + assert.equal(await pipeline.interceptInput("session-1", "123456\r"), "123456\r"); + assert.deepEqual(seen, [{ sequence: 1, data: "next" }]); + pipeline.shutdown(); +}); + +test("a confirmed shell prompt clears sensitive mode when authentication is abandoned", async () => { + const pipeline = createTerminalDataPipeline({ inputDeadlineMs: 100 }); + const { seen } = attachTransform(pipeline); + + assert.equal(pipeline.observeOutput("session-1", "Password: "), true); + assert.equal(await pipeline.interceptInput("session-1", "secret"), "secret"); + assert.deepEqual(seen, []); + + assert.equal(pipeline.observeOutput("session-1", "\r\nAccess denied\r\n$ "), false); + assert.equal(await pipeline.interceptInput("session-1", "next"), "NEXT"); + assert.deepEqual(seen, [{ sequence: 1, data: "next" }]); + pipeline.shutdown(); +}); + +test("output-only interception classifies sensitive prompts without retaining stale input state", () => { + const pipeline = createTerminalDataPipeline(); + attachTransform(pipeline, { direction: "output" }); + + assert.equal(pipeline.observeOutput("session-1", "Pass"), false); + assert.equal(pipeline.observeOutput("session-1", "word: "), true); + assert.equal(pipeline.observeOutput("session-1", "\r\nordinary output"), false); + pipeline.shutdown(); +}); + +test("an input interceptor attached after a visible password prompt starts in sensitive mode", async () => { + const pipeline = createTerminalDataPipeline({ inputDeadlineMs: 100 }); + attachTransform(pipeline, { direction: "output", transform: (data) => data }); + assert.equal(pipeline.observeOutput("session-1", "Password: "), true); + + const { seen } = attachTransform(pipeline, { direction: "input" }); + assert.equal(await pipeline.interceptInput("session-1", "secret\r"), "secret\r"); + assert.deepEqual(seen, []); + pipeline.shutdown(); +}); + +test("clearing sensitive input on interrupt restores ordinary interception", async () => { + const pipeline = createTerminalDataPipeline({ inputDeadlineMs: 100 }); + const { seen } = attachTransform(pipeline); + attachTransform(pipeline, { direction: "output" }); + + assert.equal(pipeline.observeOutput("session-1", "Password: "), true); + assert.equal(await pipeline.interceptInput("session-1", "secret"), "secret"); + assert.deepEqual(seen, []); + + pipeline.clearSensitiveInput("session-1"); + assert.equal(await pipeline.interceptInput("session-1", "next"), "NEXT"); + assert.deepEqual(seen, [{ sequence: 1, data: "next" }]); + pipeline.shutdown(); +}); + +test("an input deadline failure fails open, disables the session binding, and warns once", async () => { + const warnings = []; + const pipeline = createTerminalDataPipeline({ inputDeadlineMs: 5, onWarning: (value) => warnings.push(value) }); + attachTransform(pipeline, { hold: true }); + assert.equal(await pipeline.interceptInput("session-1", "slow"), "slow"); + assert.equal(pipeline.has("session-1", "input"), false); + assert.equal(warnings.length, 1); + assert.equal(warnings[0].code, "timeout"); + assert.equal(await pipeline.interceptInput("session-1", "later"), "later"); + assert.equal(warnings.length, 1); +}); + +test("an elapsed deadline rejects a late response before its delayed timer callback runs", async () => { + const warnings = []; + let now = 1_000; + const pipeline = createTerminalDataPipeline({ + inputDeadlineMs: 100, + now: () => now, + onWarning: (value) => warnings.push(value), + }); + const channel = new MessageChannel(); + channel.port1.unref?.(); + channel.port2.unref?.(); + listen(channel.port2, (message) => { + const envelope = readFrame(message); + if (envelope.frame.type !== "netcatty:terminal-interceptor:chunk") return; + now += 100; + const data = Uint8Array.from(Buffer.from("LATE")).buffer; + postResult(channel.port2, envelope.frame.sequence, envelope.frame.byteLength, data); + }); + pipeline.attach({ + sessionId: "session-1", + direction: "input", + providerId: "com.example.interceptor", + pluginId: "com.example", + pluginVersion: "1.0.0", + runtimeId: "runtime-1", + runtimeKind: "utility", + securityPrincipal: "principal-1", + }, channel.port1); + + assert.equal(await pipeline.interceptInput("session-1", "original"), "original"); + assert.equal(pipeline.has("session-1", "input"), false); + assert.equal(warnings.length, 1); + assert.equal(warnings[0].code, "timeout"); +}); + +test("an unsolicited interceptor result trips the protocol circuit breaker", async () => { + const warnings = []; + const pipeline = createTerminalDataPipeline({ + inputDeadlineMs: 100, + onWarning: (value) => warnings.push(value), + }); + const { channel } = attachTransform(pipeline, { hold: true }); + const data = Uint8Array.from(Buffer.from("UNSOLICITED")).buffer; + postResult(channel.port2, 999, data.byteLength, data); + for (let attempt = 0; attempt < 10 && pipeline.has("session-1", "input"); attempt += 1) { + await new Promise((resolve) => setImmediate(resolve)); + } + assert.equal(pipeline.has("session-1", "input"), false); + assert.deepEqual(warnings.map((warning) => warning.code), ["protocol"]); +}); + +test("a duplicate interceptor result trips the protocol circuit breaker", async () => { + const warnings = []; + const pipeline = createTerminalDataPipeline({ + inputDeadlineMs: 100, + onWarning: (value) => warnings.push(value), + }); + const { channel, seen } = attachTransform(pipeline, { hold: true }); + const transformed = pipeline.interceptInput("session-1", "a"); + for (let attempt = 0; attempt < 10 && seen.length === 0; attempt += 1) { + await new Promise((resolve) => setImmediate(resolve)); + } + assert.equal(seen.length, 1); + const first = Uint8Array.from(Buffer.from("A")).buffer; + const duplicate = Uint8Array.from(Buffer.from("A")).buffer; + postResult(channel.port2, seen[0].sequence, 1, first); + postResult(channel.port2, seen[0].sequence, 1, duplicate); + assert.equal(await transformed, "A"); + await new Promise((resolve) => setImmediate(resolve)); + assert.equal(pipeline.has("session-1", "input"), false); + assert.deepEqual(warnings.map((warning) => warning.code), ["protocol"]); +}); + +test("output interception is credit bounded and fails open under backpressure", async () => { + const warnings = []; + const pipeline = createTerminalDataPipeline({ + outputDeadlineMs: 100, + outputWindowBytes: 5, + onWarning: (value) => warnings.push(value), + }); + attachTransform(pipeline, { direction: "output", hold: true }); + const order = []; + const first = pipeline.interceptOutput("session-1", "1234") + .then((value) => { order.push(value); return value; }); + const second = pipeline.interceptOutput("session-1", "5678") + .then((value) => { order.push(value); return value; }); + assert.deepEqual(await Promise.all([first, second]), ["1234", "5678"]); + assert.deepEqual(order, ["1234", "5678"]); + assert.equal(warnings[0].code, "backpressure"); + assert.equal(pipeline.has("session-1", "output"), false); +}); + +test("output expansion consumes bounded credit before transformed data is delivered", async () => { + const warnings = []; + const pipeline = createTerminalDataPipeline({ + outputDeadlineMs: 100, + outputWindowBytes: 5, + onWarning: (value) => warnings.push(value), + }); + attachTransform(pipeline, { + direction: "output", + transform: () => "12345", + }); + + assert.equal(await pipeline.interceptOutput("session-1", "a"), "12345"); + assert.equal(await pipeline.interceptOutput("session-1", "b"), "b"); + assert.equal(pipeline.has("session-1", "output"), false); + assert.equal(warnings.at(-1).code, "backpressure"); +}); + +test("queued output keeps the deadline from its arrival time", async () => { + let now = 0; + const warnings = []; + const pipeline = createTerminalDataPipeline({ + now: () => now, + outputDeadlineMs: 100, + onWarning: (value) => warnings.push(value), + }); + const channel = new MessageChannel(); + channel.port1.unref?.(); + channel.port2.unref?.(); + const chunks = []; + listen(channel.port2, (message) => { + const envelope = readFrame(message); + if (envelope.frame.type === "netcatty:terminal-interceptor:chunk") chunks.push(envelope.frame); + }); + pipeline.attach({ + sessionId: "session-1", + direction: "output", + providerId: "com.example.interceptor", + pluginId: "com.example", + pluginVersion: "1.0.0", + runtimeId: "runtime-1", + runtimeKind: "utility", + securityPrincipal: "principal-1", + }, channel.port1); + + const first = pipeline.interceptOutput("session-1", "first"); + const second = pipeline.interceptOutput("session-1", "second"); + for (let attempt = 0; attempt < 10 && chunks.length < 1; attempt += 1) { + await new Promise((resolve) => setImmediate(resolve)); + } + assert.equal(chunks.length, 1); + now = 90; + const firstData = Uint8Array.from(Buffer.from("FIRST")).buffer; + postResult(channel.port2, chunks[0].sequence, 5, firstData); + for (let attempt = 0; attempt < 10 && chunks.length < 2; attempt += 1) { + await new Promise((resolve) => setImmediate(resolve)); + } + assert.equal(chunks.length, 2); + now = 101; + const secondData = Uint8Array.from(Buffer.from("SECOND")).buffer; + postResult(channel.port2, chunks[1].sequence, 6, secondData); + + assert.deepEqual(await Promise.all([first, second]), ["FIRST", "second"]); + assert.equal(warnings.at(-1).code, "timeout"); + assert.equal(pipeline.has("session-1", "output"), false); +}); + +test("invalid interceptor UTF-8 fails open and permanently trips the circuit breaker", async () => { + const warnings = []; + const pipeline = createTerminalDataPipeline({ inputDeadlineMs: 100, onWarning: (value) => warnings.push(value) }); + const channel = new MessageChannel(); + channel.port1.unref?.(); + channel.port2.unref?.(); + listen(channel.port2, (message) => { + const envelope = readFrame(message); + if (envelope.frame.type !== "netcatty:terminal-interceptor:chunk") return; + const data = Uint8Array.from([0xff]).buffer; + postResult(channel.port2, envelope.frame.sequence, 4, data); + }); + pipeline.attach({ + sessionId: "session-1", + direction: "input", + providerId: "com.example.interceptor", + pluginId: "com.example", + pluginVersion: "1.0.0", + runtimeId: "runtime-1", + runtimeKind: "utility", + securityPrincipal: "principal-1", + }, channel.port1); + assert.equal(await pipeline.interceptInput("session-1", "safe"), "safe"); + assert.equal(warnings[0].code, "encoding"); + assert.equal(pipeline.has("session-1", "input"), false); +}); + +test("the worker rejects a result that bypasses the canonical terminal frame schema", async () => { + const warnings = []; + const pipeline = createTerminalDataPipeline({ + inputDeadlineMs: 100, + onWarning: (value) => warnings.push(value), + }); + const channel = new MessageChannel(); + channel.port1.unref?.(); + channel.port2.unref?.(); + listen(channel.port2, (message) => { + const envelope = readFrame(message); + if (envelope.frame.type !== "netcatty:terminal-interceptor:chunk") return; + const data = Uint8Array.from(Buffer.from("UNSAFE")).buffer; + channel.port2.postMessage({ + frame: { + type: "netcatty:terminal-interceptor:result", + sequence: envelope.frame.sequence, + status: "ok", + creditBytes: envelope.frame.byteLength, + byteLength: data.byteLength, + extra: true, + }, + transfer: data, + }, [data]); + }); + pipeline.attach({ + sessionId: "session-1", + direction: "input", + providerId: "com.example.interceptor", + pluginId: "com.example", + pluginVersion: "1.0.0", + runtimeId: "runtime-1", + runtimeKind: "utility", + securityPrincipal: "principal-1", + }, channel.port1); + + assert.equal(await pipeline.interceptInput("session-1", "safe"), "safe"); + assert.equal(pipeline.has("session-1", "input"), false); + assert.equal(warnings.at(-1).code, "protocol"); +}); diff --git a/packages/plugin-cli/src/manifest.ts b/packages/plugin-cli/src/manifest.ts index 311b8239c..8cee574c5 100644 --- a/packages/plugin-cli/src/manifest.ts +++ b/packages/plugin-cli/src/manifest.ts @@ -466,6 +466,13 @@ function validateSemantics(manifest: PluginManifest): string[] { for (const permission of providerPermissions.get(provider.kind) ?? ["provider.terminal"]) { requirePermission(true, permission, `Provider ${provider.id}`); } + if (provider.kind === "terminal.interceptor.input" + || provider.kind === "terminal.interceptor.output") { + requirePermission(true, "runtime.advanced", `Provider ${provider.id}`); + if (!manifest.main.node) { + errors.push(`Provider ${provider.id} requires a Node utility entrypoint`); + } + } } for (const companion of manifest.companionExecutables ?? []) { for (const permission of companion.permissions ?? []) { diff --git a/packages/plugin-contract/schema/plugin-contract.schema.json b/packages/plugin-contract/schema/plugin-contract.schema.json index 40bb56885..47aaa61d4 100644 --- a/packages/plugin-contract/schema/plugin-contract.schema.json +++ b/packages/plugin-contract/schema/plugin-contract.schema.json @@ -63,6 +63,13 @@ "maxCreditBytes": 16777216 } }, + "TerminalInterceptorLimits": { + "description": "Host-enforced byte and receive-window limits for the privileged direct terminal interceptor MessagePort.", + "const": { + "maxChunkBytes": 65536, + "maxWindowBytes": 262144 + } + }, "StreamId": { "type": "string", "minLength": 1, @@ -727,7 +734,7 @@ "not": { "required": ["method"], "properties": { - "method": { "enum": ["plugin.initialize", "$/cancelRequest", "$/progress"] } + "method": { "enum": ["plugin.initialize", "plugin.terminal.interceptor.attach", "$/cancelRequest", "$/progress"] } } }, "additionalProperties": false @@ -744,7 +751,7 @@ "not": { "required": ["method"], "properties": { - "method": { "enum": ["plugin.initialize", "$/cancelRequest", "$/progress"] } + "method": { "enum": ["plugin.initialize", "plugin.terminal.interceptor.attach", "$/cancelRequest", "$/progress"] } } }, "additionalProperties": false @@ -1002,6 +1009,78 @@ } ] }, + "TerminalInterceptorDirection": { + "type": "string", + "enum": ["input", "output"] + }, + "TerminalInterceptorChunkByteLength": { + "type": "integer", + "minimum": 0, + "maximum": 65536 + }, + "TerminalInterceptorWindowBytes": { + "type": "integer", + "minimum": 1, + "maximum": 262144 + }, + "TerminalInterceptorCreditBytes": { + "type": "integer", + "minimum": 0, + "maximum": 262144 + }, + "TerminalInterceptorReadyFrame": { + "type": "object", + "required": ["type", "sessionId", "direction", "windowBytes"], + "properties": { + "type": { "const": "netcatty:terminal-interceptor:ready" }, + "sessionId": { "type": "string", "minLength": 1, "maxLength": 256, "pattern": "^[^\\u0000]+$" }, + "direction": { "$ref": "#/$defs/TerminalInterceptorDirection" }, + "windowBytes": { "$ref": "#/$defs/TerminalInterceptorWindowBytes" } + }, + "additionalProperties": false + }, + "TerminalInterceptorChunkFrame": { + "type": "object", + "required": ["type", "sequence", "direction", "creditBytes", "byteLength"], + "properties": { + "type": { "const": "netcatty:terminal-interceptor:chunk" }, + "sequence": { "$ref": "#/$defs/SafePositiveInteger" }, + "direction": { "$ref": "#/$defs/TerminalInterceptorDirection" }, + "creditBytes": { "$ref": "#/$defs/TerminalInterceptorCreditBytes" }, + "byteLength": { "$ref": "#/$defs/TerminalInterceptorChunkByteLength" } + }, + "additionalProperties": false + }, + "TerminalInterceptorOkResultFrame": { + "type": "object", + "required": ["type", "sequence", "status", "creditBytes", "byteLength"], + "properties": { + "type": { "const": "netcatty:terminal-interceptor:result" }, + "sequence": { "$ref": "#/$defs/SafePositiveInteger" }, + "status": { "const": "ok" }, + "creditBytes": { "$ref": "#/$defs/TerminalInterceptorChunkByteLength" }, + "byteLength": { "$ref": "#/$defs/TerminalInterceptorChunkByteLength" } + }, + "additionalProperties": false + }, + "TerminalInterceptorFailedResultFrame": { + "type": "object", + "required": ["type", "sequence", "status"], + "properties": { + "type": { "const": "netcatty:terminal-interceptor:result" }, + "sequence": { "$ref": "#/$defs/SafePositiveInteger" }, + "status": { "const": "failed" } + }, + "additionalProperties": false + }, + "TerminalInterceptorFrame": { + "oneOf": [ + { "$ref": "#/$defs/TerminalInterceptorReadyFrame" }, + { "$ref": "#/$defs/TerminalInterceptorChunkFrame" }, + { "$ref": "#/$defs/TerminalInterceptorOkResultFrame" }, + { "$ref": "#/$defs/TerminalInterceptorFailedResultFrame" } + ] + }, "RuntimeInitializeParams": { "type": "object", "required": ["netcattyVersion", "apiVersion", "supportedFeatures"], @@ -1056,6 +1135,78 @@ }, "additionalProperties": false }, + "TerminalSessionSnapshot": { + "type": "object", + "required": ["sessionId", "protocol", "status"], + "properties": { + "sessionId": { "type": "string", "minLength": 1, "maxLength": 256, "pattern": "^[^\\u0000]+$" }, + "hostId": { "type": "string", "minLength": 1, "maxLength": 256, "pattern": "^[^\\u0000]+$" }, + "workspaceId": { "type": "string", "minLength": 1, "maxLength": 256, "pattern": "^[^\\u0000]+$" }, + "protocol": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]*$" + }, + "status": { "type": "string", "enum": ["connecting", "connected", "disconnected"] }, + "cwd": { "type": "string", "minLength": 1, "maxLength": 4096, "pattern": "^[^\\u0000]+$" }, + "title": { "type": "string", "minLength": 1, "maxLength": 1024, "pattern": "^[^\\u0000]+$" }, + "shellType": { "type": "string", "enum": ["posix", "fish", "powershell", "cmd", "unknown"] }, + "cols": { "type": "integer", "minimum": 1, "maximum": 16384 }, + "rows": { "type": "integer", "minimum": 1, "maximum": 16384 }, + "alternateScreen": { "type": "boolean" } + }, + "additionalProperties": false + }, + "TerminalInterceptorAttachmentDescriptor": { + "type": "object", + "required": ["providerId", "direction", "session"], + "properties": { + "providerId": { "$ref": "#/$defs/ContributionId" }, + "direction": { "type": "string", "enum": ["input", "output"] }, + "session": { "$ref": "#/$defs/TerminalSessionSnapshot" } + }, + "additionalProperties": false + }, + "TerminalInterceptorAttachmentParams": { + "type": "object", + "required": ["descriptor"], + "properties": { + "descriptor": { "$ref": "#/$defs/TerminalInterceptorAttachmentDescriptor" } + }, + "additionalProperties": false + }, + "TerminalInterceptorAttachmentResult": { + "type": "object", + "required": ["accepted"], + "properties": { + "accepted": { "const": true } + }, + "additionalProperties": false + }, + "TerminalInterceptorAttachmentRequest": { + "type": "object", + "required": ["jsonrpc", "id", "method", "params"], + "properties": { + "jsonrpc": { "const": "2.0" }, + "id": { "$ref": "#/$defs/RpcId" }, + "method": { "const": "plugin.terminal.interceptor.attach" }, + "params": { "$ref": "#/$defs/TerminalInterceptorAttachmentParams" }, + "deadlineMs": { "type": "integer", "minimum": 1, "maximum": 300000 }, + "cancellationId": { "type": "string", "minLength": 1, "maxLength": 128 } + }, + "additionalProperties": false + }, + "TerminalInterceptorAttachmentSuccess": { + "type": "object", + "required": ["jsonrpc", "id", "result"], + "properties": { + "jsonrpc": { "const": "2.0" }, + "id": { "$ref": "#/$defs/RpcId" }, + "result": { "$ref": "#/$defs/TerminalInterceptorAttachmentResult" } + }, + "additionalProperties": false + }, "RpcMessage": { "description": "A mutually exclusive RPC wire envelope. Reserved inbound methods use their exact schemas. Successful responses require method-specific validation through request correlation.", "oneOf": [ @@ -1065,7 +1216,8 @@ { "$ref": "#/$defs/RpcFailure" }, { "$ref": "#/$defs/RpcCancel" }, { "$ref": "#/$defs/RpcProgressNotification" }, - { "$ref": "#/$defs/RuntimeInitializeRequest" } + { "$ref": "#/$defs/RuntimeInitializeRequest" }, + { "$ref": "#/$defs/TerminalInterceptorAttachmentRequest" } ] }, "PermissionGrantScope": { @@ -1097,7 +1249,14 @@ }, "reason": { "type": "string", "minLength": 1, "maxLength": 1024 }, "operationId": { "type": "string", "minLength": 1, "maxLength": 128 }, - "sessionId": { "type": "string", "minLength": 1, "maxLength": 128 } + "sessionId": { "type": "string", "minLength": 1, "maxLength": 128 }, + "allowedScopes": { + "type": "array", + "minItems": 1, + "maxItems": 4, + "uniqueItems": true, + "items": { "$ref": "#/$defs/PermissionGrantScope" } + } }, "additionalProperties": false }, diff --git a/packages/plugin-contract/src/contract.test.ts b/packages/plugin-contract/src/contract.test.ts index 004efcb25..4ffa69ab5 100644 --- a/packages/plugin-contract/src/contract.test.ts +++ b/packages/plugin-contract/src/contract.test.ts @@ -59,6 +59,55 @@ test("plugin manifest schema accepts the internal contract", () => { assert.equal(validate({ ...validManifest, version: "1.0.0-01" }), false); }); +test("terminal interceptor fast-path frames are owned by the canonical schema", () => { + const validate = validator("TerminalInterceptorFrame"); + assert.equal(validate({ + type: "netcatty:terminal-interceptor:ready", + sessionId: "session-1", + direction: "input", + windowBytes: 65_536, + }), true, JSON.stringify(validate.errors)); + assert.equal(validate({ + type: "netcatty:terminal-interceptor:chunk", + sequence: 1, + direction: "output", + creditBytes: 262_144, + byteLength: 65_536, + }), true, JSON.stringify(validate.errors)); + assert.equal(validate({ + type: "netcatty:terminal-interceptor:result", + sequence: 1, + status: "ok", + creditBytes: 65_536, + byteLength: 0, + }), true, JSON.stringify(validate.errors)); + assert.equal(validate({ + type: "netcatty:terminal-interceptor:result", + sequence: 1, + status: "failed", + }), true, JSON.stringify(validate.errors)); + assert.equal(validate({ + type: "netcatty:terminal-interceptor:chunk", + sequence: 0, + direction: "input", + creditBytes: 1, + byteLength: 1, + }), false); + assert.equal(validate({ + type: "netcatty:terminal-interceptor:chunk", + sequence: 1, + direction: "input", + creditBytes: 1, + byteLength: 65_537, + }), false); + assert.equal(validate({ + type: "netcatty:terminal-interceptor:result", + sequence: 1, + status: "failed", + byteLength: 0, + }), false); +}); + test("required resource-scoped permissions declare activation-time bounds", () => { const validate = validator("PluginManifest"); const resourceScoped = [ @@ -167,6 +216,10 @@ test("RPC, stream, permission, and provider schemas validate independently", () const initialize = validator("RuntimeInitializeParams"); const initializeRequest = validator("RuntimeInitializeRequest"); const initializeSuccess = validator("RuntimeInitializeSuccess"); + const interceptorAttachmentParams = validator("TerminalInterceptorAttachmentParams"); + const interceptorAttachmentResult = validator("TerminalInterceptorAttachmentResult"); + const interceptorAttachmentRequest = validator("TerminalInterceptorAttachmentRequest"); + const interceptorAttachmentSuccess = validator("TerminalInterceptorAttachmentSuccess"); const permission = validator("PermissionRequest"); const permissionDecision = validator("PermissionDecision"); const secretRef = validator("SecretRef"); @@ -242,6 +295,57 @@ test("RPC, stream, permission, and provider schemas validate independently", () id: "init-1", result: { unsupportedShape: true }, }), false); + const attachmentParams = { + descriptor: { + providerId: "com.example.contract-test.interceptor", + direction: "input", + session: { + sessionId: "terminal-session-1", + protocol: "ssh", + status: "connected", + cols: 120, + rows: 40, + }, + }, + }; + assert.equal(interceptorAttachmentParams(attachmentParams), true, JSON.stringify(interceptorAttachmentParams.errors)); + assert.equal(interceptorAttachmentParams({ + descriptor: { ...attachmentParams.descriptor, session: { sessionId: "terminal-session-1" } }, + }), false); + assert.equal(interceptorAttachmentParams({ + descriptor: { ...attachmentParams.descriptor, unexpected: true }, + }), false); + assert.equal(interceptorAttachmentResult({ accepted: true }), true, JSON.stringify(interceptorAttachmentResult.errors)); + assert.equal(interceptorAttachmentResult({ accepted: false }), false); + assert.equal(interceptorAttachmentResult({ accepted: true, unexpected: true }), false); + assert.equal(interceptorAttachmentRequest({ + jsonrpc: "2.0", + id: "attach-1", + method: "plugin.terminal.interceptor.attach", + params: attachmentParams, + }), true, JSON.stringify(interceptorAttachmentRequest.errors)); + assert.equal(rpcMessage({ + jsonrpc: "2.0", + id: "attach-1", + method: "plugin.terminal.interceptor.attach", + params: attachmentParams, + }), true, JSON.stringify(rpcMessage.errors)); + assert.equal(rpcMessage({ + jsonrpc: "2.0", + id: "attach-1", + method: "plugin.terminal.interceptor.attach", + params: { descriptor: { providerId: "com.example.contract-test.interceptor" } }, + }), false); + assert.equal(interceptorAttachmentSuccess({ + jsonrpc: "2.0", + id: "attach-1", + result: { accepted: true }, + }), true, JSON.stringify(interceptorAttachmentSuccess.errors)); + assert.equal(interceptorAttachmentSuccess({ + jsonrpc: "2.0", + id: "attach-1", + result: { accepted: false }, + }), false); assert.equal(failure({ jsonrpc: "2.0", id: null, @@ -924,11 +1028,14 @@ test("terminal provider kinds require their least-privilege data capabilities", }); assert.equal(insufficient.valid, false); assert.match(insufficient.errors.join("\n"), /terminal\.intercept\.input/); + assert.match(insufficient.errors.join("\n"), /runtime\.advanced/); + assert.match(insufficient.errors.join("\n"), /Node utility entrypoint/); const sufficient = validateManifestValue({ ...validManifest, + main: { ...validManifest.main, node: "dist/node.js" }, permissions: { - required: ["provider.terminal", "terminal.intercept.input"], + required: ["runtime.advanced", "provider.terminal", "terminal.intercept.input"], }, contributes: { providers: [provider] }, }); @@ -1047,8 +1154,10 @@ test("planned phase consumers are representable without private application type }, { ...validManifest, + main: { ...validManifest.main, node: "dist/node.js" }, permissions: { required: [ + "runtime.advanced", "provider.terminal", "terminal.intercept.input", "terminal.intercept.output", diff --git a/packages/plugin-contract/src/generated/plugin-contract-limits.ts b/packages/plugin-contract/src/generated/plugin-contract-limits.ts index 8c0fa9e1d..992597cbb 100644 --- a/packages/plugin-contract/src/generated/plugin-contract-limits.ts +++ b/packages/plugin-contract/src/generated/plugin-contract-limits.ts @@ -13,3 +13,5 @@ export const PLUGIN_STREAM_MAX_FRAME_JSON_BYTES = 25165824 as const; export const PLUGIN_STREAM_MIN_WINDOW_BYTES = 1024 as const; export const PLUGIN_STREAM_MAX_WINDOW_BYTES = 16777216 as const; export const PLUGIN_STREAM_MAX_CREDIT_BYTES = 16777216 as const; +export const PLUGIN_TERMINAL_INTERCEPTOR_MAX_CHUNK_BYTES = 65536 as const; +export const PLUGIN_TERMINAL_INTERCEPTOR_MAX_WINDOW_BYTES = 262144 as const; diff --git a/packages/plugin-contract/src/generated/plugin-contract.ts b/packages/plugin-contract/src/generated/plugin-contract.ts index 162de5be6..5b53cd064 100644 --- a/packages/plugin-contract/src/generated/plugin-contract.ts +++ b/packages/plugin-contract/src/generated/plugin-contract.ts @@ -116,6 +116,7 @@ export type PermissionRequest = { reason: string; operationId?: string; sessionId?: string; + allowedScopes?: Array; }; export type PermissionResource = string; @@ -299,7 +300,7 @@ export type RpcId = (string) | (SafeUnsignedInteger); export type RpcLimits = {"maxJsonBytes":1048576}; -export type RpcMessage = (RpcRequest) | (RpcNotification) | (RpcSuccess) | (RpcFailure) | (RpcCancel) | (RpcProgressNotification) | (RuntimeInitializeRequest); +export type RpcMessage = (RpcRequest) | (RpcNotification) | (RpcSuccess) | (RpcFailure) | (RpcCancel) | (RpcProgressNotification) | (RuntimeInitializeRequest) | (TerminalInterceptorAttachmentRequest); export type RpcNotification = { jsonrpc: "2.0"; @@ -461,6 +462,90 @@ export type StreamLimits = {"maxStreamIdLength":128,"maxChunkBytes":16777216,"ma export type StreamWindowBytes = number; +export type TerminalInterceptorAttachmentDescriptor = { + providerId: ContributionId; + direction: "input" | "output"; + session: TerminalSessionSnapshot; +}; + +export type TerminalInterceptorAttachmentParams = { + descriptor: TerminalInterceptorAttachmentDescriptor; +}; + +export type TerminalInterceptorAttachmentRequest = { + jsonrpc: "2.0"; + id: RpcId; + method: "plugin.terminal.interceptor.attach"; + params: TerminalInterceptorAttachmentParams; + deadlineMs?: number; + cancellationId?: string; +}; + +export type TerminalInterceptorAttachmentResult = { + accepted: true; +}; + +export type TerminalInterceptorAttachmentSuccess = { + jsonrpc: "2.0"; + id: RpcId; + result: TerminalInterceptorAttachmentResult; +}; + +export type TerminalInterceptorChunkByteLength = number; + +export type TerminalInterceptorChunkFrame = { + type: "netcatty:terminal-interceptor:chunk"; + sequence: SafePositiveInteger; + direction: TerminalInterceptorDirection; + creditBytes: TerminalInterceptorCreditBytes; + byteLength: TerminalInterceptorChunkByteLength; +}; + +export type TerminalInterceptorCreditBytes = number; + +export type TerminalInterceptorDirection = "input" | "output"; + +export type TerminalInterceptorFailedResultFrame = { + type: "netcatty:terminal-interceptor:result"; + sequence: SafePositiveInteger; + status: "failed"; +}; + +export type TerminalInterceptorFrame = (TerminalInterceptorReadyFrame) | (TerminalInterceptorChunkFrame) | (TerminalInterceptorOkResultFrame) | (TerminalInterceptorFailedResultFrame); + +export type TerminalInterceptorLimits = {"maxChunkBytes":65536,"maxWindowBytes":262144}; + +export type TerminalInterceptorOkResultFrame = { + type: "netcatty:terminal-interceptor:result"; + sequence: SafePositiveInteger; + status: "ok"; + creditBytes: TerminalInterceptorChunkByteLength; + byteLength: TerminalInterceptorChunkByteLength; +}; + +export type TerminalInterceptorReadyFrame = { + type: "netcatty:terminal-interceptor:ready"; + sessionId: string; + direction: TerminalInterceptorDirection; + windowBytes: TerminalInterceptorWindowBytes; +}; + +export type TerminalInterceptorWindowBytes = number; + +export type TerminalSessionSnapshot = { + sessionId: string; + hostId?: string; + workspaceId?: string; + protocol: string; + status: "connecting" | "connected" | "disconnected"; + cwd?: string; + title?: string; + shellType?: "posix" | "fish" | "powershell" | "cmd" | "unknown"; + cols?: number; + rows?: number; + alternateScreen?: boolean; +}; + export type ThemeIcon = { kind: "theme"; name: string; diff --git a/packages/plugin-contract/src/index.ts b/packages/plugin-contract/src/index.ts index 0a744ed37..a53bbab99 100644 --- a/packages/plugin-contract/src/index.ts +++ b/packages/plugin-contract/src/index.ts @@ -12,6 +12,8 @@ export { export { PLUGIN_RPC_ERROR_CODES, PLUGIN_RPC_MAX_JSON_BYTES, + PLUGIN_TERMINAL_INTERCEPTOR_MAX_CHUNK_BYTES, + PLUGIN_TERMINAL_INTERCEPTOR_MAX_WINDOW_BYTES, PLUGIN_WIRE_MAX_SAFE_INTEGER, } from "./generated/plugin-contract-limits.js"; export { diff --git a/packages/plugin-sdk/src/index.test.ts b/packages/plugin-sdk/src/index.test.ts index e37dfc20e..49be11d29 100644 --- a/packages/plugin-sdk/src/index.test.ts +++ b/packages/plugin-sdk/src/index.test.ts @@ -80,6 +80,22 @@ test("PluginSecretStore exposes opaque references instead of plaintext reads", a assert.equal(testSecretRef.key, "token"); }); +test("terminal interceptor typing stays specialized while broad ProviderKind helpers remain compatible", async () => { + const source = await readFile(new URL("./index.ts", import.meta.url), "utf8"); + assert.match( + source, + /kind: Exclude,\s*handler: PluginProviderHandler/u, + ); + assert.match( + source, + /type ProviderHandlerForKind<[\s\S]*K extends TerminalInterceptorKind[\s\S]*TerminalInterceptorHandler/u, + ); + assert.match( + source, + /kind: K,\s*handler: ProviderHandlerForKind, TPayload, TResult>/u, + ); +}); + test("DisposableStore disposes every item once", () => { const store = new DisposableStore(); const calls: string[] = []; diff --git a/packages/plugin-sdk/src/index.ts b/packages/plugin-sdk/src/index.ts index ab52434ae..1077b6a19 100644 --- a/packages/plugin-sdk/src/index.ts +++ b/packages/plugin-sdk/src/index.ts @@ -11,6 +11,7 @@ import type { SecretLeaseRef, SecretRef, SemanticVersion, + TerminalSessionSnapshot, } from "@netcatty/plugin-contract"; export type * from "@netcatty/plugin-contract"; @@ -101,34 +102,59 @@ export type PluginProviderHandler< TResult extends JsonValue = JsonValue, > = (invocation: PluginProviderInvocation) => TResult | void | Promise; +type ProviderHandlerForKind< + K extends ProviderKind, + TPayload extends JsonValue, + TResult extends JsonValue, +> = K extends TerminalInterceptorKind + ? TerminalInterceptorHandler + : K extends OrdinaryTerminalProviderKind + ? OrdinaryTerminalProviderHandler + : PluginProviderHandler; + export interface PluginProviders { register( providerId: string, kind: K, handler: OrdinaryTerminalProviderHandler, ): Disposable; + register( + providerId: string, + kind: TerminalInterceptorKind, + handler: TerminalInterceptorHandler, + ): Disposable; register( providerId: string, - kind: ProviderKind, + kind: Exclude, handler: PluginProviderHandler, ): Disposable; + register< + K extends ProviderKind, + TPayload extends JsonValue = JsonValue, + TResult extends JsonValue = JsonValue, + >( + providerId: string, + kind: K, + handler: ProviderHandlerForKind, TPayload, TResult>, + ): Disposable; } -export interface TerminalSessionSnapshot { - readonly sessionId: string; - readonly hostId?: string; - readonly workspaceId?: string; - /** Built-in or namespaced plugin connection protocol identifier. */ - readonly protocol: string; - readonly status: "connecting" | "connected" | "disconnected"; - readonly cwd?: string; - readonly title?: string; - readonly shellType?: "posix" | "fish" | "powershell" | "cmd" | "unknown"; - readonly cols?: number; - readonly rows?: number; - readonly alternateScreen?: boolean; +export type TerminalInterceptorKind = "terminal.interceptor.input" | "terminal.interceptor.output"; + +export interface TerminalInterceptorInvocation { + readonly providerId: string; + readonly kind: TerminalInterceptorKind; + readonly direction: "input" | "output"; + readonly sequence: number; + readonly session: TerminalSessionSnapshot; + /** UTF-8 terminal data. The buffer is owned by this invocation. */ + readonly data: Uint8Array; } +export type TerminalInterceptorHandler = ( + invocation: TerminalInterceptorInvocation, +) => Uint8Array | ArrayBuffer | Promise; + export interface TerminalSessionEvent { readonly type: | "snapshot" diff --git a/scripts/generate-plugin-contract.mjs b/scripts/generate-plugin-contract.mjs index 048234907..80eaa44d0 100644 --- a/scripts/generate-plugin-contract.mjs +++ b/scripts/generate-plugin-contract.mjs @@ -82,6 +82,25 @@ if (!Number.isSafeInteger(streamLimits?.maxFrameJsonBytes) || streamLimits.maxFrameJsonBytes < streamLimits?.maxChunkBytes) { throw new Error("StreamLimits.maxFrameJsonBytes must cover one maximum stream chunk"); } +const terminalInterceptorLimits = schema.$defs.TerminalInterceptorLimits?.const; +if (!Number.isSafeInteger(terminalInterceptorLimits?.maxChunkBytes) + || terminalInterceptorLimits.maxChunkBytes < 1 + || !Number.isSafeInteger(terminalInterceptorLimits?.maxWindowBytes) + || terminalInterceptorLimits.maxWindowBytes < terminalInterceptorLimits.maxChunkBytes) { + throw new Error("TerminalInterceptorLimits must define bounded chunk and window sizes"); +} +for (const [name, minimum, maximum] of [ + ["TerminalInterceptorChunkByteLength", 0, terminalInterceptorLimits.maxChunkBytes], + ["TerminalInterceptorWindowBytes", 1, terminalInterceptorLimits.maxWindowBytes], + ["TerminalInterceptorCreditBytes", 0, terminalInterceptorLimits.maxWindowBytes], +]) { + const definition = schema.$defs[name]; + if (definition?.type !== "integer" + || definition.minimum !== minimum + || definition.maximum !== maximum) { + throw new Error(`${name} must match the canonical TerminalInterceptorLimits range`); + } +} const streamIdDefinition = schema.$defs.StreamId; if (!Number.isSafeInteger(streamLimits?.maxStreamIdLength) || streamLimits.maxStreamIdLength < 1 @@ -219,6 +238,8 @@ const generatedLimits = [ `export const PLUGIN_STREAM_MIN_WINDOW_BYTES = ${streamLimits.minWindowBytes} as const;`, `export const PLUGIN_STREAM_MAX_WINDOW_BYTES = ${streamLimits.maxWindowBytes} as const;`, `export const PLUGIN_STREAM_MAX_CREDIT_BYTES = ${streamLimits.maxCreditBytes} as const;`, + `export const PLUGIN_TERMINAL_INTERCEPTOR_MAX_CHUNK_BYTES = ${terminalInterceptorLimits.maxChunkBytes} as const;`, + `export const PLUGIN_TERMINAL_INTERCEPTOR_MAX_WINDOW_BYTES = ${terminalInterceptorLimits.maxWindowBytes} as const;`, "", ].join("\n"); const normalizedSchema = `${JSON.stringify(schema, null, 2)}\n`; diff --git a/types/global/netcatty-bridge-script.d.ts b/types/global/netcatty-bridge-script.d.ts index c6752ebf0..8f75153ca 100644 --- a/types/global/netcatty-bridge-script.d.ts +++ b/types/global/netcatty-bridge-script.d.ts @@ -110,6 +110,7 @@ export interface ScriptDialogRequest { type: 'alert' | 'confirm' | 'prompt' | 'waitForTimeout' | 'form'; message: string; defaultValue?: string; + sensitive?: boolean; pattern?: string; timeoutMs?: number; form?: ScriptDialogForm; diff --git a/types/global/netcatty-bridge-session.d.ts b/types/global/netcatty-bridge-session.d.ts index 040f7e4eb..b86468053 100644 --- a/types/global/netcatty-bridge-session.d.ts +++ b/types/global/netcatty-bridge-session.d.ts @@ -310,6 +310,8 @@ declare global { data: string, options?: { automated?: boolean; + /** Host-classified secret/no-echo input; always bypasses plugin observers and interceptors. */ + sensitive?: boolean; lineDelayMs?: number; logRewrite?: { sentCommand: string; displayCommand: string }; }, @@ -345,6 +347,9 @@ declare global { snapshot?: string; kittyKeyboardModeState?: NetcattyKittyKeyboardModeState; kittyKeyboardProtocolEnabled?: boolean; + passwordPromptActive?: boolean; + cwd?: string | null; + title?: string | null; error?: string; }>; /** Home renderer: listen for snapshot requests. */ @@ -357,6 +362,9 @@ declare global { snapshot: string, kittyKeyboardModeState?: NetcattyKittyKeyboardModeState, kittyKeyboardProtocolEnabled?: boolean, + passwordPromptActive?: boolean, + cwd?: string | null, + title?: string | null, ): void; /** Observe popup: push current state back to the home renderer before restore. */ applyTerminalSessionSnapshot?( @@ -369,6 +377,9 @@ declare global { alternateScreen: boolean; kittyKeyboardModeState?: NetcattyKittyKeyboardModeState; kittyKeyboardProtocolEnabled?: boolean; + passwordPromptActive?: boolean; + cwd?: string | null; + title?: string | null; }, authorization: string, ): Promise<{ @@ -388,6 +399,9 @@ declare global { alternateScreen: boolean; kittyKeyboardModeState?: NetcattyKittyKeyboardModeState; kittyKeyboardProtocolEnabled?: boolean; + passwordPromptActive?: boolean; + cwd?: string | null; + title?: string | null; requestId: string; }) => boolean | Promise, ): () => void; @@ -437,6 +451,12 @@ declare global { /** True while Mosh is still on the ephemeral SSH handshake PTY. */ moshHandshake?: boolean; terminalPerf?: NetcattyTerminalOutputPerfMeta; + /** Original host output units acknowledged even when an interceptor changes display length. */ + pluginPipelineIngressBytes?: number; + /** Host-owned provenance marker for output already processed by an interceptor. */ + pluginPipelineProcessed?: boolean; + /** Host-classified authentication prompt state for protecting subsequent input. */ + pluginPipelineSensitiveInput?: boolean; }, ) => void, options?: { replayBacklog?: boolean },