dsh-remote-vs 0.25.0 → 0.27.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 (109) hide show
  1. package/README.en.md +12 -15
  2. package/README.md +11 -12
  3. package/THIRD-PARTY-NOTICES.md +193 -0
  4. package/lib/client.js +7313 -79961
  5. package/lib/index.js +1529 -964
  6. package/lib/p2-router-fs.js +1 -1
  7. package/lib/types/client/CodeEditor.d.ts +22 -0
  8. package/lib/types/client/OutlinePanel.d.ts +22 -0
  9. package/lib/types/client/ProcessesSection.d.ts +19 -0
  10. package/lib/types/client/RemoteExplorer.d.ts +53 -0
  11. package/lib/types/client/api.d.ts +42 -3
  12. package/lib/types/client/blame-model.d.ts +77 -0
  13. package/lib/types/client/changes/review-state.d.ts +19 -0
  14. package/lib/types/client/connection.d.ts +16 -0
  15. package/lib/types/client/i18n.d.ts +1 -1
  16. package/lib/types/client/outline-model.d.ts +59 -0
  17. package/lib/types/client/request-gate.d.ts +110 -0
  18. package/lib/types/client/scm/DiffView.d.ts +45 -7
  19. package/lib/types/client/scm/actions.d.ts +43 -4
  20. package/lib/types/client/store.d.ts +71 -0
  21. package/lib/types/client/vsc/FindWidget.d.ts +6 -0
  22. package/lib/types/client/vsc/blame.d.ts +19 -0
  23. package/lib/types/client/vsc/change-marks.d.ts +16 -6
  24. package/lib/types/client/vsc/editor-keymap.d.ts +35 -1
  25. package/lib/types/client/vsc/kit.d.ts +11 -2
  26. package/lib/types/client/vsc/preview-document.d.ts +46 -0
  27. package/lib/types/client/vsc/preview-model.d.ts +31 -0
  28. package/lib/types/client/vsc/preview-services.d.ts +24 -0
  29. package/lib/types/client/vsc/save-shortcut.d.ts +21 -0
  30. package/lib/types/client/vsc/terminal-theme.d.ts +28 -2
  31. package/lib/types/forward.d.ts +12 -0
  32. package/lib/types/fs-ops.d.ts +42 -0
  33. package/lib/types/git-ops.d.ts +18 -0
  34. package/lib/types/http.d.ts +2 -0
  35. package/lib/types/keygen.d.ts +9 -0
  36. package/lib/types/monitor.d.ts +8 -0
  37. package/lib/types/notices.d.ts +16 -1
  38. package/lib/types/p2/helper-rpc.d.ts +45 -0
  39. package/lib/types/processes.d.ts +43 -0
  40. package/lib/types/protocol.d.ts +34 -0
  41. package/lib/types/routes.d.ts +2 -0
  42. package/lib/types/store.d.ts +7 -0
  43. package/lib/types/terminal.d.ts +8 -0
  44. package/lib/types/view-settings.d.ts +5 -0
  45. package/lib/{worlds-B7gEDBzC.js → worlds-RG8K5eom.js} +113 -15
  46. package/package.json +3 -1
  47. package/src/client/CodeEditor.tsx +194 -9
  48. package/src/client/DirectoryFlow.tsx +16 -0
  49. package/src/client/DoctorPanel.tsx +70 -7
  50. package/src/client/EditorPane.tsx +574 -42
  51. package/src/client/HostsView.tsx +12 -3
  52. package/src/client/MonitorView.tsx +16 -5
  53. package/src/client/OutlinePanel.tsx +287 -0
  54. package/src/client/ProcessesSection.tsx +292 -0
  55. package/src/client/RemoteDirectoryPicker.tsx +12 -0
  56. package/src/client/RemoteExplorer.tsx +929 -40
  57. package/src/client/RemoteRoot.tsx +147 -22
  58. package/src/client/SearchView.tsx +8 -0
  59. package/src/client/TerminalSnippets.tsx +83 -8
  60. package/src/client/api.ts +114 -13
  61. package/src/client/blame-model.ts +242 -0
  62. package/src/client/changes/ChangesDock.tsx +188 -6
  63. package/src/client/changes/changes.css +10 -3
  64. package/src/client/changes/review-state.ts +34 -0
  65. package/src/client/connection.ts +29 -0
  66. package/src/client/downloads.ts +49 -4
  67. package/src/client/i18n.ts +276 -8
  68. package/src/client/index.tsx +4 -0
  69. package/src/client/outline-model.ts +775 -0
  70. package/src/client/request-gate.ts +221 -0
  71. package/src/client/scm/CommitPane.tsx +20 -2
  72. package/src/client/scm/DiffView.tsx +343 -117
  73. package/src/client/scm/HistoryPanel.tsx +61 -3
  74. package/src/client/scm/RepoPicker.tsx +1 -1
  75. package/src/client/scm/ScmPanel.tsx +391 -87
  76. package/src/client/scm/actions.ts +150 -14
  77. package/src/client/store.tsx +426 -14
  78. package/src/client/ui.tsx +4 -0
  79. package/src/client/vsc/FindWidget.tsx +24 -9
  80. package/src/client/vsc/blame.ts +147 -0
  81. package/src/client/vsc/breadcrumb.tsx +91 -3
  82. package/src/client/vsc/change-marks.ts +93 -44
  83. package/src/client/vsc/editor-keymap.ts +59 -1
  84. package/src/client/vsc/file-icons.tsx +17 -3
  85. package/src/client/vsc/kit.tsx +29 -20
  86. package/src/client/vsc/preview-document.tsx +323 -0
  87. package/src/client/vsc/preview-model.ts +216 -0
  88. package/src/client/vsc/preview-services.ts +118 -0
  89. package/src/client/vsc/save-shortcut.ts +47 -1
  90. package/src/client/vsc/terminal-theme.ts +44 -18
  91. package/src/client/vsc/vsc.css +6509 -5458
  92. package/src/forward.ts +47 -9
  93. package/src/fs-ops.ts +124 -4
  94. package/src/git-ops.ts +54 -3
  95. package/src/http.ts +35 -4
  96. package/src/keygen.ts +55 -4
  97. package/src/monitor.ts +13 -0
  98. package/src/notices.ts +23 -1
  99. package/src/p2/helper-rpc.ts +113 -7
  100. package/src/p2/worlds.ts +14 -1
  101. package/src/processes.ts +177 -0
  102. package/src/protocol.ts +37 -0
  103. package/src/routes.ts +330 -43
  104. package/src/sftp.ts +51 -14
  105. package/src/store.ts +10 -0
  106. package/src/terminal.ts +73 -26
  107. package/src/view-settings.ts +50 -10
  108. package/lib/types/client/Dialog.d.ts +0 -14
  109. package/src/client/Dialog.tsx +0 -76
