@zukhruf/ssh 0.0.0-stage → 0.8.30
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/LICENSE +21 -0
- package/README.md +1123 -2
- package/dist/address.d.ts +8 -0
- package/dist/address.d.ts.map +1 -0
- package/dist/address.js +15 -0
- package/dist/address.js.map +1 -0
- package/dist/agent.d.ts +35 -0
- package/dist/agent.d.ts.map +1 -0
- package/dist/agent.js +288 -0
- package/dist/agent.js.map +1 -0
- package/dist/channel-stream.d.ts +16 -0
- package/dist/channel-stream.d.ts.map +1 -0
- package/dist/channel-stream.js +102 -0
- package/dist/channel-stream.js.map +1 -0
- package/dist/client.d.ts +114 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +587 -0
- package/dist/client.js.map +1 -0
- package/dist/config.d.ts +82 -0
- package/dist/config.d.ts.map +1 -0
- package/dist/config.js +255 -0
- package/dist/config.js.map +1 -0
- package/dist/control/control-client.d.ts +12 -0
- package/dist/control/control-client.d.ts.map +1 -0
- package/dist/control/control-client.js +156 -0
- package/dist/control/control-client.js.map +1 -0
- package/dist/control/control-master.d.ts +12 -0
- package/dist/control/control-master.d.ts.map +1 -0
- package/dist/control/control-master.js +101 -0
- package/dist/control/control-master.js.map +1 -0
- package/dist/control/control-stream.d.ts +29 -0
- package/dist/control/control-stream.d.ts.map +1 -0
- package/dist/control/control-stream.js +54 -0
- package/dist/control/control-stream.js.map +1 -0
- package/dist/control/messages.d.ts +38 -0
- package/dist/control/messages.d.ts.map +1 -0
- package/dist/control/messages.js +92 -0
- package/dist/control/messages.js.map +1 -0
- package/dist/control/serve-dial.d.ts +11 -0
- package/dist/control/serve-dial.d.ts.map +1 -0
- package/dist/control/serve-dial.js +47 -0
- package/dist/control/serve-dial.js.map +1 -0
- package/dist/control/serve-session.d.ts +11 -0
- package/dist/control/serve-session.d.ts.map +1 -0
- package/dist/control/serve-session.js +78 -0
- package/dist/control/serve-session.js.map +1 -0
- package/dist/control/wire.d.ts +41 -0
- package/dist/control/wire.d.ts.map +1 -0
- package/dist/control/wire.js +100 -0
- package/dist/control/wire.js.map +1 -0
- package/dist/control.d.ts +4 -0
- package/dist/control.d.ts.map +1 -0
- package/dist/control.js +4 -0
- package/dist/control.js.map +1 -0
- package/dist/dial-route.d.ts +14 -0
- package/dist/dial-route.d.ts.map +1 -0
- package/dist/dial-route.js +87 -0
- package/dist/dial-route.js.map +1 -0
- package/dist/host-key-algorithms.d.ts +7 -0
- package/dist/host-key-algorithms.d.ts.map +1 -0
- package/dist/host-key-algorithms.js +16 -0
- package/dist/host-key-algorithms.js.map +1 -0
- package/dist/host-key-policy.d.ts +22 -0
- package/dist/host-key-policy.d.ts.map +1 -0
- package/dist/host-key-policy.js +72 -0
- package/dist/host-key-policy.js.map +1 -0
- package/dist/identities.d.ts +18 -0
- package/dist/identities.d.ts.map +1 -0
- package/dist/identities.js +81 -0
- package/dist/identities.js.map +1 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +8 -0
- package/dist/index.js.map +1 -0
- package/dist/knownhosts.d.ts +33 -0
- package/dist/knownhosts.d.ts.map +1 -0
- package/dist/knownhosts.js +241 -0
- package/dist/knownhosts.js.map +1 -0
- package/dist/match-pattern.d.ts +3 -0
- package/dist/match-pattern.d.ts.map +1 -0
- package/dist/match-pattern.js +18 -0
- package/dist/match-pattern.js.map +1 -0
- package/dist/private-key.d.ts +42 -0
- package/dist/private-key.d.ts.map +1 -0
- package/dist/private-key.js +100 -0
- package/dist/private-key.js.map +1 -0
- package/dist/prompt.d.ts +6 -0
- package/dist/prompt.d.ts.map +1 -0
- package/dist/prompt.js +2 -0
- package/dist/prompt.js.map +1 -0
- package/dist/proxy-command.d.ts +33 -0
- package/dist/proxy-command.d.ts.map +1 -0
- package/dist/proxy-command.js +121 -0
- package/dist/proxy-command.js.map +1 -0
- package/dist/proxy-jump.d.ts +19 -0
- package/dist/proxy-jump.d.ts.map +1 -0
- package/dist/proxy-jump.js +63 -0
- package/dist/proxy-jump.js.map +1 -0
- package/dist/public-key.d.ts +22 -0
- package/dist/public-key.d.ts.map +1 -0
- package/dist/public-key.js +102 -0
- package/dist/public-key.js.map +1 -0
- package/dist/remote-listener.d.ts +14 -0
- package/dist/remote-listener.d.ts.map +1 -0
- package/dist/remote-listener.js +39 -0
- package/dist/remote-listener.js.map +1 -0
- package/dist/server-alive-check.d.ts +36 -0
- package/dist/server-alive-check.d.ts.map +1 -0
- package/dist/server-alive-check.js +103 -0
- package/dist/server-alive-check.js.map +1 -0
- package/dist/server.d.ts +114 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/server.js +460 -0
- package/dist/server.js.map +1 -0
- package/dist/session.d.ts +97 -0
- package/dist/session.d.ts.map +1 -0
- package/dist/session.js +193 -0
- package/dist/session.js.map +1 -0
- package/dist/ssh-g.d.ts +19 -0
- package/dist/ssh-g.d.ts.map +1 -0
- package/dist/ssh-g.js +67 -0
- package/dist/ssh-g.js.map +1 -0
- package/dist/ssh2-agent-forwarding.d.ts +51 -0
- package/dist/ssh2-agent-forwarding.d.ts.map +1 -0
- package/dist/ssh2-agent-forwarding.js +56 -0
- package/dist/ssh2-agent-forwarding.js.map +1 -0
- package/dist/ssh2-channel-open-failure.d.ts +28 -0
- package/dist/ssh2-channel-open-failure.d.ts.map +1 -0
- package/dist/ssh2-channel-open-failure.js +35 -0
- package/dist/ssh2-channel-open-failure.js.map +1 -0
- package/dist/ssh2-keepalive-request.d.ts +31 -0
- package/dist/ssh2-keepalive-request.d.ts.map +1 -0
- package/dist/ssh2-keepalive-request.js +6 -0
- package/dist/ssh2-keepalive-request.js.map +1 -0
- package/dist/ssh2-server-channel.d.ts +63 -0
- package/dist/ssh2-server-channel.d.ts.map +1 -0
- package/dist/ssh2-server-channel.js +309 -0
- package/dist/ssh2-server-channel.js.map +1 -0
- package/package.json +75 -4
package/README.md
CHANGED
|
@@ -1,3 +1,1124 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @zukhruf/ssh
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
> Public from 0.8.28, as `@zukhruf/docker` moves onto it. Ezz accepted each ADR (backlog #4503).
|
|
4
|
+
|
|
5
|
+
An SSH client and server that run inside the Node process. A client connects to an SSH server, runs commands in sessions, and dials sockets and ports on the remote host. It reads the user's `~/.ssh/config` through `ssh -G`, checks host keys against the known hosts, and signs with the agent. The types follow Go's [`golang.org/x/crypto/ssh`](https://pkg.go.dev/golang.org/x/crypto/ssh) and its subpackages, and the protocol is [ssh2](https://github.com/mscdex/ssh2) ([ADR 0001](./docs/adr/0001-the-scope-and-the-name-of-gos-ssh-package.md), [ADR 0003](./docs/adr/0003-ssh2-speaks-the-protocol.md)).
|
|
6
|
+
|
|
7
|
+
No helper process carries a connection. The connection is a TCP connection of the Node process. When that process dies, also by `SIGKILL`, the kernel closes the TCP connection, and the SSH server closes each channel and each socket that a channel opened. No process of the connection is left on either machine. A remote command of a session ends only when it reads the end of its input or exits by itself ([Run a command](#run-a-command)). Through an `ssh` child, a dead owner reached the remote side only as EOF, and 203 `ssh … docker system dial-stdio` processes stayed alive on one laptop (backlog #4503, [ADR 0002](./docs/adr/0002-the-connection-runs-in-the-node-process-and-no-helper-process-carries-it.md)).
|
|
8
|
+
|
|
9
|
+
The words in these documents have one meaning each. See the glossary in [CONTEXT.md](./CONTEXT.md).
|
|
10
|
+
|
|
11
|
+
## Use it
|
|
12
|
+
|
|
13
|
+
```sh
|
|
14
|
+
npm install @zukhruf/ssh
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
With npm's `strict-allow-scripts`, add `"ssh2": false` and `"cpu-features": false` to `allowScripts`: ssh2's optional native parts stay unbuilt, and ssh2 runs in JavaScript ([Why not an npm package](#why-not-an-npm-package)).
|
|
18
|
+
|
|
19
|
+
```ts
|
|
20
|
+
import { OpenSshConfig } from '@zukhruf/ssh/config';
|
|
21
|
+
|
|
22
|
+
const config = await OpenSshConfig.resolve('mac-mini', {
|
|
23
|
+
environment: process.env,
|
|
24
|
+
});
|
|
25
|
+
await using client = await config.dial({ clock: globalThis });
|
|
26
|
+
const uname = await client.newSession().output('uname -sr');
|
|
27
|
+
console.log(String(uname).trim());
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
The package has five import paths, after Go's subpackages:
|
|
31
|
+
|
|
32
|
+
| Import path | What it has | Go |
|
|
33
|
+
| ------------------------- | ---------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
34
|
+
| `@zukhruf/ssh` | `Client`, `ClientConfig`, `Session`, `RemoteListener`, keys, `ServerConn` | `ssh` |
|
|
35
|
+
| `@zukhruf/ssh/agent` | `AgentClient`, a client of an agent on a socket that the caller connected | `ssh/agent` |
|
|
36
|
+
| `@zukhruf/ssh/knownhosts` | `KnownHosts`, `KeyError`, `RevokedError` | `ssh/knownhosts` |
|
|
37
|
+
| `@zukhruf/ssh/config` | `OpenSshConfig`: the settings of OpenSSH for a destination, through `ssh -G` | none; tools do it ([ADR 0004](./docs/adr/0004-openssh-resolves-the-config-through-ssh-g.md)) |
|
|
38
|
+
| `@zukhruf/ssh/control` | `ControlMaster`, `ControlClient`: one connection for many processes | none; OpenSSH's `ControlMaster` ([ADR 0012](./docs/adr/0012-a-control-master-serves-the-channels-of-one-connection-to-other-processes.md)) |
|
|
39
|
+
|
|
40
|
+
Only `@zukhruf/ssh/config` needs the `ssh` binary.
|
|
41
|
+
|
|
42
|
+
## Connect with the settings of OpenSSH
|
|
43
|
+
|
|
44
|
+
`OpenSshConfig.resolve(destination, options)` runs `ssh -G <flags> -- <destination>`. OpenSSH reads every `Host`, `Match` and `Include` block, and prints the settings. The package makes no connection in this step ([ADR 0004](./docs/adr/0004-openssh-resolves-the-config-through-ssh-g.md)).
|
|
45
|
+
|
|
46
|
+
```ts
|
|
47
|
+
import { OpenSshConfig } from '@zukhruf/ssh/config';
|
|
48
|
+
|
|
49
|
+
const config = await OpenSshConfig.resolve('ssh://root@box:2222', {
|
|
50
|
+
flags: ['-o', 'ServerAliveInterval=10', '-o', 'ServerAliveCountMax=2'],
|
|
51
|
+
environment: process.env,
|
|
52
|
+
});
|
|
53
|
+
console.log(config.hostname, config.port, config.user, config.route.kind);
|
|
54
|
+
|
|
55
|
+
await using client = await config.dial({
|
|
56
|
+
clock: globalThis,
|
|
57
|
+
signal: AbortSignal.timeout(60_000),
|
|
58
|
+
});
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
- The destination is OpenSSH's: `[user@]hostname`, an `ssh://` URI, or a `Host` name of the config. Only an `ssh://` URI carries a port: OpenSSH reads `box:2202` as a hostname.
|
|
62
|
+
- The flags are raw flags of `ssh`. They come first, so a flag wins over the config file, as in OpenSSH.
|
|
63
|
+
- `environment` is required. `ssh -G` runs with it. The package reads these variables from it: `SSH_AUTH_SOCK`, `HOME`, `SHELL`, the variables that `SendEnv` names, and the `$NAME` of an `IdentityAgent` or `ForwardAgent` value. The package reads no `process.env` ([ADR 0008](./docs/adr/0008-the-environment-and-the-clock-are-inputs.md)).
|
|
64
|
+
|
|
65
|
+
`config.dial()` connects as OpenSSH would:
|
|
66
|
+
|
|
67
|
+
1. It follows `config.route`: `direct` goes straight to `hostname:port`, `jump` goes through each jump host of `ProxyJump` ([ADR 0006](./docs/adr/0006-a-jump-host-is-a-connection-through-a-channel-of-the-previous-connection.md)), and `proxy-command` goes over the pipes of a `ProxyCommand` ([ADR 0010](./docs/adr/0010-a-proxycommand-runs-as-the-transport-of-the-connection.md)).
|
|
68
|
+
2. It checks the host key against `UserKnownHostsFile` and `GlobalKnownHostsFile`, under `StrictHostKeyChecking` ([Check the host key](#check-the-host-key)).
|
|
69
|
+
3. It authenticates with the keys of the agent, then with the identity files that the agent does not hold, as OpenSSH orders them (`pubkey_prepare` in `sshconnect2.c`). With `IdentitiesOnly yes`, it uses only the agent keys of an identity file. It skips a missing identity file, one that it cannot read as a key, and an encrypted one whose key the agent does not hold. It never prompts: no password, no passphrase, no host key question. With `UserKnownHostsFile none`, `accept-new` and `no` add no line and connect.
|
|
70
|
+
4. It applies `ConnectTimeout` and `ServerAliveInterval` only when the config or the flags set them ([ADR 0007](./docs/adr/0007-keepalive-and-timeouts-come-only-from-the-resolved-config.md)).
|
|
71
|
+
5. It puts each `SetEnv` variable, and each variable of the environment that a `SendEnv` pattern names, in `ClientConfig.sessionEnv`; `SetEnv` wins for a name that both give. Each session sends them first ([Open a terminal](#open-a-terminal)). `ForwardAgent yes` with no `SSH_AUTH_SOCK` in the environment forwards nothing.
|
|
72
|
+
|
|
73
|
+
## Connect with a config that you build
|
|
74
|
+
|
|
75
|
+
`Client.dial(address, config)` is Go's `ssh.Dial`. It needs no `ssh` binary and reads no file. The caller gives each input.
|
|
76
|
+
|
|
77
|
+
```ts
|
|
78
|
+
import { connect } from 'node:net';
|
|
79
|
+
|
|
80
|
+
import { Client } from '@zukhruf/ssh';
|
|
81
|
+
import { AgentClient } from '@zukhruf/ssh/agent';
|
|
82
|
+
import { KnownHosts } from '@zukhruf/ssh/knownhosts';
|
|
83
|
+
|
|
84
|
+
await using socket = connect(process.env.SSH_AUTH_SOCK!);
|
|
85
|
+
const agent = new AgentClient(socket);
|
|
86
|
+
const knownHosts = await KnownHosts.read([
|
|
87
|
+
`${process.env.HOME}/.ssh/known_hosts`,
|
|
88
|
+
]);
|
|
89
|
+
|
|
90
|
+
await using client = await Client.dial('box.example.com:22', {
|
|
91
|
+
user: 'deploy',
|
|
92
|
+
auth: [{ type: 'publickey', signers: () => agent.signers() }],
|
|
93
|
+
hostKey: (hostname, port, key) => knownHosts.check(hostname, port, key),
|
|
94
|
+
hostKeyAlgorithms: knownHosts.hostKeyAlgorithms('box.example.com', 22),
|
|
95
|
+
clock: globalThis,
|
|
96
|
+
});
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
`hostKey` is required, as Go's `HostKeyCallback` is. The package has no default that trusts a key. `clock` is required too ([root ADR 0004](../../docs/adr/0004-a-library-that-waits-takes-the-clock-as-an-input.md)): give `globalThis` in production, and `createClock()` of `@sinonjs/fake-timers` in a test.
|
|
100
|
+
|
|
101
|
+
## Run a command
|
|
102
|
+
|
|
103
|
+
A session runs one command. `run()` waits for the exit status, `output()` also gives stdout, and `combinedOutput()` gives stdout and stderr together. These are Go's `Run`, `Output` and `CombinedOutput`.
|
|
104
|
+
|
|
105
|
+
```ts
|
|
106
|
+
import { ExitError } from '@zukhruf/ssh';
|
|
107
|
+
|
|
108
|
+
await client.newSession().run('test -d /srv/app');
|
|
109
|
+
|
|
110
|
+
const listing = await client
|
|
111
|
+
.newSession()
|
|
112
|
+
.output('ls /srv/app')
|
|
113
|
+
.catch((error) => {
|
|
114
|
+
if (
|
|
115
|
+
error instanceof ExitError &&
|
|
116
|
+
error.exit.kind === 'status' &&
|
|
117
|
+
error.exit.exitStatus === 2
|
|
118
|
+
)
|
|
119
|
+
return undefined;
|
|
120
|
+
throw error;
|
|
121
|
+
});
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
A non-zero exit status rejects with `ExitError` whose `exit` is `{ kind: 'status', exitStatus }`. A command that a signal ended rejects with `ExitError` whose `exit` is `{ kind: 'signal', signal, coreDumped, errorMessage }`. The signal is a name of RFC 4254 §6.10, or a name with an `@`: sshd sends `SIG@openssh.com` for each other signal (`sig2name` in OpenSSH's `session.c`, lines 2265-2283 of 10.5p1). A session whose channel closes with no exit status rejects with `ExitMissingError`: the connection or the server ended the command, and the outcome is not known.
|
|
125
|
+
|
|
126
|
+
A close of the session does not end its command. sshd closes only the pipes of a command without a pty (`session_close_by_channel` in OpenSSH's `session.c`; backlog #4503). To end a command, send it a signal, or run it with a pty, whose close is a hangup.
|
|
127
|
+
|
|
128
|
+
## Stream the input and the output of a command
|
|
129
|
+
|
|
130
|
+
`start(command)` opens the channel and returns when the server accepted the command. `stdin`, `stdout` and `stderr` are Node streams. A write to `stdin` that the channel cannot take, because the command exited without reading it, fails `stdin` with `ssh: the channel is closed`, as `EPIPE` fails the stdin of a child process; `wait()` still gives the exit status. They exist from `newSession()`, and data flows after `start()`. The end of `stdin` sends `SSH_MSG_CHANNEL_EOF`, so the command reads the end of its input, and the output stays open.
|
|
131
|
+
|
|
132
|
+
```ts
|
|
133
|
+
import { createReadStream } from 'node:fs';
|
|
134
|
+
import { pipeline } from 'node:stream/promises';
|
|
135
|
+
|
|
136
|
+
await using session = client.newSession();
|
|
137
|
+
await session.start('docker exec -i db psql -U postgres');
|
|
138
|
+
await pipeline(createReadStream('seed.sql'), session.stdin);
|
|
139
|
+
await session.wait();
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
`wait()` resolves at exit status 0. It rejects with `ExitError` or `ExitMissingError`, as `run()` does. Output that nothing reads is discarded once `wait()` or `close()` runs, as Go discards the output of a nil `Stdout`: the server sends the channel's close only after its data is read. `close()` resolves when `SSH_MSG_CHANNEL_CLOSE` is sent, as Go's `Close` does, and does not wait for the server's answer, which sshd sends only after the command ends.
|
|
143
|
+
|
|
144
|
+
## Open a terminal
|
|
145
|
+
|
|
146
|
+
`setenv` and `requestPty` record a request, and `ClientConfig.agentForwarding` adds `auth-agent-req@openssh.com` to each session. `start()` or `shell()` sends the requests before the command, in this order:
|
|
147
|
+
|
|
148
|
+
1. `auth-agent-req@openssh.com`, when `agentForwarding` is set.
|
|
149
|
+
2. Each `env`: first the variables of `ClientConfig.sessionEnv`, then the variables of `setenv`.
|
|
150
|
+
3. `pty-req`.
|
|
151
|
+
4. `exec` or `shell`.
|
|
152
|
+
|
|
153
|
+
The package sends the first request itself. ssh2 sends the others (`exec` and `shell` in `client.js:1192-1308`). The order of `env` and `pty-req` is not the order of OpenSSH. OpenSSH sends `auth-agent-req@openssh.com`, then `pty-req`, then each `env`, then `exec` or `shell` (`ssh_session2_setup` in `ssh.c`, `client_session2_setup` in `clientloop.c`).
|
|
154
|
+
|
|
155
|
+
The package sends each `env` with no reply wanted, as ssh2 and OpenSSH send it (`reqEnv` in `client.js`, `client_send_env` in `clientloop.c`). So a server that refuses a variable (`AcceptEnv`) ignores it, and `start()` does not fail. Go's `Setenv` is different: it wants a reply, and it returns an error when the server refuses (`ssh/session.go:172-175` of `golang.org/x/crypto` v0.59.0). The package also sends `auth-agent-req@openssh.com` with no reply wanted, as OpenSSH sends it (`ssh.c:2204` of OpenSSH 10.0p1). sshd accepts only the first agent request of a connection, refuses each later one, and gives that one agent socket to every session of the connection (`session.c:2166-2185`). So a refused agent forwarding does not make `start()` fail, and each session gets the agent. ssh2 wants a reply to `pty-req`, so a refused pty rejects `start()` or `shell()`.
|
|
156
|
+
|
|
157
|
+
```ts
|
|
158
|
+
await using session = client.newSession();
|
|
159
|
+
session.setenv('LANG', 'en_US.UTF-8');
|
|
160
|
+
session.requestPty('xterm-256color', { rows: 40, columns: 120 });
|
|
161
|
+
await session.shell();
|
|
162
|
+
|
|
163
|
+
process.stdin.pipe(session.stdin);
|
|
164
|
+
session.stdout.pipe(process.stdout);
|
|
165
|
+
process.stdout.on('resize', () =>
|
|
166
|
+
session.windowChange({
|
|
167
|
+
rows: process.stdout.rows,
|
|
168
|
+
columns: process.stdout.columns,
|
|
169
|
+
}),
|
|
170
|
+
);
|
|
171
|
+
await session.wait();
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
`signal(name)` sends a signal to the command. It takes the names of RFC 4254 §6.10, with no `SIG`: `'INT'`, `'TERM'`, `'KILL'`, `'HUP'`. The server delivers it once the command runs. `start()` resolves when the server accepts the command, which can be before sshd has started it, and sshd drops a signal that finds no process: wait for a sign that the command runs, such as its first output, before you send one.
|
|
175
|
+
|
|
176
|
+
## Dial a socket on the remote host
|
|
177
|
+
|
|
178
|
+
`client.dial(network, address)` opens a stream through the server: `'tcp'` to `host:port`, or `'unix'` to the path of a socket on the remote host. It gives a `Duplex`. It is Go's `Client.Dial`. Each call is one channel on the same connection.
|
|
179
|
+
|
|
180
|
+
```ts
|
|
181
|
+
import { request } from 'node:http';
|
|
182
|
+
|
|
183
|
+
const engine = await client.dial('unix', '/Users/me/.docker/run/docker.sock');
|
|
184
|
+
request({ path: '/_ping', createConnection: () => engine }, (response) =>
|
|
185
|
+
console.log(response.statusCode),
|
|
186
|
+
).end();
|
|
187
|
+
|
|
188
|
+
const postgres = await client.dial('tcp', '127.0.0.1:5432');
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
The end of the stream's write side sends channel EOF, as the end of input of a Unix socket. `destroy()` closes the channel. A write that the channel did not take before the remote side closed it fails with `ssh: the channel is closed` once the stream's data is read, as a socket's write fails with `EPIPE`.
|
|
192
|
+
|
|
193
|
+
A server can refuse a dial. Tailscale SSH allows a `'unix'` dial only under the user's home, `/tmp` and `/run/user/<uid>` (`ssh/tailssh/fwdmonitor.go`, `fwdAllowedSocketPath`). OpenSSH's sshd allows it by default (`AllowStreamLocalForwarding yes`). The dial then rejects with `OpenChannelError`, Go's: `reason` is the RFC 4254 §5.1 name that the server sent (`administratively-prohibited`, `connect-failed`, `unknown-channel-type`, `resource-shortage`, or the number of another code), and `description` is its text. sshd sends `administratively-prohibited` only for a TCP target that its policy denies, and `connect-failed` for each other refusal, a streamlocal one included.
|
|
194
|
+
|
|
195
|
+
## Forward a local port
|
|
196
|
+
|
|
197
|
+
The package has no forwarder class, as in Go and Rust ([ADR 0009](./docs/adr/0009-the-caller-forwards-a-local-port-with-node-net-and-client-dial.md)). Listen with `node:net`, and dial for each connection:
|
|
198
|
+
|
|
199
|
+
```ts
|
|
200
|
+
import { type Socket, createServer } from 'node:net';
|
|
201
|
+
import { pipeline } from 'node:stream/promises';
|
|
202
|
+
|
|
203
|
+
async function carry(socket: Socket): Promise<void> {
|
|
204
|
+
const remote = await client
|
|
205
|
+
.dial('tcp', '127.0.0.1:5432')
|
|
206
|
+
.catch(() => undefined);
|
|
207
|
+
if (!remote) return void socket.destroy();
|
|
208
|
+
await Promise.allSettled([
|
|
209
|
+
pipeline(socket, remote),
|
|
210
|
+
pipeline(remote, socket),
|
|
211
|
+
]);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
await using server = createServer({ allowHalfOpen: true }, (socket) => {
|
|
215
|
+
void carry(socket);
|
|
216
|
+
}).listen(0, '127.0.0.1');
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
## Listen on the remote host
|
|
220
|
+
|
|
221
|
+
`client.listen(network, address, connectionListener)` asks the server to listen: `tcpip-forward` for `'tcp'`, `streamlocal-forward@openssh.com` for `'unix'`. Each connection to that socket comes to the listener as a `Duplex`. For `'tcp'`, the listener also gets the origin, the address of the peer; a `'unix'` connection has none (`forwarded-streamlocal@openssh.com` carries no origin, OpenSSH `PROTOCOL` §2.4). This is OpenSSH's `ssh -R`, and Go's `Client.Listen`.
|
|
222
|
+
|
|
223
|
+
```ts
|
|
224
|
+
await using listener = await client.listen(
|
|
225
|
+
'tcp',
|
|
226
|
+
'127.0.0.1:0',
|
|
227
|
+
(stream, origin) => {
|
|
228
|
+
stream.end(`hello ${origin}\n`);
|
|
229
|
+
},
|
|
230
|
+
);
|
|
231
|
+
console.log(listener.address); // 127.0.0.1:<the port that the server chose>
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
The close of the listener sends the cancel request. The close of the client ends every listener.
|
|
235
|
+
|
|
236
|
+
## Connect through a jump host
|
|
237
|
+
|
|
238
|
+
`OpenSshConfig#dial` follows a `jump` route by itself: it reaches the first jump host (a `FirstJumpHost`) by that jump host's own route, and each later jump host (a `JumpHost`) through the jump host before it, as OpenSSH does. The root import path gives the step that it uses: `Client.handshake(transport, address, config)` runs the handshake on a stream that the caller gives. It is Go's `NewClientConn` ([ADR 0006](./docs/adr/0006-a-jump-host-is-a-connection-through-a-channel-of-the-previous-connection.md)).
|
|
239
|
+
|
|
240
|
+
```ts
|
|
241
|
+
// jumpConfig and dbConfig are a ClientConfig each.
|
|
242
|
+
await using jump = await Client.dial('jump.example.com:22', jumpConfig);
|
|
243
|
+
const channel = await jump.dial('tcp', 'db.internal:22');
|
|
244
|
+
await using db = await Client.handshake(channel, 'db.internal:22', dbConfig);
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
No process carries the connection to a jump host. When the owner dies, the kernel closes the TCP connection to the first jump host, and each server closes its part of the chain.
|
|
248
|
+
|
|
249
|
+
## Share one connection between processes
|
|
250
|
+
|
|
251
|
+
`ControlMaster.listen(client, path)` serves the channels of a client on a Unix socket, as OpenSSH's `ControlMaster` and `ControlPath` do. A `ControlClient` in another process dials and runs sessions through it, with the calls of `Client` ([ADR 0012](./docs/adr/0012-a-control-master-serves-the-channels-of-one-connection-to-other-processes.md)):
|
|
252
|
+
|
|
253
|
+
```ts
|
|
254
|
+
import { ControlClient, ControlMaster } from '@zukhruf/ssh/control';
|
|
255
|
+
|
|
256
|
+
// The process that owns the connection, for example a test runner:
|
|
257
|
+
await using master = await ControlMaster.listen(
|
|
258
|
+
client,
|
|
259
|
+
`${runDirectory}/ssh.sock`,
|
|
260
|
+
);
|
|
261
|
+
|
|
262
|
+
// Each other process:
|
|
263
|
+
const shared = new ControlClient(`${runDirectory}/ssh.sock`);
|
|
264
|
+
const listing = await shared.newSession().output('ls /srv/app');
|
|
265
|
+
const database = await shared.dial('tcp', '127.0.0.1:5432');
|
|
266
|
+
```
|
|
267
|
+
|
|
268
|
+
Each channel is one connection to the socket, and the close of one closes the other. So a client process that dies closes its channels, and a master process that dies ends every stream of its clients with an error. A master that is killed leaves its socket file, and `listen` on an existing file fails with `EADDRINUSE`: give each run a new directory. Nothing waits on a timer, and a `ControlClient` keeps no connection between two channels. The socket gives the connection to each process that can reach it: put it in a directory that only your user can enter. Node.js cannot pass file descriptors, so the protocol is the package's own, not OpenSSH's `PROTOCOL.mux`, and `ssh -S` cannot use the master.
|
|
269
|
+
|
|
270
|
+
## Check the host key
|
|
271
|
+
|
|
272
|
+
`KnownHosts` checks a key as Go's `knownhosts` does, and matches a line as OpenSSH does where the two differ ([ADR 0005](./docs/adr/0005-host-keys-are-checked-as-gos-knownhosts-checks-them-under-openssh-stricthostkeychecking.md)). It reads plain names, patterns with `*`, `?` and `!`, hashed names (`|1|`), `[host]:port` for a port other than 22, and `@revoked` lines. `hostKeyAlgorithms()` puts the algorithms of the known keys first, as OpenSSH does, so the server signs with a key that the client knows (golang/go#29286).
|
|
273
|
+
|
|
274
|
+
A host key callback that adds an unknown key and refuses a changed or revoked one is OpenSSH's `accept-new`:
|
|
275
|
+
|
|
276
|
+
```ts
|
|
277
|
+
import type { HostKeyCallback } from '@zukhruf/ssh';
|
|
278
|
+
import { KeyError, KnownHosts } from '@zukhruf/ssh/knownhosts';
|
|
279
|
+
|
|
280
|
+
const knownHosts = await KnownHosts.read([
|
|
281
|
+
`${process.env.HOME}/.ssh/known_hosts`,
|
|
282
|
+
]);
|
|
283
|
+
const hostKey: HostKeyCallback = async (hostname, port, key) => {
|
|
284
|
+
try {
|
|
285
|
+
knownHosts.check(hostname, port, key);
|
|
286
|
+
} catch (error) {
|
|
287
|
+
if (!(error instanceof KeyError) || error.want.length > 0) throw error;
|
|
288
|
+
await knownHosts.add(hostname, port, key, { hash: true });
|
|
289
|
+
}
|
|
290
|
+
};
|
|
291
|
+
```
|
|
292
|
+
|
|
293
|
+
`@zukhruf/ssh/config` applies OpenSSH's `StrictHostKeyChecking`, and never prompts. `ssh -G` prints `true`, `false`, `ask` or `accept-new` (`multistate_strict_hostkey` in OpenSSH's `readconf.c`): it prints `yes` as `true`, and `no` and its other spelling `off` as `false`. `OpenSshConfig#strictHostKeyChecking` gives each value its config name:
|
|
294
|
+
|
|
295
|
+
| `strictHostKeyChecking` | `ssh -G` prints | Unknown key | Changed key | Revoked key |
|
|
296
|
+
| ----------------------- | --------------- | --------------------------------------------- | ------------------------------------------------ | ------------------------------------ |
|
|
297
|
+
| `'yes'` | `true` | `KeyError`, `want` empty | `KeyError`, `want` lists the known keys | `RevokedError` |
|
|
298
|
+
| `'ask'` (the default) | `ask` | As `'yes'` | As `'yes'` | `RevokedError` |
|
|
299
|
+
| `'accept-new'` | `accept-new` | Adds the key to the first user file; connects | `KeyError` | `RevokedError` |
|
|
300
|
+
| `'no'` | `false` | Adds the key to the first user file; connects | Connects, with the restrictions of OpenSSH below | Connects, with the same restrictions |
|
|
301
|
+
|
|
302
|
+
Under `no`, OpenSSH connects to a host whose key changed or is revoked, but it turns off password and keyboard-interactive auth, agent forwarding, X11 forwarding, each `LocalForward` and `RemoteForward` (`-L`, `-R`) and tunnels. It does not turn off `-W`, the stdio forward that `ProxyJump` uses (`check_host_key` in `sshconnect.c` of OpenSSH 10.5p1: a revoked key at lines 1289-1307, the restrictions at lines 1365-1416). The client does the same ([ADR 0005](./docs/adr/0005-host-keys-are-checked-as-gos-knownhosts-checks-them-under-openssh-stricthostkeychecking.md)):
|
|
303
|
+
|
|
304
|
+
- `client.dial` works, as `-W` does, so a chain of jump hosts goes on.
|
|
305
|
+
- `client.listen` rejects with the host key error (`KeyError`, or `RevokedError` for a revoked key), as OpenSSH cancels `-R`.
|
|
306
|
+
- Agent forwarding is off: no session asks for it.
|
|
307
|
+
- The client offers no password and no keyboard-interactive auth.
|
|
308
|
+
|
|
309
|
+
A line is added hashed when `HashKnownHosts` is `yes`. A host that only an `@cert-authority` line trusts fails with `KeyError`: ssh2 offers no certificate host key algorithm ([ADR 0003](./docs/adr/0003-ssh2-speaks-the-protocol.md)).
|
|
310
|
+
|
|
311
|
+
## Sign with the agent
|
|
312
|
+
|
|
313
|
+
`AgentClient` speaks the agent protocol over a socket that the caller connected. It is Go's `agent.NewClient`. It lists the keys, signs, adds and removes keys, and locks the agent.
|
|
314
|
+
|
|
315
|
+
```ts
|
|
316
|
+
import { connect } from 'node:net';
|
|
317
|
+
|
|
318
|
+
import { AgentClient } from '@zukhruf/ssh/agent';
|
|
319
|
+
|
|
320
|
+
await using socket = connect(process.env.SSH_AUTH_SOCK!);
|
|
321
|
+
const agent = new AgentClient(socket);
|
|
322
|
+
for (const { key, comment } of await agent.list())
|
|
323
|
+
console.log(key.fingerprint(), comment);
|
|
324
|
+
```
|
|
325
|
+
|
|
326
|
+
Agent forwarding needs a new connection to the agent for each channel that the server opens back, as OpenSSH and Go's `agent.ForwardToRemote` open one. So `ClientConfig.agentForwarding` is a function that connects. When it is set, every session asks for agent forwarding before it starts, as with OpenSSH's `ForwardAgent yes`. Here `config` is a `ClientConfig`, as in [Connect with a config that you build](#connect-with-a-config-that-you-build):
|
|
327
|
+
|
|
328
|
+
```ts
|
|
329
|
+
await using client = await Client.dial('box.example.com:22', {
|
|
330
|
+
...config,
|
|
331
|
+
agentForwarding: async () => connect(process.env.SSH_AUTH_SOCK!),
|
|
332
|
+
});
|
|
333
|
+
await client.newSession().run('git clone git@github.com:acme/app.git');
|
|
334
|
+
```
|
|
335
|
+
|
|
336
|
+
`@zukhruf/ssh/config` reads `ForwardAgent` as OpenSSH does ([ADR 0004](./docs/adr/0004-openssh-resolves-the-config-through-ssh-g.md)). It sets `agentForwarding` from `forwardAgent`: for `yes`, a connection to the `SSH_AUTH_SOCK` of the caller's environment; for a socket path, or a `$NAME` of the environment, a connection to that socket; for `no`, nothing. A forwarded agent signs for the remote host, so set `ForwardAgent` only for a host that you trust, as for `ssh`. A `ClientConfig` that the caller builds forwards nothing unless the caller sets `agentForwarding`.
|
|
337
|
+
|
|
338
|
+
## Bound the start, and find a dead connection
|
|
339
|
+
|
|
340
|
+
The package has no timeout and no keepalive of its own ([ADR 0007](./docs/adr/0007-keepalive-and-timeouts-come-only-from-the-resolved-config.md)):
|
|
341
|
+
|
|
342
|
+
- `connectTimeout` is OpenSSH's `ConnectTimeout`. It limits the TCP connect, the banner exchange and the key exchange, on the clock of the config. When it passes, the dial rejects with a `TimeoutError`.
|
|
343
|
+
- `keepalive` is OpenSSH's `ServerAliveInterval` and `ServerAliveCountMax`, on the clock of the config: after an interval with no data from the server, the client asks for an answer, and after more than `countMax` such checks with no data, the connection ends with `ssh: keepalive timeout, server <address> not responding`. Without it, a connection to a machine that stops answering hangs a call until its signal aborts, as with OpenSSH.
|
|
344
|
+
- `@zukhruf/ssh/config` sets them only from the resolved config, so `~/.ssh/config` and the flags decide.
|
|
345
|
+
|
|
346
|
+
```ts
|
|
347
|
+
// config is a ClientConfig without the two settings.
|
|
348
|
+
await using client = await Client.dial('box.example.com:22', {
|
|
349
|
+
...config,
|
|
350
|
+
connectTimeout: 10_000,
|
|
351
|
+
keepalive: { interval: 10_000, countMax: 2 },
|
|
352
|
+
});
|
|
353
|
+
await client.wait().catch((error) => console.error('lost', error));
|
|
354
|
+
```
|
|
355
|
+
|
|
356
|
+
`client.wait()` resolves after `close()`, and rejects with the error that ended the connection. It is Go's `Conn.Wait`.
|
|
357
|
+
|
|
358
|
+
A client keeps the Node process alive while it is open, as a `net.Socket` does. `client.unref()` lets the process exit while the client is idle, as Node's `ClientHttp2Session#unref` does, and `client.ref()` undoes it. A caller that holds a client for its whole life, such as a pool of HTTP connections over its channels, refs it while a request is in flight and unrefs it otherwise. A stream given to `Client.handshake` stays the caller's to unref.
|
|
359
|
+
|
|
360
|
+
## Run a server
|
|
361
|
+
|
|
362
|
+
`ServerConn.handshake(transport, config)` runs the server side of a connection on a stream that the caller accepted. It is Go's `NewServerConn` ([ADR 0011](./docs/adr/0011-the-package-has-a-server-as-go-and-rust-do.md)). The package opens no listener: `node:net` does. Ezz decided that the package has a server, and that its API takes Go's shape.
|
|
363
|
+
|
|
364
|
+
```ts
|
|
365
|
+
import { readFile } from 'node:fs/promises';
|
|
366
|
+
import { type Socket, createServer } from 'node:net';
|
|
367
|
+
|
|
368
|
+
import { PrivateKey, PublicKey, ServerConn } from '@zukhruf/ssh';
|
|
369
|
+
import type { ServerSession } from '@zukhruf/ssh';
|
|
370
|
+
|
|
371
|
+
const hostKey = PrivateKey.parse(await readFile('host_ed25519'));
|
|
372
|
+
const { key: allowed } = PublicKey.parseAuthorizedKey(
|
|
373
|
+
await readFile('test.pub', 'utf8'),
|
|
374
|
+
);
|
|
375
|
+
|
|
376
|
+
async function serve(session: ServerSession): Promise<void> {
|
|
377
|
+
for await (const request of session.requests()) {
|
|
378
|
+
if (request.type === 'pty-req') {
|
|
379
|
+
request.accept();
|
|
380
|
+
} else if (request.type === 'exec') {
|
|
381
|
+
request.accept();
|
|
382
|
+
session.stdout.end(`ran ${request.command}\n`);
|
|
383
|
+
await session.exit(0);
|
|
384
|
+
return;
|
|
385
|
+
} else if ('reject' in request) {
|
|
386
|
+
request.reject();
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
async function accept(socket: Socket): Promise<void> {
|
|
392
|
+
await using conn = await ServerConn.handshake(socket, {
|
|
393
|
+
hostKeys: [hostKey],
|
|
394
|
+
publicKey: (user, key) => user === 'test' && key.equals(allowed),
|
|
395
|
+
});
|
|
396
|
+
const sessions: Promise<void>[] = [];
|
|
397
|
+
for await (const channel of conn.channels()) {
|
|
398
|
+
if (channel.type !== 'session') {
|
|
399
|
+
channel.reject();
|
|
400
|
+
continue;
|
|
401
|
+
}
|
|
402
|
+
sessions.push(serve(channel.accept()));
|
|
403
|
+
}
|
|
404
|
+
await Promise.allSettled(sessions);
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
createServer((socket) => {
|
|
408
|
+
void accept(socket);
|
|
409
|
+
}).listen(2222);
|
|
410
|
+
```
|
|
411
|
+
|
|
412
|
+
## Errors
|
|
413
|
+
|
|
414
|
+
Each class marks a different next step for the caller.
|
|
415
|
+
|
|
416
|
+
| Error | When |
|
|
417
|
+
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
418
|
+
| `KeyError` | `@zukhruf/ssh/knownhosts`. The known hosts have no key for the host (`want` is empty), or only other keys (`want` lists them with file and line), under the policy of [Check the host key](#check-the-host-key). A person adds the key, or reports a possible attack. Go's `knownhosts.KeyError`. |
|
|
419
|
+
| `RevokedError` | `@zukhruf/ssh/knownhosts`. The host key is on an `@revoked` line. `@zukhruf/ssh/config` throws it under `StrictHostKeyChecking` `yes`, `ask` and `accept-new`; under `no` it connects in the restricted mode of a changed key, as OpenSSH. `revoked` has its file and line. Go's `knownhosts.RevokedError`. |
|
|
420
|
+
| `AuthenticationError` | The server refused every auth method. `attempted` lists the methods tried, and `allowed` the methods that the server still lists. The caller adds a key to the agent or to `authorized_keys`, or gives another password or other answers, and does not try again unchanged. SSH.NET's `SshAuthenticationException`; Go has no class. |
|
|
421
|
+
| `PassphraseMissingError` | `PrivateKey.parse` got an encrypted key and no passphrase. `publicKey` is set when the file has it in clear. The caller asks for the passphrase or uses the agent. `@zukhruf/ssh/config` skips such an identity file, as OpenSSH does in batch mode. Go's `PassphraseMissingError`. |
|
|
422
|
+
| `ExitError` | `run()`, `output()`, `combinedOutput()` and `wait()`, when the command exited with a status other than 0 (`exit.kind` is `'status'`, with `exitStatus`) or a signal ended it (`exit.kind` is `'signal'`, with `signal`, `coreDumped` and `errorMessage`). Go's `ExitError`. |
|
|
423
|
+
| `OpenChannelError` | `client.dial()`, or a session's `run`, `output`, `start` or `shell`, when the server refuses the channel. `reason` is the RFC 4254 §5.1 name (or the number of another code), `description` the server's text. The caller changes the target, the server's config, or the path of a socket. Go's `OpenChannelError`. Through `@zukhruf/ssh/control`, a refusal has the same message and `code` but is an `Error`, not this class. |
|
|
424
|
+
| `ExitMissingError` | The same calls, when the channel closed with no `exit-status` and no `exit-signal`. The connection or the server ended the command, and the outcome is not known: do not run a command that is not idempotent again as if it failed. When a lost connection ended the channel, `cause` is the error that ended the connection. An `exit-signal` whose name is neither an RFC 4254 name nor a `name@domain` name also gives it. Go's `ExitMissingError`. |
|
|
425
|
+
| The error of Node.js | Every other failure of a dial, with its `code`: `ENOTFOUND`, `ECONNREFUSED`, `ETIMEDOUT`, `ECONNRESET`. A signal rejects with its reason, an `AbortError` by default. `connectTimeout` rejects with a `DOMException` named `TimeoutError`. The caller treats the host as absent, or tries again later. |
|
|
426
|
+
|
|
427
|
+
A failure of the connection has no class of its own. Every error of `Client.dial`, `Client.handshake` or `OpenSshConfig#dial` that is not one of the classes above is a failure to connect, and each of them has the same next step. A handshake failure, such as no shared key exchange algorithm, is an `Error` whose message names it. The package does not give ssh2's `level` field as its API.
|
|
428
|
+
|
|
429
|
+
A connection that is lost after the start ends each open channel with an error whose `cause` is the error that ended the connection, and `client.wait()` rejects with it. `OpenSshConfig#dial` rejects a `ProxyCommand` route under `ProxyUseFdpass yes` before it runs the command (Node.js cannot receive a file descriptor), and a `ProxyCommand` with a token that OpenSSH does not know. A `ProxyCommand` that exits before the handshake ends rejects the dial with the error that ssh2 gives for a transport that closed. Through `@zukhruf/ssh/control`, an open that the master's connection refuses rejects with the same message and `code` as on the `Client`. A dial stream whose master died or was disposed fails with `ssh: the control master closed the connection`, and a session then rejects with `ExitMissingError` whose `cause` is that error, or the error that ended the master's connection. A `ControlClient` with no master at its path rejects with the error of `node:net`, such as `ENOENT` or `ECONNREFUSED`. A failed `ssh -G` rejects `OpenSshConfig.resolve` with an `Error` whose message is the standard error of `ssh` and whose `cause` is the error of `execFile`, with the exit code as its `code`. A loop of jump hosts rejects with `jumphost loop via <host>`, as OpenSSH words it.
|
|
430
|
+
|
|
431
|
+
## What the package does not do
|
|
432
|
+
|
|
433
|
+
- **No helper process carries a connection.** A ProxyCommand of the user's config is the one process that the package runs for the life of a connection ([ADR 0002](./docs/adr/0002-the-connection-runs-in-the-node-process-and-no-helper-process-carries-it.md), [ADR 0010](./docs/adr/0010-a-proxycommand-runs-as-the-transport-of-the-connection.md)). A ProxyCommand that ignores the end of its stdin can outlive its owner, as it can for OpenSSH.
|
|
434
|
+
- **It never prompts.** No password, passphrase or host key question. A caller can give a password or a keyboard-interactive callback in `ClientConfig.auth`; `@zukhruf/ssh/config` never adds them.
|
|
435
|
+
- **No SFTP.** Go and Rust give it in a separate package (`github.com/pkg/sftp`, russh-sftp). It is a subsystem protocol with its own draft.
|
|
436
|
+
- **No forwarder class for `ssh -L` or `ssh -D`.** The caller composes `node:net` and `client.dial` ([ADR 0009](./docs/adr/0009-the-caller-forwards-a-local-port-with-node-net-and-client-dial.md)). A SOCKS server for `-D` is the same composition, as in Go and Rust.
|
|
437
|
+
- **No certificates.** ssh2 1.17.0 has no `*-cert-v01@openssh.com` algorithm, so `@cert-authority` host keys and certificate user keys do not work ([ADR 0003](./docs/adr/0003-ssh2-speaks-the-protocol.md)).
|
|
438
|
+
- **No security keys and no ML-DSA keys.** ssh2 1.17.0 cannot parse `sk-ssh-ed25519@openssh.com`, `sk-ecdsa-sha2-nistp256@openssh.com` or `ssh-mldsa*` keys, so they work neither as identity files nor through the agent. `@zukhruf/ssh/config` skips such an identity file, and `AgentClient#list` leaves such a key out.
|
|
439
|
+
- **No post-quantum key exchange.** ssh2's best is `curve25519-sha256`. OpenSSH 10.0 made `mlkem768x25519-sha256` its default ([ADR 0003](./docs/adr/0003-ssh2-speaks-the-protocol.md)).
|
|
440
|
+
- **No parser of `ssh_config`.** OpenSSH resolves the config through `ssh -G` ([ADR 0004](./docs/adr/0004-openssh-resolves-the-config-through-ssh-g.md)).
|
|
441
|
+
- **No connection sharing (`ControlMaster`).** The master is a process that outlives its clients. A program shares one `Client` by holding it.
|
|
442
|
+
- **No `KnownHostsCommand`, `VerifyHostKeyDNS`, `CheckHostIP` or `UpdateHostKeys`.** Without them, the client trusts only the known hosts files: it accepts fewer keys, never more ([ADR 0004](./docs/adr/0004-openssh-resolves-the-config-through-ssh-g.md)).
|
|
443
|
+
- **No keepalive and no timeout of its own** ([ADR 0007](./docs/adr/0007-keepalive-and-timeouts-come-only-from-the-resolved-config.md)).
|
|
444
|
+
- **No agent server.** Go's `agent.NewKeyring` and `agent.ServeAgent` hold private keys in the program's memory, which an agent such as `ssh-agent`, 1Password or Secretive exists to avoid. The package is a client of such an agent.
|
|
445
|
+
- **No X11 forwarding and no GSSAPI.** Node has no display server, and ssh2 has no GSSAPI.
|
|
446
|
+
|
|
447
|
+
## The same concepts in other systems
|
|
448
|
+
|
|
449
|
+
| Concept | Other systems |
|
|
450
|
+
| --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
451
|
+
| A client and its dial | Go: `ssh.Dial(network, addr, *ClientConfig)`. Rust russh: `client::connect`. .NET SSH.NET: `SshClient`, `ConnectionInfo`. Podman: `ssh.Dial(*ConnectionDialOptions, mode)` of `containers/common/pkg/ssh`. OpenSSH: `ssh`. |
|
|
452
|
+
| A handshake on a stream | Go: `ssh.NewClientConn(conn, addr, config)`. russh: `connect_stream` (`client/mod.rs`). SSH.NET: none. |
|
|
453
|
+
| A session | Go: `Session` with `Run`, `Start`, `Wait`, `Output`, `Setenv`, `RequestPty`, `WindowChange`, `Signal`, `Shell` (`session.go:167-357`). russh: `channel_open_session`. SSH.NET: `RunCommand`, `CreateCommand`, `SshCommand`. OpenSSH: `ssh host command`. |
|
|
454
|
+
| A dial to a socket or port | Go: `Client.Dial("unix" \| "tcp", addr)` (`tcpip.go:380-461`). russh: `channel_open_direct_streamlocal`, `channel_open_direct_tcpip`. Podman: `DialNet(client, "unix", url)`. SSH.NET: no streamlocal (#238). OpenSSH: `ssh -W`, `direct-streamlocal@openssh.com` (`PROTOCOL` §2.4). |
|
|
455
|
+
| A local forward | Go and russh: none; the caller listens and dials. SSH.NET: `ForwardedPortLocal`. OpenSSH: `ssh -L`. |
|
|
456
|
+
| A remote listener | Go: `Client.Listen`, `ListenTCP`, `ListenUnix` (`tcpip.go:29`, `:116`, `streamlocal.go:34`). russh: `tcpip_forward`, `streamlocal_forward`. SSH.NET: `ForwardedPortRemote`. OpenSSH: `ssh -R`. |
|
|
457
|
+
| A jump host | Go: `NewClientConn` over `Client.Dial`. russh: `connect_stream`. VS Code: an `ssh -J … -W` child (`sshProxyJump.ts:107-114`). SSH.NET: none (#481, #530). OpenSSH: `ProxyJump`, an `ssh -W` child. |
|
|
458
|
+
| Known hosts | Go: `ssh/knownhosts` with `KeyError` and `RevokedError`. Podman: skeema/knownhosts, which orders the host key algorithms (golang/go#29286). russh: known_hosts in its keys module. SSH.NET: only the `HostKeyReceived` event. OpenSSH: sshd(8), SSH_KNOWN_HOSTS FILE FORMAT. |
|
|
459
|
+
| The config through `ssh -G` | VS Code: `execFile('ssh', ['-G', '--', host])` and `parseSSHGOutput` (`sshRemoteAgentHostService.ts:1397`). distant: "Tries ssh -G first". zed, `gh codespace`, coder, the Buildkite agent, trzsz-ssh, nh. Go, russh and SSH.NET: none. |
|
|
460
|
+
| One connection for many processes | Go, russh and SSH.NET: none. OpenSSH: `ControlMaster`, `ControlPath`, `ssh -S`, with `PROTOCOL.mux`, which passes file descriptors. |
|
|
461
|
+
| An agent client | Go: `agent.NewClient(conn)`, `agent.ForwardToRemote`, `agent.RequestAgentForwarding` (`agent/forward.go:19-58`). russh: an agent client in its keys module. SSH.NET: none. OpenSSH: `ssh-add`, `ForwardAgent`. |
|
|
462
|
+
| A server | Go: `ssh.NewServerConn` (`server.go:356`). russh: its `server` module. SSH.NET: none. OpenSSH: `sshd`. |
|
|
463
|
+
| SSH in the owner's process | Podman's remote client: one connection in its process, the engine socket dialed for each HTTP connection (`pkg/bindings/connection.go`), `dial-stdio` on a session when the server refuses (`connection_stdio.go`). docker-modem: ssh2 with `dial-stdio` for each request. docker/cli: an `ssh` child. |
|
|
464
|
+
|
|
465
|
+
## What each call does underneath
|
|
466
|
+
|
|
467
|
+
The RFC sections are of RFC 4252 (authentication), RFC 4253 (transport) and RFC 4254 (connection). The ssh2 calls are of ssh2 1.17.0.
|
|
468
|
+
|
|
469
|
+
| Call | On the wire | ssh2 |
|
|
470
|
+
| ----------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
471
|
+
| `OpenSshConfig.resolve()` | Nothing. `ssh -G <flags> -- <destination>` prints the settings and exits | None |
|
|
472
|
+
| `OpenSshConfig#dial()`, `proxy-command` | The handshake over the pipes of `spawn(SHELL or /bin/sh, ['-c', 'exec <command with %h %k %n %p %r %% expanded>'], { env: environment, stdio: ['pipe', 'pipe', 'inherit'] })`; `SIGHUP` when the client ends its side; `close()` closes each client of a jump chain | `Client.handshake(transport, …)` |
|
|
473
|
+
| `Client.dial(address, config)` | A TCP connect, the version exchange, the key exchange (RFC 4253 §7), the authentication (RFC 4252) | `net.connect`, then `new Client().connect({ sock, username, hostVerifier, algorithms: { serverHostKey }, authHandler, readyTimeout: 0, strictVendor: false })` |
|
|
474
|
+
| `Client.handshake(transport, …)` | The same, on the given stream | `connect({ sock: transport, … })` |
|
|
475
|
+
| `hostKey` | Gets the host key of the key exchange reply | `hostVerifier(key, verify)` |
|
|
476
|
+
| auth `publickey` | `SSH_MSG_USERAUTH_REQUEST` `publickey`, a query, then a signature (RFC 4252 §7) | `authHandler` → `{ type: 'agent', agent }`, with an ssh2 `BaseAgent` that serves the signers |
|
|
477
|
+
| auth `password`, `keyboard-interactive` | `password` (RFC 4252 §8); `keyboard-interactive` (RFC 4256). ssh2 answers an info request with no prompt itself, with no answer, so `respond` gets only rounds that have prompts. A rejected `respond`, or an answer count that is not the prompt count, fails the dial. Go then tries the next method; ssh2 cannot leave a `keyboard-interactive` exchange before it ends | `authHandler` → `{ type: 'password' }`, `{ type: 'keyboard-interactive', prompt }` |
|
|
478
|
+
| `connectTimeout` | Nothing; a timer on the clock until the key exchange ends | Ends at the `handshake` event (`client.js:323`) |
|
|
479
|
+
| `keepalive` | `SSH_MSG_GLOBAL_REQUEST` `keepalive@openssh.com`, reply wanted, only after an interval with no data from the server, as OpenSSH's `ServerAliveInterval`. Any data from the server resets the count of requests with no answer; above `countMax` the connection ends. The timer runs on the clock of the config | `_protocol.ping()` and a placeholder on `_callbacks`, in `src/ssh2-keepalive-request.ts`; the timing is `src/server-alive-check.ts` |
|
|
480
|
+
| `client.dial('tcp', 'host:port')` | `SSH_MSG_CHANNEL_OPEN` `direct-tcpip` (RFC 4254 §7.2), originator `0.0.0.0` port 0, as Go's `Client.Dial` | `forwardOut('0.0.0.0', 0, host, port)` (`client.js:1398`) |
|
|
481
|
+
| `client.dial('unix', path)` | `SSH_MSG_CHANNEL_OPEN` `direct-streamlocal@openssh.com` (OpenSSH `PROTOCOL` §2.4) | `openssh_forwardOutStreamLocal(path)` (`client.js:1533`) |
|
|
482
|
+
| `client.listen('tcp', …)` | `tcpip-forward` (RFC 4254 §7.1); each connection is a `forwarded-tcpip` channel | `forwardIn(host, port)` (`client.js:1333`), event `tcp connection` |
|
|
483
|
+
| `client.listen('unix', …)` | `streamlocal-forward@openssh.com`; each connection is a `forwarded-streamlocal@openssh.com` channel | `openssh_forwardInStreamLocal(path)` (`client.js:1457`), event `unix connection` |
|
|
484
|
+
| `listener.close()` | `cancel-tcpip-forward`, `cancel-streamlocal-forward@openssh.com` | `unforwardIn`, `openssh_unforwardInStreamLocal` |
|
|
485
|
+
| `session.start(command)` | A `session` channel (RFC 4254 §6.1), then `auth-agent-req@openssh.com` when `agentForwarding` is set (no reply wanted), each `env` (§6.4, no reply wanted), `pty-req` (§6.2, reply wanted), `exec` (§6.5). OpenSSH sends `auth-agent-req@openssh.com`, `pty-req`, each `env`, then `exec` | `exec(command, { env, pty })` (`client.js:1192-1247`) |
|
|
486
|
+
| `session.shell()` | The same, with `shell` (§6.5) | `shell(window, { env })` (`client.js:1249-1308`), with `window` `false` when no pty was asked for: ssh2 asks for a pty otherwise (`client.js:1290-1291`) |
|
|
487
|
+
| `sessionEnv` | Each `env` (§6.4), no reply wanted, as the first requests of each session, before the variables of `setenv` | The `env` object of `exec` and `shell`; `reqEnv` sends it at once with no reply wanted (`client.js:1863-1891`) |
|
|
488
|
+
| `session.stdin.end()`, a stream's `end()` | `SSH_MSG_CHANNEL_EOF` (RFC 4254 §5.3) | `channel.end()` |
|
|
489
|
+
| `session.stderr` | `SSH_MSG_CHANNEL_EXTENDED_DATA`, type 1 (§5.2) | `channel.stderr` |
|
|
490
|
+
| `session.windowChange()` | `window-change` (§6.7) | `channel.setWindow(rows, columns, height, width)` (`Channel.js:221`) |
|
|
491
|
+
| `session.signal()` | `signal` (§6.9) | `channel.signal(name)` (`Channel.js:237`) |
|
|
492
|
+
| `session.wait()` | `exit-status` or `exit-signal` (§6.10), then `SSH_MSG_CHANNEL_CLOSE` | the `exit` event, then the `close` event of the channel |
|
|
493
|
+
| `session.close()`, a stream's `destroy()` | `SSH_MSG_CHANNEL_CLOSE` (§5.3) | `channel.close()` (`Channel.js:207`) |
|
|
494
|
+
| `agentForwarding` | Each session sends `auth-agent-req@openssh.com` first, with no reply wanted, as OpenSSH's `ForwardAgent yes`. The server opens `auth-agent@openssh.com` channels; each one is joined to a new connection to the agent | `agent` with `getStream`, given to `connect` (`client.js:219-224`, `:1995-2006`), and no `agentForward`: ssh2 would send the request with a reply wanted, and only on the first session of a client (`client.js:1794-1823`). The package sends the request on each session through ssh2's internals (`_chanMgr`, `_protocol.openssh_agentForward`, `_agentFwdEnabled`; `src/ssh2-agent-forwarding.ts`) |
|
|
495
|
+
| `client.unref()`, `client.ref()` | Nothing | `unref()`/`ref()` of the socket that the package opened, of a ProxyCommand's child and pipes, of each jump client, and of the keepalive timer on the clock |
|
|
496
|
+
| `client.close()` | `SSH_MSG_DISCONNECT`, then the transport closes | `end()` (`client.js:1179`) |
|
|
497
|
+
| The owner process dies | Nothing more: the kernel closes the TCP connection, and the server closes each channel (`src/owner-death.test.ts`) | None |
|
|
498
|
+
| `AgentClient` | The agent protocol over the caller's socket (draft-ietf-sshm-ssh-agent) | None: the package speaks the whole protocol. ssh2's `AgentProtocol` (`agent.js:509`) parses only the answers to `list` and `sign`, so it cannot share a socket with `add`, `remove` and `lock` |
|
|
499
|
+
| `ControlMaster.listen(client, path)` | Nothing; a `node:net` server on the Unix socket. Each connection to it carries one request, one reply, then frames of one channel | None |
|
|
500
|
+
| `controlClient.dial()`, `.newSession()` | The master opens the channel on its own connection, as `client.dial()` or `client.newSession()` would | The calls of the master's `Client` |
|
|
501
|
+
| A `ControlClient` process dies | Nothing more: the kernel closes its Unix connections, and the master closes each of their channels | None |
|
|
502
|
+
| `KnownHosts` | Nothing | None |
|
|
503
|
+
| `ServerConn.handshake()` | The server side of RFC 4253 and RFC 4252 | `new Server({ hostKeys }).injectSocket(transport)` (`server.js:217`, `:361`) |
|
|
504
|
+
| `serverConn.forward()` | `SSH_MSG_CHANNEL_OPEN` `forwarded-tcpip` or `forwarded-streamlocal@openssh.com` | `forwardOut`, `openssh_forwardOutStreamLocal` of the server's client (`server.js:1295`, `:1301`) |
|
|
505
|
+
|
|
506
|
+
## API
|
|
507
|
+
|
|
508
|
+
```ts
|
|
509
|
+
// @zukhruf/ssh
|
|
510
|
+
|
|
511
|
+
import type { Duplex, Readable, Writable } from 'node:stream';
|
|
512
|
+
|
|
513
|
+
import type { Clock } from '@zukhruf/async';
|
|
514
|
+
|
|
515
|
+
/** One SSH connection and its channels. Go's ssh.Client. */
|
|
516
|
+
export class Client implements AsyncDisposable {
|
|
517
|
+
/** Opens a TCP connection to `address` (host:port) with node:net, and runs the handshake on it. Go's ssh.Dial. */
|
|
518
|
+
static dial(
|
|
519
|
+
address: string,
|
|
520
|
+
config: ClientConfig,
|
|
521
|
+
options?: { readonly family?: 4 | 6; readonly signal?: AbortSignal },
|
|
522
|
+
): Promise<Client>;
|
|
523
|
+
/** Runs the handshake on a stream that the caller opened: a channel of a jump host, the pipes of a ProxyCommand. The stream stays the caller's: ref() and unref() leave it as it is. Go's ssh.NewClientConn with ssh.NewClient. */
|
|
524
|
+
static handshake(
|
|
525
|
+
transport: Duplex,
|
|
526
|
+
address: string,
|
|
527
|
+
config: ClientConfig,
|
|
528
|
+
options?: { readonly signal?: AbortSignal },
|
|
529
|
+
): Promise<Client>;
|
|
530
|
+
readonly user: string;
|
|
531
|
+
/** The version line of the server, such as SSH-2.0-OpenSSH_10.3. Go's ServerVersion. */
|
|
532
|
+
readonly serverVersion: string;
|
|
533
|
+
/** 'tcp': a direct-tcpip channel to host:port. 'unix': a direct-streamlocal@openssh.com channel to a socket path. Go's Client.Dial. */
|
|
534
|
+
dial(
|
|
535
|
+
network: 'tcp' | 'unix',
|
|
536
|
+
address: string,
|
|
537
|
+
options?: { readonly signal?: AbortSignal },
|
|
538
|
+
): Promise<Duplex>;
|
|
539
|
+
/** tcpip-forward. Each connection comes to connectionListener with its origin, host:port of the peer. Go's Client.Listen. */
|
|
540
|
+
listen(
|
|
541
|
+
network: 'tcp',
|
|
542
|
+
address: string,
|
|
543
|
+
connectionListener: (stream: Duplex, origin: string) => void,
|
|
544
|
+
options?: { readonly signal?: AbortSignal },
|
|
545
|
+
): Promise<RemoteListener>;
|
|
546
|
+
/** streamlocal-forward@openssh.com. A forwarded-streamlocal@openssh.com channel carries no origin. Go's Client.ListenUnix. */
|
|
547
|
+
listen(
|
|
548
|
+
network: 'unix',
|
|
549
|
+
path: string,
|
|
550
|
+
connectionListener: (stream: Duplex) => void,
|
|
551
|
+
options?: { readonly signal?: AbortSignal },
|
|
552
|
+
): Promise<RemoteListener>;
|
|
553
|
+
/** A session. Its channel opens at start(), run(), output(), combinedOutput() or shell(). Go's Client.NewSession. */
|
|
554
|
+
newSession(): Session;
|
|
555
|
+
/** Resolves after close(). Rejects with the error that ended the connection. Go's Conn.Wait. */
|
|
556
|
+
wait(): Promise<void>;
|
|
557
|
+
/** The client no longer keeps the Node process alive: its socket, the child and pipes of a ProxyCommand, its keepalive timer and each jump client. Node's ClientHttp2Session#unref. */
|
|
558
|
+
unref(): void;
|
|
559
|
+
/** Undoes unref(). A new client is ref'd, as a net.Socket is. */
|
|
560
|
+
ref(): void;
|
|
561
|
+
/** Sends SSH_MSG_DISCONNECT and closes the transport, then the clients of its jump hosts. It sends SIGHUP to its ProxyCommand and does not wait for it, as OpenSSH. A later call waits for the same close. */
|
|
562
|
+
close(): Promise<void>;
|
|
563
|
+
[Symbol.asyncDispose](): Promise<void>;
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
/** Go's ssh.ClientConfig. */
|
|
567
|
+
export interface ClientConfig {
|
|
568
|
+
readonly user: string;
|
|
569
|
+
/** Tried in order. Go's ClientConfig.Auth. */
|
|
570
|
+
readonly auth: readonly AuthMethod[];
|
|
571
|
+
/** Throws to refuse the key. Required: no default trusts a key. Go's HostKeyCallback. */
|
|
572
|
+
readonly hostKey: HostKeyCallback;
|
|
573
|
+
/** The host key algorithms to offer, in order. Default: each one that the package supports. Go's HostKeyAlgorithms. */
|
|
574
|
+
readonly hostKeyAlgorithms?: readonly string[];
|
|
575
|
+
readonly clock: Clock;
|
|
576
|
+
/** OpenSSH's ConnectTimeout, in ms: the TCP connect, the banner exchange and the key exchange. Default: no limit. */
|
|
577
|
+
readonly connectTimeout?: number;
|
|
578
|
+
/** OpenSSH's ServerAliveInterval (ms) and ServerAliveCountMax. Default: no keepalive. */
|
|
579
|
+
readonly keepalive?: {
|
|
580
|
+
readonly interval: number;
|
|
581
|
+
readonly countMax: number;
|
|
582
|
+
};
|
|
583
|
+
/** When set, every session asks for agent forwarding (auth-agent-req@openssh.com) before its command, as OpenSSH's ForwardAgent yes, and each auth-agent@openssh.com channel gets a new connection from this function. In the root import path, because the protocol library takes the agent when it connects. Go's agent.ForwardToRemote with agent.RequestAgentForwarding. */
|
|
584
|
+
readonly agentForwarding?: () => Promise<Duplex>;
|
|
585
|
+
/** The env requests that each new session sends before its first other request, with no reply wanted. OpenSshConfig#dial fills it from SetEnv, and from the variables of the caller's environment that SendEnv names. OpenSSH's SetEnv and SendEnv. */
|
|
586
|
+
readonly sessionEnv?: Readonly<Record<string, string>>;
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
export type HostKeyCallback = (
|
|
590
|
+
hostname: string,
|
|
591
|
+
port: number,
|
|
592
|
+
key: PublicKey,
|
|
593
|
+
) => void | Promise<void>;
|
|
594
|
+
|
|
595
|
+
/** Go's ssh.AuthMethod: PublicKeysCallback, Password, KeyboardInteractive. */
|
|
596
|
+
export type AuthMethod =
|
|
597
|
+
| {
|
|
598
|
+
readonly type: 'publickey';
|
|
599
|
+
readonly signers: () => Promise<readonly Signer[]>;
|
|
600
|
+
}
|
|
601
|
+
| { readonly type: 'password'; readonly password: string }
|
|
602
|
+
| {
|
|
603
|
+
readonly type: 'keyboard-interactive';
|
|
604
|
+
/** Called once for each info request that has prompts; gives one answer for each prompt. A rejection, or another count of answers, fails the dial. Go's KeyboardInteractiveChallenge. */
|
|
605
|
+
readonly respond: (
|
|
606
|
+
prompts: readonly Prompt[],
|
|
607
|
+
) => Promise<readonly string[]>;
|
|
608
|
+
};
|
|
609
|
+
|
|
610
|
+
/** RFC 4256 §3.2. */
|
|
611
|
+
export interface Prompt {
|
|
612
|
+
readonly prompt: string;
|
|
613
|
+
readonly echo: boolean;
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
/** A private key that signs: a parsed key, or a key of the agent. Go's ssh.Signer. */
|
|
617
|
+
export interface Signer {
|
|
618
|
+
readonly publicKey: PublicKey;
|
|
619
|
+
sign(data: Uint8Array, algorithm?: string): Promise<Uint8Array>;
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
/** Go's ssh.PublicKey. */
|
|
623
|
+
export class PublicKey {
|
|
624
|
+
/** The wire form, RFC 4253 §6.6. Go's ParsePublicKey. */
|
|
625
|
+
static parse(wire: Uint8Array): PublicKey;
|
|
626
|
+
/** A line of authorized_keys or of a .pub file. Go's ParseAuthorizedKey. */
|
|
627
|
+
static parseAuthorizedKey(line: string): {
|
|
628
|
+
readonly key: PublicKey;
|
|
629
|
+
readonly comment: string;
|
|
630
|
+
readonly options: readonly string[];
|
|
631
|
+
};
|
|
632
|
+
/** Such as ssh-ed25519. */
|
|
633
|
+
readonly type: string;
|
|
634
|
+
/** Go's Marshal. */
|
|
635
|
+
readonly wire: Uint8Array;
|
|
636
|
+
/** SHA256:<base64>, as ssh-keygen -l prints it. Go's FingerprintSHA256. */
|
|
637
|
+
fingerprint(): string;
|
|
638
|
+
equals(other: PublicKey): boolean;
|
|
639
|
+
/** <type> <base64>, as a line of authorized_keys. Go's MarshalAuthorizedKey. */
|
|
640
|
+
toString(): string;
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
/** Go's ParsePrivateKey and ParsePrivateKeyWithPassphrase. */
|
|
644
|
+
export class PrivateKey implements Signer {
|
|
645
|
+
/** An OpenSSH key, or a PKCS#1, PKCS#8 or SEC1 PEM key. Throws PassphraseMissingError for an encrypted key with no passphrase. */
|
|
646
|
+
static parse(data: Uint8Array, passphrase?: string): PrivateKey;
|
|
647
|
+
readonly publicKey: PublicKey;
|
|
648
|
+
sign(data: Uint8Array, algorithm?: string): Promise<Uint8Array>;
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
/** One command or shell on the remote host. Go's ssh.Session. */
|
|
652
|
+
export class Session implements AsyncDisposable {
|
|
653
|
+
/** Its end sends SSH_MSG_CHANNEL_EOF. A write that the closed channel did not take fails it with `ssh: the channel is closed`, as EPIPE. */
|
|
654
|
+
readonly stdin: Writable;
|
|
655
|
+
readonly stdout: Readable;
|
|
656
|
+
/** SSH_MSG_CHANNEL_EXTENDED_DATA, type 1. */
|
|
657
|
+
readonly stderr: Readable;
|
|
658
|
+
/** An env request, sent at start after the variables of ClientConfig.sessionEnv, with no reply wanted, as ssh2 and OpenSSH send it: a server that refuses the variable ignores it. Go's Setenv wants a reply and returns an error on a refusal. */
|
|
659
|
+
setenv(name: string, value: string): void;
|
|
660
|
+
/** Sent at start. A refusal rejects start() or shell(). Go's RequestPty. */
|
|
661
|
+
requestPty(term: string, size: WindowSize, modes?: TerminalModes): void;
|
|
662
|
+
/** Resolves when the server accepted the command. Go's Start. */
|
|
663
|
+
start(command: string): Promise<void>;
|
|
664
|
+
/** A login shell. Go's Shell. */
|
|
665
|
+
shell(): Promise<void>;
|
|
666
|
+
/** Resolves at exit status 0. Rejects with ExitError or ExitMissingError. Go's Wait. */
|
|
667
|
+
wait(): Promise<void>;
|
|
668
|
+
/** start(), then wait(). Go's Run. */
|
|
669
|
+
run(command: string): Promise<void>;
|
|
670
|
+
/** run(), and stdout. Go's Output. */
|
|
671
|
+
output(command: string): Promise<Buffer>;
|
|
672
|
+
/** run(), and stdout and stderr in the order they came. Go's CombinedOutput. */
|
|
673
|
+
combinedOutput(command: string): Promise<Buffer>;
|
|
674
|
+
/** Go's WindowChange. */
|
|
675
|
+
windowChange(size: WindowSize): Promise<void>;
|
|
676
|
+
/** Go's Signal. */
|
|
677
|
+
signal(name: SignalName): Promise<void>;
|
|
678
|
+
/** SSH_MSG_CHANNEL_CLOSE. sshd does not end a command without a pty on a close. */
|
|
679
|
+
close(): Promise<void>;
|
|
680
|
+
[Symbol.asyncDispose](): Promise<void>;
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
export interface WindowSize {
|
|
684
|
+
readonly rows: number;
|
|
685
|
+
readonly columns: number;
|
|
686
|
+
readonly width?: number;
|
|
687
|
+
readonly height?: number;
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
/** The terminal modes of RFC 4254 §8 by name, such as { ECHO: 0, ISIG: 1 }. */
|
|
691
|
+
export type TerminalModes = Readonly<Record<string, number>>;
|
|
692
|
+
|
|
693
|
+
/** RFC 4254 §6.10, with no SIG. */
|
|
694
|
+
export type SignalName =
|
|
695
|
+
| 'ABRT'
|
|
696
|
+
| 'ALRM'
|
|
697
|
+
| 'FPE'
|
|
698
|
+
| 'HUP'
|
|
699
|
+
| 'ILL'
|
|
700
|
+
| 'INT'
|
|
701
|
+
| 'KILL'
|
|
702
|
+
| 'PIPE'
|
|
703
|
+
| 'QUIT'
|
|
704
|
+
| 'SEGV'
|
|
705
|
+
| 'TERM'
|
|
706
|
+
| 'USR1'
|
|
707
|
+
| 'USR2';
|
|
708
|
+
|
|
709
|
+
/** A socket that the server listens on for the client. */
|
|
710
|
+
export class RemoteListener implements AsyncDisposable {
|
|
711
|
+
readonly network: 'tcp' | 'unix';
|
|
712
|
+
/** For port 0, the port that the server chose. */
|
|
713
|
+
readonly address: string;
|
|
714
|
+
/** cancel-tcpip-forward or cancel-streamlocal-forward@openssh.com. */
|
|
715
|
+
close(): Promise<void>;
|
|
716
|
+
[Symbol.asyncDispose](): Promise<void>;
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
/** How the command of a session ended: exit-status or exit-signal, RFC 4254 §6.10. */
|
|
720
|
+
export type Exit =
|
|
721
|
+
| { readonly kind: 'status'; readonly exitStatus: number }
|
|
722
|
+
| {
|
|
723
|
+
readonly kind: 'signal';
|
|
724
|
+
/** sshd sends SIG@openssh.com for a signal outside RFC 4254's list (session.c, sig2name). */
|
|
725
|
+
readonly signal: SignalName | `${string}@${string}`;
|
|
726
|
+
readonly coreDumped: boolean;
|
|
727
|
+
readonly errorMessage: string;
|
|
728
|
+
};
|
|
729
|
+
|
|
730
|
+
/** Go's ExitError. */
|
|
731
|
+
export class ExitError extends Error {
|
|
732
|
+
readonly exit: Exit;
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
export class ExitMissingError extends Error {}
|
|
736
|
+
|
|
737
|
+
/** RFC 4254 §5.1 names; a number for another code. */
|
|
738
|
+
export type RejectionReason =
|
|
739
|
+
| 'administratively-prohibited'
|
|
740
|
+
| 'connect-failed'
|
|
741
|
+
| 'unknown-channel-type'
|
|
742
|
+
| 'resource-shortage'
|
|
743
|
+
| number;
|
|
744
|
+
|
|
745
|
+
/** The server refused a channel open: client.dial(), or the channel of a session. Go's ssh.OpenChannelError. */
|
|
746
|
+
export class OpenChannelError extends Error {
|
|
747
|
+
readonly reason: RejectionReason;
|
|
748
|
+
/** The server's text. */
|
|
749
|
+
readonly description: string;
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
export class AuthenticationError extends Error {
|
|
753
|
+
readonly attempted: readonly string[];
|
|
754
|
+
readonly allowed: readonly string[];
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
export class PassphraseMissingError extends Error {
|
|
758
|
+
readonly publicKey: PublicKey | undefined;
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
/** Go's ssh.ServerConfig. No clock: the server waits on no timer, and the signal of ServerConn.handshake bounds a slow handshake. */
|
|
762
|
+
export interface ServerConfig {
|
|
763
|
+
readonly hostKeys: readonly PrivateKey[];
|
|
764
|
+
/** Go's PublicKeyCallback. */
|
|
765
|
+
readonly publicKey?: (
|
|
766
|
+
user: string,
|
|
767
|
+
key: PublicKey,
|
|
768
|
+
) => boolean | Promise<boolean>;
|
|
769
|
+
/** Go's PasswordCallback. */
|
|
770
|
+
readonly password?: (
|
|
771
|
+
user: string,
|
|
772
|
+
password: string,
|
|
773
|
+
) => boolean | Promise<boolean>;
|
|
774
|
+
/** Go's KeyboardInteractiveCallback. */
|
|
775
|
+
readonly keyboardInteractive?: (
|
|
776
|
+
user: string,
|
|
777
|
+
ask: (prompts: readonly Prompt[]) => Promise<readonly string[]>,
|
|
778
|
+
) => boolean | Promise<boolean>;
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
/** The server side of one connection, after its handshake. Go's ssh.ServerConn. */
|
|
782
|
+
export class ServerConn implements AsyncDisposable {
|
|
783
|
+
/** Go's ssh.NewServerConn. */
|
|
784
|
+
static handshake(
|
|
785
|
+
transport: Duplex,
|
|
786
|
+
config: ServerConfig,
|
|
787
|
+
options?: { readonly signal?: AbortSignal },
|
|
788
|
+
): Promise<ServerConn>;
|
|
789
|
+
readonly user: string;
|
|
790
|
+
readonly clientVersion: string;
|
|
791
|
+
/** Go's <-chan NewChannel. */
|
|
792
|
+
channels(): AsyncIterable<IncomingChannel>;
|
|
793
|
+
/** Go's <-chan *Request, for the global requests. */
|
|
794
|
+
requests(): AsyncIterable<GlobalRequest>;
|
|
795
|
+
/** forwarded-tcpip, for a tcpip-forward that the server accepted: address is the listened address, origin host:port of the peer. */
|
|
796
|
+
forward(network: 'tcp', address: string, origin: string): Promise<Duplex>;
|
|
797
|
+
/** forwarded-streamlocal@openssh.com, for a streamlocal-forward that the server accepted. It carries no origin. */
|
|
798
|
+
forward(network: 'unix', path: string): Promise<Duplex>;
|
|
799
|
+
close(): Promise<void>;
|
|
800
|
+
[Symbol.asyncDispose](): Promise<void>;
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
export type IncomingChannel =
|
|
804
|
+
| { readonly type: 'session'; accept(): ServerSession; reject(): void }
|
|
805
|
+
| {
|
|
806
|
+
readonly type: 'direct-tcpip';
|
|
807
|
+
readonly address: string;
|
|
808
|
+
readonly origin: string;
|
|
809
|
+
accept(): Duplex;
|
|
810
|
+
reject(): void;
|
|
811
|
+
}
|
|
812
|
+
| {
|
|
813
|
+
readonly type: 'direct-streamlocal@openssh.com';
|
|
814
|
+
readonly path: string;
|
|
815
|
+
accept(): Duplex;
|
|
816
|
+
reject(): void;
|
|
817
|
+
};
|
|
818
|
+
|
|
819
|
+
export type GlobalRequest =
|
|
820
|
+
| {
|
|
821
|
+
readonly type: 'tcpip-forward';
|
|
822
|
+
readonly address: string;
|
|
823
|
+
/** port: the port that the server bound, when the address asked for port 0 (RFC 4254 §7.1). */
|
|
824
|
+
accept(port?: number): void;
|
|
825
|
+
reject(): void;
|
|
826
|
+
}
|
|
827
|
+
| {
|
|
828
|
+
readonly type: 'cancel-tcpip-forward';
|
|
829
|
+
readonly address: string;
|
|
830
|
+
accept(): void;
|
|
831
|
+
reject(): void;
|
|
832
|
+
}
|
|
833
|
+
| {
|
|
834
|
+
readonly type:
|
|
835
|
+
| 'streamlocal-forward@openssh.com'
|
|
836
|
+
| 'cancel-streamlocal-forward@openssh.com';
|
|
837
|
+
readonly path: string;
|
|
838
|
+
accept(): void;
|
|
839
|
+
reject(): void;
|
|
840
|
+
};
|
|
841
|
+
|
|
842
|
+
/** A session channel that the server accepted. */
|
|
843
|
+
export class ServerSession {
|
|
844
|
+
readonly stdin: Readable;
|
|
845
|
+
readonly stdout: Writable;
|
|
846
|
+
readonly stderr: Writable;
|
|
847
|
+
requests(): AsyncIterable<SessionRequest>;
|
|
848
|
+
/** Sends exit-status, or exit-signal, and closes the channel. */
|
|
849
|
+
exit(
|
|
850
|
+
status:
|
|
851
|
+
| number
|
|
852
|
+
| {
|
|
853
|
+
readonly signal: SignalName | `${string}@${string}`;
|
|
854
|
+
readonly coreDumped?: boolean;
|
|
855
|
+
readonly errorMessage?: string;
|
|
856
|
+
},
|
|
857
|
+
): Promise<void>;
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
export type SessionRequest =
|
|
861
|
+
| {
|
|
862
|
+
readonly type: 'env';
|
|
863
|
+
readonly name: string;
|
|
864
|
+
readonly value: string;
|
|
865
|
+
accept(): void;
|
|
866
|
+
reject(): void;
|
|
867
|
+
}
|
|
868
|
+
| {
|
|
869
|
+
readonly type: 'pty-req';
|
|
870
|
+
readonly term: string;
|
|
871
|
+
readonly size: WindowSize;
|
|
872
|
+
readonly modes: TerminalModes;
|
|
873
|
+
accept(): void;
|
|
874
|
+
reject(): void;
|
|
875
|
+
}
|
|
876
|
+
| { readonly type: 'window-change'; readonly size: WindowSize }
|
|
877
|
+
| {
|
|
878
|
+
readonly type: 'signal';
|
|
879
|
+
readonly name: SignalName | `${string}@${string}`;
|
|
880
|
+
}
|
|
881
|
+
| {
|
|
882
|
+
readonly type: 'exec';
|
|
883
|
+
readonly command: string;
|
|
884
|
+
accept(): void;
|
|
885
|
+
reject(): void;
|
|
886
|
+
}
|
|
887
|
+
| {
|
|
888
|
+
readonly type: 'shell' | 'auth-agent-req@openssh.com';
|
|
889
|
+
accept(): void;
|
|
890
|
+
reject(): void;
|
|
891
|
+
};
|
|
892
|
+
|
|
893
|
+
// @zukhruf/ssh/agent
|
|
894
|
+
|
|
895
|
+
import type { Duplex } from 'node:stream';
|
|
896
|
+
|
|
897
|
+
import type { PrivateKey, PublicKey, Signer } from '@zukhruf/ssh';
|
|
898
|
+
|
|
899
|
+
/** A client of an agent over a socket that the caller connected. Go's agent.NewClient. draft-ietf-sshm-ssh-agent. */
|
|
900
|
+
export class AgentClient {
|
|
901
|
+
constructor(socket: Duplex);
|
|
902
|
+
/** The keys of the agent, in its order. A key that the package cannot parse, such as a certificate, is left out. Go's List. */
|
|
903
|
+
list(): Promise<AgentKey[]>;
|
|
904
|
+
/** One signer for each key; each signature is a request to the agent. Go's Signers. */
|
|
905
|
+
signers(): Promise<Signer[]>;
|
|
906
|
+
/** The signature blob. Without `algorithm`, an RSA key signs with ssh-rsa. Go's SignWithFlags. */
|
|
907
|
+
sign(
|
|
908
|
+
key: PublicKey,
|
|
909
|
+
data: Uint8Array,
|
|
910
|
+
options?: { readonly algorithm?: 'rsa-sha2-256' | 'rsa-sha2-512' },
|
|
911
|
+
): Promise<Uint8Array>;
|
|
912
|
+
/** lifetime in ms, as ssh-add -t (rounded up to whole seconds); confirm, as ssh-add -c. Go's Add. */
|
|
913
|
+
add(
|
|
914
|
+
key: PrivateKey,
|
|
915
|
+
options?: {
|
|
916
|
+
readonly comment?: string;
|
|
917
|
+
readonly lifetime?: number;
|
|
918
|
+
readonly confirm?: boolean;
|
|
919
|
+
},
|
|
920
|
+
): Promise<void>;
|
|
921
|
+
remove(key: PublicKey): Promise<void>;
|
|
922
|
+
removeAll(): Promise<void>;
|
|
923
|
+
/** The agent lists no key and signs nothing until unlock with the same passphrase. Go's Lock. */
|
|
924
|
+
lock(passphrase: string): Promise<void>;
|
|
925
|
+
unlock(passphrase: string): Promise<void>;
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
export interface AgentKey {
|
|
929
|
+
readonly key: PublicKey;
|
|
930
|
+
readonly comment: string;
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
// @zukhruf/ssh/control
|
|
934
|
+
|
|
935
|
+
import type { Duplex } from 'node:stream';
|
|
936
|
+
|
|
937
|
+
import type { Client, Session } from '@zukhruf/ssh';
|
|
938
|
+
|
|
939
|
+
/** Serves the channels of a client to other processes on a Unix socket. OpenSSH's ControlMaster and ControlPath. */
|
|
940
|
+
export class ControlMaster implements AsyncDisposable {
|
|
941
|
+
/** Listens on `path`. Disposal stops the listener and closes each channel that the master serves; it does not close `client`. */
|
|
942
|
+
static listen(client: Client, path: string): Promise<ControlMaster>;
|
|
943
|
+
readonly path: string;
|
|
944
|
+
[Symbol.asyncDispose](): Promise<void>;
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
/** Opens channels through the master at `path`, one connection to the socket for each channel. */
|
|
948
|
+
export class ControlClient {
|
|
949
|
+
constructor(path: string);
|
|
950
|
+
/** As Client#dial. */
|
|
951
|
+
dial(network: 'tcp' | 'unix', address: string): Promise<Duplex>;
|
|
952
|
+
/** As Client#newSession. */
|
|
953
|
+
newSession(): Session;
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
// @zukhruf/ssh/knownhosts
|
|
957
|
+
|
|
958
|
+
import type { PublicKey } from '@zukhruf/ssh';
|
|
959
|
+
|
|
960
|
+
/** The keys of the known hosts files. Go's ssh/knownhosts. */
|
|
961
|
+
export class KnownHosts {
|
|
962
|
+
/** Reads the files in order; a missing file is empty. Go's knownhosts.New. */
|
|
963
|
+
static read(files: readonly string[]): Promise<KnownHosts>;
|
|
964
|
+
/** Throws KeyError or RevokedError. Looks up [hostname]:port when the port is not 22. */
|
|
965
|
+
check(hostname: string, port: number, key: PublicKey): void;
|
|
966
|
+
/** The algorithms of the known keys of the host first, then the rest of `offered`. Default `offered`: each one that the package supports. */
|
|
967
|
+
hostKeyAlgorithms(
|
|
968
|
+
hostname: string,
|
|
969
|
+
port: number,
|
|
970
|
+
offered?: readonly string[],
|
|
971
|
+
): string[];
|
|
972
|
+
/** Appends a line to the first file, hashed when `hash` is true. Go's knownhosts.Line. */
|
|
973
|
+
add(
|
|
974
|
+
hostname: string,
|
|
975
|
+
port: number,
|
|
976
|
+
key: PublicKey,
|
|
977
|
+
options: { readonly hash: boolean },
|
|
978
|
+
): Promise<void>;
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
/** Go's knownhosts.KnownKey. */
|
|
982
|
+
export interface KnownKey {
|
|
983
|
+
readonly key: PublicKey;
|
|
984
|
+
readonly file: string;
|
|
985
|
+
readonly line: number;
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
/** Go's knownhosts.KeyError: an empty `want` means an unknown host. */
|
|
989
|
+
export class KeyError extends Error {
|
|
990
|
+
readonly want: readonly KnownKey[];
|
|
991
|
+
}
|
|
992
|
+
|
|
993
|
+
/** Go's knownhosts.RevokedError. */
|
|
994
|
+
export class RevokedError extends Error {
|
|
995
|
+
readonly revoked: KnownKey;
|
|
996
|
+
}
|
|
997
|
+
|
|
998
|
+
// @zukhruf/ssh/config
|
|
999
|
+
|
|
1000
|
+
import type { Clock } from '@zukhruf/async';
|
|
1001
|
+
import type { Client } from '@zukhruf/ssh';
|
|
1002
|
+
|
|
1003
|
+
export type Environment = Readonly<Record<string, string | undefined>>;
|
|
1004
|
+
|
|
1005
|
+
/** The settings of OpenSSH for one destination, as ssh -G prints them. */
|
|
1006
|
+
export class OpenSshConfig {
|
|
1007
|
+
/** Runs ssh -G <flags> -- <destination> with `environment`, and resolves each jump host of the route with its own ssh -G. */
|
|
1008
|
+
static resolve(
|
|
1009
|
+
destination: string,
|
|
1010
|
+
options: {
|
|
1011
|
+
readonly flags?: readonly string[];
|
|
1012
|
+
readonly environment: Environment;
|
|
1013
|
+
readonly signal?: AbortSignal;
|
|
1014
|
+
},
|
|
1015
|
+
): Promise<OpenSshConfig>;
|
|
1016
|
+
readonly destination: string;
|
|
1017
|
+
readonly hostname: string;
|
|
1018
|
+
readonly port: number;
|
|
1019
|
+
readonly user: string;
|
|
1020
|
+
readonly hostKeyAlias: string | undefined;
|
|
1021
|
+
readonly knownHostsFiles: {
|
|
1022
|
+
readonly user: readonly string[];
|
|
1023
|
+
readonly global: readonly string[];
|
|
1024
|
+
};
|
|
1025
|
+
/** ssh -G prints true, false, ask or accept-new: 'yes', 'no', 'ask', 'accept-new'. */
|
|
1026
|
+
readonly strictHostKeyChecking: 'yes' | 'ask' | 'accept-new' | 'no';
|
|
1027
|
+
readonly hashKnownHosts: boolean;
|
|
1028
|
+
/** Without the algorithms that ssh2 does not have. */
|
|
1029
|
+
readonly hostKeyAlgorithms: readonly string[];
|
|
1030
|
+
/** The agent socket; undefined for IdentityAgent none, or no SSH_AUTH_SOCK. */
|
|
1031
|
+
readonly identityAgent: string | undefined;
|
|
1032
|
+
/** With ~ expanded from HOME of the environment. ssh -G prints % tokens and ${VAR} here unexpanded (ssh expands them only when it loads the keys), so a file named with them is not found and its key is not offered: fewer keys, as ADR 0004 allows for a setting that the package does not read. */
|
|
1033
|
+
readonly identityFiles: readonly string[];
|
|
1034
|
+
readonly identitiesOnly: boolean;
|
|
1035
|
+
readonly route: Route;
|
|
1036
|
+
/** ms; undefined for none or 0. */
|
|
1037
|
+
readonly connectTimeout: number | undefined;
|
|
1038
|
+
/** undefined when ServerAliveInterval is 0. */
|
|
1039
|
+
readonly keepalive:
|
|
1040
|
+
{ readonly interval: number; readonly countMax: number } | undefined;
|
|
1041
|
+
/** undefined for any. */
|
|
1042
|
+
readonly addressFamily: 4 | 6 | undefined;
|
|
1043
|
+
readonly setEnv: ReadonlyMap<string, string>;
|
|
1044
|
+
readonly sendEnv: readonly string[];
|
|
1045
|
+
/** ForwardAgent as OpenSSH resolves it: no, yes (the agent at SSH_AUTH_SOCK of the environment), or a socket path (a $NAME value is read from the environment; a $NAME that it does not set is off, as in ssh.c). dial sets ClientConfig.agentForwarding from it. */
|
|
1046
|
+
readonly forwardAgent:
|
|
1047
|
+
| { readonly kind: 'off' }
|
|
1048
|
+
| { readonly kind: 'agent' }
|
|
1049
|
+
| { readonly kind: 'socket'; readonly path: string };
|
|
1050
|
+
/** Connects by the route, checks the host key under the policy, authenticates with the agent, then the identity files, and sets sessionEnv from setEnv and sendEnv, and agentForwarding from forwardAgent. */
|
|
1051
|
+
dial(options: {
|
|
1052
|
+
readonly clock: Clock;
|
|
1053
|
+
readonly signal?: AbortSignal;
|
|
1054
|
+
}): Promise<Client>;
|
|
1055
|
+
}
|
|
1056
|
+
|
|
1057
|
+
/** How dial reaches the host. OpenSSH uses one of the three: ProxyJump and ProxyCommand exclude each other. */
|
|
1058
|
+
export type Route =
|
|
1059
|
+
| { readonly kind: 'direct' }
|
|
1060
|
+
/** ProxyCommand, with its tokens not yet expanded (ADR 0010). */
|
|
1061
|
+
| { readonly kind: 'proxy-command'; readonly command: string }
|
|
1062
|
+
/** ProxyJump, in the order of the list. Only the first jump host has a route of its own (ADR 0006). */
|
|
1063
|
+
| {
|
|
1064
|
+
readonly kind: 'jump';
|
|
1065
|
+
readonly jumpHosts: readonly [FirstJumpHost, ...JumpHost[]];
|
|
1066
|
+
};
|
|
1067
|
+
|
|
1068
|
+
/** The resolved settings of a jump host, by its own ssh -G, with no route: OpenSSH reaches a jump host after the first through the one before it, and reads no ProxyJump or ProxyCommand of its config. A jump host opens no session, so it has no session env and no agent forwarding. */
|
|
1069
|
+
export type JumpHost = Omit<
|
|
1070
|
+
OpenSshConfig,
|
|
1071
|
+
'route' | 'setEnv' | 'sendEnv' | 'forwardAgent' | 'dial'
|
|
1072
|
+
>;
|
|
1073
|
+
|
|
1074
|
+
/** The first jump host: the one jump host that follows its own ProxyJump or ProxyCommand. */
|
|
1075
|
+
export interface FirstJumpHost extends JumpHost {
|
|
1076
|
+
readonly route: Route;
|
|
1077
|
+
}
|
|
1078
|
+
```
|
|
1079
|
+
|
|
1080
|
+
## Why not an npm package
|
|
1081
|
+
|
|
1082
|
+
The package depends on ssh2 for the protocol, and adds the rest: the known hosts, `ssh -G`, the agent and identity files from the config, jump hosts, the `AbortSignal` of each call, the clock, and the API of Go ([ADR 0003](./docs/adr/0003-ssh2-speaks-the-protocol.md)). The search of npm on 2026-11-17 found no package that gives that rest:
|
|
1083
|
+
|
|
1084
|
+
| Package | Last release | Downloads a week | Packages | Why it is not the package |
|
|
1085
|
+
| ---------------------------- | ------------ | ---------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------- |
|
|
1086
|
+
| `ssh2` 1.17.0 | 2025-08-20 | 21.2M | 8 | The protocol base. No known_hosts, no config, no `AbortSignal`, no certificate host keys; `privateKey` takes bytes. One maintainer |
|
|
1087
|
+
| `node-ssh` 14.0.0 | 2026-11-16 | 467k | 12 | Wraps ssh2 and adds nothing that this package needs |
|
|
1088
|
+
| `ssh2-promise` 1.0.3 | 2022-06-19 | 23k | 14 | No streamlocal; stale |
|
|
1089
|
+
| `tunnel-ssh` 5.2.0 | 2024-12-15 | 406k | 9 | A port-forward helper |
|
|
1090
|
+
| `@microsoft/dev-tunnels-ssh` | 2026-08-24 | 46k | 13 | Its own stack; no agent client, no streamlocal message |
|
|
1091
|
+
| `ssh-config` 5.3.0 | 2026-09-11 | 234k | 1 | A parser: no `Include`, `Match exec` behind an option, no defaults, no `%h` or `%p`. `ssh -G` needs no package |
|
|
1092
|
+
| `sshpk` 1.18.0 | 2023-10-19 | 21.8M | 10 | Parses keys and certificates; no known_hosts parser; stale |
|
|
1093
|
+
| `known_hosts` 1.0.3 | 2016-03-31 | 10 | 0 | Only `\|1\|` entries, no markers; dead |
|
|
1094
|
+
|
|
1095
|
+
ssh2's footprint is 8 packages. Its optional native parts, `sshcrypto.node` and `cpu-features`, stay unbuilt. zukhruf's `.npmrc` sets `strict-allow-scripts=true`, so an install fails when a dependency has an install script that `allowScripts` does not name. The root `allowScripts` lists `"ssh2": false` and `"cpu-features": false`, and a consumer with `strict-allow-scripts` adds the same two lines. ssh2 falls back to JavaScript when they are missing (`protocol/crypto.js:30-33`, `protocol/constants.js:5-8`); `src/ssh2-javascript-crypto.test.ts` proves a handshake with the native parts absent, which answers the Electron concern of [docker ADR 0001](../docker/docs/adr/0001-the-client-speaks-the-engine-api-not-the-docker-cli.md).
|
|
1096
|
+
|
|
1097
|
+
## What each repository changes
|
|
1098
|
+
|
|
1099
|
+
The package leads. Each repository below changes to fit it, with no adapter, and no consumer shapes the API ([ADR 0001](./docs/adr/0001-the-scope-and-the-name-of-gos-ssh-package.md)).
|
|
1100
|
+
|
|
1101
|
+
| Repository and file | Change | Backlog |
|
|
1102
|
+
| -------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------- |
|
|
1103
|
+
| `@zukhruf/docker`: `src/transport.ts`, `src/ssh-connection.ts` | `SocketTransport` and `SshTransport` become one HTTP transport over a dial function, as moby's `WithDialContext` takes docker/cli's `helper.Dialer` (`client/client_options.go`, `cli/context/docker/load.go`). `unix://` and `npipe://` dial through `node:net`. `ssh://` resolves an `OpenSshConfig` with `sshFlags` (and `-o ConnectTimeout=30` when they do not name it, as the Docker CLI), holds one `Client`, and dials `client.dial('unix', <engine socket>)` for each HTTP connection. Docker finds the engine socket itself: a session runs `docker context inspect --format '{{.Endpoints.docker.Host}}'` on the remote host. When the server refuses the dial, docker refuses with a clear error that names the server's refusal and the fixes: rootless Docker, whose socket is under `/run/user/<uid>`, or an OpenSSH server. It has no `docker system dial-stdio` fallback (Ezz, 2026-11-17: "Refuse with a clear error"); Podman's `connection_stdio.go` fallback was the precedent that lost. `SshExitError` goes; the errors of this package become the `cause` of `ConnectionFailedError`. New ADRs supersede the connection helper of docker ADR 0002 and all of ADR 0010. | #4503 |
|
|
1104
|
+
| `@zukhruf/docker`: `src/testing/ssh-stand-in.ts` | The fake `ssh` binary of the attach, disposal, local-engine and ssh-engine tests gives way to a real server: `ServerConn` of this package in the test process, or an sshd container | #4503 |
|
|
1105
|
+
| `@zukhruf/docker`: `README.md`, `CONTEXT.md` | Line 5 and the `package.json` description ("no third-party dependencies"), the `ssh` rows of the errors, and the section "SSH engines". The terms "Connection helper" and "Connection failure" | #4503 |
|
|
1106
|
+
| `@zukhruf/testing`: `src/docker/host.ts` | `shell()` becomes `client.newSession().output(script)`, with the input on `stdin`. `forward()` becomes a `node:net` server and `client.dial('tcp', '127.0.0.1:<port>')` ([ADR 0009](./docs/adr/0009-the-caller-forwards-a-local-port-with-node-net-and-client-dial.md)). `sshArgs()`, the remote `cat`, the forward folder, its record and the 1 s kill go. Tests: `src/docker/ssh-forward.integration.test.ts` | #4503 |
|
|
1107
|
+
| `@zukhruf/testing`: `src/scripts/run-cleanup.ts` | The `forward-*` records go. `execFileSync('ssh', …)` for `rm -rf` is synchronous, because the global teardown must finish under `--test-force-exit`: it becomes a session in a worker that the teardown waits for with `Atomics.wait` (docker ADR 0001), or stays a one-shot `ssh`. Testing decides in its own ADR | #4503 |
|
|
1108
|
+
| text2sql: `infra/dokploy/seed/box.ts` | `ssh()` becomes `output()`. `streamToBox()` becomes `session.start(remoteCommand)` with the local command's stdout piped to `session.stdin`. `SSH_OPTS` become the flags of `OpenSshConfig.resolve`; `StrictHostKeyChecking=accept-new` keeps its meaning | #4513 (text2sql) |
|
|
1109
|
+
|
|
1110
|
+
## Documentation
|
|
1111
|
+
|
|
1112
|
+
**Decisions**
|
|
1113
|
+
|
|
1114
|
+
- [ADR 0001](./docs/adr/0001-the-scope-and-the-name-of-gos-ssh-package.md): the scope and the name of Go's ssh package.
|
|
1115
|
+
- [ADR 0002](./docs/adr/0002-the-connection-runs-in-the-node-process-and-no-helper-process-carries-it.md): the connection runs in the Node process, and no helper process carries it.
|
|
1116
|
+
- [ADR 0003](./docs/adr/0003-ssh2-speaks-the-protocol.md): ssh2 speaks the protocol.
|
|
1117
|
+
- [ADR 0004](./docs/adr/0004-openssh-resolves-the-config-through-ssh-g.md): OpenSSH resolves the config through ssh -G.
|
|
1118
|
+
- [ADR 0005](./docs/adr/0005-host-keys-are-checked-as-gos-knownhosts-checks-them-under-openssh-stricthostkeychecking.md): host keys are checked as Go's knownhosts checks them, under OpenSSH's StrictHostKeyChecking.
|
|
1119
|
+
- [ADR 0006](./docs/adr/0006-a-jump-host-is-a-connection-through-a-channel-of-the-previous-connection.md): a jump host is a connection through a channel of the previous connection.
|
|
1120
|
+
- [ADR 0007](./docs/adr/0007-keepalive-and-timeouts-come-only-from-the-resolved-config.md): keepalive and timeouts come only from the resolved config.
|
|
1121
|
+
- [ADR 0008](./docs/adr/0008-the-environment-and-the-clock-are-inputs.md): the environment and the clock are inputs.
|
|
1122
|
+
- [ADR 0009](./docs/adr/0009-the-caller-forwards-a-local-port-with-node-net-and-client-dial.md): the caller forwards a local port with node:net and client.dial.
|
|
1123
|
+
- [ADR 0010](./docs/adr/0010-a-proxycommand-runs-as-the-transport-of-the-connection.md): a ProxyCommand runs as the transport of the connection.
|
|
1124
|
+
- [ADR 0011](./docs/adr/0011-the-package-has-a-server-as-go-and-rust-do.md): the package has a server, as Go and Rust do.
|