dsh-remote-vs 0.13.0 → 0.15.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.
Files changed (128) hide show
  1. package/README.en.md +455 -443
  2. package/README.md +408 -396
  3. package/lib/client.js +8062 -2651
  4. package/lib/index.js +1058 -288
  5. package/lib/p2-router-fs.js +1 -1
  6. package/lib/p2-router-refs.js +89 -10
  7. package/lib/p2-router-spill.js +73 -1
  8. package/lib/p2-router-subprocess.js +18 -6
  9. package/lib/spill-retention-BwKEWrl5.js +115 -0
  10. package/lib/{ssh-proc-arI5lm4W.js → ssh-proc-VKWn_LZC.js} +17 -0
  11. package/lib/types/archive.d.ts +1 -1
  12. package/lib/types/changes/recorder.d.ts +34 -2
  13. package/lib/types/client/CodeEditor.d.ts +12 -0
  14. package/lib/types/client/ConnectionStatus.d.ts +17 -0
  15. package/lib/types/client/DirectoryFlow.d.ts +2 -0
  16. package/lib/types/client/DoctorPanel.d.ts +25 -0
  17. package/lib/types/client/QuickOpen.d.ts +17 -0
  18. package/lib/types/client/RemoteExplorer.d.ts +192 -1
  19. package/lib/types/client/RemoteRoot.d.ts +17 -0
  20. package/lib/types/client/SearchView.d.ts +55 -0
  21. package/lib/types/client/TerminalView.d.ts +38 -0
  22. package/lib/types/client/WorkspaceWizard.d.ts +17 -0
  23. package/lib/types/client/api.d.ts +54 -4
  24. package/lib/types/client/changes/undo-affordance.d.ts +16 -0
  25. package/lib/types/client/changes/undo-context.d.ts +14 -18
  26. package/lib/types/client/changes/undo-target.d.ts +78 -0
  27. package/lib/types/client/connection.d.ts +111 -0
  28. package/lib/types/client/doctor.d.ts +122 -0
  29. package/lib/types/client/download.d.ts +35 -5
  30. package/lib/types/client/downloads.d.ts +18 -1
  31. package/lib/types/client/file-open-probe.d.ts +64 -0
  32. package/lib/types/client/i18n.d.ts +1 -1
  33. package/lib/types/client/quickopen-model.d.ts +332 -0
  34. package/lib/types/client/scm/DiffView.d.ts +34 -0
  35. package/lib/types/client/scm/actions.d.ts +18 -0
  36. package/lib/types/client/scm/diff-model.d.ts +17 -1
  37. package/lib/types/client/scm/git-cache.d.ts +10 -2
  38. package/lib/types/client/scm/read-queue.d.ts +2 -1
  39. package/lib/types/client/scm/stage-queue.d.ts +13 -0
  40. package/lib/types/client/scm/status-map.d.ts +3 -1
  41. package/lib/types/client/store.d.ts +114 -5
  42. package/lib/types/client/vsc/FindWidget.d.ts +7 -0
  43. package/lib/types/client/vsc/save-shortcut.d.ts +57 -0
  44. package/lib/types/deploy.d.ts +44 -2
  45. package/lib/types/git-format.d.ts +15 -0
  46. package/lib/types/http.d.ts +44 -0
  47. package/lib/types/p2/file-refs.d.ts +39 -2
  48. package/lib/types/p2/helper-rpc.d.ts +26 -0
  49. package/lib/types/p2/router-spill.d.ts +19 -0
  50. package/lib/types/p2/router-subprocess.d.ts +2 -0
  51. package/lib/types/p2/spill-retention.d.ts +74 -0
  52. package/lib/types/p2/worlds.d.ts +11 -0
  53. package/lib/types/pool.d.ts +73 -11
  54. package/lib/types/protocol.d.ts +63 -0
  55. package/lib/types/routes.d.ts +18 -0
  56. package/lib/types/sftp.d.ts +114 -8
  57. package/lib/types/store.d.ts +34 -0
  58. package/lib/types/timeouts.d.ts +14 -0
  59. package/lib/{worlds-C6Xha1mQ.js → worlds-Be1YE2Ot.js} +727 -78
  60. package/package.json +1 -1
  61. package/src/archive.ts +41 -9
  62. package/src/changes/recorder.ts +227 -31
  63. package/src/changes/status.ts +37 -1
  64. package/src/client/CodeEditor.tsx +84 -2
  65. package/src/client/ConnectionStatus.tsx +130 -0
  66. package/src/client/DirectoryFlow.tsx +40 -5
  67. package/src/client/DoctorPanel.tsx +202 -0
  68. package/src/client/DownloadDock.tsx +13 -25
  69. package/src/client/EditorPane.tsx +291 -7
  70. package/src/client/HostsView.tsx +17 -8
  71. package/src/client/QuickOpen.tsx +371 -0
  72. package/src/client/RemoteDirectoryPicker.tsx +54 -3
  73. package/src/client/RemoteExplorer.tsx +879 -160
  74. package/src/client/RemoteRoot.tsx +178 -1
  75. package/src/client/SearchView.tsx +180 -6
  76. package/src/client/SettingsHosts.tsx +1 -1
  77. package/src/client/TerminalView.tsx +174 -9
  78. package/src/client/WorkspaceWizard.tsx +110 -16
  79. package/src/client/WorkspacesView.tsx +22 -6
  80. package/src/client/api.ts +197 -11
  81. package/src/client/changes/ChangesDock.tsx +35 -8
  82. package/src/client/changes/undo-affordance.ts +33 -0
  83. package/src/client/changes/undo-context.ts +14 -18
  84. package/src/client/changes/undo-target.ts +139 -0
  85. package/src/client/connection.ts +264 -0
  86. package/src/client/doctor.ts +441 -0
  87. package/src/client/download.ts +148 -12
  88. package/src/client/downloads.ts +43 -2
  89. package/src/client/file-open-probe.ts +83 -0
  90. package/src/client/i18n.ts +244 -0
  91. package/src/client/index.tsx +5 -2
  92. package/src/client/quickopen-model.ts +778 -0
  93. package/src/client/remote-file-open.ts +21 -33
  94. package/src/client/scm/DiffView.tsx +116 -6
  95. package/src/client/scm/ScmPanel.tsx +19 -0
  96. package/src/client/scm/actions.ts +34 -2
  97. package/src/client/scm/diff-model.ts +33 -37
  98. package/src/client/scm/git-cache.ts +61 -4
  99. package/src/client/scm/read-queue.ts +33 -2
  100. package/src/client/scm/stage-queue.ts +72 -1
  101. package/src/client/scm/status-map.ts +22 -1
  102. package/src/client/store.tsx +704 -21
  103. package/src/client/vsc/FindWidget.tsx +20 -0
  104. package/src/client/vsc/kit.tsx +115 -6
  105. package/src/client/vsc/reveal-line.ts +33 -14
  106. package/src/client/vsc/save-shortcut.ts +131 -0
  107. package/src/client/vsc/vsc.css +419 -0
  108. package/src/deploy.ts +185 -33
  109. package/src/git-format.ts +136 -22
  110. package/src/git-ops.ts +14 -6
  111. package/src/http.ts +80 -12
  112. package/src/importers.ts +80 -21
  113. package/src/index.ts +21 -1
  114. package/src/p2/file-refs.ts +112 -10
  115. package/src/p2/helper-rpc.ts +73 -36
  116. package/src/p2/router-spill.ts +96 -1
  117. package/src/p2/router-subprocess.ts +18 -5
  118. package/src/p2/spill-retention.ts +134 -0
  119. package/src/p2/ssh-proc.ts +22 -0
  120. package/src/p2/worlds.ts +24 -0
  121. package/src/pool.ts +329 -47
  122. package/src/protocol.ts +66 -0
  123. package/src/routes.ts +251 -43
  124. package/src/sftp.ts +486 -26
  125. package/src/store.ts +207 -85
  126. package/src/terminal.ts +38 -2
  127. package/src/timeouts.ts +14 -0
  128. package/src/tools.ts +14 -5
