dsh-remote-go 0.2.0 → 0.3.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.
- package/README.md +11 -3
- package/{client.js → dist/client.js} +7710 -8182
- package/dist/index.js +4 -0
- package/dist/src/admission.js +46 -0
- package/dist/src/api.js +442 -0
- package/dist/src/atomic-json.js +235 -0
- package/dist/src/bootstrap.js +106 -0
- package/dist/src/connect/attach.js +43 -0
- package/dist/src/connect/bootstrap.js +14 -0
- package/dist/src/connect/failures.js +44 -0
- package/dist/src/connect/guards.js +31 -0
- package/dist/src/connect/launch.js +80 -0
- package/dist/src/connect/links.js +70 -0
- package/dist/src/connect/ownership.js +220 -0
- package/dist/src/connect/pipeline.js +473 -0
- package/dist/src/connect/reattach.js +215 -0
- package/dist/src/connect/registry.js +11 -0
- package/dist/src/connect/repair.js +126 -0
- package/dist/src/connect/restart.js +316 -0
- package/dist/src/connect/stop.js +198 -0
- package/dist/src/connect/transport.js +109 -0
- package/dist/src/connect/verify.js +39 -0
- package/dist/src/connect/watchdog.js +76 -0
- package/dist/src/connect-log.js +162 -0
- package/dist/src/connect-progress.js +142 -0
- package/{src → dist/src}/constants.js +30 -56
- package/dist/src/context.js +117 -0
- package/dist/src/diagnostics.js +102 -0
- package/dist/src/download-jobs.js +230 -0
- package/dist/src/errors.js +243 -0
- package/dist/src/events.js +390 -0
- package/dist/src/host-lifecycle.js +504 -0
- package/dist/src/host-registry.js +232 -0
- package/dist/src/host-runtime.js +86 -0
- package/dist/src/host-view.js +75 -0
- package/dist/src/index.js +216 -0
- package/dist/src/kernel-adapter.js +434 -0
- package/dist/src/key-files.js +52 -0
- package/dist/src/known-hosts.js +125 -0
- package/dist/src/layout.js +43 -0
- package/dist/src/local-download.js +380 -0
- package/dist/src/local-ssh.js +30 -0
- package/dist/src/local-version.js +101 -0
- package/dist/src/node/download.js +160 -0
- package/dist/src/node-runtime.js +346 -0
- package/dist/src/probe.js +96 -0
- package/dist/src/prompts.js +270 -0
- package/dist/src/proxy/cookies.js +136 -0
- package/dist/src/proxy/headers.js +262 -0
- package/dist/src/proxy/http.js +142 -0
- package/dist/src/proxy/index.js +135 -0
- package/dist/src/proxy/limits.js +8 -0
- package/dist/src/proxy/routes.js +39 -0
- package/dist/src/proxy/upgrade.js +175 -0
- package/dist/src/redact.js +104 -0
- package/dist/src/remote-files.js +72 -0
- package/dist/src/remote-path.js +123 -0
- package/dist/src/remote-proc.js +339 -0
- package/dist/src/remote-web/registry.js +147 -0
- package/dist/src/remote-web/resolve.js +310 -0
- package/dist/src/remote-web/start.js +227 -0
- package/dist/src/remote-web/stop.js +93 -0
- package/dist/src/request-trust.js +87 -0
- package/dist/src/runtime/dispatch.js +310 -0
- package/dist/src/runtime/effects.js +91 -0
- package/dist/src/runtime/events.js +35 -0
- package/dist/src/runtime/fsm.js +120 -0
- package/dist/src/runtime/rules.js +565 -0
- package/dist/src/secrets.js +142 -0
- package/dist/src/service.js +406 -0
- package/dist/src/settings.js +144 -0
- package/dist/src/ssh-config.js +276 -0
- package/dist/src/ssh-failures.js +122 -0
- package/dist/src/ssh-port.js +4 -0
- package/dist/src/ssh-sftp.js +297 -0
- package/dist/src/ssh.js +477 -0
- package/dist/src/store.js +191 -0
- package/dist/src/tool-shared.js +181 -0
- package/dist/src/tools-exec-policy.js +167 -0
- package/dist/src/tools-exec.js +371 -0
- package/dist/src/tools-report.js +424 -0
- package/dist/src/tools.js +411 -0
- package/dist/src/tunnel.js +129 -0
- package/dist/src/util.js +149 -0
- package/dist/src/version.js +114 -0
- package/dist/src/watchdog-bus.js +29 -0
- package/dist/src/watchdog.js +156 -0
- package/index.js +5 -4
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +37 -19
- package/src/admission.js +0 -43
- package/src/api.js +0 -536
- package/src/atomic-json.js +0 -225
- package/src/bootstrap.js +0 -113
- package/src/connect-log.js +0 -176
- package/src/connect-pipeline.js +0 -1900
- package/src/connect-progress.js +0 -155
- package/src/diagnostics.js +0 -160
- package/src/download-jobs.js +0 -234
- package/src/errors.js +0 -412
- package/src/host-lifecycle.js +0 -604
- package/src/host-registry.js +0 -217
- package/src/host-runtime.js +0 -127
- package/src/host-view.js +0 -75
- package/src/index.js +0 -206
- package/src/key-files.js +0 -54
- package/src/known-hosts.js +0 -133
- package/src/layout.js +0 -53
- package/src/local-download.js +0 -381
- package/src/local-ssh.js +0 -27
- package/src/local-version.js +0 -88
- package/src/node-runtime.js +0 -521
- package/src/probe.js +0 -101
- package/src/prompts.js +0 -229
- package/src/redact.js +0 -68
- package/src/remote-files.js +0 -71
- package/src/remote-path.js +0 -137
- package/src/remote-proc.js +0 -343
- package/src/remote-proxy.js +0 -815
- package/src/remote-web.js +0 -751
- package/src/request-trust.js +0 -89
- package/src/secrets.js +0 -109
- package/src/service.js +0 -459
- package/src/settings.js +0 -163
- package/src/ssh-config.js +0 -271
- package/src/ssh.js +0 -731
- package/src/store.js +0 -193
- package/src/tools.js +0 -386
- package/src/tunnel.js +0 -132
- package/src/util.js +0 -153
- package/src/version.js +0 -103
- package/src/webapp.js +0 -43
- /package/{vendor → dist/vendor}/ssh2.bundle.cjs +0 -0
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The browser-trust fence shared by the local HTTP API and the same-origin remote proxy.
|
|
3
|
+
*
|
|
4
|
+
* Both surfaces answer on the local DSH origin, so both must give the same answer to one question:
|
|
5
|
+
* did this request arrive from the origin it names? Two confused-deputy paths reach a loopback web
|
|
6
|
+
* server — DNS rebinding and a cross-site page — and a browser labels neither reliably: a rebound
|
|
7
|
+
* page sends its own hostname as `Host` while the socket lands on this server, and a plain
|
|
8
|
+
* navigation or image read carries no `Origin` and no Fetch-Metadata. `Host` is the one header
|
|
9
|
+
* rebinding cannot forge, so it is checked for every request; when a browser does attach `Origin`
|
|
10
|
+
* or `sec-fetch-site`, they must agree too.
|
|
11
|
+
*/
|
|
12
|
+
const LOOPBACK_HOSTNAMES = new Set(['127.0.0.1', 'localhost', '[::1]', '::1']);
|
|
13
|
+
/** The port a URL actually names, counting an omitted default port. */
|
|
14
|
+
function effectivePort(url) {
|
|
15
|
+
if (url.port !== '')
|
|
16
|
+
return url.port;
|
|
17
|
+
return url.protocol === 'https:' ? '443' : '80';
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Hostname/port match for a `Host` header (which carries no scheme). The suffix is the local
|
|
21
|
+
* listener's origin; loopback spellings are interchangeable because a browser may dial either one.
|
|
22
|
+
*/
|
|
23
|
+
export function sameServerHost(value, origin) {
|
|
24
|
+
if (typeof value !== 'string' || value === '')
|
|
25
|
+
return false;
|
|
26
|
+
let candidate;
|
|
27
|
+
try {
|
|
28
|
+
candidate = new URL(`${origin.protocol}//${value}`);
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
return false;
|
|
32
|
+
}
|
|
33
|
+
// WHATWG parsing rewrites anything that is not a bare authority: `user@host` drops its userinfo,
|
|
34
|
+
// a backslash becomes a path separator, `#`/`?` start the fragment/query, and a trailing dot or a
|
|
35
|
+
// zero-padded port is normalized away. A browser fills `Host` from the serialized URL, so a value
|
|
36
|
+
// the parser had to rewrite is not an authority this server answers to; comparing the rewritten
|
|
37
|
+
// hostname would let `attacker.example@127.0.0.1:port` pass as loopback.
|
|
38
|
+
if (candidate.host !== value.toLowerCase())
|
|
39
|
+
return false;
|
|
40
|
+
if (effectivePort(candidate) !== effectivePort(origin))
|
|
41
|
+
return false;
|
|
42
|
+
if (candidate.hostname === origin.hostname)
|
|
43
|
+
return true;
|
|
44
|
+
return LOOPBACK_HOSTNAMES.has(origin.hostname) && LOOPBACK_HOSTNAMES.has(candidate.hostname);
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Full same-origin match for an `Origin` header (scheme included).
|
|
48
|
+
*
|
|
49
|
+
* The authority is compared verbatim (case-insensitively) as well as through `sameServerHost`.
|
|
50
|
+
* A browser fills `Origin` from the serialized URL, so anything the URL parser had to rewrite —
|
|
51
|
+
* `user@host`, a trailing dot, a zero-padded port — cannot have come from one, and letting the
|
|
52
|
+
* rewritten form through would accept `http://attacker.example@127.0.0.1:port` as loopback.
|
|
53
|
+
*/
|
|
54
|
+
export function sameServerOrigin(value, origin) {
|
|
55
|
+
if (typeof value !== 'string' || value === '')
|
|
56
|
+
return false;
|
|
57
|
+
// One trailing slash is tolerated (`Origin: http://host/` is not what a browser sends, but a
|
|
58
|
+
// hand-written caller may); no regex on this string, it is attacker-controlled.
|
|
59
|
+
const text = value.endsWith('/') ? value.slice(0, -1) : value;
|
|
60
|
+
let candidate;
|
|
61
|
+
try {
|
|
62
|
+
candidate = new URL(text);
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
return false;
|
|
66
|
+
}
|
|
67
|
+
// Drop the scheme without a regex: `scheme://rest` is the only shape left after URL parsing.
|
|
68
|
+
const schemeEnd = text.indexOf('://');
|
|
69
|
+
const authority = schemeEnd === -1 ? '' : text.slice(schemeEnd + 3);
|
|
70
|
+
if (authority.toLowerCase() !== candidate.host)
|
|
71
|
+
return false;
|
|
72
|
+
return candidate.protocol === origin.protocol && sameServerHost(candidate.host, origin);
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* The fence applied to a browser navigation and its subresources: the request must name this
|
|
76
|
+
* server, and any browser-announced relationship must be same-origin.
|
|
77
|
+
*/
|
|
78
|
+
export function trustedRequest(req, origin) {
|
|
79
|
+
if (!sameServerHost(req.headers.host, origin))
|
|
80
|
+
return false;
|
|
81
|
+
const originHeader = req.headers.origin;
|
|
82
|
+
if (typeof originHeader === 'string' && originHeader !== '' && !sameServerOrigin(originHeader, origin))
|
|
83
|
+
return false;
|
|
84
|
+
if (req.headers['sec-fetch-site'] === 'cross-site')
|
|
85
|
+
return false;
|
|
86
|
+
return true;
|
|
87
|
+
}
|
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The executor half of the `HostRuntime.session` state machine.
|
|
3
|
+
*
|
|
4
|
+
* `fsm.ts` decides *what* the session block becomes; this file turns that decision into the
|
|
5
|
+
* block's storage form and performs the effects the rule asked for (design-arch §2.4.2/§7.6).
|
|
6
|
+
* It is deliberately free of service imports: every action arrives through the `DispatchHost`
|
|
7
|
+
* the calling module builds from its own context, so `dispatch.ts` creates no import cycle with
|
|
8
|
+
* `host-lifecycle.ts`/`prompts.ts` (both of which call back into `dispatch`).
|
|
9
|
+
*
|
|
10
|
+
* Wiring rules this executor implements (from the design and the P2b hand-off):
|
|
11
|
+
*
|
|
12
|
+
* - **One transition, then one write.** The state is read with `readSession`, computed by the
|
|
13
|
+
* pure `transition`, and written back with `writeBack` before any effect runs. Effects never
|
|
14
|
+
* mutate the session block; they only act on the rest of the runtime and publish.
|
|
15
|
+
* - **`emit` is the only publication.** `options.emit === false` suppresses it for the callers
|
|
16
|
+
* whose old code published later in the same routine (the connect/restart/re-attach catches,
|
|
17
|
+
* which emit after deciding whether a retry is armed), so the frame sequence stays what it was.
|
|
18
|
+
* - **`arm(reconnect)` has a single source.** `connect.failed`/`transport.closed` ask for a retry
|
|
19
|
+
* timer with the *base* delay, but the randomized delay, the budget and the settings switch live
|
|
20
|
+
* in `host-lifecycle.ts#scheduleReconnect`. Creating a timer here would run two retry loops, so
|
|
21
|
+
* only `reconnect.scheduled` — the event `scheduleReconnect` dispatches once it has decided —
|
|
22
|
+
* may arm it. Every other `arm(reconnect)` means "a retry makes sense" and is left to the
|
|
23
|
+
* caller's policy (`scheduleConnectRetry`), never turned into a second timer.
|
|
24
|
+
* - **Refusals are graded by caller.** A one-shot script treats a refusal as a bug
|
|
25
|
+
* (`IllegalTransition`); a transport/proxy callback only logs; a timer logs at debug (the idle
|
|
26
|
+
* stop in particular must not warn: a host that is connected again is the normal race, not a
|
|
27
|
+
* fault).
|
|
28
|
+
* - **`connect.cancelled`'s teardown options are the failure's, not the table's.** The §2.4.2 row
|
|
29
|
+
* says `{stopRemote:false, keepRemote:true}`, but today's cancel branch releases with
|
|
30
|
+
* `stopRemote: remoteStarted && keepAlive === 'stop'` and `keepRemote: remoteStarted &&
|
|
31
|
+
* keepAlive !== 'stop'`; behavior freeze wins (reported as a deviation).
|
|
32
|
+
*/
|
|
33
|
+
import { IllegalTransition, isRefusal, transition, writeBack } from './fsm.js';
|
|
34
|
+
import { DEFAULT_IDLE_MINUTES, REMOTE_HEARTBEAT_DEFAULT_SEC, REMOTE_HEARTBEAT_MAX_SEC, REMOTE_HEARTBEAT_MIN_SEC, } from '../constants.js';
|
|
35
|
+
/* ── storage form ↔ pure state ───────────────────────────────────────────────────────────── */
|
|
36
|
+
/** The five activity kinds `host-lifecycle.ts#beginLinkWork` may store (`Activity`). */
|
|
37
|
+
const ACTIVITIES = ['connect', 'restart', 'reattach', 'stop', 'repair'];
|
|
38
|
+
/**
|
|
39
|
+
* `linkBusy` is the `activity` storage form. Its declared type stays the wide `string | null`
|
|
40
|
+
* (§7.4), so a value written by an older caller must not be handed to the FSM as an activity it
|
|
41
|
+
* does not know: an unknown kind means "no one-shot action", which is what the token checks
|
|
42
|
+
* already assume.
|
|
43
|
+
* @param value - the stored `linkBusy` value.
|
|
44
|
+
* @returns whether it is one of the five activities the machine models.
|
|
45
|
+
*/
|
|
46
|
+
export function isActivity(value) {
|
|
47
|
+
return typeof value === 'string' && ACTIVITIES.includes(value);
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Read the session block out of the flat runtime (design-arch §2.2 keeps the fields flat; this is
|
|
51
|
+
* the only adapter between storage and the pure machine).
|
|
52
|
+
*
|
|
53
|
+
* The four liveness fields (`remoteEpisode`/`episodeSource`/`episodeCooldownUntil`/`remoteFailures`)
|
|
54
|
+
* are **not** read here: `watchdog.ts` owns them and never dispatches an event, so a read would only
|
|
55
|
+
* round-trip the same value back. They used to be read for the dead `remote.*` transitions, which
|
|
56
|
+
* nothing dispatched.
|
|
57
|
+
* @param runtime - the session block of one host.
|
|
58
|
+
* @returns the pure session state.
|
|
59
|
+
*/
|
|
60
|
+
export function readSession(runtime) {
|
|
61
|
+
const progress = runtime.progress ?? null;
|
|
62
|
+
return {
|
|
63
|
+
status: runtime.status,
|
|
64
|
+
desired: runtime.desired,
|
|
65
|
+
activity: isActivity(runtime.linkBusy) ? runtime.linkBusy : null,
|
|
66
|
+
phase: runtime.phase,
|
|
67
|
+
progress,
|
|
68
|
+
error: runtime.error,
|
|
69
|
+
warning: runtime.warning,
|
|
70
|
+
warningSource: runtime.warningSource,
|
|
71
|
+
closing: runtime.closing === true,
|
|
72
|
+
connectCancelled: runtime.connectCancelled === true,
|
|
73
|
+
transportLost: runtime.transportLost === true,
|
|
74
|
+
reconnectAttempts: Number(runtime.reconnectAttempts) || 0,
|
|
75
|
+
epoch: Number(runtime.linkToken) || 0,
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* The heartbeat interval the watchdog would use, clamped exactly like
|
|
80
|
+
* `host-lifecycle.ts#remoteHeartbeatIntervalSec` (a pure rule cannot read settings, so the delay
|
|
81
|
+
* arrives in the scope). Duplicated here on purpose: importing the lifecycle function would make
|
|
82
|
+
* `dispatch.ts` depend on a module that depends on `dispatch.ts`.
|
|
83
|
+
* @param raw - the configured `remoteHeartbeat` setting.
|
|
84
|
+
* @returns the interval in milliseconds.
|
|
85
|
+
*/
|
|
86
|
+
function heartbeatMs(raw) {
|
|
87
|
+
const seconds = Number(raw?.intervalSec);
|
|
88
|
+
if (!Number.isFinite(seconds))
|
|
89
|
+
return REMOTE_HEARTBEAT_DEFAULT_SEC * 1000;
|
|
90
|
+
return Math.min(REMOTE_HEARTBEAT_MAX_SEC, Math.max(REMOTE_HEARTBEAT_MIN_SEC, Math.round(seconds))) * 1000;
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* The scope facts of the two prompt events (`hostkey.*`, `conflict.*`).
|
|
94
|
+
*
|
|
95
|
+
* Their rules read exactly one scope field — `promptsPending` — because a prompt answer is only
|
|
96
|
+
* about the slot it belongs to. The prompt module has no deps/settings slice (design-arch §1.2
|
|
97
|
+
* keeps it narrow), so the unrelated facts are the neutral values: none of these rules consumes
|
|
98
|
+
* them, and a future rule that tried to would be a wiring bug the tests would catch.
|
|
99
|
+
* @param runtime - the host runtime the prompt belongs to.
|
|
100
|
+
* @returns the facts `dispatch()` freezes for a prompt event.
|
|
101
|
+
*/
|
|
102
|
+
export function promptScopeFacts(runtime) {
|
|
103
|
+
return {
|
|
104
|
+
disposed: false,
|
|
105
|
+
runtimeExists: true,
|
|
106
|
+
linkAlive: runtime.ssh?.connected === true,
|
|
107
|
+
tunnelAlive: runtime.tunnel !== null,
|
|
108
|
+
transportIsCurrent: true,
|
|
109
|
+
promptsPending: runtime.pendingHostKey !== null || runtime.pendingConflict !== null,
|
|
110
|
+
keepAlive: runtime.entry.keepAlive,
|
|
111
|
+
remoteStarted: runtime.remote.pid !== null || runtime.remote.port !== null,
|
|
112
|
+
recoverable: false,
|
|
113
|
+
delays: { reconnectMs: 0, idleMs: 0, heartbeatMs: 0 },
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Read the scope facts of one event from the caller's context. Every value is a read: this is the
|
|
118
|
+
* executor's half of §2.4.4's "the pure function never touches a runtime".
|
|
119
|
+
* @param ctx - the caller's context (the watchdog slice is the widest one the facts need).
|
|
120
|
+
* @param runtime - the host runtime.
|
|
121
|
+
* @param event - the event about to be applied (its transport, if any, decides `transportIsCurrent`).
|
|
122
|
+
* @returns the facts `dispatch()` freezes into an `EventScope`.
|
|
123
|
+
*/
|
|
124
|
+
export function scopeFactsFor(ctx, runtime, event) {
|
|
125
|
+
const settings = ctx.settings();
|
|
126
|
+
const linkAlive = runtime.ssh?.connected === true;
|
|
127
|
+
const keepAlive = runtime.entry.keepAlive;
|
|
128
|
+
const idleMinutes = Math.max(1, runtime.entry.idleMinutes ?? DEFAULT_IDLE_MINUTES);
|
|
129
|
+
return {
|
|
130
|
+
disposed: ctx.state.disposed === true,
|
|
131
|
+
runtimeExists: ctx.state.runtimes.has(runtime.id),
|
|
132
|
+
linkAlive,
|
|
133
|
+
tunnelAlive: runtime.tunnel !== null,
|
|
134
|
+
transportIsCurrent: event.type === 'transport.closed' ? runtime.ssh === event.transport || runtime.jumpSsh === event.transport : true,
|
|
135
|
+
promptsPending: runtime.pendingHostKey !== null || runtime.pendingConflict !== null,
|
|
136
|
+
keepAlive,
|
|
137
|
+
remoteStarted: runtime.remote.pid !== null || runtime.remote.port !== null,
|
|
138
|
+
recoverable: runtime.status === 'error' && runtime.error?.code === 'remote-unreachable' && linkAlive && runtime.facts !== null,
|
|
139
|
+
delays: {
|
|
140
|
+
reconnectMs: Number(settings.autoReconnect.baseDelayMs) || 0,
|
|
141
|
+
idleMs: idleMinutes * 60_000,
|
|
142
|
+
heartbeatMs: heartbeatMs(settings.remoteHeartbeat),
|
|
143
|
+
},
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Build the read-only scope of one event.
|
|
148
|
+
*
|
|
149
|
+
* `promptsPending` is event-specific on purpose: a `hostkey.*` answer is stale once the host-key
|
|
150
|
+
* slot is gone, a `conflict.*` answer once the conflict slot is gone. One shared "any prompt"
|
|
151
|
+
* flag would let a conflict answer satisfy a host-key rule.
|
|
152
|
+
* @param event - the event about to be applied (its payload names the transport, if any).
|
|
153
|
+
* @param runtime - the host runtime (only for the identity fields the patches need).
|
|
154
|
+
* @param facts - the caller's read of what the context can see.
|
|
155
|
+
* @returns the frozen scope the pure machine reads.
|
|
156
|
+
*/
|
|
157
|
+
export function scopeFor(event, runtime, facts) {
|
|
158
|
+
const promptsPending = event.type === 'hostkey.pending' || event.type === 'hostkey.answered' || event.type === 'hostkey.timeout'
|
|
159
|
+
? runtime.pendingHostKey !== null
|
|
160
|
+
: event.type === 'conflict.pending' || event.type === 'conflict.answered'
|
|
161
|
+
? runtime.pendingConflict !== null
|
|
162
|
+
: runtime.pendingHostKey !== null || runtime.pendingConflict !== null;
|
|
163
|
+
return {
|
|
164
|
+
disposed: facts.disposed,
|
|
165
|
+
runtimeExists: facts.runtimeExists,
|
|
166
|
+
linkAlive: facts.linkAlive,
|
|
167
|
+
tunnelAlive: facts.tunnelAlive,
|
|
168
|
+
promptsPending,
|
|
169
|
+
transportIsCurrent: facts.transportIsCurrent,
|
|
170
|
+
hostId: runtime.id,
|
|
171
|
+
keepAlive: facts.keepAlive,
|
|
172
|
+
remoteStarted: facts.remoteStarted,
|
|
173
|
+
recoverable: facts.recoverable,
|
|
174
|
+
delays: facts.delays,
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
/* ── refusal handling ───────────────────────────────────────────────────────────────────── */
|
|
178
|
+
/** What a refusal means for this caller, as the design's three-tier rule states it. */
|
|
179
|
+
function reportRefusal(host, runtime, event, reason, caller) {
|
|
180
|
+
if (caller === 'script')
|
|
181
|
+
throw new IllegalTransition(reason, event.type);
|
|
182
|
+
// The idle timer firing for a host that is wanted again is the normal race, not a fault: it
|
|
183
|
+
// keeps today's debug line (and its exact wording), which is what the operator's log shows.
|
|
184
|
+
if (event.type === 'idle.elapsed') {
|
|
185
|
+
host.log(runtime, 'debug', 'idle stop skipped: the host is connected again');
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
if (caller === 'silent')
|
|
189
|
+
return;
|
|
190
|
+
// A callback that lost the race is a warning; a timer is expected (a reconnected host's idle
|
|
191
|
+
// timer, a retry a user disconnect made stale) and must not warn.
|
|
192
|
+
host.log(runtime, caller === 'timer' ? 'debug' : 'warn', `state transition refused (${event.type}: ${reason})`);
|
|
193
|
+
}
|
|
194
|
+
/* ── effect execution ───────────────────────────────────────────────────────────────────── */
|
|
195
|
+
/**
|
|
196
|
+
* The teardown options one event really uses.
|
|
197
|
+
*
|
|
198
|
+
* §2.4.2's `connect.cancelled` row says `{stopRemote:false, keepRemote:true}`; today's cancel
|
|
199
|
+
* branch releases exactly like a failure (`stopRemote` only under the `stop` keep-alive policy,
|
|
200
|
+
* `keepRemote` otherwise). Behavior freeze keeps the failure's options — a cancellation after the
|
|
201
|
+
* remote was started under `keepAlive: 'stop'` must still stop it.
|
|
202
|
+
* @param effect - the rule's teardown effect.
|
|
203
|
+
* @param event - the event being executed.
|
|
204
|
+
* @param scope - the read-only facts (remote started? which keep-alive policy?).
|
|
205
|
+
* @returns the options to hand to the teardown path.
|
|
206
|
+
*/
|
|
207
|
+
function teardownOptions(effect, event, scope) {
|
|
208
|
+
if (event.type !== 'connect.cancelled')
|
|
209
|
+
return effect.options;
|
|
210
|
+
return {
|
|
211
|
+
stopRemote: scope.remoteStarted && scope.keepAlive === 'stop',
|
|
212
|
+
keepRemote: scope.remoteStarted && scope.keepAlive !== 'stop',
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* Execute the effects of one accepted transition, in the order the rule lists them.
|
|
217
|
+
* @param host - the effect owner bound to this caller's context.
|
|
218
|
+
* @param runtime - the host runtime the transition was computed for.
|
|
219
|
+
* @param event - the event that produced the effects.
|
|
220
|
+
* @param scope - the read-only facts of that event.
|
|
221
|
+
* @param effects - the rule's effect list.
|
|
222
|
+
* @param options - per-call hooks.
|
|
223
|
+
*/
|
|
224
|
+
async function runEffects(host, runtime, event, scope, effects, options) {
|
|
225
|
+
for (const effect of effects) {
|
|
226
|
+
switch (effect.type) {
|
|
227
|
+
case 'emit':
|
|
228
|
+
if (options.emit !== false)
|
|
229
|
+
host.emit();
|
|
230
|
+
break;
|
|
231
|
+
case 'flushLogs':
|
|
232
|
+
host.flushLogs(runtime);
|
|
233
|
+
break;
|
|
234
|
+
case 'log':
|
|
235
|
+
host.log(runtime, effect.level, effect.message);
|
|
236
|
+
break;
|
|
237
|
+
case 'logFailure':
|
|
238
|
+
host.logFailure(runtime, effect.phase, effect.label, effect.view);
|
|
239
|
+
break;
|
|
240
|
+
case 'arm':
|
|
241
|
+
if (effect.timer === 'reconnect') {
|
|
242
|
+
// Single source: see the module comment. Only `reconnect.scheduled` owns the timer.
|
|
243
|
+
if (event.type === 'reconnect.scheduled')
|
|
244
|
+
options.armReconnect?.(effect.ms);
|
|
245
|
+
}
|
|
246
|
+
else {
|
|
247
|
+
host.arm(runtime, effect.timer, effect.ms);
|
|
248
|
+
}
|
|
249
|
+
break;
|
|
250
|
+
case 'disarm':
|
|
251
|
+
host.disarm(runtime, effect.timer);
|
|
252
|
+
break;
|
|
253
|
+
case 'settlePrompts':
|
|
254
|
+
host.settlePrompts(runtime);
|
|
255
|
+
break;
|
|
256
|
+
case 'closeLink':
|
|
257
|
+
if (options.keepLink !== true)
|
|
258
|
+
host.closeLink(runtime);
|
|
259
|
+
break;
|
|
260
|
+
case 'teardown':
|
|
261
|
+
if (options.keepLink !== true) {
|
|
262
|
+
const chosen = options.teardown ?? teardownOptions(effect, event, scope);
|
|
263
|
+
await host.teardown(runtime, chosen, event);
|
|
264
|
+
}
|
|
265
|
+
break;
|
|
266
|
+
case 'apply':
|
|
267
|
+
// `mark-detached` describes a released link; a caller that keeps the link must not
|
|
268
|
+
// publish `uiReady:false`/`localPort:null` for a listener that is still serving.
|
|
269
|
+
if (options.keepLink === true && effect.patch.kind === 'mark-detached')
|
|
270
|
+
break;
|
|
271
|
+
host.apply(runtime, effect.patch);
|
|
272
|
+
break;
|
|
273
|
+
case 'run':
|
|
274
|
+
if (options.run === undefined) {
|
|
275
|
+
// Only the request events carry `run`, and every entry point supplies it. Reaching this
|
|
276
|
+
// branch is a wiring bug, not a runtime condition.
|
|
277
|
+
throw new Error(`dispatch: the ${event.type} event needs a run hook`);
|
|
278
|
+
}
|
|
279
|
+
options.run(effect.activity, effect.token);
|
|
280
|
+
break;
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
/* ── the dispatcher ─────────────────────────────────────────────────────────────────────── */
|
|
285
|
+
/**
|
|
286
|
+
* Apply one event to a runtime's session block and perform its effects.
|
|
287
|
+
*
|
|
288
|
+
* The state write happens before the first effect, so a script that resumes after an `await`
|
|
289
|
+
* inside an effect list sees the state the table produced (the connect catch depends on this to
|
|
290
|
+
* classify a failure).
|
|
291
|
+
* @param host - the effects, bound to the caller's service context.
|
|
292
|
+
* @param runtime - the host runtime.
|
|
293
|
+
* @param event - one of the 31 events.
|
|
294
|
+
* @param facts - the read-only scope facts.
|
|
295
|
+
* @param options - caller semantics and the per-call effect hooks.
|
|
296
|
+
* @returns the transition result: `ok:true` after the effects ran, or the refusal (state unchanged).
|
|
297
|
+
* @throws IllegalTransition only for a `script` caller, i.e. inside a one-shot action.
|
|
298
|
+
*/
|
|
299
|
+
export async function dispatch(host, runtime, event, facts, options = {}) {
|
|
300
|
+
const caller = options.caller ?? 'script';
|
|
301
|
+
const scope = scopeFor(event, runtime, facts);
|
|
302
|
+
const result = transition(readSession(runtime), event, scope);
|
|
303
|
+
if (isRefusal(result)) {
|
|
304
|
+
reportRefusal(host, runtime, event, result.reason, caller);
|
|
305
|
+
return result;
|
|
306
|
+
}
|
|
307
|
+
writeBack(runtime, result.state);
|
|
308
|
+
await runEffects(host, runtime, event, scope, result.effects, options);
|
|
309
|
+
return result;
|
|
310
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { cancelConflict, cancelHostKeyPrompt } from '../prompts.js';
|
|
2
|
+
import { cancelIdleStop, cancelReconnect, closeTunnel, releaseRuntimeForShutdown, scheduleIdleStop, stopRemoteHeartbeat, teardownRuntime, } from '../host-lifecycle.js';
|
|
3
|
+
import { startRemoteHeartbeat } from '../watchdog.js';
|
|
4
|
+
/**
|
|
5
|
+
* `mark-attached` also resets the link block's repair budget: today's `markConnected` owns both
|
|
6
|
+
* halves of the same fact, and until `connect/link.ts#markAttached` exists (P2 step 7) this patch
|
|
7
|
+
* is where the link half lands.
|
|
8
|
+
* @param runtime - the host runtime being attached.
|
|
9
|
+
*/
|
|
10
|
+
function markAttached(runtime) {
|
|
11
|
+
runtime.remote.uiReady = true;
|
|
12
|
+
runtime.remote.viewRev = (Number(runtime.remote.viewRev) || 0) + 1;
|
|
13
|
+
runtime.tunnelRepairFailures = 0;
|
|
14
|
+
runtime.nextTunnelRepairAt = 0;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Build the effect owner for one caller.
|
|
18
|
+
* @param ctx - the reporter, and the state/deps a teardown needs.
|
|
19
|
+
* @returns the actions `dispatch()` performs.
|
|
20
|
+
*/
|
|
21
|
+
export function createRuntimeEffects(ctx) {
|
|
22
|
+
return {
|
|
23
|
+
emit: () => ctx.emitState(),
|
|
24
|
+
log: (runtime, level, message) => ctx.progress.log(runtime, level, message),
|
|
25
|
+
logFailure: (runtime, phase, label, view) => ctx.progress.logFailure(runtime, view ?? runtime.error, { phase, label }),
|
|
26
|
+
arm: (runtime, timer, _ms) => {
|
|
27
|
+
if (timer === 'idle') {
|
|
28
|
+
scheduleIdleStop(ctx, runtime);
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
startRemoteHeartbeat(ctx, runtime);
|
|
32
|
+
},
|
|
33
|
+
disarm: (runtime, timer) => {
|
|
34
|
+
if (timer === 'reconnect')
|
|
35
|
+
cancelReconnect(runtime);
|
|
36
|
+
else if (timer === 'idle')
|
|
37
|
+
cancelIdleStop(runtime);
|
|
38
|
+
else
|
|
39
|
+
stopRemoteHeartbeat(runtime);
|
|
40
|
+
},
|
|
41
|
+
settlePrompts: (runtime) => {
|
|
42
|
+
// The teardown path does the same pair first; both are idempotent by contract (M1).
|
|
43
|
+
cancelHostKeyPrompt(runtime);
|
|
44
|
+
cancelConflict(runtime);
|
|
45
|
+
},
|
|
46
|
+
closeLink: (runtime) => {
|
|
47
|
+
void closeTunnel(runtime);
|
|
48
|
+
},
|
|
49
|
+
teardown: async (runtime, options) => {
|
|
50
|
+
if (options.shutdown === true) {
|
|
51
|
+
await releaseRuntimeForShutdown(ctx, runtime, options.stopRemote === true);
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
await teardownRuntime(ctx, runtime, {
|
|
55
|
+
stopRemote: options.stopRemote === true,
|
|
56
|
+
...(options.keepRemote === true ? { keepRemote: true } : {}),
|
|
57
|
+
...(options.keepSshForIdle === true ? { keepSshForIdle: true } : {}),
|
|
58
|
+
});
|
|
59
|
+
},
|
|
60
|
+
apply: (runtime, patch) => {
|
|
61
|
+
if (patch.kind === 'mark-attached') {
|
|
62
|
+
markAttached(runtime);
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
if (patch.kind === 'mark-detached') {
|
|
66
|
+
runtime.remote.uiReady = false;
|
|
67
|
+
runtime.remote.localPort = null;
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
if (patch.kind === 'mark-ui-up') {
|
|
71
|
+
runtime.remote.uiReady = true;
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
if (patch.kind === 'clear-conflict') {
|
|
75
|
+
runtime.conflict = null;
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
if (patch.kind === 'publish-active-host') {
|
|
79
|
+
ctx.state.activeHostId = patch.hostId;
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
// `restore-stop`: the two `remote` fields a failed stop has to put back.
|
|
83
|
+
runtime.remote.uiReady = patch.uiReady === true;
|
|
84
|
+
runtime.remote.localPort = patch.localPort;
|
|
85
|
+
},
|
|
86
|
+
flushLogs: () => {
|
|
87
|
+
// `connect-progress` owns the coalescing flush timer; `log()` already scheduled it. No rule
|
|
88
|
+
// emits `flushLogs` today, and this stays a no-op instead of reaching into that module.
|
|
89
|
+
},
|
|
90
|
+
};
|
|
91
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/** The 31 event names, in the order design-arch §2.4.2 lists them (minus the three dead `remote.*`). */
|
|
2
|
+
export const EVENT_TYPES = [
|
|
3
|
+
'connect.requested',
|
|
4
|
+
'step.entered',
|
|
5
|
+
'step.done',
|
|
6
|
+
'transport.ready',
|
|
7
|
+
'transport.closed',
|
|
8
|
+
'hostkey.pending',
|
|
9
|
+
'hostkey.answered',
|
|
10
|
+
'hostkey.timeout',
|
|
11
|
+
'conflict.pending',
|
|
12
|
+
'conflict.answered',
|
|
13
|
+
'connect.succeeded',
|
|
14
|
+
'connect.cancelled',
|
|
15
|
+
'connect.failed',
|
|
16
|
+
'disconnect.requested',
|
|
17
|
+
'idle.elapsed',
|
|
18
|
+
'repair.requested',
|
|
19
|
+
'repair.finished',
|
|
20
|
+
'restart.requested',
|
|
21
|
+
'restart.resumed',
|
|
22
|
+
'restart.failed',
|
|
23
|
+
'stop.requested',
|
|
24
|
+
'stop.refused',
|
|
25
|
+
'stop.succeeded',
|
|
26
|
+
'reattach.requested',
|
|
27
|
+
'reattach.failed',
|
|
28
|
+
'reconnect.scheduled',
|
|
29
|
+
'reconnect.gaveup',
|
|
30
|
+
'reconnect.skipped',
|
|
31
|
+
'link.cancelled',
|
|
32
|
+
'shutdown',
|
|
33
|
+
'host.removed',
|
|
34
|
+
];
|
|
35
|
+
export const EVENT_TYPE_PARITY = true;
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `HostRuntime.session` state machine: a pure `transition(state, event, scope)`, plus the
|
|
3
|
+
* types and the write-back the executor uses.
|
|
4
|
+
*
|
|
5
|
+
* The transition table itself (one `Record<EventType, Rule>` row per event, its guards and its
|
|
6
|
+
* effects) lives in `rules.ts` next door; this file is the engine that looks a row up and applies
|
|
7
|
+
* it. Both halves together are the only place allowed to decide what a host runtime's session block
|
|
8
|
+
* becomes next (design-arch §2.4). Neither imports I/O: no runtime object, no clock, no settings,
|
|
9
|
+
* no timers. Everything outside the state arrives as a frozen `EventScope`; everything the
|
|
10
|
+
* executor has to do arrives as an `Effect` it performs itself. `test/unit/fsm.test.ts` drives all
|
|
11
|
+
* 8 statuses × 6 activities × 2 desires × 2 closing flags = 192 representative states against all
|
|
12
|
+
* 31 events (5,952 pairs) and asserts every pair has an explicit outcome: `ok: true` with effects,
|
|
13
|
+
* or `ok: false` with a `RefusalReason` — never an "unhandled" third shape.
|
|
14
|
+
*
|
|
15
|
+
* The machine does **not** own liveness. `remote.suspected/confirmed/recovered` used to live here
|
|
16
|
+
* and were never dispatched (nothing in `src/` ever emitted one); the watchdog (`watchdog.ts`) owns
|
|
17
|
+
* `remoteEpisode`/`episodeSource`/`remoteFailures`/`episodeCooldownUntil` and publishes its own
|
|
18
|
+
* bus events, so a second liveness writer in the FSM would have been a second source of truth.
|
|
19
|
+
*
|
|
20
|
+
* The table is a `Record<EventType, Rule>` over the 31 names `events.ts` declares, so a missing
|
|
21
|
+
* event is a compile error and an unlisted event cannot reach a rule. A refused transition returns
|
|
22
|
+
* the *same* state object: "invalid transitions never modify the state" is structural, not a
|
|
23
|
+
* promise the implementation has to remember.
|
|
24
|
+
*
|
|
25
|
+
* Semantics worth calling out (all from §2.4.5):
|
|
26
|
+
* - `activity` is the single flight lock. `null` means no one-shot action owns the link, so every
|
|
27
|
+
* entry point except `connect.requested` requires it; `connect.requested` refuses with
|
|
28
|
+
* `already-connecting`/`already-restarting`/`already-connected`, the strings `api.ts` passes on.
|
|
29
|
+
* - `epoch` (== the storage field `linkToken`) is the late-write filter. Request events adopt the
|
|
30
|
+
* caller's token through `epochAfter()`, which never lets the number go backwards; cancel events
|
|
31
|
+
* bump it. A late script compares `state.epoch` with its own token and stops writing.
|
|
32
|
+
* - `desired` is what the user wants, `status` is what is observed; they are deliberately not
|
|
33
|
+
* derived from each other.
|
|
34
|
+
*/
|
|
35
|
+
import { TABLE } from './rules.js';
|
|
36
|
+
/** The exhaustive list of refusals, for tests that assert "no third outcome" (§7.6). */
|
|
37
|
+
export const REFUSALS = [
|
|
38
|
+
'illegal-transition',
|
|
39
|
+
'unknown-event',
|
|
40
|
+
'already-connecting',
|
|
41
|
+
'already-restarting',
|
|
42
|
+
'already-connected',
|
|
43
|
+
'not-connected',
|
|
44
|
+
'not-recoverable',
|
|
45
|
+
'busy',
|
|
46
|
+
'prompt-not-pending',
|
|
47
|
+
'stale-prompt',
|
|
48
|
+
];
|
|
49
|
+
export function isRefusal(result) {
|
|
50
|
+
return result.ok === false;
|
|
51
|
+
}
|
|
52
|
+
/** Never reaches `ErrorView`: only a script that ran into a refusal treats it as a bug (§7.6). */
|
|
53
|
+
export class IllegalTransition extends Error {
|
|
54
|
+
code = 'illegal-transition';
|
|
55
|
+
eventType;
|
|
56
|
+
constructor(reason, eventType) {
|
|
57
|
+
super(`illegal transition: ${eventType} refused (${reason})`);
|
|
58
|
+
this.name = 'IllegalTransition';
|
|
59
|
+
this.eventType = eventType;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
/* ── the two shared predicates (single implementation, §2.4.4) ────────────────────────────── */
|
|
63
|
+
/** "The user still wants this link, and this process still owns the runtime." */
|
|
64
|
+
export function stillWanted(state, scope) {
|
|
65
|
+
return state.desired === 'connected' && !state.closing && scope.runtimeExists && !scope.disposed;
|
|
66
|
+
}
|
|
67
|
+
/** `state.epoch === token`: a one-shot action may write (R4). */
|
|
68
|
+
export function isActivityCurrent(state, token) {
|
|
69
|
+
return state.epoch === token;
|
|
70
|
+
}
|
|
71
|
+
/* ── write-back ─────────────────────────────────────────────────────────────────────────── */
|
|
72
|
+
/** Put the session block of a runtime back to the state the machine produced (§7.6). */
|
|
73
|
+
export function writeBack(runtime, state) {
|
|
74
|
+
runtime.status = state.status;
|
|
75
|
+
runtime.desired = state.desired;
|
|
76
|
+
runtime.linkBusy = state.activity;
|
|
77
|
+
runtime.linkToken = state.epoch;
|
|
78
|
+
runtime.phase = state.phase;
|
|
79
|
+
runtime.progress = state.progress;
|
|
80
|
+
runtime.error = state.error;
|
|
81
|
+
runtime.warning = state.warning;
|
|
82
|
+
runtime.warningSource = state.warningSource;
|
|
83
|
+
runtime.closing = state.closing;
|
|
84
|
+
runtime.connectCancelled = state.connectCancelled;
|
|
85
|
+
runtime.transportLost = state.transportLost;
|
|
86
|
+
runtime.reconnectAttempts = state.reconnectAttempts;
|
|
87
|
+
// The liveness fields (`remoteFailures`/`remoteEpisode`/`episodeSource`/`episodeCooldownUntil`)
|
|
88
|
+
// are deliberately absent: `watchdog.ts` is their only writer (B9); see docs/invariants.md.
|
|
89
|
+
}
|
|
90
|
+
/* ── the pure function ───────────────────────────────────────────────────────────────────── */
|
|
91
|
+
/**
|
|
92
|
+
* Look one rule up by its event name. Generic on the key so the returned rule keeps the *narrow*
|
|
93
|
+
* event payload of that row: `TABLE[event.type]` in `transition` would otherwise be a union of 31
|
|
94
|
+
* rule types with 31 different parameter types, which TypeScript cannot correlate with the event
|
|
95
|
+
* it was indexed by.
|
|
96
|
+
*/
|
|
97
|
+
function ruleFor(type) {
|
|
98
|
+
return TABLE[type];
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Compute the next state and the effects of one event. Never mutates, never throws, never reads
|
|
102
|
+
* anything but its three arguments.
|
|
103
|
+
* @param state - the session state before the event.
|
|
104
|
+
* @param event - the event to apply (one of the 31 declared types).
|
|
105
|
+
* @param scope - read-only facts the guards and effects need.
|
|
106
|
+
* @returns `{ok:true,state,effects}` for an accepted move; `{ok:false,reason,state}` (same state
|
|
107
|
+
* object) for a refused one.
|
|
108
|
+
*/
|
|
109
|
+
export function transition(state, event, scope) {
|
|
110
|
+
// The table is a record over the 31 declared names, so this lookup cannot miss for a typed
|
|
111
|
+
// caller; the `unknown-event` branch only protects a JavaScript caller from a name the types
|
|
112
|
+
// forbid (and the completeness test asserts it never fires for a declared event).
|
|
113
|
+
const rule = ruleFor(event.type);
|
|
114
|
+
if (rule === undefined)
|
|
115
|
+
return { ok: false, reason: 'unknown-event', state };
|
|
116
|
+
const verdict = rule.guard(state, event, scope);
|
|
117
|
+
if (verdict !== true)
|
|
118
|
+
return { ok: false, reason: verdict, state };
|
|
119
|
+
return { ok: true, state: rule.apply(state, event, scope), effects: rule.effects(state, event, scope) };
|
|
120
|
+
}
|