dsh-remote-go 0.2.0 → 0.3.0

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.
Files changed (134) hide show
  1. package/README.md +11 -3
  2. package/{client.js → dist/client.js} +7710 -8182
  3. package/dist/index.js +4 -0
  4. package/dist/src/admission.js +46 -0
  5. package/dist/src/api.js +442 -0
  6. package/dist/src/atomic-json.js +235 -0
  7. package/dist/src/bootstrap.js +106 -0
  8. package/dist/src/connect/attach.js +43 -0
  9. package/dist/src/connect/bootstrap.js +14 -0
  10. package/dist/src/connect/failures.js +44 -0
  11. package/dist/src/connect/guards.js +31 -0
  12. package/dist/src/connect/launch.js +80 -0
  13. package/dist/src/connect/links.js +70 -0
  14. package/dist/src/connect/ownership.js +220 -0
  15. package/dist/src/connect/pipeline.js +473 -0
  16. package/dist/src/connect/reattach.js +215 -0
  17. package/dist/src/connect/registry.js +11 -0
  18. package/dist/src/connect/repair.js +126 -0
  19. package/dist/src/connect/restart.js +316 -0
  20. package/dist/src/connect/stop.js +198 -0
  21. package/dist/src/connect/transport.js +109 -0
  22. package/dist/src/connect/verify.js +39 -0
  23. package/dist/src/connect/watchdog.js +76 -0
  24. package/dist/src/connect-log.js +162 -0
  25. package/dist/src/connect-progress.js +142 -0
  26. package/{src → dist/src}/constants.js +30 -56
  27. package/dist/src/context.js +117 -0
  28. package/dist/src/diagnostics.js +102 -0
  29. package/dist/src/download-jobs.js +230 -0
  30. package/dist/src/errors.js +243 -0
  31. package/dist/src/events.js +390 -0
  32. package/dist/src/host-lifecycle.js +504 -0
  33. package/dist/src/host-registry.js +232 -0
  34. package/dist/src/host-runtime.js +86 -0
  35. package/dist/src/host-view.js +75 -0
  36. package/dist/src/index.js +216 -0
  37. package/dist/src/kernel-adapter.js +434 -0
  38. package/dist/src/key-files.js +52 -0
  39. package/dist/src/known-hosts.js +125 -0
  40. package/dist/src/layout.js +43 -0
  41. package/dist/src/local-download.js +380 -0
  42. package/dist/src/local-ssh.js +30 -0
  43. package/dist/src/local-version.js +101 -0
  44. package/dist/src/node/download.js +160 -0
  45. package/dist/src/node-runtime.js +346 -0
  46. package/dist/src/probe.js +96 -0
  47. package/dist/src/prompts.js +270 -0
  48. package/dist/src/proxy/cookies.js +136 -0
  49. package/dist/src/proxy/headers.js +262 -0
  50. package/dist/src/proxy/http.js +142 -0
  51. package/dist/src/proxy/index.js +135 -0
  52. package/dist/src/proxy/limits.js +8 -0
  53. package/dist/src/proxy/routes.js +39 -0
  54. package/dist/src/proxy/upgrade.js +175 -0
  55. package/dist/src/redact.js +104 -0
  56. package/dist/src/remote-files.js +72 -0
  57. package/dist/src/remote-path.js +123 -0
  58. package/dist/src/remote-proc.js +339 -0
  59. package/dist/src/remote-web/registry.js +147 -0
  60. package/dist/src/remote-web/resolve.js +310 -0
  61. package/dist/src/remote-web/start.js +227 -0
  62. package/dist/src/remote-web/stop.js +93 -0
  63. package/dist/src/request-trust.js +87 -0
  64. package/dist/src/runtime/dispatch.js +310 -0
  65. package/dist/src/runtime/effects.js +91 -0
  66. package/dist/src/runtime/events.js +35 -0
  67. package/dist/src/runtime/fsm.js +120 -0
  68. package/dist/src/runtime/rules.js +565 -0
  69. package/dist/src/secrets.js +142 -0
  70. package/dist/src/service.js +406 -0
  71. package/dist/src/settings.js +144 -0
  72. package/dist/src/ssh-config.js +276 -0
  73. package/dist/src/ssh-failures.js +122 -0
  74. package/dist/src/ssh-port.js +4 -0
  75. package/dist/src/ssh-sftp.js +297 -0
  76. package/dist/src/ssh.js +477 -0
  77. package/dist/src/store.js +191 -0
  78. package/dist/src/tool-shared.js +181 -0
  79. package/dist/src/tools-exec-policy.js +167 -0
  80. package/dist/src/tools-exec.js +371 -0
  81. package/dist/src/tools-report.js +424 -0
  82. package/dist/src/tools.js +411 -0
  83. package/dist/src/tunnel.js +129 -0
  84. package/dist/src/util.js +149 -0
  85. package/dist/src/version.js +114 -0
  86. package/dist/src/watchdog-bus.js +29 -0
  87. package/dist/src/watchdog.js +156 -0
  88. package/index.js +5 -4
  89. package/locale/en.json +1 -1
  90. package/locale/zh.json +1 -1
  91. package/package.json +37 -19
  92. package/src/admission.js +0 -43
  93. package/src/api.js +0 -536
  94. package/src/atomic-json.js +0 -225
  95. package/src/bootstrap.js +0 -113
  96. package/src/connect-log.js +0 -176
  97. package/src/connect-pipeline.js +0 -1900
  98. package/src/connect-progress.js +0 -155
  99. package/src/diagnostics.js +0 -160
  100. package/src/download-jobs.js +0 -234
  101. package/src/errors.js +0 -412
  102. package/src/host-lifecycle.js +0 -604
  103. package/src/host-registry.js +0 -217
  104. package/src/host-runtime.js +0 -127
  105. package/src/host-view.js +0 -75
  106. package/src/index.js +0 -206
  107. package/src/key-files.js +0 -54
  108. package/src/known-hosts.js +0 -133
  109. package/src/layout.js +0 -53
  110. package/src/local-download.js +0 -381
  111. package/src/local-ssh.js +0 -27
  112. package/src/local-version.js +0 -88
  113. package/src/node-runtime.js +0 -521
  114. package/src/probe.js +0 -101
  115. package/src/prompts.js +0 -229
  116. package/src/redact.js +0 -68
  117. package/src/remote-files.js +0 -71
  118. package/src/remote-path.js +0 -137
  119. package/src/remote-proc.js +0 -343
  120. package/src/remote-proxy.js +0 -815
  121. package/src/remote-web.js +0 -751
  122. package/src/request-trust.js +0 -89
  123. package/src/secrets.js +0 -109
  124. package/src/service.js +0 -459
  125. package/src/settings.js +0 -163
  126. package/src/ssh-config.js +0 -271
  127. package/src/ssh.js +0 -731
  128. package/src/store.js +0 -193
  129. package/src/tools.js +0 -386
  130. package/src/tunnel.js +0 -132
  131. package/src/util.js +0 -153
  132. package/src/version.js +0 -103
  133. package/src/webapp.js +0 -43
  134. /package/{vendor → dist/vendor}/ssh2.bundle.cjs +0 -0