package/src/deploy.ts CHANGED
@@ -9,8 +9,8 @@
9
9
  * probe-bundle marker (P0 behavior).
10
10
  */
11
11
  import { createHash } from 'node:crypto'
12
- import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync } from 'node:fs'
13
- import { dirname, join } from 'node:path'
12
+ import { copyFileSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, rmSync } from 'node:fs'
13
+ import { dirname, join, posix, resolve, sep } from 'node:path'
14
14
  import { fileURLToPath } from 'node:url'
15
15
  import type { RemotePool } from './pool.ts'
16
16
  import { RemoteFiles } from './sftp.ts'
@@ -109,6 +109,49 @@ export interface HelperCacheEntry {
109
109
 
110
110
  const HEX64 = /^[0-9a-f]{64}$/
111
111
 
112
+ /**
113
+ * Charset for a cached helper version.
114
+ *
115
+ * The version reaches a REMOTE shell line and remote directory names, so it is
116
+ * not "just metadata": the sidecar in the cache directory (or a vendored copy
117
+ * seeded into it) could otherwise smuggle `'`/`;` into the install script.
118
+ * `-` is allowed only after the first character so the value cannot look like a
119
+ * command-line option.
120
+ */
121
+ const HELPER_VERSION_RE = /^[0-9A-Za-z][0-9A-Za-z._-]{0,63}$/
122
+
123
+ /** Platforms `mapPlatform()` can produce; a cache entry must name one of them. */
124
+ const HELPER_PLATFORMS = new Set(['linux-x64', 'linux-arm64', 'macos-x64', 'macos-arm64'])
125
+
126
+ /** Wire protocol this plugin's `dsh-ssh` generation speaks (see MAINTENANCE §2.7). */
127
+ export const EXPECTED_HELPER_PROTOCOL = 2
128
+
129
+ /** Resolve one cached tarball, or `undefined` when the name escapes the cache dir. */
130
+ function safeHelperTarball(dir: string, tarball: unknown): string | undefined {
131
+ if (typeof tarball !== 'string' || tarball === '' || tarball === '.' || tarball === '..') return undefined
132
+ // Same-directory plain file name only: both separators are rejected (on
133
+ // Windows `a\b` is a path separator too, not part of the name).
134
+ if (tarball.includes('/') || tarball.includes('\\')) return undefined
135
+ if (posix.basename(tarball) !== tarball) return undefined
136
+ const root = resolve(dir)
137
+ const full = resolve(root, tarball)
138
+ if (full !== join(root, tarball) || !full.startsWith(root + sep)) return undefined
139
+ try {
140
+ // lstat, not stat: a symlink in the cache dir must not turn the upload into
141
+ // "copy any file on this machine to the remote host".
142
+ return lstatSync(full).isFile() ? full : undefined
143
+ } catch {
144
+ return undefined
145
+ }
146
+ }
147
+
148
+ /** Absolute path of one cached helper tarball; throws when it is not inside the cache. */
149
+ export function helperTarballPath(helper: HelperCacheEntry, dir: string = helpersDir()): string {
150
+ const path = safeHelperTarball(dir, helper.tarball)
151
+ if (path === undefined) throw new Error(`invalid helper tarball path: ${helper.tarball}`)
152
+ return path
153
+ }
154
+
112
155
  /** Scan the local helper cache; invalid/incomplete entries are skipped. */
113
156
  export function listCachedHelpers(dir: string = helpersDir()): HelperCacheEntry[] {
114
157
  let names: string[]
@@ -128,32 +171,78 @@ export function listCachedHelpers(dir: string = helpersDir()): HelperCacheEntry[
128
171
  const tarball = raw.tarball
129
172
  const tarballSha256 = raw.tarballSha256
130
173
  const binarySha256 = raw.binarySha256
131
- if (typeof version !== 'string' || version === '') continue
132
- if (typeof platform !== 'string' || platform === '') continue
133
- if (typeof tarball !== 'string' || !existsSync(join(dir, tarball))) continue
174
+ const protocol = raw.protocol
175
+ if (typeof version !== 'string' || !HELPER_VERSION_RE.test(version)) continue
176
+ if (typeof platform !== 'string' || !HELPER_PLATFORMS.has(platform)) continue
177
+ if (safeHelperTarball(dir, tarball) === undefined) continue
134
178
  if (typeof tarballSha256 !== 'string' || !HEX64.test(tarballSha256)) continue
135
179
  if (typeof binarySha256 !== 'string' || !HEX64.test(binarySha256)) continue
180
+ if (typeof protocol !== 'number' || !Number.isInteger(protocol) || protocol <= 0) continue
136
181
  entries.push({
137
182
  kind: 'executable',
138
183
  version,
139
184
  platform,
140
- tarball,
185
+ tarball: tarball as string,
141
186
  tarballSha256,
142
187
  binarySha256,
143
- protocol: typeof raw.protocol === 'number' ? raw.protocol : 0,
188
+ protocol,
144
189
  nodeVersion: typeof raw.nodeVersion === 'string' ? raw.nodeVersion : '',
145
190
  })
146
191
  } catch {
147
192
  // Corrupt sidecar: skip.
148
193
  }
149
194
  }
150
- entries.sort((a, b) => (a.version < b.version ? 1 : a.version > b.version ? -1 : 0))
195
+ entries.sort(compareHelperVersionsDesc)
151
196
  return entries
152
197
  }
