dsh-remote-go 0.1.0 → 0.2.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.
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Connect progress: the coalesced `/state` frame that carries log lines, the staged progress line and the npm / managed-Node reporters; it never sets a status.
3
3
  */
4
- import { appendConnectLog, connectLogVisible } from './connect-log.js'
4
+ import { appendConnectLog, connectFailureLines, connectLogVisible } from './connect-log.js'
5
5
  import { logVisible, nowIso } from './util.js'
6
6
 
7
7
  /**
@@ -39,15 +39,35 @@ export function describePreflightEvent(line, version) {
39
39
  export function createConnectProgress(options) {
40
40
  let flushTimer = null
41
41
 
42
- function log(runtime, level, ...args) {
43
- const message = args.map((value) => (typeof value === 'string' ? value : JSON.stringify(value))).join(' ')
44
- const entry = appendConnectLog(runtime, { at: nowIso(), level, message })
45
- scheduleFlush(runtime)
42
+ /** Append one line and echo it to the Host logger at the same level. */
43
+ function write(runtime, input) {
44
+ const entry = appendConnectLog(runtime, { at: nowIso(), ...input })
46
45
  // Verbosity is a runtime decision: `options.logLevel` (tests, diagnostics) or settings.
47
46
  const threshold = options.logLevel ?? options.getSettings()?.logLevel ?? 'info'
48
- if (!logVisible(level, threshold)) return
49
- const method = options.logger[level] ?? options.logger.info
47
+ if (!logVisible(entry.level, threshold)) return entry
48
+ const method = options.logger[entry.level] ?? options.logger.info
50
49
  method?.(entry.line)
50
+ return entry
51
+ }
52
+
53
+ function log(runtime, level, ...args) {
54
+ const message = args.map((value) => (typeof value === 'string' ? value : JSON.stringify(value))).join(' ')
55
+ const entry = write(runtime, { level, message, phase: runtime.phase })
56
+ scheduleFlush(runtime)
57
+ return entry
58
+ }
59
+
60
+ /**
61
+ * Print a failed connection as the lines that explain it (phase, code, localized reason,
62
+ * hints, redacted details), instead of one line of code plus a raw message. `context.label`
63
+ * replaces the leading line for a one-shot action that is not a connect (the remote stop).
64
+ */
65
+ function logFailure(runtime, view, context = {}) {
66
+ const phase = typeof context.phase === 'string' && context.phase !== '' ? context.phase : null
67
+ for (const line of connectFailureLines(view, { phase, label: context.label })) {
68
+ write(runtime, { level: line.level, message: line.message, text: line.text, phase: line.phase })
69
+ }
70
+ scheduleFlush(runtime)
51
71
  }
52
72
 
53
73
  /** Ship the log tail to the Client's console without one `/state` frame per line. */
@@ -131,5 +151,5 @@ export function createConnectProgress(options) {
131
151
  }
132
152
  }
133
153
 
134
- return { log, set, phase, nodeProgress, bootstrapReporter, dispose }
154
+ return { log, logFailure, set, phase, nodeProgress, bootstrapReporter, dispose }
135
155
  }
package/src/constants.js CHANGED
@@ -10,13 +10,27 @@ export const REMOTE_STATE_DIR = 'remote-go'
10
10
 
11
11
  export const API_PREFIX = '/dsh-remote-go/api'
12
12
 
13
+ /**
14
+ * Same-origin seat of the remote web UI used by the browser half: every request below
15
+ * `<prefix><hostId>/` is proxied to that connected host's loopback tunnel (see remote-proxy.js).
16
+ */
17
+ export const REMOTE_VIEW_PREFIX = '/dsh-remote-go/remote/'
18
+
13
19
  export const API_HEADER = 'x-dsh-remote-go'
14
20
 
15
21
  export const PLUGIN_ID = 'dsh-remote-go'
16
- export const PLUGIN_VERSION = '0.1.0'
22
+ export const PLUGIN_VERSION = '0.2.0'
17
23
 
18
- /** Host↔Client contract version served by `GET /version` (docs/api.md v2.4). */
19
- export const API_VERSION = '2.6'
24
+ /**
25
+ * DSH's own lower bound, mirrored from this package's `engines.dsh`. The client may only
26
+ * backfill a locally-detected DSH version; a value below this floor names a build the plugin
27
+ * does not support, so `/local-version` refuses it (it would otherwise pin the remote npx
28
+ * runtime to an arbitrary, possibly unusable version).
29
+ */
30
+ export const MIN_DSH_VERSION = '0.2.2-rc.3'
31
+
32
+ /** Host↔Client contract version served by `GET /version` (docs/api.md v2.11). */
33
+ export const API_VERSION = '2.11'
20
34
 
