Repository navigation
Expand file tree
/
Copy pathcommand.ts
More file actions
243 lines (204 loc) · 6.46 KB
/
Copy pathcommand.ts
File metadata and controls
243 lines (204 loc) · 6.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
import { Effect, PlatformError, Predicate, Schema, Stream } from "effect"
import { ChildProcess, ChildProcessSpawner } from "effect/process"
import { RemoteCli } from "./remote-cli"
export class SshFailure extends Schema.TaggedError<SshFailure>()("SshFailure", {
code: Schema.Literals([
"input",
"connection",
"platform",
"version",
"install",
"service",
"unpublished",
"ssh-missing",
]),
detail: Schema.String,
}) {
constructor(code: SshFailure["code"], detail = "") {
super({ code, detail })
}
override get message() {
return this.detail
}
static from(this: void, cause: unknown) {
if (cause instanceof RemoteCli.Failure) return new SshFailure(cause.code, cause.detail)
if (
cause instanceof PlatformError.PlatformError &&
Predicate.isTagged(cause.reason, "NotFound") &&
cause.reason.method === "spawn"
)
return new SshFailure("ssh-missing", cause.message)
return cause instanceof SshFailure
? cause
: new SshFailure("connection", cause instanceof Error ? cause.message : String(cause))
}
}
export function quote(value: string) {
return `'${value.replaceAll("'", "'\\''")}'`
}
export function parseTarget(input: string) {
const tokens: string[] = []
const state = { word: "", quote: "", started: false }
for (let i = 0; i < input.length; i++) {
const c = input[i] ?? ""
if (c === "\n" || c === "\r" || c === "\0") throw new SshFailure("input")
if (c === "\\" && state.quote !== "'" && i + 1 < input.length && /[\s\\"']/.test(input[i + 1] ?? "")) {
state.word += input[++i]
state.started = true
continue
}
if (state.quote) {
if (c === state.quote) state.quote = ""
else state.word += c
continue
}
if (c === "'" || c === '"') {
state.quote = c
state.started = true
continue
}
if (/\s/.test(c)) {
if (state.started) tokens.push(state.word)
state.word = ""
state.started = false
continue
}
state.word += c
state.started = true
}
if (state.quote) throw new SshFailure("input")
if (state.started) tokens.push(state.word)
if (tokens[0] === "ssh") tokens.shift()
const args: string[] = []
const options = new Set([
"hostname",
"user",
"port",
"identityfile",
"identityagent",
"identitiesonly",
"proxyjump",
"proxycommand",
"connecttimeout",
"addressfamily",
])
while (tokens[0]?.startsWith("-")) {
const token = tokens.shift() ?? ""
if (["-4", "-6", "-C", "-A", "-a"].includes(token)) {
args.push(token)
continue
}
const flag = token.slice(0, 2)
if (!["-p", "-l", "-i", "-F", "-J", "-o"].includes(flag)) throw new SshFailure("input")
const value = token.length > 2 ? token.slice(2) : tokens.shift()
if (!value || value.startsWith("-")) throw new SshFailure("input")
if (flag === "-p" && (!/^\d+$/.test(value) || Number(value) < 1 || Number(value) > 65535))
throw new SshFailure("input")
if (flag === "-o" && !options.has((value.split(/[=\s]/)[0] ?? "").toLowerCase())) throw new SshFailure("input")
args.push(flag, value)
}
const host = tokens[0]
if (tokens.length !== 1 || !host || !/^[a-zA-Z0-9_@.:[\]%-]+$/.test(host) || host.startsWith("-"))
throw new SshFailure("input")
if (host.includes("@") && host.slice(0, host.lastIndexOf("@")).includes(":")) throw new SshFailure("input")
return { host, args }
}
export const sshExecutable = () => (process.platform === "win32" ? "ssh.exe" : "ssh")
export function sshArgs(target: ReturnType<typeof parseTarget>) {
return [
"-T",
"-o",
"ConnectTimeout=10",
"-o",
"ServerAliveInterval=15",
"-o",
"ServerAliveCountMax=3",
"-o",
"RemoteCommand=none",
"-o",
"RequestTTY=no",
"-o",
"PermitLocalCommand=no",
...target.args,
]
}
export function tunnelArgs(
target: ReturnType<typeof parseTarget>,
localPort: number,
remote: { host: string; port: number },
) {
// A multiplexed `ssh -N` may exit after handing forwarding to its master.
// Keep a session open on stdin instead; the scoped process owns that pipe.
return [
"-o",
"ControlMaster=no",
"-o",
"ControlPersist=no",
...sshArgs(target),
"-o",
"ExitOnForwardFailure=yes",
"-L",
`127.0.0.1:${localPort}:${remote.host}:${remote.port}`,
target.host,
"sh -c 'exec cat >/dev/null'",
]
}
export const runSsh = Effect.fn("Ssh.run")(function* (input: {
args: string[]
env?: NodeJS.ProcessEnv
stdin?: string | Uint8Array
timeout?: number
}) {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner
return yield* Effect.gen(function* () {
const child = yield* spawner.spawn(
ChildProcess.make(sshExecutable(), input.args, {
env: input.env,
extendEnv: true,
windowsHide: true,
killSignal: "SIGTERM",
forceKillAfter: "2 seconds",
stdin:
input.stdin === undefined
? "ignore"
: {
stream: Stream.make(
Predicate.isString(input.stdin) ? new TextEncoder().encode(input.stdin) : input.stdin,
),
endOnDone: true,
},
}),
)
const output = yield* Effect.all(
{
stdout: child.stdout.pipe(
Stream.decodeText(),
Stream.runFold(
() => "",
(tail, text) => (tail + text).slice(-1_048_576),
),
),
stderr: child.stderr.pipe(
Stream.decodeText(),
Stream.runFold(
() => "",
(tail, text) => (tail + text).slice(-16_384),
),
),
code: child.exitCode,
},
{ concurrency: "unbounded" },
)
if (output.code !== 0)
return yield* Effect.fail(new SshFailure("connection", commandFailureDetail(output.code, output)))
return output.stdout
}).pipe(Effect.scoped, Effect.timeout(input.timeout ?? 600_000), Effect.mapError(SshFailure.from))
})
export function commandFailureDetail(code: number | null, output: { stdout: string; stderr: string }) {
// The CLI may report failures on stdout. Never include its private bootstrap
// response in diagnostic text, even if shutdown fails after printing it.
const stdout = output.stdout
.replace(/OPENCODE_SSH_REGISTRATION_BEGIN[\s\S]*?(?:OPENCODE_SSH_REGISTRATION_END|$)/g, "")
.trim()
return [output.stderr.trim(), stdout].filter(Boolean).join("\n") || JSON.stringify({ exitCode: code })
}