dsh-crate 0.0.0-stage → 0.5.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/LICENSE +27 -0
- package/README.md +288 -2
- package/README.zh.md +263 -0
- package/UPDATE-API-V1.md +207 -0
- package/assets/logo.svg +37 -0
- package/client/client.js +18964 -0
- package/cordis.patch.yml +4 -0
- package/lib/accelerate.js +194 -0
- package/lib/agents.js +67 -0
- package/lib/backup.js +688 -0
- package/lib/body-progress.js +173 -0
- package/lib/catalog-local-match.js +160 -0
- package/lib/catalog-npm.js +180 -0
- package/lib/changelog.js +462 -0
- package/lib/channels.js +64 -0
- package/lib/check.js +1557 -0
- package/lib/compatibility.js +243 -0
- package/lib/crate-catalog.js +179 -0
- package/lib/diagnostics.js +49 -0
- package/lib/discovery-compatibility.js +447 -0
- package/lib/drain-journal.js +164 -0
- package/lib/drain.js +1043 -0
- package/lib/dsh-cli.js +1373 -0
- package/lib/dsh-install.js +259 -0
- package/lib/entry-identity.js +85 -0
- package/lib/gist.js +369 -0
- package/lib/groups.js +108 -0
- package/lib/home-paths.js +29 -0
- package/lib/host-recovery.js +187 -0
- package/lib/hot.js +871 -0
- package/lib/http.js +252 -0
- package/lib/index.js +394 -0
- package/lib/install.js +1147 -0
- package/lib/lifecycle.js +37 -0
- package/lib/log-redaction.js +24 -0
- package/lib/log.js +204 -0
- package/lib/ndjson.js +154 -0
- package/lib/net.js +174 -0
- package/lib/official-desktop.js +619 -0
- package/lib/order.js +284 -0
- package/lib/patch.js +943 -0
- package/lib/pending-rows.js +142 -0
- package/lib/pending-updates.js +346 -0
- package/lib/pnpm-compat.js +972 -0
- package/lib/presets.js +282 -0
- package/lib/probe-context.js +20 -0
- package/lib/proc-text.js +69 -0
- package/lib/profile.js +1978 -0
- package/lib/recovery.js +1059 -0
- package/lib/region-probe.js +93 -0
- package/lib/regions.js +283 -0
- package/lib/registry.js +308 -0
- package/lib/release-candidates.js +115 -0
- package/lib/release-updates.js +70 -0
- package/lib/restart.js +688 -0
- package/lib/routes.js +7960 -0
- package/lib/settings.js +164 -0
- package/lib/shelfry-catalog.js +179 -0
- package/lib/snapshot.js +506 -0
- package/lib/source-migration.js +164 -0
- package/lib/sources.js +1005 -0
- package/lib/state.js +38 -0
- package/lib/store.js +163 -0
- package/lib/themes.js +350 -0
- package/lib/trial.js +125 -0
- package/lib/types/accelerate.d.ts +85 -0
- package/lib/types/agents.d.ts +52 -0
- package/lib/types/backup.d.ts +171 -0
- package/lib/types/body-progress.d.ts +94 -0
- package/lib/types/catalog-local-match.d.ts +39 -0
- package/lib/types/catalog-npm.d.ts +77 -0
- package/lib/types/changelog.d.ts +131 -0
- package/lib/types/channels.d.ts +56 -0
- package/lib/types/check.d.ts +353 -0
- package/lib/types/compatibility.d.ts +83 -0
- package/lib/types/crate-catalog.d.ts +48 -0
- package/lib/types/diagnostics.d.ts +29 -0
- package/lib/types/discovery-compatibility.d.ts +145 -0
- package/lib/types/drain-journal.d.ts +25 -0
- package/lib/types/drain.d.ts +306 -0
- package/lib/types/dsh-cli.d.ts +481 -0
- package/lib/types/dsh-install.d.ts +106 -0
- package/lib/types/entry-identity.d.ts +68 -0
- package/lib/types/gist.d.ts +79 -0
- package/lib/types/groups.d.ts +34 -0
- package/lib/types/home-paths.d.ts +13 -0
- package/lib/types/host-recovery.d.ts +95 -0
- package/lib/types/hot.d.ts +405 -0
- package/lib/types/http.d.ts +114 -0
- package/lib/types/index.d.ts +52 -0
- package/lib/types/install.d.ts +463 -0
- package/lib/types/lifecycle.d.ts +14 -0
- package/lib/types/log-redaction.d.ts +2 -0
- package/lib/types/log.d.ts +43 -0
- package/lib/types/ndjson.d.ts +52 -0
- package/lib/types/net.d.ts +94 -0
- package/lib/types/official-desktop.d.ts +59 -0
- package/lib/types/order.d.ts +100 -0
- package/lib/types/patch.d.ts +218 -0
- package/lib/types/pending-rows.d.ts +81 -0
- package/lib/types/pending-updates.d.ts +161 -0
- package/lib/types/pnpm-compat.d.ts +102 -0
- package/lib/types/presets.d.ts +94 -0
- package/lib/types/probe-context.d.ts +14 -0
- package/lib/types/proc-text.d.ts +29 -0
- package/lib/types/profile.d.ts +551 -0
- package/lib/types/recovery.d.ts +342 -0
- package/lib/types/region-probe.d.ts +50 -0
- package/lib/types/regions.d.ts +134 -0
- package/lib/types/registry.d.ts +160 -0
- package/lib/types/release-candidates.d.ts +42 -0
- package/lib/types/release-updates.d.ts +15 -0
- package/lib/types/restart.d.ts +279 -0
- package/lib/types/routes.d.ts +130 -0
- package/lib/types/settings.d.ts +112 -0
- package/lib/types/shelfry-catalog.d.ts +48 -0
- package/lib/types/snapshot.d.ts +93 -0
- package/lib/types/source-migration.d.ts +100 -0
- package/lib/types/sources.d.ts +391 -0
- package/lib/types/state.d.ts +20 -0
- package/lib/types/store.d.ts +47 -0
- package/lib/types/themes.d.ts +46 -0
- package/lib/types/trial.d.ts +61 -0
- package/lib/types/update-api-v1.d.ts +83 -0
- package/lib/types/updates.d.ts +273 -0
- package/lib/types/verify.d.ts +277 -0
- package/lib/update-api-v1.js +273 -0
- package/lib/updates.js +981 -0
- package/lib/verify.js +904 -0
- package/locale/en.json +5 -0
- package/locale/zh.json +6 -0
- package/package.json +113 -4
package/lib/restart.js
ADDED
|
@@ -0,0 +1,688 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Self-restart: relaunch the exact DSH invocation that booted this host so
|
|
3
|
+
* pending (non-hot) plugin changes take effect without the user leaving the
|
|
4
|
+
* UI. Contributed in #14 by @ysyyhhh; ported onto the layered architecture.
|
|
5
|
+
*
|
|
6
|
+
* Safety model: the endpoint accepts only same-origin requests whose Host
|
|
7
|
+
* names an authority this deployment serves — a loopback authority reached
|
|
8
|
+
* directly (no forwarding headers), or a name the host DECLARED
|
|
9
|
+
* (`dsh web --trusted-host <name>`), which is how a deployment behind a
|
|
10
|
+
* tunnel or a reverse proxy is reached. It refuses while a plugin operation
|
|
11
|
+
* runs, and deployments under a supervisor (systemd/launchd/pm2) can disable
|
|
12
|
+
* the whole feature with `allowRestart: false` — the supervisor owns restarts.
|
|
13
|
+
*/
|
|
14
|
+
import { spawn } from 'node:child_process';
|
|
15
|
+
import { declaredTrustedHosts, loopbackAuthority, trustedAuthority } from './http.js';
|
|
16
|
+
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
|
17
|
+
import inspector from 'node:inspector';
|
|
18
|
+
import { tmpdir } from 'node:os';
|
|
19
|
+
import { join } from 'node:path';
|
|
20
|
+
import { fileURLToPath } from 'node:url';
|
|
21
|
+
import { dshArgv, nodeExecutable } from './dsh-cli.js';
|
|
22
|
+
/** Vitest / flows can pin detection without opening a real inspector port. */
|
|
23
|
+
let debuggerOverride;
|
|
24
|
+
/** @internal test hook — production callers use detectedDebugger() only. */
|
|
25
|
+
export function setDetectedDebuggerOverride(value) {
|
|
26
|
+
debuggerOverride = value;
|
|
27
|
+
}
|
|
28
|
+
const INSPECT_ARG_PREFIXES = ['--inspect', '--inspect-brk', '--inspect-port', '--inspect-wait'];
|
|
29
|
+
function tokenHasInspectFlag(token) {
|
|
30
|
+
for (const prefix of INSPECT_ARG_PREFIXES) {
|
|
31
|
+
if (token === prefix || token.startsWith(`${prefix}=`))
|
|
32
|
+
return true;
|
|
33
|
+
}
|
|
34
|
+
if (token === '--debug-brk' || token.startsWith('--debug-brk='))
|
|
35
|
+
return true;
|
|
36
|
+
if (token === '--debug' || token.startsWith('--debug='))
|
|
37
|
+
return true;
|
|
38
|
+
return false;
|
|
39
|
+
}
|
|
40
|
+
function argvHasInspectFlag(tokens) {
|
|
41
|
+
for (const token of tokens) {
|
|
42
|
+
if (tokenHasInspectFlag(token))
|
|
43
|
+
return true;
|
|
44
|
+
}
|
|
45
|
+
return false;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* The process supervisor running this host, when one can be identified —
|
|
49
|
+
* `null` when nothing says so.
|
|
50
|
+
*
|
|
51
|
+
* This exists because the failure it prevents is the worst one the market
|
|
52
|
+
* can cause. Under systemd's default `KillMode=control-group`, everything in
|
|
53
|
+
* the unit's cgroup dies with the main process — including the detached
|
|
54
|
+
* helper that was supposed to bring the replacement up. So "restart" killed
|
|
55
|
+
* a production service and nothing came back (#229 by @SkillBase-Al: "杀死了
|
|
56
|
+
* 服务但是无法重复启动服务"). `allowRestart: false` was always the documented
|
|
57
|
+
* answer, but it is opt-in, and nothing told the operator to opt in until
|
|
58
|
+
* after they had already lost the service.
|
|
59
|
+
*
|
|
60
|
+
* TWO signals are required, and the second is the whole reason this function
|
|
61
|
+
* is not a one-line env check. `INVOCATION_ID` is INHERITED: every
|
|
62
|
+
* descendant of a systemd unit carries it, which on Linux includes an
|
|
63
|
+
* ordinary desktop terminal (its shell descends from a user-session unit)
|
|
64
|
+
* and a CI runner (the agent is a unit — this repo's own smoke test caught
|
|
65
|
+
* that). Treating inheritance as ownership would disable the button for a
|
|
66
|
+
* large population of hosts where it works fine, which is a worse bug than
|
|
67
|
+
* the one being fixed.
|
|
68
|
+
*
|
|
69
|
+
* The parent test is what distinguishes being the unit's own main process
|
|
70
|
+
* from merely descending from one: a terminal's node has the shell as its
|
|
71
|
+
* parent and a runner's has the agent. It used to be `ppid === 1`, which is
|
|
72
|
+
* only true for SYSTEM units. A per-user unit's service is forked by that
|
|
73
|
+
* user's manager instance — `systemd --user`, an ordinary PID — so user-unit
|
|
74
|
+
* hosts read as unsupervised, and one-click restart killed them for good
|
|
75
|
+
* (#471 by @automagik-genie, with the journal to prove the whole chain:
|
|
76
|
+
* clean SIGTERM exit → `Restart=on-failure` does not fire → `KillMode=mixed`
|
|
77
|
+
* SIGKILLs the detached helper before it can spawn the replacement). So the
|
|
78
|
+
* parent counts as a manager when it is PID 1 or its comm is `systemd` —
|
|
79
|
+
* the one name both manager instances share and the false-positive parents
|
|
80
|
+
* (shells, CI agents) never carry. `/proc` is Linux-only, which is exactly
|
|
81
|
+
* as wide as systemd itself; anywhere it cannot be read the answer stays
|
|
82
|
+
* "not a manager".
|
|
83
|
+
*
|
|
84
|
+
* Scoped to systemd on purpose. pm2 sets `pm_id`, but it is inherited the
|
|
85
|
+
* same way and pm2's God daemon — not PID 1 — is the parent, so there is no
|
|
86
|
+
* equivalent second signal; a guess there would reintroduce exactly the
|
|
87
|
+
* false positive this pair exists to avoid. launchd has no marker at all.
|
|
88
|
+
* Both still need the explicit setting: detection is a safety net over the
|
|
89
|
+
* documented option, never a replacement for it.
|
|
90
|
+
*/
|
|
91
|
+
export function detectedSupervisor(env = process.env, ppid = process.ppid, parentComm = readParentComm) {
|
|
92
|
+
const set = (name) => (env[name] ?? '') !== '';
|
|
93
|
+
if (!set('INVOCATION_ID') && !set('JOURNAL_STREAM'))
|
|
94
|
+
return null;
|
|
95
|
+
if (ppid === 1 || parentComm(ppid) === 'systemd')
|
|
96
|
+
return 'systemd';
|
|
97
|
+
return null;
|
|
98
|
+
}
|
|
99
|
+
/** The comm of `pid` from /proc, or null wherever that cannot be read. */
|
|
100
|
+
function readParentComm(pid) {
|
|
101
|
+
try {
|
|
102
|
+
return readFileSync(`/proc/${String(pid)}/comm`, 'utf8').trim();
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
return null;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Whether this host process is under a debugger, when one can be identified —
|
|
110
|
+
* `'inspector'` or `null`.
|
|
111
|
+
*
|
|
112
|
+
* Parallel to `detectedSupervisor()` (#229): a runtime latch for the restart
|
|
113
|
+
* route and status poll, NOT an entry in `restartAllowed()`. Folding it into
|
|
114
|
+
* `restartAllowed()` would write `allowRestart: false` through the settings
|
|
115
|
+
* page while a debug session is open, and the switch would stay off after
|
|
116
|
+
* the debugger detaches (#447).
|
|
117
|
+
*
|
|
118
|
+
* An explicit `allowRestart: true` does NOT override this latch either —
|
|
119
|
+
* unlike systemd, there is no documented deployment shape where killing a
|
|
120
|
+
* debug-attached host from the market UI is the right answer.
|
|
121
|
+
*
|
|
122
|
+
* Primary signal: `inspector.url()` is set (covers `--inspect` at boot,
|
|
123
|
+
* `inspector.open()`, and SIGUSR1 attach). Secondary: inspect-family flags
|
|
124
|
+
* in `execArgv` and `NODE_OPTIONS`, matched by token prefix — not a
|
|
125
|
+
* `/inspect/` substring, so script paths like `.../inspect-tool.js` do not
|
|
126
|
+
* false-positive. Includes `--inspect-wait` for Node versions that expose it
|
|
127
|
+
* as a distinct flag before `inspector.url()` is populated.
|
|
128
|
+
*
|
|
129
|
+
* Accepted false positive (same trade as #229 not guessing pm2): a host left
|
|
130
|
+
* listening on an inspector port — including `NODE_OPTIONS=--inspect` with
|
|
131
|
+
* nobody attached — is treated as debug-owned and gets no one-click restart.
|
|
132
|
+
*/
|
|
133
|
+
export function detectedDebugger(inspectorUrl = inspector.url(), execArgv = process.execArgv, nodeOptions = process.env.NODE_OPTIONS ?? '') {
|
|
134
|
+
if (debuggerOverride !== undefined)
|
|
135
|
+
return debuggerOverride;
|
|
136
|
+
if (inspectorUrl !== undefined && inspectorUrl !== '')
|
|
137
|
+
return 'inspector';
|
|
138
|
+
if (argvHasInspectFlag(execArgv))
|
|
139
|
+
return 'inspector';
|
|
140
|
+
const options = nodeOptions.trim();
|
|
141
|
+
if (options !== '' && argvHasInspectFlag(options.split(/\s+/u)))
|
|
142
|
+
return 'inspector';
|
|
143
|
+
return null;
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Self-restart is enabled by default, disabled by an explicit false — and
|
|
147
|
+
* disabled by DEFAULT under a detected supervisor, which owns restarts and
|
|
148
|
+
* whose process group would take the replacement helper down with it.
|
|
149
|
+
*
|
|
150
|
+
* An explicit `true` still wins: an operator who has configured their unit
|
|
151
|
+
* for it (`KillMode=process`, or a wrapper that survives) is making a
|
|
152
|
+
* statement about their own deployment, and this should not overrule it.
|
|
153
|
+
*/
|
|
154
|
+
export function restartAllowed(config, env = process.env, ppid = process.ppid) {
|
|
155
|
+
if (config.allowRestart !== undefined)
|
|
156
|
+
return config.allowRestart;
|
|
157
|
+
return detectedSupervisor(env, ppid) === null;
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* The port this process is serving on, read off the request that asked for
|
|
161
|
+
* the restart.
|
|
162
|
+
*
|
|
163
|
+
* The alternative is to parse it out of the launch argv, which is wrong for
|
|
164
|
+
* every host that binds from config or an env var. The Host header is what
|
|
165
|
+
* the browser actually reached us on, so it is the port the replacement has
|
|
166
|
+
* to take over — and it is already validated against Origin by the guard
|
|
167
|
+
* below before any of this runs.
|
|
168
|
+
* @returns the port, or null when the header carries none (a default port).
|
|
169
|
+
*/
|
|
170
|
+
export function servingPort(request) {
|
|
171
|
+
// The port this process is actually listening on (#859): behind a tunnel
|
|
172
|
+
// the Host carries the proxy's port (dsh.example.com:8443), and handing
|
|
173
|
+
// that to the restart helper makes it probe and bind the proxy instead of
|
|
174
|
+
// the server it is replacing. The socket's local port is the listener's
|
|
175
|
+
// own; Host stays as the fallback for a request object without one.
|
|
176
|
+
const localPort = request.socket?.localPort;
|
|
177
|
+
if (typeof localPort === 'number' && Number.isInteger(localPort) && localPort > 0 && localPort < 65536)
|
|
178
|
+
return localPort;
|
|
179
|
+
const host = request.headers.host;
|
|
180
|
+
if (host === undefined)
|
|
181
|
+
return null;
|
|
182
|
+
const match = /:(\d{1,5})$/u.exec(host);
|
|
183
|
+
if (match === null)
|
|
184
|
+
return null;
|
|
185
|
+
const port = Number(match[1]);
|
|
186
|
+
return Number.isInteger(port) && port > 0 && port < 65536 ? port : null;
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* The part of the restart fence that does not depend on `Origin`: a loopback
|
|
190
|
+
* peer, no forwarding trace, and a Host that names a loopback authority.
|
|
191
|
+
*
|
|
192
|
+
* One function so the route that ENFORCES the fence and the status poll that
|
|
193
|
+
* PREDICTS it cannot drift apart (#782). It deliberately leaves `Origin` out:
|
|
194
|
+
* a same-origin GET — which is what the status poll is — carries none, so a
|
|
195
|
+
* prediction that required it would call every ordinary local request
|
|
196
|
+
* impossible and take the button away from everyone.
|
|
197
|
+
*/
|
|
198
|
+
function directLoopbackRequest(request) {
|
|
199
|
+
const address = request.socket.remoteAddress;
|
|
200
|
+
if (address !== '127.0.0.1' && address !== '::1' && address !== '::ffff:127.0.0.1')
|
|
201
|
+
return false;
|
|
202
|
+
// Any forwarding trace means the loopback peer is a proxy, not the user.
|
|
203
|
+
if (request.headers.forwarded !== undefined
|
|
204
|
+
|| request.headers['x-forwarded-for'] !== undefined
|
|
205
|
+
|| request.headers['x-real-ip'] !== undefined)
|
|
206
|
+
return false;
|
|
207
|
+
// A loopback PEER is not enough: a DNS-rebinding page reaches 127.0.0.1
|
|
208
|
+
// through a name it controls, so the address proves nothing and Host/Origin
|
|
209
|
+
// both carry the attacker's domain (#678). Host is what the attack cannot
|
|
210
|
+
// forge, so it has to name a loopback authority.
|
|
211
|
+
return loopbackAuthority(request.headers.host);
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* Whether the request's Host names an authority the HOST declared —
|
|
215
|
+
* `dsh web --trusted-host <name>` — as the ordinary route fence reads it.
|
|
216
|
+
*
|
|
217
|
+
* A declared authority is the operator's own statement about the name this
|
|
218
|
+
* deployment serves. It is the same statement the host's own fence already
|
|
219
|
+
* accepts for every other request on the host, and the same one `sameOrigin`
|
|
220
|
+
* accepts for the market's ordinary routes (#729): a deployment reached by a
|
|
221
|
+
* name is not a stranger to itself.
|
|
222
|
+
*
|
|
223
|
+
* A LOOPBACK authority is deliberately not this path. The lane deployments
|
|
224
|
+
* declare `127.0.0.1` alongside their public name, and a loopback Host is the
|
|
225
|
+
* direct path's business — where the peer's address is checked as well. This
|
|
226
|
+
* path is only for a name the deployment answers to on the network.
|
|
227
|
+
*/
|
|
228
|
+
function declaredAuthority(request) {
|
|
229
|
+
const host = request.headers.host;
|
|
230
|
+
if (host === undefined)
|
|
231
|
+
return false;
|
|
232
|
+
if (loopbackAuthority(host))
|
|
233
|
+
return false;
|
|
234
|
+
return trustedAuthority(host, declaredTrustedHosts());
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* Whether the request names an authority this deployment serves, and is not
|
|
238
|
+
* a cross-site request.
|
|
239
|
+
*
|
|
240
|
+
* Two shapes, and a deployment has to be one of them:
|
|
241
|
+
*
|
|
242
|
+
* - DIRECT: a loopback peer, no forwarding trace, and a loopback Host. The
|
|
243
|
+
* peer proves the request did not come through a proxy, and the Host proves
|
|
244
|
+
* it did not come through a name the attacker controls (#678).
|
|
245
|
+
* - THROUGH THE PERIMETER: a Host the host DECLARED. The peer is then the
|
|
246
|
+
* proxy (a tunnel, an Ingress) and a forwarding trace is expected rather
|
|
247
|
+
* than suspicious, so the peer is not what decides — the declared Host is.
|
|
248
|
+
*
|
|
249
|
+
* What still holds in both: the Host is the header an attacker's page cannot
|
|
250
|
+
* forge, an undeclared name is refused, and a browser that labels the request
|
|
251
|
+
* cross-site is refused outright — exactly as the host's own fence and
|
|
252
|
+
* `sameOrigin` do.
|
|
253
|
+
*/
|
|
254
|
+
function servedAuthority(request) {
|
|
255
|
+
if (request.headers['sec-fetch-site'] === 'cross-site')
|
|
256
|
+
return false;
|
|
257
|
+
if (declaredAuthority(request))
|
|
258
|
+
return true;
|
|
259
|
+
return directLoopbackRequest(request);
|
|
260
|
+
}
|
|
261
|
+
/**
|
|
262
|
+
* Whether an `Origin` header names the same authority as the `Host` header.
|
|
263
|
+
*
|
|
264
|
+
* The `null` origin (a sandboxed iframe, a `data:` document) is a
|
|
265
|
+
* present-but-unparseable origin and is refused; an absent Origin is the
|
|
266
|
+
* caller's decision, not this function's.
|
|
267
|
+
*/
|
|
268
|
+
function sameAuthorityOrigin(origin, host) {
|
|
269
|
+
if (origin === undefined)
|
|
270
|
+
return false;
|
|
271
|
+
try {
|
|
272
|
+
const parsed = new URL(origin);
|
|
273
|
+
return (parsed.protocol === 'http:' || parsed.protocol === 'https:') && parsed.host === host;
|
|
274
|
+
}
|
|
275
|
+
catch {
|
|
276
|
+
return false;
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
/**
|
|
280
|
+
* Whether a restart request made from the same page as THIS request could pass
|
|
281
|
+
* the fence (#782): the answer the status poll reports so the banner can say
|
|
282
|
+
* why there is no button, instead of rendering one that always answers 403.
|
|
283
|
+
*
|
|
284
|
+
* Read off the request that asked for status, not off configuration. Behind an
|
|
285
|
+
* Ingress or any reverse proxy the restart POST arrives from the same page over
|
|
286
|
+
* the same path, so it fails for the same reasons this request shows — a proxy
|
|
287
|
+
* peer, forwarding headers, a non-loopback Host. It is a prediction, never a
|
|
288
|
+
* grant: the route still runs the full fence, including `Origin`, on the POST.
|
|
289
|
+
*
|
|
290
|
+
* A deployment that DECLARES its public name answers it truthfully now: the
|
|
291
|
+
* status poll sees the declared Host and reports the restart as reachable,
|
|
292
|
+
* exactly as the route will judge it.
|
|
293
|
+
*/
|
|
294
|
+
export function restartReachableFrom(request) {
|
|
295
|
+
return servedAuthority(request);
|
|
296
|
+
}
|
|
297
|
+
/**
|
|
298
|
+
* Whether the request has the exact shape dsh Desktop's own document proxy
|
|
299
|
+
* forwards: a loopback peer, no forwarding headers, and **neither** `Host`
|
|
300
|
+
* nor `Origin`.
|
|
301
|
+
*
|
|
302
|
+
* The desktop app strips `origin`/`host` (and cookies) before forwarding to
|
|
303
|
+
* the internal host (#648), so that absence is the trusted desktop shape
|
|
304
|
+
* rather than a missing signal. It is also not something a browser can
|
|
305
|
+
* produce — every browser request carries `Host` — so a rebinding page or a
|
|
306
|
+
* cross-site POST still lands on the strict path below, carrying the
|
|
307
|
+
* attacker's own names (#678). A local non-browser client could omit both,
|
|
308
|
+
* but such a client can equally set them correctly, so this widens nothing
|
|
309
|
+
* against the threats the fence exists for.
|
|
310
|
+
*/
|
|
311
|
+
function desktopForwardedRequest(request) {
|
|
312
|
+
const address = request.socket.remoteAddress;
|
|
313
|
+
if (address !== '127.0.0.1' && address !== '::1' && address !== '::ffff:127.0.0.1')
|
|
314
|
+
return false;
|
|
315
|
+
if (request.headers.forwarded !== undefined
|
|
316
|
+
|| request.headers['x-forwarded-for'] !== undefined
|
|
317
|
+
|| request.headers['x-real-ip'] !== undefined)
|
|
318
|
+
return false;
|
|
319
|
+
return request.headers.host === undefined && request.headers.origin === undefined;
|
|
320
|
+
}
|
|
321
|
+
/**
|
|
322
|
+
* Whether a self-uninstall request may proceed.
|
|
323
|
+
*
|
|
324
|
+
* Same door as the restart route, plus the desktop proxy's headerless shape
|
|
325
|
+
* (#903): on Desktop the market's own card is the place users go to remove it,
|
|
326
|
+
* and the fence was refusing every such click because the proxy had stripped
|
|
327
|
+
* the very headers it required. Restart keeps the stricter predicate — it
|
|
328
|
+
* spawns a replacement host, which is not something a desktop-managed profile
|
|
329
|
+
* should get from here.
|
|
330
|
+
*/
|
|
331
|
+
export function trustedSelfUninstallRequest(request) {
|
|
332
|
+
return trustedRestartRequest(request) || desktopForwardedRequest(request);
|
|
333
|
+
}
|
|
334
|
+
/**
|
|
335
|
+
* Whether the request that asked for status could uninstall the market (#903).
|
|
336
|
+
*
|
|
337
|
+
* The prediction, like the restart one, leaves `Origin` out: the status poll
|
|
338
|
+
* is a same-origin GET and carries none, so a prediction that required one
|
|
339
|
+
* would hide the button on every deployment that has a declared authority —
|
|
340
|
+
* the same shape the route accepts.
|
|
341
|
+
*/
|
|
342
|
+
export function selfUninstallReachableFrom(request) {
|
|
343
|
+
return servedAuthority(request) || desktopForwardedRequest(request);
|
|
344
|
+
}
|
|
345
|
+
/** Whether a process-control request came from this Web host on loopback. */
|
|
346
|
+
export function trustedRestartRequest(request) {
|
|
347
|
+
if (!servedAuthority(request))
|
|
348
|
+
return false;
|
|
349
|
+
const host = request.headers.host;
|
|
350
|
+
if (host === undefined)
|
|
351
|
+
return false;
|
|
352
|
+
// Process control always carries an Origin: the button is a page's own
|
|
353
|
+
// request, and a request without one is not a page's request.
|
|
354
|
+
return sameAuthorityOrigin(request.headers.origin, host);
|
|
355
|
+
}
|
|
356
|
+
/**
|
|
357
|
+
* Whether a download navigation may fetch a sensitive GET export.
|
|
358
|
+
* Browsers do NOT send an Origin header on same-origin GET navigations
|
|
359
|
+
* (`<a href="/..." download>`), so unlike process-control requests a missing
|
|
360
|
+
* Origin is the NORMAL shape of a user-initiated download and must pass.
|
|
361
|
+
* Keep the rest of the posture: the Host must name an authority this
|
|
362
|
+
* deployment serves (loopback, or one the host declared), and — when an
|
|
363
|
+
* Origin IS present (fetch/CORS attempts) — it must still match Host so a
|
|
364
|
+
* cross-origin page cannot read the export.
|
|
365
|
+
*/
|
|
366
|
+
export function trustedDownloadRequest(request) {
|
|
367
|
+
if (!servedAuthority(request))
|
|
368
|
+
return false;
|
|
369
|
+
const host = request.headers.host;
|
|
370
|
+
if (host === undefined)
|
|
371
|
+
return false;
|
|
372
|
+
const origin = request.headers.origin;
|
|
373
|
+
if (origin === undefined)
|
|
374
|
+
return true; // plain browser download navigation
|
|
375
|
+
return sameAuthorityOrigin(origin, host);
|
|
376
|
+
}
|
|
377
|
+
/** The exact boot invocation the detached restart helper replays. */
|
|
378
|
+
export function restartLaunch() {
|
|
379
|
+
const launch = dshArgv();
|
|
380
|
+
return {
|
|
381
|
+
...launch,
|
|
382
|
+
args: [...launch.args, ...process.argv.slice(2)],
|
|
383
|
+
cwd: launch.cwd ?? process.cwd(),
|
|
384
|
+
};
|
|
385
|
+
}
|
|
386
|
+
/**
|
|
387
|
+
* Platform-correct spawn invocation for the replacement host (#40 by
|
|
388
|
+
* @1123762794): on Windows a `detached` spawn maps to DETACHED_PROCESS — the
|
|
389
|
+
* new host gets NO console, and every console child it later spawns (e.g.
|
|
390
|
+
* DSH sandbox tool runners) pops a visible node window. Wrapping the launch
|
|
391
|
+
* in `powershell -WindowStyle Hidden` gives the host a HIDDEN console that
|
|
392
|
+
* children inherit instead. POSIX keeps the plain detached spawn.
|
|
393
|
+
*
|
|
394
|
+
* The helper that runs this invocation spawns it with `windowsHide`, because
|
|
395
|
+
* the helper has no console of its own to hand down and Windows would
|
|
396
|
+
* otherwise create a visible one for PowerShell (#624).
|
|
397
|
+
*/
|
|
398
|
+
export function respawnInvocation(launch, platform = process.platform) {
|
|
399
|
+
if (platform !== 'win32') {
|
|
400
|
+
return { file: launch.file, args: launch.args, viaShell: launch.viaShell, detached: true };
|
|
401
|
+
}
|
|
402
|
+
// PowerShell single-quoting: only embedded single quotes need escaping
|
|
403
|
+
// (doubled). Name the cmd shim explicitly: invoking bare `dsh` lets
|
|
404
|
+
// PowerShell prefer dsh.ps1, which a default Restricted execution policy
|
|
405
|
+
// refuses before the replacement can start (#397). `dsh.cmd` is produced
|
|
406
|
+
// by the same npm install and is not governed by PowerShell script policy.
|
|
407
|
+
const quote = (part) => `'${part.replace(/'/g, "''")}'`;
|
|
408
|
+
const file = launch.viaShell && !/\.(?:cmd|bat)$/iu.test(launch.file)
|
|
409
|
+
? `${launch.file}.cmd`
|
|
410
|
+
: launch.file;
|
|
411
|
+
return {
|
|
412
|
+
file: 'powershell.exe',
|
|
413
|
+
args: ['-NoProfile', '-WindowStyle', 'Hidden', '-Command',
|
|
414
|
+
[`& ${quote(file)}`, ...launch.args.map(quote)].join(' ')],
|
|
415
|
+
viaShell: false,
|
|
416
|
+
detached: false,
|
|
417
|
+
};
|
|
418
|
+
}
|
|
419
|
+
/**
|
|
420
|
+
* Where the recovery script lives beside this module.
|
|
421
|
+
*
|
|
422
|
+
* The built layout is `lib/restart.js` + `lib/recovery.js`, and the source
|
|
423
|
+
* layout has no runnable sibling at all (a spawned `node` cannot load a `.ts`
|
|
424
|
+
* file), so the answer is the built path or nothing. Nothing is a supported
|
|
425
|
+
* outcome, not a failure: the helper then behaves exactly as it did before the
|
|
426
|
+
* recovery surface existed — it notes the failure and exits — and every test
|
|
427
|
+
* that drives the handoff passes its own script instead of relying on a build
|
|
428
|
+
* having happened.
|
|
429
|
+
* @returns the absolute path, or null when this checkout has no built copy.
|
|
430
|
+
*/
|
|
431
|
+
export function recoveryScriptPath() {
|
|
432
|
+
try {
|
|
433
|
+
const candidate = fileURLToPath(new URL('./recovery.js', import.meta.url));
|
|
434
|
+
return existsSync(candidate) ? candidate : null;
|
|
435
|
+
}
|
|
436
|
+
catch {
|
|
437
|
+
return null;
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
/**
|
|
441
|
+
* Source for the detached helper that outlives this process and brings the
|
|
442
|
+
* replacement up.
|
|
443
|
+
*
|
|
444
|
+
* Extracted so the waiting can be tested by RUNNING it, which is the only
|
|
445
|
+
* way this class of bug shows itself: every part of the old helper looked
|
|
446
|
+
* right in isolation.
|
|
447
|
+
*
|
|
448
|
+
* What it fixes (#177, reported on Windows 11, reproducible every time): the
|
|
449
|
+
* helper slept a flat 1500ms and spawned. The old process had exited, but
|
|
450
|
+
* the listening socket had not been released yet, so the replacement died
|
|
451
|
+
* instantly with EADDRINUSE — and the spawn was wrapped in `catch {}`, so
|
|
452
|
+
* nothing was written anywhere. The user saw a restart button that did
|
|
453
|
+
* nothing. The docstring above it even claimed the helper "waits for our
|
|
454
|
+
* port to free up"; it never did.
|
|
455
|
+
*
|
|
456
|
+
* So: wait for the port to actually go quiet, then start, then CHECK that
|
|
457
|
+
* something came up, and write a diagnosis when it did not. A restart that
|
|
458
|
+
* fails must leave evidence — this one is invisible by construction, since
|
|
459
|
+
* the process that would have logged it is the one that just exited.
|
|
460
|
+
* @param port - the port the replacement must bind; when unknown, the helper
|
|
461
|
+
* falls back to the old fixed delay, which is better than nothing.
|
|
462
|
+
*/
|
|
463
|
+
export function restartHelperSource(spawned, launch, logs, port, recovery = null) {
|
|
464
|
+
return [
|
|
465
|
+
"const { spawn } = require('node:child_process')",
|
|
466
|
+
"const fs = require('node:fs')",
|
|
467
|
+
"const net = require('node:net')",
|
|
468
|
+
`const file = ${JSON.stringify(spawned.file)}`,
|
|
469
|
+
`const args = ${JSON.stringify(spawned.args)}`,
|
|
470
|
+
`const cwd = ${JSON.stringify(launch.cwd)}`,
|
|
471
|
+
`const viaShell = ${JSON.stringify(spawned.viaShell)}`,
|
|
472
|
+
`const detached = ${JSON.stringify(spawned.detached)}`,
|
|
473
|
+
`const logOut = ${JSON.stringify(logs.out)}`,
|
|
474
|
+
`const logErr = ${JSON.stringify(logs.err)}`,
|
|
475
|
+
`const port = ${JSON.stringify(port)}`,
|
|
476
|
+
`const recoveryScript = ${JSON.stringify(recovery?.script ?? null)}`,
|
|
477
|
+
`const recoveryConfig = ${JSON.stringify(recovery?.config ?? null)}`,
|
|
478
|
+
'const sleep = (ms) => new Promise(r => setTimeout(r, ms))',
|
|
479
|
+
'const note = (line) => { try { fs.appendFileSync(logErr, `[dsh-crate] ${line}\n`) } catch {} }',
|
|
480
|
+
// How the helper itself ended. A restart that fails leaves this file as
|
|
481
|
+
// the only account of what happened, and "the helper vanished" and "the
|
|
482
|
+
// helper exited" are different bugs with the same symptom.
|
|
483
|
+
'process.on("exit", (code) => note("helper exiting (code " + code + ")"))',
|
|
484
|
+
'process.on("uncaughtException", (error) => note("helper crashed: " + (error && error.stack ? error.stack : error)))',
|
|
485
|
+
'process.on("unhandledRejection", (error) => note("helper rejection: " + (error && error.stack ? error.stack : error)))',
|
|
486
|
+
// "Free" means nothing accepts a connection. Checked by connecting rather
|
|
487
|
+
// than by binding: binding to test would itself hold the port for the
|
|
488
|
+
// moment the replacement needs it.
|
|
489
|
+
'const listening = () => new Promise((resolve) => {',
|
|
490
|
+
' const probe = net.connect({ host: "127.0.0.1", port })',
|
|
491
|
+
' const done = (value) => { probe.destroy(); resolve(value) }',
|
|
492
|
+
' probe.on("connect", () => done(true))',
|
|
493
|
+
' probe.on("error", () => done(false))',
|
|
494
|
+
' setTimeout(() => done(false), 500)',
|
|
495
|
+
'})',
|
|
496
|
+
// The recovery surface is a separate process on purpose: it has to
|
|
497
|
+
// outlive this helper AND the DSH package tree it protects, and it must
|
|
498
|
+
// be startable when the composition that just failed is the market's own.
|
|
499
|
+
// A script that cannot be spawned degrades to the pre-recovery behaviour
|
|
500
|
+
// — one line in the log — rather than to no restart at all.
|
|
501
|
+
// How the replacement ended, when it ended before it bound the port.
|
|
502
|
+
// Top level rather than inside main() because the handoff reads it.
|
|
503
|
+
'let exited = null',
|
|
504
|
+
// The pid of the replacement, so the recovery surface can refuse to take
|
|
505
|
+
// the port while that process is still alive (#719). Passed as an argument
|
|
506
|
+
// rather than through the config: the config is written before the spawn.
|
|
507
|
+
'let replacementPid = null',
|
|
508
|
+
'const handOff = async () => {',
|
|
509
|
+
' if (!recoveryScript || !recoveryConfig) return',
|
|
510
|
+
' try {',
|
|
511
|
+
// windowsHide with the detached spawn: this helper has no console, so a
|
|
512
|
+
// console program spawned from it is handed a new, visible one (#624).
|
|
513
|
+
// Measured on Windows 11: the flag combination is accepted and the child
|
|
514
|
+
// runs (the two flags are documented as mutually exclusive on MSDN, so
|
|
515
|
+
// the probe matters more than the docs here).
|
|
516
|
+
' const child = spawn(process.execPath, [recoveryScript, recoveryConfig, "--exit=" + String(exited), "--bound=0", "--pid=" + String(replacementPid ?? 0)], { detached: true, stdio: "ignore", env: process.env, windowsHide: true })',
|
|
517
|
+
' child.on("error", (error) => note(`could not start the recovery surface: ${error && error.message ? error.message : error}`))',
|
|
518
|
+
' child.unref()',
|
|
519
|
+
' note("the replacement never came up — starting the recovery surface")',
|
|
520
|
+
' } catch (error) {',
|
|
521
|
+
' note(`could not start the recovery surface: ${error && error.message ? error.message : error}`)',
|
|
522
|
+
' }',
|
|
523
|
+
'}',
|
|
524
|
+
'const main = async () => {',
|
|
525
|
+
// Stage lines, not debugging: a restart that fails leaves this file as the
|
|
526
|
+
// only account of what the helper did, and "the replacement never came up"
|
|
527
|
+
// reads very differently depending on whether the port was ever released.
|
|
528
|
+
' note(`helper up (pid ${process.pid}) for port ${port}`)',
|
|
529
|
+
' if (port) {',
|
|
530
|
+
' const until = Date.now() + 30000',
|
|
531
|
+
' while (Date.now() < until && await listening()) await sleep(250)',
|
|
532
|
+
' if (await listening()) note(`port ${port} was still in use after 30s; starting anyway`)',
|
|
533
|
+
// A released socket can still be in TIME_WAIT for a moment on Windows.
|
|
534
|
+
' await sleep(300)',
|
|
535
|
+
' note(`port ${port} is free; starting the replacement`)',
|
|
536
|
+
' } else {',
|
|
537
|
+
' await sleep(1500)',
|
|
538
|
+
' }',
|
|
539
|
+
' let child',
|
|
540
|
+
' try {',
|
|
541
|
+
' const out = fs.openSync(logOut, "a")',
|
|
542
|
+
' const err = fs.openSync(logErr, "a")',
|
|
543
|
+
// windowsHide (#624 by @davidekingsss): this helper is itself detached,
|
|
544
|
+
// so on Windows it has no console, and a console program spawned from a
|
|
545
|
+
// console-less parent is given a NEW, visible one — the "Windows
|
|
546
|
+
// PowerShell" window that owns the replacement and takes it down when
|
|
547
|
+
// closed. `-WindowStyle Hidden` cannot hide it: that flag governs the
|
|
548
|
+
// window PowerShell would create, not the console the spawn handed it.
|
|
549
|
+
// CREATE_NO_WINDOW keeps the console but never shows it, and the host's
|
|
550
|
+
// own console children inherit that hidden console rather than popping
|
|
551
|
+
// windows of their own (measured by the reporter with a console-less
|
|
552
|
+
// launcher: one PseudoConsoleWindow without the flag, none with it).
|
|
553
|
+
' child = spawn(file, args, { cwd, detached, stdio: ["ignore", out, err], env: process.env, shell: viaShell, windowsHide: true })',
|
|
554
|
+
// spawn reports a missing or unexecutable file ASYNCHRONOUSLY; the
|
|
555
|
+
// try/catch below only covers the synchronous throw, so without this
|
|
556
|
+
// listener that failure is exactly as silent as the bug being fixed.
|
|
557
|
+
' child.on("error", (error) => note(`could not start the replacement: ${error && error.message ? error.message : error}`))',
|
|
558
|
+
// A replacement that has already exited is a verdict, not a wait: polling
|
|
559
|
+
// out the whole window for a process that is gone is the difference
|
|
560
|
+
// between a recovery page in seconds and one after twenty, and the market
|
|
561
|
+
// page's own poll is racing that same clock.
|
|
562
|
+
' child.on("exit", (code) => { exited = code === null ? -1 : code })',
|
|
563
|
+
' child.unref()',
|
|
564
|
+
' replacementPid = child.pid ?? null',
|
|
565
|
+
' note(`replacement started (pid ${child.pid})`)',
|
|
566
|
+
' } catch (error) {',
|
|
567
|
+
' note(`could not start the replacement: ${error && error.message ? error.message : error}`)',
|
|
568
|
+
' return',
|
|
569
|
+
' }',
|
|
570
|
+
// Outliving the spawn matters on Windows: a helper that exits the
|
|
571
|
+
// instant it has spawned can take the replacement with it, because the
|
|
572
|
+
// child is in its process group and has not detached yet. The port path
|
|
573
|
+
// below already lingers while it polls; this is the same guarantee for
|
|
574
|
+
// the path that has no port to poll. CI on windows-latest caught it —
|
|
575
|
+
// locally it passes either way.
|
|
576
|
+
" if (!port) { await sleep(3000); return }",
|
|
577
|
+
// Success is not 'the port answered once'. A boot that fails its
|
|
578
|
+
// activation audit has ALREADY bound the web port by the time the audit
|
|
579
|
+
// runs — the tree mounts, the server listens, and only then does DSH
|
|
580
|
+
// refuse the whole composition and exit. Judging on a single answer
|
|
581
|
+
// therefore reports success for a harness that is mid-collapse, and the
|
|
582
|
+
// recovery surface never starts: exactly the failure this handoff exists
|
|
583
|
+
// for. The port has to answer CONTINUOUSLY for SETTLE_MS instead, which
|
|
584
|
+
// is far longer than an audit takes to refuse a tree and much shorter
|
|
585
|
+
// than a user would notice. (src/recovery.ts keeps the same rule for the
|
|
586
|
+
// boots it supervises.)
|
|
587
|
+
' const SETTLE_MS = 8000',
|
|
588
|
+
// 45s, not 20s: this window has to outlast a real cold start, and on a
|
|
589
|
+
// source-run host with a large plugin tree the webserver binds at ~42-45s
|
|
590
|
+
// (measured, #719). At 20s the helper gave up while the replacement was
|
|
591
|
+
// still starting, handed the port to the recovery surface, and the
|
|
592
|
+
// replacement then died on EADDRINUSE — a deadlock nothing could break.
|
|
593
|
+
// Matches BOOT_TIMEOUT_MS in src/recovery.ts, which is the same budget
|
|
594
|
+
// seen from the other side. A replacement that EXITS still ends this
|
|
595
|
+
// early (the `exited` break below), so a genuinely failed boot is not
|
|
596
|
+
// made slower by the wider backstop.
|
|
597
|
+
' const startedAt = Date.now()',
|
|
598
|
+
' const upBy = Date.now() + 45000 + SETTLE_MS',
|
|
599
|
+
// #854: the window is a budget for "has it come up", NOT a verdict on
|
|
600
|
+
// "is it dead". A cold start right after the market rewrote node_modules
|
|
601
|
+
// can outlast it (measured on Windows: bind at ~63s with a scanner on the
|
|
602
|
+
// fresh files), and handing the port over while the replacement is still
|
|
603
|
+
// RUNNING is what turns a slow boot into the deadlock #719 removed: the
|
|
604
|
+
// surface takes port 3080, the host reaches its own bind and dies on
|
|
605
|
+
// EADDRINUSE, and nothing can come back. So a replacement that has NOT
|
|
606
|
+
// exited keeps the port, up to a hard cap; one that has exited still ends
|
|
607
|
+
// the wait immediately, which is the failed-boot case.
|
|
608
|
+
' const hardBy = Date.now() + 240000',
|
|
609
|
+
' let steadySince = null',
|
|
610
|
+
' let announcedWait = false',
|
|
611
|
+
' while (true) {',
|
|
612
|
+
' if (await listening()) {',
|
|
613
|
+
' if (steadySince === null) steadySince = Date.now()',
|
|
614
|
+
' else if (Date.now() - steadySince >= SETTLE_MS) return',
|
|
615
|
+
' } else {',
|
|
616
|
+
' steadySince = null',
|
|
617
|
+
' if (exited !== null) break',
|
|
618
|
+
' const now = Date.now()',
|
|
619
|
+
' if (now >= hardBy) break',
|
|
620
|
+
' if (now >= upBy && !announcedWait) {',
|
|
621
|
+
' announcedWait = true',
|
|
622
|
+
// The numbers are computed, not typed twice: a log line that drifts from
|
|
623
|
+
// the constants it describes is worse than no line at all.
|
|
624
|
+
' note(`the replacement is still starting after ${String(Math.round((upBy - startedAt) / 1000))}s and has not exited — waiting up to ${String(Math.round((hardBy - startedAt) / 1000))}s for it rather than taking its port (it would die on EADDRINUSE)`)',
|
|
625
|
+
' }',
|
|
626
|
+
' }',
|
|
627
|
+
' await sleep(500)',
|
|
628
|
+
' }',
|
|
629
|
+
' note(`the replacement never came up on port ${port}${exited === null ? " (it is still running, so the recovery surface waits for it to exit before binding)" : ` (it exited with code ${exited})`} — see the output log beside this one`)',
|
|
630
|
+
// The host is not coming back on its own. Everything the user can still
|
|
631
|
+
// do about it lives in the recovery surface, so start it while the
|
|
632
|
+
// browser tab that asked for the restart is still open.
|
|
633
|
+
' await handOff()',
|
|
634
|
+
'}',
|
|
635
|
+
'main()',
|
|
636
|
+
].join('\n');
|
|
637
|
+
}
|
|
638
|
+
/**
|
|
639
|
+
* Relaunch this exact DSH entry after a detached handoff, then stop this
|
|
640
|
+
* process. The helper outlives us (detached + unref), waits for our port to
|
|
641
|
+
* be released before starting the replacement, and logs under tmpdir.
|
|
642
|
+
*
|
|
643
|
+
* When a recovery config is supplied it is written out BEFORE the helper
|
|
644
|
+
* starts, because it describes the state of the world this process is about
|
|
645
|
+
* to leave behind: the plugin inventory as the live loader sees it, and the
|
|
646
|
+
* exact invocation the replacement needs. Nothing downstream could
|
|
647
|
+
* reconstruct either — the process that knows them is the one being replaced.
|
|
648
|
+
* @param port - the port this process is serving on, so the helper can wait
|
|
649
|
+
* for it rather than guessing at a delay.
|
|
650
|
+
* @param recovery - what the recovery surface needs, when the restart should
|
|
651
|
+
* leave one behind; omitted by callers that do not want one.
|
|
652
|
+
*/
|
|
653
|
+
export function scheduleRestart(port = null, recovery) {
|
|
654
|
+
const launch = restartLaunch();
|
|
655
|
+
const spawned = respawnInvocation(launch);
|
|
656
|
+
const stamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
|
|
657
|
+
const logOut = join(tmpdir(), `dsh-crate-restart-${stamp}.out.log`);
|
|
658
|
+
const logErr = join(tmpdir(), `dsh-crate-restart-${stamp}.err.log`);
|
|
659
|
+
let handoff = null;
|
|
660
|
+
const script = recoveryScriptPath();
|
|
661
|
+
// No port means no origin to serve the recovery page on, and no script
|
|
662
|
+
// means no recovery server to serve it with; in both cases the helper keeps
|
|
663
|
+
// its pre-recovery behaviour instead of leaving a config file nobody reads.
|
|
664
|
+
if (recovery !== undefined && port !== null && script !== null) {
|
|
665
|
+
const configPath = join(tmpdir(), `dsh-crate-restart-${stamp}.recovery.json`);
|
|
666
|
+
try {
|
|
667
|
+
writeFileSync(configPath, JSON.stringify({
|
|
668
|
+
...recovery,
|
|
669
|
+
port,
|
|
670
|
+
logs: { out: logOut, err: logErr },
|
|
671
|
+
spawn: spawned,
|
|
672
|
+
cwd: launch.cwd,
|
|
673
|
+
}, null, 2));
|
|
674
|
+
handoff = { script, config: configPath };
|
|
675
|
+
}
|
|
676
|
+
catch {
|
|
677
|
+
handoff = null;
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
const helper = spawn(nodeExecutable(), ['-e', restartHelperSource(spawned, launch, { out: logOut, err: logErr }, port, handoff)], {
|
|
681
|
+
detached: true,
|
|
682
|
+
stdio: 'ignore',
|
|
683
|
+
env: process.env,
|
|
684
|
+
});
|
|
685
|
+
helper.unref();
|
|
686
|
+
setTimeout(() => process.kill(process.pid, 'SIGTERM'), 500);
|
|
687
|
+
return { pid: process.pid, helperPid: helper.pid, logOut, logErr, recovery: handoff };
|
|
688
|
+
}
|