@@ -0,0 +1,142 @@
1
+ /**
2
+ * The HTTP half of the same-origin proxy: admission, the local same-origin fence, view-path
3
+ * resolution, the upstream forward with its 30 s deadline, and the seven plain-text refusals.
4
+ */
5
+ import http from 'node:http';
6
+ import { trustedRequest } from '../request-trust.js';
7
+ import { storeCookies } from './cookies.js';
8
+ import { remoteOrigin, responseHeaders, upstreamHeaders } from './headers.js';
9
+ import { parseViewPath } from './routes.js';
10
+ /** One status line and a short body: every refusal this proxy answers with. */
11
+ function plain(res, status, text) {
12
+ const body = String(text);
13
+ try {
14
+ res.writeHead(status, {
15
+ 'content-type': 'text/plain; charset=utf-8',
16
+ 'cache-control': 'no-store',
17
+ 'content-length': Buffer.byteLength(body),
18
+ });
19
+ res.end(body);
20
+ }
21
+ catch {
22
+ // swallow-ok: the client may already have closed the response
23
+ }
24
+ }
25
+ /**
26
+ * Create the HTTP handler of one proxy activation.
27
+ *
28
+ * Every request under the view prefix is stripped of the prefix and forwarded to that host's
29
+ * loopback tunnel; a host that is not currently connected is a 404, and DSH's own admission plus
30
+ * the local same-origin fence decide whether the caller may use the seat at all.
31
+ */
32
+ export function createHttpHandler(rt) {
33
+ return function handle(req, res) {
34
+ if (rt.disposed()) {
35
+ plain(res, 503, 'proxy disposed');
36
+ return;
37
+ }
38
+ // DSH's own admission gate runs before anything this module decides: the proxy reaches a
39
+ // connected host's remote session (its cookie jar), so only an admitted caller may use it.
40
+ const rejection = rt.admit(req);
41
+ if (rejection !== undefined) {
42
+ plain(res, rejection, 'request rejected by DSH admission');
43
+ return;
44
+ }
45
+ const origin = rt.localOrigin();
46
+ if (origin === null) {
47
+ plain(res, 503, 'local origin is not ready');
48
+ return;
49
+ }
50
+ if (!trustedRequest(req, origin)) {
51
+ plain(res, 403, 'cross-site request rejected');
52
+ return;
53
+ }
54
+ let pathname;
55
+ let search;
56
+ try {
57
+ const url = new URL(req.url ?? '/', 'http://127.0.0.1');
58
+ pathname = url.pathname;
59
+ search = url.search;
60
+ }
61
+ catch {
62
+ plain(res, 400, 'bad request path');
63
+ return;
64
+ }
65
+ const parsed = parseViewPath(pathname);
66
+ if (parsed === null) {
67
+ plain(res, 404, 'unknown remote view');
68
+ return;
69
+ }
70
+ const target = rt.targetOf(parsed.hostId);
71
+ if (target === null) {
72
+ plain(res, 404, 'host is not connected');
73
+ return;
74
+ }
75
+ const jar = rt.jarFor(parsed.hostId, target);
76
+ const upstreamPath = parsed.path + search;
77
+ const headers = upstreamHeaders(req.rawHeaders, {
78
+ target,
79
+ localOrigin: origin.origin,
80
+ path: parsed.path,
81
+ jar,
82
+ });
83
+ // The remote is reached over a tunnel; a listener that accepts and never answers used to
84
+ // hang the local request forever. The deadline covers the wait for response headers only —
85
+ // once the response started, an idle stream (SSE, a large asset) is legitimate.
86
+ let answered = false;
87
+ let failed = false;
88
+ const upstream = http.request({
89
+ host: '127.0.0.1',
90
+ port: target.localPort,
91
+ path: upstreamPath,
92
+ method: req.method,
93
+ headers,
94
+ timeout: rt.upstreamTimeoutMs,
95
+ }, (response) => {
96
+ answered = true;
97
+ upstream.setTimeout(0);
98
+ storeCookies(jar, response.headers['set-cookie']);
99
+ try {
100
+ res.writeHead(response.statusCode ?? 502, responseHeaders(response.rawHeaders, {
101
+ hostId: parsed.hostId,
102
+ remoteOrigin: remoteOrigin(target),
103
+ }));
104
+ }
105
+ catch {
106
+ response.destroy();
107
+ return;
108
+ }
109
+ // A browser that leaves the page mid-load must not keep the tunneled response alive.
110
+ res.once('close', () => response.destroy());
111
+ response.pipe(res);
112
+ });
113
+ /**
114
+ * One failed upstream: report it once and answer 502 (or nothing, when the response has
115
+ * already started). Nothing from the failure reaches the log line: the emitter is
116
+ * request-driven, so CodeQL treats its error as user-controlled (log injection). The
117
+ * loopback port names the host to an operator, and the browser only ever sees the 502.
118
+ */
119
+ const upstreamFailed = () => {
120
+ if (failed)
121
+ return;
122
+ failed = true;
123
+ rt.logger.debug?.(`[dsh-remote-go] remote proxy upstream 127.0.0.1:${target.localPort} failed`);
124
+ plain(res, 502, 'remote UI is unreachable');
125
+ rt.reportUpstreamFailure(parsed.hostId);
126
+ };
127
+ upstream.on('timeout', () => {
128
+ if (answered)
129
+ return;
130
+ answered = true;
131
+ upstream.destroy();
132
+ upstreamFailed();
133
+ });
134
+ upstream.on('error', () => {
135
+ // A failure after the response started is still worth reporting (the Host confirms it
136
+ // with probes); `plain` is a no-op once the headers are out.
137
+ upstreamFailed();
138
+ });
139
+ req.once('aborted', () => upstream.destroy());
140
+ req.pipe(upstream);
141
+ };
142
+ }
@@ -0,0 +1,135 @@
1
+ import { REMOTE_VIEW_PREFIX } from '../constants.js';
2
+ import { createJarBook } from './cookies.js';
3
+ import { cookieHeader } from './cookies.js';
4
+ import { remoteAuthority } from './headers.js';
5
+ import { createHttpHandler } from './http.js';
6
+ import { UPSTREAM_TIMEOUT_MS } from './limits.js';
7
+ import { HOST_ID_PATTERN, upgradePath } from './routes.js';
8
+ import { createUpgradeHandler } from './upgrade.js';
9
+ /**
10
+ * Create the proxy. `resolveHost` is the single pivot: it returns the loopback target for one
11
+ * connected host (`{ localPort, remotePort }`) or null. Nothing else in this module knows how a
12
+ * tunnel was made.
13
+ */
14
+ export function createRemoteProxy(options) {
15
+ const logger = options.logger ?? console;
16
+ const webServer = options.webServer;
17
+ const getOrigin = options.getOrigin;
18
+ const resolveHost = options.resolveHost;
19
+ // Annotated because the default below must answer like the real gate: the kernel may not
20
+ // provide the Connection service at all, and a missing gate admits the request.
21
+ const admit = typeof options.admit === 'function' ? options.admit : () => undefined;
22
+ const onUpstreamError = options.onUpstreamError;
23
+ const upstreamTimeoutMs = Number.isSafeInteger(options.upstreamTimeoutMs) && options.upstreamTimeoutMs > 0
24
+ ? options.upstreamTimeoutMs
25
+ : UPSTREAM_TIMEOUT_MS;
26
+ const jars = createJarBook(remoteAuthority);
27
+ const upgrades = new Map();
28
+ const sockets = new Set();
29
+ let disposed = false;
30
+ /** Report one failed upstream without letting the reporter break the proxy. */
31
+ function reportUpstreamFailure(hostId) {
32
+ try {
33
+ onUpstreamError?.(hostId);
34
+ }
35
+ catch {
36
+ // swallow-ok: reporting only feeds the liveness confirmation, it must never fail a request
37
+ }
38
+ }
39
+ function localOrigin() {
40
+ try {
41
+ const origin = getOrigin();
42
+ return typeof origin === 'string' && origin !== '' ? new URL(origin) : null;
43
+ }
44
+ catch {
45
+ return null;
46
+ }
47
+ }
48
+ function targetOf(hostId) {
49
+ try {
50
+ const target = resolveHost(hostId);
51
+ return target && Number.isInteger(Number(target.localPort)) && Number(target.localPort) > 0 ? target : null;
52
+ }
53
+ catch {
54
+ return null;
55
+ }
56
+ }
57
+ /** The two handlers see exactly these operations, never this closure. */
58
+ const runtime = {
59
+ disposed: () => disposed,
60
+ logger,
61
+ admit,
62
+ localOrigin,
63
+ targetOf,
64
+ jarFor: (hostId, target) => jars.jarFor(hostId, target),
65
+ reportUpstreamFailure,
66
+ upstreamTimeoutMs,
67
+ };
68
+ const handle = createHttpHandler(runtime);
69
+ const handleUpgrade = createUpgradeHandler(runtime, {
70
+ add(socket) {
71
+ sockets.add(socket);
72
+ },
73
+ delete(socket) {
74
+ sockets.delete(socket);
75
+ },
76
+ });
77
+ /**
78
+ * Keep one upgrade route per configured host. Called on init and on every state change; a host
79
+ * that disappears loses its route and its cookies.
80
+ */
81
+ function sync(hostIds) {
82
+ if (disposed)
83
+ return;
84
+ const wanted = new Set((Array.isArray(hostIds) ? hostIds : []).filter((id) => HOST_ID_PATTERN.test(String(id))));
85
+ for (const [hostId, dispose] of upgrades) {
86
+ if (wanted.has(hostId))
87
+ continue;
88
+ dispose();
89
+ upgrades.delete(hostId);
90
+ jars.clear(hostId);
91
+ }
92
+ for (const hostId of wanted) {
93
+ if (upgrades.has(hostId))
94
+ continue;
95
+ try {
96
+ upgrades.set(hostId, webServer.registerUpgrade({
97
+ path: upgradePath(hostId),
98
+ handler: (req, socket, head) => handleUpgrade(hostId, req, socket, head),
99
+ }));
100
+ }
101
+ catch (error) {
102
+ logger.warn?.(`[dsh-remote-go] could not register the stream route for ${hostId}: ${error instanceof Error ? error.message : String(error)}`);
103
+ }
104
+ }
105
+ }
106
+ return {
107
+ prefix: REMOTE_VIEW_PREFIX,
108
+ /**
109
+ * The route registration path. The web server matches a prefix as `pathname === prefix ||
110
+ * pathname.startsWith(prefix + '/')`, so registering the trailing-slash seat prefix verbatim
111
+ * would never match a real view URL.
112
+ */
113
+ routePath: REMOTE_VIEW_PREFIX.replace(/\/$/, ''),
114
+ handle,
115
+ handleUpgrade,
116
+ sync,
117
+ /** One host's current cookie header, for diagnostics and tests. */
118
+ cookies(hostId) {
119
+ const jar = jars.get(hostId);
120
+ return jar === undefined ? '' : cookieHeader(jar, '/');
121
+ },
122
+ dispose() {
123
+ if (disposed)
124
+ return;
125
+ disposed = true;
126
+ for (const dispose of upgrades.values())
127
+ dispose();
128
+ upgrades.clear();
129
+ jars.clear();
130
+ for (const socket of sockets)
131
+ socket.destroy();
132
+ sockets.clear();
133
+ },
134
+ };
135
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The two ceilings one upstream connection is held to: how long it may take to answer, and how
3
+ * large a handshake response head may grow before it can no longer be a WebSocket upgrade.
4
+ */
5
+ /** How long the remote may take to accept a connection and answer; see `createRemoteProxy`. */
6
+ export const UPSTREAM_TIMEOUT_MS = 30_000;
7
+ /** A handshake response head larger than this is not a WebSocket upgrade; it is dropped. */
8
+ export const MAX_UPSTREAM_HEAD_BYTES = 64 * 1024;
@@ -0,0 +1,39 @@
1
+ /**
2
+ * The URL shapes of the same-origin proxy: which view path names which host, and the exact
3
+ * upgrade pathname one host's stream arrives on.
4
+ */
5
+ import { REMOTE_VIEW_PREFIX } from '../constants.js';
6
+ /** How long the remote web UI's own stream route is (the only upgrade a DSH web serves). */
7
+ const REMOTE_STREAM_PATH = '/api/remote.mux';
8
+ /** One host id, as the view prefix and the run registry spell it. */
9
+ export const HOST_ID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
10
+ /**
11
+ * Split `/dsh-remote-go/remote/<hostId>/<rest>` into its host and the upstream path.
12
+ * Returns null for anything that is not one well-formed view path (encoded slashes included).
13
+ * @param pathname - URL pathname; anything else is refused, so the guard stays.
14
+ */
15
+ export function parseViewPath(pathname) {
16
+ if (typeof pathname !== 'string' || !pathname.startsWith(REMOTE_VIEW_PREFIX))
17
+ return null;
18
+ const rest = pathname.slice(REMOTE_VIEW_PREFIX.length);
19
+ const slash = rest.indexOf('/');
20
+ const rawId = slash === -1 ? rest : rest.slice(0, slash);
21
+ let hostId;
22
+ try {
23
+ hostId = decodeURIComponent(rawId);
24
+ }
25
+ catch {
26
+ return null;
27
+ }
28
+ if (!HOST_ID_PATTERN.test(hostId))
29
+ return null;
30
+ // The seat is always `<prefix><hostId>/`: the bare id is not a page.
31
+ if (slash === -1)
32
+ return null;
33
+ const upstream = rest.slice(slash);
34
+ return { hostId, path: upstream === '' ? '/' : upstream };
35
+ }
36
+ /** Exact pathname the remote's stream upgrade arrives on. */
37
+ export function upgradePath(hostId) {
38
+ return `${REMOTE_VIEW_PREFIX}${hostId}${REMOTE_STREAM_PATH}`;
39
+ }
@@ -0,0 +1,175 @@
1
+ /**
2
+ * The WebSocket half of the same-origin proxy.
3
+ *
4
+ * The only WebSocket route a remote DSH owns (`/api/remote.mux`) gets one exact upgrade route per
5
+ * connected host, because the local web server matches upgrades by exact pathname. The handshake
6
+ * is admitted and fenced like an HTTP request, the upstream's response head is filtered before
7
+ * the browser sees it (a 101 used to be forwarded byte-for-byte, also handing the remote's
8
+ * `Set-Cookie` to the local origin), and both directions stream untouched afterwards.
9
+ */
10
+ import http from 'node:http';
11
+ import net from 'node:net';
12
+ import { trustedRequest } from '../request-trust.js';
13
+ import { filterResponseHead, remoteOrigin, upstreamHeaders } from './headers.js';
14
+ import { MAX_UPSTREAM_HEAD_BYTES } from './limits.js';
15
+ import { parseViewPath } from './routes.js';
16
+ /**
17
+ * Create the upgrade handler of one proxy activation.
18
+ *
19
+ * An upgrade owns its socket, so every refusal here either answers the handshake with a status and
20
+ * closes it (an admission rejection) or destroys it; nothing falls back to an HTTP response.
21
+ */
22
+ export function createUpgradeHandler(rt, track) {
23
+ /** One exact upgrade route per host: the only WebSocket a DSH web serves is its stream mux. */
24
+ return function handleUpgrade(hostId, req, socket, head) {
25
+ if (rt.disposed()) {
26
+ socket.destroy();
27
+ return;
28
+ }
29
+ const rejection = rt.admit(req);
30
+ if (rejection !== undefined) {
31
+ // An upgrade owns its socket: answer the handshake with the status, then close it.
32
+ socket.on('error', () => { });
33
+ socket.end(`HTTP/1.1 ${rejection} ${http.STATUS_CODES[rejection] ?? 'Rejected'}\r\n` +
34
+ 'connection: close\r\ncontent-length: 0\r\n\r\n');
35
+ return;
36
+ }
37
+ const origin = rt.localOrigin();
38
+ if (origin === null || !trustedRequest(req, origin)) {
39
+ socket.destroy();
40
+ return;
41
+ }
42
+ const target = rt.targetOf(hostId);
43
+ if (target === null) {
44
+ socket.destroy();
45
+ return;
46
+ }
47
+ // A malformed request target (absolute-form, broken escape) must not throw out of the upgrade
48
+ // handler: the HTTP path already degrades to a 400, this one just drops the socket.
49
+ let parsed = null;
50
+ try {
51
+ parsed = parseViewPath(new URL(req.url ?? '/', 'http://127.0.0.1').pathname);
52
+ }
53
+ catch {
54
+ parsed = null;
55
+ }
56
+ if (parsed === null) {
57
+ socket.destroy();
58
+ return;
59
+ }
60
+ const jar = rt.jarFor(hostId, target);
61
+ const headers = upstreamHeaders(req.rawHeaders, {
62
+ target,
63
+ localOrigin: origin.origin,
64
+ path: parsed.path,
65
+ jar,
66
+ preserveUpgrade: true,
67
+ });
68
+ let raw = `${req.method} ${parsed.path} HTTP/1.1\r\n`;
69
+ for (const [name, value] of Object.entries(headers)) {
70
+ for (const item of Array.isArray(value) ? value : [value])
71
+ raw += `${name}: ${item}\r\n`;
72
+ }
73
+ raw += '\r\n';
74
+ const upstream = net.connect({ port: target.localPort, host: '127.0.0.1', timeout: rt.upstreamTimeoutMs });
75
+ // An upgrade owns its socket, so the deadline covers the handshake only: an upstream that
76
+ // accepts and never answers would otherwise leave both sockets dangling forever.
77
+ let settled = false;
78
+ const handshakeTimer = setTimeout(() => failUpgrade(), rt.upstreamTimeoutMs);
79
+ handshakeTimer.unref?.();
80
+ function failUpgrade() {
81
+ clearTimeout(handshakeTimer);
82
+ if (settled)
83
+ return;
84
+ settled = true;
85
+ upstream.destroy();
86
+ socket.destroy();
87
+ rt.reportUpstreamFailure(hostId);
88
+ }
89
+ track.add(socket);
90
+ // The upstream's response head is filtered before the browser sees it: a 101 used to be
91
+ // forwarded byte-for-byte, which also handed the remote's `Set-Cookie` and policy headers to
92
+ // the local origin. Only the head is parsed; everything after it streams untouched.
93
+ let upstreamHead = Buffer.alloc(0);
94
+ let headForwarded = false;
95
+ const writeToClient = (chunk) => {
96
+ if (!socket.write(chunk))
97
+ upstream.pause();
98
+ };
99
+ const forwardUpstreamData = (chunk) => {
100
+ if (settled)
101
+ return;
102
+ clearTimeout(handshakeTimer);
103
+ upstream.setTimeout(0);
104
+ if (headForwarded) {
105
+ writeToClient(chunk);
106
+ return;
107
+ }
108
+ upstreamHead = upstreamHead.length === 0 ? Buffer.from(chunk) : Buffer.concat([upstreamHead, chunk]);
109
+ if (upstreamHead.length > MAX_UPSTREAM_HEAD_BYTES) {
110
+ // Nothing legitimate answers a handshake with a head this large.
111
+ failUpgrade();
112
+ return;
113
+ }
114
+ const end = upstreamHead.indexOf('\r\n\r\n');
115
+ if (end === -1)
116
+ return;
117
+ const filtered = filterResponseHead(upstreamHead.subarray(0, end).toString('latin1'), {
118
+ hostId,
119
+ remoteOrigin: remoteOrigin(target),
120
+ });
121
+ if (filtered === '') {
122
+ failUpgrade();
123
+ return;
124
+ }
125
+ headForwarded = true;
126
+ writeToClient(`${filtered}\r\n`);
127
+ const rest = upstreamHead.subarray(end + 4);
128
+ upstreamHead = Buffer.alloc(0);
129
+ if (rest.length > 0)
130
+ writeToClient(rest);
131
+ };
132
+ upstream.on('data', forwardUpstreamData);
133
+ socket.on('drain', () => upstream.resume());
134
+ upstream.on('timeout', () => failUpgrade());
135
+ upstream.on('error', () => failUpgrade());
136
+ /**
137
+ * The remote ended the stream. `upstream.pipe(socket)` used to forward that EOF implicitly;
138
+ * the head is parsed here, so the end of the upstream must still close the browser side or
139
+ * the page would hold a dead socket forever.
140
+ */
141
+ const endClient = () => {
142
+ if (settled)
143
+ return;
144
+ settled = true;
145
+ clearTimeout(handshakeTimer);
146
+ try {
147
+ socket.end();
148
+ }
149
+ catch {
150
+ // swallow-ok: the client socket may already be closed
151
+ }
152
+ };
153
+ upstream.on('end', endClient);
154
+ upstream.on('close', endClient);
155
+ socket.once('close', () => {
156
+ settled = true;
157
+ clearTimeout(handshakeTimer);
158
+ track.delete(socket);
159
+ upstream.destroy();
160
+ });
161
+ socket.on('error', () => {
162
+ settled = true;
163
+ clearTimeout(handshakeTimer);
164
+ upstream.destroy();
165
+ });
166
+ upstream.once('connect', () => {
167
+ if (settled)
168
+ return;
169
+ upstream.write(raw);
170
+ if (head && head.length > 0)
171
+ upstream.write(head);
172
+ socket.pipe(upstream);
173
+ });
174
+ };
175
+ }
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Diagnostics redaction: tokens, passwords and private keys never leave the machine in a diagnostic package.
3
+ */
4
+ const SECRET_QUERY_KEYS = ['token', 'access_token', 'api_key', 'apikey', 'key', 'secret', 'password', 'passwd', 'auth'];
5
+ const SECRET_HEADER_RE = /\b(authorization|cookie|set-cookie|x-api-key|proxy-authorization)\s*:\s*[^\r\n]+/gi;
6
+ /** Custom authentication headers (`x-auth-token`, `x-dsh-session-key`, …) are secrets too. */
7
+ const SECRET_CUSTOM_HEADER_RE = /\b(x-[a-z0-9-]*(?:token|key|secret|auth)[a-z0-9-]*)\s*:\s*[^\r\n]+/gi;
8
+ const BEARER_RE = /\b(Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{8,}/g;
9
+ const TOKEN_QUERY_RE = new RegExp(`([?&](?:${SECRET_QUERY_KEYS.join('|')})=)[^&#\\s"']+`, 'gi');
10
+ /**
11
+ * A bare `token=…` outside a query string (log lines, `#fragment`, key=value dumps). The
12
+ * value never contains `<`/`>` so an already-redacted `<redacted>` is left alone.
13
+ */
14
+ /**
15
+ * A bare `key=value` pair (log lines, `#fragment`, dumps). The anchor is "not alphanumeric" rather
16
+ * than `\b`, so a prefixed env name such as `MYSQL_PWD=…` is caught too (`_` is a word character,
17
+ * which made `\b` miss it). The value never contains `<`/`>` so an already-redacted `<redacted>` is
18
+ * left alone.
19
+ */
20
+ const BARE_TOKEN_KEYS = [
21
+ 'token',
22
+ 'access_token',
23
+ 'api_key',
24
+ 'apikey',
25
+ 'secret',
26
+ 'password',
27
+ 'passwd',
28
+ 'pwd',
29
+ 'auth',
30
+ 'credential',
31
+ 'key',
32
+ ];
33
+ const BARE_TOKEN_RE = new RegExp(`(^|[^A-Za-z0-9])((?:${BARE_TOKEN_KEYS.join('|')})\\s*=\\s*)[^\\s&;,'"<>]+`, 'gi');
34
+ /**
35
+ * A secret passed as a command-line flag (`--token abc`, `--api-key x`, `--password y`). No `\b`
36
+ * anchor: `-` is a non-word character, so a boundary never holds right before `--token`. The
37
+ * separate `PASSWORD_FLAG_RE` below covers the historic spellings; this one catches the token-ish
38
+ * flags that a launch command line carries, which `ps` output made worth redacting.
39
+ */
40
+ const SECRET_FLAG_RE = /(?:--?)(?:token|api-key|apikey|auth-token|access-token|password|passphrase)[=\s]+(?!<redacted>)\S+/gi;
41
+ const PRIVATE_KEY_RE = /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z0-9 ]*PRIVATE KEY-----/g;
42
+ /**
43
+ * `--password X`, `password=X` and the short `-p X` form. The short form is also ssh's
44
+ * port flag (`ssh -p 2222`), so a bare number is left alone: a port is not a secret and
45
+ * mangling it would make the technical detail unreadable. The value may also be glued to the
46
+ * flag (`mysql -pHunter2`), which is why the whitespace after `-p` is optional.
47
+ */
48
+ const PASSWORD_FLAG_RE = /(--password[=\s]+|password[=:]\s*|-p\s*(?!\d+\b))(\S+)/gi;
49
+ const DSH_TOKEN_LINE_RE = /(dsh web:\s*\S*?\?token=)[A-Za-z0-9._~+/=-]+/g;
50
+ export function redactText(text, options = {}) {
51
+ if (typeof text !== 'string' || text === '')
52
+ return text;
53
+ let out = text;
54
+ out = out.replace(PRIVATE_KEY_RE, '-----BEGIN PRIVATE KEY-----<redacted>-----END PRIVATE KEY-----');
55
+ // A capture that was cut before the footer (`safeText` bounds every field before it redacts) leaves
56
+ // a header with no END; the complete-block rule above cannot match it, so the body is dropped
57
+ // explicitly. The placeholder from the rule above already carries an END and is left alone.
58
+ const strayBegin = out.lastIndexOf('-----BEGIN ');
59
+ if (strayBegin >= 0 && strayBegin > out.lastIndexOf('-----END ')) {
60
+ out = `${out.slice(0, strayBegin)}-----BEGIN PRIVATE KEY-----<redacted>`;
61
+ }
62
+ out = out.replace(SECRET_HEADER_RE, (match) => `${match.split(':')[0]}: <redacted>`);
63
+ out = out.replace(SECRET_CUSTOM_HEADER_RE, (match) => `${match.split(':')[0]}: <redacted>`);
64
+ out = out.replace(BEARER_RE, (_match, scheme) => `${scheme} <redacted>`);
65
+ out = out.replace(TOKEN_QUERY_RE, '$1<redacted>');
66
+ out = out.replace(DSH_TOKEN_LINE_RE, '$1<redacted>');
67
+ out = out.replace(SECRET_FLAG_RE, (match) => `${match.replace(/\S+$/, '')}<redacted>`);
68
+ out = out.replace(BARE_TOKEN_RE, '$1$2<redacted>');
69
+ out = out.replace(PASSWORD_FLAG_RE, '$1<redacted>');
70
+ if (!options.keepPaths) {
71
+ // Home directories of the remote account are not secrets, but avoid leaking
72
+ // arbitrary local user names into exported diagnostics.
73
+ out = out.replace(/(\/home\/)[^/\s]+/g, '$1<user>');
74
+ out = out.replace(/(\/Users\/)[^/\s]+/g, '$1<user>');
75
+ out = out.replace(/\b(C:\\Users\\)[^\\\s]+/gi, '$1<user>');
76
+ }
77
+ return out;
78
+ }
79
+ function redactValue(key, value) {
80
+ const lowered = String(key).toLowerCase();
81
+ if (typeof value === 'string') {
82
+ if (/(password|token|secret|passphrase|authorization|apikey|api_key|privatekey|cookie)/.test(lowered))
83
+ return '<redacted>';
84
+ return redactText(value);
85
+ }
86
+ if (Array.isArray(value))
87
+ return value.map((item) => redactValue(key, item));
88
+ if (value && typeof value === 'object')
89
+ return redactObject(value);
90
+ return value;
91
+ }
92
+ /**
93
+ * Deep-redact a JSON-compatible value.
94
+ */
95
+ export function redactObject(value) {
96
+ if (Array.isArray(value))
97
+ return value.map((item) => redactValue('', item));
98
+ if (!value || typeof value !== 'object')
99
+ return value;
100
+ const out = {};
101
+ for (const [key, item] of Object.entries(value))
102
+ out[key] = redactValue(key, item);
103
+ return out;
104
+ }
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Remote download entry: validate an absolute Linux path, inspect it, then hand it
3
+ * to the local writer. Both files and folders stream directly to disk; no bytes are
4
+ * buffered in the Host and no ZIP is created.
5
+ */
6
+ import { errors, isRemoteGoError } from './errors.js';
7
+ import { requireDestination, saveHostFile, saveHostFolder } from './local-download.js';
8
+ import { normalizeRemoteFilePath } from './remote-path.js';
9
+ /**
10
+ * Save one file or one folder for a download job.
11
+ * @param runtime - the connected host runtime.
12
+ * @param rawPath - the requested absolute remote path.
13
+ */
14
+ export async function readHostDownload(runtime, rawPath, options = {}) {
15
+ if (!runtime || runtime.status !== 'connected' || !runtime.ssh) {
16
+ throw errors.remoteFileUnavailable({
17
+ zh: '这台主机还没有连接,无法读取远端内容。',
18
+ en: 'This host is not connected, so the remote content cannot be read.',
19
+ });
20
+ }
21
+ const remotePath = normalizeRemoteFilePath(rawPath);
22
+ const ssh = runtime.ssh;
23
+ if (typeof ssh.inspectRemotePath !== 'function') {
24
+ throw errors.internal('the SSH transport does not support path inspection');
25
+ }
26
+ let destination;
27
+ try {
28
+ const info = await ssh.inspectRemotePath(remotePath);
29
+ destination = await requireDestination(options.destination, { home: options.home });
30
+ if (info.isFile)
31
+ return await saveHostFile(runtime, remotePath, destination, options);
32
+ if (info.isDirectory)
33
+ return await saveHostFolder(runtime, remotePath, destination, options);
34
+ throw errors.remoteFileUnavailable({
35
+ zh: '这个远端路径既不是普通文件,也不是文件夹。',
36
+ en: 'This remote path is neither a regular file nor a folder.',
37
+ });
38
+ }
39
+ catch (error) {
40
+ if (isRemoteGoError(error))
41
+ throw error;
42
+ throw toRemoteFileError(error);
43
+ }
44
+ }
45
+ /**
46
+ * Classify an SFTP failure without leaking transport internals to the client.
47
+ * @param error - the transport error.
48
+ * @returns a client-safe error.
49
+ */
50
+ export function toRemoteFileError(error) {
51
+ // `isRemoteGoError` only declares a boolean (it lives in the P1a set); the `as` restates
52
+ // the narrowing its `instanceof` proves at runtime.
53
+ if (isRemoteGoError(error))
54
+ return error;
55
+ // A transport error is `unknown`: the `as` restates the two fields an SFTP error carries
56
+ // (`code` 2/3 for ENOENT/EACCES) and the `??` fallbacks keep a thrown string working.
57
+ const code = Number(error?.code);
58
+ const message = String(error?.message ?? error ?? '');
59
+ if (code === 2 || /no such file|not found/i.test(message)) {
60
+ return errors.remoteFileUnavailable({
61
+ zh: '远端文件不存在或已经被移动。',
62
+ en: 'The remote file no longer exists or was moved.',
63
+ });
64
+ }
65
+ if (code === 3 || /permission denied|access denied/i.test(message)) {
66
+ return errors.remoteFileUnavailable({
67
+ zh: '当前 SSH 用户没有读取这个远端路径的权限。',
68
+ en: 'The SSH user is not allowed to read this remote path.',
69
+ });
70
+ }
71
+ return errors.remoteFileUnavailable(undefined, { technical: message.slice(0, 300) });
72
+ }