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.
- package/README.md +1 -0
- package/dist/client.js +1348 -2095
- package/dist/src/admission.js +3 -28
- package/dist/src/api.js +37 -99
- package/dist/src/atomic-json.js +32 -66
- package/dist/src/bootstrap.js +17 -27
- package/dist/src/connect/attach.js +3 -25
- package/dist/src/connect/bootstrap.js +2 -8
- package/dist/src/connect/failures.js +3 -18
- package/dist/src/connect/guards.js +13 -8
- package/dist/src/connect/launch.js +11 -21
- package/dist/src/connect/links.js +11 -27
- package/dist/src/connect/ownership.js +33 -114
- package/dist/src/connect/pipeline.js +62 -159
- package/dist/src/connect/reattach.js +26 -44
- package/dist/src/connect/registry.js +0 -1
- package/dist/src/connect/repair.js +8 -37
- package/dist/src/connect/restart.js +36 -97
- package/dist/src/connect/stop.js +16 -50
- package/dist/src/connect/transport.js +10 -18
- package/dist/src/connect/verify.js +3 -12
- package/dist/src/connect/watchdog.js +6 -38
- package/dist/src/connect-log.js +16 -41
- package/dist/src/connect-progress.js +13 -45
- package/dist/src/constants.js +18 -43
- package/dist/src/context.js +13 -32
- package/dist/src/diagnostics.js +56 -25
- package/dist/src/download-jobs.js +11 -20
- package/dist/src/errors.js +175 -190
- package/dist/src/events.js +20 -84
- package/dist/src/host-lifecycle.js +69 -177
- package/dist/src/host-registry.js +27 -78
- package/dist/src/host-runtime.js +0 -9
- package/dist/src/host-view.js +6 -29
- package/dist/src/index.js +15 -35
- package/dist/src/kernel-adapter.js +34 -80
- package/dist/src/key-files.js +10 -23
- package/dist/src/known-hosts.js +13 -34
- package/dist/src/layout.js +3 -20
- package/dist/src/local-download.js +94 -163
- package/dist/src/local-ssh.js +12 -19
- package/dist/src/local-version.js +35 -49
- package/dist/src/node/download.js +1 -4
- package/dist/src/node-runtime.js +19 -38
- package/dist/src/probe.js +6 -7
- package/dist/src/prompts.js +56 -128
- package/dist/src/proxy/cookies.js +26 -60
- package/dist/src/proxy/headers.js +30 -125
- package/dist/src/proxy/http.js +33 -41
- package/dist/src/proxy/index.js +20 -34
- package/dist/src/proxy/limits.js +4 -6
- package/dist/src/proxy/routes.js +10 -17
- package/dist/src/proxy/upgrade.js +27 -42
- package/dist/src/redact.js +14 -33
- package/dist/src/remote-files.js +9 -21
- package/dist/src/remote-path.js +21 -62
- package/dist/src/remote-proc.js +35 -103
- package/dist/src/remote-web/registry.js +10 -50
- package/dist/src/remote-web/resolve.js +23 -104
- package/dist/src/remote-web/start.js +27 -64
- package/dist/src/remote-web/stop.js +6 -25
- package/dist/src/request-trust.js +15 -32
- package/dist/src/runtime/dispatch.js +33 -143
- package/dist/src/runtime/effects.js +7 -17
- package/dist/src/runtime/events.js +1 -1
- package/dist/src/runtime/fsm.js +11 -61
- package/dist/src/runtime/rules.js +121 -199
- package/dist/src/secrets.js +15 -38
- package/dist/src/service.js +22 -128
- package/dist/src/settings.js +41 -42
- package/dist/src/ssh-config.js +22 -41
- package/dist/src/ssh-failures.js +23 -74
- package/dist/src/ssh-sftp.js +47 -86
- package/dist/src/ssh.js +99 -179
- package/dist/src/store.js +31 -48
- package/dist/src/tool-shared.js +17 -52
- package/dist/src/tools-exec-policy.js +33 -79
- package/dist/src/tools-exec.js +87 -151
- package/dist/src/tools-report.js +100 -167
- package/dist/src/tools.js +59 -133
- package/dist/src/tunnel.js +9 -27
- package/dist/src/util.js +19 -56
- package/dist/src/version.js +6 -12
- package/dist/src/watchdog-bus.js +0 -8
- package/dist/src/watchdog.js +7 -47
- package/package.json +3 -3
|
@@ -1,16 +1,10 @@
|
|
|
1
|
-
/**
|
|
2
|
-
*
|
|
3
|
-
* an instance an earlier local run left behind, the real version a process runs, and the
|
|
4
|
-
* re-attach probe that refuses a candidate it cannot prove (`no-token`, `identity-*`, …).
|
|
5
|
-
*
|
|
6
|
-
* Everything here answers "what is running, and may this connection talk to it?"; starting and
|
|
7
|
-
* stopping live in `start.ts` / `stop.ts`, and the run-registry record in `registry.ts`.
|
|
8
|
-
*/
|
|
1
|
+
/** Probing the remote DSH web: the `dsh web:` readiness line, pid liveness, adoption, the real version a process
|
|
2
|
+
* runs, and the re-attach probe that refuses a candidate it cannot prove. */
|
|
9
3
|
import { DEFAULT_REMOTE_PROFILE } from '../constants.js';
|
|
10
4
|
import { findForeignDshProcesses, isUiUp, remoteHttpStatus, remoteListenPorts, remotePortOwnerPid, remoteProcessIdentity, } from '../remote-proc.js';
|
|
11
5
|
import { isLoopbackHost, isPid, shellQuote } from '../util.js';
|
|
12
6
|
import { normalizeVersion } from '../version.js';
|
|
13
|
-
import { LAUNCH_MARKER, isPlainObjectValue, readRunRegistry } from './registry.js';
|
|
7
|
+
import { LAUNCH_MARKER, isPlainObjectValue, readRunRegistry, registryNamesInstance } from './registry.js';
|
|
14
8
|
const WEB_LINE_RE = /dsh web:\s*(https?:\/\/[^\s]+)/;
|
|
15
9
|
export function parseWebLine(text) {
|
|
16
10
|
const match = WEB_LINE_RE.exec(String(text ?? ''));
|
|
@@ -55,39 +49,24 @@ export async function remotePidAlive(ssh, pid) {
|
|
|
55
49
|
return false;
|
|
56
50
|
}
|
|
57
51
|
}
|
|
58
|
-
/**
|
|
59
|
-
* Try to adopt a still-running remote web instance from a previous local
|
|
60
|
-
* process: registry pid alive + last log line parseable + loopback HTTP alive.
|
|
61
|
-
*
|
|
62
|
-
* The registry must name the same DSH home and profile this connection is about
|
|
63
|
-
* to use; a process left over from another home or profile would show a
|
|
64
|
-
* different DSH state than the user asked for.
|
|
65
|
-
*/
|
|
66
52
|
export async function adoptRemoteWeb(ssh, layout, options = {}) {
|
|
67
53
|
const profile = options.profile ?? DEFAULT_REMOTE_PROFILE;
|
|
68
54
|
const registry = await readRunRegistry(ssh, layout);
|
|
69
|
-
// Instances from a launch path
|
|
70
|
-
// cannot be adopted: the page they serve may be stuck at "failed to load
|
|
71
|
-
// plugins", and nothing on the server side reveals that.
|
|
55
|
+
// Instances from a launch path without the browser-carrier overlay could serve a stuck page: not adoptable.
|
|
72
56
|
if (registry?.launch !== LAUNCH_MARKER)
|
|
73
57
|
return null;
|
|
74
|
-
if (registry?.dshHome !== layout.dshHome)
|
|
75
|
-
return null;
|
|
76
|
-
if (registry?.profile !== profile)
|
|
77
|
-
return null;
|
|
78
58
|
const pid = Number(registry?.pid ?? 0);
|
|
59
|
+
if (!registryNamesInstance(registry, layout, profile, pid))
|
|
60
|
+
return null;
|
|
79
61
|
if (!(await remotePidAlive(ssh, pid)))
|
|
80
62
|
return null;
|
|
81
63
|
const line = await readWebLineFromLog(ssh, layout);
|
|
82
64
|
if (!line || line.token === '')
|
|
83
65
|
return null;
|
|
84
|
-
// An adopted instance is reached through the loopback tunnel only
|
|
85
|
-
// advertises another host cannot be served safely and must not be adopted (adopt parity
|
|
86
|
-
// with a fresh launch, which refuses a non-loopback URL).
|
|
66
|
+
// An adopted instance is reached through the loopback tunnel only, exactly like a fresh launch.
|
|
87
67
|
if (!isLoopbackHost(line.host))
|
|
88
68
|
return null;
|
|
89
|
-
|
|
90
|
-
if (!isUiUp(status))
|
|
69
|
+
if (!isUiUp(await remoteHttpStatus(ssh, line.port)))
|
|
91
70
|
return null;
|
|
92
71
|
const version = typeof registry?.version === 'string' && registry.version !== '' ? normalizeVersion(registry.version) : null;
|
|
93
72
|
return {
|
|
@@ -99,13 +78,9 @@ export async function adoptRemoteWeb(ssh, layout, options = {}) {
|
|
|
99
78
|
profile,
|
|
100
79
|
dshHome: layout.dshHome,
|
|
101
80
|
adopted: true,
|
|
102
|
-
// Only a record written by the launch script (or a local restart) proves the process was
|
|
103
|
-
// started by this plugin; a re-attached record names a process the remote restarted itself
|
|
104
|
-
// and must not grant kill rights to the next connection.
|
|
105
81
|
origin: registry.origin === 'reattach' ? 'reattach' : 'launch',
|
|
106
82
|
};
|
|
107
83
|
}
|
|
108
|
-
/** Whether a `ps` command line is the DSH process for this profile. */
|
|
109
84
|
export function commandMatchesProfile(command, profile) {
|
|
110
85
|
const wanted = String(profile ?? '');
|
|
111
86
|
if (wanted === '')
|
|
@@ -113,41 +88,32 @@ export function commandMatchesProfile(command, profile) {
|
|
|
113
88
|
const escaped = wanted.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
114
89
|
return new RegExp(`--profile[=\\s]+${escaped}(?:\\s|$)`).test(String(command ?? ''));
|
|
115
90
|
}
|
|
116
|
-
/** The pinned `@deepseek-ai/dsh@<version>` an npx command line names, if any. */
|
|
117
91
|
export function versionFromCommand(command) {
|
|
118
92
|
const match = /@deepseek-ai\/dsh@([^\s'"]+)/.exec(String(command ?? ''));
|
|
119
93
|
return match ? normalizeVersion(match[1]) : null;
|
|
120
94
|
}
|
|
121
|
-
/**
|
|
122
|
-
* The installed package directory a real node argv names, e.g.
|
|
123
|
-
* `/home/u/.npm/_npx/<hash>/node_modules/@deepseek-ai/dsh` or an app install path.
|
|
124
|
-
* The version is read from that directory's `package.json` (the argv itself does not
|
|
125
|
-
* carry one in the npx-cache and app-install shapes).
|
|
126
|
-
*/
|
|
127
95
|
export function dshPackageDirFromCommand(command) {
|
|
128
96
|
const text = String(command ?? '');
|
|
129
97
|
const marker = '/node_modules/@deepseek-ai/dsh';
|
|
130
|
-
// Linear scan on purpose: a nested-quantifier regex over an argv with many `/` segments can be
|
|
131
|
-
// made to backtrack exponentially, and the command line is remote input.
|
|
132
98
|
let at = text.indexOf(marker);
|
|
133
99
|
while (at !== -1) {
|
|
134
|
-
|
|
135
|
-
if (/^(?:\/lib\/bin\.js|[\s'"]|$)/.test(rest)) {
|
|
100
|
+
if (/^(?:\/lib\/bin\.js|[\s'"]|$)/.test(text.slice(at + marker.length))) {
|
|
136
101
|
let start = at;
|
|
137
102
|
while (start > 0 && !/[\s'"]/.test(text[start - 1]))
|
|
138
103
|
start -= 1;
|
|
139
104
|
const dir = text.slice(start, at + marker.length);
|
|
140
|
-
|
|
141
|
-
return dir;
|
|
142
|
-
return null;
|
|
105
|
+
return dir.startsWith('/') && !dir.split('/').includes('..') ? dir : null;
|
|
143
106
|
}
|
|
144
107
|
at = text.indexOf(marker, at + marker.length);
|
|
145
108
|
}
|
|
146
109
|
return null;
|
|
147
110
|
}
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
if (
|
|
111
|
+
export async function remoteDshVersion(ssh, command) {
|
|
112
|
+
const pinned = versionFromCommand(command);
|
|
113
|
+
if (pinned)
|
|
114
|
+
return pinned;
|
|
115
|
+
const dir = dshPackageDirFromCommand(command);
|
|
116
|
+
if (dir === null || typeof ssh.readRemoteFile !== 'function')
|
|
151
117
|
return null;
|
|
152
118
|
try {
|
|
153
119
|
const file = await ssh.readRemoteFile(`${dir}/package.json`, { maxBytes: 64 * 1024 });
|
|
@@ -161,43 +127,15 @@ async function packageVersionFromDir(ssh, dir) {
|
|
|
161
127
|
return null;
|
|
162
128
|
}
|
|
163
129
|
}
|
|
164
|
-
/**
|
|
165
|
-
* The real version a remote DSH process runs: the pinned npx spec when there is one,
|
|
166
|
-
* otherwise the `package.json` of the package its argv loaded. Null when it cannot be
|
|
167
|
-
* proven - the caller must not fill in the local version.
|
|
168
|
-
*/
|
|
169
|
-
export async function remoteDshVersion(ssh, command) {
|
|
170
|
-
const pinned = versionFromCommand(command);
|
|
171
|
-
if (pinned)
|
|
172
|
-
return pinned;
|
|
173
|
-
const dir = dshPackageDirFromCommand(command);
|
|
174
|
-
return dir === null ? null : packageVersionFromDir(ssh, dir);
|
|
175
|
-
}
|
|
176
|
-
/**
|
|
177
|
-
* Re-read the remote's real web state after it restarted: the same pid on a new
|
|
178
|
-
* random port (in-place exec) or a new pid from a supervisor. The run registry is only
|
|
179
|
-
* a hint; a candidate is accepted only when all of these hold:
|
|
180
|
-
*
|
|
181
|
-
* - the listening port belongs to the pid the plugin thinks it owns;
|
|
182
|
-
* - that pid's `/proc` identity proves the same `DSH_HOME` and the same `--profile`;
|
|
183
|
-
* - the newest `dsh web:` line names that exact port, so a launch token is available.
|
|
184
|
-
*
|
|
185
|
-
* A candidate that answers HTTP but has no token is **not** usable: a real DSH answers
|
|
186
|
-
* `/?token=` with 401, so claiming success would be dishonest. The process-scan fallback
|
|
187
|
-
* therefore never yields a takeover; it only turns the failure reason into `no-token`
|
|
188
|
-
* ("still running, but no way to authenticate") so the user gets the right remedy.
|
|
189
|
-
*/
|
|
190
130
|
export async function resolveRemoteWeb(ssh, layout, options = {}) {
|
|
191
131
|
const profile = options.profile ?? DEFAULT_REMOTE_PROFILE;
|
|
192
132
|
const registry = await readRunRegistry(ssh, layout);
|
|
193
133
|
const line = await readWebLineFromLog(ssh, layout);
|
|
194
|
-
const registryMatches = registry !== null &&
|
|
195
|
-
registry.dshHome === layout.dshHome &&
|
|
196
|
-
registry.profile === profile &&
|
|
197
|
-
registry.launch === LAUNCH_MARKER;
|
|
198
134
|
const registryPid = Number(registry?.pid ?? 0);
|
|
199
135
|
const registryVersion = typeof registry?.version === 'string' && registry.version !== '' ? normalizeVersion(registry.version) : null;
|
|
200
|
-
const alive =
|
|
136
|
+
const alive = registryNamesInstance(registry, layout, profile, registryPid) &&
|
|
137
|
+
registry?.launch === LAUNCH_MARKER &&
|
|
138
|
+
(await remotePidAlive(ssh, registryPid));
|
|
201
139
|
let listeners = null;
|
|
202
140
|
const listenersOf = async (pid) => {
|
|
203
141
|
if (listeners === null)
|
|
@@ -206,20 +144,16 @@ export async function resolveRemoteWeb(ssh, layout, options = {}) {
|
|
|
206
144
|
};
|
|
207
145
|
let tokenlessPort = 0;
|
|
208
146
|
let firstFailure = null;
|
|
209
|
-
/**
|
|
210
|
-
* Accept one reachable candidate only when its identity and its token both check out.
|
|
211
|
-
* Returns null for "reachable but no token" and a typed failure for "wrong process".
|
|
212
|
-
*/
|
|
213
147
|
const take = async (pid, port, source) => {
|
|
214
148
|
const identity = await remoteProcessIdentity(ssh, pid);
|
|
215
149
|
if (identity.ok !== true)
|
|
216
150
|
return { ok: false, reason: `identity-${identity.reason}` };
|
|
217
151
|
if (!commandMatchesProfile(identity.command, profile))
|
|
218
152
|
return { ok: false, reason: 'profile-mismatch' };
|
|
219
|
-
if (identity.dshHome === '' || identity.dshHome !== layout.dshHome)
|
|
153
|
+
if (identity.dshHome === '' || identity.dshHome !== layout.dshHome)
|
|
220
154
|
return { ok: false, reason: 'dsh-home-mismatch' };
|
|
221
|
-
}
|
|
222
155
|
const token = line !== null && line.port === port ? line.token : '';
|
|
156
|
+
// A candidate that answers HTTP but has no token is not usable: a real DSH answers `/?token=` with 401.
|
|
223
157
|
if (token === '') {
|
|
224
158
|
tokenlessPort = port;
|
|
225
159
|
return null;
|
|
@@ -231,7 +165,6 @@ export async function resolveRemoteWeb(ssh, layout, options = {}) {
|
|
|
231
165
|
port,
|
|
232
166
|
token,
|
|
233
167
|
url: line.url,
|
|
234
|
-
// Never backfill the local version: an unproven version stays null.
|
|
235
168
|
version: proven ?? (pid === registryPid ? registryVersion : null),
|
|
236
169
|
profile,
|
|
237
170
|
dshHome: identity.dshHome,
|
|
@@ -242,9 +175,6 @@ export async function resolveRemoteWeb(ssh, layout, options = {}) {
|
|
|
242
175
|
if (candidate !== null && candidate.ok !== true && firstFailure === null)
|
|
243
176
|
firstFailure = candidate;
|
|
244
177
|
};
|
|
245
|
-
// 1. The instance this plugin started: the registry still names a live pid. Only ports
|
|
246
|
-
// that pid actually listens on are candidates, and the readiness line must name the
|
|
247
|
-
// same port for its launch token to be used.
|
|
248
178
|
if (alive) {
|
|
249
179
|
const candidates = [...(await listenersOf(registryPid))];
|
|
250
180
|
if (isPid(Number(registry?.port ?? 0)))
|
|
@@ -252,8 +182,6 @@ export async function resolveRemoteWeb(ssh, layout, options = {}) {
|
|
|
252
182
|
for (const port of [...new Set(candidates.filter((value) => isPid(value) && value <= 65535))]) {
|
|
253
183
|
if (!isUiUp(await remoteHttpStatus(ssh, port)))
|
|
254
184
|
continue;
|
|
255
|
-
// The port must belong to the pid whose identity we are about to trust. Without a
|
|
256
|
-
// readable owner (restricted /proc) the candidate is refused: fail closed.
|
|
257
185
|
const owner = await remotePortOwnerPid(ssh, port);
|
|
258
186
|
if (!isPid(owner) || owner !== registryPid)
|
|
259
187
|
continue;
|
|
@@ -263,14 +191,10 @@ export async function resolveRemoteWeb(ssh, layout, options = {}) {
|
|
|
263
191
|
rememberFailure(candidate);
|
|
264
192
|
}
|
|
265
193
|
}
|
|
266
|
-
// 2. A readiness line for a port owned by some other pid (the market restart re-execs
|
|
267
|
-
// in place, or a supervisor re-launched it). The owner pid must prove itself.
|
|
268
194
|
if (line !== null && isPid(line.port) && isUiUp(await remoteHttpStatus(ssh, line.port))) {
|
|
269
195
|
let pid = 0;
|
|
270
196
|
if (alive && (await listenersOf(registryPid)).includes(line.port))
|
|
271
197
|
pid = registryPid;
|
|
272
|
-
// The owner lookup is authoritative even when the registry pid is alive: the newest line
|
|
273
|
-
// may belong to another profile's process that shares this plugin's log file.
|
|
274
198
|
if (!isPid(pid))
|
|
275
199
|
pid = await remotePortOwnerPid(ssh, line.port);
|
|
276
200
|
if (isPid(pid)) {
|
|
@@ -283,22 +207,17 @@ export async function resolveRemoteWeb(ssh, layout, options = {}) {
|
|
|
283
207
|
firstFailure = { ok: false, reason: 'pid-unknown' };
|
|
284
208
|
}
|
|
285
209
|
}
|
|
286
|
-
// 3. No usable readiness line (a supervisor may redirect stdout). Find the same-profile
|
|
287
|
-
// DSH process only to explain the failure: without its launch token it cannot be
|
|
288
|
-
// re-attached, so this path never returns ok.
|
|
289
210
|
const scanned = await findForeignDshProcesses(ssh, { ignorePids: alive ? [registryPid] : [] });
|
|
290
211
|
if (scanned.ok === true) {
|
|
291
212
|
for (const process of scanned.processes) {
|
|
292
213
|
if (!commandMatchesProfile(process.command, profile))
|
|
293
214
|
continue;
|
|
294
|
-
const
|
|
295
|
-
for (const port of ports) {
|
|
215
|
+
for (const port of await remoteListenPorts(ssh, process.pid)) {
|
|
296
216
|
if (!isUiUp(await remoteHttpStatus(ssh, port)))
|
|
297
217
|
continue;
|
|
298
218
|
const identity = await remoteProcessIdentity(ssh, process.pid);
|
|
299
|
-
if (identity.ok === true && identity.dshHome === layout.dshHome)
|
|
219
|
+
if (identity.ok === true && identity.dshHome === layout.dshHome)
|
|
300
220
|
return { ok: false, reason: 'no-token' };
|
|
301
|
-
}
|
|
302
221
|
}
|
|
303
222
|
}
|
|
304
223
|
}
|
|
@@ -6,16 +6,7 @@ import { normalizeVersion } from '../version.js';
|
|
|
6
6
|
import { LAUNCH_MARKER } from './registry.js';
|
|
7
7
|
import { parseWebLine, remotePidAlive } from './resolve.js';
|
|
8
8
|
import { stopRemoteWeb } from './stop.js';
|
|
9
|
-
/** Overlay file the launch passes with `--patch` when the profile disables the carrier. */
|
|
10
9
|
export const BROWSER_CARRIER_PATCH_FILE = 'browser-carrier.patch.yml';
|
|
11
|
-
/**
|
|
12
|
-
* The window shows the remote DSH *web* UI, so the `api-remotes` Remote-Event
|
|
13
|
-
* carrier must stay mounted. A profile bundle aimed at a native companion can
|
|
14
|
-
* disable that row (e.g. goldenpigeon's patch does), which leaves the browser
|
|
15
|
-
* client with `typert gateway: $events: forwarded Remote event source is
|
|
16
|
-
* unavailable` and a blank "failed to load plugins" page. Re-enable the row with
|
|
17
|
-
* a launch-only overlay instead of editing the user's profile.
|
|
18
|
-
*/
|
|
19
10
|
const BROWSER_CARRIER_PATCH = `# Written by dsh-remote-go. The remote window is a browser client, so the
|
|
20
11
|
# Remote-Event carrier (api-remotes) must stay enabled even when a profile
|
|
21
12
|
# bundle disables it for a native-UI companion.
|
|
@@ -32,8 +23,6 @@ export function buildBrowserCarrierProbe(plan, layout, profile) {
|
|
|
32
23
|
const pathPrefix = plan.start.nodeBinDir ? `PATH=${shellQuote(plan.start.nodeBinDir)}:"$PATH" ` : '';
|
|
33
24
|
const dumpFile = shellQuote(`${layout.root}/profile-dump.yml`);
|
|
34
25
|
const patchFile = shellQuote(`${layout.root}/${BROWSER_CARRIER_PATCH_FILE}`);
|
|
35
|
-
// The dump contains the profile's effective configuration: it is created 0600 and removed
|
|
36
|
-
// again before this script returns, on both the success and the failure path (M3).
|
|
37
26
|
return `set -u
|
|
38
27
|
umask 077
|
|
39
28
|
mkdir -p ${shellQuote(layout.root)}
|
|
@@ -61,10 +50,7 @@ export async function ensureBrowserCarrier(ssh, options) {
|
|
|
61
50
|
});
|
|
62
51
|
if (result.code === 0 && result.stdout.includes('PATCH')) {
|
|
63
52
|
options.onLine?.('browser carrier: the profile disables api-remotes; re-enabling it for this launch');
|
|
64
|
-
return {
|
|
65
|
-
status: 'patched',
|
|
66
|
-
patchPath: `${options.layout.root}/${BROWSER_CARRIER_PATCH_FILE}`,
|
|
67
|
-
};
|
|
53
|
+
return { status: 'patched', patchPath: `${options.layout.root}/${BROWSER_CARRIER_PATCH_FILE}` };
|
|
68
54
|
}
|
|
69
55
|
if (result.code === 0 && result.stdout.includes('CLEAR')) {
|
|
70
56
|
options.onLine?.('browser carrier: api-remotes is enabled by the profile');
|
|
@@ -74,8 +60,7 @@ export async function ensureBrowserCarrier(ssh, options) {
|
|
|
74
60
|
return { status: 'unknown', patchPath: null };
|
|
75
61
|
}
|
|
76
62
|
catch (error) {
|
|
77
|
-
// swallow-ok:
|
|
78
|
-
// error (missing profile, npx failure) as the actionable one.
|
|
63
|
+
// swallow-ok: launching without the overlay keeps the start error (missing profile, npx failure)
|
|
79
64
|
options.onLine?.(`browser carrier: probe failed (${messageOf(error)})`);
|
|
80
65
|
return { status: 'unknown', patchPath: null };
|
|
81
66
|
}
|
|
@@ -86,11 +71,9 @@ export function buildStartScript(startCommand, layout, options = {}) {
|
|
|
86
71
|
const profile = options.profile ?? DEFAULT_REMOTE_PROFILE;
|
|
87
72
|
const logFile = shellQuote(layout.logFile);
|
|
88
73
|
const runFile = shellQuote(layout.runFile);
|
|
74
|
+
// `umask 077` keeps the log (which carries the launch URL with its token) private; the run registry is written to
|
|
75
|
+
// a temp file and renamed, so a reader never sees a half-written record.
|
|
89
76
|
const startedAtPlaceholder = '$(date -u +%Y-%m-%dT%H:%M:%SZ)';
|
|
90
|
-
// `umask 077` keeps the log (and the launch's state directory) private: the log carries the
|
|
91
|
-
// launch URL with its token, and the default umask used to leave it world-readable (M3).
|
|
92
|
-
// The run registry is written to a temp file and renamed, so a reader never sees a
|
|
93
|
-
// half-written record (M4).
|
|
94
77
|
return `set -eu
|
|
95
78
|
umask 077
|
|
96
79
|
mkdir -p ${shellQuote(layout.logsDir)} ${shellQuote(layout.runDir)} ${shellQuote(layout.stateHome)}
|
|
@@ -130,42 +113,13 @@ mv -f "$TMP" "$RUN"
|
|
|
130
113
|
echo "DONE:$PID:$PORT"
|
|
131
114
|
`;
|
|
132
115
|
}
|
|
133
|
-
/** The pid the launch script announced, from `DONE:` or the earlier `PID:` line. */
|
|
134
116
|
export function parseLaunchedPid(text) {
|
|
135
117
|
const combined = String(text ?? '');
|
|
136
118
|
const done = /DONE:(\d+):(\d+)/.exec(combined);
|
|
137
119
|
if (done)
|
|
138
120
|
return { pid: Number(done[1]), port: Number(done[2]) };
|
|
139
121
|
const started = /(?:^|\n)PID:(\d+)\s*(?:\n|$)/.exec(combined);
|
|
140
|
-
|
|
141
|
-
return { pid: Number(started[1]), port: 0 };
|
|
142
|
-
return { pid: 0, port: 0 };
|
|
143
|
-
}
|
|
144
|
-
/**
|
|
145
|
-
* Stop a launch that failed *after* it started: the detached process must not be left
|
|
146
|
-
* running on the remote just because its readiness line never parsed (M2).
|
|
147
|
-
*
|
|
148
|
-
* Only the pid this launch script printed is ours to stop. `run/web.json` may name another
|
|
149
|
-
* instance (a re-attached process, or a previous launch), so it is deliberately not used as
|
|
150
|
-
* a fallback here: killing that pid would be exactly the "a re-attached instance is not
|
|
151
|
-
* stopped" rule the connect pipeline enforces (review blocker 2).
|
|
152
|
-
*/
|
|
153
|
-
async function stopFailedLaunch(ssh, layout, startedPid, onLine) {
|
|
154
|
-
if (!isPid(startedPid))
|
|
155
|
-
return { ok: false, pid: null };
|
|
156
|
-
let alive = false;
|
|
157
|
-
try {
|
|
158
|
-
alive = await remotePidAlive(ssh, startedPid);
|
|
159
|
-
}
|
|
160
|
-
catch {
|
|
161
|
-
// swallow-ok: an unreadable liveness check means "cannot prove it is ours", so no signal
|
|
162
|
-
return { ok: false, pid: null };
|
|
163
|
-
}
|
|
164
|
-
if (!alive)
|
|
165
|
-
return { ok: false, pid: null };
|
|
166
|
-
const stopped = await stopRemoteWeb(ssh, layout, { pid: startedPid });
|
|
167
|
-
onLine?.(`start failed after pid ${startedPid} was launched; ${stopped.ok === true ? 'it was stopped' : 'it could not be stopped'}`);
|
|
168
|
-
return { ok: stopped.ok === true, pid: startedPid, output: stopped.output };
|
|
122
|
+
return started ? { pid: Number(started[1]), port: 0 } : { pid: 0, port: 0 };
|
|
169
123
|
}
|
|
170
124
|
export async function startRemoteWeb(ssh, options) {
|
|
171
125
|
const layout = options.layout ?? remoteLayout(options.home);
|
|
@@ -183,24 +137,35 @@ export async function startRemoteWeb(ssh, options) {
|
|
|
183
137
|
maxBytes: 200_000,
|
|
184
138
|
onStdout: (chunk) => {
|
|
185
139
|
for (const line of chunk.split(/\r?\n/)) {
|
|
186
|
-
if (line
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
140
|
+
if (line === '')
|
|
141
|
+
continue;
|
|
142
|
+
lines.push(line);
|
|
143
|
+
options.onLine?.(line);
|
|
190
144
|
}
|
|
191
145
|
},
|
|
192
146
|
});
|
|
147
|
+
// The launch script prints its pid before it waits, so a failure can still stop what it started.
|
|
193
148
|
const combined = `${result.stdout}\n${result.stderr}`;
|
|
194
|
-
// The launch script prints its pid before it waits for the readiness line: keep it even
|
|
195
|
-
// when the wait itself fails, so a failure can stop what it started (M2).
|
|
196
149
|
const launched = parseLaunchedPid(combined);
|
|
197
150
|
const failed = async (error) => {
|
|
198
|
-
|
|
151
|
+
if (isPid(launched.pid)) {
|
|
152
|
+
let alive = false;
|
|
153
|
+
try {
|
|
154
|
+
alive = await remotePidAlive(ssh, launched.pid);
|
|
155
|
+
}
|
|
156
|
+
catch {
|
|
157
|
+
// swallow-ok: an unreadable liveness check means "cannot prove it is ours", so no signal
|
|
158
|
+
}
|
|
159
|
+
if (alive) {
|
|
160
|
+
const stopped = await stopRemoteWeb(ssh, layout, { pid: launched.pid });
|
|
161
|
+
const outcome = stopped.ok === true ? 'it was stopped' : 'it could not be stopped';
|
|
162
|
+
options.onLine?.(`start failed after pid ${launched.pid} was launched; ${outcome}`);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
199
165
|
return error;
|
|
200
166
|
};
|
|
201
|
-
if (result.code !== 0)
|
|
167
|
+
if (result.code !== 0)
|
|
202
168
|
throw await failed(errors.remoteDshStartFailed(headTail(combined, 1500)));
|
|
203
|
-
}
|
|
204
169
|
const parsed = parseWebLine(combined);
|
|
205
170
|
if (!parsed)
|
|
206
171
|
throw await failed(errors.remoteDshStartFailed(headTail(combined, 1500)));
|
|
@@ -210,15 +175,13 @@ export async function startRemoteWeb(ssh, options) {
|
|
|
210
175
|
en: `The remote DSH advertised a non-loopback host (${parsed.host}); it cannot be reached safely through the SSH tunnel.`,
|
|
211
176
|
}));
|
|
212
177
|
}
|
|
213
|
-
const pid = launched.pid;
|
|
214
|
-
const startedAt = new Date().toISOString();
|
|
215
178
|
return {
|
|
216
|
-
pid,
|
|
179
|
+
pid: launched.pid,
|
|
217
180
|
port: parsed.port,
|
|
218
181
|
token: parsed.token,
|
|
219
182
|
url: parsed.url,
|
|
220
183
|
logPath: layout.logFile,
|
|
221
|
-
startedAt,
|
|
184
|
+
startedAt: new Date().toISOString(),
|
|
222
185
|
rawLine: parsed.rawLine,
|
|
223
186
|
profile,
|
|
224
187
|
dshHome: layout.dshHome,
|
|
@@ -2,31 +2,15 @@ import { remotePortOwnerPid } from '../remote-proc.js';
|
|
|
2
2
|
import { isPid, messageOf, shellQuote } from '../util.js';
|
|
3
3
|
import { readRunRegistry } from './registry.js';
|
|
4
4
|
import { readWebLineFromLog } from './resolve.js';
|
|
5
|
-
/**
|
|
6
|
-
* The pid a readiness line in the log belongs to, as a last resort for a stop whose pid is
|
|
7
|
-
* unknown. The log only names the port; `/proc` proves which process listens on it (M4).
|
|
8
|
-
*/
|
|
9
|
-
async function pidFromReadinessLine(ssh, layout) {
|
|
10
|
-
const line = await readWebLineFromLog(ssh, layout);
|
|
11
|
-
if (!line || !isPid(line.port))
|
|
12
|
-
return 0;
|
|
13
|
-
const owner = await remotePortOwnerPid(ssh, line.port);
|
|
14
|
-
return isPid(Number(owner)) ? Number(owner) : 0;
|
|
15
|
-
}
|
|
16
5
|
export async function stopRemoteWeb(ssh, layout, options = {}) {
|
|
17
6
|
let pid = Number(options.pid ?? 0);
|
|
7
|
+
if (!isPid(pid))
|
|
8
|
+
pid = Number((await readRunRegistry(ssh, layout))?.pid ?? 0);
|
|
18
9
|
if (!isPid(pid)) {
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
pid = Number(registry?.pid ?? 0);
|
|
10
|
+
const line = await readWebLineFromLog(ssh, layout);
|
|
11
|
+
const owner = line && isPid(line.port) ? Number(await remotePortOwnerPid(ssh, line.port)) : 0;
|
|
12
|
+
pid = isPid(owner) ? owner : 0;
|
|
23
13
|
}
|
|
24
|
-
if (!isPid(pid))
|
|
25
|
-
pid = await pidFromReadinessLine(ssh, layout);
|
|
26
|
-
// The registry is removed only after the stop is confirmed: a failed stop must leave the
|
|
27
|
-
// record in place, otherwise the next connect adopts nothing and a second instance starts
|
|
28
|
-
// next to the surviving one (M4). It is also removed only when it names *this* pid: a
|
|
29
|
-
// record that belongs to another instance (a re-attach) is not ours to delete.
|
|
30
14
|
const script = `set -u
|
|
31
15
|
umask 077
|
|
32
16
|
RUN=${shellQuote(layout.runFile)}
|
|
@@ -75,8 +59,6 @@ echo "STOPPED:$PID"
|
|
|
75
59
|
try {
|
|
76
60
|
const result = await ssh.exec(script, { timeoutMs: 40_000 });
|
|
77
61
|
const output = result.stdout.trim();
|
|
78
|
-
// An explicit pid that is already gone means the same thing as no target at all: there
|
|
79
|
-
// is nothing left to signal (the caller can clear the stale registry).
|
|
80
62
|
if (output.includes('NO-TARGET'))
|
|
81
63
|
return { ok: false, reason: 'no-target', output };
|
|
82
64
|
if (output.includes('ALIVE:'))
|
|
@@ -86,8 +68,7 @@ echo "STOPPED:$PID"
|
|
|
86
68
|
return { ok: true, output };
|
|
87
69
|
}
|
|
88
70
|
catch (error) {
|
|
89
|
-
// swallow-ok: a throw here is a transport failure, reported as an unconfirmed stop so the
|
|
90
|
-
// caller keeps the run registry instead of adopting nothing on the next connect
|
|
71
|
+
// swallow-ok: a throw here is a transport failure, reported as an unconfirmed stop so the caller
|
|
91
72
|
return { ok: false, reason: 'error', output: messageOf(error) };
|
|
92
73
|
}
|
|
93
74
|
}
|
|
@@ -1,14 +1,7 @@
|
|
|
1
|
-
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
*
|
|
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
|
-
*/
|
|
1
|
+
/** The browser-trust fence shared by the local HTTP API and the same-origin remote proxy: did this request arrive from
|
|
2
|
+
* the origin it names? Two confused-deputy paths reach a loopback web server — DNS rebinding and a cross-site page —
|
|
3
|
+
* and a browser labels neither reliably, so `Host` (the one header rebinding cannot forge) is checked on every request,
|
|
4
|
+
* and `Origin`/`sec-fetch-site` must agree when attached. */
|
|
12
5
|
const LOOPBACK_HOSTNAMES = new Set(['127.0.0.1', 'localhost', '[::1]', '::1']);
|
|
13
6
|
/** The port a URL actually names, counting an omitted default port. */
|
|
14
7
|
function effectivePort(url) {
|
|
@@ -16,10 +9,8 @@ function effectivePort(url) {
|
|
|
16
9
|
return url.port;
|
|
17
10
|
return url.protocol === 'https:' ? '443' : '80';
|
|
18
11
|
}
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
* listener's origin; loopback spellings are interchangeable because a browser may dial either one.
|
|
22
|
-
*/
|
|
12
|
+
// Hostname/port match for a `Host` header (no scheme); loopback spellings are interchangeable
|
|
13
|
+
// because a browser may dial either one.
|
|
23
14
|
export function sameServerHost(value, origin) {
|
|
24
15
|
if (typeof value !== 'string' || value === '')
|
|
25
16
|
return false;
|
|
@@ -30,11 +21,10 @@ export function sameServerHost(value, origin) {
|
|
|
30
21
|
catch {
|
|
31
22
|
return false;
|
|
32
23
|
}
|
|
33
|
-
// WHATWG parsing rewrites anything that is not a bare authority: `user@host` drops its userinfo,
|
|
34
|
-
// a
|
|
35
|
-
//
|
|
36
|
-
// the
|
|
37
|
-
// hostname would let `attacker.example@127.0.0.1:port` pass as loopback.
|
|
24
|
+
// WHATWG parsing rewrites anything that is not a bare authority: `user@host` drops its userinfo, a backslash becomes
|
|
25
|
+
// a path separator, `#`/`?` start the fragment/query, a trailing dot and a zero-padded port are normalized away. A
|
|
26
|
+
// browser fills `Host` from the serialized URL, so a rewritten value is not an authority this server answers to —
|
|
27
|
+
// comparing the rewritten hostname would let `attacker.example@127.0.0.1:port` pass as loopback.
|
|
38
28
|
if (candidate.host !== value.toLowerCase())
|
|
39
29
|
return false;
|
|
40
30
|
if (effectivePort(candidate) !== effectivePort(origin))
|
|
@@ -43,14 +33,9 @@ export function sameServerHost(value, origin) {
|
|
|
43
33
|
return true;
|
|
44
34
|
return LOOPBACK_HOSTNAMES.has(origin.hostname) && LOOPBACK_HOSTNAMES.has(candidate.hostname);
|
|
45
35
|
}
|
|
46
|
-
|
|
47
|
-
|
|
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
|
-
*/
|
|
36
|
+
// Full same-origin match for an `Origin` header (scheme included). The authority is compared verbatim
|
|
37
|
+
// as well as through `sameServerHost`, for the rewrite reason above: otherwise
|
|
38
|
+
// `http://attacker.example@127.0.0.1:port` would pass as loopback.
|
|
54
39
|
export function sameServerOrigin(value, origin) {
|
|
55
40
|
if (typeof value !== 'string' || value === '')
|
|
56
41
|
return false;
|
|
@@ -71,10 +56,8 @@ export function sameServerOrigin(value, origin) {
|
|
|
71
56
|
return false;
|
|
72
57
|
return candidate.protocol === origin.protocol && sameServerHost(candidate.host, origin);
|
|
73
58
|
}
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
* server, and any browser-announced relationship must be same-origin.
|
|
77
|
-
*/
|
|
59
|
+
// The fence applied to a browser navigation and its subresources: the request must name this server,
|
|
60
|
+
// and any browser-announced relationship must be same-origin.
|
|
78
61
|
export function trustedRequest(req, origin) {
|
|
79
62
|
if (!sameServerHost(req.headers.host, origin))
|
|
80
63
|
return false;
|