dsh-remote-vs 0.27.0 → 0.29.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 (67) hide show
  1. package/README.en.md +159 -23
  2. package/README.md +123 -23
  3. package/lib/client.js +6906 -6619
  4. package/lib/index.js +2014 -67
  5. package/lib/types/changes/recorder.d.ts +119 -2
  6. package/lib/types/client/CodeEditor.d.ts +15 -0
  7. package/lib/types/client/HostsView.d.ts +139 -2
  8. package/lib/types/client/api.d.ts +42 -2
  9. package/lib/types/client/changes/apply-failure.d.ts +41 -0
  10. package/lib/types/client/changes/block-confirm.d.ts +97 -0
  11. package/lib/types/client/changes/diff-outcome.d.ts +56 -0
  12. package/lib/types/client/changes/freshness.d.ts +51 -0
  13. package/lib/types/client/changes/model.d.ts +19 -1
  14. package/lib/types/client/changes/session-diff.d.ts +100 -0
  15. package/lib/types/client/changes/staleness.d.ts +98 -0
  16. package/lib/types/client/changes/turn-reverted.d.ts +82 -0
  17. package/lib/types/client/changes/turn-view.d.ts +131 -0
  18. package/lib/types/client/changes/undo-affordance.d.ts +44 -10
  19. package/lib/types/client/changes/undo-target.d.ts +12 -0
  20. package/lib/types/client/connection.d.ts +28 -1
  21. package/lib/types/client/i18n.d.ts +1 -1
  22. package/lib/types/client/store.d.ts +91 -1
  23. package/lib/types/client/vsc/change-marks.d.ts +21 -0
  24. package/lib/types/forward.d.ts +11 -1
  25. package/lib/types/pool.d.ts +95 -1
  26. package/lib/types/protocol.d.ts +221 -1
  27. package/lib/types/proxy.d.ts +136 -0
  28. package/lib/types/store.d.ts +81 -1
  29. package/lib/types/tools.d.ts +3 -0
  30. package/package.json +1 -1
  31. package/src/changes/recorder.ts +851 -8
  32. package/src/client/CodeEditor.tsx +43 -3
  33. package/src/client/ConnectionStatus.tsx +19 -5
  34. package/src/client/EditorPane.tsx +64 -7
  35. package/src/client/HostsView.tsx +552 -11
  36. package/src/client/PortsView.tsx +16 -0
  37. package/src/client/SettingsHosts.tsx +132 -6
  38. package/src/client/api.ts +60 -3
  39. package/src/client/changes/ChangesDock.tsx +539 -54
  40. package/src/client/changes/apply-failure.ts +73 -0
  41. package/src/client/changes/block-confirm.ts +180 -0
  42. package/src/client/changes/changes.css +45 -0
  43. package/src/client/changes/diff-outcome.ts +97 -0
  44. package/src/client/changes/freshness.ts +68 -0
  45. package/src/client/changes/model.ts +56 -1
  46. package/src/client/changes/session-diff.ts +187 -0
  47. package/src/client/changes/staleness.ts +148 -0
  48. package/src/client/changes/turn-reverted.ts +254 -0
  49. package/src/client/changes/turn-view.ts +195 -0
  50. package/src/client/changes/undo-affordance.ts +295 -63
  51. package/src/client/changes/undo-target.ts +12 -0
  52. package/src/client/connection.ts +76 -2
  53. package/src/client/i18n.ts +204 -4
  54. package/src/client/scm/DiffView.tsx +32 -13
  55. package/src/client/store.tsx +392 -16
  56. package/src/client/vsc/change-marks.ts +21 -0
  57. package/src/client/vsc/preview-document.tsx +4 -1
  58. package/src/client/vsc/vsc.css +6747 -6509
  59. package/src/forward.ts +38 -2
  60. package/src/importers.ts +125 -13
  61. package/src/keygen.ts +8 -1
  62. package/src/pool.ts +422 -27
  63. package/src/protocol.ts +229 -1
  64. package/src/proxy.ts +673 -0
  65. package/src/routes.ts +93 -14
  66. package/src/store.ts +335 -0
  67. package/src/tools.ts +47 -2
package/src/routes.ts CHANGED
@@ -483,22 +483,37 @@ export function makeRoutes(deps: RemoteRoutesDeps): {
483
483
  res.on('close', () => stop())
484
484
  }
485
485
 
