dsh-remote-go 0.3.0 → 0.3.2

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 (86) hide show
  1. package/README.md +1 -0
  2. package/dist/client.js +1348 -2095
  3. package/dist/src/admission.js +3 -28
  4. package/dist/src/api.js +37 -99
  5. package/dist/src/atomic-json.js +32 -66
  6. package/dist/src/bootstrap.js +17 -27
  7. package/dist/src/connect/attach.js +3 -25
  8. package/dist/src/connect/bootstrap.js +2 -8
  9. package/dist/src/connect/failures.js +3 -18
  10. package/dist/src/connect/guards.js +13 -8
  11. package/dist/src/connect/launch.js +11 -21
  12. package/dist/src/connect/links.js +11 -27
  13. package/dist/src/connect/ownership.js +33 -114
  14. package/dist/src/connect/pipeline.js +62 -159
  15. package/dist/src/connect/reattach.js +26 -44
  16. package/dist/src/connect/registry.js +0 -1
  17. package/dist/src/connect/repair.js +8 -37
  18. package/dist/src/connect/restart.js +36 -97
  19. package/dist/src/connect/stop.js +16 -50
  20. package/dist/src/connect/transport.js +10 -18
  21. package/dist/src/connect/verify.js +3 -12
  22. package/dist/src/connect/watchdog.js +6 -38
  23. package/dist/src/connect-log.js +16 -41
  24. package/dist/src/connect-progress.js +13 -45
  25. package/dist/src/constants.js +18 -43
  26. package/dist/src/context.js +13 -32
  27. package/dist/src/diagnostics.js +56 -25
  28. package/dist/src/download-jobs.js +11 -20
  29. package/dist/src/errors.js +175 -190
  30. package/dist/src/events.js +20 -84
  31. package/dist/src/host-lifecycle.js +69 -177
  32. package/dist/src/host-registry.js +27 -78
  33. package/dist/src/host-runtime.js +0 -9
  34. package/dist/src/host-view.js +6 -29
  35. package/dist/src/index.js +15 -35
  36. package/dist/src/kernel-adapter.js +34 -80
  37. package/dist/src/key-files.js +10 -23
  38. package/dist/src/known-hosts.js +13 -34
  39. package/dist/src/layout.js +3 -20
  40. package/dist/src/local-download.js +94 -163
  41. package/dist/src/local-ssh.js +12 -19
  42. package/dist/src/local-version.js +35 -49
  43. package/dist/src/node/download.js +1 -4
  44. package/dist/src/node-runtime.js +19 -38
  45. package/dist/src/probe.js +6 -7
  46. package/dist/src/prompts.js +56 -128
  47. package/dist/src/proxy/cookies.js +26 -60
  48. package/dist/src/proxy/headers.js +30 -125
  49. package/dist/src/proxy/http.js +33 -41
  50. package/dist/src/proxy/index.js +20 -34
  51. package/dist/src/proxy/limits.js +4 -6
  52. package/dist/src/proxy/routes.js +10 -17
  53. package/dist/src/proxy/upgrade.js +27 -42
  54. package/dist/src/redact.js +14 -33
  55. package/dist/src/remote-files.js +9 -21
  56. package/dist/src/remote-path.js +21 -62
  57. package/dist/src/remote-proc.js +35 -103
  58. package/dist/src/remote-web/registry.js +10 -50
  59. package/dist/src/remote-web/resolve.js +23 -104
  60. package/dist/src/remote-web/start.js +27 -64
  61. package/dist/src/remote-web/stop.js +6 -25
  62. package/dist/src/request-trust.js +15 -32
  63. package/dist/src/runtime/dispatch.js +33 -143
  64. package/dist/src/runtime/effects.js +7 -17
  65. package/dist/src/runtime/events.js +1 -1
  66. package/dist/src/runtime/fsm.js +11 -61
  67. package/dist/src/runtime/rules.js +121 -199
  68. package/dist/src/secrets.js +15 -38
  69. package/dist/src/service.js +22 -128
  70. package/dist/src/settings.js +41 -42
  71. package/dist/src/ssh-config.js +22 -41
  72. package/dist/src/ssh-failures.js +23 -74
  73. package/dist/src/ssh-sftp.js +47 -86
  74. package/dist/src/ssh.js +99 -179
  75. package/dist/src/store.js +31 -48
  76. package/dist/src/tool-shared.js +17 -52
  77. package/dist/src/tools-exec-policy.js +33 -79
  78. package/dist/src/tools-exec.js +87 -151
  79. package/dist/src/tools-report.js +100 -167
  80. package/dist/src/tools.js +59 -133
  81. package/dist/src/tunnel.js +9 -27
  82. package/dist/src/util.js +19 -56
  83. package/dist/src/version.js +6 -12
  84. package/dist/src/watchdog-bus.js +0 -8
  85. package/dist/src/watchdog.js +7 -47
  86. package/package.json +3 -3