153
198
 
154
- /** Pick a cached build for a platform (exact version pin or newest). */
155
- export function pickCached(platform: string, version?: string): HelperCacheEntry | undefined {
156
- const matches = listCachedHelpers().filter(h => h.platform === platform)
199
+ /**
200
+ * SemVer-ish comparison for cached helper versions.
201
+ *
202
+ * A plain string compare picked `0.9.0` over `0.10.0` (multi-digit segments sort
203
+ * wrong: `9` > `10`) and the pipeline then pushed an OLD helper as "ok". Numeric
204
+ * segments compare as numbers, everything else lexicographically; a shorter
205
+ * version loses to its own extension (`0.2` < `0.2.1`) and a numeric segment wins
206
+ * over a pre-release one (`0.2.1` > `0.2.1-alpha.2`).
207
+ */
208
+ export function compareHelperVersions(left: string, right: string): number {
209
+ const split = (value: string): string[] => value.split(/[.+-]/)
210
+ const a = split(left)
211
+ const b = split(right)
212
+ for (let index = 0; index < Math.max(a.length, b.length); index += 1) {
213
+ const x = a[index]
214
+ const y = b[index]
215
+ // One side ran out of segments: its extra segments decide whether the other
216
+ // side is a release (`1.2.3` > `1.2.3-rc.1`) or a deeper version (`1.2` < `1.2.1`).
217
+ if (x === undefined) return y !== undefined && /^\d+$/.test(y) ? -1 : 1
218
+ if (y === undefined) return x !== undefined && /^\d+$/.test(x) ? 1 : -1
219
+ const nx = /^\d+$/.test(x) ? Number(x) : undefined
220
+ const ny = /^\d+$/.test(y) ? Number(y) : undefined
221
+ if (nx !== undefined && ny !== undefined) {
222
+ if (nx !== ny) return nx < ny ? -1 : 1
223
+ continue
224
+ }
225
+ if (nx !== undefined) return -1
226
+ if (ny !== undefined) return 1
227
+ if (x !== y) return x < y ? -1 : 1
228
+ }
229
+ return 0
230
+ }
231
+
232
+ /** Newest first (Array.prototype.sort comparator). */
233
+ function compareHelperVersionsDesc(a: HelperCacheEntry, b: HelperCacheEntry): number {
234
+ return compareHelperVersions(b.version, a.version)
235
+ }
236
+
237
+ /**
238
+ * Pick a cached build for a platform (exact version pin or newest).
239
+ *
240
+ * `expectedProtocol` (default: this plugin's wire protocol) is part of the
241
+ * choice: a cached build whose protocol does not match would install fine and
242
+ * then fail the runtime handshake, so it is not a candidate at all.
243
+ */
244
+ export function pickCached(platform: string, version?: string, expectedProtocol: number = EXPECTED_HELPER_PROTOCOL): HelperCacheEntry | undefined {
245
+ const matches = listCachedHelpers().filter(h => h.platform === platform && h.protocol === expectedProtocol)
157
246
  if (version !== undefined && version !== '') return matches.find(h => h.version === version)
158
247
  return matches[0]
159
248
  }
@@ -402,6 +491,51 @@ async function pushProbeBundle(
402
491
  }
403
492
  }
404
493
 