486
- /** Apply parsed import payloads; per-entry errors become skips. */
486
+ /**
487
+ * Apply parsed import payloads; per-entry errors become skips.
488
+ *
489
+ * Two rounds, jump rows LAST, because a `jump` decision names ANOTHER host and
490
+ * `store.create` refuses a `viaAlias` that is not stored yet. Payload order is
491
+ * the order of the source file, which is not a dependency order: a config that
492
+ * writes `Host target` (`ProxyJump bastion`) before `Host bastion` used to
493
+ * import the bastion and silently drop the host that needs it, reported only as
494
+ * `proxy.jump.viaAlias: unknown host alias bastion`. One hop is the supported
495
+ * shape (a jump host is never itself a jump host), so two rounds always
496
+ * suffice; whatever is still unknown in round two is a host this import did
497
+ * not create (it was skipped for its own reason, which the report already
498
+ * carries), and stays a skip with the store's own wording.
499
+ */
487
500
  const applyImport = (parsed: ParsedImport): ImportReport => {
488
501
  const imported: string[] = []
489
502
  const skipped = [...parsed.skipped]
490
- for (const payload of parsed.payloads) {
503
+ const create = (payload: HostPayload): void => {
491
504
  if (store.get(payload.alias) !== undefined) {
492
505
  skipped.push({ alias: payload.alias, reason: 'alias already exists' })
493
- continue
506
+ return
494
507
  }
495
508
  try {
496
- store.create(payload as HostPayload)
509
+ store.create(payload)
497
510
  imported.push(payload.alias)
498
511
  } catch (error) {
499
512
  skipped.push({ alias: payload.alias, reason: error instanceof Error ? error.message : String(error) })
500
513
  }
501
514
  }
515
+ for (const payload of parsed.payloads.filter(entry => entry.proxy?.mode !== 'jump')) create(payload)
516
+ for (const payload of parsed.payloads.filter(entry => entry.proxy?.mode === 'jump')) create(payload)
502
517
  return { imported, skipped }
503
518
  }
504
519
 
@@ -572,13 +587,24 @@ export function makeRoutes(deps: RemoteRoutesDeps): {
572
587
  return
573
588
  }
574
589
  try {
590
+ const entry = store.update(alias, body as Partial<HostPayload>)
591
+ // Drop AFTER the update lands, never before. The other order leaves a
592
+ // window where a concurrent dial (the status poll, a background op)
593
+ // opens a connection with the OLD egress — the jump route it was
594
+ // configured for a moment ago — and `forget` has already run past it,
595
+ // so nothing ever closes it: the old route keeps serving until idle
596
+ // eviction. Observed in the field as a direct TCP to the target while
597
+ // the host was configured to reach it through a jump host. Dropping
598
+ // last means the new configuration is in force before anything is
599
+ // torn down, and the dials that raced this request go with the rest.
575
600
  pool.forget(alias)
576
601
  monitor.forget(alias)
577
602
  forgetProcesses(alias)
578
603
  void worlds.dropHost(alias).catch(() => undefined)
579
- const entry = store.update(alias, body as Partial<HostPayload>)
580
604
  writeJson(res, 200, { host: store.summarize(entry) })
581
605
  } catch (error) {
606
+ // The update itself was refused (400/404), so the stored host did NOT
607
+ // change: its connections still match the configuration and must stay.
582
608
  const status = (error instanceof Error ? error.message : '').startsWith('unknown host alias') ? 404 : 400
583
609
  writeJson(res, status, { error: error instanceof Error ? error.message : String(error) })
584
610
  }
@@ -1288,7 +1314,7 @@ export function makeRoutes(deps: RemoteRoutesDeps): {
1288
1314
  // ------------------------------------------- session change ledger
1289
1315
  // What one live session changed on its remote host. The ledger itself is
1290
1316
  // fed by turn events (see index.ts); the browser only ever reads it, which
1291
- // is why both ops are side-effect free and answer null instead of 404 when
1317
+ // is why all three ops are side-effect free and answer null instead of 404 when
1292
1318
  // the session has no ledger yet (the panel shows its pending/absent state).
1293
1319
  {
1294
1320
  kind: 'exact',
@@ -1307,8 +1333,8 @@ export function makeRoutes(deps: RemoteRoutesDeps): {
1307
1333
  const body = read.body
1308
1334
  const sessionId = typeof body?.sessionId === 'string' ? body.sessionId : ''
1309
1335
  const op = typeof body?.op === 'string' ? body.op : ''
1310
- if (sessionId === '' || (op !== 'list' && op !== 'diff')) {
1311
- writeJson(res, 400, { error: 'op (list|diff) and a non-empty sessionId are required' })
1336
+ if (sessionId === '' || (op !== 'list' && op !== 'diff' && op !== 'turnDiff')) {
1337
+ writeJson(res, 400, { error: 'op (list|diff|turnDiff) and a non-empty sessionId are required' })
1312
1338
  return
1313
1339
  }
1314
1340
  const ledger = deps.changes
@@ -1331,22 +1357,33 @@ export function makeRoutes(deps: RemoteRoutesDeps): {
1331
1357
  const cwd = liveSessionCwd(ctx, sessionId)
1332
1358
  if (cwd !== undefined) ledger.beginTurn({ sessionId, cwd })
1333
1359
  }
1334
- // `force` runs the slow untracked scan now instead of waiting for the
1335
- // cadence — which is what the panel's refresh button means. A plain
1336
- // poll still self-heals data that has gone stale, so a missed turn
1337
- // boundary costs seconds rather than a manual click.
1360
+ // Three refresh intents, deliberately different in COST:
1361
+ // - `force` = the panel's ⟳ button: tracked scan now AND re-arm the slow
1362
+ // new-file walk (clears its write-off). A human click can afford it.
1363
+ // - `trackedOnly` = the panel's "back to the page" refresh: tracked files
1364
+ // now, but the slow walk keeps its cadence and its written-off verdict.
1365
+ // A window focus can happen every few seconds, and re-arming an 11s
1366
+ // (cold: minutes) walk on each one would multiply remote load.
1367
+ // - neither = the ordinary poll, which self-heals once data is stale.
1338
1368
  if (body?.force === true) ledger.rescan(sessionId)
1369
+ else if (body?.trackedOnly === true) ledger.touch(sessionId, 0)
1339
1370
  else ledger.touch(sessionId)
1340
1371
  writeJson(res, 200, { summary: ledger.summary(sessionId) })
1341
1372
  return
1342
1373
  }
1343
1374
  const path = typeof body?.path === 'string' ? body.path : ''
1344
1375
  if (path === '') {
1345
- writeJson(res, 400, { error: 'path is required for op=diff' })
1376
+ writeJson(res, 400, { error: `path is required for op=${op}` })
1346
1377
  return
1347
1378
  }
1348
1379
  try {
1349
- writeJson(res, 200, { diff: await ledger.diff(sessionId, path) })
1380
+ // `turnDiff` answers the same shape from the ledger's last completed
1381
+ // turn (cached hunks, plus a `stale` verdict when the file moved on).
1382
+ writeJson(res, 200, {
1383
+ diff: op === 'turnDiff'
1384
+ ? await ledger.turnDiff(sessionId, path)
1385
+ : await ledger.diff(sessionId, path),
1386
+ })
1350
1387
  } catch (error) {
1351
1388
  // Reading the diff is a remote (git) round trip: it failed upstream.
1352
1389
  writeRouteError(res, error)
@@ -1434,6 +1471,48 @@ export function makeRoutes(deps: RemoteRoutesDeps): {
1434
1471
  }
1435
1472
  },
1436
1473
  },
1474
+ // ------------------------------------------- proxy default (profile)
1475
+ // The profile-wide "upper" of the two proxy levels: hosts set to `inherit`
1476
+ // (which is every pre-existing host) use this decision. `direct` is the
1477
+ // default default, so a fresh profile dials exactly as it always did.
1478
+ {
1479
+ kind: 'exact',
1480
+ path: REMOTE_API.proxySettings,
1481
+ handler: async (req, res) => {
1482
+ if (!isLoopbackRequest(req)) {
1483
+ writeJson(res, 403, { error: 'forbidden: loopback-only' })
1484
+ return
1485
+ }
1486
+ const method = req.method ?? 'GET'
1487
+ if (method === 'GET') {
1488
+ try {
1489
+ writeJson(res, 200, { settings: store.getDefaultProxy() })
1490
+ } catch (error) {
1491
+ // A corrupt store is a real failure the page should name: answering
1492
+ // the defaults would hide it and the next save would overwrite it.
1493
+ writeStoreError(res, error)
1494
+ }
1495
+ return
1496
+ }
1497
+ if (method !== 'POST' && method !== 'PATCH') {
1498
+ writeJson(res, 405, { error: `method not allowed: ${method}` })
1499
+ return
1500
+ }
1501
+ const read = await readBodyOrError<Record<string, unknown>>(req, res, { objectOnly: true })
1502
+ if (!read.ok) return
1503
+ try {
1504
+ writeJson(res, 200, { settings: store.patchDefaultProxy(read.body ?? {}) })
1505
+ } catch (error) {
1506
+ // A rejected patch is the caller's fault (bad mode, missing target); a
1507
+ // corrupt/unwritable store is the service's, and names its path.
1508
+ if (isStoreError(error)) {
1509
+ writeStoreError(res, error)
1510
+ return
1511
+ }
1512
+ writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) })
1513
+ }
1514
+ },
1515
+ },
1437
1516
  // ------------------------------------------------------------ deploy
