@myrialabs/clopen 0.4.32 → 0.4.34
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/backend/auth/permissions.ts +3 -0
- package/backend/auth/rate-limiter.test.ts +115 -0
- package/backend/auth/rate-limiter.ts +25 -12
- package/backend/chat/stream-manager.ts +4 -1
- package/backend/database/migrations/069_create_ssh_client_tables.ts +116 -0
- package/backend/database/migrations/index.ts +7 -0
- package/backend/database/queries/db-client-connection-queries.ts +7 -2
- package/backend/database/queries/file-audit-log-queries.ts +1 -0
- package/backend/database/queries/index.ts +3 -0
- package/backend/database/queries/ssh-connection-queries.ts +244 -0
- package/backend/database/queries/ssh-known-host-queries.ts +67 -0
- package/backend/database/queries/ssh-port-forward-queries.ts +113 -0
- package/backend/db-client/connection-manager.ts +21 -1
- package/backend/engine/adapters/codex/message-converter.ts +18 -12
- package/backend/engine/adapters/codex/patch-rollout.test.ts +88 -0
- package/backend/engine/adapters/codex/patch-rollout.ts +120 -109
- package/backend/engine/adapters/codex/stream.ts +33 -4
- package/backend/engine/adapters/copilot/stream.ts +1 -1
- package/backend/engine/adapters/cursor/stream.ts +1 -1
- package/backend/engine/adapters/qwen/stream.ts +1 -1
- package/backend/engine/docs/adapter-contract.md +7 -0
- package/backend/files/file-watcher.ts +283 -51
- package/backend/files/git-events.test.ts +110 -0
- package/backend/git/git-dirs.test.ts +132 -0
- package/backend/git/git-dirs.ts +0 -0
- package/backend/git/nested-repos.test.ts +108 -5
- package/backend/git/nested-repos.ts +103 -18
- package/backend/http/audio.ts +5 -32
- package/backend/http/bearer-auth.ts +47 -0
- package/backend/http/files-download.test.ts +146 -0
- package/backend/http/files-download.ts +109 -0
- package/backend/http/files-upload.ts +3 -29
- package/backend/http/ssh-sftp.ts +133 -0
- package/backend/index.ts +25 -2
- package/backend/mcp/README.md +34 -6
- package/backend/mcp/index.ts +8 -8
- package/backend/mcp/internal/config.ts +69 -19
- package/backend/mcp/internal/project-context.test.ts +40 -0
- package/backend/mcp/internal/project-context.ts +80 -7
- package/backend/mcp/internal/remote-server.test.ts +17 -2
- package/backend/mcp/internal/remote-server.ts +36 -3
- package/backend/mcp/internal/servers/helper.ts +48 -18
- package/backend/middleware/security.test.ts +95 -0
- package/backend/middleware/security.ts +114 -0
- package/backend/ports/attribute.test.ts +231 -0
- package/backend/ports/attribute.ts +444 -0
- package/backend/ports/kill.ts +203 -0
- package/backend/ports/monitor.ts +365 -0
- package/backend/ports/processes.test.ts +98 -0
- package/backend/ports/processes.ts +374 -0
- package/backend/ports/registry.ts +165 -0
- package/backend/ports/runner.ts +195 -0
- package/backend/ports/scan-host.ts +260 -0
- package/backend/ports/scan.test.ts +341 -0
- package/backend/ports/scan.ts +687 -0
- package/backend/ports/ssh-lineage.ts +318 -0
- package/backend/preview/browser/browser-video-capture.ts +51 -4
- package/backend/ssh/client-pool.ts +196 -0
- package/backend/ssh/connect.ts +375 -0
- package/backend/ssh/disk-usage.test.ts +134 -0
- package/backend/ssh/disk-usage.ts +214 -0
- package/backend/ssh/forwards.ts +340 -0
- package/backend/ssh/health.ts +141 -0
- package/backend/ssh/known-hosts.ts +96 -0
- package/backend/ssh/pty-backend.ts +215 -0
- package/backend/ssh/ptykit.ts +66 -0
- package/backend/ssh/sftp.test.ts +242 -0
- package/backend/ssh/sftp.ts +967 -0
- package/backend/ssh/socks5.test.ts +167 -0
- package/backend/ssh/socks5.ts +164 -0
- package/backend/ssh/tunnel.ts +87 -0
- package/backend/ws/auth/device.ts +1 -1
- package/backend/ws/auth/login.ts +8 -4
- package/backend/ws/db-client/connections.ts +1 -0
- package/backend/ws/files/watch.ts +5 -1
- package/backend/ws/index.ts +6 -0
- package/backend/ws/ports/index.ts +19 -0
- package/backend/ws/ports/kill.ts +80 -0
- package/backend/ws/ports/list.ts +60 -0
- package/backend/ws/ssh/access.ts +31 -0
- package/backend/ws/ssh/connections.ts +224 -0
- package/backend/ws/ssh/forwards.ts +109 -0
- package/backend/ws/ssh/index.ts +18 -0
- package/backend/ws/ssh/sftp.ts +259 -0
- package/backend/ws/ssh/tunnel.ts +93 -0
- package/dist/assets/{index-hu17G6tX.js → index-gGTMFUa8.js} +1 -1
- package/dist/assets/{index-DSvGoxp2.js → index-vW2RpdHu.js} +1 -1
- package/dist/assets/main-CYCMEbXB.css +1 -0
- package/dist/assets/{main-BccclZsC.js → main-ZCojSzvW.js} +506 -477
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/shared/types/database/schema.ts +49 -0
- package/shared/types/db-client/connection.ts +6 -0
- package/shared/types/ports/index.ts +5 -0
- package/shared/types/ports/port.ts +192 -0
- package/shared/types/ssh/connection.ts +80 -0
- package/shared/types/ssh/forward.ts +46 -0
- package/shared/types/ssh/index.ts +8 -0
- package/shared/types/ssh/known-host.ts +19 -0
- package/shared/types/ssh/sftp.ts +141 -0
- package/shared/utils/logger.ts +2 -0
- package/dist/assets/main-Ciuw0wF0.css +0 -1
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ssh-client — trust-on-first-use host key checking.
|
|
3
|
+
*
|
|
4
|
+
* OpenSSH asks the user at the terminal the first time it meets a host. Clopen
|
|
5
|
+
* has no terminal to ask at connect time, so it records the first key it sees
|
|
6
|
+
* and refuses any later key that differs. A change is a hard stop with both
|
|
7
|
+
* fingerprints reported; trusting the new key is an explicit action in the UI.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { createHash } from 'node:crypto';
|
|
11
|
+
import { sshKnownHostQueries } from '../database/queries';
|
|
12
|
+
import type { SshKnownHost } from '$shared/types/ssh';
|
|
13
|
+
import { debug } from '$shared/utils/logger';
|
|
14
|
+
|
|
15
|
+
export interface HostKeyIdentity {
|
|
16
|
+
keyType: string;
|
|
17
|
+
/** `SHA256:…` — the same rendering `ssh-keygen -lf` prints. */
|
|
18
|
+
fingerprint: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* An SSH public key blob is a sequence of length-prefixed fields; the first is
|
|
23
|
+
* the algorithm name (`ssh-ed25519`, `rsa-sha2-512`, …). Read just that one.
|
|
24
|
+
*/
|
|
25
|
+
function readKeyType(keyBlob: Buffer): string {
|
|
26
|
+
if (keyBlob.length < 4) return 'unknown';
|
|
27
|
+
const nameLength = keyBlob.readUInt32BE(0);
|
|
28
|
+
if (nameLength <= 0 || nameLength > keyBlob.length - 4) return 'unknown';
|
|
29
|
+
return keyBlob.subarray(4, 4 + nameLength).toString('utf8');
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function describeHostKey(keyBlob: Buffer): HostKeyIdentity {
|
|
33
|
+
// OpenSSH prints the base64 digest without its padding.
|
|
34
|
+
const digest = createHash('sha256').update(keyBlob).digest('base64').replace(/=+$/, '');
|
|
35
|
+
return { keyType: readKeyType(keyBlob), fingerprint: `SHA256:${digest}` };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export type HostKeyVerdict =
|
|
39
|
+
| { outcome: 'trusted-now'; identity: HostKeyIdentity }
|
|
40
|
+
| { outcome: 'matches'; identity: HostKeyIdentity }
|
|
41
|
+
| { outcome: 'changed'; identity: HostKeyIdentity; known: SshKnownHost }
|
|
42
|
+
| { outcome: 'accepted-unchecked'; identity: HostKeyIdentity };
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Decide what to do with the key `host:port` just presented, and persist the
|
|
46
|
+
* decision. `strict` false still records and reports the key — it only stops
|
|
47
|
+
* a mismatch from being fatal.
|
|
48
|
+
*/
|
|
49
|
+
export function evaluateHostKey(
|
|
50
|
+
host: string,
|
|
51
|
+
port: number,
|
|
52
|
+
keyBlob: Buffer,
|
|
53
|
+
strict: boolean
|
|
54
|
+
): HostKeyVerdict {
|
|
55
|
+
const identity = describeHostKey(keyBlob);
|
|
56
|
+
const known = sshKnownHostQueries.find(host, port);
|
|
57
|
+
|
|
58
|
+
if (!known) {
|
|
59
|
+
sshKnownHostQueries.trust(host, port, identity.keyType, identity.fingerprint);
|
|
60
|
+
debug.log('ssh', `trusted new host key for ${host}:${port} — ${identity.fingerprint}`);
|
|
61
|
+
return { outcome: 'trusted-now', identity };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
if (known.fingerprint === identity.fingerprint) {
|
|
65
|
+
sshKnownHostQueries.markSeen(host, port);
|
|
66
|
+
return { outcome: 'matches', identity };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
if (!strict) {
|
|
70
|
+
debug.warn('ssh', `host key for ${host}:${port} changed but strict checking is off`);
|
|
71
|
+
sshKnownHostQueries.trust(host, port, identity.keyType, identity.fingerprint);
|
|
72
|
+
return { outcome: 'accepted-unchecked', identity };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
return { outcome: 'changed', identity, known };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** The message shown in the terminal (and in Test) when a key stops matching. */
|
|
79
|
+
export function hostKeyChangedMessage(host: string, port: number, verdict: HostKeyVerdict): string {
|
|
80
|
+
if (verdict.outcome !== 'changed') return '';
|
|
81
|
+
return [
|
|
82
|
+
`Host key verification failed for ${host}:${port}.`,
|
|
83
|
+
` expected ${verdict.known.fingerprint}`,
|
|
84
|
+
` received ${verdict.identity.fingerprint}`,
|
|
85
|
+
'The host may have been rebuilt, or the connection may be intercepted.',
|
|
86
|
+
'If you expected this, use "Trust new key" on the connection to accept it.'
|
|
87
|
+
].join('\n');
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export const knownHosts = {
|
|
91
|
+
list: (): SshKnownHost[] => sshKnownHostQueries.list(),
|
|
92
|
+
find: (host: string, port: number): SshKnownHost | null => sshKnownHostQueries.find(host, port),
|
|
93
|
+
trust: (host: string, port: number, keyType: string, fingerprint: string): SshKnownHost =>
|
|
94
|
+
sshKnownHostQueries.trust(host, port, keyType, fingerprint),
|
|
95
|
+
forget: (host: string, port: number): void => sshKnownHostQueries.forget(host, port)
|
|
96
|
+
};
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ssh-client — a PtyKit backend whose "process" is a remote shell.
|
|
3
|
+
*
|
|
4
|
+
* `PtyBackend` is the seam PtyKit already uses to talk to bun-pty/node-pty:
|
|
5
|
+
* spawn something, then write/resize/kill it and listen for data and exit. An
|
|
6
|
+
* ssh2 shell channel answers all of that, so pointing PtyKit at this backend
|
|
7
|
+
* gives the SSH terminal PtyKit's scrollback, serialized reattach, collaborative
|
|
8
|
+
* rooms and reconnect without reimplementing any of it.
|
|
9
|
+
*
|
|
10
|
+
* The one impedance mismatch: `spawn` is synchronous while connecting is not.
|
|
11
|
+
* The handle is returned immediately and queues writes and resizes until the
|
|
12
|
+
* channel opens; a connection failure surfaces as terminal output followed by a
|
|
13
|
+
* non-zero exit, which is exactly how a failed `ssh` invocation reads.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import type {
|
|
17
|
+
PtyBackend,
|
|
18
|
+
PtyDisposable,
|
|
19
|
+
PtyExitEvent,
|
|
20
|
+
PtyProcessHandle,
|
|
21
|
+
PtySpawnOptions
|
|
22
|
+
} from '@myrialabs/ptykit/core';
|
|
23
|
+
import type { ClientChannel } from 'ssh2';
|
|
24
|
+
import { sshConnectionQueries } from '../database/queries';
|
|
25
|
+
import { sshClientPool, type SshLease } from './client-pool';
|
|
26
|
+
import { debug } from '$shared/utils/logger';
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* The `file` PtyKit passes to `spawn`. PtyKit hands `shell` through untouched,
|
|
30
|
+
* so this is the one per-session channel available to name the target — and the
|
|
31
|
+
* value is stamped server-side (never taken from the client) in ws/ssh/tunnel.ts.
|
|
32
|
+
*/
|
|
33
|
+
const TARGET_PREFIX = 'clopen-ssh:';
|
|
34
|
+
|
|
35
|
+
export function encodeSshTarget(connectionId: string): string {
|
|
36
|
+
return `${TARGET_PREFIX}${connectionId}`;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function decodeSshTarget(file: string): string {
|
|
40
|
+
if (!file.startsWith(TARGET_PREFIX)) {
|
|
41
|
+
throw new Error('SSH terminal sessions must name a saved connection');
|
|
42
|
+
}
|
|
43
|
+
return file.slice(TARGET_PREFIX.length);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const ANSI_DIM = '\u001b[2m';
|
|
47
|
+
const ANSI_RED = '\u001b[31m';
|
|
48
|
+
const ANSI_RESET = '\u001b[0m';
|
|
49
|
+
|
|
50
|
+
/** Terminals expect CRLF; a lone \n leaves the cursor mid-line. */
|
|
51
|
+
function terminalLine(text: string): string {
|
|
52
|
+
return `${text.replace(/\n/g, '\r\n')}\r\n`;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Single-quote a POSIX shell argument, escaping any embedded quote. */
|
|
56
|
+
function shellQuote(value: string): string {
|
|
57
|
+
return `'${value.replace(/'/g, `'\\''`)}'`;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Distinct per-session ids so the tab list can tell sessions apart. */
|
|
61
|
+
let nextSyntheticPid = 1;
|
|
62
|
+
|
|
63
|
+
class SshShellHandle implements PtyProcessHandle {
|
|
64
|
+
readonly pid: number;
|
|
65
|
+
cols: number;
|
|
66
|
+
rows: number;
|
|
67
|
+
|
|
68
|
+
private readonly dataListeners = new Set<(data: string) => void>();
|
|
69
|
+
private readonly exitListeners = new Set<(event: PtyExitEvent) => void>();
|
|
70
|
+
private readonly pendingInput: string[] = [];
|
|
71
|
+
|
|
72
|
+
private channel: ClientChannel | null = null;
|
|
73
|
+
private lease: SshLease | null = null;
|
|
74
|
+
private finished = false;
|
|
75
|
+
|
|
76
|
+
constructor(connectionId: string, options: PtySpawnOptions) {
|
|
77
|
+
this.pid = nextSyntheticPid++;
|
|
78
|
+
this.cols = options.cols;
|
|
79
|
+
this.rows = options.rows;
|
|
80
|
+
// Deferred by one microtask on purpose: PtyKit subscribes to `onData` only
|
|
81
|
+
// after `spawn` returns, so anything emitted from this constructor — the
|
|
82
|
+
// "Connecting…" line, or an immediate failure — would go to nobody.
|
|
83
|
+
queueMicrotask(() => void this.open(connectionId, options.name ?? 'xterm-256color'));
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
private emitData(data: string): void {
|
|
87
|
+
for (const listener of this.dataListeners) listener(data);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
private finish(exitCode: number, signal?: string): void {
|
|
91
|
+
if (this.finished) return;
|
|
92
|
+
this.finished = true;
|
|
93
|
+
this.lease?.release();
|
|
94
|
+
this.lease = null;
|
|
95
|
+
for (const listener of this.exitListeners) listener({ exitCode, signal });
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
private async open(connectionId: string, term: string): Promise<void> {
|
|
99
|
+
const connection = sshConnectionQueries.get(connectionId);
|
|
100
|
+
if (!connection) {
|
|
101
|
+
this.emitData(terminalLine(`${ANSI_RED}This SSH connection no longer exists.${ANSI_RESET}`));
|
|
102
|
+
this.finish(1);
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const address = `${connection.username}@${connection.host}:${connection.port || 22}`;
|
|
107
|
+
this.emitData(terminalLine(`${ANSI_DIM}Connecting to ${address}…${ANSI_RESET}`));
|
|
108
|
+
|
|
109
|
+
let lease: SshLease;
|
|
110
|
+
try {
|
|
111
|
+
lease = await sshClientPool.acquire(connectionId);
|
|
112
|
+
} catch (error) {
|
|
113
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
114
|
+
this.emitData(terminalLine(`${ANSI_RED}${reason}${ANSI_RESET}`));
|
|
115
|
+
this.finish(255);
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// The session may have been killed while the handshake was in flight.
|
|
120
|
+
if (this.finished) {
|
|
121
|
+
lease.release();
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
this.lease = lease;
|
|
125
|
+
|
|
126
|
+
lease.client.shell({ term, cols: this.cols, rows: this.rows }, (error, channel) => {
|
|
127
|
+
if (error) {
|
|
128
|
+
this.emitData(terminalLine(`${ANSI_RED}Could not open a shell: ${error.message}${ANSI_RESET}`));
|
|
129
|
+
this.finish(1);
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
if (this.finished) {
|
|
133
|
+
channel.end();
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
this.channel = channel;
|
|
138
|
+
|
|
139
|
+
channel.on('data', (chunk: Buffer) => this.emitData(chunk.toString('utf8')));
|
|
140
|
+
channel.stderr.on('data', (chunk: Buffer) => this.emitData(chunk.toString('utf8')));
|
|
141
|
+
channel.on('close', (code?: number, signal?: string) => {
|
|
142
|
+
this.channel = null;
|
|
143
|
+
this.finish(typeof code === 'number' ? code : 0, signal);
|
|
144
|
+
});
|
|
145
|
+
channel.on('error', (channelError: Error) => {
|
|
146
|
+
this.emitData(terminalLine(`${ANSI_RED}${channelError.message}${ANSI_RESET}`));
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
// Start where the connection says to. The `cd` is sent as ordinary
|
|
150
|
+
// input so it lands in scrollback — the user can see where they are.
|
|
151
|
+
if (connection.initialPath) {
|
|
152
|
+
channel.write(`cd ${shellQuote(connection.initialPath)}\n`);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
for (const queued of this.pendingInput) channel.write(queued);
|
|
156
|
+
this.pendingInput.length = 0;
|
|
157
|
+
|
|
158
|
+
// A resize that arrived during the handshake was recorded on the
|
|
159
|
+
// handle; replay it so the remote pty matches the browser.
|
|
160
|
+
channel.setWindow(this.rows, this.cols, 0, 0);
|
|
161
|
+
debug.log('ssh', `shell opened on ${address}`);
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
write(data: string): void {
|
|
166
|
+
if (this.finished) return;
|
|
167
|
+
if (this.channel) {
|
|
168
|
+
this.channel.write(data);
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
this.pendingInput.push(data);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
resize(cols: number, rows: number): void {
|
|
175
|
+
this.cols = cols;
|
|
176
|
+
this.rows = rows;
|
|
177
|
+
this.channel?.setWindow(rows, cols, 0, 0);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
kill(): void {
|
|
181
|
+
// SSH has no signal to send a shell channel, so closing the channel is the
|
|
182
|
+
// kill: the remote shell sees its pty go away and exits.
|
|
183
|
+
const channel = this.channel;
|
|
184
|
+
this.channel = null;
|
|
185
|
+
try {
|
|
186
|
+
channel?.end();
|
|
187
|
+
} catch {
|
|
188
|
+
// Already gone.
|
|
189
|
+
}
|
|
190
|
+
this.finish(0);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
onData(listener: (data: string) => void): PtyDisposable {
|
|
194
|
+
this.dataListeners.add(listener);
|
|
195
|
+
return { dispose: () => this.dataListeners.delete(listener) };
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
onExit(listener: (event: PtyExitEvent) => void): PtyDisposable {
|
|
199
|
+
this.exitListeners.add(listener);
|
|
200
|
+
return { dispose: () => this.exitListeners.delete(listener) };
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* PtyKit's backend contract, satisfied by remote shells. The name has to be one
|
|
206
|
+
* of PtyKit's two known backend identifiers — it is only used for diagnostics,
|
|
207
|
+
* and the session engine never branches on it.
|
|
208
|
+
*/
|
|
209
|
+
export const sshPtyBackend: PtyBackend = {
|
|
210
|
+
name: 'node-pty',
|
|
211
|
+
experimental: false,
|
|
212
|
+
spawn(file: string, _args: string[], options: PtySpawnOptions): PtyProcessHandle {
|
|
213
|
+
return new SshShellHandle(decodeSshTarget(file), options);
|
|
214
|
+
}
|
|
215
|
+
};
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ssh-client — the PtyKit session engine for remote shells.
|
|
3
|
+
*
|
|
4
|
+
* A second `PtyKitManager` alongside the local-terminal one, differing only in
|
|
5
|
+
* its injected backend (`sshPtyBackend`). Everything downstream — scrollback,
|
|
6
|
+
* serialized reattach, collaborative rooms, reconnect — is PtyKit's.
|
|
7
|
+
*
|
|
8
|
+
* The namespace is `ssh:<connectionId>`: it scopes the collaborative room to a
|
|
9
|
+
* single host and is what `authorize` checks ownership against. It is also the
|
|
10
|
+
* only trustworthy statement of intent a client makes, so the tunnel derives the
|
|
11
|
+
* spawn target from it rather than from anything else in the frame.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { PtyKitManager } from '@myrialabs/ptykit/core';
|
|
15
|
+
import { createPtyKitServer } from '@myrialabs/ptykit/server';
|
|
16
|
+
import { sshConnectionQueries } from '../database/queries';
|
|
17
|
+
import { sshPtyBackend } from './pty-backend';
|
|
18
|
+
|
|
19
|
+
const NAMESPACE_PREFIX = 'ssh:';
|
|
20
|
+
|
|
21
|
+
export function sshNamespaceFor(connectionId: string): string {
|
|
22
|
+
return `${NAMESPACE_PREFIX}${connectionId}`;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** The connection a namespace refers to, or null when it is not one of ours. */
|
|
26
|
+
export function connectionIdFromNamespace(namespace: string): string | null {
|
|
27
|
+
if (!namespace.startsWith(NAMESPACE_PREFIX)) return null;
|
|
28
|
+
const connectionId = namespace.slice(NAMESPACE_PREFIX.length);
|
|
29
|
+
return connectionId || null;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Remote shells outlive a browser refresh the same way local ones do, so the
|
|
34
|
+
* settings mirror backend/terminal/ptykit.ts. Env injection is omitted: the
|
|
35
|
+
* environment that matters belongs to the remote host, not to this process.
|
|
36
|
+
*/
|
|
37
|
+
export const sshPtyKitManager = new PtyKitManager({
|
|
38
|
+
backend: sshPtyBackend,
|
|
39
|
+
scrollback: 5000,
|
|
40
|
+
idleTtl: null,
|
|
41
|
+
retainExitedMs: 5 * 60_000
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
export const sshPtyKitServer = createPtyKitServer(sshPtyKitManager, {
|
|
45
|
+
room: (ctx) => ctx.namespace,
|
|
46
|
+
authorize: (ctx) => {
|
|
47
|
+
const userId = ctx.conn.data.userId;
|
|
48
|
+
const isAdmin = ctx.conn.data.isAdmin === true;
|
|
49
|
+
if (typeof userId !== 'string' || !userId) return false;
|
|
50
|
+
|
|
51
|
+
const connectionId = connectionIdFromNamespace(ctx.namespace);
|
|
52
|
+
if (!connectionId) return false;
|
|
53
|
+
|
|
54
|
+
return sshConnectionQueries.getForUser(connectionId, userId, isAdmin) !== null;
|
|
55
|
+
}
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
/** Kill every shell open on a host. Used when its connection is edited or deleted. */
|
|
59
|
+
export function killSessionsForConnection(connectionId: string): number {
|
|
60
|
+
let killed = 0;
|
|
61
|
+
for (const session of sshPtyKitManager.list(sshNamespaceFor(connectionId))) {
|
|
62
|
+
sshPtyKitManager.killSession(session.sessionId, 'SIGKILL');
|
|
63
|
+
killed++;
|
|
64
|
+
}
|
|
65
|
+
return killed;
|
|
66
|
+
}
|
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test';
|
|
2
|
+
import {
|
|
3
|
+
archiveBaseName,
|
|
4
|
+
buildArchiveListCommand,
|
|
5
|
+
buildCandidateName,
|
|
6
|
+
buildCompressCommand,
|
|
7
|
+
buildExtractCommand,
|
|
8
|
+
joinRemote,
|
|
9
|
+
normalizeRemote,
|
|
10
|
+
parentOfRemote,
|
|
11
|
+
parseArchiveTopLevelNames,
|
|
12
|
+
splitRemoteName
|
|
13
|
+
} from './sftp';
|
|
14
|
+
|
|
15
|
+
describe('normalizeRemote', () => {
|
|
16
|
+
test('collapses duplicate slashes and dot segments', () => {
|
|
17
|
+
expect(normalizeRemote('/var//log/./nginx')).toBe('/var/log/nginx');
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
test('resolves parent segments', () => {
|
|
21
|
+
expect(normalizeRemote('/var/log/../www')).toBe('/var/www');
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
test('cannot climb above the root', () => {
|
|
25
|
+
expect(normalizeRemote('/../../etc')).toBe('/etc');
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
test('keeps leading parents on a relative path', () => {
|
|
29
|
+
expect(normalizeRemote('../sibling')).toBe('../sibling');
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
test('an emptied relative path becomes the current directory', () => {
|
|
33
|
+
expect(normalizeRemote('a/..')).toBe('.');
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
test('the root survives normalization', () => {
|
|
37
|
+
expect(normalizeRemote('/')).toBe('/');
|
|
38
|
+
});
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
describe('joinRemote', () => {
|
|
42
|
+
test('joins a directory and a name', () => {
|
|
43
|
+
expect(joinRemote('/var/log', 'nginx')).toBe('/var/log/nginx');
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
test('does not double the separator on a trailing slash', () => {
|
|
47
|
+
expect(joinRemote('/var/log/', 'nginx')).toBe('/var/log/nginx');
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
test('joins onto the root', () => {
|
|
51
|
+
expect(joinRemote('/', 'etc')).toBe('/etc');
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
test('an absolute name replaces the directory', () => {
|
|
55
|
+
expect(joinRemote('/var/log', '/etc/hosts')).toBe('/etc/hosts');
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
test('a parent name climbs one level', () => {
|
|
59
|
+
expect(joinRemote('/var/log', '..')).toBe('/var');
|
|
60
|
+
});
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
describe('parentOfRemote', () => {
|
|
64
|
+
test('drops the last segment', () => {
|
|
65
|
+
expect(parentOfRemote('/var/log/nginx')).toBe('/var/log');
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
test('a top-level path has the root as its parent', () => {
|
|
69
|
+
expect(parentOfRemote('/etc')).toBe('/');
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
test('the root is its own parent', () => {
|
|
73
|
+
expect(parentOfRemote('/')).toBe('/');
|
|
74
|
+
});
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
describe('buildCompressCommand', () => {
|
|
78
|
+
test('zip does not get a -- separator', () => {
|
|
79
|
+
// `zip -- archive.zip name` fails with "can't use -- before archive name".
|
|
80
|
+
const command = buildCompressCommand(
|
|
81
|
+
['/home/user/site', '/home/user/notes.txt'],
|
|
82
|
+
'/home/user/backup.zip',
|
|
83
|
+
'zip'
|
|
84
|
+
);
|
|
85
|
+
expect(command).not.toContain(' -- ');
|
|
86
|
+
expect(command).toBe(
|
|
87
|
+
`cd '/home/user' && zip -r -q '/home/user/backup.zip' './site' './notes.txt'`
|
|
88
|
+
);
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
test('tar does get one, since GNU tar accepts it', () => {
|
|
92
|
+
const command = buildCompressCommand(['/home/user/site'], '/home/user/backup.tar.gz', 'tar.gz');
|
|
93
|
+
expect(command).toBe(`cd '/home/user' && tar -czf '/home/user/backup.tar.gz' -- 'site'`);
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
test('runs from the common parent so entries are stored by plain name', () => {
|
|
97
|
+
const command = buildCompressCommand(['/var/www/html'], '/var/www/html.zip', 'zip');
|
|
98
|
+
expect(command.startsWith(`cd '/var/www' &&`)).toBe(true);
|
|
99
|
+
expect(command).toContain(`'./html'`);
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
test('a name starting with a dash is not read as an option', () => {
|
|
103
|
+
const zipCommand = buildCompressCommand(['/home/user/-rf'], '/home/user/out.zip', 'zip');
|
|
104
|
+
expect(zipCommand).toContain(`'./-rf'`);
|
|
105
|
+
const tarCommand = buildCompressCommand(['/home/user/-rf'], '/home/user/out.tar.gz', 'tar.gz');
|
|
106
|
+
expect(tarCommand).toContain(`-- '-rf'`);
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
test('a quote in a name cannot break out of the command', () => {
|
|
110
|
+
const command = buildCompressCommand(["/home/user/it's"], '/home/user/out.zip', 'zip');
|
|
111
|
+
expect(command).toContain(`'./it'\\''s'`);
|
|
112
|
+
});
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
describe('buildExtractCommand', () => {
|
|
116
|
+
test('picks unzip for a zip', () => {
|
|
117
|
+
expect(buildExtractCommand('/home/user/a.zip', '/home/user')).toBe(
|
|
118
|
+
`unzip -o -q '/home/user/a.zip' -d '/home/user'`
|
|
119
|
+
);
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
test('keeping the existing files flips unzip from -o to -n', () => {
|
|
123
|
+
expect(buildExtractCommand('/home/user/a.zip', '/home/user', true)).toBe(
|
|
124
|
+
`unzip -n -q '/home/user/a.zip' -d '/home/user'`
|
|
125
|
+
);
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
test('tar tries the quiet skip flag first and falls back to -k', () => {
|
|
129
|
+
// --skip-old-files is GNU tar's; a BSD or macOS host only knows -k.
|
|
130
|
+
const command = buildExtractCommand('/a/b.tar.gz', '/a', true);
|
|
131
|
+
expect(command).toBe(
|
|
132
|
+
`tar -xzf '/a/b.tar.gz' -C '/a' --skip-old-files 2>/dev/null || tar -xzf '/a/b.tar.gz' -C '/a' -k`
|
|
133
|
+
);
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
test('a bare gz is left alone when the decompressed file is already there', () => {
|
|
137
|
+
expect(buildExtractCommand('/a/access.log.gz', '/tmp', true)).toBe(
|
|
138
|
+
`[ -e '/tmp/access.log' ] || gunzip -c '/a/access.log.gz' > '/tmp/access.log'`
|
|
139
|
+
);
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
test('picks the matching decompressor for each tar flavour', () => {
|
|
143
|
+
expect(buildExtractCommand('/a/b.tar.gz', '/a')).toContain('tar -xzf');
|
|
144
|
+
expect(buildExtractCommand('/a/b.tgz', '/a')).toContain('tar -xzf');
|
|
145
|
+
expect(buildExtractCommand('/a/b.tar.bz2', '/a')).toContain('tar -xjf');
|
|
146
|
+
expect(buildExtractCommand('/a/b.tar.xz', '/a')).toContain('tar -xJf');
|
|
147
|
+
expect(buildExtractCommand('/a/b.tar', '/a')).toContain('tar -xf');
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
test('a bare gz is decompressed to its stem in the destination', () => {
|
|
151
|
+
expect(buildExtractCommand('/a/access.log.gz', '/tmp')).toBe(
|
|
152
|
+
`gunzip -c '/a/access.log.gz' > '/tmp/access.log'`
|
|
153
|
+
);
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
test('the suffix check is case-insensitive', () => {
|
|
157
|
+
expect(buildExtractCommand('/a/B.ZIP', '/a')).toContain('unzip');
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
test('an unknown type is refused rather than guessed at', () => {
|
|
161
|
+
expect(() => buildExtractCommand('/a/b.rar', '/a')).toThrow('does not know how to extract');
|
|
162
|
+
});
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
describe('splitRemoteName', () => {
|
|
166
|
+
test('splits a name from its extension', () => {
|
|
167
|
+
expect(splitRemoteName('notes.txt')).toEqual({ stem: 'notes', suffix: '.txt' });
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
test('a leading dot is part of the name, not a suffix', () => {
|
|
171
|
+
expect(splitRemoteName('.bashrc')).toEqual({ stem: '.bashrc', suffix: '' });
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
test('a compound archive suffix stays whole', () => {
|
|
175
|
+
expect(splitRemoteName('site.tar.gz')).toEqual({ stem: 'site', suffix: '.tar.gz' });
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
test('a name with no dot at all has no suffix', () => {
|
|
179
|
+
expect(splitRemoteName('logs')).toEqual({ stem: 'logs', suffix: '' });
|
|
180
|
+
});
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
describe('buildCandidateName', () => {
|
|
184
|
+
test('numbers a file before its extension', () => {
|
|
185
|
+
expect(buildCandidateName('notes.txt', 2)).toBe('notes (2).txt');
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
test('numbers a folder at the end', () => {
|
|
189
|
+
expect(buildCandidateName('logs', 3)).toBe('logs (3)');
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
test('numbers a tarball before its whole suffix', () => {
|
|
193
|
+
expect(buildCandidateName('site.tar.gz', 2)).toBe('site (2).tar.gz');
|
|
194
|
+
});
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
describe('archiveBaseName', () => {
|
|
198
|
+
test('drops a compound suffix rather than half of it', () => {
|
|
199
|
+
expect(archiveBaseName('/home/user/site.tar.gz')).toBe('site');
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
test('drops a single suffix', () => {
|
|
203
|
+
expect(archiveBaseName('/home/user/backup.zip')).toBe('backup');
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
test('leaves a name that is only a suffix alone', () => {
|
|
207
|
+
expect(archiveBaseName('/home/user/.zip')).toBe('.zip');
|
|
208
|
+
});
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
describe('buildArchiveListCommand', () => {
|
|
212
|
+
test('lists a zip with zipinfo and caps the output', () => {
|
|
213
|
+
expect(buildArchiveListCommand('/a/b.zip', 100)).toBe(`unzip -Z1 '/a/b.zip' | head -n 100`);
|
|
214
|
+
});
|
|
215
|
+
|
|
216
|
+
test('lists a tarball with the matching decompressor', () => {
|
|
217
|
+
expect(buildArchiveListCommand('/a/b.tar.xz', 100)).toBe(`tar -tJf '/a/b.tar.xz' | head -n 100`);
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
test('a bare gz has no index, so its single entry is named after itself', () => {
|
|
221
|
+
expect(buildArchiveListCommand('/a/access.log.gz')).toBe(`echo 'access.log'`);
|
|
222
|
+
});
|
|
223
|
+
|
|
224
|
+
test('an unknown type is refused rather than guessed at', () => {
|
|
225
|
+
expect(() => buildArchiveListCommand('/a/b.rar')).toThrow('does not know how to extract');
|
|
226
|
+
});
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
describe('parseArchiveTopLevelNames', () => {
|
|
230
|
+
test('collapses every entry to the name it creates in the destination', () => {
|
|
231
|
+
const names = parseArchiveTopLevelNames('site/\nsite/index.html\nsite/css/app.css\nREADME.md');
|
|
232
|
+
expect(names).toEqual(['site', 'README.md']);
|
|
233
|
+
});
|
|
234
|
+
|
|
235
|
+
test('strips the ./ prefix tar writes for an archive made from .', () => {
|
|
236
|
+
expect(parseArchiveTopLevelNames('./\n./bin/run\n./bin/stop')).toEqual(['bin']);
|
|
237
|
+
});
|
|
238
|
+
|
|
239
|
+
test('an empty listing has no names', () => {
|
|
240
|
+
expect(parseArchiveTopLevelNames('')).toEqual([]);
|
|
241
|
+
});
|
|
242
|
+
});
|