494
+ /** Paths of one helper install attempt (absolute, probe-derived + whitelisted version). */
495
+ export interface HelperInstallPaths {
496
+ root: string
497
+ verDir: string
498
+ tmpFile: string
499
+ }
500
+
501
+ /**
502
+ * Remote shell steps installing one cached helper.
503
+ *
504
+ * Invariant: the currently installed version is never deleted before the new one
505
+ * is fully extracted — the old dir is renamed to `.old` and removed only after
506
+ * the swap, and a crash between "old moved away" and "new moved in" is repaired
507
+ * by the recovery step (restore `.old` when the live dir is missing). Every path
508
+ * goes through `shRoot`; the tarball name embedded in the sha256 line is quoted
509
+ * too (the caller's version already passed `HELPER_VERSION_RE`, so it cannot
510
+ * break out of the shell any more).
511
+ *
512
+ * Pure string work (no fs/pool) so a gate can pin the ORDER without a remote.
513
+ */
514
+ export function helperInstallSteps(helper: HelperCacheEntry, paths: HelperInstallPaths): string[] {
515
+ const { root, verDir, tmpFile } = paths
516
+ return [
517
+ `cd ${shRoot(root)}`,
518
+ `echo ${shRoot(`${helper.tarballSha256} ${posix.basename(tmpFile)}`)} | sha256sum -c --status -`,
519
+ // A previous attempt may have died between "old moved away" and "new moved in".
520
+ `if [ ! -d ${shRoot(verDir)} ] && [ -d ${shRoot(verDir + '.old')} ]; then mv ${shRoot(verDir + '.old')} ${shRoot(verDir)}; fi`,
521
+ `rm -rf ${shRoot(verDir + '.next')}`,
522
+ `mkdir -p ${shRoot(verDir + '.next')}`,
523
+ `tar -xzf ${shRoot(tmpFile)} -C ${shRoot(verDir + '.next')} --strip-components=1`,
524
+ `rm -f ${shRoot(tmpFile)}`,
525
+ // Swap: old version survives as `.old` until the new one is in place.
526
+ `rm -rf ${shRoot(verDir + '.old')}`,
527
+ `if [ -d ${shRoot(verDir)} ]; then mv ${shRoot(verDir)} ${shRoot(verDir + '.old')}; fi`,
528
+ `mv ${shRoot(verDir + '.next')} ${shRoot(verDir)}`,
529
+ `rm -rf ${shRoot(verDir + '.old')}`,
530
+ `echo "RV_DIGEST=$(sha256sum ${shRoot(verDir + '/dsh-ssh-helper')} | cut -d' ' -f1)"`,
531
+ ]
532
+ }
533
+
534
+ /** One POSIX shell line: steps joined so any failure stops the sequence. */
535
+ export function helperInstallScript(helper: HelperCacheEntry, paths: HelperInstallPaths): string {
536
+ return helperInstallSteps(helper, paths).join(' && ')
537
+ }
538
+
405
539
  /** P1 path: push a cached helper tarball, verify, extract, manifest. */
