dsh-remote-vs 0.28.0 → 0.30.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 (46) hide show
  1. package/README.en.md +63 -7
  2. package/README.md +51 -7
  3. package/lib/client.js +393 -112
  4. package/lib/index.js +2271 -160
  5. package/lib/p2-router-fs.js +1 -1
  6. package/lib/types/changes/recorder.d.ts +65 -10
  7. package/lib/types/changes/status.d.ts +48 -3
  8. package/lib/types/client/ConnectionsSection.d.ts +73 -0
  9. package/lib/types/client/HostsView.d.ts +139 -2
  10. package/lib/types/client/api.d.ts +65 -2
  11. package/lib/types/client/connection.d.ts +28 -1
  12. package/lib/types/client/scm/actions.d.ts +25 -1
  13. package/lib/types/forward.d.ts +11 -1
  14. package/lib/types/p2/helper-rpc.d.ts +48 -0
  15. package/lib/types/p2/worlds.d.ts +28 -0
  16. package/lib/types/pool.d.ts +337 -8
  17. package/lib/types/protocol.d.ts +218 -0
  18. package/lib/types/proxy.d.ts +136 -0
  19. package/lib/types/store.d.ts +81 -1
  20. package/lib/types/tools.d.ts +3 -0
  21. package/lib/{worlds-RG8K5eom.js → worlds-CRRZMZhg.js} +85 -6
  22. package/package.json +1 -1
  23. package/src/changes/recorder.ts +151 -15
  24. package/src/changes/status.ts +59 -4
  25. package/src/client/ConnectionStatus.tsx +19 -5
  26. package/src/client/ConnectionsSection.tsx +359 -0
  27. package/src/client/HostsView.tsx +552 -11
  28. package/src/client/MonitorView.tsx +14 -0
  29. package/src/client/PortsView.tsx +16 -0
  30. package/src/client/SettingsHosts.tsx +132 -6
  31. package/src/client/api.ts +102 -4
  32. package/src/client/connection.ts +76 -2
  33. package/src/client/i18n.ts +152 -2
  34. package/src/client/scm/actions.ts +63 -12
  35. package/src/client/vsc/vsc.css +281 -0
  36. package/src/forward.ts +38 -2
  37. package/src/importers.ts +125 -13
  38. package/src/keygen.ts +8 -1
  39. package/src/p2/helper-rpc.ts +73 -5
  40. package/src/p2/worlds.ts +48 -0
  41. package/src/pool.ts +1120 -100
  42. package/src/protocol.ts +228 -0
  43. package/src/proxy.ts +673 -0
  44. package/src/routes.ts +139 -5
  45. package/src/store.ts +335 -0
  46. package/src/tools.ts +47 -2
package/src/routes.ts CHANGED
@@ -62,6 +62,25 @@ function bodyAliasOf(value: unknown): string | null {
62
62
  return typeof alias === 'string' && alias !== '' ? alias : null
63
63
  }
64
64
 
