@lethevimlet/sshift 1.7.9 → 1.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -5
- package/package.json +1 -1
- package/src/server/endpoints/rest/system.js +17 -12
- package/src/server/endpoints/ws/ssh.js +10 -1
- package/src/server/index.js +26 -140
- package/src/server/services/ssh-manager.js +67 -75
- package/src/server/utils/certs.js +314 -0
- package/src/webapp/css/style.css +52 -18
- package/src/webapp/index.html +136 -104
- package/src/webapp/js/app.js +309 -187
- package/src/webapp/js/mobile-terminal.js +138 -32
package/README.md
CHANGED
|
@@ -186,19 +186,21 @@ See [Configuration](docs/configuration.md) for details.
|
|
|
186
186
|
|
|
187
187
|
When accessing sshift from a LAN IP (e.g., `https://192.168.1.50:8022`), browsers show "Not Secure" warnings because the self-signed certificate is not trusted. This also blocks PWA installation, which requires a trusted secure context.
|
|
188
188
|
|
|
189
|
-
### Recommended: Trust the Auto-Generated
|
|
189
|
+
### Recommended: Trust the Auto-Generated Local CA
|
|
190
190
|
|
|
191
|
-
sshift
|
|
191
|
+
On first run sshift creates its own small certificate authority (CA) and signs its HTTPS certificate with it. Both live in `~/.local/share/sshift/` and survive updates. Trust the CA once per device and every certificate sshift issues afterwards (new IPs, renewals) is accepted automatically:
|
|
192
192
|
|
|
193
|
-
1. **Download the certificate** — visit `https://<your-sshift-host>:8022/api/cert`
|
|
193
|
+
1. **Download the CA certificate** — click **Download CA Certificate** in Settings → Security & Connection Info, visit `https://<your-sshift-host>:8022/api/cert` (works over plain `http://` too), or copy `~/.local/share/sshift/ssl-ca-cert.pem` from the server
|
|
194
194
|
2. **Add it to your device's trusted root store:**
|
|
195
195
|
- **Windows:** Double-click the file → Install Certificate → Local Machine → Trusted Root Certification Authorities
|
|
196
196
|
- **macOS:** Double-click the file → Add to Keychain → Set "Always Trust" in Keychain Access
|
|
197
197
|
- **Linux:** Copy to `/usr/local/share/ca-certificates/` and run `sudo update-ca-certificates`
|
|
198
|
-
- **Android:** Settings → Security → Install from
|
|
198
|
+
- **Android (Chrome/Brave):** Settings → Security & privacy → More security settings → Encryption & credentials → Install a certificate → **CA certificate** → pick `sshift-ca.crt` from Downloads
|
|
199
199
|
- **iOS:** Send via AirDrop/email → Open → Install profile → Settings → General → About → Certificate Trust Settings → Enable full trust
|
|
200
200
|
|
|
201
|
-
After trusting the
|
|
201
|
+
After trusting the CA, the "Not Secure" warning will disappear and PWA installation will work.
|
|
202
|
+
|
|
203
|
+
> Upgrading from a version before 1.8.1: the old certificate was a plain self-signed one that Android refuses to install as a CA. It is replaced by the CA-signed one on first start, so re-download and install the CA once.
|
|
202
204
|
|
|
203
205
|
### Using Your Own Certificate
|
|
204
206
|
|
package/package.json
CHANGED
|
@@ -6,8 +6,7 @@ const fs = require('fs');
|
|
|
6
6
|
const path = require('path');
|
|
7
7
|
const { getDataDir, getCertPath, getKeyPath, getConfigPath } = require('../../utils/config');
|
|
8
8
|
|
|
9
|
-
const SSL_CERT_FILE = '
|
|
10
|
-
const SSL_KEY_FILE = 'ssl-key.pem';
|
|
9
|
+
const { SSL_CERT_FILE, SSL_KEY_FILE, SSL_CA_CERT_FILE } = require('../../utils/certs');
|
|
11
10
|
const UPDATE_MARKER_FILE = '.updating';
|
|
12
11
|
|
|
13
12
|
/**
|
|
@@ -186,29 +185,32 @@ function registerSystemEndpoints(app, io) {
|
|
|
186
185
|
});
|
|
187
186
|
});
|
|
188
187
|
|
|
189
|
-
// API: Download
|
|
188
|
+
// API: Download the local CA certificate (the file to install on devices).
|
|
189
|
+
// Served as application/x-x509-ca-cert so Android/Brave offer to install
|
|
190
|
+
// it as a CA credential. Also reachable over plain HTTP (see index.js).
|
|
190
191
|
app.get('/api/cert', (req, res) => {
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
192
|
+
if (getCertPath() && getKeyPath()) {
|
|
193
|
+
return res.status(404).json({ error: 'A custom certificate is configured; obtain its CA from your administrator' });
|
|
194
|
+
}
|
|
195
|
+
const caCertPath = path.join(getDataDir(), SSL_CA_CERT_FILE);
|
|
196
|
+
if (!fs.existsSync(caCertPath)) {
|
|
195
197
|
return res.status(404).json({ error: 'Certificate not found' });
|
|
196
198
|
}
|
|
197
199
|
|
|
198
|
-
res.setHeader('Content-Type', 'application/x-
|
|
200
|
+
res.setHeader('Content-Type', 'application/x-x509-ca-cert');
|
|
199
201
|
res.setHeader('Content-Disposition', 'attachment; filename="sshift-ca.crt"');
|
|
200
|
-
|
|
202
|
+
res.setHeader('Cache-Control', 'no-store');
|
|
203
|
+
fs.createReadStream(caCertPath).pipe(res);
|
|
201
204
|
});
|
|
202
205
|
|
|
203
206
|
// API: Get security context info
|
|
204
207
|
app.get('/api/security-info', (req, res) => {
|
|
205
208
|
const dataDir = getDataDir();
|
|
206
|
-
const
|
|
207
|
-
const hasCert = fs.existsSync(
|
|
209
|
+
const usesCustomCert = !!(getCertPath() && getKeyPath());
|
|
210
|
+
const hasCert = !usesCustomCert && fs.existsSync(path.join(dataDir, SSL_CA_CERT_FILE));
|
|
208
211
|
const protocol = req.protocol;
|
|
209
212
|
const isSecure = req.secure || protocol === 'https';
|
|
210
213
|
const isLocalhost = req.hostname === 'localhost' || req.hostname === '127.0.0.1' || req.hostname === '::1';
|
|
211
|
-
const usesCustomCert = !!(getCertPath() && getKeyPath());
|
|
212
214
|
|
|
213
215
|
res.json({
|
|
214
216
|
isSecure,
|
|
@@ -225,6 +227,7 @@ function registerSystemEndpoints(app, io) {
|
|
|
225
227
|
const dataDir = getDataDir();
|
|
226
228
|
const selfSignedCertPath = path.join(dataDir, SSL_CERT_FILE);
|
|
227
229
|
const selfSignedKeyPath = path.join(dataDir, SSL_KEY_FILE);
|
|
230
|
+
const caCertPath = path.join(dataDir, SSL_CA_CERT_FILE);
|
|
228
231
|
const customCertPath = getCertPath();
|
|
229
232
|
const customKeyPath = getKeyPath();
|
|
230
233
|
const usesCustomCert = !!(customCertPath && customKeyPath);
|
|
@@ -234,6 +237,8 @@ function registerSystemEndpoints(app, io) {
|
|
|
234
237
|
dataDir,
|
|
235
238
|
certPath: usesCustomCert ? customCertPath : selfSignedCertPath,
|
|
236
239
|
keyPath: usesCustomCert ? customKeyPath : selfSignedKeyPath,
|
|
240
|
+
caCertPath: usesCustomCert ? null : caCertPath,
|
|
241
|
+
certType: usesCustomCert ? 'Custom' : 'Local CA-signed',
|
|
237
242
|
usesCustomCert
|
|
238
243
|
});
|
|
239
244
|
});
|
|
@@ -133,7 +133,16 @@ function registerSSHHandlers(socket, io) {
|
|
|
133
133
|
cols: state.cols,
|
|
134
134
|
rows: state.rows,
|
|
135
135
|
encoded: true,
|
|
136
|
-
partial:
|
|
136
|
+
partial: !!state.partial
|
|
137
|
+
});
|
|
138
|
+
} else if (sshManager.hasSession && sshManager.hasSession(data.sessionId)) {
|
|
139
|
+
// The session exists but its screen could not be serialized right
|
|
140
|
+
// now. That is an operational hiccup, not a dead session — a hard
|
|
141
|
+
// 'Session not found' would make the client treat the tab as gone.
|
|
142
|
+
socket.emit('ssh-error', {
|
|
143
|
+
sessionId: data.sessionId,
|
|
144
|
+
message: 'Screen sync unavailable, please retry',
|
|
145
|
+
advisory: true
|
|
137
146
|
});
|
|
138
147
|
} else {
|
|
139
148
|
socket.emit('ssh-error', { message: 'Session not found', sessionId: data.sessionId });
|
package/src/server/index.js
CHANGED
|
@@ -21,11 +21,11 @@ const https = require('https');
|
|
|
21
21
|
const fs = require('fs');
|
|
22
22
|
const path = require('path');
|
|
23
23
|
const socketIO = require('socket.io');
|
|
24
|
-
const
|
|
24
|
+
const { ensureLocalCertificates } = require('./utils/certs');
|
|
25
25
|
const httpolyglot = require('httpolyglot');
|
|
26
26
|
|
|
27
27
|
// Import utilities
|
|
28
|
-
const { ensureConfig, loadConfig, getPort, getBindAddress, getEnableHttps, getHttpRedirect, getCertPath, getKeyPath, getDataDir,
|
|
28
|
+
const { ensureConfig, loadConfig, getPort, getBindAddress, getEnableHttps, getHttpRedirect, getCertPath, getKeyPath, getDataDir, isPasswordSet, USER_INSTALL_DIR, migrateLegacyPackageConfig } = require('./utils/config');
|
|
29
29
|
|
|
30
30
|
// Import services
|
|
31
31
|
const { sshManager, sftpManager } = require('./services');
|
|
@@ -39,14 +39,16 @@ const pluginManager = require('./plugins/plugin-manager');
|
|
|
39
39
|
// Import endpoints
|
|
40
40
|
const { rest, ws } = require('./endpoints');
|
|
41
41
|
|
|
42
|
-
const SSL_CERT_FILE = 'ssl-cert.pem';
|
|
43
|
-
const SSL_KEY_FILE = 'ssl-key.pem';
|
|
44
|
-
|
|
45
42
|
/**
|
|
46
|
-
* Get SSL credentials
|
|
47
|
-
*
|
|
48
|
-
*
|
|
49
|
-
*
|
|
43
|
+
* Get SSL credentials.
|
|
44
|
+
*
|
|
45
|
+
* Custom certPath/keyPath from config win. Otherwise a local CA and a
|
|
46
|
+
* CA-signed server certificate are kept in the user-space data directory
|
|
47
|
+
* (see utils/certs.js): the CA is created once and survives npm updates
|
|
48
|
+
* and Docker recreation (when /data is a volume); the server certificate
|
|
49
|
+
* is re-issued from it whenever it is missing, self-signed (pre-1.8.1
|
|
50
|
+
* installs), expiring or no longer covers the current hostname/IPs.
|
|
51
|
+
* @returns {Promise<Object>} Certificate chain and private key
|
|
50
52
|
*/
|
|
51
53
|
async function getSSLCredentials() {
|
|
52
54
|
const customCertPath = getCertPath();
|
|
@@ -63,142 +65,23 @@ async function getSSLCredentials() {
|
|
|
63
65
|
};
|
|
64
66
|
} catch (err) {
|
|
65
67
|
console.error('[HTTPS] Failed to read custom certificate files:', err.message);
|
|
66
|
-
console.error('[HTTPS] Falling back to
|
|
68
|
+
console.error('[HTTPS] Falling back to the local CA-signed certificate');
|
|
67
69
|
}
|
|
68
70
|
} else if (customCertPath || customKeyPath) {
|
|
69
|
-
console.warn('[HTTPS] Both certPath and keyPath must be set in config. Only one was provided; falling back to
|
|
71
|
+
console.warn('[HTTPS] Both certPath and keyPath must be set in config. Only one was provided; falling back to the local CA-signed certificate.');
|
|
70
72
|
}
|
|
71
73
|
|
|
72
74
|
const dataDir = getDataDir();
|
|
73
|
-
const
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
if (fs.existsSync(certPath) && fs.existsSync(keyPath)) {
|
|
77
|
-
console.log('[HTTPS] Reusing persisted SSL certificate from', dataDir);
|
|
78
|
-
try {
|
|
79
|
-
const cert = fs.readFileSync(certPath, 'utf8');
|
|
80
|
-
const key = fs.readFileSync(keyPath, 'utf8');
|
|
81
|
-
if (!certIncludesOrg(cert)) {
|
|
82
|
-
console.log('[HTTPS] Existing certificate lacks organizationName, regenerating...');
|
|
83
|
-
} else {
|
|
84
|
-
return { cert, key };
|
|
85
|
-
}
|
|
86
|
-
} catch (err) {
|
|
87
|
-
console.warn('[HTTPS] Failed to read persisted certificate, regenerating:', err.message);
|
|
88
|
-
}
|
|
89
|
-
} else {
|
|
90
|
-
// Migrate from legacy (package) directory if certs exist there
|
|
91
|
-
const legacyDir = getLegacyDataDir();
|
|
92
|
-
if (legacyDir) {
|
|
93
|
-
const legacyCert = path.join(legacyDir, SSL_CERT_FILE);
|
|
94
|
-
const legacyKey = path.join(legacyDir, SSL_KEY_FILE);
|
|
95
|
-
if (fs.existsSync(legacyCert) && fs.existsSync(legacyKey)) {
|
|
96
|
-
console.log('[HTTPS] Migrating SSL certificate from', legacyDir, 'to', dataDir);
|
|
97
|
-
try {
|
|
98
|
-
if (!fs.existsSync(dataDir)) {
|
|
99
|
-
fs.mkdirSync(dataDir, { recursive: true });
|
|
100
|
-
}
|
|
101
|
-
const certData = fs.readFileSync(legacyCert, 'utf8');
|
|
102
|
-
const keyData = fs.readFileSync(legacyKey, 'utf8');
|
|
103
|
-
fs.writeFileSync(certPath, certData, { mode: 0o600 });
|
|
104
|
-
fs.writeFileSync(keyPath, keyData, { mode: 0o600 });
|
|
105
|
-
console.log('[HTTPS] SSL certificate migrated to user-space directory');
|
|
106
|
-
if (certIncludesOrg(certData)) {
|
|
107
|
-
return { cert: certData, key: keyData };
|
|
108
|
-
}
|
|
109
|
-
console.log('[HTTPS] Migrated certificate lacks organizationName, regenerating...');
|
|
110
|
-
} catch (err) {
|
|
111
|
-
console.warn('[HTTPS] Failed to migrate certificate:', err.message);
|
|
112
|
-
}
|
|
113
|
-
}
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
const creds = await generateSelfSignedCert();
|
|
118
|
-
|
|
119
|
-
try {
|
|
120
|
-
if (!fs.existsSync(dataDir)) {
|
|
121
|
-
fs.mkdirSync(dataDir, { recursive: true });
|
|
122
|
-
}
|
|
123
|
-
fs.writeFileSync(certPath, creds.cert, { mode: 0o600 });
|
|
124
|
-
fs.writeFileSync(keyPath, creds.key, { mode: 0o600 });
|
|
125
|
-
console.log('[HTTPS] SSL certificate persisted to', dataDir);
|
|
126
|
-
} catch (err) {
|
|
127
|
-
console.warn('[HTTPS] Failed to persist certificate:', err.message);
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
return creds;
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
/**
|
|
134
|
-
* Check if a PEM certificate includes an organizationName (O=) attribute.
|
|
135
|
-
* @param {string} certPem - PEM-encoded certificate
|
|
136
|
-
* @returns {boolean} True if O=sshift is present
|
|
137
|
-
*/
|
|
138
|
-
function certIncludesOrg(certPem) {
|
|
139
|
-
try {
|
|
140
|
-
const { X509Certificate } = require('crypto');
|
|
141
|
-
const x509 = new X509Certificate(certPem);
|
|
142
|
-
return /O=sshift/i.test(x509.subject);
|
|
143
|
-
} catch {
|
|
144
|
-
return false;
|
|
145
|
-
}
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
/**
|
|
149
|
-
* Generate self-signed SSL certificates using selfsigned package (pure JS, no OpenSSL dependency)
|
|
150
|
-
* @returns {Promise<Object>} Certificate and private key
|
|
151
|
-
*/
|
|
152
|
-
async function generateSelfSignedCert() {
|
|
153
|
-
console.log('[HTTPS] Generating self-signed certificate...');
|
|
154
|
-
|
|
155
|
-
const os = require('os');
|
|
156
|
-
|
|
157
|
-
const interfaces = os.networkInterfaces();
|
|
158
|
-
const localIPs = ['127.0.0.1'];
|
|
159
|
-
|
|
160
|
-
Object.values(interfaces).forEach(iface => {
|
|
161
|
-
iface.forEach(addr => {
|
|
162
|
-
if (addr.family === 'IPv4' && !addr.internal) {
|
|
163
|
-
localIPs.push(addr.address);
|
|
164
|
-
}
|
|
165
|
-
});
|
|
75
|
+
const result = await ensureLocalCertificates(dataDir, {
|
|
76
|
+
log: msg => console.log('[HTTPS]', msg)
|
|
166
77
|
});
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
const altNames = [
|
|
173
|
-
{ type: 2, value: 'localhost' },
|
|
174
|
-
{ type: 2, value: hostname },
|
|
175
|
-
...localIPs.map(ip => ({ type: 7, ip }))
|
|
176
|
-
];
|
|
177
|
-
|
|
178
|
-
try {
|
|
179
|
-
const attrs = [
|
|
180
|
-
{ name: 'commonName', value: hostname },
|
|
181
|
-
{ name: 'organizationName', value: 'sshift' }
|
|
182
|
-
];
|
|
183
|
-
const pems = await selfsigned.generate(attrs, {
|
|
184
|
-
days: 365,
|
|
185
|
-
keySize: 2048,
|
|
186
|
-
algorithm: 'sha256',
|
|
187
|
-
extensions: [{
|
|
188
|
-
name: 'subjectAltName',
|
|
189
|
-
altNames
|
|
190
|
-
}]
|
|
191
|
-
});
|
|
192
|
-
|
|
193
|
-
console.log('[HTTPS] Self-signed certificate generated successfully');
|
|
194
|
-
return {
|
|
195
|
-
cert: pems.cert,
|
|
196
|
-
key: pems.private
|
|
197
|
-
};
|
|
198
|
-
} catch (err) {
|
|
199
|
-
console.error('[HTTPS] Error generating certificate:', err);
|
|
200
|
-
throw err;
|
|
78
|
+
if (result.caCreated) {
|
|
79
|
+
console.log('[HTTPS] NOTE: a new local CA was created. Devices that trusted the previous');
|
|
80
|
+
console.log('[HTTPS] self-signed certificate must install the new CA from /api/cert.');
|
|
81
|
+
} else if (!result.certIssued) {
|
|
82
|
+
console.log('[HTTPS] Reusing persisted local CA and server certificate from', dataDir);
|
|
201
83
|
}
|
|
84
|
+
return { cert: result.cert, key: result.key };
|
|
202
85
|
}
|
|
203
86
|
|
|
204
87
|
// Create Express app
|
|
@@ -282,6 +165,9 @@ async function initializeServer() {
|
|
|
282
165
|
// HTTP to HTTPS redirect middleware (for dual-protocol httpolyglot server)
|
|
283
166
|
if (enableHttpRedirect) {
|
|
284
167
|
app.use((req, res, next) => {
|
|
168
|
+
// The CA download must stay reachable over plain HTTP: a device that
|
|
169
|
+
// does not trust the CA yet cannot fetch it over HTTPS without warnings.
|
|
170
|
+
if (req.path === '/api/cert') return next();
|
|
285
171
|
if (!req.socket.encrypted) {
|
|
286
172
|
const host = req.headers.host ? req.headers.host.split(':')[0] : 'localhost';
|
|
287
173
|
const port = getPort();
|
|
@@ -472,8 +358,8 @@ async function initializeServer() {
|
|
|
472
358
|
console.log(`${ESC}]8;;${protocol}://${address}:${PORT}${ESC}\\Open in browser${ESC}]8;;${ESC}\\`);
|
|
473
359
|
|
|
474
360
|
if (actuallyHttps) {
|
|
475
|
-
console.log('[HTTPS] Note:
|
|
476
|
-
console.log('[HTTPS]
|
|
361
|
+
console.log('[HTTPS] Note: the certificate is issued by sshift\'s local CA. Browsers warn until that CA is trusted.');
|
|
362
|
+
console.log('[HTTPS] Install the CA on each device once: download it from /api/cert (also over plain http://).');
|
|
477
363
|
}
|
|
478
364
|
});
|
|
479
365
|
}
|
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
const { Client } = require('ssh2');
|
|
2
2
|
const { Terminal } = require('@xterm/headless');
|
|
3
3
|
const { SerializeAddon } = require('@xterm/addon-serialize');
|
|
4
|
+
|
|
5
|
+
// Screen-sync payload cap (raw, pre-base64) and the scrollback tiers tried
|
|
6
|
+
// when the full history is larger than that. See _serializeForSync().
|
|
7
|
+
const SYNC_FULL_MAX_BYTES = 768 * 1024;
|
|
8
|
+
const SYNC_SCROLLBACK_TIERS = [2000, 500, 100, 0];
|
|
4
9
|
const { Unicode11Addon } = require('@xterm/addon-unicode11');
|
|
5
10
|
const pluginManager = require('../plugins/plugin-manager');
|
|
6
11
|
const { convertKeyIfNeeded } = require('../utils/key-converter');
|
|
@@ -359,59 +364,19 @@ class SSHManager {
|
|
|
359
364
|
// Send current terminal state to the joining socket BEFORE joining the room
|
|
360
365
|
// This ensures the client gets the full state before receiving any new data
|
|
361
366
|
if (session.terminal && session.serializeAddon) {
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
if (serializedState.length > fullMaxSize) {
|
|
376
|
-
console.warn(`[SSH] Full terminal state too large (${serializedState.length} bytes), falling back to viewport-only`);
|
|
377
|
-
serializedState = session.serializeAddon.serialize({ mode: 'normal' });
|
|
378
|
-
if (typeof serializedState !== 'string') {
|
|
379
|
-
serializedState = String(serializedState);
|
|
380
|
-
}
|
|
381
|
-
|
|
382
|
-
if (serializedState.length > viewportMaxSize) {
|
|
383
|
-
console.warn(`[SSH] Viewport state also too large (${serializedState.length} bytes), skipping sync`);
|
|
384
|
-
} else {
|
|
385
|
-
// Send viewport-only state
|
|
386
|
-
const base64State = Buffer.from(serializedState, 'utf-8').toString('base64');
|
|
387
|
-
socket.emit('ssh-screen-sync', {
|
|
388
|
-
sessionId: sessionId,
|
|
389
|
-
state: base64State,
|
|
390
|
-
cols: session.cols,
|
|
391
|
-
rows: session.rows,
|
|
392
|
-
encoded: true,
|
|
393
|
-
partial: true
|
|
394
|
-
});
|
|
395
|
-
hasTerminalState = true;
|
|
396
|
-
}
|
|
397
|
-
} else {
|
|
398
|
-
// Send full state including scrollback
|
|
399
|
-
const base64State = Buffer.from(serializedState, 'utf-8').toString('base64');
|
|
400
|
-
console.log(`[SSH] Sending full serialized terminal state to socket ${socket.id}, size: ${serializedState.length}, base64: ${base64State.length}`);
|
|
401
|
-
|
|
402
|
-
socket.emit('ssh-screen-sync', {
|
|
403
|
-
sessionId: sessionId,
|
|
404
|
-
state: base64State,
|
|
405
|
-
cols: session.cols,
|
|
406
|
-
rows: session.rows,
|
|
407
|
-
encoded: true,
|
|
408
|
-
partial: false
|
|
409
|
-
});
|
|
410
|
-
|
|
411
|
-
hasTerminalState = true;
|
|
412
|
-
}
|
|
413
|
-
} catch (err) {
|
|
414
|
-
console.error(`[SSH] Error serializing terminal state:`, err.message);
|
|
367
|
+
const snapshot = this._serializeForSync(session, SYNC_FULL_MAX_BYTES);
|
|
368
|
+
if (snapshot) {
|
|
369
|
+
const base64State = Buffer.from(snapshot.state, 'utf-8').toString('base64');
|
|
370
|
+
console.log(`[SSH] Sending serialized terminal state to socket ${socket.id}, size: ${snapshot.state.length}, base64: ${base64State.length}, scrollback: ${snapshot.scrollbackLines === undefined ? 'full' : snapshot.scrollbackLines}`);
|
|
371
|
+
socket.emit('ssh-screen-sync', {
|
|
372
|
+
sessionId: sessionId,
|
|
373
|
+
state: base64State,
|
|
374
|
+
cols: session.cols,
|
|
375
|
+
rows: session.rows,
|
|
376
|
+
encoded: true,
|
|
377
|
+
partial: snapshot.partial
|
|
378
|
+
});
|
|
379
|
+
hasTerminalState = true;
|
|
415
380
|
}
|
|
416
381
|
}
|
|
417
382
|
|
|
@@ -628,31 +593,58 @@ if (this.io) {
|
|
|
628
593
|
if (!session || !session.terminal || !session.serializeAddon) {
|
|
629
594
|
return null;
|
|
630
595
|
}
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
596
|
+
const snapshot = this._serializeForSync(session, SYNC_FULL_MAX_BYTES);
|
|
597
|
+
if (!snapshot) return null;
|
|
598
|
+
return {
|
|
599
|
+
state: snapshot.state,
|
|
600
|
+
cols: session.cols,
|
|
601
|
+
rows: session.rows,
|
|
602
|
+
partial: snapshot.partial
|
|
603
|
+
};
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
hasSession(sessionId) {
|
|
607
|
+
return this.sessions.has(sessionId);
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
// Serialize a session's screen for a client sync, shrinking the amount
|
|
611
|
+
// of scrollback until the payload fits under `maxBytes`.
|
|
612
|
+
//
|
|
613
|
+
// The old code tried `serialize({ mode: 'normal' })` as a "viewport-only"
|
|
614
|
+
// fallback. `mode` is not a SerializeAddon option — that call returned the
|
|
615
|
+
// exact same full-scrollback payload, so any long-running session whose
|
|
616
|
+
// history serialized above the cap got NO screen state at all: the
|
|
617
|
+
// joining browser saw only the live stream from that point on, and
|
|
618
|
+
// line-diff TUIs (which never repaint rows they consider unchanged) left
|
|
619
|
+
// it with a screen full of black rows until a resize forced a full
|
|
620
|
+
// repaint. That is the "alternating text/black lines when opening a new
|
|
621
|
+
// window" bug.
|
|
622
|
+
//
|
|
623
|
+
// Tiers: full scrollback → recent scrollback → viewport only. The viewport
|
|
624
|
+
// tier is a few KB and is always sent, so a sync can only fail if the
|
|
625
|
+
// serialize addon itself throws.
|
|
626
|
+
_serializeForSync(session, maxBytes) {
|
|
627
|
+
if (!session || !session.terminal || !session.serializeAddon) return null;
|
|
628
|
+
const tiers = [undefined, ...SYNC_SCROLLBACK_TIERS];
|
|
629
|
+
for (const scrollback of tiers) {
|
|
630
|
+
let state;
|
|
631
|
+
try {
|
|
632
|
+
state = scrollback === undefined
|
|
633
|
+
? session.serializeAddon.serialize()
|
|
634
|
+
: session.serializeAddon.serialize({ scrollback });
|
|
635
|
+
} catch (err) {
|
|
636
|
+
console.error(`[SSH] Error serializing terminal state (scrollback=${scrollback}):`, err.message);
|
|
637
|
+
continue;
|
|
638
|
+
}
|
|
639
|
+
if (typeof state !== 'string') state = String(state);
|
|
640
|
+
if (state.length <= maxBytes || scrollback === 0) {
|
|
641
|
+
if (scrollback !== undefined) {
|
|
642
|
+
console.warn(`[SSH] Terminal state trimmed to ${scrollback} scrollback lines (${state.length} bytes) for sync`);
|
|
644
643
|
}
|
|
644
|
+
return { state, partial: scrollback !== undefined, scrollbackLines: scrollback };
|
|
645
645
|
}
|
|
646
|
-
|
|
647
|
-
return {
|
|
648
|
-
state: serializedState,
|
|
649
|
-
cols: session.cols,
|
|
650
|
-
rows: session.rows
|
|
651
|
-
};
|
|
652
|
-
} catch (err) {
|
|
653
|
-
console.error(`[SSH] Error getting terminal state:`, err.message);
|
|
654
|
-
return null;
|
|
655
646
|
}
|
|
647
|
+
return null;
|
|
656
648
|
}
|
|
657
649
|
|
|
658
650
|
// Get ONLY the visible viewport of a session (no scrollback).
|