21
35
  export const DEFAULT_KEY_PATH = '~/.ssh/id_rsa'
22
36
 
@@ -29,3 +43,51 @@ export const SSH_READY_TIMEOUT_MS = 20_000
29
43
  export const DEFAULT_IDLE_MINUTES = 15
30
44
 
31
45
  export const TUNNEL_PROBE_TIMEOUT_MS = 10_000
46
+
47
+ /**
48
+ * Remote liveness: a connected host's remote UI is probed on this interval
49
+ * (`settings.remoteHeartbeat`). Two consecutive failed probes - not one failed
50
+ * request - are what confirm that the remote web really went away.
51
+ */
52
+ export const REMOTE_HEARTBEAT_DEFAULT_SEC = 30
53
+
54
+ export const REMOTE_HEARTBEAT_MIN_SEC = 5
55
+
56
+ export const REMOTE_HEARTBEAT_MAX_SEC = 600
57
+
58
+ /** Consecutive failed probes that turn a suspicion into a confirmed restart. */
59
+ export const REMOTE_UNREACHABLE_FAILURES = 2
60
+
61
+ /** Delay before the confirming probe after a proxy/tunnel error (never trust one failure). */
62
+ export const REMOTE_UNREACHABLE_CONFIRM_DELAY_MS = 750
63
+
64
+ /** Delay between the two confirming probes, so they are consecutive but not one slow request. */
65
+ export const REMOTE_UNREACHABLE_RECHECK_DELAY_MS = 1200
66
+
67
+ /**
68
+ * After a transient (proxy/tunnel) episode is confirmed healthy, the same kind of report is
69
+ * ignored for this long: a flapping tunnel must not emit suspected/recovered on every request.
70
+ */
71
+ export const REMOTE_EPISODE_COOLDOWN_MS = 15_000
72
+
73
+ /**
74
+ * A failed listener rebuild waits before the next attempt (doubling up to the max). The
75
+ * episode cooldown alone would still let a broken rebuild retry every 15s forever.
76
+ */
77
+ export const REMOTE_REPAIR_BACKOFF_MS = 30_000
78
+ export const REMOTE_REPAIR_BACKOFF_MAX_MS = 120_000
79
+
80
+ /**
81
+ * How long teardown waits for an in-flight listener rebuild. The rebuild is local and fast;
82
+ * a stuck one must not delay disconnect / host removal / shutdown indefinitely. Its token is
83
+ * already cancelled, so it still closes any listener it manages to publish afterwards.
84
+ */
85
+ export const REMOTE_TUNNEL_REPAIR_SETTLE_MS = 5_000
86
+
87
+ /**
88
+ * A remote restart needs a little time to print its new readiness line. The
89
+ * re-attach retries the read-back a few times before it declares the remote gone.
90
+ */
91
+ export const REMOTE_REATTACH_ATTEMPTS = 6
92
+
93
+ export const REMOTE_REATTACH_INTERVAL_MS = 2_000
@@ -152,6 +152,9 @@ export async function diagnoseHost(runtime, ctx) {
152
152
  checks,
153
153
  redacted: true,
154
154
  generatedAt: nowIso(),
155
+ // One entry per restart / re-attach, so an exported report can tell a local restart
156
+ // apart from a remote one without re-reading the whole connect log.
157
+ restarts: (Array.isArray(runtime.restarts) ? runtime.restarts : []).slice(-10),
155
158
  logs: runtime.logs.slice(-40).map((entry) => entry.line),
156
159
  })
157
160
  }