406
540
  async function pushHelper(
407
541
  pool: RemotePool,
@@ -427,34 +561,31 @@ async function pushHelper(
427
561
  return { alias, probe: probed, action: 'skipped-same', previous, installed: previous, detail }
428
562
  }
429
563
  const root = `${home}/.dsh-helpers`
430
- const verDir = `${root}/dsh-ssh-helper-${helper.version}-${helper.platform}`
431
- const tmpFile = `${root}/.tmp-${helper.version}-${Date.now()}.tar.gz`
564
+ const manifestPath = `${root}/manifest.json`
565
+ const manifestNext = `${root}/manifest.json.next`
566
+ const paths: HelperInstallPaths = {
567
+ root,
568
+ verDir: `${root}/dsh-ssh-helper-${helper.version}-${helper.platform}`,
569
+ tmpFile: `${root}/.tmp-${helper.version}-${Date.now()}.tar.gz`,
570
+ }
432
571
  try {
433
572
  const files = new RemoteFiles(pool)
434
573
  await files.mkdir(alias, root)
435
574
  // 1. Upload (host streams the local tarball over SFTP; the browser never touches bytes).
436
- await pool.putFile(alias, join(helpersDir(), helper.tarball), tmpFile)
437
- // 2. Verify + extract atomically-ish (fresh dir, then swap by rename).
438
- const install = [
439
- `cd ${shRoot(root)}`,
440
- `echo '${helper.tarballSha256} ${tmpFile.split('/').pop() as string}' | sha256sum -c --status -`,
441
- `rm -rf ${shRoot(verDir + '.new')} ${shRoot(verDir)}`,
442
- `mkdir -p ${shRoot(verDir + '.new')}`,
443
- `tar -xzf ${shRoot(tmpFile)} -C ${shRoot(verDir + '.new')} --strip-components=1`,
444
- `rm -f ${shRoot(tmpFile)}`,
445
- `mv ${shRoot(verDir + '.new')} ${shRoot(verDir)}`,
446
- `echo "RV_DIGEST=$(sha256sum ${shRoot(verDir + '/dsh-ssh-helper')} | cut -d' ' -f1)"`,
447
- ].join(' && ')
448
- const installed = await pool.exec(alias, install, { timeoutMs: 180_000 })
449
- if (!installed.success) {
450
- throw new Error(`remote install failed [exit code: ${installed.exitCode}]: ${installed.stderr || installed.stdout || installed.error || 'unknown'}`)
575
+ await pool.putFile(alias, helperTarballPath(helper), paths.tmpFile)
576
+ // 2. Verify + extract + swap with the old version kept until the new one is in.
577
+ const installedRun = await pool.exec(alias, helperInstallScript(helper, paths), { timeoutMs: 180_000 })
578
+ if (!installedRun.success) {
579
+ throw new Error(`remote install failed [exit code: ${installedRun.exitCode}]: ${installedRun.stderr || installedRun.stdout || installedRun.error || 'unknown'}`)
451
580
  }
452
- const digestMatch = /^RV_DIGEST=([0-9a-fA-F]{64})$/m.exec(installed.stdout)
581
+ const digestMatch = /^RV_DIGEST=([0-9a-fA-F]{64})$/m.exec(installedRun.stdout)
453
582
  const digest = digestMatch !== null ? (digestMatch[1] as string).toLowerCase() : ''
454
583
  if (digest === '' || digest !== helper.binarySha256) {
455
584
  throw new Error(`binary digest mismatch after extract: got ${digest || '(unparsed)'} want ${helper.binarySha256}`)
456
585
  }
457
- // 3. Write our manifest (official manifest.json ships inside verDir).
586
+ // 3. Write our manifest next to the live one, then rename it into place, so a
587
+ // crashed push cannot leave a half-written manifest.json (official
588
+ // manifest.json ships inside verDir).
458
589
  const manifest: RemoteManifest = {
459
590
  version: 1,
460
591
  artifact,
@@ -462,19 +593,40 @@ async function pushHelper(
462
593
  helper: helperRef,
463
594
  installedAt: Date.now(),
464
595
  }
465
- await files.write(alias, `${root}/manifest.json`, JSON.stringify(manifest, null, 2) + '\n')
596
+ await files.write(alias, manifestNext, JSON.stringify(manifest, null, 2) + '\n')
597
+ const renamed = await pool.exec(alias, `mv ${shRoot(manifestNext)} ${shRoot(manifestPath)}`, { timeoutMs: 15_000 })
598
+ if (!renamed.success) {
599
+ throw new Error(`manifest rename failed [exit code: ${renamed.exitCode}]: ${renamed.stderr || renamed.error || 'unknown'}`)
600
+ }
466
601
  const detail = `pushed ${artifact} (${helper.platform}, bin ${helper.binarySha256.slice(0, 12)}…) in ${Date.now() - started} ms`
467
602
  store.setDeploy(alias, { status: 'ok', artifact, manifestHash: hash, home, helper: helperRef, detail, at: Date.now() })
468
603
  return { alias, probe: probed, action: 'pushed', previous, installed: manifest, detail }
469
604
  } catch (error) {
470
605
  const detail = `push failed: ${error instanceof Error ? error.message : String(error)}`
471
606
  store.setDeploy(alias, failedState(store, alias, artifact, detail))
472
- await pool.exec(alias, `rm -f ${shRoot(tmpFile)}; rm -rf ${shRoot(verDir + '.new')}`, { timeoutMs: 15_000 }).catch(() => undefined)
607
+ // Keep the live helper dir and any `.old` backup: a failed push must not
608
+ // leave the host without the version it already had. If the swap died
609
+ // between `mv live .old` and `mv next live`, the backup is moved back here
610
+ // (P2-N4: the install script's own recovery line only runs on the NEXT push,
611
+ // which can be minutes away under the retry backoff).
612
+ const cleanup = [
613
+ `rm -f ${shRoot(paths.tmpFile)}`,
614
+ `rm -rf ${shRoot(paths.verDir + '.next')}`,
615
+ `rm -f ${shRoot(manifestNext)}`,
616
+ `if [ ! -d ${shRoot(paths.verDir)} ] && [ -d ${shRoot(paths.verDir + '.old')} ]; then mv ${shRoot(paths.verDir + '.old')} ${shRoot(paths.verDir)}; fi`,
617
+ ].join('; ')
618
+ await pool.exec(alias, cleanup, { timeoutMs: 15_000 }).catch(() => undefined)
473
619
  return { alias, probe: probed, action: 'failed', previous, installed: null, detail }
474
620
  }
475
621
  }
476
622
 
477
- /** Single-quote a remote path for sh (paths here are probe-derived + fixed names). */
623
+ /**
624
+ * Single-quote a remote path for sh.
625
+ *
626
+ * Paths are probe-derived, but the version/platform segments come from a cache
627
+ * sidecar: they pass `HELPER_VERSION_RE`/`HELPER_PLATFORMS` before ever reaching
628
+ * this function, so the quoting here is the second layer, not the only one.
629
+ */
478
630
  function shRoot(path: string): string {
479
631
  if (path.includes('\0')) throw new Error('invalid path')
480
632
  return `'${path.replace(/'/g, `'\\''`)}'`
package/src/git-format.ts CHANGED
@@ -107,29 +107,145 @@ export function gitFailed(stderr: string): string | undefined {
107
107
 
108
108
  // ------------------------------------------------------------- parsers
109
109
 
110
+ /**
111
+ * Parse the `-b` header line of `status --porcelain=v1`.
112
+ *
113
+ * The branch name runs up to the first whitespace or the `...` upstream
114
+ * separator — NOT through a character class that excludes dots. `release.1.2026`,
115
+ * `v1.2.3` and `feature/x.y` are ordinary branch names, and stopping at the
116
+ * first `.` also left the `...upstream` part and the `[ahead/behind]` block
117
+ * unmatched, so ahead/behind silently stayed 0 for those branches.
118
+ *
119
+ * Shapes git emits (all of them are covered here):
120
+ * ## main
121
+ * ## main...origin/main
122
+ * ## main...origin/main [ahead 1, behind 2]
123
+ * ## main...origin/main [gone]
124
+ * ## HEAD (no branch) (detached HEAD)
125
+ * ## No commits yet on master (empty repository)
126
+ */
127
+ function parseStatusHead(head: string): { branch: string; detached: boolean; ahead: number; behind: number } {
128
+ if (!head.startsWith('## ')) return { branch: '', detached: false, ahead: 0, behind: 0 }
129
+ let rest = head.slice(3)
130
+ let counts = ''
131
+ const bracket = /^(.*?) \[([^\]]*)\]$/.exec(rest)
132
+ if (bracket !== null) {
133
+ rest = bracket[1] as string
134
+ counts = bracket[2] as string
135
+ }
136
+ // `[ahead 1]`, `[behind 2]`, `[ahead 1, behind 2]` and `[gone]` (no counts at
137
+ // all). Any other token in the block is ignored on purpose, exactly like git's
138
+ // own extra flags.
139
+ const aheadMatch = /(?:^|, )ahead (\d+)/.exec(counts)
140
+ const behindMatch = /(?:^|, )behind (\d+)/.exec(counts)
141
+ const ahead = aheadMatch === null ? 0 : Number(aheadMatch[1])
142
+ const behind = behindMatch === null ? 0 : Number(behindMatch[1])
143
+ const noCommits = /^No commits yet on (\S+)$/.exec(rest)
144
+ if (noCommits !== null) return { branch: noCommits[1] as string, detached: false, ahead, behind }
145
+ if (rest === 'HEAD (no branch)') return { branch: 'HEAD (detached)', detached: true, ahead: 0, behind: 0 }
146
+ // A refname cannot contain `..`, so the first `...` is always the separator.
147
+ const name = rest.split('...')[0] as string
148
+ if (name === 'HEAD') return { branch: 'HEAD (detached)', detached: true, ahead: 0, behind: 0 }
149
+ return { branch: name, detached: false, ahead, behind }
150
+ }
151
+
152
+ /**
153
+ * Reverse git's C-style quoting of one porcelain path.
154
+ *
155
+ * `git status --porcelain` (without `-z`) quotes any path containing whitespace,
156
+ * a quote, a backslash or a control character, and escapes the specials inside:
157
+ * `"a\"b.txt"`, `"plain space.txt"`, `"ctl\001name.txt"`. Passing that field on
158
+ * as if it were the path made every such file unusable in the SCM panel
159
+ * (open/diff/stage asked for a literal filename with quotes in it) — and a space
160
+ * in a name is common, not an exotic edge (2026-10 audit, A18-b).
161
+ *
162
+ * Unquoted input is returned unchanged. Octal escapes are decoded as BYTES and
163
+ * only then interpreted as UTF-8: a multi-byte character can arrive as several
164
+ * `\NNN` escapes and failing to group them would corrupt it.
165
+ */
166
+ export function unquoteGitPath(path: string): string {
167
+ if (path.length < 2 || !path.startsWith('"') || !path.endsWith('"')) return path
168
+ const body = path.slice(1, -1)
169
+ let out = ''
170
+ let bytes: number[] = []
171
+ const flushBytes = (): void => {
172
+ if (bytes.length === 0) return
173
+ // `TextDecoder` exists in both halves (browser bundle + Node), unlike Buffer.
174
+ out += new TextDecoder().decode(Uint8Array.from(bytes))
175
+ bytes = []
176
+ }
177
+ for (let index = 0; index < body.length; index += 1) {
178
+ const char = body[index] as string
179
+ if (char !== '\\') {
180
+ flushBytes()
181
+ out += char
182
+ continue
183
+ }
184
+ const escaped = body[index + 1]
185
+ if (escaped === undefined) {
186
+ flushBytes()
187
+ out += '\\'
188
+ break
189
+ }
190
+ index += 1
191
+ switch (escaped) {
192
+ case 'a': flushBytes(); out += '\x07'; break
193
+ case 'b': flushBytes(); out += '\b'; break
194
+ case 'f': flushBytes(); out += '\f'; break
195
+ case 'n': flushBytes(); out += '\n'; break
196
+ case 'r': flushBytes(); out += '\r'; break
197
+ case 't': flushBytes(); out += '\t'; break
198
+ case 'v': flushBytes(); out += '\v'; break
199
+ case '"': flushBytes(); out += '"'; break
200
+ case '\\': flushBytes(); out += '\\'; break
201
+ default: {
202
+ const octal = /^[0-7]{1,3}/.exec(body.slice(index))?.[0]
203
+ if (octal === undefined) {
204
+ flushBytes()
205
+ out += escaped
206
+ break
207
+ }
208
+ bytes.push(Number.parseInt(octal, 8))
209
+ index += octal.length - 1
210
+ }
211
+ }
212
+ }
213
+ flushBytes()
214
+ return out
215
+ }
216
+
217
+ /**
218
+ * The path of one porcelain row (`XY PATH`, or `XY OLD -> NEW` for renames).
219
+ *
220
+ * Each side is quoted independently, so a rename may mix quoted and plain names.
221
+ * A quoted name can itself contain ` -> `, hence the closing quote is located
222
+ * before looking for the arrow (an unquoted name containing the same bytes keeps
223
+ * the old, ambiguous behaviour — unchanged by this fix).
224
+ */
225
+ function statusRowPath(raw: string): string {
226
+ if (raw.startsWith('"')) {
227
+ let index = 1
228
+ while (index < raw.length) {
229
+ if (raw[index] === '\\') {
230
+ index += 2
231
+ continue
232
+ }
233
+ if (raw[index] === '"') break
234
+ index += 1
235
+ }
236
+ const rest = raw.slice(index + 1)
237
+ const arrow = rest.indexOf(' -> ')
238
+ return unquoteGitPath(arrow >= 0 ? rest.slice(arrow + 4).trim() : raw)
239
+ }
240
+ const arrow = raw.indexOf(' -> ')
241
+ return unquoteGitPath(arrow >= 0 ? raw.slice(arrow + 4) : raw)
242
+ }
243
+
110
244
  /** Parse `status --porcelain=v1 -b` into branch + file rows. */
111
245
  export function parseStatus(stdout: string): GitStatus {
112
246
  const lines = stdout.split('\n')
113
247
  const head = lines[0] ?? ''
114
- let branch = ''
115
- let detached = false
116
- let ahead = 0
117
- let behind = 0
118
- const branchMatch = /^## ([^\s.]+(?:\.\.\.[^\s[]+)?)(?: \[(?:ahead (\d+))?(?:, )?(?:behind (\d+))?\])?/.exec(head)
119
- if (branchMatch !== null) {
120
- const name = branchMatch[1] as string
121
- if (name === 'HEAD' || name.startsWith('HEAD ')) {
122
- detached = true
123
- branch = 'HEAD (detached)'
124
- } else {
125
- branch = name.includes('...') ? (name.split('...')[0] as string) : name
126
- }
127
- ahead = branchMatch[2] !== undefined ? Number(branchMatch[2]) : 0
128
- behind = branchMatch[3] !== undefined ? Number(branchMatch[3]) : 0
129
- } else if (head.startsWith('## HEAD (no branch')) {
130
- detached = true
131
- branch = 'HEAD (detached)'
132
- }
248
+ const { branch, detached, ahead, behind } = parseStatusHead(head)
133
249
  const staged: GitStatus['staged'] = []
134
250
  const unstaged: GitStatus['unstaged'] = []
135
251
  const untracked: string[] = []
@@ -139,9 +255,7 @@ export function parseStatus(stdout: string): GitStatus {
139
255
  if (line.length < 4) continue
140
256
  const x = line[0] as string
141
257
  const y = line[1] as string
142
- let path = line.slice(3)
143
- const arrow = path.indexOf(' -> ')
144
- if (arrow >= 0) path = path.slice(arrow + 4)
258
+ const path = statusRowPath(line.slice(3))
145
259
  if (x === '?' && y === '?') {
146
260
  if (untracked.length < STATUS_ROW_CAP) untracked.push(path)
147
261
  else truncated = true
package/src/git-ops.ts CHANGED
@@ -58,11 +58,18 @@ function capped(command: string, bytes: number = GIT_CAP): string {
58
58
  * So: run git with stdout going straight to a file (no SIGPIPE), keep its
59
59
  * status in a variable, then emit the capped bytes and exit with that status.
60
60
  *
61
+ * `cleanup` runs after the capped bytes/stderr are forwarded and after the
62
+ * mktemp directory is removed, but before `exit`. A caller-owned temp file
63
+ * (e.g. the patch being applied) is therefore deleted on success AND failure
64
+ * without bringing a second `exit` into the wrapper — an embedded `exit` skips
65
+ * the `rm -rf "$d"` above and leaks one remote temp directory per call.
66
+ *
61
67
  * stderr is deliberately left alone: git's own diagnosis (‘! [rejected]’,
62
68
  * ‘hook declined’) has to reach the caller, which is the whole point.
63
69
  */
64
- function statusOk(command: string, bytes: number = GIT_CAP): string {
65
- return `d=$(mktemp -d); ${command} > "$d/out" 2>"$d/err"; st=$?; head -c ${bytes} "$d/out"; cat "$d/err" >&2; rm -rf "$d"; exit $st`
70
+ function statusOk(command: string, bytes: number = GIT_CAP, cleanup?: string): string {
71
+ const tail = cleanup === undefined ? '' : `; ${cleanup}`
72
+ return `d=$(mktemp -d); ${command} > "$d/out" 2>"$d/err"; st=$?; head -c ${bytes} "$d/out"; cat "$d/err" >&2; rm -rf "$d"${tail}; exit $st`
66
73
  }
67
74
 
68
75
  // ------------------------------------------------------------- assertions
@@ -484,10 +491,11 @@ export function applyPatchCommand(workdir: string, patchPath: string, mode: 'sta
484
491
  const file = shQuote(assertRemoteDir(patchPath))
485
492
  const args = APPLY_ARGS[mode]
486
493
  // `git apply` is the whole point of this call, so its exit status is the
487
- // result: a plain `; rm -f` would hand back rm's 0 and report a rejected
488
- // hunk as staged. The status is latched into a variable before the cleanup
489
- // runs, because any command in between would overwrite `$?`.
490
- return statusOk(`${git(workdir)} apply ${args} ${file}; st=$?; rm -f ${file}; exit $st`)
494
+ // result (a plain `; rm -f` would hand back rm's 0 and report a rejected hunk
495
+ // as staged). The patch file is deleted by `statusOk`'s cleanup tail: running
496
+ // the removal inside the command with its own `exit` skipped the wrapper's
497
+ // temp-dir cleanup and leaked one remote directory per hunk operation.
498
+ return statusOk(`${git(workdir)} apply ${args} ${file}`, GIT_CAP, `rm -f ${file}`)
491
499
  }
492
500
 
493
501
  // ------------------------------------------------------------- parsers
package/src/http.ts CHANGED
@@ -2,6 +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 { DeadlineError } from './timeouts.ts'
5
6
 
6
7
  const JSON_HEADERS = {
7
8
  'content-type': 'application/json; charset=utf-8',
@@ -9,34 +10,85 @@ const JSON_HEADERS = {
9
10
  } satisfies OutgoingHttpHeaders
10
11
 
11
12
  /**
12
- * Lenient bounded body reader: parse a request body as JSON, or null on an
13
- * empty body, invalid JSON, or a body past maxBytes (default 64 KiB).
13
+ * Extra bytes a too-large body may stream past its cap before the socket is
14
+ * dropped. Draining the rest keeps the caller's error response readable; the
15
+ * hard stop below refuses to read an unbounded body from a stuck/hostile client.
14
16
  */
15
- export async function readJsonBody(
17
+ const DRAIN_LIMIT_BYTES = 8 * 1024 * 1024
18
+
19
+ /**
20
+ * Outcome of one bounded body read.
21
+ *
22
+ * The discriminant exists because `null` collapsed three very different cases
23
+ * (empty, malformed, too large) into one, and the caller could only answer them
24
+ * all the same way. `too-large` is what a 413 should be built from.
25
+ */
26
+ export type JsonBodyResult =
27
+ | { kind: 'ok'; value: unknown }
28
+ | { kind: 'empty' }
29
+ | { kind: 'invalid' }
30
+ | { kind: 'too-large'; maxBytes: number }
31
+
32
+ /**
33
+ * Bounded body reader with a truthful outcome.
34
+ *
35
+ * Oversize no longer destroys the request immediately: returning early from the
36
+ * `for await` loop would tear the socket down, and the caller's 400/413 then
37
+ * reaches the client as a connection reset (the reported A11 symptom). The body
38
+ * is drained instead, up to `DRAIN_LIMIT_BYTES`, so the route can answer with a
39
+ * readable JSON error; an absurd stream is still cut off with `destroy()`.
40
+ */
41
+ export async function readJsonBodyResult(
16
42
  req: IncomingMessage,
17
43
  opts: { maxBytes?: number; objectOnly?: boolean } = {},
18
- ): Promise<unknown | null> {
44
+ ): Promise<JsonBodyResult> {
19
45
  const maxBytes = opts.maxBytes ?? 64 * 1024
20
46
  const chunks: Buffer[] = []
21
47
  let size = 0
48
+ let tooLarge = false
22
49
  for await (const chunk of req) {
23
50
  const buffer = chunk as Buffer
24
51
  size += buffer.length
25
- if (size > maxBytes) {
26
- req.destroy()
27
- return null
52
+ if (!tooLarge && size > maxBytes) {
53
+ // Stop buffering at the cap; keep consuming so the connection stays usable.
54
+ tooLarge = true
55
+ chunks.length = 0
56
+ }
57
+ if (tooLarge) {
58
+ if (size > maxBytes + DRAIN_LIMIT_BYTES) {
59
+ req.destroy()
60
+ return { kind: 'too-large', maxBytes }
61
+ }
62
+ continue
28
63
  }
29
64
  chunks.push(buffer)
30
65
  }
66
+ if (tooLarge) return { kind: 'too-large', maxBytes }
31
67
  const text = Buffer.concat(chunks).toString('utf8')
32
- if (text === '') return null
68
+ if (text === '') return { kind: 'empty' }
69
+ let parsed: unknown
33
70
  try {
34
- const parsed: unknown = JSON.parse(text)
35
- if (opts.objectOnly && !isJsonObject(parsed)) return null
36
- return parsed
71
+ parsed = JSON.parse(text)
37
72
  } catch {
38
- return null
73
+ return { kind: 'invalid' }
39
74
  }
75
+ if (opts.objectOnly === true && !isJsonObject(parsed)) return { kind: 'invalid' }
76
+ return { kind: 'ok', value: parsed }
77
+ }
78
+
79
+ /**
80
+ * Lenient bounded body reader: parse a request body as JSON, or null on an
81
+ * empty body, invalid JSON, or a body past maxBytes (default 64 KiB).
82
+ *
83
+ * Facade over {@link readJsonBodyResult} for the existing route call sites; new
84
+ * code should use the result form so `too-large` can be answered with a 413.
85
+ */
86
+ export async function readJsonBody(
87
+ req: IncomingMessage,
88
+ opts: { maxBytes?: number; objectOnly?: boolean } = {},
89
+ ): Promise<unknown | null> {
90
+ const result = await readJsonBodyResult(req, opts)
91
+ return result.kind === 'ok' ? result.value : null
40
92
  }
41
93
 
42
94
  function isJsonObject(value: unknown): value is Record<string, unknown> {
@@ -53,3 +105,19 @@ export function writeJson(
53
105
  res.writeHead(status, { ...JSON_HEADERS, ...headers })
54
106
  res.end(JSON.stringify(body))
55
107
  }
108
+
109
+ /**
110
+ * Write one failed-operation response, tagging a budget that merely ran out.
111
+ *
112
+ * `code: 'deadline'` is what lets the browser tell "this one request was too
113
+ * slow" from "the link is down": the client keeps the status chip green and the
114
+ * editor editable, while the operation still fails with a readable reason. Only
115
+ * the error object carries that distinction — the message is prose, and matching
116
+ * on prose stops working the moment the sentence changes.
117
+ */
118
+ export function writeRouteError(res: ServerResponse, error: unknown): void {
119
+ writeJson(res, 502, {
120
+ error: error instanceof Error ? error.message : String(error),
121
+ ...(error instanceof DeadlineError ? { code: 'deadline' } : {}),
122
+ })
123
+ }