package/src/forward.ts CHANGED
@@ -162,6 +162,18 @@ export class ForwardManager {
162
162
  * first listener orphaned — unreachable from the panel and never closed.
163
163
  */
164
164
  private readonly starting = new Map<string, Promise<RemoteForwardState>>()
165
+ /**
166
+ * Rules stopped while their listener was still BINDING.
167
+ *
168
+ * A pending bind is not in `forwards` yet, so `stop()`, `stopAlias()`,
169
+ * `stopAll()` and `dispose()` used to see nothing to close: the listener the
170
+ * OS was about to hand out stayed bound with no panel row left to stop it
171
+ * (click a forward, immediately disable the plugin or delete the host, and
172
+ * `127.0.0.1:<port>` stayed taken until the Host restarted). The id sits here
173
+ * until the bind settles; a settling bind that finds its id records itself as
174
+ * stopped and closes the fresh listener instead of entering `forwards`.
175
+ */
176
+ private readonly stoppedWhileBinding = new Set<string>()
165
177
  /** Set on unload so a bind that settles afterwards closes itself. */
166
178
  private disposed = false
167
179
 
@@ -189,17 +201,20 @@ export class ForwardManager {
189
201
  throw new Error(`host ${request.alias} already has ${maxPerAlias} local forwards; stop one first`)
190
202
  }
191
203
  const pending = this.bindForward(id, request, requestedLocalPort).then((forward) => {
192
- // Unloaded while the bind was in flight: nobody can ever stop this
193
- // listener, so it closes itself instead of leaking.
194
- if (this.disposed) {
204
+ // Unloaded/stopped while the bind was in flight: nobody can ever stop
205
+ // this listener from the panel, so it closes itself instead of leaking.
206
+ if (this.disposed || this.stoppedWhileBinding.has(id)) {
195
207
  this.closeForward(forward)
196
- throw new Error('the port-forward manager was unloaded while the rule was binding')
208
+ throw new Error(this.disposed
209
+ ? 'the port-forward manager was unloaded while the rule was binding'
210
+ : 'the rule was stopped while its local listener was binding')
197
211
  }
198
212
  this.forwards.set(id, forward)
199
213
  this.log('info', `forward ${id} listening on 127.0.0.1:${forward.localPort}`)
200
214
  return this.stateOf(forward)
201
215
  }).finally(() => {
202
216
  this.starting.delete(id)
217
+ this.stoppedWhileBinding.delete(id)
203
218
  })
204
219
  this.starting.set(id, pending)
205
220
  return pending
@@ -208,10 +223,17 @@ export class ForwardManager {
208
223
  /** Stop one rule. Returns false when the id is unknown (already stopped). */
209
224
  stop(id: string): boolean {
210
225
  const forward = this.forwards.get(id)
211
- if (forward === undefined) return false
212
- this.forwards.delete(id)
213
- this.closeForward(forward)
214
- this.log('info', `forward ${id} stopped`)
226
+ if (forward !== undefined) {
227
+ this.forwards.delete(id)
228
+ this.closeForward(forward)
229
+ this.log('info', `forward ${id} stopped`)
230
+ return true
231
+ }
232
+ // Still binding: the listener does not exist yet, so the stop is recorded
233
+ // and `start()` closes the listener the moment the bind settles.
234
+ if (!this.starting.has(id)) return false
235
+ this.stoppedWhileBinding.add(id)
236
+ this.log('info', `forward ${id} stopped while binding; its listener will close on settle`)
215
237
  return true
216
238
  }
217
239
 
@@ -230,6 +252,13 @@ export class ForwardManager {
230
252
  this.closeForward(forward)
231
253
  stopped += 1
232
254
  }
255
+ // Rules still binding have no listener to close yet, but the one they are
256
+ // about to create belongs to this alias too.
257
+ for (const id of [...this.starting.keys()]) {
258
+ if (this.forwards.has(id) || !id.startsWith(`${alias}|`)) continue
259
+ this.stoppedWhileBinding.add(id)
260
+ stopped += 1
261
+ }
233
262
  if (stopped > 0) this.log('info', `stopped ${stopped} forward(s) for deleted host ${alias}`)
234
263
  return stopped
235
264
  }
@@ -246,6 +275,13 @@ export class ForwardManager {
246
275
  for (const id of [...this.forwards.keys()]) {
247
276
  if (this.stop(id)) stopped += 1
248
277
  }
278
+ // Pending binds are part of "every rule" too: deleting the rows without
279
+ // waiting for the bind is exactly how a listener used to outlive its panel.
280
+ for (const id of [...this.starting.keys()]) {
281
+ if (this.forwards.has(id)) continue
282
+ this.stoppedWhileBinding.add(id)
283
+ stopped += 1
284
+ }
249
285
  return stopped
250
286
  }
251
287
 
@@ -260,7 +296,9 @@ export class ForwardManager {
260
296
  /** Close every listener and every proxied connection (plugin unload). */
261
297
  dispose(): void {
262
298
  this.disposed = true
263
- for (const id of [...this.forwards.keys()]) this.stop(id)
299
+ // `stopAll` covers bound rules AND pending binds (the settle path above
300
+ // closes a listener that was created after this call started).
301
+ this.stopAll()
264
302
  }
265
303
 
266
304
  /** Bind the loopback listener. Split out so the error path is one place. */
package/src/fs-ops.ts CHANGED
@@ -47,11 +47,131 @@ export function moveToCommand(from: string, intoDir: string, name?: string): str
47
47
  return `mv -- ${source} ${target}`
48
48
  }
49
49
 
50
+ /**
51
+ * One batch holds at most this many paths.
52
+ *
53
+ * The client streams one exec per batch and paints per-path progress from its
54
+ * markers; a bounded batch keeps one failure/cancel from swallowing a whole
55
+ * thousand-path selection.
56
+ */
57
+ const BATCH_REMOVE_MAX_PATHS = 200
58
+
59
+ /**
60
+ * Upper bound on one batch's script, in UTF-8 bytes.
61
+ *
62
+ * The script is sent as a JSON string over the exec route, so it is kept well
63
+ * under any sane command-line budget; a selection of maximum-length paths is
64
+ * split further by this cap, not just by count.
65
+ */
66
+ const BATCH_REMOVE_MAX_BYTES = 48 * 1024
67
+
68
+ /**
69
+ * Validate one removal target: absolute, no `..`, no control characters, and
70
+ * never the filesystem root.
71
+ *
72
+ * `assertAbsPath` legitimately accepts `/` (one character away from `rm -rf -- /`)
73
+ * and rewrites `\` to `/` for Windows-shaped input. A remote POSIX name may
74
+ * legitimately contain a literal backslash, and rewriting it would delete a
75
+ * DIFFERENT path, so removal validation keeps every character as-is and only
76
+ * rejects what cannot be deleted safely.
77
+ */
78
+ export function assertRemovablePath(path: string): string {
79
+ if (typeof path !== 'string' || path === '') throw new Error('invalid path: empty')
80
+ if (path.length > 4096) throw new Error('invalid path: too long')
81
+ if (!path.startsWith('/')) throw new Error('invalid path: must be absolute')
82
+ // C0 + DEL + C1: none can be embedded in a shell line safely, and every
83
+ // well-known remote filesystem lets `rm` reach names without them.
84
+ if (/[\u0000-\u001f\u007f-\u009f]/.test(path)) throw new Error('invalid path: control characters')
85
+ // Collapse duplicate and trailing separators (same target), but keep `\` —
86
+ // it is an ordinary character in a POSIX name.
87
+ const normalized = path.replace(/\/{2,}/g, '/').replace(/\/+$/, '') || '/'
88
+ if (normalized === '/') throw new Error('invalid path: refusing to remove /')
89
+ if (normalized.split('/').some(segment => segment === '..' || segment === '.')) {
90
+ throw new Error('invalid path: must not contain . or ..')
91
+ }
92
+ return normalized
93
+ }
94
+
95
+ /**
96
+ * Build the POSIX sh script that removes `paths`, in order.
97
+ *
98
+ * Each entry prints an indexed marker before and after its own `rm`, so the
99
+ * client can show which path is on the wire, count settled entries and retry
100
+ * exactly the ones that failed. The script ends with `exit 0` on purpose: one
101
+ * failed path is not a failed batch — the markers own the per-path truth (see
102
+ * `parseDeleteMarker`), and the caller falls back to the per-entry route for
103
+ * whatever they report as FAIL.
104
+ */
105
+ export function batchRemoveScript(paths: string[]): string {
106
+ const lines: string[] = []
107
+ for (let index = 0; index < paths.length; index += 1) {
108
+ const target = shQuote(assertRemovablePath(paths[index]))
109
+ lines.push(`echo 'RV_DEL_ITEM ${index}'`)
110
+ lines.push(`if rm -rf -- ${target}; then echo 'RV_DEL_OK ${index}'; else echo 'RV_DEL_FAIL ${index}'; fi`)
111
+ }
112
+ lines.push('exit 0')
113
+ return lines.join('\n')
114
+ }
115
+
116
+ /**
117
+ * Split one multi-selection into bounded batches, dropping duplicate paths.
118
+ *
119
+ * Order is preserved (markers are index-based within a batch); the inputs are
120
+ * validated here, before anything touches the remote, so an unquotable path
121
+ * rejects the whole delete instead of starting a half-executed batch.
122
+ */
123
+ export function splitBatchRemovePaths(paths: string[]): string[][] {
124
+ const unique: string[] = []
125
+ const seen = new Set<string>()
126
+ for (const path of paths) {
127
+ const normalized = assertRemovablePath(path)
128
+ if (seen.has(normalized)) continue
129
+ seen.add(normalized)
130
+ unique.push(normalized)
131
+ }
132
+ const batches: string[][] = []
133
+ let batch: string[] = []
134
+ for (const path of unique) {
135
+ if (batch.length > 0) {
136
+ const candidate = [...batch, path]
137
+ const bytes = new TextEncoder().encode(batchRemoveScript(candidate)).length
138
+ if (candidate.length > BATCH_REMOVE_MAX_PATHS || bytes > BATCH_REMOVE_MAX_BYTES) {
139
+ batches.push(batch)
140
+ batch = [path]
141
+ continue
142
+ }
143
+ batch = candidate
144
+ continue
145
+ }
146
+ batch = [path]
147
+ }
148
+ if (batch.length > 0) batches.push(batch)
149
+ return batches
150
+ }
151
+
152
+ /**
153
+ * Parse one marker line printed by `batchRemoveScript`.
154
+ *
155
+ * Strict on purpose: remote `rm` diagnostics ("rm: cannot remove …") and a
156
+ * mangled marker must never be mistaken for a settled entry. The index is a
157
+ * plain non-negative integer (no sign, no decimal) because it indexes the
158
+ * batch's path list.
159
+ */
160
+ export function parseDeleteMarker(line: string): { kind: 'item' | 'ok' | 'fail'; index: number } | undefined {
161
+ const match = /^RV_DEL_(ITEM|OK|FAIL) (\d+)$/.exec(line.trim())
162
+ if (match === null) return undefined
163
+ const index = Number(match[2])
164
+ if (!Number.isSafeInteger(index)) return undefined
165
+ const kind = match[1] === 'ITEM' ? 'item' : match[1] === 'OK' ? 'ok' : 'fail'
166
+ return { kind, index }
167
+ }
168
+
50
169
  // Two builders were removed from this file because nothing imported them:
51
170
  // `removeTreeCommand` (`rm -rf -- <path>`) and `statCommand`. Both had live,
52
- // tested counterparts elsewhere — removal goes through the SFTP route
171
+ // tested counterparts elsewhere — removal went through the SFTP route
53
172
  // (`sftp.ts` `removeTree`, which re-reads each child's attributes, refuses a
54
173
  // symlink, and rejects `/`), and stat through `git-format.ts` `statCommand`.
55
- // An unreachable `rm -rf` builder is stale destructive API: `assertAbsPath`
56
- // legitimately accepts `/`, so wiring it up later would put `rm -rf -- /` one
57
- // call away. Re-add it with the same guards as `sftp.ts` if it is ever needed.
174
+ // `batchRemoveScript` above is the deliberate re-add: it only ever builds a
175
+ // bounded, marker-instrumented batch, and `assertRemovablePath` refuses `/` —
176
+ // the old single-path builder had neither guard, which is why it was deleted
177
+ // rather than left one call away from `rm -rf -- /`.
package/src/git-ops.ts CHANGED
@@ -29,6 +29,19 @@ export const GIT_CAP = 2_000_000
29
29
  /** Env prefix: never block on a prompt, never page, never open an editor. */
30
30
  const GIT_ENV = 'GIT_TERMINAL_PROMPT=0 GIT_PAGER=cat GIT_EDITOR=true'
31
31
 
32
+ /**
33
+ * Extra env for the read-only walks the client may ABORT on a workspace switch.
34
+ *
35
+ * `git status` opportunistically refreshes and rewrites the index, which takes
36
+ * `.git/index.lock`; a status killed mid-flight (SIGTERM→SIGKILL after the
37
+ * group-grace) could otherwise leave that lock — or a refreshed index — behind.
38
+ * `GIT_OPTIONAL_LOCKS=0` turns those optional lock-taking steps off, so
39
+ * `rev-parse` / `status` / the branch header stay pure reads and an aborted
40
+ * walk cannot change the repository at all. Required locks of mutating verbs are
41
+ * unaffected (they do not use this constant).
42
+ */
43
+ const GIT_READ_ENV = 'GIT_OPTIONAL_LOCKS=0'
44
+
32
45
  /** `git` pinned to a work dir: no pager, no path quoting, no prompts. */
33
46
  function git(workdir: string): string {
34
47
  return `${GIT_ENV} git --no-pager -C ${shQuote(assertRemoteDir(workdir))} -c core.quotepath=false`
@@ -167,7 +180,7 @@ export function repoProbeDetailCommand(workdir: string): string {
167
180
  // `printf` is last in the pipeline, so the exec route sees success and the
168
181
  // caller can read the REAL git exit code out of the first line.
169
182
  return capped(
170
- `out=$(LC_ALL=C LANG=C ${git(workdir)} rev-parse --show-toplevel 2>&1); rc=$?; printf 'RVS_RC=%s\\n%s\\n' "$rc" "$out"`,
183
+ `out=$(LC_ALL=C LANG=C ${GIT_READ_ENV} ${git(workdir)} rev-parse --show-toplevel 2>&1); rc=$?; printf 'RVS_RC=%s\\n%s\\n' "$rc" "$out"`,
171
184
  )
172
185
  }
173
186
 
@@ -187,7 +200,7 @@ export function repoDiscoveryCommand(root: string): string {
187
200
  * ignored paths one level deep for the tree's greying, under the same bound.
188
201
  */
189
202
  export function statusDetailCommand(workdir: string): string {
190
- return capped(`${git(workdir)} status --porcelain=v1 -z --untracked-files=normal --ignored=matching`)
203
+ return capped(`${GIT_READ_ENV} ${git(workdir)} status --porcelain=v1 -z --untracked-files=normal --ignored=matching`)
191
204
  }
192
205
 
193
206
  /**
@@ -233,7 +246,11 @@ export function statusDirCommand(workdir: string, dir: string): string {
233
246
 
234
247
  /** Branch header only (`## branch...upstream [ahead N, behind M]`), NUL safe. */
235
248
  export function branchHeaderCommand(workdir: string): string {
236
- return capped(`${git(workdir)} status --porcelain=v1 -b -z --untracked-files=no`, 64_000)
249
+ // `LC_ALL=C` is REQUIRED here (unlike the porcelain body): the `## <branch>`
250
+ // header is translated by git, and a non-English remote would otherwise make
251
+ // an empty repository read as a branch literally named "No" (probe: a zh_CN
252
+ // remote answered `## 尚无提交,位于 master`).
253
+ return capped(`LC_ALL=C LANG=C ${GIT_READ_ENV} ${git(workdir)} status --porcelain=v1 -b -z --untracked-files=no`, 64_000)
237
254
  }
238
255
 
239
256
  /** Full message of the current HEAD commit. */
@@ -310,6 +327,40 @@ export function fileAtRevCommand(workdir: string, rev: string, path: string): st
310
327
  return capped(`${git(workdir)} show ${shQuote(spec)}`)
311
328
  }
312
329
 
330
+ /**
331
+ * One inclusive line window of `git blame` for a repo-relative file.
332
+ *
333
+ * The window is part of the command (not a post-filter): blame is one of the
334
+ * reads that can be very expensive on a large file, and the editor only ever
335
+ * needs the lines around the viewport. `--line-porcelain` repeats the commit
336
+ * header for every line, so the parser is stateless (see `blame-model.ts`).
337
+ */
338
+ export function blameCommand(workdir: string, path: string, from: number, to: number): string {
339
+ const start = Number.isFinite(from) ? Math.max(1, Math.floor(from)) : 1
340
+ const end = Number.isFinite(to) ? Math.max(start, Math.floor(to)) : start
341
+ return capped(`${git(workdir)} blame --line-porcelain -L ${start},${end} -- ${shQuote(assertRepoPath(path))}`)
342
+ }
343
+
344
+ /**
345
+ * Commits that touched one file, newest first, with rename following.
346
+ *
347
+ * `--follow` works only for a single path; the format matches `parseLog`, so
348
+ * the existing history row type is reused without a second parser.
349
+ */
350
+ export function fileHistoryCommand(workdir: string, path: string, max = 100): string {
351
+ const count = Math.min(Math.max(Number.isFinite(max) ? Math.floor(max) : 100, 1), 200)
352
+ return capped(
353
+ `${git(workdir)} log --follow --name-status -M --pretty=format:'%x00%H%x1f%P%x1f%an%x1f%ae%x1f%at%x1f%D%x1f%s' -n ${count} -- ${shQuote(assertRepoPath(path))}`,
354
+ )
355
+ }
356
+
357
+ /** One commit's header fields, even when it is older than the log window. */
358
+ export function commitMetaCommand(workdir: string, ref: string): string {
359
+ return capped(
360
+ `${git(workdir)} log -1 --pretty=format:'%H%x1f%P%x1f%an%x1f%ae%x1f%at%x1f%D%x1f%s%x1e' ${assertRef(ref)} --`,
361
+ )
362
+ }
363
+
313
364
  /** Local + remote-tracking branches with their upstream and tip. */
314
365
  export function allBranchesCommand(workdir: string): string {
315
366
  return capped(`${git(workdir)} for-each-ref --format='%(refname:short)%x1f%(objectname:short)%x1f%(upstream:short)%x1f%(HEAD)%x1f%(refname)' refs/heads refs/remotes`)
package/src/http.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  * Small JSON body/response helpers for the /api/dsh-remote route family.
3
3
  */
4
4
  import type { IncomingMessage, OutgoingHttpHeaders, ServerResponse } from 'node:http'
5
- import { drainHostNotices } from './notices.ts'
5
+ import { drainHostNotices, takeHostNotices, type HostNotice } from './notices.ts'
6
6
  import { DeadlineError } from './timeouts.ts'
7
7
 
8
8
  const JSON_HEADERS = {
@@ -96,6 +96,34 @@ function isJsonObject(value: unknown): value is Record<string, unknown> {
96
96
  return typeof value === 'object' && value !== null && !Array.isArray(value)
97
97
  }
98
98
 
99
+ /**
100
+ * The host alias one response is about (consumed by {@link writeJson}).
101
+ *
102
+ * A response may only carry news about the host it concerns, otherwise one
103
+ * window shows another window's silent helper push and the queue loses it for
104
+ * the window that caused it. `null` is the explicit "about no single host"
105
+ * answer (a hosts/workspaces listing): it leaves the queue alone. An untouched
106
+ * response keeps the historical drain-all answer — only this plugin's route
107
+ * table marks its responses, and every route states what it is about.
108
+ */
109
+ const noticeAliasOf = new WeakMap<ServerResponse, string | null>()
110
+
111
+ /** Declare which host the response being written concerns (`null` = no host). */
112
+ export function scopeHostNotices(res: ServerResponse, alias: string | null): void {
113
+ noticeAliasOf.set(res, alias === '' ? null : alias)
114
+ }
115
+
116
+ /** The notices this response may carry and consume. */
117
+ function noticesFor(res: ServerResponse, attachable: boolean, status: number): HostNotice[] {
118
+ // A failed response is never read by the client's notice dispatcher, so
119
+ // draining into it would silently drop the notice; leave it queued for the
120
+ // next successful response about the same host.
121
+ if (!attachable || status >= 400) return []
122
+ if (!noticeAliasOf.has(res)) return drainHostNotices()
123
+ const alias = noticeAliasOf.get(res)
124
+ return typeof alias === 'string' && alias !== '' ? takeHostNotices(alias) : []
125
+ }
126
+
99
127
  /** Write one JSON response. */
100
128
  export function writeJson(
101
129
  res: ServerResponse,
@@ -106,10 +134,13 @@ export function writeJson(
106
134
  // Piggyback Host notices (an automatic helper push happened during this
107
135
  // request) on any plain-object body: the browser's API wrapper renders them
108
136
  // after parsing, so the user learns about the push without opening Settings.
109
- // Arrays and scalars cannot carry extra keys — their notices stay queued for
110
- // the next object response instead of being silently dropped.
137
+ // Only the host-scoped ones ride along (see `scopeHostNotices`): the browser
138
+ // toasts them in the window that made the request, so a critical detail is
139
+ // that the request is about that host. Arrays and scalars cannot carry extra
140
+ // keys — their notices stay queued for the next object response instead of
141
+ // being silently dropped.
111
142
  const attachable = typeof body === 'object' && body !== null && !Array.isArray(body)
112
- const notices = attachable ? drainHostNotices() : []
143
+ const notices = noticesFor(res, attachable, status)
113
144
  const payload = notices.length > 0
114
145
  ? { ...body as Record<string, unknown>, notices }
115
146
  : body
package/src/keygen.ts CHANGED
@@ -22,6 +22,47 @@ export interface BootstrapResult {
22
22
  detail: string
23
23
  }
24
24
 
25
+ /**
26
+ * `type base64` — the only two fields of a `.pub` file that are key material.
27
+ *
28
+ * ssh-keygen appends a free-text comment, and that comment is NOT part of the
29
+ * key. The old code only checked the line's prefix and then spliced the WHOLE
30
+ * line into a single-quoted remote shell command; a garbled or tampered `.pub`
31
+ * therefore reached `sh -c` as code. The strict grammar below admits nothing
32
+ * but the two safe fields, and the comment is regenerated from the alias.
33
+ */
34
+ const PUBLIC_KEY_FIELDS_RE = /^(ssh-ed25519) ([A-Za-z0-9+/]+={0,2})$/
35
+
36
+ /** Ed25519 wire blob: 4-byte length + "ssh-ed25519", 4-byte length + 32 bytes. */
37
+ function isEd25519Blob(blob: string): boolean {
38
+ const decoded = Buffer.from(blob, 'base64')
39
+ if (decoded.length !== 51) return false
40
+ if (decoded.readUInt32BE(0) !== 11) return false
41
+ if (decoded.subarray(4, 15).toString('latin1') !== 'ssh-ed25519') return false
42
+ return decoded.readUInt32BE(15) === 32
43
+ }
44
+
45
+ /**
46
+ * Normalize one `.pub` line to `ssh-ed25519 <base64> dsh-remote-vs/<alias>`.
47
+ *
48
+ * Throws when the line is not a well-formed ed25519 public key, so the caller
49
+ * sees a clear "this file is not a key" error instead of a remote login that
50
+ * fails later. The returned text is the only form that may enter the shell
51
+ * command: its comment is ours, and both remaining fields are shell-inert.
52
+ */
53
+ export function formatPublicKey(raw: string, alias: string): string {
54
+ const fields = raw.trim().split(/\s+/)
55
+ const type = fields[0]
56
+ const blob = fields[1]
57
+ if (fields.length < 2 || type === undefined || blob === undefined || !PUBLIC_KEY_FIELDS_RE.test(`${type} ${blob}`)) {
58
+ throw new Error('expected an "ssh-ed25519 <base64>" public key line')
59
+ }
60
+ if (!isEd25519Blob(blob)) throw new Error('the base64 blob is not a valid ed25519 public key')
61
+ // The comment never matters to sshd; rebuild it from the (already validated)
62
+ // alias so no text from the file can reach the remote command.
63
+ return `${type} ${blob} dsh-remote-vs/${alias.replace(/[^A-Za-z0-9._-]/g, '_')}`
64
+ }
65
+
25
66
  /** Ensure the managed keypair exists; return the private key path. */
26
67
  export async function ensureKeypair(alias: string, dir: string = keysDir()): Promise<{ privatePath: string; publicKey: string }> {
27
68
  ensurePrivateDir(dir)
@@ -41,8 +82,14 @@ export async function ensureKeypair(alias: string, dir: string = keysDir()): Pro
41
82
  // Windows ACLs: ignore.
42
83
  }
43
84
  }
44
- const publicKey = readFileSync(publicPath, 'utf8').trim()
45
- if (!publicKey.startsWith('ssh-ed25519 ')) throw new Error(`unexpected public key format in ${publicPath}`)
85
+ let publicKey: string
86
+ try {
87
+ publicKey = formatPublicKey(readFileSync(publicPath, 'utf8'), alias)
88
+ } catch (error) {
89
+ throw new Error(
90
+ `unexpected public key format in ${publicPath}: ${error instanceof Error ? error.message : String(error)}`,
91
+ )
92
+ }
46
93
  return { privatePath, publicKey }
47
94
  }
48
95
 
@@ -56,11 +103,15 @@ export async function bootstrap(pool: RemotePool, store: RemoteStore, alias: str
56
103
  return { alias, keyPath: entry.auth.keyPath ?? '', flipped: false, detail: 'host already uses key auth' }
57
104
  }
58
105
  const { privatePath, publicKey } = await ensureKeypair(alias)
59
- // Single-line ed25519 key: safe inside single quotes (base64 has no quote chars).
106
+ // `formatPublicKey` reduced the line to type + base64 + our own comment:
107
+ // safe inside single quotes (no quote, whitespace or shell metacharacters).
108
+ // Match on the two KEY FIELDS only: an older/foreign comment on the same key
109
+ // must not cause a duplicate authorized_keys line.
110
+ const keyFields = publicKey.split(' ').slice(0, 2).join(' ')
60
111
  const script = [
61
112
  'mkdir -p ~/.ssh && chmod 700 ~/.ssh',
62
113
  `touch ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys`,
63
- `grep -qxF '${publicKey}' ~/.ssh/authorized_keys 2>/dev/null || echo '${publicKey}' >> ~/.ssh/authorized_keys`,
114
+ `grep -qF '${keyFields}' ~/.ssh/authorized_keys 2>/dev/null || echo '${publicKey}' >> ~/.ssh/authorized_keys`,
64
115
  ].join(' && ')
65
116
  const result = await pool.exec(alias, script, { timeoutMs: 30_000 })
66
117
  if (!result.success) {
package/src/monitor.ts CHANGED
@@ -135,6 +135,19 @@ export class HostMonitor {
135
135
  this.generations.set(alias, (this.generations.get(alias) ?? 0) + 1)
136
136
  }
137
137
 
138
+ /**
139
+ * Snapshots already in the cache, without dialing anything.
140
+ *
141
+ * A GET must not have a dial side effect: listing what the Host knows is the
142
+ * read-only shape, and only an explicit per-host request (or the opt-in batch
143
+ * flag) may wake a sleeping host.
144
+ */
145
+ cached(): RemoteHostMetrics[] {
146
+ return [...this.cache.values()]
147
+ .map(entry => entry.snapshot)
148
+ .sort((left, right) => left.alias.localeCompare(right.alias))
149
+ }
150
+
138
151
  private async probe(alias: string): Promise<RemoteHostMetrics> {
139
152
  const generation = this.generations.get(alias) ?? 0
140
153
  const startedAt = this.now()
package/src/notices.ts CHANGED
@@ -28,7 +28,29 @@ export function pushHostNotice(notice: HostNotice): void {
28
28
  pending = [...pending, notice]
29
29
  }
30
30
 
31
- /** Take everything queued; the caller attaches it and the queue starts over. */
31
+ /**
32
+ * Take the notices queued for ONE host alias.
33
+ *
34
+ * A response only reports news about the host it is about. Draining the whole
35
+ * queue from whichever response was written first delivered host A's helper
36
+ * push into a window looking at host B — and consumed it, so A never saw it.
37
+ * Notices for other aliases stay queued for a response about their host.
38
+ */
39
+ export function takeHostNotices(alias: string): HostNotice[] {
40
+ if (pending.length === 0) return []
41
+ const taken = pending.filter(notice => notice.alias === alias)
42
+ if (taken.length === 0) return []
43
+ pending = pending.filter(notice => notice.alias !== alias)
44
+ return taken
45
+ }
46
+
47
+ /**
48
+ * Take everything queued (no host filtering).
49
+ *
50
+ * Kept for callers that own the whole queue — the offline probes reset it, and
51
+ * a response written OUTSIDE the route table has no host to filter by
52
+ * (`src/http.ts` keeps that historical drain-all answer).
53
+ */
32
54
  export function drainHostNotices(): HostNotice[] {
33
55
  if (pending.length === 0) return []
34
56
  const drained = pending