65
+ /**
66
+ * Which channel budget an exec request asks for, from the two accepted spellings.
67
+ *
68
+ * `lane` is the current field (`'network'` for fetch/pull/push, `'git'` for git
69
+ * commands — reads and local writes alike) and `network: true` is the flag from
70
+ * before the git budget existed — kept because a browser tab can run an OLD client
71
+ * bundle against this host. An explicit `lane` wins when both are sent, and
72
+ * anything else (a typo, `'exec'`, a number) is IGNORED so a bad value can never
73
+ * move traffic onto a smaller budget than the caller meant.
74
+ *
75
+ * An empty object means "no lane": the command spends the shared exec budget,
76
+ * which is what every caller that predates the lanes gets.
77
+ */
78
+ function execLaneOf(body: { lane?: unknown; network?: unknown }): { lane?: 'network' | 'git' } {
79
+ if (body.lane === 'network' || body.lane === 'git') return { lane: body.lane }
80
+ if (body.network === true) return { lane: 'network' }
81
+ return {}
82
+ }
83
+
65
84
  /**
66
85
  * A caller mistake the route can name: well-formed HTTP, unusable payload.
67
86
  *
@@ -483,22 +502,37 @@ export function makeRoutes(deps: RemoteRoutesDeps): {
483
502
  res.on('close', () => stop())
484
503
  }
485
504
 
486
- /** Apply parsed import payloads; per-entry errors become skips. */
505
+ /**
506
+ * Apply parsed import payloads; per-entry errors become skips.
507
+ *
508
+ * Two rounds, jump rows LAST, because a `jump` decision names ANOTHER host and
509
+ * `store.create` refuses a `viaAlias` that is not stored yet. Payload order is
510
+ * the order of the source file, which is not a dependency order: a config that
511
+ * writes `Host target` (`ProxyJump bastion`) before `Host bastion` used to
512
+ * import the bastion and silently drop the host that needs it, reported only as
513
+ * `proxy.jump.viaAlias: unknown host alias bastion`. One hop is the supported
514
+ * shape (a jump host is never itself a jump host), so two rounds always
515
+ * suffice; whatever is still unknown in round two is a host this import did
516
+ * not create (it was skipped for its own reason, which the report already
517
+ * carries), and stays a skip with the store's own wording.
518
+ */
487
519
  const applyImport = (parsed: ParsedImport): ImportReport => {
488
520
  const imported: string[] = []
489
521
  const skipped = [...parsed.skipped]
490
- for (const payload of parsed.payloads) {
522
+ const create = (payload: HostPayload): void => {
491
523
  if (store.get(payload.alias) !== undefined) {
492
524
  skipped.push({ alias: payload.alias, reason: 'alias already exists' })
493
- continue
525
+ return
494
526
  }
495
527
  try {
496
- store.create(payload as HostPayload)
528
+ store.create(payload)
497
529
  imported.push(payload.alias)
498
530
  } catch (error) {
499
531
  skipped.push({ alias: payload.alias, reason: error instanceof Error ? error.message : String(error) })
500
532
  }
501
533
  }
534
+ for (const payload of parsed.payloads.filter(entry => entry.proxy?.mode !== 'jump')) create(payload)
535
+ for (const payload of parsed.payloads.filter(entry => entry.proxy?.mode === 'jump')) create(payload)
502
536
  return { imported, skipped }
503
537
  }
504
538
 
@@ -572,13 +606,24 @@ export function makeRoutes(deps: RemoteRoutesDeps): {
572
606
  return
573
607
  }
574
608
  try {
609
+ const entry = store.update(alias, body as Partial<HostPayload>)
610
+ // Drop AFTER the update lands, never before. The other order leaves a
611
+ // window where a concurrent dial (the status poll, a background op)
612
+ // opens a connection with the OLD egress — the jump route it was
613
+ // configured for a moment ago — and `forget` has already run past it,
614
+ // so nothing ever closes it: the old route keeps serving until idle
615
+ // eviction. Observed in the field as a direct TCP to the target while
616
+ // the host was configured to reach it through a jump host. Dropping
617
+ // last means the new configuration is in force before anything is
618
+ // torn down, and the dials that raced this request go with the rest.
575
619
  pool.forget(alias)
576
620
  monitor.forget(alias)
577
621
  forgetProcesses(alias)
578
622
  void worlds.dropHost(alias).catch(() => undefined)
579
- const entry = store.update(alias, body as Partial<HostPayload>)
580
623
  writeJson(res, 200, { host: store.summarize(entry) })
581
624
  } catch (error) {
625
+ // The update itself was refused (400/404), so the stored host did NOT
626
+ // change: its connections still match the configuration and must stay.
582
627
  const status = (error instanceof Error ? error.message : '').startsWith('unknown host alias') ? 404 : 400
583
628
  writeJson(res, status, { error: error instanceof Error ? error.message : String(error) })
584
629
  }
@@ -603,6 +648,41 @@ export function makeRoutes(deps: RemoteRoutesDeps): {
603
648
  writeJson(res, 200, { connections: pool.status() })
604
649
  },
605
650
  },
651
+ // ------------------------------------------------------ pool shape
652
+ // The live pool per host: the four connection lanes, their open channels and
653
+ // the two channel budgets. Same contract as `status` (read-only, dial-free) —
654
+ // it answers "why is this slow" with numbers instead of a hunch, which is
655
+ // what the monitor page needs.
656
+ {
657
+ kind: 'exact',
658
+ path: REMOTE_API.connections,
659
+ handler: async (req, res) => {
660
+ if (!isLoopbackRequest(req)) {
661
+ writeJson(res, 403, { error: 'forbidden: loopback-only' })
662
+ return
663
+ }
664
+ if (req.method !== 'GET') {
665
+ writeJson(res, 405, { error: `method not allowed: ${req.method}` })
666
+ return
667
+ }
668
+ try {
669
+ const hosts = pool.stats()
670
+ // The helper owns the fifth lane but dials outside the pool, so its
671
+ // record is merged in here. A host without one keeps the key absent —
672
+ // "cannot say" must not read as "closed". `helperLane` never dials
673
+ // (see its docstring), so a monitor poll cannot bring a helper up.
674
+ await Promise.all(hosts.map(async host => {
675
+ // One host whose record misbehaves must not cost the whole page its
676
+ // data: the diagnostic value of the other hosts is the point.
677
+ const lane = await worlds.helperLane(host.alias).catch(() => undefined)
678
+ if (lane !== undefined) host.connections.helper = lane
679
+ }))
680
+ writeJson(res, 200, { hosts })
681
+ } catch (error) {
682
+ writeRouteError(res, error)
683
+ }
684
+ },
685
+ },
606
686
  // ------------------------------------------------------------- test