@@ -1,9 +1,5 @@
1
- /**
2
- * The plugin's own Node.js runtime on the remote: an official build, SHA-256 verified, under `$DSH_HOME/remote-go/node`; commands are fixed templates, never user-composed.
3
- *
4
- * The artifact scripts themselves — checksum discovery, verified download and unpack — live in
5
- * `node/download.ts`; this module decides what can be reused and runs the install.
6
- */
1
+ /** The plugin's Node.js runtime on the remote: an official build, SHA-256 verified, under `$DSH_HOME/remote-go/node`,
2
+ * installed by fixed command templates (never user-composed). The artifact scripts live in `node/download.ts`. */
7
3
  import { errors } from './errors.js';
8
4
  import { headTail, messageOf, shellQuote } from './util.js';
9
5
  import { MIN_NODE_VERSION, normalizeVersion, parseVersion } from './version.js';
@@ -16,8 +12,8 @@ export function managedNodeVersionFromEngine(range, fallback = MANAGED_NODE_VERS
16
12
  const first = text.split('||')[0].trim();
17
13
  if (first === '' || first === '*' || first === 'latest')
18
14
  return normalizeVersion(fallback);
19
- // A strict `>` needs the next patch; `>=`, `^`, `~`, `=` and a bare version all
20
- // mean that version itself.
15
+ // A strict `>` needs the next patch; `>=`, `^`, `~`, `=` and a bare version all mean that version
16
+ // itself.
21
17
  const strict = /^>\s*v?(\d+)(?:\.(\d+))?(?:\.(\d+))?/.exec(first);
22
18
  if (strict && !first.startsWith('>=')) {
23
19
  return normalizeVersion(`${Number(strict[1])}.${Number(strict[2] ?? 0)}.${Number(strict[3] ?? 0) + 1}`);
@@ -48,14 +44,11 @@ export function nodeDistArch(arch) {
48
44
  function compareGlibc(left, right) {
49
45
  const a = String(left ?? '').split('.');
50
46
  const b = String(right ?? '').split('.');
51
- const length = Math.max(a.length, b.length);
52
- for (let index = 0; index < length; index += 1) {
53
- const x = Number.parseInt(a[index] ?? '0', 10);
54
- const y = Number.parseInt(b[index] ?? '0', 10);
55
- const leftValue = Number.isFinite(x) ? x : 0;
56
- const rightValue = Number.isFinite(y) ? y : 0;
57
- if (leftValue !== rightValue)
58
- return leftValue < rightValue ? -1 : 1;
47
+ for (let index = 0; index < Math.max(a.length, b.length); index += 1) {
48
+ const x = Number.parseInt(a[index] ?? '0', 10) || 0;
49
+ const y = Number.parseInt(b[index] ?? '0', 10) || 0;
50
+ if (x !== y)
51
+ return x < y ? -1 : 1;
59
52
  }
60
53
  return 0;
61
54
  }
@@ -90,9 +83,6 @@ export function parseNodeScanOutput(stdout) {
90
83
  }
91
84
  return versions;
92
85
  }
93
- function technicalOf(error) {
94
- return messageOf(error ?? '');
95
- }
96
86
  function nodeError(detail, technical) {
97
87
  return errors.nodeInstallFailed(detail, technical ? { technical } : undefined);
98
88
  }
@@ -114,7 +104,7 @@ async function scanManagedNode(ssh, layout) {
114
104
  });
115
105
  }
116
106
  catch (error) {
117
- throw nodeError({ zh: '无法检查远端托管的 Node。', en: 'Could not inspect the managed Node on the remote.' }, technicalOf(error));
107
+ throw nodeError({ zh: '无法检查远端托管的 Node。', en: 'Could not inspect the managed Node on the remote.' }, messageOf(error ?? ''));
118
108
  }
119
109
  if (result.code !== 0) {
120
110
  throw nodeError({
@@ -135,9 +125,8 @@ async function resolveNodeRelease(ssh, input) {
135
125
  }), { timeoutMs: NODE_CHECKSUM_TIMEOUT_MS, maxBytes: 200_000 });
136
126
  }
137
127
  catch (error) {
138
- // swallow-ok: unreachable — a transport failure is reported as a typed resolution
139
- // reason; the caller turns it into the install error.
140
- return { ok: false, reason: 'unreachable', technical: technicalOf(error) };
128
+ // swallow-ok: unreachable — a transport failure is reported as a typed resolution reason
129
+ return { ok: false, reason: 'unreachable', technical: messageOf(error ?? '') };
141
130
  }
142
131
  if (result.code === 0) {
143
132
  const release = parseNodeChecksumOutput(result.stdout, {
@@ -149,9 +138,8 @@ async function resolveNodeRelease(ssh, input) {
149
138
  return { ok: true, release };
150
139
  return { ok: false, reason: 'no-checksum', technical: headTail(result.stdout, 600) };
151
140
  }
152
- if (result.code === 9 || result.stdout.includes('FAILED\tno-fetch')) {
141
+ if (result.code === 9 || result.stdout.includes('FAILED\tno-fetch'))
153
142
  return { ok: false, reason: 'no-fetch' };
154
- }
155
143
  if (result.code === 5) {
156
144
  return { ok: false, reason: 'unreachable', technical: headTail(result.stderr || result.stdout, 600) };
157
145
  }
@@ -211,9 +199,8 @@ async function installNodeRelease(ssh, input) {
211
199
  });
212
200
  }
213
201
  catch (error) {
214
- // swallow-ok: unreachable — same contract as the checksum step: the caller turns
215
- // it into the install error with the technical detail.
216
- return { ok: false, reason: 'unreachable', technical: technicalOf(error) };
202
+ // swallow-ok: unreachable — same contract as the checksum step, the caller reports it
203
+ return { ok: false, reason: 'unreachable', technical: messageOf(error ?? '') };
217
204
  }
218
205
  if (result.code !== 0 || !dir) {
219
206
  return {
@@ -222,9 +209,8 @@ async function installNodeRelease(ssh, input) {
222
209
  technical: headTail(`${result.stdout}\n${result.stderr}`, 800),
223
210
  };
224
211
  }
225
- if (dir !== expectedDir) {
212
+ if (dir !== expectedDir)
226
213
  return { ok: false, reason: 'unexpected-location', technical: dir };
227
- }
228
214
  return { ok: true, dir };
229
215
  }
230
216
  export async function ensureRemoteNode(ssh, options) {
@@ -244,8 +230,8 @@ export async function ensureRemoteNode(ssh, options) {
244
230
  });
245
231
  }
246
232
  if (String(facts.os ?? '') !== 'Linux') {
247
- // The official builds this module installs are Linux-only; refusing here keeps a
248
- // Darwin/Windows remote from downloading a binary that could never run.
233
+ // The official builds this module installs are Linux-only; refusing here keeps a Darwin/Windows
234
+ // remote from downloading a binary that could never run.
249
235
  throw errors.unsupportedOs(`${facts.os ?? 'unknown'} ${facts.arch ?? ''}`.trim());
250
236
  }
251
237
  if (facts.libc === 'glibc' && facts.glibcVersion && compareGlibc(facts.glibcVersion, NODE_MIN_GLIBC) < 0) {
@@ -279,12 +265,7 @@ export async function ensureRemoteNode(ssh, options) {
279
265
  let installedNow = false;
280
266
  if (!current) {
281
267
  onProgress({ step: 'checksum', version });
282
- const resolved = await resolveNodeRelease(ssh, {
283
- layout,
284
- version,
285
- arch,
286
- bases: options.bases,
287
- });
268
+ const resolved = await resolveNodeRelease(ssh, { layout, version, arch, bases: options.bases });
288
269
  if (resolved.ok === false) {
289
270
  throw nodeError(resolveFailureDetail(resolved.reason, version), resolved.technical ?? `reason=${resolved.reason}`);
290
271
  }
package/dist/src/probe.js CHANGED
@@ -1,6 +1,5 @@
1
- /**
2
- * One read-only remote probe: a single POSIX `sh` script prints `key<TAB>value` lines that become the facts used by the planner, the Node installer and diagnostics.
3
- */
1
+ /** One read-only remote probe: a single POSIX `sh` script prints `key<TAB>value` lines that become the facts used by
2
+ * the planner, the Node installer and diagnostics. */
4
3
  import { headTail } from './util.js';
5
4
  import { errors } from './errors.js';
6
5
  import { normalizeVersion } from './version.js';
@@ -48,6 +47,7 @@ export function parseProbeOutput(stdout) {
48
47
  return values;
49
48
  }
50
49
  export function toProbeFacts(values) {
50
+ /** A measured number, or `null` when the remote reported nothing usable. */
51
51
  const num = (value) => {
52
52
  const n = Number(value);
53
53
  return Number.isFinite(n) ? n : null;
@@ -75,11 +75,10 @@ export function toProbeFacts(values) {
75
75
  };
76
76
  }
77
77
  export async function probeRemote(ssh, options = {}) {
78
- const script = buildProbeScript();
79
78
  const timeoutMs = options.timeoutMs ?? 60_000;
80
- const result = await ssh.exec(script, { timeoutMs });
81
- // A probe that ran out of time says nothing about the remote's DSH: report a timeout
82
- // (retryable network), not a missing remote runtime (L).
79
+ const result = await ssh.exec(buildProbeScript(), { timeoutMs });
80
+ // A probe that ran out of time says nothing about the remote's DSH: report a retryable timeout, not a
81
+ // missing remote runtime.
83
82
  if (result.timedOut === true) {
84
83
  throw errors.network({
85
84
  zh: `远端环境探测超过 ${Math.round(timeoutMs / 1000)} 秒没有完成,可能是链路很慢或远端负载过高。`,
@@ -1,23 +1,10 @@
1
- /**
2
- * The two prompts a connection can pause on (unknown host key, foreign DSH already running) and the answers the Client sends back; each settles exactly once.
3
- *
4
- * The status/phase/progress writes are transitions now (`hostkey.pending` / `hostkey.answered` /
5
- * `hostkey.timeout` / `conflict.pending` / `conflict.answered`); this module only owns the two
6
- * deferred slots and the fingerprint/conflict data.
7
- */
1
+ /** The two prompts a connection can pause on (unknown host key, foreign DSH running) and the Client's answers; each
2
+ * settles exactly once. Only the deferred slots and card data live here — the state writes belong to `dispatch.ts`. */
8
3
  import { errors, toErrorView } from './errors.js';
9
4
  import { dispatch, promptScopeFacts } from './runtime/dispatch.js';
10
5
  import { createDecision, nowIso } from './util.js';
11
- /**
12
- * The effect owner of this module.
13
- *
14
- * A prompt transition publishes a frame and (for `conflict.answered`) clears the conflict card;
15
- * it never arms a timer, touches the link or tears anything down. The heavy effects are declared so
16
- * the interface stays one shape, and throw if a future rule ever asks this module to perform one
17
- * (that would be a wiring bug: the prompt module has no deps slice).
18
- * @param ctx - the prompt context (settings, reporter, store).
19
- * @returns the effect owner for one prompt transition.
20
- */
6
+ /** The effect owner of this module: a prompt transition publishes a frame and, for `conflict.answered`, clears the
7
+ * conflict card. The heavy effects are declared for one shape and throw if a rule asks this module to perform one. */
21
8
  function promptEffects(ctx) {
22
9
  const noEffect = (name) => {
23
10
  throw new Error(`dispatch: the prompt module cannot perform the ${name} effect`);
@@ -46,27 +33,28 @@ function promptEffects(ctx) {
46
33
  },
47
34
  };
48
35
  }
49
- /**
50
- * Park the SSH handshake until the user answers the fingerprint prompt.
51
- *
52
- * A jump host and the target are different machines with different keys: the `role`
53
- * decides which context the answer belongs to, so a jump-host confirmation can never be
54
- * mistaken for the target's (B1).
55
- *
56
- * @returns whether the user accepted the key.
57
- */
36
+ /** Publish one prompt transition through this module's effect owner. */
37
+ function publish(ctx, runtime, event, caller) {
38
+ void dispatch(promptEffects(ctx), runtime, event, promptScopeFacts(runtime), { caller });
39
+ }
40
+ /** The two prompt slots are `unknown` on the runtime, and this module is their only writer. */
41
+ const pendingHostKeyOf = (runtime) => runtime.pendingHostKey;
42
+ const pendingConflictOf = (runtime) => runtime.pendingConflict;
43
+ /** A refusal the Client renders: the field it names and the bilingual reason. */
44
+ const reject = (field, zh, en) => errors.invalidInput(field, { zh, en });
45
+ /** Park the SSH handshake until the user answers the fingerprint prompt. The `role` decides which context the answer
46
+ * belongs to: a jump host and the target are different machines with different keys, so neither can cross over. */
58
47
  export function requestHostKey(ctx, runtime, info, options = {}) {
59
48
  const role = options.role === 'jump' ? 'jump' : 'target';
60
49
  const isJump = role === 'jump';
61
- // A per-host policy describes the target the user saved. A jump host has its own
62
- // security context, so only the global policy applies to it.
50
+ // A per-host policy describes the saved target; a jump host has its own security context, so only the global applies.
63
51
  const policy = isJump
64
52
  ? (ctx.settings()?.hostKeyPolicy ?? 'first-use')
65
53
  : (runtime.entry.hostKeyPolicy ?? ctx.settings()?.hostKeyPolicy ?? 'first-use');
66
54
  if (policy === 'strict')
67
55
  throw errors.hostKeyUnknown(info.sha256);
68
- const hostLabel = isJump && options.host ? ` ${options.host}` : '';
69
- ctx.progress.log(runtime, 'info', `waiting for the ${isJump ? `jump host${hostLabel}` : 'host'} key to be confirmed (${info.keyType} ${info.sha256}); the SSH handshake is paused`);
56
+ const where = isJump ? `jump host${options.host ? ` ${options.host}` : ''}` : 'host';
57
+ ctx.progress.log(runtime, 'info', `waiting for the ${where} key to be confirmed (${info.keyType} ${info.sha256}); the SSH handshake is paused`);
70
58
  const pending = {
71
59
  sha256: info.sha256,
72
60
  keyType: info.keyType,
@@ -81,9 +69,8 @@ export function requestHostKey(ctx, runtime, info, options = {}) {
81
69
  return false;
82
70
  if (runtime.desired !== 'connected' || runtime.closing === true)
83
71
  return false;
84
- // `hostkey.timeout` owns the `error` card and the "do not retry" flag; the slot itself is
85
- // cleared here (the settle hook below is idempotent).
86
- void dispatch(promptEffects(ctx), runtime, { type: 'hostkey.timeout', view: toErrorView(errors.hostKeyUnknown(info.sha256)) }, promptScopeFacts(runtime), { caller: 'timer' });
72
+ // `hostkey.timeout` owns the `error` card and the "do not retry" flag; the slot is cleared here.
73
+ publish(ctx, runtime, { type: 'hostkey.timeout', view: toErrorView(errors.hostKeyUnknown(info.sha256)) }, 'timer');
87
74
  runtime.pendingHostKey = null;
88
75
  return false;
89
76
  }, () => {
@@ -99,57 +86,33 @@ export function requestHostKey(ctx, runtime, info, options = {}) {
99
86
  status: 'pending',
100
87
  pinned: null,
101
88
  };
102
- if (isJump) {
103
- // The jump pin belongs to *this* jump host: an edited `jumpHost` must not be checked
104
- // against the previous machine's key (review blocker 3).
89
+ // The jump pin belongs to *this* jump host: an edited `jumpHost` must not be checked against the previous key.
90
+ // The dialog renders `HostView.fingerprint`, so it shows this pin now.
91
+ runtime.fingerprint = { ...fingerprint };
92
+ if (isJump)
105
93
  runtime.jumpFingerprint = { ...fingerprint, host: pending.host, port: pending.port };
106
- // The Client's dialog renders `HostView.fingerprint`, so the key being confirmed right now
107
- // has to be the one shown there - even though the pin it may produce stays separate (B1).
108
- runtime.fingerprint = { ...fingerprint };
109
- }
110
- else {
111
- runtime.fingerprint = fingerprint;
112
- }
113
94
  // The dialog data is in place before the transition publishes the frame that shows it.
114
- void dispatch(promptEffects(ctx), runtime, {
95
+ publish(ctx, runtime, {
115
96
  type: 'hostkey.pending',
116
97
  info: { sha256: info.sha256, keyType: info.keyType },
117
98
  role,
118
99
  host: pending.host,
119
100
  port: pending.port,
120
- }, promptScopeFacts(runtime), { caller: 'callback' });
101
+ }, 'callback');
121
102
  return decision.promise;
122
103
  }
123
- /**
124
- * Answer the host-key prompt. Pinning is written straight through to the store so
125
- * a failed first attempt still remembers the key the user accepted.
126
- *
127
- * A jump host's key is remembered in memory only (`runtime.jumpFingerprint`): the store's
128
- * `pinnedFingerprint` describes the target, and writing a jump key there would pin the
129
- * target to the wrong machine forever (B1).
130
- */
104
+ /** Answer the host-key prompt. Pinning is written straight through, so a failed attempt still remembers the accepted
105
+ * key; a jump key stays in memory — the store's `pinnedFingerprint` describes the target and would pin it wrongly. */
131
106
  export async function confirmHostKey(ctx, runtime, decision) {
132
- // `unknown` on `host-runtime.ts`; this module is the slot's only writer (see PendingHostKey).
133
- const pending = runtime.pendingHostKey;
134
- if (!pending) {
135
- throw errors.invalidInput('fingerprint', {
136
- zh: '没有待确认的主机指纹。',
137
- en: 'No host key is pending confirmation.',
138
- });
139
- }
140
- // A prompt is only answerable while it is the live one: a timeout, a disconnect or a
141
- // replacement attempt already settled it, and a late answer must not revive it (M1).
107
+ const pending = pendingHostKeyOf(runtime);
108
+ if (!pending)
109
+ throw reject('fingerprint', '没有待确认的主机指纹。', 'No host key is pending confirmation.');
110
+ // A prompt is answerable only while it is the live one: a timeout, a disconnect or a replacement already settled it.
142
111
  if (runtime.status !== 'fingerprint-pending') {
143
- throw errors.invalidInput('fingerprint', {
144
- zh: '这个指纹提示已经失效,请在下次连接时重新确认。',
145
- en: 'This host-key prompt is no longer active; confirm the key on the next connection.',
146
- });
112
+ throw reject('fingerprint', '这个指纹提示已经失效,请在下次连接时重新确认。', 'This host-key prompt is no longer active; confirm the key on the next connection.');
147
113
  }
148
114
  if (decision.sha256 && pending.sha256 && decision.sha256 !== pending.sha256) {
149
- throw errors.invalidInput('fingerprint', {
150
- zh: '确认的指纹与待确认的不一致。',
151
- en: 'The confirmed fingerprint does not match the pending one.',
152
- });
115
+ throw reject('fingerprint', '确认的指纹与待确认的不一致。', 'The confirmed fingerprint does not match the pending one.');
153
116
  }
154
117
  if (decision.accept && decision.remember && pending.role !== 'jump') {
155
118
  await ctx.store.patchHost(runtime.id, { pinnedFingerprint: pending.sha256 });
@@ -162,40 +125,29 @@ export async function confirmHostKey(ctx, runtime, decision) {
162
125
  pinned: decision.remember ? pending.sha256 : null,
163
126
  };
164
127
  if (pending.role === 'jump') {
165
- // Keep the identity with the pin: the same remembered pin may only be used for the same
166
- // jump host and port (review blocker 3).
128
+ // Keep the identity with the pin (it serves only the same jump host and port) and keep showing it until the dial.
167
129
  runtime.jumpFingerprint = { ...fingerprint, host: pending.host, port: pending.port };
168
- // The dialog that asked about the jump host must not start describing the target as soon
169
- // as it is answered: keep showing what was confirmed until the target is dialled.
170
130
  runtime.fingerprint = { ...fingerprint };
171
131
  ctx.progress.log(runtime, 'info', `jump host key accepted${decision.remember ? ' and remembered for this session' : ''} (${pending.host ?? 'jump host'}: ${pending.sha256})`);
172
132
  }
173
133
  else {
174
134
  runtime.fingerprint = fingerprint;
175
135
  }
176
- // `hostkey.answered` owns the `connecting` card and the "user said no" flag. The slot is still
177
- // installed here (the rule's guard reads it) and is cleared right after, as before.
178
- void dispatch(promptEffects(ctx), runtime, { type: 'hostkey.answered', accept: decision.accept === true }, promptScopeFacts(runtime), { caller: 'callback' });
136
+ // `hostkey.answered` owns the `connecting` card and the "no" flag; its guard reads the slot, cleared after dispatch.
137
+ publish(ctx, runtime, { type: 'hostkey.answered', accept: decision.accept === true }, 'callback');
179
138
  runtime.pendingHostKey = null;
180
139
  pending.resolve(decision.accept === true);
181
140
  return { ok: true };
182
141
  }
183
- /**
184
- * Abandon a pending host-key prompt (teardown, host removal, lost transport). Resolving it
185
- * with `false` makes the stalled `verifyHostKey` throw instead of holding the connect
186
- * promise open until the prompt times out (M1).
187
- */
142
+ /** Abandon a pending host-key prompt (teardown, host removal, lost transport): resolving `false` makes the stalled
143
+ * `verifyHostKey` throw instead of holding the connect promise open until the prompt times out. */
188
144
  export function cancelHostKeyPrompt(runtime) {
189
- // `unknown` on `host-runtime.ts`; this module is the slot's only writer (see PendingHostKey).
190
- const pending = runtime.pendingHostKey;
145
+ const pending = pendingHostKeyOf(runtime);
191
146
  runtime.pendingHostKey = null;
192
147
  if (pending)
193
148
  pending.resolve(false);
194
149
  }
195
- /**
196
- * Pause the pipeline for a decision about foreign remote processes.
197
- * Mirrors the host-key prompt: a status, a promise, and a bounded timeout.
198
- */
150
+ /** Pause the pipeline for a decision about foreign remote processes: a status, a promise, a bounded timeout. */
199
151
  export function askConflict(ctx, runtime, processes) {
200
152
  // The card data is in place before the transition publishes the frame that renders it.
201
153
  runtime.conflict = {
@@ -205,64 +157,40 @@ export function askConflict(ctx, runtime, processes) {
205
157
  command: String(process.command ?? '').slice(0, 400),
206
158
  })),
207
159
  };
208
- // A prompt the user never sees (the link was cancelled in the same tick) must not throw into
209
- // the pipeline; the refusal is logged and the caller's own guard reports the cancellation.
210
- void dispatch(promptEffects(ctx), runtime, { type: 'conflict.pending', count: processes.length }, promptScopeFacts(runtime), { caller: 'callback' });
160
+ // A prompt the user never sees (link cancelled just now) must not throw: its refusal is logged, the caller guards.
161
+ publish(ctx, runtime, { type: 'conflict.pending', count: processes.length }, 'callback');
211
162
  const decision = createDecision(ctx.timers.conflictConfirmMs, () => ({ action: 'cancel', timedOut: true }), (value) => {
212
- // The transition owns the `probing` card, the "user said no" flag and the conflict card.
213
- // A settlement that arrives after the link was torn down has no state to publish (the
214
- // teardown's own frame follows), so only the card is cleared here — the same guard today's
215
- // `desired === 'connected'` test provided, expressed on the status the rule checks.
163
+ // The transition owns the cards and the "user said no" flag; a settlement after a teardown only clears the card.
216
164
  if (runtime.status === 'conflict-pending') {
217
- void dispatch(promptEffects(ctx), runtime, {
218
- type: 'conflict.answered',
219
- action: value.action,
220
- ...(value.timedOut === true ? { timedOut: true } : {}),
221
- }, promptScopeFacts(runtime), { caller: 'silent' });
165
+ publish(ctx, runtime, { type: 'conflict.answered', action: value.action, ...(value.timedOut === true ? { timedOut: true } : {}) }, 'silent');
222
166
  }
223
167
  else {
224
168
  runtime.conflict = null;
225
169
  }
226
- // `unknown` on `host-runtime.ts`; this module is the slot's only writer (see PendingConflict).
227
- if (runtime.pendingConflict?.resolve === decision.settle) {
170
+ if (pendingConflictOf(runtime)?.resolve === decision.settle)
228
171
  runtime.pendingConflict = null;
229
- }
230
172
  });
231
173
  runtime.pendingConflict = { processes, resolve: decision.settle };
232
174
  return decision.promise;
233
175
  }
234
176
  export function confirmConflict(runtime, decision) {
235
- // `unknown` on `host-runtime.ts`; this module is the slot's only writer (see PendingConflict).
236
- const pending = runtime.pendingConflict;
237
- if (!pending) {
238
- throw errors.invalidInput('conflict', {
239
- zh: '没有待确认的远端 DSH 冲突。',
240
- en: 'No remote DSH conflict is pending confirmation.',
241
- });
242
- }
177
+ const pending = pendingConflictOf(runtime);
178
+ if (!pending)
179
+ throw reject('conflict', '没有待确认的远端 DSH 冲突。', 'No remote DSH conflict is pending confirmation.');
243
180
  const action = decision?.action;
244
181
  if (action !== 'stop' && action !== 'alongside' && action !== 'cancel') {
245
- throw errors.invalidInput('conflict', {
246
- zh: '请选择停止手工实例、与它并存,或取消连接。',
247
- en: 'Choose whether to stop the manual instance, keep it alongside, or cancel.',
248
- });
182
+ throw reject('conflict', '请选择停止手工实例、与它并存,或取消连接。', 'Choose whether to stop the manual instance, keep it alongside, or cancel.');
249
183
  }
250
- // The three-way guard directly above is the runtime proof; `ConflictDecision.action` is
251
- // `unknown` on purpose (it is the Client's body) and inequality cannot narrow `unknown`, so the
252
- // assertion names the type the guard already established. It erases at emit time.
184
+ // The three-way guard above is the runtime proof; `ConflictDecision.action` is `unknown` on purpose (the Client's
185
+ // body), and inequality cannot narrow `unknown`, so this assertion only names the type the guard established.
253
186
  pending.resolve({ action });
254
187
  return { ok: true };
255
188
  }
256
- /**
257
- * Abandon a pending conflict prompt (teardown). Resolving it with `cancel` makes
258
- * the stalled `askConflict` call return instead of holding the pipeline open.
259
- */
189
+ /** Abandon a pending conflict prompt (teardown): resolving `cancel` makes the stalled `askConflict` call return
190
+ * instead of holding the pipeline open. */
260
191
  export function cancelConflict(runtime) {
261
- // `unknown` on `host-runtime.ts`; this module is the slot's only writer (see PendingConflict).
262
- const pending = runtime.pendingConflict;
263
- // The answer is delivered while the slot is still installed: the settlement hook's
264
- // `conflict.answered` guard reads it. Both the hook and this function clear the slot, and both
265
- // clears are idempotent (M1).
192
+ const pending = pendingConflictOf(runtime);
193
+ // The answer is delivered while the slot is still installed (the settle hook reads it); both clears are idempotent.
266
194
  if (pending)
267
195
  pending.resolve({ action: 'cancel' });
268
196
  runtime.pendingConflict = null;
@@ -1,16 +1,10 @@
1
- /**
2
- * Bounds of one host's cookie jar. The remote decides what to set, so the jar needs a ceiling:
3
- * 64 cookies of at most 4 KiB keep a hostile or simply broken remote from growing the process,
4
- * and a cookie the remote marks `Secure` never lands in this plaintext, in-memory jar at all.
5
- */
1
+ /** Bounds of one host's cookie jar: the remote decides what to set, so the jar needs a ceiling and a hostile or broken
2
+ * remote must not grow the process. A `Secure` cookie never lands in this plaintext, in-memory jar at all. */
6
3
  export const MAX_JAR_COOKIES = 64;
7
4
  export const MAX_COOKIE_VALUE = 4096;
8
5
  export const MAX_COOKIE_NAME = 128;
9
- /**
10
- * Parse one `Set-Cookie` line into the jar entry it should replace.
11
- * Only the attributes that decide whether and where the value is sent are kept.
12
- * @param line - one Set-Cookie header value.
13
- */
6
+ /** Parse one `Set-Cookie` line into the jar entry it should replace: only the attributes that decide whether and where
7
+ * the value is sent are kept. */
14
8
  export function parseSetCookie(line) {
15
9
  const [pair, ...attributes] = String(line ?? '').split(';');
16
10
  const equals = pair.indexOf('=');
@@ -18,9 +12,7 @@ export function parseSetCookie(line) {
18
12
  return null;
19
13
  const name = pair.slice(0, equals).trim();
20
14
  const value = pair.slice(equals + 1).trim();
21
- if (name === '' || name.length > MAX_COOKIE_NAME)
22
- return null;
23
- if (value.length > MAX_COOKIE_VALUE)
15
+ if (name === '' || name.length > MAX_COOKIE_NAME || value.length > MAX_COOKIE_VALUE)
24
16
  return null;
25
17
  let cookiePath = '/';
26
18
  let expiresAt = Number.POSITIVE_INFINITY;
@@ -46,15 +38,7 @@ export function parseSetCookie(line) {
46
38
  }
47
39
  return { name, value, path: cookiePath, expiresAt, secure };
48
40
  }
49
- /** One host's cookies, keyed by name; values never leave this process. */
50
- function createCookieJar() {
51
- return new Map();
52
- }
53
- /**
54
- * Store every non-expired cookie from one response and drop the ones it cleared.
55
- * @param jar - host jar.
56
- * @param setCookie - raw Set-Cookie value(s).
57
- */
41
+ /** Store every non-expired cookie from one response and drop the ones it cleared. */
58
42
  export function storeCookies(jar, setCookie) {
59
43
  if (setCookie === undefined)
60
44
  return;
@@ -62,13 +46,9 @@ export function storeCookies(jar, setCookie) {
62
46
  const entry = parseSetCookie(line);
63
47
  if (entry === null)
64
48
  continue;
65
- if (entry.value === '' || entry.expiresAt <= Date.now()) {
66
- jar.delete(entry.name);
67
- continue;
68
- }
69
- // The tunnel is plain HTTP to 127.0.0.1, so a `Secure` cookie is not one this jar may
70
- // keep: storing and replaying it would downgrade a flag the remote asked for.
71
- if (entry.secure) {
49
+ // A `Secure` cookie is refused too: the tunnel is plain HTTP to 127.0.0.1, so replaying it would downgrade a
50
+ // flag the remote asked for.
51
+ if (entry.value === '' || entry.expiresAt <= Date.now() || entry.secure) {
72
52
  jar.delete(entry.name);
73
53
  continue;
74
54
  }
@@ -77,11 +57,7 @@ export function storeCookies(jar, setCookie) {
77
57
  jar.set(entry.name, { name: entry.name, value: entry.value, path: entry.path, expiresAt: entry.expiresAt });
78
58
  }
79
59
  }
80
- /**
81
- * Cookies whose path covers the upstream path, as one Cookie header value.
82
- * @param jar - host jar.
83
- * @param path - upstream request path.
84
- */
60
+ /** Cookies whose path covers the upstream path, as one `Cookie` header value. */
85
61
  export function cookieHeader(jar, path) {
86
62
  const now = Date.now();
87
63
  const parts = [];
@@ -90,39 +66,29 @@ export function cookieHeader(jar, path) {
90
66
  jar.delete(name);
91
67
  continue;
92
68
  }
93
- const covers = entry.path === '/' ||
94
- path === entry.path ||
95
- path.startsWith(`${entry.path.endsWith('/') ? entry.path.slice(0, -1) : entry.path}/`);
96
- if (covers)
69
+ const base = entry.path.endsWith('/') ? entry.path.slice(0, -1) : entry.path;
70
+ if (entry.path === '/' || path === entry.path || path.startsWith(`${base}/`)) {
97
71
  parts.push(`${name}=${entry.value}`);
72
+ }
98
73
  }
99
74
  return parts.join('; ');
100
75
  }
101
- /**
102
- * Create the per-host jar book.
103
- *
104
- * `authorityOf` is injected instead of imported: `remoteAuthority` is defined next to the header
105
- * rewriting, and `headers.ts` already imports `cookieHeader` from here, so reaching back would
106
- * make the two leaf modules import each other.
107
- */
76
+ /** Create the per-host jar book. `authorityOf` is injected instead of imported: `remoteAuthority` lives with header
77
+ * rewriting, which already imports `cookieHeader` here, so reaching back would make two leaves import each other. */
108
78
  export function createJarBook(authorityOf) {
109
79
  const jars = new Map();
110
- /**
111
- * The per-host cookie jar is bound to the remote authority it was filled from: after a
112
- * restart or a re-attach the remote comes back on a new random port, and cookies issued
113
- * by the old instance must not be sent to the new one (nor kept after the host is gone).
114
- */
115
- function jarFor(hostId, target) {
116
- const authority = authorityOf(target);
117
- let entry = jars.get(hostId);
118
- if (entry === undefined || entry.authority !== authority) {
119
- entry = { authority, jar: createCookieJar() };
120
- jars.set(hostId, entry);
121
- }
122
- return entry.jar;
123
- }
124
80
  return {
125
- jarFor,
81
+ // A jar is bound to the authority it was filled from: after a restart or a re-attach the remote comes back on a
82
+ // new random port, and cookies issued by the old instance must not be sent to the new one.
83
+ jarFor(hostId, target) {
84
+ const authority = authorityOf(target);
85
+ const entry = jars.get(hostId);
86
+ if (entry !== undefined && entry.authority === authority)
87
+ return entry.jar;
88
+ const fresh = { authority, jar: new Map() };
89
+ jars.set(hostId, fresh);
90
+ return fresh.jar;
91
+ },
126
92
  clear(hostId) {
127
93
  if (hostId === undefined)
128
94
  jars.clear();