dsh-code-server-app 0.1.43 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +118 -106
- package/README.md +129 -92
- package/cordis.patch.yml +19 -15
- package/lib/client.js +1 -3
- package/lib/index.js +247 -144
- package/lib/launcher.mjs +369 -0
- package/lib/serve-dsh.mjs +162 -0
- package/lib/vendor.js +94 -33
- package/package.json +11 -7
- package/scripts/vendor-repacks.mjs +72 -99
- package/scripts/vendor-vscode-server.mjs +278 -0
- package/vendor/VENDOR.json +5 -2
package/lib/launcher.mjs
ADDED
|
@@ -0,0 +1,369 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* lib/launcher.mjs — VS Code server 的最小启动器(取代 code-server 的 out/node/** 服务层)。
|
|
3
|
+
*
|
|
4
|
+
* 它在**子进程**里加载 <tree>/lib/vscode/out/server-main.js,自建 node:http 把请求交给
|
|
5
|
+
* VS Code 的 handleRequest/handleUpgrade,并补齐 code-server 原先负责的少量 HTTP 面:
|
|
6
|
+
* /healthz 就绪探针(host 轮询;也回传最近一次 upgrade 路径,便于排障)
|
|
7
|
+
* /manifest.json PWA manifest(VS Code server 不提供)
|
|
8
|
+
* /_static/* 浏览器静态资源(favicon / PWA 图标 / serviceWorker.js)
|
|
9
|
+
* /proxy/:port/… 转发端口 HTTP 代理(Ports 面板;WS 版仅在 loopback 模式可用)
|
|
10
|
+
*
|
|
11
|
+
* 为什么是独立进程:VS Code 的 server 会改进程全局(win32 下 import 即 chdir、覆盖
|
|
12
|
+
* Error.stackTraceLimit、注册 SIGPIPE、patch Module._resolveLookupPaths、多处 process.exit),
|
|
13
|
+
* 且 node-pty/sqlite 崩溃时必须只带走 IDE,不能带走 DSH host。
|
|
14
|
+
*
|
|
15
|
+
* 用法(由 lib/index.js 调用,不面向用户):
|
|
16
|
+
* node lib/launcher.mjs --tree <VS Code 树根> --user-data-dir <dir> --extensions-dir <dir> \
|
|
17
|
+
* (--port <n> [--host 127.0.0.1] | --pipe <\\.\pipe\name|unix socket>) \
|
|
18
|
+
* [--parent-pid <pid>] [--locale zh-cn]
|
|
19
|
+
*
|
|
20
|
+
* 就绪信号:stdout 打印 `dshcs-ready <productPath> <mode> <addr>`。
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import { createServer as createHttpServer, request as httpRequest } from 'node:http';
|
|
24
|
+
import { createReadStream, existsSync, mkdirSync, readFileSync, statSync } from 'node:fs';
|
|
25
|
+
import { connect } from 'node:net';
|
|
26
|
+
import { dirname, extname, join, normalize, resolve, sep } from 'node:path';
|
|
27
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
28
|
+
|
|
29
|
+
const HERE = dirname(fileURLToPath(import.meta.url));
|
|
30
|
+
const PACKAGE_ROOT = resolve(HERE, '..');
|
|
31
|
+
|
|
32
|
+
// ---------------------------------------------------------------- 参数
|
|
33
|
+
|
|
34
|
+
function parseArgs(argv) {
|
|
35
|
+
const out = {
|
|
36
|
+
tree: process.env.DSHCS_VS_ROOT ?? null,
|
|
37
|
+
userDataDir: null,
|
|
38
|
+
extensionsDir: null,
|
|
39
|
+
host: '127.0.0.1',
|
|
40
|
+
port: null,
|
|
41
|
+
pipe: null,
|
|
42
|
+
parentPid: null,
|
|
43
|
+
locale: null,
|
|
44
|
+
disableProxy: false,
|
|
45
|
+
};
|
|
46
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
47
|
+
const a = argv[i];
|
|
48
|
+
if (a === '--tree') out.tree = argv[++i];
|
|
49
|
+
else if (a === '--user-data-dir') out.userDataDir = argv[++i];
|
|
50
|
+
else if (a === '--extensions-dir') out.extensionsDir = argv[++i];
|
|
51
|
+
else if (a === '--host') out.host = argv[++i];
|
|
52
|
+
else if (a === '--port') out.port = Number(argv[++i]);
|
|
53
|
+
else if (a === '--pipe') out.pipe = argv[++i];
|
|
54
|
+
else if (a === '--parent-pid') out.parentPid = Number(argv[++i]);
|
|
55
|
+
else if (a === '--locale') out.locale = argv[++i];
|
|
56
|
+
else if (a === '--disable-proxy') out.disableProxy = true;
|
|
57
|
+
}
|
|
58
|
+
return out;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const args = parseArgs(process.argv.slice(2));
|
|
62
|
+
const log = (...parts) => console.log('[dshcs-launcher]', ...parts);
|
|
63
|
+
const fail = (message) => { console.error('[dshcs-launcher] FATAL', message); process.exit(2); };
|
|
64
|
+
|
|
65
|
+
if (args.tree === null) fail('缺少 --tree(或环境变量 DSHCS_VS_ROOT)');
|
|
66
|
+
const tree = resolve(args.tree);
|
|
67
|
+
const serverMain = join(tree, 'lib', 'vscode', 'out', 'server-main.js');
|
|
68
|
+
if (!existsSync(serverMain)) fail(`不是一棵 VS Code 树(缺少 ${serverMain})`);
|
|
69
|
+
if (args.pipe === null && !Number.isFinite(args.port)) fail('必须给 --port 或 --pipe');
|
|
70
|
+
|
|
71
|
+
const userDataDir = resolve(args.userDataDir ?? join(PACKAGE_ROOT, '.dshcs-data', 'user-data'));
|
|
72
|
+
const extensionsDir = resolve(args.extensionsDir ?? join(userDataDir, '..', 'extensions'));
|
|
73
|
+
mkdirSync(userDataDir, { recursive: true });
|
|
74
|
+
mkdirSync(extensionsDir, { recursive: true });
|
|
75
|
+
|
|
76
|
+
const product = (() => {
|
|
77
|
+
try { return JSON.parse(readFileSync(join(tree, 'lib', 'vscode', 'product.json'), 'utf8')); } catch { return {}; }
|
|
78
|
+
})();
|
|
79
|
+
const productPath = `${product.quality ?? 'oss'}-${product.commit ?? 'dev'}`;
|
|
80
|
+
|
|
81
|
+
// ---------------------------------------------------------------- 进程护栏(必须 import 前)
|
|
82
|
+
|
|
83
|
+
process.env.CODE_SERVER_PARENT_PID ??= String(process.pid);
|
|
84
|
+
process.env.VSCODE_HANDLES_SIGPIPE ??= '1';
|
|
85
|
+
process.env.VSCODE_CWD ??= process.cwd();
|
|
86
|
+
|
|
87
|
+
let vsServer = null;
|
|
88
|
+
const recentUpgrades = [];
|
|
89
|
+
|
|
90
|
+
async function loadVscodeServer() {
|
|
91
|
+
const cwdBefore = process.cwd();
|
|
92
|
+
const mod = await import(pathToFileURL(serverMain).href);
|
|
93
|
+
// win32 下 server-main 顶层 DB() 会 chdir 到 dirname(process.execPath),立即复位
|
|
94
|
+
try { if (process.cwd() !== cwdBefore) process.chdir(cwdBefore); } catch { /* ignore */ }
|
|
95
|
+
const serverModule = await mod.loadCodeWithNls();
|
|
96
|
+
const codeArgs = {
|
|
97
|
+
auth: 'none',
|
|
98
|
+
'user-data-dir': userDataDir,
|
|
99
|
+
'extensions-dir': extensionsDir,
|
|
100
|
+
'accept-server-license-terms': true,
|
|
101
|
+
compatibility: '1.64',
|
|
102
|
+
'without-connection-token': true,
|
|
103
|
+
'disable-telemetry': true,
|
|
104
|
+
'disable-update-check': true,
|
|
105
|
+
_: [],
|
|
106
|
+
};
|
|
107
|
+
if (args.locale !== null) codeArgs.locale = args.locale;
|
|
108
|
+
return serverModule.createServer(null, codeArgs);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// ---------------------------------------------------------------- 静态资源(/_static/*)
|
|
112
|
+
|
|
113
|
+
const MIME = {
|
|
114
|
+
'.svg': 'image/svg+xml; charset=utf-8',
|
|
115
|
+
'.ico': 'image/x-icon',
|
|
116
|
+
'.png': 'image/png',
|
|
117
|
+
'.jpg': 'image/jpeg',
|
|
118
|
+
'.js': 'text/javascript; charset=utf-8',
|
|
119
|
+
'.css': 'text/css; charset=utf-8',
|
|
120
|
+
'.json': 'application/json; charset=utf-8',
|
|
121
|
+
'.txt': 'text/plain; charset=utf-8',
|
|
122
|
+
'.webmanifest': 'application/manifest+json',
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
function serveTreeStatic(urlPath, res) {
|
|
126
|
+
const rel = decodeURIComponent(urlPath.replace(/^\/_static\/?/, ''));
|
|
127
|
+
const full = normalize(join(tree, rel));
|
|
128
|
+
if (full !== tree && !full.startsWith(tree + sep)) { res.writeHead(403); res.end('forbidden'); return; }
|
|
129
|
+
let stat;
|
|
130
|
+
try { stat = statSync(full); } catch { res.writeHead(404); res.end(); return; }
|
|
131
|
+
if (!stat.isFile()) { res.writeHead(404); res.end(); return; }
|
|
132
|
+
const headers = {
|
|
133
|
+
'content-type': MIME[extname(full).toLowerCase()] ?? 'application/octet-stream',
|
|
134
|
+
'cache-control': 'public, max-age=3600',
|
|
135
|
+
};
|
|
136
|
+
if (full.endsWith('serviceWorker.js')) headers['service-worker-allowed'] = '/';
|
|
137
|
+
res.writeHead(200, headers);
|
|
138
|
+
createReadStream(full).pipe(res);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function manifestBody() {
|
|
142
|
+
return JSON.stringify({
|
|
143
|
+
name: product.nameShort ?? 'code-server',
|
|
144
|
+
short_name: product.nameShort ?? 'code-server',
|
|
145
|
+
start_url: '.',
|
|
146
|
+
display: 'fullscreen',
|
|
147
|
+
display_override: ['window-controls-overlay'],
|
|
148
|
+
description: 'Run Code on a remote server.',
|
|
149
|
+
icons: [192, 512].flatMap((size) => ([
|
|
150
|
+
{ src: `./_static/src/browser/media/pwa-icon-${size}.png`, type: 'image/png', sizes: `${size}x${size}`, purpose: 'any' },
|
|
151
|
+
{ src: `./_static/src/browser/media/pwa-icon-maskable-${size}.png`, type: 'image/png', sizes: `${size}x${size}`, purpose: 'maskable' },
|
|
152
|
+
])),
|
|
153
|
+
}, null, 2);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// ---------------------------------------------------------------- 转发端口代理(/proxy/:port、/absproxy/:port)
|
|
157
|
+
|
|
158
|
+
const PROXY_RE = /^\/(abs)?proxy\/(\d{1,5})(\/.*)?$/;
|
|
159
|
+
|
|
160
|
+
function proxyTarget(url) {
|
|
161
|
+
const m = PROXY_RE.exec(new URL(url, 'http://x').pathname);
|
|
162
|
+
if (m === null) return null;
|
|
163
|
+
const port = Number(m[2]);
|
|
164
|
+
if (!Number.isInteger(port) || port <= 0 || port > 65535) return null;
|
|
165
|
+
const rest = m[3] ?? '/';
|
|
166
|
+
const search = new URL(url, 'http://x').search;
|
|
167
|
+
return { port, path: m[1] === 'abs' ? `${rest}${search}` : `${rest}${search}` };
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function handleProxy(req, res, target) {
|
|
171
|
+
const upstream = httpRequest({
|
|
172
|
+
host: '127.0.0.1',
|
|
173
|
+
port: target.port,
|
|
174
|
+
method: req.method,
|
|
175
|
+
path: target.path,
|
|
176
|
+
headers: stripHopHeaders(req.headers),
|
|
177
|
+
}, (upstreamRes) => {
|
|
178
|
+
res.writeHead(upstreamRes.statusCode ?? 502, upstreamRes.headers);
|
|
179
|
+
upstreamRes.pipe(res);
|
|
180
|
+
});
|
|
181
|
+
upstream.on('error', (error) => {
|
|
182
|
+
log(`proxy ${target.port} failed: ${error.message}`);
|
|
183
|
+
if (!res.headersSent) res.writeHead(502, { 'content-type': 'text/plain; charset=utf-8' });
|
|
184
|
+
res.end(`proxy error: ${error.message}`);
|
|
185
|
+
});
|
|
186
|
+
req.pipe(upstream);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function stripHopHeaders(headers) {
|
|
190
|
+
const out = { ...headers };
|
|
191
|
+
delete out.connection;
|
|
192
|
+
delete out['proxy-connection'];
|
|
193
|
+
return out;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function handleProxyUpgrade(req, socket, head, target) {
|
|
197
|
+
const upstream = connect({ host: '127.0.0.1', port: target.port }, () => {
|
|
198
|
+
const lines = [`GET ${target.path} HTTP/1.1`];
|
|
199
|
+
for (let i = 0; i < req.rawHeaders.length; i += 2) lines.push(`${req.rawHeaders[i]}: ${req.rawHeaders[i + 1]}`);
|
|
200
|
+
upstream.write(`${lines.join('\r\n')}\r\n\r\n`);
|
|
201
|
+
if (head.length > 0) upstream.write(head);
|
|
202
|
+
upstream.pipe(socket);
|
|
203
|
+
socket.pipe(upstream);
|
|
204
|
+
});
|
|
205
|
+
upstream.on('error', (error) => { log(`proxy ws ${target.port} failed: ${error.message}`); socket.destroy(); });
|
|
206
|
+
socket.on('error', () => upstream.destroy());
|
|
207
|
+
socket.on('close', () => upstream.destroy());
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// ---------------------------------------------------------------- 跨源防护(等价 code-server 的 ensureOrigin)
|
|
211
|
+
|
|
212
|
+
/** 取请求 Host:优先 `Forwarded: host=`、其次 `X-Forwarded-Host`(取第一个)、最后 `Host`。
|
|
213
|
+
* trim + 小写,与 code-server 的 getHost() 同语义(反向代理未透传 Host 时返回 undefined)。 */
|
|
214
|
+
function getHostHeader(req) {
|
|
215
|
+
const first = (name) => {
|
|
216
|
+
const value = req.headers[name];
|
|
217
|
+
return Array.isArray(value) ? value[0] : value;
|
|
218
|
+
};
|
|
219
|
+
const forwarded = first('forwarded');
|
|
220
|
+
if (forwarded !== undefined && forwarded !== '') {
|
|
221
|
+
for (const part of forwarded.split(/[;,]/)) {
|
|
222
|
+
const eq = part.indexOf('=');
|
|
223
|
+
if (eq < 0) continue;
|
|
224
|
+
const key = part.slice(0, eq).trim().toLowerCase();
|
|
225
|
+
const value = part.slice(eq + 1).trim();
|
|
226
|
+
if (key === 'host' && value !== '') return value.toLowerCase();
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
const xHost = first('x-forwarded-host');
|
|
230
|
+
if (xHost !== undefined && xHost !== '') {
|
|
231
|
+
const head = xHost.split(',')[0];
|
|
232
|
+
if (head !== undefined && head.trim() !== '') return head.trim().toLowerCase();
|
|
233
|
+
}
|
|
234
|
+
const host = first('host');
|
|
235
|
+
return host !== undefined && host !== '' ? host.trim().toLowerCase() : undefined;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** code-server `authenticateOrigin()` 的等价物:带 Origin 的请求(浏览器)其 host 必须等于 Host;
|
|
239
|
+
* 缺 Origin(非浏览器,如本地工具/测试)放行。code-server 另外支持 `--trusted-origins` /
|
|
240
|
+
* `--proxy-domain` 通配,本插件没有这两个概念,故不实现。
|
|
241
|
+
* 为什么必须有:VS Code 的 handleUpgrade 不校验来源,而 IDE 是 auth=none —— 缺了这道检查,
|
|
242
|
+
* 本机任意浏览器页面都能开 ws://127.0.0.1:<port>/stable-<commit> 直接驱动 IDE。
|
|
243
|
+
* (dsh 模式下请求来自 DSH 自己的路由并已过 requestRejection,Origin/Host 天然一致。) */
|
|
244
|
+
function originAllowed(req) {
|
|
245
|
+
const raw = req.headers.origin;
|
|
246
|
+
const originRaw = Array.isArray(raw) ? raw[0] : raw;
|
|
247
|
+
if (originRaw === undefined || originRaw === '') return true;
|
|
248
|
+
let origin;
|
|
249
|
+
try {
|
|
250
|
+
origin = new URL(originRaw).host.trim().toLowerCase();
|
|
251
|
+
} catch {
|
|
252
|
+
return false;
|
|
253
|
+
}
|
|
254
|
+
if (origin === '') return false;
|
|
255
|
+
const host = getHostHeader(req);
|
|
256
|
+
if (host === undefined) return false;
|
|
257
|
+
return host === origin;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
// ---------------------------------------------------------------- HTTP / WS 分发
|
|
261
|
+
|
|
262
|
+
const server = createHttpServer((req, res) => {
|
|
263
|
+
const url = req.url ?? '/';
|
|
264
|
+
if (url === '/healthz') {
|
|
265
|
+
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
|
|
266
|
+
res.end(JSON.stringify({
|
|
267
|
+
ok: true,
|
|
268
|
+
productPath,
|
|
269
|
+
pid: process.pid,
|
|
270
|
+
mode: args.pipe === null ? 'tcp' : 'pipe',
|
|
271
|
+
recentUpgrades: recentUpgrades.slice(-3),
|
|
272
|
+
}));
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
275
|
+
if (url === '/manifest.json') {
|
|
276
|
+
res.writeHead(200, { 'content-type': 'application/manifest+json; charset=utf-8' });
|
|
277
|
+
res.end(manifestBody());
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
280
|
+
if (url.startsWith('/_static/')) { serveTreeStatic(url, res); return; }
|
|
281
|
+
if (!args.disableProxy) {
|
|
282
|
+
const target = proxyTarget(url);
|
|
283
|
+
if (target !== null) { handleProxy(req, res, target); return; }
|
|
284
|
+
}
|
|
285
|
+
Promise.resolve(vsServer.handleRequest(req, res)).catch((error) => {
|
|
286
|
+
log(`handleRequest failed: ${error && error.stack ? error.stack : error}`);
|
|
287
|
+
if (!res.headersSent) res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' });
|
|
288
|
+
if (!res.writableEnded) res.end('internal error');
|
|
289
|
+
});
|
|
290
|
+
});
|
|
291
|
+
|
|
292
|
+
server.on('upgrade', (req, socket, head) => {
|
|
293
|
+
const url = req.url ?? '/';
|
|
294
|
+
recentUpgrades.push(url);
|
|
295
|
+
if (recentUpgrades.length > 10) recentUpgrades.shift();
|
|
296
|
+
// 跨源防护(与 code-server 一致:只卡 upgrade,HTTP 侧 VS Code 仅接受 GET 且状态变更都走 WS)
|
|
297
|
+
if (!originAllowed(req)) {
|
|
298
|
+
log(`拒绝跨源 WebSocket:origin=${req.headers.origin} host=${req.headers.host ?? '-'} url=${url}`);
|
|
299
|
+
socket.end('HTTP/1.1 403 Forbidden\r\nConnection: close\r\nContent-Length: 0\r\n\r\n');
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
if (!args.disableProxy) {
|
|
303
|
+
const target = proxyTarget(url);
|
|
304
|
+
if (target !== null) { handleProxyUpgrade(req, socket, head, target); return; }
|
|
305
|
+
}
|
|
306
|
+
socket.pause();
|
|
307
|
+
req.ws = socket;
|
|
308
|
+
req.head = head;
|
|
309
|
+
try {
|
|
310
|
+
vsServer.handleUpgrade(req, socket);
|
|
311
|
+
} catch (error) {
|
|
312
|
+
log(`handleUpgrade threw: ${error && error.message ? error.message : error}`);
|
|
313
|
+
socket.destroy();
|
|
314
|
+
}
|
|
315
|
+
socket.resume();
|
|
316
|
+
});
|
|
317
|
+
|
|
318
|
+
// ---------------------------------------------------------------- 生命周期
|
|
319
|
+
|
|
320
|
+
let shuttingDown = false;
|
|
321
|
+
async function shutdown(reason, code = 0) {
|
|
322
|
+
if (shuttingDown) return;
|
|
323
|
+
shuttingDown = true;
|
|
324
|
+
log(`shutting down (${reason})`);
|
|
325
|
+
try { await vsServer?.dispose?.(); } catch (error) { log(`dispose failed: ${error && error.message}`); }
|
|
326
|
+
const done = () => process.exit(code);
|
|
327
|
+
try { server.close(done); } catch { done(); }
|
|
328
|
+
setTimeout(() => process.exit(code), 3000).unref();
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
for (const sig of ['SIGINT', 'SIGTERM']) process.on(sig, () => { void shutdown(sig); });
|
|
332
|
+
|
|
333
|
+
// 父进程(DSH host)消失 → 自行退出,避免留下孤儿 IDE 进程
|
|
334
|
+
if (Number.isFinite(args.parentPid) && args.parentPid > 0) {
|
|
335
|
+
const parentPid = args.parentPid;
|
|
336
|
+
const timer = setInterval(() => {
|
|
337
|
+
try {
|
|
338
|
+
process.kill(parentPid, 0);
|
|
339
|
+
} catch (error) {
|
|
340
|
+
if (error && error.code === 'ESRCH') void shutdown(`parent ${parentPid} gone`);
|
|
341
|
+
}
|
|
342
|
+
}, 5000);
|
|
343
|
+
timer.unref();
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
// ---------------------------------------------------------------- 启动
|
|
347
|
+
|
|
348
|
+
try {
|
|
349
|
+
vsServer = await loadVscodeServer();
|
|
350
|
+
} catch (error) {
|
|
351
|
+
fail(`加载 VS Code server 失败: ${error && error.stack ? error.stack : error}`);
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
const listenTarget = args.pipe === null ? { host: args.host, port: args.port } : args.pipe;
|
|
355
|
+
server.on('error', (error) => { fail(`监听失败(${JSON.stringify(listenTarget)}): ${error.message}`); });
|
|
356
|
+
|
|
357
|
+
server.listen(listenTarget, () => {
|
|
358
|
+
const addr = server.address();
|
|
359
|
+
const shown = typeof addr === 'string' ? addr : `${addr.address}:${addr.port}`;
|
|
360
|
+
log(`listening on ${shown} (tree=${tree})`);
|
|
361
|
+
log(`user-data-dir=${userDataDir} extensions-dir=${extensionsDir}`);
|
|
362
|
+
console.log(`dshcs-ready ${productPath} ${args.pipe === null ? 'tcp' : 'pipe'} ${shown}`);
|
|
363
|
+
});
|
|
364
|
+
|
|
365
|
+
// 兜底:未捕获异常不应静默留下半死进程
|
|
366
|
+
process.on('uncaughtException', (error) => {
|
|
367
|
+
console.error('[dshcs-launcher] uncaughtException', error && error.stack ? error.stack : error);
|
|
368
|
+
void shutdown('uncaughtException', 1);
|
|
369
|
+
});
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* lib/serve-dsh.mjs — 把 VS Code server 挂到 DSH 自身 HTTP 端口上的两段式注册(serve=dsh)。
|
|
3
|
+
*
|
|
4
|
+
* ctx.webServer.register({ kind: 'prefix', path: '/code-server', handler }) ← HTTP
|
|
5
|
+
* ctx.webServer.registerUpgrade({ path: '/code-server/<productPath>', handler }) ← WebSocket(精确匹配)
|
|
6
|
+
*
|
|
7
|
+
* 两条路径都必须先过 ctx.connection.requestRejection():DSH 的 webServer 本身不做任何校验,
|
|
8
|
+
* 防护是逐路由的(Host/Origin fence + 浏览器 cookie 认证),缺了它 IDE 会成为源站上唯一的无认证面。
|
|
9
|
+
*
|
|
10
|
+
* 转发策略(Phase 0 实测):**剥掉挂载前缀**后转给 launcher 的命名管道 —— VS Code 侧保持根挂载,
|
|
11
|
+
* 与今天已验证的配置完全一致;客户端渲染出的资源引用全是相对路径,浏览器按 /code-server/ 解析,
|
|
12
|
+
* 因此同一套 prefix 路由就能覆盖 HTML、静态资源、vscode-remote-resource 与 /_static/*。
|
|
13
|
+
*
|
|
14
|
+
* 已知退化:转发端口(/proxy/:port)的 WebSocket 无法用精确升级路由覆盖(端口号在路径里),
|
|
15
|
+
* 需要 DSH 上游提供 prefix upgrade;HTTP 转发端口不受影响。
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import { request as httpRequest } from 'node:http';
|
|
19
|
+
import { connect } from 'node:net';
|
|
20
|
+
|
|
21
|
+
export const MOUNT_PATH = '/code-server';
|
|
22
|
+
|
|
23
|
+
/** 前缀匹配(与 DSH webServer 的 prefix 语义一致:命中 p 与 p/<anything>)。 */
|
|
24
|
+
function matchesPrefix(pathname, prefix) {
|
|
25
|
+
return pathname === prefix || pathname.startsWith(`${prefix}/`);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** 把 /code-server/xxx 转成上游要的 /xxx(空则 '/'),保留 query。 */
|
|
29
|
+
function stripPrefix(url, prefix) {
|
|
30
|
+
const rest = url.slice(prefix.length);
|
|
31
|
+
return rest === '' ? '/' : rest;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function rejectionOf(connection, req) {
|
|
35
|
+
try {
|
|
36
|
+
return connection.requestRejection({ headers: req.headers }) ?? undefined;
|
|
37
|
+
} catch (error) {
|
|
38
|
+
return { error };
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** 转发目标的两种形态:命名管道(kind:'pipe')或回环 TCP(kind:'tcp')。
|
|
43
|
+
* 注意 http.request 用 socketPath、net.connect 用 path —— 两者键名不同,必须在这里翻译。 */
|
|
44
|
+
function httpOptions(target, extra) {
|
|
45
|
+
return target.kind === 'pipe'
|
|
46
|
+
? { socketPath: target.pipe, ...extra }
|
|
47
|
+
: { host: target.host, port: target.port, ...extra };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function connectTo(target, onConnect) {
|
|
51
|
+
return target.kind === 'pipe'
|
|
52
|
+
? connect({ path: target.pipe }, onConnect)
|
|
53
|
+
: connect({ host: target.host, port: target.port }, onConnect);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* 注册 IDE 的同源挂载点。
|
|
58
|
+
* @param {object} options
|
|
59
|
+
* @param {object} options.webServer - DSH webServer 服务(register / registerUpgrade)
|
|
60
|
+
* @param {object} options.connection - DSH connection 服务(requestRejection)
|
|
61
|
+
* @param {() => ({socketPath: string} | {host: string, port: number} | null)} options.getTarget
|
|
62
|
+
* 当前 launcher 的转发目标(命名管道为主;loopback TCP 用于测试/回退)
|
|
63
|
+
* @param {string} options.productPath - VS Code 客户端路径(quality-commit)
|
|
64
|
+
* @param {string} [options.mount] - 挂载前缀,默认 /code-server
|
|
65
|
+
* @param {(msg: string) => void} [options.log]
|
|
66
|
+
* @returns {{ disposers: (() => void)[], upgradePath: string }}
|
|
67
|
+
*/
|
|
68
|
+
export function mountOnWebServer({ webServer, connection, getTarget, productPath, mount = MOUNT_PATH, log = () => {} }) {
|
|
69
|
+
const upgradePath = `${mount}/${productPath}`;
|
|
70
|
+
const disposers = [];
|
|
71
|
+
|
|
72
|
+
/** 请求被 fence 拒绝时按 DSH 的约定回 401/403(upgrade 走裸 socket)。 */
|
|
73
|
+
function fence(req) {
|
|
74
|
+
const rejection = rejectionOf(connection, req);
|
|
75
|
+
if (rejection === undefined) return null;
|
|
76
|
+
if (typeof rejection === 'object' && rejection.error !== undefined) {
|
|
77
|
+
log(`requestRejection 抛错,按 403 处理: ${rejection.error?.message ?? rejection.error}`);
|
|
78
|
+
return 403;
|
|
79
|
+
}
|
|
80
|
+
return rejection;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
disposers.push(webServer.register({
|
|
84
|
+
kind: 'prefix',
|
|
85
|
+
path: mount,
|
|
86
|
+
handler: (req, res) => {
|
|
87
|
+
try {
|
|
88
|
+
const pathname = new URL(req.url ?? '/', 'http://x').pathname;
|
|
89
|
+
if (!matchesPrefix(pathname, mount)) { res.writeHead(404); res.end(); return; }
|
|
90
|
+
const status = fence(req);
|
|
91
|
+
if (status !== null) {
|
|
92
|
+
res.writeHead(status, { 'content-type': 'text/plain; charset=utf-8' });
|
|
93
|
+
res.end(status === 401 ? 'unauthorized\n' : 'forbidden\n');
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
const target = getTarget();
|
|
97
|
+
if (target === null) {
|
|
98
|
+
res.writeHead(503, { 'content-type': 'text/plain; charset=utf-8' });
|
|
99
|
+
res.end('code-server 未启动\n');
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
const upstream = httpRequest(httpOptions(target, {
|
|
103
|
+
method: req.method,
|
|
104
|
+
path: stripPrefix(req.url ?? '/', mount),
|
|
105
|
+
headers: req.headers,
|
|
106
|
+
}), (upstreamRes) => {
|
|
107
|
+
res.writeHead(upstreamRes.statusCode ?? 502, upstreamRes.headers);
|
|
108
|
+
upstreamRes.pipe(res);
|
|
109
|
+
});
|
|
110
|
+
upstream.on('error', (error) => {
|
|
111
|
+
log(`HTTP 转发失败(${req.method} ${req.url}): ${error.message}`);
|
|
112
|
+
if (!res.headersSent) res.writeHead(502, { 'content-type': 'text/plain; charset=utf-8' });
|
|
113
|
+
if (!res.writableEnded) res.end('code-server 不可达\n');
|
|
114
|
+
});
|
|
115
|
+
req.on('aborted', () => upstream.destroy());
|
|
116
|
+
req.pipe(upstream);
|
|
117
|
+
} catch (error) {
|
|
118
|
+
// 路由回调里的异常绝不能冒泡到 DSH 的 webServer(会变成未捕获异常)
|
|
119
|
+
log(`HTTP 挂载点异常(${req.method} ${req.url}): ${error && error.stack ? error.stack : error}`);
|
|
120
|
+
if (!res.headersSent) res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' });
|
|
121
|
+
if (!res.writableEnded) res.end('code-server 挂载点异常\n');
|
|
122
|
+
}
|
|
123
|
+
},
|
|
124
|
+
}));
|
|
125
|
+
|
|
126
|
+
disposers.push(webServer.registerUpgrade({
|
|
127
|
+
path: upgradePath,
|
|
128
|
+
handler: (req, socket, head) => {
|
|
129
|
+
try {
|
|
130
|
+
const status = fence(req);
|
|
131
|
+
if (status !== null) {
|
|
132
|
+
socket.end(`HTTP/1.1 ${status} ${status === 401 ? 'Unauthorized' : 'Forbidden'}\r\nConnection: close\r\n\r\n`);
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
const target = getTarget();
|
|
136
|
+
if (target === null) { socket.destroy(); return; }
|
|
137
|
+
const upstream = connectTo(target, () => {
|
|
138
|
+
const lines = [`GET ${stripPrefix(req.url ?? '/', mount)} HTTP/1.1`];
|
|
139
|
+
for (let i = 0; i < req.rawHeaders.length; i += 2) {
|
|
140
|
+
lines.push(`${req.rawHeaders[i]}: ${req.rawHeaders[i + 1]}`);
|
|
141
|
+
}
|
|
142
|
+
upstream.write(`${lines.join('\r\n')}\r\n\r\n`);
|
|
143
|
+
if (head !== undefined && head.length > 0) upstream.write(head);
|
|
144
|
+
upstream.pipe(socket);
|
|
145
|
+
socket.pipe(upstream);
|
|
146
|
+
});
|
|
147
|
+
upstream.on('error', (error) => { log(`WS 转发失败(${req.url}): ${error.message}`); socket.destroy(); });
|
|
148
|
+
socket.on('error', () => upstream.destroy());
|
|
149
|
+
socket.on('close', () => upstream.destroy());
|
|
150
|
+
} catch (error) {
|
|
151
|
+
log(`WS 挂载点异常(${req.url}): ${error && error.stack ? error.stack : error}`);
|
|
152
|
+
socket.destroy();
|
|
153
|
+
}
|
|
154
|
+
},
|
|
155
|
+
}));
|
|
156
|
+
|
|
157
|
+
log(`已挂载 ${mount}/ (HTTP prefix)+ ${upgradePath} (WS exact)`);
|
|
158
|
+
return {
|
|
159
|
+
upgradePath,
|
|
160
|
+
disposers,
|
|
161
|
+
};
|
|
162
|
+
}
|