607
687
  {
608
688
  kind: 'exact',
@@ -674,6 +754,8 @@ export function makeRoutes(deps: RemoteRoutesDeps): {
674
754
  alias?: unknown
675
755
  command?: unknown
676
756
  timeoutMs?: unknown
757
+ network?: unknown
758
+ lane?: unknown
677
759
  }>(req, res, { objectOnly: true })
678
760
  if (!read.ok) return
679
761
  const body = read.body
@@ -682,6 +764,9 @@ export function makeRoutes(deps: RemoteRoutesDeps): {
682
764
  return
683
765
  }
684
766
  const timeoutMs = clampExecTimeout(body.timeoutMs)
767
+ // `lane` (network verbs / git commands) with the older `network: true`
768
+ // flag still honoured — see `execLaneOf`.
769
+ const lane = execLaneOf(body)
685
770
  /** The client closed the request: its response is never read. */
686
771
  let clientGone = false
687
772
  /** The client asked to stop: kill the remote even if the read is still opening. */
@@ -714,6 +799,7 @@ export function makeRoutes(deps: RemoteRoutesDeps): {
714
799
  try {
715
800
  const result = await pool.exec(body.alias, body.command, {
716
801
  ...(timeoutMs === undefined ? {} : { timeoutMs }),
802
+ ...lane,
717
803
  onCancel: (handle) => {
718
804
  cancel = handle
719
805
  if (cancelRequested && !cancelSent) {
@@ -748,6 +834,8 @@ export function makeRoutes(deps: RemoteRoutesDeps): {
748
834
  alias?: unknown
749
835
  command?: unknown
750
836
  timeoutMs?: unknown
837
+ network?: unknown
838
+ lane?: unknown
751
839
  }>(req, res, { objectOnly: true })
752
840
  if (!read.ok) return
753
841
  const body = read.body
@@ -756,6 +844,9 @@ export function makeRoutes(deps: RemoteRoutesDeps): {
756
844
  return
757
845
  }
758
846
  const timeoutMs = clampExecTimeout(body.timeoutMs)
847
+ // Same resolution as the unary route: `lane` first, `network: true` for
848
+ // older clients (`execLaneOf`), nothing means the exec budget.
849
+ const lane = execLaneOf(body)
759
850
  res.writeHead(200, {
760
851
  'Content-Type': 'text/event-stream; charset=utf-8',
761
852
  'Cache-Control': 'no-cache, no-transform',
@@ -836,6 +927,7 @@ export function makeRoutes(deps: RemoteRoutesDeps): {
836
927
  try {
837
928
  const result = await pool.exec(body.alias, body.command, {
838
929
  ...(timeoutMs === undefined ? {} : { timeoutMs }),
930
+ ...lane,
839
931
  onData: (stream, text) => {
840
932
  if (outputClosed || sent >= FORWARD_CAP) return
841
933
  sent += Buffer.byteLength(text, 'utf8')
@@ -1445,6 +1537,48 @@ export function makeRoutes(deps: RemoteRoutesDeps): {
1445
1537
  }
1446
1538
  },
1447
1539
  },
1540
+ // ------------------------------------------- proxy default (profile)
1541
+ // The profile-wide "upper" of the two proxy levels: hosts set to `inherit`
1542
+ // (which is every pre-existing host) use this decision. `direct` is the
1543
+ // default default, so a fresh profile dials exactly as it always did.
1544
+ {
1545
+ kind: 'exact',
1546
+ path: REMOTE_API.proxySettings,
1547
+ handler: async (req, res) => {
1548
+ if (!isLoopbackRequest(req)) {
1549
+ writeJson(res, 403, { error: 'forbidden: loopback-only' })
1550
+ return
1551
+ }
1552
+ const method = req.method ?? 'GET'
1553
+ if (method === 'GET') {
1554
+ try {
1555
+ writeJson(res, 200, { settings: store.getDefaultProxy() })
1556
+ } catch (error) {
1557
+ // A corrupt store is a real failure the page should name: answering
1558
+ // the defaults would hide it and the next save would overwrite it.
1559
+ writeStoreError(res, error)
1560
+ }
1561
+ return
1562
+ }
1563
+ if (method !== 'POST' && method !== 'PATCH') {
1564
+ writeJson(res, 405, { error: `method not allowed: ${method}` })
1565
+ return
1566
+ }
1567
+ const read = await readBodyOrError<Record<string, unknown>>(req, res, { objectOnly: true })
1568
+ if (!read.ok) return
1569
+ try {
1570
+ writeJson(res, 200, { settings: store.patchDefaultProxy(read.body ?? {}) })
1571
+ } catch (error) {
1572
+ // A rejected patch is the caller's fault (bad mode, missing target); a
1573
+ // corrupt/unwritable store is the service's, and names its path.
1574
+ if (isStoreError(error)) {
1575
+ writeStoreError(res, error)
1576
+ return
1577
+ }
1578
+ writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) })
1579
+ }
1580
+ },
1581
+ },
1448
1582
  // ------------------------------------------------------------ deploy
1449
1583
  {
1450
1584
  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)