1438
1517
  {
1439
1518
  kind: 'exact',
package/src/store.ts CHANGED
@@ -6,13 +6,28 @@ import { existsSync, statSync, openSync, readFileSync, renameSync, writeSync, cl
6
6
  import { randomUUID } from 'node:crypto'
7
7
  import { dirname, join } from 'node:path'
8
8
  import { aliasRoot, keysDir, storePath } from './paths.ts'
9
+ import { normalizeProxy, type ProxyConfig } from './proxy.ts'
9
10
  import type {
10
11
  RemoteDeployState,
11
12
  RemoteHostEntry,
13
+ RemoteHostProxySetting,
14
+ RemoteHostProxyView,
15
+ RemoteProxyMode,
16
+ RemoteProxySetting,
17
+ RemoteProxySettingsPatch,
18
+ RemoteProxySettingsView,
19
+ RemoteProxyTargetView,
12
20
  RemoteHostSummary,
13
21
  RemoteWorkspaceBinding,
14
22
  } from './protocol.ts'
15
23
 
24
+ /** Profile-wide proxy default as stored (absent = direct). */
25
+ interface StoredDefaultProxy {
26
+ mode: 'direct' | 'proxy'
27
+ /** Endpoint for `mode: 'proxy'`; kept when switching back to direct. */
28
+ proxy?: ProxyConfig
29
+ }
30
+
16
31
  /** On-disk document shape. */
17
32
  interface StoreDoc {
18
33
  version: 1
@@ -20,6 +35,13 @@ interface StoreDoc {
20
35
  workspaces: RemoteWorkspaceBinding[]
21
36
  /** Removed alias dirs (fail-closed tombstones; never auto-deleted). */
22
37
  tombstones: string[]
38
+ /**
39
+ * Profile-wide proxy default (the "upper" level hosts may `inherit`).
40
+ *
41
+ * Optional so every pre-existing file keeps loading; absent means direct, which
42
+ * is the behaviour an upgrade must not change.
43
+ */
44
+ defaultProxy?: StoredDefaultProxy
23
45
  }
24
46
 
25
47
  /** Empty document. */
@@ -27,6 +49,37 @@ function emptyDoc(): StoreDoc {
27
49
  return { version: 1, hosts: [], workspaces: [], tombstones: [] }
28
50
  }
29
51
 
52
+ /** The proxy modes a stored host decision may name. */
53
+ const PROXY_MODES: readonly RemoteProxyMode[] = ['inherit', 'direct', 'proxy', 'jump']
54
+
55
+ /** Narrow an untrusted value to a declared mode (garbage falls back to `inherit`). */
56
+ function proxyModeOf(mode: unknown): RemoteProxyMode {
57
+ return PROXY_MODES.includes(mode as RemoteProxyMode) ? (mode as RemoteProxyMode) : 'inherit'
58
+ }
59
+
60
+ /** Message of an error without assuming it is an `Error`. */
61
+ function messageOf(error: unknown): string {
62
+ return error instanceof Error ? error.message : String(error)
63
+ }
64
+
65
+ /**
66
+ * Read a stored default-proxy block, tolerating hand-edited garbage.
67
+ *
68
+ * A malformed value is DROPPED (→ direct) rather than throwing: a store file an
69
+ * older version or a text editor touched must still load, and "direct" is the
70
+ * behaviour an upgrade would have had anyway.
71
+ */
72
+ function sanitizeDefaultProxy(value: unknown): StoredDefaultProxy | undefined {
73
+ if (typeof value !== 'object' || value === null) return undefined
74
+ const raw = value as { mode?: unknown; proxy?: unknown }
75
+ if (raw.proxy === undefined) return { mode: raw.mode === 'proxy' ? 'proxy' : 'direct' }
76
+ try {
77
+ return { mode: raw.mode === 'proxy' ? 'proxy' : 'direct', proxy: normalizeProxy(raw.proxy) }
78
+ } catch {
79
+ return { mode: 'direct' }
80
+ }
81
+ }
82
+
30
83
  /** Identity of the store file at one point in time; `null` = the file is absent. */
31
84
  type FileStamp = { mtimeMs: number; size: number } | null
32
85
 
@@ -74,6 +127,8 @@ export interface HostPayload {
74
127
  port?: number
75
128
  user: string
76
129
  auth: { kind: 'key' | 'password'; keyPath?: string; passphrase?: string; password?: string }
130
+ /** How this host reaches the network; omitted = `inherit` (back-compat). */
131
+ proxy?: RemoteHostProxySetting
77
132
  description?: string
78
133
  tags?: string[]
79
134
  }
@@ -84,6 +139,17 @@ export interface WorkspacePayload {
84
139
  remotePath: string
85
140
  }
86
141
 
142
+ /**
143
+ * The effective network route one dial must take (see `resolveProxy`).
144
+ *
145
+ * `source` is kept because "the profile default sent me through a proxy" and "this
146
+ * host says so" are different answers to the same question in `remote_hosts`.
147
+ */
148
+ export type ResolvedProxy =
149
+ | { kind: 'direct' }
150
+ | { kind: 'proxy'; proxy: ProxyConfig; source: 'host' | 'default' }
151
+ | { kind: 'jump'; viaAlias: string }
152
+
87
153
  export class RemoteStore {
88
154
  private readonly file: string
89
155
  private doc: StoreDoc
@@ -161,6 +227,10 @@ export class RemoteStore {
161
227
  hosts: doc.hosts,
162
228
  workspaces: doc.workspaces,
163
229
  tombstones: Array.isArray(doc.tombstones) ? doc.tombstones.filter(t => typeof t === 'string') : [],
230
+ ...(() => {
231
+ const defaultProxy = sanitizeDefaultProxy((doc as { defaultProxy?: unknown }).defaultProxy)
232
+ return defaultProxy === undefined ? {} : { defaultProxy }
233
+ })(),
164
234
  }
165
235
  }
166
236
 
@@ -321,10 +391,34 @@ export class RemoteStore {
321
391
  port: patch.port ?? current.port,
322
392
  user: patch.user ?? current.user,
323
393
  auth,
394
+ // `undefined` keeps the stored decision; `{mode:'inherit'}` clears it
395
+ // (the browser cannot send `null` through this payload shape).
396
+ proxy: patch.proxy ?? current.proxy,
324
397
  description: patch.description ?? current.description,
325
398
  tags: patch.tags ?? current.tags,
326
399
  }
327
400
  const next = this.normalize(merged, current)
401
+ /*
402
+ * A host other hosts jump through must stay a SINGLE hop.
403
+ *
404
+ * Making it a `jump` host would turn every dependent into a two-hop chain
405
+ * that `resolveProxy` refuses at dial time ("itself uses a jump host"), so
406
+ * the change landed here and broke someone ELSE's dials later without a
407
+ * word. Refusing it at save time is the only place the user can still see
408
+ * which host is in the way. (The reverse direction — creating a host that
409
+ * jumps through a jump host — stays allowed on purpose: that setting is new
410
+ * and its own row says why it cannot work today.)
411
+ */
412
+ if (proxyModeOf(next.proxy?.mode) === 'jump' && proxyModeOf(current.proxy?.mode) !== 'jump') {
413
+ const dependent = this.doc.hosts.find(
414
+ host => host.alias !== alias
415
+ && proxyModeOf(host.proxy?.mode) === 'jump'
416
+ && host.proxy?.jump?.viaAlias === alias,
417
+ )
418
+ if (dependent !== undefined) {
419
+ throw new Error(`host "${dependent.alias}" jumps through this host; change it first`)
420
+ }
421
+ }
328
422
  this.doc.hosts[index] = next
329
423
  return next
330
424
  })
@@ -374,6 +468,11 @@ export class RemoteStore {
374
468
  if (payload.tags !== undefined && (!Array.isArray(payload.tags) || payload.tags.some(t => typeof t !== 'string'))) {
375
469
  throw new Error('tags must be string[] when provided')
376
470
  }
471
+ // `inherit` is the absence of a decision, so it is stored as absence
472
+ // (an older file keeps loading, and a client that ignores the field is right).
473
+ const proxy = payload.proxy === undefined
474
+ ? undefined
475
+ : this.validateHostProxy(payload.proxy, payload.alias, current)
377
476
  const now = Date.now()
378
477
  return {
379
478
  alias: payload.alias,
@@ -386,6 +485,7 @@ export class RemoteStore {
386
485
  ...(auth.passphrase !== undefined ? { passphrase: auth.passphrase } : {}),
387
486
  ...(auth.password !== undefined ? { password: auth.password } : {}),
388
487
  },
488
+ ...(proxy === undefined ? {} : { proxy }),
389
489
  ...(payload.description !== undefined ? { description: payload.description } : {}),
390
490
  tags: payload.tags ?? [],
391
491
  ...(current?.deploy !== undefined ? { deploy: current.deploy } : {}),
@@ -394,6 +494,113 @@ export class RemoteStore {
394
494
  }
395
495
  }
396
496
 
497
+ /**
498
+ * Validate one host's stored proxy decision.
499
+ *
500
+ * The rules are the ones the two-level model needs to stay explainable:
501
+ * - the mode is one of the four declared values;
502
+ * - `proxy` needs an endpoint, `jump` needs another EXISTING alias (a host
503
+ * cannot jump through itself, and a chain is impossible to resolve with one
504
+ * pooled hop);
505
+ * - fields that the chosen mode does not use are DROPPED rather than stored, so
506
+ * switching modes cannot leave a stale endpoint behind that a later reader
507
+ * would take for the active one.
508
+ *
509
+ * @returns the normalized setting, or undefined for `inherit` (stored as the
510
+ * field's absence, which is what older files have).
511
+ */
512
+ private validateHostProxy(
513
+ input: RemoteHostProxySetting,
514
+ alias: string,
515
+ current: RemoteHostEntry | undefined,
516
+ ): RemoteHostProxySetting | undefined {
517
+ if (typeof input !== 'object' || input === null) throw new Error('proxy must be an object')
518
+ const mode = input.mode
519
+ if (!PROXY_MODES.includes(mode)) {
520
+ throw new Error('proxy.mode must be inherit, direct, proxy or jump')
521
+ }
522
+ if (mode === 'inherit') return undefined
523
+ if (mode === 'direct') return { mode }
524
+ if (mode === 'proxy') {
525
+ if (input.proxy === undefined) throw new Error('proxy.mode "proxy" requires a proxy endpoint')
526
+ /*
527
+ * The browser never receives the stored password back, so an untouched
528
+ * egress decision arrives WITHOUT one — and a PATCH that only changes the
529
+ * description resends that decision. Merging here (the same rule
530
+ * `mergeProxyTarget` applies to the profile default) is what keeps the
531
+ * password alive: without it, editing any field wiped it and the next dial
532
+ * failed with 407. An empty/omitted password keeps the stored one; the way
533
+ * to clear it is to leave `proxy` mode (which drops the endpoint).
534
+ */
535
+ return { mode, proxy: this.mergeProxyTarget(input.proxy, current?.proxy?.proxy) }
536
+ }
537
+ const viaAlias = input.jump?.viaAlias
538
+ if (typeof viaAlias !== 'string' || viaAlias === '') {
539
+ throw new Error('proxy.mode "jump" requires proxy.jump.viaAlias')
540
+ }
541
+ if (viaAlias === alias) throw new Error('proxy.jump.viaAlias must name another host, not this one')
542
+ if (!this.doc.hosts.some(host => host.alias === viaAlias)) {
543
+ throw new Error(`proxy.jump.viaAlias: unknown host alias ${viaAlias}`)
544
+ }
545
+ return { mode, jump: { viaAlias } }
546
+ }
547
+
548
+ /**
549
+ * Why a host's proxy decision cannot be used, when it cannot.
550
+ *
551
+ * Reads NEVER throw for this: a host that points at a deleted jump host must
552
+ * still be listed (with the reason on its row) instead of making the whole host
553
+ * list fail. The dial path asks {@link resolveProxy}, which does fail closed.
554
+ */
555
+ private proxyProblem(entry: RemoteHostEntry, mode: RemoteProxyMode): string | undefined {
556
+ const setting = entry.proxy
557
+ if (mode === 'proxy') {
558
+ if (setting?.proxy === undefined) return 'proxy mode is selected but no proxy endpoint is configured'
559
+ try {
560
+ normalizeProxy(setting.proxy)
561
+ return undefined
562
+ } catch (error) {
563
+ return messageOf(error)
564
+ }
565
+ }
566
+ if (mode !== 'jump') return undefined
567
+ const viaAlias = setting?.jump?.viaAlias
568
+ if (viaAlias === undefined || viaAlias === '') return 'jump mode is selected but no jump host is configured'
569
+ if (viaAlias === entry.alias) return 'a host cannot jump through itself'
570
+ const via = this.doc.hosts.find(host => host.alias === viaAlias)
571
+ if (via === undefined) return `jump host "${viaAlias}" is not configured`
572
+ if (proxyModeOf(via.proxy?.mode) === 'jump') return `jump host "${viaAlias}" itself uses a jump host (one hop only)`
573
+ return undefined
574
+ }
575
+
576
+ /** Secret-free view of one stored proxy endpoint. */
577
+ private targetView(setting: RemoteProxySetting | ProxyConfig): RemoteProxyTargetView {
578
+ return {
579
+ kind: setting.kind,
580
+ host: setting.host,
581
+ port: setting.port,
582
+ ...(setting.username === undefined || setting.username === '' ? {} : { username: setting.username }),
583
+ hasPassword: typeof setting.password === 'string' && setting.password !== '',
584
+ }
585
+ }
586
+
587
+ /** Secret-free view of one host's proxy decision (always present). */
588
+ private proxyView(entry: RemoteHostEntry): RemoteHostProxyView {
589
+ const mode = proxyModeOf(entry.proxy?.mode)
590
+ const view: RemoteHostProxyView = { mode }
591
+ if (entry.proxy?.proxy !== undefined) {
592
+ try {
593
+ view.target = this.targetView(normalizeProxy(entry.proxy.proxy))
594
+ } catch {
595
+ // The problem string below carries the reason.
596
+ }
597
+ }
598
+ if (entry.proxy?.jump?.viaAlias !== undefined) view.jumpVia = entry.proxy.jump.viaAlias
599
+ const problem = this.proxyProblem(entry, mode)
600
+ if (problem !== undefined) view.problem = problem
601
+ return view
602
+ }
603
+
397
604
  /** Secret-free projection for browser/agent surfaces. */
398
605
  summarize(entry: RemoteHostEntry): RemoteHostSummary {
399
606
  let keyReady = false
@@ -416,12 +623,140 @@ export class RemoteStore {
416
623
  && entry.auth.keyPath.startsWith(keysDir() + (process.platform === 'win32' ? '\\' : '/')),
417
624
  ...(entry.description !== undefined ? { description: entry.description } : {}),
418
625
  tags: [...entry.tags],
626
+ proxy: this.proxyView(entry),
419
627
  ...(entry.deploy !== undefined ? { deploy: entry.deploy } : {}),
420
628
  createdAt: entry.createdAt,
421
629
  updatedAt: entry.updatedAt,
422
630
  }
423
631
  }
424
632
 
633
+ // ------------------------------------------------------ proxy defaults
634
+
635
+ /** Secret-free view of the profile-wide proxy default (read-only). */
636
+ getDefaultProxy(): RemoteProxySettingsView {
637
+ this.reload()
638
+ return this.defaultProxyView()
639
+ }
640
+
641
+ /** View of the in-memory document (no reload: callers already reloaded). */
642
+ private defaultProxyView(): RemoteProxySettingsView {
643
+ const stored = this.doc.defaultProxy
644
+ const view: RemoteProxySettingsView = { defaultMode: stored?.mode === 'proxy' ? 'proxy' : 'direct' }
645
+ if (stored?.proxy !== undefined) {
646
+ try {
647
+ view.target = this.targetView(normalizeProxy(stored.proxy))
648
+ } catch {
649
+ // A malformed stored endpoint is not addressable: report direct instead of
650
+ // echoing a target nobody could dial (the dial path fails closed too).
651
+ view.defaultMode = 'direct'
652
+ }
653
+ } else if (view.defaultMode === 'proxy') {
654
+ // "proxy" without an endpoint is not a usable default; the upgrade-safe
655
+ // answer is direct until the user (or a patch) supplies one.
656
+ view.defaultMode = 'direct'
657
+ }
658
+ return view
659
+ }
660
+
661
+ /**
662
+ * Patch the profile-wide proxy default.
663
+ *
664
+ * `target` semantics follow the host form: omitted keeps the stored endpoint,
665
+ * `null` clears it, an object replaces it — and an EMPTY PASSWORD keeps the
666
+ * stored one, because the browser never receives secrets back.
667
+ */
668
+ patchDefaultProxy(patch: RemoteProxySettingsPatch): RemoteProxySettingsView {
669
+ if (typeof patch !== 'object' || patch === null) throw new Error('proxy settings patch must be an object')
670
+ return this.mutate(() => {
671
+ const current: StoredDefaultProxy = this.doc.defaultProxy ?? { mode: 'direct' }
672
+ let proxy = current.proxy
673
+ if (patch.target === null) {
674
+ proxy = undefined
675
+ } else if (patch.target !== undefined) {
676
+ proxy = this.mergeProxyTarget(patch.target, current.proxy)
677
+ }
678
+ const mode = patch.defaultMode ?? current.mode
679
+ if (mode !== 'direct' && mode !== 'proxy') throw new Error("defaultMode must be 'direct' or 'proxy'")
680
+ if (mode === 'proxy' && proxy === undefined) {
681
+ throw new Error('defaultMode "proxy" requires a proxy target')
682
+ }
683
+ this.doc.defaultProxy = { mode, ...(proxy === undefined ? {} : { proxy }) }
684
+ return this.defaultProxyView()
685
+ })
686
+ }
687
+
688
+ /**
689
+ * Normalize a patched endpoint, keeping the stored password on an empty one.
690
+ *
691
+ * "Empty means keep" is only sound for the SAME endpoint: the browser never
692
+ * receives the secret back, so every PATCH of a proxied host arrives without
693
+ * one — but when kind/host/port/username changed, the stored password is a
694
+ * credential for a DIFFERENT server, and carrying it over would send the old
695
+ * secret to a new address (a 407 at best, a leaked credential at worst). A
696
+ * changed endpoint therefore drops it and the user re-enters it.
697
+ */
698
+ private mergeProxyTarget(target: RemoteProxySetting, current: ProxyConfig | undefined): ProxyConfig {
699
+ const next = normalizeProxy(target)
700
+ const password = typeof target.password === 'string' ? target.password : ''
701
+ if (password === '') {
702
+ const sameEndpoint = current !== undefined
703
+ && current.kind === next.kind
704
+ && current.host === next.host
705
+ && current.port === next.port
706
+ && (current.username ?? '') === (next.username ?? '')
707
+ if (sameEndpoint && current.password !== undefined) next.password = current.password
708
+ else delete next.password
709
+ }
710
+ return next
711
+ }
712
+
713
+ /**
714
+ * Resolve one host's EFFECTIVE route, in the precedence the UI describes:
715
+ * the host's own decision, else the profile default, else direct.
716
+ *
717
+ * Unlike {@link summarize}, this FAILS CLOSED for an unusable jump: dialing
718
+ * through a deleted host (or a second jump) cannot work, and the caller must say
719
+ * why instead of silently connecting some other way.
720
+ */
721
+ resolveProxy(alias: string): ResolvedProxy {
722
+ const entry = this.require(alias)
723
+ const mode = proxyModeOf(entry.proxy?.mode)
724
+ if (mode === 'direct') return { kind: 'direct' }
725
+ if (mode === 'proxy') {
726
+ const stored = entry.proxy?.proxy
727
+ if (stored === undefined) {
728
+ throw new Error(`host ${alias}: proxy mode is selected but no proxy endpoint is configured`)
729
+ }
730
+ return { kind: 'proxy', proxy: this.requireStoredProxy(stored, alias), source: 'host' }
731
+ }
732
+ if (mode === 'jump') {
733
+ const viaAlias = entry.proxy?.jump?.viaAlias
734
+ if (viaAlias === undefined || viaAlias === '') {
735
+ throw new Error(`host ${alias}: jump mode is selected but no jump host is configured`)
736
+ }
737
+ if (viaAlias === alias) throw new Error(`host ${alias}: a host cannot jump through itself`)
738
+ const via = this.get(viaAlias)
739
+ if (via === undefined) throw new Error(`host ${alias}: jump host "${viaAlias}" is not configured`)
740
+ if (proxyModeOf(via.proxy?.mode) === 'jump') {
741
+ throw new Error(`host ${alias}: jump host "${viaAlias}" itself uses a jump host (one hop only)`)
742
+ }
743
+ return { kind: 'jump', viaAlias }
744
+ }
745
+ const storedDefault = this.doc.defaultProxy
746
+ if (storedDefault?.mode === 'proxy' && storedDefault.proxy !== undefined) {
747
+ return { kind: 'proxy', proxy: this.requireStoredProxy(storedDefault.proxy, alias), source: 'default' }
748
+ }
749
+ return { kind: 'direct' }
750
+ }
751
+
752
+ private requireStoredProxy(stored: RemoteProxySetting | ProxyConfig, alias: string): ProxyConfig {
753
+ try {
754
+ return normalizeProxy(stored)
755
+ } catch (error) {
756
+ throw new Error(`host ${alias}: invalid proxy configuration (${messageOf(error)})`)
757
+ }
758
+ }
759
+
425
760
  setDeploy(alias: string, state: RemoteDeployState): void {
426
761
  this.mutate(() => {
427
762
  const entry = this.doc.hosts.find(h => h.alias === alias)