@@ -46,6 +46,11 @@ export function createDownloadJobs(options) {
46
46
  doneBytes: job.doneBytes,
47
47
  totalFiles: job.totalFiles,
48
48
  doneFiles: job.doneFiles,
49
+ /**
50
+ * Names a folder download deliberately skipped (Windows metadata / shell shortcuts on a
51
+ * Windows host). Surfaced so nothing disappears without the user seeing it.
52
+ */
53
+ ignoredNames: Array.isArray(job.ignoredNames) ? job.ignoredNames : [],
49
54
  destination: job.destination ?? null,
50
55
  startedAt: job.startedAt,
51
56
  error: job.error,
@@ -92,6 +97,8 @@ export function createDownloadJobs(options) {
92
97
  try {
93
98
  const result = await readDownload(runtime, job.path, {
94
99
  destination: job.destination ?? undefined,
100
+ // The same home root the API pre-flight used; the write is judged by it again.
101
+ home: job.home,
95
102
  isCancelled: () => job.cancelled === true,
96
103
  onInventory: (info) => {
97
104
  if (job.cancelled) return
@@ -107,6 +114,13 @@ export function createDownloadJobs(options) {
107
114
  if (Number.isFinite(info?.totalFiles)) job.totalFiles = Math.max(0, Number(info.totalFiles))
108
115
  publish(job)
109
116
  },
117
+ // Folder downloads report the names they skipped (Windows-only metadata/shortcuts);
118
+ // `saveHostFolder` forwards this options object to the SSH layer unchanged.
119
+ onIgnored: (names) => {
120
+ if (job.cancelled || !Array.isArray(names)) return
121
+ job.ignoredNames = names.slice(0, 200).map((name) => String(name))
122
+ publish(job)
123
+ },
110
124
  })
111
125
  if (job.cancelled) return
112
126
  job.kind = result.kind
@@ -167,8 +181,11 @@ export function createDownloadJobs(options) {
167
181
  totalFiles: 0,
168
182
  doneFiles: 0,
169
183
  destination: typeof options.destination === 'string' && options.destination !== '' ? options.destination : null,
184
+ // The local home root the destination policy must judge against; not part of the view.
185
+ home: typeof options.home === 'string' && options.home !== '' ? options.home : undefined,
170
186
  startedAt: new Date(now()).toISOString(),
171
187
  error: null,
188
+ ignoredNames: [],
172
189
  timer: null,
173
190
  lastEmit: 0,
174
191
  cancelled: false,
package/src/errors.js CHANGED
@@ -1,6 +1,8 @@
1
1
  /**
2
2
  * Coded, bilingual errors; `toErrorView` is the only shape the Client ever sees.
3
3
  */
4
+ import { redactObject, redactText } from './redact.js'
5
+ import { headTail } from './util.js'
4
6
 
5
7
  const ErrorCode = Object.freeze({
6
8
  NETWORK: 'network',
@@ -12,6 +14,9 @@ const ErrorCode = Object.freeze({
12
14
  REMOTE_DSH_START_FAILED: 'remote-dsh-start-failed',
13
15
  REMOTE_DSH_RUNNING: 'remote-dsh-running',
14
16
  REMOTE_UI_UNREACHABLE: 'remote-ui-unreachable',
17
+ REMOTE_UNREACHABLE: 'remote-unreachable',
18
+ RESTART_UNAVAILABLE: 'restart-unavailable',
19
+ STOP_UNAVAILABLE: 'stop-unavailable',
15
20
  REMOTE_FILE_UNAVAILABLE: 'remote-file-unavailable',
16
21
  DOWNLOAD_NOT_READY: 'download-not-ready',
17
22
  DOWNLOAD_BUSY: 'download-busy',
@@ -46,6 +51,18 @@ const CODE_TABLE = {
46
51
  retryable: true,
47
52
  title: { zh: '远端界面打不开', en: 'The remote interface is unreachable' },
48
53
  },
54
+ [ErrorCode.REMOTE_UNREACHABLE]: {
55
+ retryable: true,
56
+ title: { zh: '远端 DSH 已不在运行', en: 'The remote DSH is no longer running' },
57
+ },
58
+ [ErrorCode.RESTART_UNAVAILABLE]: {
59
+ retryable: true,
60
+ title: { zh: '现在不能重启远端 DSH', en: 'The remote DSH cannot be restarted now' },
61
+ },
62
+ [ErrorCode.STOP_UNAVAILABLE]: {
63
+ retryable: true,
64
+ title: { zh: '现在不能关闭远端 DSH', en: 'The remote DSH cannot be stopped now' },
65
+ },
49
66
  [ErrorCode.REMOTE_FILE_UNAVAILABLE]: {
50
67
  retryable: true,
51
68
  title: { zh: '无法读取远端文件', en: 'Cannot read the remote file' },
@@ -218,6 +235,68 @@ export const errors = {
218
235
  ['查看诊断中的隧道与界面可达性检查', 'Check tunnel and UI reachability in diagnostics'],
219
236
  ],
220
237
  ),
238
+ /**
239
+ * The remote web went away and nothing adoptable came back. Kept apart from
240
+ * `remote-ui-unreachable`: here the tunnel may be perfectly fine and the process
241
+ * is what is missing, which is what the restart button exists for.
242
+ */
243
+ remoteUnreachable: (detail, options) =>
244
+ fail(
245
+ ErrorCode.REMOTE_UNREACHABLE,
246
+ detail ??
247
+ say(
248
+ '远端 DSH 已经停止响应,而且没有找到可以重新挂载的实例;主机配置保留。',
249
+ 'The remote DSH stopped responding and no instance could be re-attached to; the host configuration is kept.',
250
+ ),
251
+ [
252
+ [
253
+ '点「重启」用同一份配置重新拉起远端进程',
254
+ 'Use "Restart" to start the remote process again with the same settings',
255
+ ],
256
+ ['点「重连」按存活策略重新连接', 'Use Reconnect to connect again under the keep-alive policy'],
257
+ ],
258
+ options,
259
+ ),
260
+ /**
261
+ * One-shot restart requested in a state that cannot support it (not connected, no live
262
+ * SSH, or already busy with another action). The HTTP API answers 409 for this.
263
+ */
264
+ restartUnavailable: (detail, options) =>
265
+ fail(
266
+ ErrorCode.RESTART_UNAVAILABLE,
267
+ detail ??
268
+ say(
269
+ '只有已连接、或远端不可达但仍保留 SSH 连接的主机才能重启远端 DSH。',
270
+ 'The remote DSH can only be restarted while this host is connected, or after a remote-unreachable failure that kept the SSH session.',
271
+ ),
272
+ [
273
+ ['先连接这台主机,再点「重启」', 'Connect the host first, then use "Restart"'],
274
+ ['如果连接已断开,点「重连」重新建立连接', 'If the link dropped, use Reconnect to establish it again'],
275
+ ],
276
+ options,
277
+ ),
278
+ /**
279
+ * The explicit "stop remote DSH" action was refused: wrong state, another link action in
280
+ * flight, or the bound process could not be proven to be this connection's own. The HTTP
281
+ * API answers 409 for this.
282
+ */
283
+ stopRemoteUnavailable: (detail, options) =>
284
+ fail(
285
+ ErrorCode.STOP_UNAVAILABLE,
286
+ detail ??
287
+ say(
288
+ '只有已连接、或远端不可达但仍保留 SSH 连接的主机才能关闭远端 DSH,而且只能关闭本连接启动或接管的那一个进程。',
289
+ 'The remote DSH can only be stopped while this host is connected (or after a remote-unreachable failure that kept the SSH session), and only when it is the process this connection launched or took over.',
290
+ ),
291
+ [
292
+ ['先连接这台主机,再点「关闭」', 'Connect the host first, then use "Stop"'],
293
+ [
294
+ '如果强烈怀疑远端进程不属于本连接,点「重连」重建连接后再试',
295
+ 'If the remote process may not belong to this connection, use Reconnect and try again',
296
+ ],
297
+ ],
298
+ options,
299
+ ),
221
300
  remoteFileUnavailable: (detail, options) =>
222
301
  fail(
223
302
  ErrorCode.REMOTE_FILE_UNAVAILABLE,
@@ -295,6 +374,23 @@ export const errors = {
295
374
  ),
296
375
  }
297
376
 
377
+ /**
378
+ * How much of one `ErrorView.technical` string the API will carry. The producers hand over
379
+ * captured process output (a remote `web.log` tail, an SFTP failure); the API response is the
380
+ * one place that must never carry the whole of it.
381
+ */
382
+ export const TECHNICAL_LIMIT = 1200
383
+
384
+ /**
385
+ * The only ErrorView a caller may send: redaction is part of the contract, not an opt-in.
386
+ * `technical` is the risky field — producers put remote process output there, and the first
387
+ * line of a remote `web.log` is the launch URL with its session token. It is redacted and
388
+ * length-capped, then the whole view goes through `redactObject` so a detail/next-step that
389
+ * quotes one of those lines is covered too (docs/api.md: "已脱敏").
390
+ * @param {unknown} error
391
+ * @returns {{ code: string, title: { zh: string, en: string }, detail: { zh: string, en: string },
392
+ * nextSteps: { zh: string, en: string }[], retryable: boolean, technical?: string }}
393
+ */
298
394
  export function toErrorView(error) {
299
395
  if (error instanceof RemoteGoError) {
300
396
  const table = CODE_TABLE[error.code] ?? { retryable: true, title: { zh: '未知错误', en: 'Unknown error' } }
@@ -305,8 +401,8 @@ export function toErrorView(error) {
305
401
  nextSteps: error.nextSteps,
306
402
  retryable: error.retryable,
307
403
  }
308
- if (error.technical) view.technical = error.technical
309
- return view
404
+ if (error.technical) view.technical = headTail(redactText(error.technical), TECHNICAL_LIMIT)
405
+ return redactObject(view)
310
406
  }
311
407
  return toErrorView(errors.internal(error))
312
408
  }