@pyrokine/mcp-ssh 1.1.3 → 1.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -1
- package/README_zh.md +3 -1
- package/dist/file-ops.js +3 -1
- package/dist/forward-manager.d.ts +33 -0
- package/dist/forward-manager.js +185 -0
- package/dist/pty-manager.d.ts +37 -0
- package/dist/pty-manager.js +169 -0
- package/dist/session-manager.d.ts +15 -67
- package/dist/session-manager.js +104 -365
- package/package.json +2 -2
- package/src/file-ops.ts +3 -1
- package/src/forward-manager.ts +257 -0
- package/src/pty-manager.ts +220 -0
- package/src/session-manager.ts +136 -450
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 端口转发管理器
|
|
3
|
+
*
|
|
4
|
+
* 负责本地/远程端口转发的完整生命周期
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import * as net from 'net'
|
|
8
|
+
import type {Client, ClientChannel} from 'ssh2'
|
|
9
|
+
import type {PortForwardInfo} from './types.js'
|
|
10
|
+
|
|
11
|
+
/** 端口转发所需的外部依赖 */
|
|
12
|
+
export interface ForwardDependencies {
|
|
13
|
+
/** 获取 SSH client */
|
|
14
|
+
getClient(alias: string): Client;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
interface ForwardSession {
|
|
18
|
+
id: string;
|
|
19
|
+
alias: string;
|
|
20
|
+
type: 'local' | 'remote';
|
|
21
|
+
localHost: string;
|
|
22
|
+
localPort: number;
|
|
23
|
+
remoteHost: string;
|
|
24
|
+
remotePort: number;
|
|
25
|
+
server?: net.Server;
|
|
26
|
+
createdAt: number;
|
|
27
|
+
active: boolean;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// tcp connection 事件处理函数类型
|
|
31
|
+
type TcpConnectionHandler = (
|
|
32
|
+
info: { destIP: string; destPort: number; srcIP: string; srcPort: number },
|
|
33
|
+
accept: () => ClientChannel,
|
|
34
|
+
reject: () => void,
|
|
35
|
+
) => void;
|
|
36
|
+
|
|
37
|
+
/** 每个 SSH session 的 dispatcher 状态 */
|
|
38
|
+
interface DispatcherState {
|
|
39
|
+
handler: TcpConnectionHandler;
|
|
40
|
+
client: Client;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export class ForwardManager {
|
|
44
|
+
private sessions: Map<string, ForwardSession> = new Map()
|
|
45
|
+
private dispatchers: Map<string, DispatcherState> = new Map() // alias → dispatcher
|
|
46
|
+
private idCounter = 0
|
|
47
|
+
|
|
48
|
+
async forwardLocal(
|
|
49
|
+
deps: ForwardDependencies,
|
|
50
|
+
alias: string,
|
|
51
|
+
localPort: number,
|
|
52
|
+
remoteHost: string,
|
|
53
|
+
remotePort: number,
|
|
54
|
+
localHost: string = '127.0.0.1',
|
|
55
|
+
): Promise<string> {
|
|
56
|
+
const client = deps.getClient(alias)
|
|
57
|
+
const forwardId = this.generateId()
|
|
58
|
+
|
|
59
|
+
return new Promise((resolve, reject) => {
|
|
60
|
+
const server = net.createServer((socket) => {
|
|
61
|
+
client.forwardOut(
|
|
62
|
+
socket.remoteAddress || '127.0.0.1',
|
|
63
|
+
socket.remotePort || 0,
|
|
64
|
+
remoteHost,
|
|
65
|
+
remotePort,
|
|
66
|
+
(err, stream) => {
|
|
67
|
+
if (err) {
|
|
68
|
+
socket.end()
|
|
69
|
+
return
|
|
70
|
+
}
|
|
71
|
+
socket.pipe(stream).pipe(socket)
|
|
72
|
+
},
|
|
73
|
+
)
|
|
74
|
+
})
|
|
75
|
+
|
|
76
|
+
server.on('error', (err) => {
|
|
77
|
+
reject(new Error(`Local forward failed: ${err.message}`))
|
|
78
|
+
})
|
|
79
|
+
|
|
80
|
+
server.listen(localPort, localHost, () => {
|
|
81
|
+
this.sessions.set(forwardId, {
|
|
82
|
+
id: forwardId,
|
|
83
|
+
alias,
|
|
84
|
+
type: 'local',
|
|
85
|
+
localHost,
|
|
86
|
+
localPort,
|
|
87
|
+
remoteHost,
|
|
88
|
+
remotePort,
|
|
89
|
+
server,
|
|
90
|
+
createdAt: Date.now(),
|
|
91
|
+
active: true,
|
|
92
|
+
})
|
|
93
|
+
resolve(forwardId)
|
|
94
|
+
})
|
|
95
|
+
})
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
async forwardRemote(
|
|
99
|
+
deps: ForwardDependencies,
|
|
100
|
+
alias: string,
|
|
101
|
+
remotePort: number,
|
|
102
|
+
localHost: string,
|
|
103
|
+
localPort: number,
|
|
104
|
+
remoteHost: string = '127.0.0.1',
|
|
105
|
+
): Promise<string> {
|
|
106
|
+
const client = deps.getClient(alias)
|
|
107
|
+
const forwardId = this.generateId()
|
|
108
|
+
|
|
109
|
+
return new Promise((resolve, reject) => {
|
|
110
|
+
client.forwardIn(remoteHost, remotePort, (err) => {
|
|
111
|
+
if (err) {
|
|
112
|
+
reject(new Error(`Remote forward failed: ${err.message}`))
|
|
113
|
+
return
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
this.sessions.set(forwardId, {
|
|
117
|
+
id: forwardId,
|
|
118
|
+
alias,
|
|
119
|
+
type: 'remote',
|
|
120
|
+
localHost,
|
|
121
|
+
localPort,
|
|
122
|
+
remoteHost,
|
|
123
|
+
remotePort,
|
|
124
|
+
createdAt: Date.now(),
|
|
125
|
+
active: true,
|
|
126
|
+
})
|
|
127
|
+
|
|
128
|
+
this.ensureTcpDispatcher(alias, client)
|
|
129
|
+
resolve(forwardId)
|
|
130
|
+
})
|
|
131
|
+
})
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
close(forwardId: string, deps?: ForwardDependencies): boolean {
|
|
135
|
+
const fwd = this.sessions.get(forwardId)
|
|
136
|
+
if (!fwd) {
|
|
137
|
+
return false
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
fwd.active = false
|
|
141
|
+
|
|
142
|
+
if (fwd.type === 'local' && fwd.server) {
|
|
143
|
+
try {
|
|
144
|
+
fwd.server.close()
|
|
145
|
+
} catch (e) {
|
|
146
|
+
console.warn(`Forward ${forwardId} server close failed:`, (e as Error).message)
|
|
147
|
+
}
|
|
148
|
+
} else if (fwd.type === 'remote' && deps) {
|
|
149
|
+
try {
|
|
150
|
+
const client = deps.getClient(fwd.alias)
|
|
151
|
+
client.unforwardIn(fwd.remoteHost, fwd.remotePort)
|
|
152
|
+
} catch { /* session 可能已断开 */
|
|
153
|
+
}
|
|
154
|
+
this.removeTcpDispatcherIfEmpty(fwd.alias)
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
this.sessions.delete(forwardId)
|
|
158
|
+
return true
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** 关闭指定 alias 的所有转发(disconnect 时调用,不需要 unforwardIn) */
|
|
162
|
+
closeByAlias(alias: string): void {
|
|
163
|
+
for (const [id, fwd] of this.sessions) {
|
|
164
|
+
if (fwd.alias === alias) {
|
|
165
|
+
fwd.active = false
|
|
166
|
+
if (fwd.type === 'local' && fwd.server) {
|
|
167
|
+
try {
|
|
168
|
+
fwd.server.close()
|
|
169
|
+
} catch (e) {
|
|
170
|
+
console.warn(`Forward ${id} server close failed:`, (e as Error).message)
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
this.sessions.delete(id)
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
// 清理该 alias 的 dispatcher
|
|
177
|
+
const state = this.dispatchers.get(alias)
|
|
178
|
+
if (state) {
|
|
179
|
+
try {
|
|
180
|
+
state.client.removeListener('tcp connection', state.handler)
|
|
181
|
+
} catch { /* client 可能已关闭 */ }
|
|
182
|
+
this.dispatchers.delete(alias)
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
list(): PortForwardInfo[] {
|
|
187
|
+
const result: PortForwardInfo[] = []
|
|
188
|
+
for (const [id, fwd] of this.sessions) {
|
|
189
|
+
result.push({
|
|
190
|
+
id,
|
|
191
|
+
alias: fwd.alias,
|
|
192
|
+
type: fwd.type,
|
|
193
|
+
localHost: fwd.localHost,
|
|
194
|
+
localPort: fwd.localPort,
|
|
195
|
+
remoteHost: fwd.remoteHost,
|
|
196
|
+
remotePort: fwd.remotePort,
|
|
197
|
+
createdAt: fwd.createdAt,
|
|
198
|
+
active: fwd.active,
|
|
199
|
+
})
|
|
200
|
+
}
|
|
201
|
+
return result
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* 确保 SSH session 有共享的 tcp connection dispatcher
|
|
206
|
+
* 所有 remote forward 共用一个 dispatcher,根据 destIP/destPort 路由
|
|
207
|
+
*/
|
|
208
|
+
private ensureTcpDispatcher(alias: string, client: Client): void {
|
|
209
|
+
if (this.dispatchers.has(alias)) {
|
|
210
|
+
return
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
const handler: TcpConnectionHandler = (info, accept, rejectConn) => {
|
|
214
|
+
for (const fwd of this.sessions.values()) {
|
|
215
|
+
if (fwd.type === 'remote' &&
|
|
216
|
+
fwd.active &&
|
|
217
|
+
fwd.alias === alias &&
|
|
218
|
+
fwd.remoteHost === info.destIP &&
|
|
219
|
+
fwd.remotePort === info.destPort) {
|
|
220
|
+
const stream = accept()
|
|
221
|
+
const socket = net.createConnection(fwd.localPort, fwd.localHost)
|
|
222
|
+
socket.pipe(stream).pipe(socket)
|
|
223
|
+
socket.on('error', () => stream.close())
|
|
224
|
+
stream.on('error', () => socket.destroy())
|
|
225
|
+
return
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
rejectConn()
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
this.dispatchers.set(alias, {handler, client})
|
|
232
|
+
client.on('tcp connection', handler)
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* 移除 dispatcher(当没有活跃的 remote forward 时)
|
|
237
|
+
*/
|
|
238
|
+
private removeTcpDispatcherIfEmpty(alias: string): void {
|
|
239
|
+
const state = this.dispatchers.get(alias)
|
|
240
|
+
if (!state) {
|
|
241
|
+
return
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
for (const fwd of this.sessions.values()) {
|
|
245
|
+
if (fwd.type === 'remote' && fwd.alias === alias && fwd.active) {
|
|
246
|
+
return // 还有活跃的 remote forward
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
state.client.removeListener('tcp connection', state.handler)
|
|
251
|
+
this.dispatchers.delete(alias)
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
private generateId(): string {
|
|
255
|
+
return `fwd_${++this.idCounter}_${Date.now()}`
|
|
256
|
+
}
|
|
257
|
+
}
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PTY 会话管理器
|
|
3
|
+
*
|
|
4
|
+
* 负责 PTY 会话的完整生命周期:创建、读写、调整大小、关闭
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import xterm from '@xterm/headless'
|
|
8
|
+
import type {ClientChannel} from 'ssh2'
|
|
9
|
+
import type {PtyOptions, PtySessionInfo} from './types.js'
|
|
10
|
+
|
|
11
|
+
const Terminal = xterm.Terminal as typeof import('@xterm/headless').Terminal
|
|
12
|
+
type TerminalType = import('@xterm/headless').Terminal;
|
|
13
|
+
|
|
14
|
+
/** PTY 创建所需的外部依赖 */
|
|
15
|
+
export interface PtyDependencies {
|
|
16
|
+
/** 通过 alias 获取 SSH client 并执行命令 */
|
|
17
|
+
execPty(alias: string, command: string, options: PtyOptions): Promise<ClientChannel>;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
interface PtySession {
|
|
21
|
+
id: string;
|
|
22
|
+
alias: string;
|
|
23
|
+
command: string;
|
|
24
|
+
stream: ClientChannel;
|
|
25
|
+
terminal: TerminalType;
|
|
26
|
+
rows: number;
|
|
27
|
+
cols: number;
|
|
28
|
+
createdAt: number;
|
|
29
|
+
lastReadAt: number;
|
|
30
|
+
rawBuffer: string;
|
|
31
|
+
maxBufferSize: number;
|
|
32
|
+
active: boolean;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export class PtyManager {
|
|
36
|
+
private sessions: Map<string, PtySession> = new Map()
|
|
37
|
+
private idCounter = 0
|
|
38
|
+
private readonly defaultBufferSize = 1024 * 1024 // 1MB
|
|
39
|
+
|
|
40
|
+
async start(
|
|
41
|
+
deps: PtyDependencies,
|
|
42
|
+
alias: string,
|
|
43
|
+
command: string,
|
|
44
|
+
options: PtyOptions = {},
|
|
45
|
+
): Promise<string> {
|
|
46
|
+
const ptyId = this.generateId()
|
|
47
|
+
const rows = options.rows || 24
|
|
48
|
+
const cols = options.cols || 80
|
|
49
|
+
const maxBufferSize = options.bufferSize || this.defaultBufferSize
|
|
50
|
+
|
|
51
|
+
const stream = await deps.execPty(alias, command, options)
|
|
52
|
+
|
|
53
|
+
// 创建 xterm headless 终端仿真器
|
|
54
|
+
const terminal = new Terminal({rows, cols, allowProposedApi: true})
|
|
55
|
+
|
|
56
|
+
const ptySession: PtySession = {
|
|
57
|
+
id: ptyId,
|
|
58
|
+
alias,
|
|
59
|
+
command,
|
|
60
|
+
stream,
|
|
61
|
+
terminal,
|
|
62
|
+
rows,
|
|
63
|
+
cols,
|
|
64
|
+
createdAt: Date.now(),
|
|
65
|
+
lastReadAt: Date.now(),
|
|
66
|
+
rawBuffer: '',
|
|
67
|
+
maxBufferSize,
|
|
68
|
+
active: true,
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// 监听输出数据
|
|
72
|
+
stream.on('data', (data: Buffer) => {
|
|
73
|
+
if (!ptySession.active) {
|
|
74
|
+
return
|
|
75
|
+
}
|
|
76
|
+
const chunk = data.toString('utf-8')
|
|
77
|
+
// 写入终端仿真器(解析 ANSI 序列)
|
|
78
|
+
terminal.write(chunk)
|
|
79
|
+
// 同时保留原始流(用于 raw 模式)
|
|
80
|
+
ptySession.rawBuffer += chunk
|
|
81
|
+
if (ptySession.rawBuffer.length > maxBufferSize) {
|
|
82
|
+
ptySession.rawBuffer = ptySession.rawBuffer.slice(-maxBufferSize)
|
|
83
|
+
}
|
|
84
|
+
})
|
|
85
|
+
|
|
86
|
+
stream.on('close', () => {
|
|
87
|
+
ptySession.active = false
|
|
88
|
+
})
|
|
89
|
+
|
|
90
|
+
stream.on('error', (err: Error) => {
|
|
91
|
+
ptySession.active = false
|
|
92
|
+
terminal.write(`\n[PTY Error: ${err.message}]`)
|
|
93
|
+
})
|
|
94
|
+
|
|
95
|
+
this.sessions.set(ptyId, ptySession)
|
|
96
|
+
return ptyId
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
write(ptyId: string, data: string): boolean {
|
|
100
|
+
const session = this.getSession(ptyId)
|
|
101
|
+
if (!session.active) {
|
|
102
|
+
throw new Error(`PTY session '${ptyId}' is closed`)
|
|
103
|
+
}
|
|
104
|
+
return session.stream.write(data)
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
read(
|
|
108
|
+
ptyId: string,
|
|
109
|
+
options: { mode?: 'screen' | 'raw'; clear?: boolean } = {},
|
|
110
|
+
): { data: string; active: boolean; rows: number; cols: number } {
|
|
111
|
+
const session = this.getSession(ptyId)
|
|
112
|
+
const mode = options.mode || 'screen'
|
|
113
|
+
const clear = options.clear !== false
|
|
114
|
+
|
|
115
|
+
let data: string
|
|
116
|
+
if (mode === 'screen') {
|
|
117
|
+
data = this.getScreenContent(session.terminal)
|
|
118
|
+
} else {
|
|
119
|
+
data = session.rawBuffer
|
|
120
|
+
if (clear) {
|
|
121
|
+
session.rawBuffer = ''
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
session.lastReadAt = Date.now()
|
|
126
|
+
return {
|
|
127
|
+
data,
|
|
128
|
+
active: session.active,
|
|
129
|
+
rows: session.rows,
|
|
130
|
+
cols: session.cols,
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
resize(ptyId: string, rows: number, cols: number): boolean {
|
|
135
|
+
const session = this.getSession(ptyId)
|
|
136
|
+
if (!session.active) {
|
|
137
|
+
throw new Error(`PTY session '${ptyId}' is closed`)
|
|
138
|
+
}
|
|
139
|
+
session.stream.setWindow(rows, cols, 0, 0)
|
|
140
|
+
session.terminal.resize(cols, rows)
|
|
141
|
+
session.rows = rows
|
|
142
|
+
session.cols = cols
|
|
143
|
+
return true
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
close(ptyId: string): boolean {
|
|
147
|
+
const session = this.sessions.get(ptyId)
|
|
148
|
+
if (!session) {
|
|
149
|
+
return false
|
|
150
|
+
}
|
|
151
|
+
try {
|
|
152
|
+
session.stream.close()
|
|
153
|
+
} catch (e) {
|
|
154
|
+
console.warn(`PTY ${ptyId} stream close failed:`, (e as Error).message)
|
|
155
|
+
}
|
|
156
|
+
try {
|
|
157
|
+
session.terminal.dispose()
|
|
158
|
+
} catch (e) {
|
|
159
|
+
console.warn(`PTY ${ptyId} terminal dispose failed:`, (e as Error).message)
|
|
160
|
+
}
|
|
161
|
+
session.active = false
|
|
162
|
+
this.sessions.delete(ptyId)
|
|
163
|
+
return true
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** 关闭指定 alias 的所有 PTY 会话 */
|
|
167
|
+
closeByAlias(alias: string): void {
|
|
168
|
+
for (const [id, session] of this.sessions) {
|
|
169
|
+
if (session.alias === alias) {
|
|
170
|
+
this.close(id)
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
list(): PtySessionInfo[] {
|
|
176
|
+
const result: PtySessionInfo[] = []
|
|
177
|
+
for (const [id, pty] of this.sessions) {
|
|
178
|
+
result.push({
|
|
179
|
+
id,
|
|
180
|
+
alias: pty.alias,
|
|
181
|
+
command: pty.command,
|
|
182
|
+
rows: pty.rows,
|
|
183
|
+
cols: pty.cols,
|
|
184
|
+
createdAt: pty.createdAt,
|
|
185
|
+
lastReadAt: pty.lastReadAt,
|
|
186
|
+
bufferSize: pty.rawBuffer.length,
|
|
187
|
+
active: pty.active,
|
|
188
|
+
})
|
|
189
|
+
}
|
|
190
|
+
return result
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
private getSession(ptyId: string): PtySession {
|
|
194
|
+
const session = this.sessions.get(ptyId)
|
|
195
|
+
if (!session) {
|
|
196
|
+
throw new Error(`PTY session '${ptyId}' not found`)
|
|
197
|
+
}
|
|
198
|
+
return session
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
private generateId(): string {
|
|
202
|
+
return `pty_${++this.idCounter}_${Date.now()}`
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** 从终端仿真器获取当前屏幕内容 */
|
|
206
|
+
private getScreenContent(terminal: TerminalType): string {
|
|
207
|
+
const buffer = terminal.buffer.active
|
|
208
|
+
const lines: string[] = []
|
|
209
|
+
for (let i = 0; i < terminal.rows; i++) {
|
|
210
|
+
const line = buffer.getLine(i)
|
|
211
|
+
if (line) {
|
|
212
|
+
lines.push(line.translateToString(true))
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
while (lines.length > 0 && lines[lines.length - 1].trim() === '') {
|
|
216
|
+
lines.pop()
|
|
217
|
+
}
|
|
218
|
+
return lines.join('\n')
|
|
219
|
+
}
|
|
220
|
+
}
|