shellpuppet 0.1.0 → 0.2.1
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 +210 -33
- package/dist/cli/desktopShortcut.d.ts +22 -0
- package/dist/cli/desktopShortcut.js +157 -0
- package/dist/cli/desktopShortcut.js.map +1 -0
- package/dist/cli/index.js +268 -59
- package/dist/cli/index.js.map +1 -1
- package/dist/client/http.d.ts +74 -3
- package/dist/client/http.js +560 -37
- package/dist/client/http.js.map +1 -1
- package/dist/core/dialogs.d.ts +20 -12
- package/dist/core/dialogs.js +31 -19
- package/dist/core/dialogs.js.map +1 -1
- package/dist/core/manager.d.ts +35 -5
- package/dist/core/manager.js +121 -8
- package/dist/core/manager.js.map +1 -1
- package/dist/core/nativePty.d.ts +9 -5
- package/dist/core/nativePty.js +11 -6
- package/dist/core/nativePty.js.map +1 -1
- package/dist/core/promptDetector.d.ts +37 -3
- package/dist/core/promptDetector.js +303 -12
- package/dist/core/promptDetector.js.map +1 -1
- package/dist/core/reasoning.d.ts +19 -6
- package/dist/core/reasoning.js +223 -30
- package/dist/core/reasoning.js.map +1 -1
- package/dist/core/regexBudget.d.ts +20 -0
- package/dist/core/regexBudget.js +25 -1
- package/dist/core/regexBudget.js.map +1 -1
- package/dist/core/renderer.d.ts +16 -1
- package/dist/core/renderer.js +97 -6
- package/dist/core/renderer.js.map +1 -1
- package/dist/core/selection.d.ts +6 -0
- package/dist/core/selection.js +48 -0
- package/dist/core/selection.js.map +1 -0
- package/dist/core/session.d.ts +267 -13
- package/dist/core/session.js +585 -101
- package/dist/core/session.js.map +1 -1
- package/dist/core/types.d.ts +53 -18
- package/dist/core/types.js +30 -6
- package/dist/core/types.js.map +1 -1
- package/dist/core/waiter.d.ts +12 -4
- package/dist/core/waiter.js +63 -70
- package/dist/core/waiter.js.map +1 -1
- package/dist/core/windowsConsoleHost.d.ts +147 -0
- package/dist/core/windowsConsoleHost.js +588 -0
- package/dist/core/windowsConsoleHost.js.map +1 -0
- package/dist/core/windowsPtyStart.d.ts +100 -29
- package/dist/core/windowsPtyStart.js +143 -36
- package/dist/core/windowsPtyStart.js.map +1 -1
- package/dist/daemon/auth.d.ts +72 -2
- package/dist/daemon/auth.js +128 -3
- package/dist/daemon/auth.js.map +1 -1
- package/dist/daemon/config.d.ts +44 -1
- package/dist/daemon/config.js +276 -9
- package/dist/daemon/config.js.map +1 -1
- package/dist/daemon/folderPicker.d.ts +27 -0
- package/dist/daemon/folderPicker.js +115 -0
- package/dist/daemon/folderPicker.js.map +1 -0
- package/dist/daemon/index.js +20 -19
- package/dist/daemon/index.js.map +1 -1
- package/dist/daemon/launchProfiles.d.ts +155 -0
- package/dist/daemon/launchProfiles.js +554 -0
- package/dist/daemon/launchProfiles.js.map +1 -0
- package/dist/daemon/liveness.d.ts +1 -1
- package/dist/daemon/liveness.js +2 -2
- package/dist/daemon/liveness.js.map +1 -1
- package/dist/daemon/paths.d.ts +4 -0
- package/dist/daemon/paths.js.map +1 -1
- package/dist/daemon/restartHold.d.ts +16 -0
- package/dist/daemon/restartHold.js +126 -0
- package/dist/daemon/restartHold.js.map +1 -0
- package/dist/daemon/screenshot.d.ts +58 -1
- package/dist/daemon/screenshot.js +172 -26
- package/dist/daemon/screenshot.js.map +1 -1
- package/dist/daemon/server.d.ts +220 -10
- package/dist/daemon/server.js +1975 -205
- package/dist/daemon/server.js.map +1 -1
- package/dist/daemon/sessionFeed.d.ts +48 -0
- package/dist/daemon/sessionFeed.js +101 -0
- package/dist/daemon/sessionFeed.js.map +1 -0
- package/dist/daemon/viewerLauncher.d.ts +100 -9
- package/dist/daemon/viewerLauncher.js +349 -67
- package/dist/daemon/viewerLauncher.js.map +1 -1
- package/dist/mcp/config.d.ts +7 -14
- package/dist/mcp/config.js +10 -21
- package/dist/mcp/config.js.map +1 -1
- package/dist/mcp/index.js +20 -11
- package/dist/mcp/index.js.map +1 -1
- package/dist/mcp/tools.d.ts +14 -7
- package/dist/mcp/tools.js +161 -60
- package/dist/mcp/tools.js.map +1 -1
- package/dist/viewer/dashboard-folders.js +20 -0
- package/dist/viewer/dashboard-layout.js +52 -0
- package/dist/viewer/dashboard.css +67 -0
- package/dist/viewer/dashboard.html +44 -0
- package/dist/viewer/dashboard.js +1523 -0
- package/dist/viewer/icon.ico +0 -0
- package/dist/viewer/index.html +12 -7
- package/dist/viewer/pane.js +736 -0
- package/dist/viewer/viewer.css +18 -7
- package/dist/viewer/viewer.js +47 -624
- package/package.json +13 -13
package/dist/daemon/server.js
CHANGED
|
@@ -6,33 +6,44 @@
|
|
|
6
6
|
* upgrades, bearer-token auth on the API, no CORS headers at all.
|
|
7
7
|
*/
|
|
8
8
|
import * as fs from 'node:fs';
|
|
9
|
+
import { randomUUID } from 'node:crypto';
|
|
9
10
|
import * as http from 'node:http';
|
|
10
11
|
import { createRequire } from 'node:module';
|
|
12
|
+
import * as os from 'node:os';
|
|
11
13
|
import * as path from 'node:path';
|
|
12
14
|
import { fileURLToPath } from 'node:url';
|
|
13
15
|
import { WebSocketServer } from 'ws';
|
|
14
|
-
import { SessionManager, PolicyViolationError } from '../core/manager.js';
|
|
15
|
-
import { CommandNotFoundError, DEFAULT_SESSION_ENV, credentialShapedNames } from '../core/session.js';
|
|
16
|
+
import { SessionManager, PolicyViolationError, SessionStartError } from '../core/manager.js';
|
|
17
|
+
import { CommandNotFoundError, DEFAULT_SESSION_ENV, SessionInputFailedError, SessionProgramEndedError, WindowsWithoutConPTYError, credentialShapedNames, } from '../core/session.js';
|
|
16
18
|
import { NativePtyUnavailableError } from '../core/nativePty.js';
|
|
17
|
-
import { commandLine, compilePolicy } from '../core/policy.js';
|
|
19
|
+
import { checkSessionCapacity, commandLine, compilePolicy, evaluateCommand } from '../core/policy.js';
|
|
18
20
|
import { keyToBytes, knownKeys } from '../core/keys.js';
|
|
19
21
|
import { findOnScreen } from '../core/find.js';
|
|
20
22
|
import { screenShows } from '../core/echo.js';
|
|
21
23
|
import { RegexBudgetError } from '../core/regexBudget.js';
|
|
22
24
|
import { detectPrompt } from '../core/promptDetector.js';
|
|
25
|
+
import { markFilteredSelectedOption } from '../core/selection.js';
|
|
23
26
|
import { WaitConditionError } from '../core/waiter.js';
|
|
24
27
|
import { agentNames, hideReasoning, latestResult, programName, signatureFor } from '../core/reasoning.js';
|
|
25
|
-
import { ENV_NAME_PATTERN } from '../core/types.js';
|
|
26
|
-
import { TokenStore, VIEWER_COOKIE, VIEWER_GRANT_TTL_MS, bearerToken, cookieValues, viewerCookie, } from './auth.js';
|
|
28
|
+
import { DEFAULT_WAIT_TIMEOUT_MS, ENV_NAME_PATTERN, MAX_WAIT_TIMEOUT_MS, WAIT_POLL_INTERVAL_MS, howSessionEnded } from '../core/types.js';
|
|
29
|
+
import { DASHBOARD_COOKIE, TokenStore, VIEWER_COOKIE, VIEWER_GRANT_TTL_MS, bearerToken, cookieValues, dashboardCookie, dashboardProofFromProtocol, tokensEqual, viewerCookie, } from './auth.js';
|
|
27
30
|
import { NULL_AUDITOR } from './audit.js';
|
|
28
|
-
import { findBrowser, launchViewer } from './viewerLauncher.js';
|
|
29
|
-
import { DEFAULT_CAPTURE_TIMEOUT_MS, MAX_CAPTURE_TIMEOUT_MS, MIN_CAPTURE_TIMEOUT_MS, captureViewer, } from './screenshot.js';
|
|
31
|
+
import { findBrowser, launchDashboard, launchViewer } from './viewerLauncher.js';
|
|
32
|
+
import { DEFAULT_CAPTURE_TIMEOUT_MS, MAX_CAPTURE_TIMEOUT_MS, MIN_CAPTURE_TIMEOUT_MS, captureProfileRoot, captureViewer, sweepCaptureProfiles, } from './screenshot.js';
|
|
30
33
|
import { claimDaemonState, daemonStatePath, ensureHome, inspectDaemonState, readDaemonState, removeDaemonState, removeDaemonStateIf, removeDaemonStateIfNotARecord, } from './paths.js';
|
|
31
34
|
import { daemonRunning } from './liveness.js';
|
|
32
35
|
import { packageVersion } from './meta.js';
|
|
33
36
|
import { terminalReportKind } from './terminalReports.js';
|
|
34
37
|
import { ViewerSync } from './viewerSync.js';
|
|
38
|
+
import { SessionFeed } from './sessionFeed.js';
|
|
39
|
+
import { compileProfilePolicy, copyDaemonEnv, describeProfileText, expandProfileText, resolveLaunchCommand, resolveAnyFolder, } from './launchProfiles.js';
|
|
40
|
+
import { listRootFolders, resolveRootFolder } from './launchProfiles.js';
|
|
41
|
+
import { chooseFolder, FOLDER_PICKER_TIMEOUT_MS, FolderPickerFailureError, FolderPickerUnavailableError, FolderPickerTimeoutError } from './folderPicker.js';
|
|
35
42
|
const DEFAULT_IDLE_MS = 30 * 60_000;
|
|
43
|
+
/** Stop waits this long for an automatic dashboard launch before continuing. */
|
|
44
|
+
const DASHBOARD_LAUNCH_SHUTDOWN_WAIT_MS = 3_000;
|
|
45
|
+
/** Stop waits this long for a cancelled desktop picker to exit. */
|
|
46
|
+
const FOLDER_PICKER_SHUTDOWN_WAIT_MS = 3_000;
|
|
36
47
|
const IDLE_CHECK_INTERVAL_MS = 60_000;
|
|
37
48
|
/**
|
|
38
49
|
* How often a running daemon checks that daemon.json still names it, and
|
|
@@ -55,6 +66,10 @@ const MAX_BODY_BYTES = 1_000_000;
|
|
|
55
66
|
*/
|
|
56
67
|
const PROMPT_SCAN_INTERVAL_MS = 5_000;
|
|
57
68
|
const PROMPT_STALL_MS = 20_000;
|
|
69
|
+
// A repaint can leave a scan with no complete dialog. Keep the held prompt
|
|
70
|
+
// for one second, long enough for a TUI redraw. A one-off check at the end
|
|
71
|
+
// of that grace clears a lasting disappearance between normal scan beats.
|
|
72
|
+
const PROMPT_REPAINT_GRACE_MS = 1_000;
|
|
58
73
|
/**
|
|
59
74
|
* How long `verify` looks for typed text: a base, plus time for each
|
|
60
75
|
* character, up to a ceiling. Some TUIs work through every keystroke before
|
|
@@ -95,13 +110,42 @@ const MAX_VIEWPORT_ROWS = 150;
|
|
|
95
110
|
* the wipe and nothing stale can paint after it.
|
|
96
111
|
*/
|
|
97
112
|
const VIEWER_WIPE = '\x1bc\x1b[3J';
|
|
113
|
+
/** Bounded, text-free facts about a browser replay that disagrees with its source. */
|
|
114
|
+
function rowDifferenceDiagnostics(expected, actual) {
|
|
115
|
+
const differingRows = [];
|
|
116
|
+
let differenceCount = 0;
|
|
117
|
+
for (let row = 0; row < Math.max(expected.length, actual.length); row++) {
|
|
118
|
+
const left = expected[row] ?? '';
|
|
119
|
+
const right = actual[row] ?? '';
|
|
120
|
+
if (expected[row] === actual[row])
|
|
121
|
+
continue;
|
|
122
|
+
differenceCount++;
|
|
123
|
+
if (differingRows.length === 5)
|
|
124
|
+
continue;
|
|
125
|
+
let firstColumn = 0;
|
|
126
|
+
while (firstColumn < Math.min(left.length, right.length) &&
|
|
127
|
+
left[firstColumn] === right[firstColumn])
|
|
128
|
+
firstColumn++;
|
|
129
|
+
differingRows.push({
|
|
130
|
+
row, expectedLength: left.length, actualLength: right.length, firstColumn,
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
return {
|
|
134
|
+
differenceCount,
|
|
135
|
+
expectedRowCount: expected.length,
|
|
136
|
+
actualRowCount: actual.length,
|
|
137
|
+
differingRows,
|
|
138
|
+
};
|
|
139
|
+
}
|
|
98
140
|
/**
|
|
99
|
-
* What a watcher is shown when the
|
|
141
|
+
* What a watcher is shown when the session ends: grey, on its own line
|
|
100
142
|
* and identical whether it was sent live at the moment of exit or replayed
|
|
101
|
-
* to someone who joined during the fifteen-minute grace.
|
|
143
|
+
* to someone who joined during the fifteen-minute grace. An end with no exit
|
|
144
|
+
* code says why the session ended (`howSessionEnded`).
|
|
102
145
|
*/
|
|
103
146
|
function exitNotice(exitCode) {
|
|
104
|
-
|
|
147
|
+
const notice = exitCode === null ? `session ended: ${howSessionEnded(null)}` : `process exited: ${String(exitCode)}`;
|
|
148
|
+
return `\r\n\x1b[90m[${notice}]\x1b[0m\r\n`;
|
|
105
149
|
}
|
|
106
150
|
/**
|
|
107
151
|
* Static viewer assets, resolved once and served from a fixed allowlist.
|
|
@@ -115,7 +159,12 @@ const nodeRequire = createRequire(import.meta.url);
|
|
|
115
159
|
const xtermJsPath = nodeRequire.resolve('@xterm/xterm');
|
|
116
160
|
const STATIC_ASSETS = {
|
|
117
161
|
'/viewer/viewer.js': { file: path.join(viewerDir, 'viewer.js'), type: 'text/javascript' },
|
|
162
|
+
'/viewer/pane.js': { file: path.join(viewerDir, 'pane.js'), type: 'text/javascript' },
|
|
118
163
|
'/viewer/viewer.css': { file: path.join(viewerDir, 'viewer.css'), type: 'text/css' },
|
|
164
|
+
'/viewer/dashboard.js': { file: path.join(viewerDir, 'dashboard.js'), type: 'text/javascript' },
|
|
165
|
+
'/viewer/dashboard-layout.js': { file: path.join(viewerDir, 'dashboard-layout.js'), type: 'text/javascript' },
|
|
166
|
+
'/viewer/dashboard-folders.js': { file: path.join(viewerDir, 'dashboard-folders.js'), type: 'text/javascript' },
|
|
167
|
+
'/viewer/dashboard.css': { file: path.join(viewerDir, 'dashboard.css'), type: 'text/css' },
|
|
119
168
|
// The mark. SVG first (crisp at any size, and what the tab uses); the PNGs
|
|
120
169
|
// are for Windows, which wants a raster for the taskbar button of a Chrome
|
|
121
170
|
// --app window. An SVG-only favicon leaves that button showing the generic
|
|
@@ -133,7 +182,19 @@ const STATIC_ASSETS = {
|
|
|
133
182
|
'/vendor/addon-fit.js': { file: nodeRequire.resolve('@xterm/addon-fit'), type: 'text/javascript' },
|
|
134
183
|
};
|
|
135
184
|
const viewerHtmlPath = path.join(viewerDir, 'index.html');
|
|
185
|
+
const dashboardHtmlPath = path.join(viewerDir, 'dashboard.html');
|
|
186
|
+
/**
|
|
187
|
+
* Shared by the viewer page and the dashboard page. Inline styles are what
|
|
188
|
+
* xterm uses to size itself. Scripts stay under `default-src 'self'`.
|
|
189
|
+
*/
|
|
190
|
+
const PAGE_CSP = "default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:";
|
|
191
|
+
const DASHBOARD_HEARTBEAT_INTERVAL_MS = 15_000;
|
|
192
|
+
const DASHBOARD_HEARTBEAT_TIMEOUT_MS = 10_000;
|
|
193
|
+
const DASHBOARD_PROOF_META = '<meta name="sp-csrf" content="">';
|
|
194
|
+
const DASHBOARD_FONT_META = '<meta name="sp-dashboard-font-size" content="">';
|
|
136
195
|
/** Thrown by `start()` when a healthy daemon already owns this home. */
|
|
196
|
+
/** The largest dashboard window registration frame the daemon will parse. */
|
|
197
|
+
const MAX_WINDOW_REGISTRATION_BYTES = 256;
|
|
137
198
|
export class AlreadyRunningError extends Error {
|
|
138
199
|
state;
|
|
139
200
|
constructor(state) {
|
|
@@ -143,6 +204,40 @@ export class AlreadyRunningError extends Error {
|
|
|
143
204
|
this.name = 'AlreadyRunningError';
|
|
144
205
|
}
|
|
145
206
|
}
|
|
207
|
+
/** The scheme and authority that open an absolute-form request target (`http://user@host:port`). */
|
|
208
|
+
const SCHEME_AND_AUTHORITY = /^[a-z][a-z0-9+.-]*:\/\/[^/]*/i;
|
|
209
|
+
/**
|
|
210
|
+
* A request target's path, for a log line: without its query or fragment,
|
|
211
|
+
* and, for an absolute-form target, without the scheme and authority, which
|
|
212
|
+
* name the host and can name a user and a password. Split rather than
|
|
213
|
+
* parsed: a target `new URL` refuses must still be logged, and never throw
|
|
214
|
+
* inside the error handler.
|
|
215
|
+
*/
|
|
216
|
+
function pathOnly(target) {
|
|
217
|
+
const path = (target ?? '').split(/[?#]/, 1)[0] ?? '';
|
|
218
|
+
const absolute = SCHEME_AND_AUTHORITY.exec(path);
|
|
219
|
+
return absolute === null ? path : path.slice(absolute[0].length) || '/';
|
|
220
|
+
}
|
|
221
|
+
function headerOne(req, name) {
|
|
222
|
+
const value = req.headers[name];
|
|
223
|
+
if (Array.isArray(value))
|
|
224
|
+
return value[0];
|
|
225
|
+
return value;
|
|
226
|
+
}
|
|
227
|
+
/** Subprotocols offered on an upgrade, in header order. */
|
|
228
|
+
function offeredProtocols(req) {
|
|
229
|
+
const value = req.headers['sec-websocket-protocol'];
|
|
230
|
+
const raw = Array.isArray(value) ? value.join(',') : (value ?? '');
|
|
231
|
+
return raw
|
|
232
|
+
.split(',')
|
|
233
|
+
.map((part) => part.trim())
|
|
234
|
+
.filter((part) => part !== '');
|
|
235
|
+
}
|
|
236
|
+
/** The 409 for input, a key or a resize sent to a session that has ended. */
|
|
237
|
+
function endedRefusal(id, exitCode) {
|
|
238
|
+
return (`Session ${id} has ${exitCode === null ? 'ended' : 'exited'} ` +
|
|
239
|
+
`(${howSessionEnded(exitCode)}) and no longer accepts input or geometry changes.`);
|
|
240
|
+
}
|
|
146
241
|
function isRecord(value) {
|
|
147
242
|
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
148
243
|
}
|
|
@@ -154,20 +249,38 @@ function json(res, code, body) {
|
|
|
154
249
|
});
|
|
155
250
|
res.end(payload);
|
|
156
251
|
}
|
|
252
|
+
/**
|
|
253
|
+
* A request body over `MAX_BODY_BYTES`. Answered with 413, not a reset: the
|
|
254
|
+
* reader keeps consuming and discarding what is left so the response can be
|
|
255
|
+
* read, rather than destroying the socket mid-upload.
|
|
256
|
+
*/
|
|
257
|
+
class RequestBodyTooLargeError extends Error {
|
|
258
|
+
constructor() {
|
|
259
|
+
super(`Request body too large: the limit is ${String(MAX_BODY_BYTES)} bytes.`);
|
|
260
|
+
this.name = 'RequestBodyTooLargeError';
|
|
261
|
+
}
|
|
262
|
+
}
|
|
157
263
|
function readBody(req) {
|
|
158
264
|
return new Promise((resolve, reject) => {
|
|
159
265
|
let size = 0;
|
|
266
|
+
let tooLarge = false;
|
|
160
267
|
const chunks = [];
|
|
161
268
|
req.on('data', (chunk) => {
|
|
269
|
+
if (tooLarge)
|
|
270
|
+
return; // discard the rest, so the 413 can be read
|
|
162
271
|
size += chunk.length;
|
|
163
272
|
if (size > MAX_BODY_BYTES) {
|
|
164
|
-
|
|
165
|
-
|
|
273
|
+
tooLarge = true;
|
|
274
|
+
chunks.length = 0;
|
|
166
275
|
return;
|
|
167
276
|
}
|
|
168
277
|
chunks.push(chunk);
|
|
169
278
|
});
|
|
170
279
|
req.on('end', () => {
|
|
280
|
+
if (tooLarge) {
|
|
281
|
+
reject(new RequestBodyTooLargeError());
|
|
282
|
+
return;
|
|
283
|
+
}
|
|
171
284
|
if (chunks.length === 0) {
|
|
172
285
|
resolve({});
|
|
173
286
|
return;
|
|
@@ -236,6 +349,14 @@ function overBudgetMessage(signature) {
|
|
|
236
349
|
return (`The ${signature.name} signature ran past the regular-expression time budget and is set ` +
|
|
237
350
|
'aside for a minute, so the screen is not returned filtered. Try again shortly.');
|
|
238
351
|
}
|
|
352
|
+
/** Read one rendered frame for both a filtered wait predicate and its reply. */
|
|
353
|
+
function filteredWaitScreen(session, signature) {
|
|
354
|
+
const view = session.styledScreenNow(REASONING_CONTEXT_LINES);
|
|
355
|
+
const filtered = hideReasoning(view.lines, signature, view.firstVisible);
|
|
356
|
+
if (filtered === null)
|
|
357
|
+
throw new WaitConditionError(overBudgetMessage(signature));
|
|
358
|
+
return { screen: markFilteredSelectedOption(filtered.lines, view.lines).join('\n'), filtered };
|
|
359
|
+
}
|
|
239
360
|
/**
|
|
240
361
|
* A query flag: absent, `0` or `false` is off, `1` or `true` is on, and
|
|
241
362
|
* anything else is null, a mistake the caller is refused for. A flag that
|
|
@@ -249,6 +370,16 @@ function queryFlag(url, name) {
|
|
|
249
370
|
return true;
|
|
250
371
|
return null;
|
|
251
372
|
}
|
|
373
|
+
/**
|
|
374
|
+
* `drive=0` on a session stream: a viewer or client socket adopts the grid
|
|
375
|
+
* and does not become the controller by connecting. An absent flag is not
|
|
376
|
+
* this request. The single-session viewer sends none and still drives.
|
|
377
|
+
* `drive=false` is not a spelling. A dashboard credential does not consult
|
|
378
|
+
* this flag: that socket is always passive.
|
|
379
|
+
*/
|
|
380
|
+
function passiveDrive(url) {
|
|
381
|
+
return url.searchParams.get('drive') === '0';
|
|
382
|
+
}
|
|
252
383
|
const BAD_HIDE_REASONING = 'hideReasoning must be true or false (or 1 or 0).';
|
|
253
384
|
/**
|
|
254
385
|
* The cursor among the lines a filtered screen returns: on its own row when
|
|
@@ -318,29 +449,56 @@ export class Daemon {
|
|
|
318
449
|
tokens = new TokenStore();
|
|
319
450
|
manager;
|
|
320
451
|
server;
|
|
321
|
-
wss = new WebSocketServer({
|
|
452
|
+
wss = new WebSocketServer({
|
|
453
|
+
noServer: true,
|
|
454
|
+
// Echo a subprotocol only when the dashboard credential opens the feed
|
|
455
|
+
// or a session stream. A client token wins a session stream, so that
|
|
456
|
+
// upgrade selects none even if the cookie and a live proof are also
|
|
457
|
+
// offered. Returning false leaves the upgrade with none selected.
|
|
458
|
+
handleProtocols: (protocols, request) => this.dashboardProtocol(protocols, request),
|
|
459
|
+
});
|
|
322
460
|
sockets = new Set();
|
|
323
461
|
/** Every watcher of a session, with the gate that orders its stream across snapshots. */
|
|
324
462
|
sessionSockets = new Map();
|
|
463
|
+
/** Frozen replay bytes belong only to the screenshot's one-use viewer grant. */
|
|
464
|
+
captureSnapshots = new Map();
|
|
325
465
|
/**
|
|
326
466
|
* The viewport currently driving each session's grid (§5).
|
|
327
467
|
*
|
|
328
|
-
* Connecting is passive and acting takes control: the first
|
|
329
|
-
* arrive with nobody driving picks the grid up, a later one
|
|
330
|
-
* finds and
|
|
331
|
-
*
|
|
332
|
-
*
|
|
333
|
-
*
|
|
468
|
+
* Connecting is passive and acting takes control: the first single-session
|
|
469
|
+
* viewport to arrive with nobody driving picks the grid up, a later one
|
|
470
|
+
* adopts what it finds, and a resize from that human hands control over.
|
|
471
|
+
* A dashboard credential is the exception, whatever the query says. It
|
|
472
|
+
* adopts and does not pick the grid up on connect, and it does not inherit
|
|
473
|
+
* the grid when the controlling socket leaves. Its resize counts only when
|
|
474
|
+
* the frame carries `take: true`. `drive=0` is the same opt-out for a
|
|
475
|
+
* viewer or client socket, and it cannot make a dashboard socket drive.
|
|
334
476
|
*/
|
|
335
477
|
geometryController = new Map();
|
|
478
|
+
/** A dashboard document keeps its grid while a covered pane reconnects. */
|
|
479
|
+
dashboardGeometryOwner = new Map();
|
|
336
480
|
/** Subscribers to the daemon-wide event stream (`/events`). */
|
|
337
481
|
eventSockets = new Set();
|
|
482
|
+
/**
|
|
483
|
+
* Open `/dashboard/events` sockets. While one is open, a session start does
|
|
484
|
+
* not launch a per-session viewer window and does not hand back a viewer URL.
|
|
485
|
+
*/
|
|
486
|
+
dashboardEventSockets = new Set();
|
|
487
|
+
/** Opaque roster ids carried by dashboard feed sockets, never used for authorisation. */
|
|
488
|
+
dashboardWindowIds = new Map();
|
|
489
|
+
liveDashboardEventSockets = new Set();
|
|
490
|
+
/** A launched dashboard has 30 seconds to connect before a start may retry. */
|
|
491
|
+
dashboardWindowStartedAt = 0;
|
|
492
|
+
dashboardOpenPromise = null;
|
|
493
|
+
pendingDashboardGrants = new Set();
|
|
494
|
+
stopping = false;
|
|
338
495
|
/**
|
|
339
496
|
* Per-session prompt tracking for stall alerts: the signature of the prompt
|
|
340
497
|
* currently on screen, when it was first seen and whether it has alerted.
|
|
341
498
|
*/
|
|
342
499
|
promptStates = new Map();
|
|
343
500
|
version = packageVersion();
|
|
501
|
+
sessionFeed;
|
|
344
502
|
portValue = null;
|
|
345
503
|
waitsInFlight = 0;
|
|
346
504
|
lastActivity = Date.now();
|
|
@@ -350,9 +508,11 @@ export class Daemon {
|
|
|
350
508
|
statePublishRunning = false;
|
|
351
509
|
/** What this daemon published in daemon.json, once it has claimed it. */
|
|
352
510
|
publishedState = null;
|
|
511
|
+
instanceId = randomUUID();
|
|
353
512
|
/** The pid of another running daemon already reported as owning daemon.json. */
|
|
354
513
|
foreignOwnerReported = null;
|
|
355
514
|
promptScanTimer = null;
|
|
515
|
+
promptGraceTimers = new Map();
|
|
356
516
|
promptScanRunning = false;
|
|
357
517
|
stopPromise = null;
|
|
358
518
|
audit;
|
|
@@ -361,17 +521,47 @@ export class Daemon {
|
|
|
361
521
|
* that what the daemon reports is what its sessions get.
|
|
362
522
|
*/
|
|
363
523
|
sessionEnv;
|
|
524
|
+
/** The profiles the dashboard may name, and the entries that did not load. */
|
|
525
|
+
launchProfiles;
|
|
526
|
+
daemonEnv;
|
|
527
|
+
/** The global policy, kept here so a launch can report it before creating. */
|
|
528
|
+
compiledPolicy;
|
|
529
|
+
/** Accepted launch times, for the sliding sixty-second cap. */
|
|
530
|
+
launchTimes = [];
|
|
531
|
+
folderPickerBusy = false;
|
|
532
|
+
folderPickerAbort = null;
|
|
533
|
+
folderPickerDone = null;
|
|
534
|
+
/** Includes requests still reading their body when shutdown begins. */
|
|
535
|
+
folderPickerHandlers = new Set();
|
|
536
|
+
/**
|
|
537
|
+
* Sessions created whose program does not exist yet (`programStarted`):
|
|
538
|
+
* not listed and not in the feed until the start contract is met.
|
|
539
|
+
*/
|
|
540
|
+
startingIds = new Set();
|
|
364
541
|
constructor(options) {
|
|
365
|
-
|
|
542
|
+
const startedWrapped = process.env['SHELLPUPPET_DAEMON_STARTED_WRAPPED'] === '1';
|
|
543
|
+
delete process.env['SHELLPUPPET_DAEMON_STARTED_WRAPPED'];
|
|
544
|
+
this.options = { ...options, startedWrapped: options.startedWrapped ?? startedWrapped };
|
|
366
545
|
this.logger = options.logger;
|
|
367
546
|
this.audit = options.audit ?? NULL_AUDITOR;
|
|
368
547
|
this.sessionEnv = options.sessionEnv ?? DEFAULT_SESSION_ENV;
|
|
548
|
+
this.launchProfiles = options.launchProfiles ?? { profiles: [], problems: [] };
|
|
549
|
+
this.daemonEnv = options.daemonEnv ?? process.env;
|
|
550
|
+
this.compiledPolicy = compilePolicy(options.policy);
|
|
369
551
|
this.manager = new SessionManager(compilePolicy(options.policy), this.logger, {
|
|
370
552
|
sessionEnv: this.sessionEnv,
|
|
371
|
-
});
|
|
553
|
+
}, (id) => this.sessionFeed.remove(id));
|
|
554
|
+
this.sessionFeed = new SessionFeed(this.version, () => this.listedSummaries().map((summary) => this.summaryWithPrompt(summary)), this.logger);
|
|
372
555
|
this.server = http.createServer((req, res) => {
|
|
373
556
|
this.handleRequest(req, res).catch((error) => {
|
|
374
|
-
|
|
557
|
+
// What a person needs to find the fault: the stack, and which request
|
|
558
|
+
// met it by method and path. Never the query, the headers or the
|
|
559
|
+
// body: a query can carry a viewer grant, a header the client token.
|
|
560
|
+
this.logger.error('unhandled request error', {
|
|
561
|
+
method: req.method,
|
|
562
|
+
path: pathOnly(req.url),
|
|
563
|
+
error: error instanceof Error ? (error.stack ?? String(error)) : String(error),
|
|
564
|
+
});
|
|
375
565
|
if (!res.headersSent)
|
|
376
566
|
json(res, 500, { error: 'The daemon hit an unexpected error handling this request. Its daemon.log records the error.' });
|
|
377
567
|
});
|
|
@@ -385,6 +575,10 @@ export class Daemon {
|
|
|
385
575
|
throw new Error('Daemon not started.');
|
|
386
576
|
return this.portValue;
|
|
387
577
|
}
|
|
578
|
+
/** Clock for dashboard grant expiry. Tests inject one; otherwise wall time. */
|
|
579
|
+
now() {
|
|
580
|
+
return this.options.now?.() ?? Date.now();
|
|
581
|
+
}
|
|
388
582
|
get token() {
|
|
389
583
|
return this.tokens.token;
|
|
390
584
|
}
|
|
@@ -402,6 +596,10 @@ export class Daemon {
|
|
|
402
596
|
get liveSessions() {
|
|
403
597
|
return this.manager.liveCount();
|
|
404
598
|
}
|
|
599
|
+
/** Subscribe inside the daemon to the dashboard's session feed. */
|
|
600
|
+
subscribeDashboardFeed(listener) {
|
|
601
|
+
return this.sessionFeed.subscribe(listener);
|
|
602
|
+
}
|
|
405
603
|
// ------------------------------------------------------------------ start
|
|
406
604
|
async start() {
|
|
407
605
|
const { home } = this.options;
|
|
@@ -422,6 +620,13 @@ export class Daemon {
|
|
|
422
620
|
this.server.once('error', reject);
|
|
423
621
|
this.server.listen(0, '127.0.0.1', () => {
|
|
424
622
|
this.server.removeListener('error', reject);
|
|
623
|
+
// Once listening, an error is a connection the server failed to
|
|
624
|
+
// accept, out of handles say. With no listener it would be an
|
|
625
|
+
// uncaught exception, on which the daemon shuts down with every
|
|
626
|
+
// session; the server goes on accepting instead.
|
|
627
|
+
this.server.on('error', (error) => {
|
|
628
|
+
this.logger.error('http server error', { error: String(error) });
|
|
629
|
+
});
|
|
425
630
|
resolve();
|
|
426
631
|
});
|
|
427
632
|
});
|
|
@@ -432,9 +637,10 @@ export class Daemon {
|
|
|
432
637
|
this.portValue = address.port;
|
|
433
638
|
// Browser detection is slow the first time it runs (viewerLauncher.ts), and
|
|
434
639
|
// a session start waits for its viewer launch, so look once now and let the
|
|
435
|
-
// memoised answer serve every start.
|
|
436
|
-
|
|
437
|
-
|
|
640
|
+
// memoised answer serve every start. It never holds the event loop, so the
|
|
641
|
+
// daemon answers /health and everything else while it runs.
|
|
642
|
+
if (['dashboard', 'isolated-app'].includes(this.options.viewer?.launchMode ?? 'no-window')) {
|
|
643
|
+
void findBrowser(this.options.viewer?.browserPath, this.logger).catch(() => undefined);
|
|
438
644
|
}
|
|
439
645
|
const state = {
|
|
440
646
|
port: this.portValue,
|
|
@@ -442,6 +648,8 @@ export class Daemon {
|
|
|
442
648
|
pid: process.pid,
|
|
443
649
|
version: this.version,
|
|
444
650
|
startedAt: new Date().toISOString(),
|
|
651
|
+
instanceId: this.instanceId,
|
|
652
|
+
startedWrapped: this.options.startedWrapped ?? false,
|
|
445
653
|
};
|
|
446
654
|
// Atomic claim; on losing the race, defer to the winner (design §2.2:
|
|
447
655
|
// the race is normal, not exceptional). A file that holds no record at all,
|
|
@@ -485,6 +693,10 @@ export class Daemon {
|
|
|
485
693
|
}
|
|
486
694
|
}, 1_000);
|
|
487
695
|
this.raceCheckTimer.unref();
|
|
696
|
+
// Capture profiles an earlier daemon on this home could not remove, which
|
|
697
|
+
// Windows can refuse while a browser's last processes hold them. Only
|
|
698
|
+
// folders a capture names, untouched for longer than any capture runs.
|
|
699
|
+
void sweepCaptureProfiles(captureProfileRoot(home), this.logger);
|
|
488
700
|
// Said once, at start, because passthrough leaks silently otherwise
|
|
489
701
|
// (ADR-008): the names only, never the values.
|
|
490
702
|
const { exposed } = this.environmentReport();
|
|
@@ -645,7 +857,10 @@ export class Daemon {
|
|
|
645
857
|
stop(opts = {}) {
|
|
646
858
|
// Idle-stop, signal handlers and explicit stops can overlap, so everyone
|
|
647
859
|
// awaits the one real shutdown.
|
|
648
|
-
this.stopPromise
|
|
860
|
+
if (this.stopPromise === null) {
|
|
861
|
+
this.stopping = true;
|
|
862
|
+
this.stopPromise = this.doStop(opts);
|
|
863
|
+
}
|
|
649
864
|
return this.stopPromise;
|
|
650
865
|
}
|
|
651
866
|
async doStop(opts) {
|
|
@@ -657,6 +872,10 @@ export class Daemon {
|
|
|
657
872
|
clearInterval(this.statePublishTimer);
|
|
658
873
|
if (this.promptScanTimer !== null)
|
|
659
874
|
clearInterval(this.promptScanTimer);
|
|
875
|
+
for (const timer of this.promptGraceTimers.values())
|
|
876
|
+
clearTimeout(timer);
|
|
877
|
+
this.promptGraceTimers.clear();
|
|
878
|
+
this.folderPickerAbort?.abort(new FolderPickerFailureError('The folder picker was stopped.'));
|
|
660
879
|
// Stop LISTENING first, before tearing down session trees. Killing process
|
|
661
880
|
// trees is not fast (`taskkill /T` on a loaded machine can take seconds
|
|
662
881
|
// per session), and a daemon that still answers on its port while shutting
|
|
@@ -674,63 +893,1091 @@ export class Daemon {
|
|
|
674
893
|
// Best effort.
|
|
675
894
|
}
|
|
676
895
|
}
|
|
677
|
-
await this.manager.killAll();
|
|
678
|
-
if (
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
896
|
+
await this.manager.killAll();
|
|
897
|
+
if (this.folderPickerDone !== null) {
|
|
898
|
+
let pickerWaitTimer;
|
|
899
|
+
await Promise.race([
|
|
900
|
+
this.folderPickerDone,
|
|
901
|
+
new Promise((resolve) => { pickerWaitTimer = setTimeout(resolve, FOLDER_PICKER_SHUTDOWN_WAIT_MS); }),
|
|
902
|
+
]);
|
|
903
|
+
if (pickerWaitTimer !== undefined)
|
|
904
|
+
clearTimeout(pickerWaitTimer);
|
|
905
|
+
}
|
|
906
|
+
if (this.folderPickerHandlers.size > 0) {
|
|
907
|
+
let handlerWaitTimer;
|
|
908
|
+
await Promise.race([
|
|
909
|
+
Promise.allSettled([...this.folderPickerHandlers]),
|
|
910
|
+
new Promise((resolve) => { handlerWaitTimer = setTimeout(resolve, FOLDER_PICKER_SHUTDOWN_WAIT_MS); }),
|
|
911
|
+
]);
|
|
912
|
+
if (handlerWaitTimer !== undefined)
|
|
913
|
+
clearTimeout(handlerWaitTimer);
|
|
914
|
+
}
|
|
915
|
+
// Revoke grants even if browser detection or spawn never settles. A late
|
|
916
|
+
// launcher result also takes the stopping path in openDashboardWindow.
|
|
917
|
+
for (const grant of this.pendingDashboardGrants)
|
|
918
|
+
this.tokens.revokeDashboardGrant(grant);
|
|
919
|
+
if (this.dashboardOpenPromise !== null) {
|
|
920
|
+
let timer;
|
|
921
|
+
await Promise.race([
|
|
922
|
+
this.dashboardOpenPromise,
|
|
923
|
+
new Promise((resolve) => { timer = setTimeout(resolve, DASHBOARD_LAUNCH_SHUTDOWN_WAIT_MS); }),
|
|
924
|
+
]);
|
|
925
|
+
if (timer !== undefined)
|
|
926
|
+
clearTimeout(timer);
|
|
927
|
+
}
|
|
928
|
+
if (opts.removeState !== false) {
|
|
929
|
+
// Remove this daemon's record, or a file that holds none. A file that
|
|
930
|
+
// cannot be read says nothing about what it holds, so it stays.
|
|
931
|
+
const file = inspectDaemonState(this.options.home);
|
|
932
|
+
if (file.kind === 'record' && file.state.pid === process.pid) {
|
|
933
|
+
removeDaemonState(this.options.home);
|
|
934
|
+
}
|
|
935
|
+
else if (file.kind === 'not-a-record') {
|
|
936
|
+
removeDaemonStateIfNotARecord(this.options.home, file.raw);
|
|
937
|
+
}
|
|
938
|
+
}
|
|
939
|
+
// Only now terminate lingering keep-alive connections, so close() cannot hang.
|
|
940
|
+
this.server.closeAllConnections();
|
|
941
|
+
await listenerClosed;
|
|
942
|
+
this.logger.info('daemon stopped');
|
|
943
|
+
}
|
|
944
|
+
/**
|
|
945
|
+
* What sessions inherit (ADR-008): the mode, and under passthrough the names
|
|
946
|
+
* of the credential-shaped variables in the daemon's environment. Never values.
|
|
947
|
+
*/
|
|
948
|
+
environmentReport() {
|
|
949
|
+
const mode = this.sessionEnv;
|
|
950
|
+
if (mode === 'passthrough')
|
|
951
|
+
return { mode, exposed: credentialShapedNames(process.env) };
|
|
952
|
+
return { mode: mode === 'clean' ? 'clean' : 'list', exposed: [] };
|
|
953
|
+
}
|
|
954
|
+
// ------------------------------------------------------- request handling
|
|
955
|
+
hostAllowed(host) {
|
|
956
|
+
if (host === undefined || this.portValue === null)
|
|
957
|
+
return false;
|
|
958
|
+
const normalised = host.toLowerCase();
|
|
959
|
+
return (normalised === `127.0.0.1:${String(this.portValue)}` ||
|
|
960
|
+
normalised === `localhost:${String(this.portValue)}`);
|
|
961
|
+
}
|
|
962
|
+
originAllowed(origin) {
|
|
963
|
+
if (origin === undefined)
|
|
964
|
+
return true; // non-browser clients send none
|
|
965
|
+
if (this.portValue === null)
|
|
966
|
+
return false;
|
|
967
|
+
const normalised = origin.toLowerCase();
|
|
968
|
+
return (normalised === `http://127.0.0.1:${String(this.portValue)}` ||
|
|
969
|
+
normalised === `http://localhost:${String(this.portValue)}`);
|
|
970
|
+
}
|
|
971
|
+
/**
|
|
972
|
+
* An Origin that is this daemon's own and whose host matches `Host`.
|
|
973
|
+
* `127.0.0.1` and `localhost` are both allowed names, and they are not the
|
|
974
|
+
* same host: a cookie minted for one must not be presented as the other.
|
|
975
|
+
*/
|
|
976
|
+
originMatchesRequest(req) {
|
|
977
|
+
const origin = headerOne(req, 'origin');
|
|
978
|
+
if (origin === undefined || origin === '')
|
|
979
|
+
return false;
|
|
980
|
+
if (!this.originAllowed(origin))
|
|
981
|
+
return false;
|
|
982
|
+
const host = headerOne(req, 'host');
|
|
983
|
+
if (host === undefined)
|
|
984
|
+
return false;
|
|
985
|
+
try {
|
|
986
|
+
return new URL(origin).host.toLowerCase() === host.toLowerCase();
|
|
987
|
+
}
|
|
988
|
+
catch {
|
|
989
|
+
return false;
|
|
990
|
+
}
|
|
991
|
+
}
|
|
992
|
+
/** Top-level document load of the dashboard. Origin may be absent. */
|
|
993
|
+
isDocumentNavigation(req) {
|
|
994
|
+
if (req.method !== 'GET' && req.method !== 'HEAD')
|
|
995
|
+
return false;
|
|
996
|
+
if (headerOne(req, 'sec-fetch-mode') !== 'navigate')
|
|
997
|
+
return false;
|
|
998
|
+
if (headerOne(req, 'sec-fetch-dest') !== 'document')
|
|
999
|
+
return false;
|
|
1000
|
+
const site = headerOne(req, 'sec-fetch-site');
|
|
1001
|
+
if (site !== 'none' && site !== 'same-origin')
|
|
1002
|
+
return false;
|
|
1003
|
+
const origin = headerOne(req, 'origin');
|
|
1004
|
+
if (origin === undefined || origin === '')
|
|
1005
|
+
return true;
|
|
1006
|
+
return this.originMatchesRequest(req);
|
|
1007
|
+
}
|
|
1008
|
+
/** Same-origin read, such as `GET /sessions` from the dashboard page. */
|
|
1009
|
+
isSameOriginRead(req) {
|
|
1010
|
+
if (req.method !== 'GET' && req.method !== 'HEAD')
|
|
1011
|
+
return false;
|
|
1012
|
+
if (headerOne(req, 'sec-fetch-site') !== 'same-origin')
|
|
1013
|
+
return false;
|
|
1014
|
+
const mode = headerOne(req, 'sec-fetch-mode');
|
|
1015
|
+
if (mode !== 'cors' && mode !== 'no-cors' && mode !== 'same-origin')
|
|
1016
|
+
return false;
|
|
1017
|
+
const origin = headerOne(req, 'origin');
|
|
1018
|
+
if (origin === undefined || origin === '')
|
|
1019
|
+
return true;
|
|
1020
|
+
return this.originMatchesRequest(req);
|
|
1021
|
+
}
|
|
1022
|
+
/** `same-site`, `cross-site`, or any site value that is not a dashboard site. */
|
|
1023
|
+
forbiddenFetchSite(site) {
|
|
1024
|
+
if (site === undefined || site === '')
|
|
1025
|
+
return false;
|
|
1026
|
+
return site !== 'none' && site !== 'same-origin';
|
|
1027
|
+
}
|
|
1028
|
+
dashboardCookiePresented(header) {
|
|
1029
|
+
if (header === undefined)
|
|
1030
|
+
return false;
|
|
1031
|
+
for (const part of header.split(';')) {
|
|
1032
|
+
const at = part.indexOf('=');
|
|
1033
|
+
if (at === -1)
|
|
1034
|
+
continue;
|
|
1035
|
+
if (part.slice(0, at).trim() === DASHBOARD_COOKIE)
|
|
1036
|
+
return true;
|
|
1037
|
+
}
|
|
1038
|
+
return false;
|
|
1039
|
+
}
|
|
1040
|
+
/** The first `sp_dash` value the daemon issued for the current credential. */
|
|
1041
|
+
dashboardCookieToken(header) {
|
|
1042
|
+
for (const value of cookieValues(header, DASHBOARD_COOKIE)) {
|
|
1043
|
+
if (this.tokens.verifyDashboardToken(value))
|
|
1044
|
+
return value;
|
|
1045
|
+
}
|
|
1046
|
+
return null;
|
|
1047
|
+
}
|
|
1048
|
+
auditDashboardRefusal(req, reason) {
|
|
1049
|
+
this.audit.record('dashboard', 'refuse', undefined, {
|
|
1050
|
+
method: req.method ?? '',
|
|
1051
|
+
path: pathOnly(req.url),
|
|
1052
|
+
reason,
|
|
1053
|
+
});
|
|
1054
|
+
}
|
|
1055
|
+
/**
|
|
1056
|
+
* Why a presented cookie was refused on a route that may omit Origin:
|
|
1057
|
+
* the dashboard page, outside a document navigation, and `GET /sessions`.
|
|
1058
|
+
* A present Origin that does not match is `origin`. These routes allow an
|
|
1059
|
+
* absent Origin, so that absence is not the reason: the Fetch Metadata is.
|
|
1060
|
+
*/
|
|
1061
|
+
cookieRefusalReason(req) {
|
|
1062
|
+
const origin = headerOne(req, 'origin');
|
|
1063
|
+
const originAbsent = origin === undefined || origin === '';
|
|
1064
|
+
if (!originAbsent && !this.originMatchesRequest(req))
|
|
1065
|
+
return 'origin';
|
|
1066
|
+
return 'fetch-site';
|
|
1067
|
+
}
|
|
1068
|
+
dashboardDocument(proof) {
|
|
1069
|
+
const html = fs.readFileSync(dashboardHtmlPath, 'utf8');
|
|
1070
|
+
const withProof = proof === null ? html.replace(DASHBOARD_PROOF_META, '')
|
|
1071
|
+
: html.replace(DASHBOARD_PROOF_META, `<meta name="sp-csrf" content="${proof}">`);
|
|
1072
|
+
const size = proof === null ? undefined : this.options.dashboardFontSize;
|
|
1073
|
+
return withProof.replace(DASHBOARD_FONT_META, size === undefined ? '' : `<meta name="sp-dashboard-font-size" content="${String(size)}">`);
|
|
1074
|
+
}
|
|
1075
|
+
sendDashboardPage(res, proof, head) {
|
|
1076
|
+
const headers = {
|
|
1077
|
+
'content-type': 'text/html; charset=utf-8',
|
|
1078
|
+
'cache-control': 'no-store',
|
|
1079
|
+
'content-security-policy': PAGE_CSP,
|
|
1080
|
+
};
|
|
1081
|
+
res.writeHead(200, headers);
|
|
1082
|
+
res.end(head ? '' : this.dashboardDocument(proof));
|
|
1083
|
+
}
|
|
1084
|
+
/**
|
|
1085
|
+
* `GET` and `HEAD /dashboard`. A grant is spent only by an accepted
|
|
1086
|
+
* document navigation, which redirects with a cookie before any page loads.
|
|
1087
|
+
* A fetch does not spend it. A bad, spent or absent grant without a live
|
|
1088
|
+
* cookie returns the guidance page without revealing whether it was real.
|
|
1089
|
+
*/
|
|
1090
|
+
handleDashboardPage(req, res, url) {
|
|
1091
|
+
const site = headerOne(req, 'sec-fetch-site');
|
|
1092
|
+
if (this.forbiddenFetchSite(site)) {
|
|
1093
|
+
this.auditDashboardRefusal(req, 'fetch-site');
|
|
1094
|
+
json(res, 403, { error: 'Forbidden.' });
|
|
1095
|
+
return;
|
|
1096
|
+
}
|
|
1097
|
+
const grant = url.searchParams.get('dt');
|
|
1098
|
+
// An empty dt is still a presented grant: it must never fall through to a cookie.
|
|
1099
|
+
const grantPresented = grant !== null;
|
|
1100
|
+
const cookiePresented = this.dashboardCookiePresented(req.headers.cookie);
|
|
1101
|
+
const cookie = this.dashboardCookieToken(req.headers.cookie);
|
|
1102
|
+
if (this.isDocumentNavigation(req)) {
|
|
1103
|
+
if (grantPresented) {
|
|
1104
|
+
const redeemed = this.tokens.redeemDashboardGrant(grant, this.now());
|
|
1105
|
+
if (redeemed !== null) {
|
|
1106
|
+
this.audit.record('dashboard', 'grant-redeem');
|
|
1107
|
+
res.writeHead(303, {
|
|
1108
|
+
location: '/dashboard',
|
|
1109
|
+
'set-cookie': dashboardCookie(redeemed.token),
|
|
1110
|
+
'cache-control': 'no-store',
|
|
1111
|
+
});
|
|
1112
|
+
res.end();
|
|
1113
|
+
return;
|
|
1114
|
+
}
|
|
1115
|
+
this.sendDashboardPage(res, null, req.method === 'HEAD');
|
|
1116
|
+
return;
|
|
1117
|
+
}
|
|
1118
|
+
const proof = cookie === null ? null : this.tokens.issueDashboardProof();
|
|
1119
|
+
this.sendDashboardPage(res, proof, req.method === 'HEAD');
|
|
1120
|
+
return;
|
|
1121
|
+
}
|
|
1122
|
+
if (grantPresented || cookiePresented) {
|
|
1123
|
+
if (!this.isSameOriginRead(req)) {
|
|
1124
|
+
this.auditDashboardRefusal(req, this.cookieRefusalReason(req));
|
|
1125
|
+
json(res, 403, { error: 'Forbidden.' });
|
|
1126
|
+
return;
|
|
1127
|
+
}
|
|
1128
|
+
}
|
|
1129
|
+
this.sendDashboardPage(res, null, req.method === 'HEAD');
|
|
1130
|
+
}
|
|
1131
|
+
async openDashboardWindow(req, actor) {
|
|
1132
|
+
if (this.stopping)
|
|
1133
|
+
return false;
|
|
1134
|
+
const grant = this.tokens.mintDashboardGrant({ now: this.now() });
|
|
1135
|
+
this.pendingDashboardGrants.add(grant);
|
|
1136
|
+
const pageUrl = `http://127.0.0.1:${String(this.port)}/dashboard?dt=${grant}`;
|
|
1137
|
+
// The dashboard opens only in the isolated profile. The viewer launcher
|
|
1138
|
+
// may fall back to the default browser so a session start never fails;
|
|
1139
|
+
// that fallback would hand this grant to a profile with extensions.
|
|
1140
|
+
const launch = this.options.launcher ?? launchDashboard;
|
|
1141
|
+
let opened;
|
|
1142
|
+
try {
|
|
1143
|
+
opened = await launch(pageUrl, this.options.home, this.options.viewer ?? {}, this.logger, {
|
|
1144
|
+
shouldLaunch: () => !this.stopping,
|
|
1145
|
+
});
|
|
1146
|
+
}
|
|
1147
|
+
catch {
|
|
1148
|
+
// The thrown text can carry the URL. It is not logged and not returned.
|
|
1149
|
+
opened = { launched: false, mode: 'no-window' };
|
|
1150
|
+
}
|
|
1151
|
+
this.pendingDashboardGrants.delete(grant);
|
|
1152
|
+
if (this.stopping || !opened.launched || opened.mode === 'default-browser') {
|
|
1153
|
+
this.tokens.revokeDashboardGrant(grant);
|
|
1154
|
+
this.auditDashboardRefusal(req, 'launch-failed');
|
|
1155
|
+
return false;
|
|
1156
|
+
}
|
|
1157
|
+
this.audit.record(actor, 'grant-mint', undefined, { credential: 'dashboard' });
|
|
1158
|
+
return true;
|
|
1159
|
+
}
|
|
1160
|
+
async handleDashboardOpen(req, res, actor) {
|
|
1161
|
+
// The body cannot choose a lifetime. It is read so a keep-alive connection
|
|
1162
|
+
// is not left holding it, and then ignored.
|
|
1163
|
+
await readBody(req);
|
|
1164
|
+
if (await this.openDashboardWindow(req, actor)) {
|
|
1165
|
+
this.dashboardWindowStartedAt = this.now();
|
|
1166
|
+
json(res, 200, { opened: true });
|
|
1167
|
+
}
|
|
1168
|
+
else {
|
|
1169
|
+
json(res, 502, {
|
|
1170
|
+
error: 'The dashboard window did not open. ShellPuppet opens the dashboard only in its ' +
|
|
1171
|
+
'own browser profile; set viewer.browserPath in config.json to a Chromium-family ' +
|
|
1172
|
+
'browser.',
|
|
1173
|
+
});
|
|
1174
|
+
}
|
|
1175
|
+
}
|
|
1176
|
+
async handleDesktopOpen(req, res, actor) {
|
|
1177
|
+
await readBody(req);
|
|
1178
|
+
if (this.hasLiveDashboardSocket()) {
|
|
1179
|
+
json(res, 200, { opened: false, alreadyOpen: true });
|
|
1180
|
+
return;
|
|
1181
|
+
}
|
|
1182
|
+
const result = await this.openDashboardForStart(req, actor);
|
|
1183
|
+
if (result.launched) {
|
|
1184
|
+
json(res, 200, { opened: true, alreadyOpen: false });
|
|
1185
|
+
}
|
|
1186
|
+
else if (result.reason === 'a dashboard window is opening' || result.reason === 'a dashboard is connected') {
|
|
1187
|
+
json(res, 200, { opened: false, alreadyOpen: true });
|
|
1188
|
+
}
|
|
1189
|
+
else {
|
|
1190
|
+
json(res, 502, { error: 'The dashboard window did not open. Set viewer.browserPath in config.json to a Chromium-family browser.' });
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
async openDashboardForStart(req, actor) {
|
|
1194
|
+
if (this.hasLiveDashboardSocket()) {
|
|
1195
|
+
return { launched: false, mode: 'dashboard', reason: 'a dashboard is connected' };
|
|
1196
|
+
}
|
|
1197
|
+
if (this.dashboardWindowStartedAt > 0 && this.now() - this.dashboardWindowStartedAt < 30_000) {
|
|
1198
|
+
return { launched: false, mode: 'dashboard', reason: 'a dashboard window is opening' };
|
|
1199
|
+
}
|
|
1200
|
+
if (this.dashboardOpenPromise !== null) {
|
|
1201
|
+
const opened = await this.dashboardOpenPromise;
|
|
1202
|
+
return opened
|
|
1203
|
+
? { launched: false, mode: 'dashboard', reason: 'a dashboard window is opening' }
|
|
1204
|
+
: { launched: false, mode: 'dashboard', reason: 'the dashboard window did not open' };
|
|
1205
|
+
}
|
|
1206
|
+
this.dashboardOpenPromise = this.openDashboardWindow(req, actor).then((opened) => {
|
|
1207
|
+
if (opened)
|
|
1208
|
+
this.dashboardWindowStartedAt = this.now();
|
|
1209
|
+
return opened;
|
|
1210
|
+
}).finally(() => { this.dashboardOpenPromise = null; });
|
|
1211
|
+
const opened = await this.dashboardOpenPromise;
|
|
1212
|
+
return opened
|
|
1213
|
+
? { launched: true, mode: 'dashboard', reason: 'opened in the dashboard' }
|
|
1214
|
+
: { launched: false, mode: 'dashboard', reason: 'the dashboard window did not open' };
|
|
1215
|
+
}
|
|
1216
|
+
writeSessionList(res, url) {
|
|
1217
|
+
const hide = queryFlag(url, 'hideReasoning');
|
|
1218
|
+
const waitingOnly = queryFlag(url, 'waitingOnly');
|
|
1219
|
+
if (hide === null || waitingOnly === null) {
|
|
1220
|
+
json(res, 400, { error: hide === null ? BAD_HIDE_REASONING : 'waitingOnly must be true or false.' });
|
|
1221
|
+
return;
|
|
1222
|
+
}
|
|
1223
|
+
json(res, 200, { sessions: waitingOnly ? this.waitingSessions(hide) : this.listWithPrompts(hide), version: this.version });
|
|
1224
|
+
}
|
|
1225
|
+
waitingSessions(hideReasoning, ids) {
|
|
1226
|
+
return this.listWithPrompts(hideReasoning).flatMap((session) => {
|
|
1227
|
+
const waiting = session.waitingOnPrompt;
|
|
1228
|
+
if (session.exited || waiting === undefined || (ids !== undefined && !ids.has(session.id)))
|
|
1229
|
+
return [];
|
|
1230
|
+
return [{
|
|
1231
|
+
id: session.id,
|
|
1232
|
+
label: session.label,
|
|
1233
|
+
...(waiting.question === undefined ? {} : { question: waiting.question }),
|
|
1234
|
+
...(waiting.options === undefined ? {} : { options: waiting.options }),
|
|
1235
|
+
...(waiting.selectedOption === undefined ? {} : { selectedOption: waiting.selectedOption }),
|
|
1236
|
+
waitingMs: waiting.waitingMs,
|
|
1237
|
+
}];
|
|
1238
|
+
});
|
|
1239
|
+
}
|
|
1240
|
+
async waitAcrossSessions(res, url) {
|
|
1241
|
+
const hide = queryFlag(url, 'hideReasoning');
|
|
1242
|
+
const now = queryFlag(url, 'now');
|
|
1243
|
+
const timeoutText = url.searchParams.get('timeout');
|
|
1244
|
+
const timeout = timeoutText === null ? DEFAULT_WAIT_TIMEOUT_MS : Number(timeoutText);
|
|
1245
|
+
if (hide === null || now === null || url.searchParams.get('prompt') !== 'true' ||
|
|
1246
|
+
!Number.isFinite(timeout) || timeout < 0 || timeout > MAX_WAIT_TIMEOUT_MS ||
|
|
1247
|
+
['text', 'regex', 'quiet', 'debounce', 'matchAfterInput'].some((key) => url.searchParams.has(key))) {
|
|
1248
|
+
json(res, 400, { error: 'A multi-session wait needs prompt=true, optional now, hideReasoning and a timeout from 0 to 300000 ms.' });
|
|
1249
|
+
return;
|
|
1250
|
+
}
|
|
1251
|
+
const requested = url.searchParams.getAll('session');
|
|
1252
|
+
if (requested.some((id) => id === '' || this.manager.get(id) === undefined)) {
|
|
1253
|
+
json(res, 404, { error: 'No such session in session list.' });
|
|
1254
|
+
return;
|
|
1255
|
+
}
|
|
1256
|
+
const ids = requested.length === 0 ? undefined : new Set(requested);
|
|
1257
|
+
const started = Date.now();
|
|
1258
|
+
this.waitsInFlight += 1;
|
|
1259
|
+
try {
|
|
1260
|
+
while (!res.destroyed) {
|
|
1261
|
+
const sessions = this.waitingSessions(hide, ids);
|
|
1262
|
+
const waitedMs = Date.now() - started;
|
|
1263
|
+
if (sessions.length > 0 || now || waitedMs >= timeout) {
|
|
1264
|
+
json(res, 200, { matched: sessions.length > 0, reason: sessions.length > 0 ? 'prompt' : 'timeout', waitedMs, sessions });
|
|
1265
|
+
return;
|
|
1266
|
+
}
|
|
1267
|
+
await new Promise((resolve) => setTimeout(resolve, Math.min(WAIT_POLL_INTERVAL_MS, timeout - waitedMs)));
|
|
1268
|
+
}
|
|
1269
|
+
}
|
|
1270
|
+
finally {
|
|
1271
|
+
this.waitsInFlight -= 1;
|
|
1272
|
+
}
|
|
1273
|
+
}
|
|
1274
|
+
/** Cookie-authenticated `GET /sessions`. A missing or wrong proof is a 403. */
|
|
1275
|
+
serveDashboardSessionList(req, res, url) {
|
|
1276
|
+
const presented = this.dashboardCookiePresented(req.headers.cookie);
|
|
1277
|
+
const cookie = this.dashboardCookieToken(req.headers.cookie);
|
|
1278
|
+
if (cookie === null) {
|
|
1279
|
+
if (presented)
|
|
1280
|
+
this.auditDashboardRefusal(req, 'unauthenticated');
|
|
1281
|
+
json(res, 401, { error: 'Unauthorised: a valid client token is required.' });
|
|
1282
|
+
return;
|
|
1283
|
+
}
|
|
1284
|
+
if (!this.isSameOriginRead(req)) {
|
|
1285
|
+
this.auditDashboardRefusal(req, this.cookieRefusalReason(req));
|
|
1286
|
+
json(res, 403, { error: 'Forbidden.' });
|
|
1287
|
+
return;
|
|
1288
|
+
}
|
|
1289
|
+
const proof = headerOne(req, 'x-shellpuppet-csrf');
|
|
1290
|
+
if (!this.tokens.acceptsDashboardProof(proof)) {
|
|
1291
|
+
this.auditDashboardRefusal(req, 'proof');
|
|
1292
|
+
json(res, 403, { error: 'Forbidden.' });
|
|
1293
|
+
return;
|
|
1294
|
+
}
|
|
1295
|
+
this.lastActivity = Date.now();
|
|
1296
|
+
this.writeSessionList(res, url);
|
|
1297
|
+
}
|
|
1298
|
+
/** A cookie mutation: same-origin Fetch Metadata and a matching Origin. */
|
|
1299
|
+
isSameOriginMutation(req) {
|
|
1300
|
+
if (headerOne(req, 'sec-fetch-site') !== 'same-origin')
|
|
1301
|
+
return false;
|
|
1302
|
+
return this.originMatchesRequest(req);
|
|
1303
|
+
}
|
|
1304
|
+
/**
|
|
1305
|
+
* Why a cookie mutation is refused, for the audit. A missing or foreign
|
|
1306
|
+
* `Origin` is `origin`; a request whose `Origin` is this page's but whose
|
|
1307
|
+
* `Sec-Fetch-Site` is not `same-origin` is `fetch-site`. The route needs
|
|
1308
|
+
* both, so this only decides the reason a request failing both is recorded
|
|
1309
|
+
* under: naming the Origin keeps the two defences apart in the log.
|
|
1310
|
+
*/
|
|
1311
|
+
mutationRefusalReason(req) {
|
|
1312
|
+
const origin = headerOne(req, 'origin');
|
|
1313
|
+
if (origin === undefined || origin === '' || !this.originMatchesRequest(req))
|
|
1314
|
+
return 'origin';
|
|
1315
|
+
return 'fetch-site';
|
|
1316
|
+
}
|
|
1317
|
+
/**
|
|
1318
|
+
* What the page needs to show a profile, and nothing secret: the command
|
|
1319
|
+
* and arguments are the profile's own, and `envFromDaemon` contributes
|
|
1320
|
+
* configured names or "all". `{folder}` stays unexpanded here because it
|
|
1321
|
+
* depends on the click.
|
|
1322
|
+
*/
|
|
1323
|
+
async profileDescription(profile) {
|
|
1324
|
+
return {
|
|
1325
|
+
name: profile.name,
|
|
1326
|
+
label: describeProfileText(profile.label ?? '', profile.name),
|
|
1327
|
+
purpose: describeProfileText(profile.purpose ?? '', profile.name),
|
|
1328
|
+
command: profile.command,
|
|
1329
|
+
args: [...profile.args],
|
|
1330
|
+
folderRequired: profile.askCwd,
|
|
1331
|
+
anyFolder: profile.anyFolder,
|
|
1332
|
+
folders: profile.folders.map((folder) => ({ name: folder.name, path: folder.path })),
|
|
1333
|
+
rootFolders: (await listRootFolders(profile.folderRoots.map((root) => path.resolve(os.homedir(), root))))
|
|
1334
|
+
.map((choice) => profile.anyFolder
|
|
1335
|
+
? { ...choice, path: path.join(path.resolve(os.homedir(), profile.folderRoots[choice.rootIndex] ?? ''), choice.name) }
|
|
1336
|
+
: choice),
|
|
1337
|
+
envFromDaemon: profile.envFromDaemon === 'all' ? 'all' : [...profile.envFromDaemon],
|
|
1338
|
+
};
|
|
1339
|
+
}
|
|
1340
|
+
/** Cookie-authenticated `GET /dashboard/profiles`. A missing proof is a 403. */
|
|
1341
|
+
async serveDashboardProfiles(req, res) {
|
|
1342
|
+
const presented = this.dashboardCookiePresented(req.headers.cookie);
|
|
1343
|
+
const cookie = this.dashboardCookieToken(req.headers.cookie);
|
|
1344
|
+
if (cookie === null) {
|
|
1345
|
+
if (presented)
|
|
1346
|
+
this.auditDashboardRefusal(req, 'unauthenticated');
|
|
1347
|
+
json(res, 401, { error: 'Unauthorised: a valid client token is required.' });
|
|
1348
|
+
return;
|
|
1349
|
+
}
|
|
1350
|
+
if (!this.isSameOriginRead(req)) {
|
|
1351
|
+
this.auditDashboardRefusal(req, this.cookieRefusalReason(req));
|
|
1352
|
+
json(res, 403, { error: 'Forbidden.' });
|
|
1353
|
+
return;
|
|
1354
|
+
}
|
|
1355
|
+
if (!this.tokens.acceptsDashboardProof(headerOne(req, 'x-shellpuppet-csrf'))) {
|
|
1356
|
+
this.auditDashboardRefusal(req, 'proof');
|
|
1357
|
+
json(res, 403, { error: 'Forbidden.' });
|
|
1358
|
+
return;
|
|
1359
|
+
}
|
|
1360
|
+
this.lastActivity = Date.now();
|
|
1361
|
+
json(res, 200, {
|
|
1362
|
+
profiles: await Promise.all(this.launchProfiles.profiles.map((profile) => this.profileDescription(profile))),
|
|
1363
|
+
problems: [...this.launchProfiles.problems],
|
|
1364
|
+
});
|
|
1365
|
+
}
|
|
1366
|
+
/** The desktop picker is available only to an authenticated any-folder profile. */
|
|
1367
|
+
async handleDashboardFolderPicker(req, res) {
|
|
1368
|
+
const presented = this.dashboardCookiePresented(req.headers.cookie);
|
|
1369
|
+
if (this.dashboardCookieToken(req.headers.cookie) === null) {
|
|
1370
|
+
if (presented)
|
|
1371
|
+
this.auditDashboardRefusal(req, 'unauthenticated');
|
|
1372
|
+
json(res, 401, { error: 'Unauthorised: a valid client token is required.' });
|
|
1373
|
+
return;
|
|
1374
|
+
}
|
|
1375
|
+
if (!this.isSameOriginMutation(req)) {
|
|
1376
|
+
this.auditDashboardRefusal(req, this.mutationRefusalReason(req));
|
|
1377
|
+
json(res, 403, { error: 'Forbidden.' });
|
|
1378
|
+
return;
|
|
1379
|
+
}
|
|
1380
|
+
if (!this.tokens.acceptsDashboardProof(headerOne(req, 'x-shellpuppet-csrf'))) {
|
|
1381
|
+
this.auditDashboardRefusal(req, 'proof');
|
|
1382
|
+
json(res, 403, { error: 'Forbidden.' });
|
|
1383
|
+
return;
|
|
1384
|
+
}
|
|
1385
|
+
if ((headerOne(req, 'content-type') ?? '').split(';', 1)[0]?.trim().toLowerCase() !== 'application/json') {
|
|
1386
|
+
json(res, 415, { error: 'The picker body must be JSON (application/json).' });
|
|
1387
|
+
return;
|
|
1388
|
+
}
|
|
1389
|
+
let body;
|
|
1390
|
+
try {
|
|
1391
|
+
body = await readBody(req);
|
|
1392
|
+
}
|
|
1393
|
+
catch {
|
|
1394
|
+
json(res, 400, { error: 'Invalid picker body.' });
|
|
1395
|
+
return;
|
|
1396
|
+
}
|
|
1397
|
+
if (this.stopping) {
|
|
1398
|
+
json(res, 503, { error: 'The daemon is stopping.' });
|
|
1399
|
+
return;
|
|
1400
|
+
}
|
|
1401
|
+
if (Object.keys(body).length !== 1 || typeof body['profile'] !== 'string' ||
|
|
1402
|
+
!this.launchProfiles.profiles.some((profile) => profile.name === body['profile'] && profile.anyFolder)) {
|
|
1403
|
+
json(res, 400, { error: 'This profile does not allow a folder picker.' });
|
|
1404
|
+
return;
|
|
1405
|
+
}
|
|
1406
|
+
// Stop sets `stopping` synchronously. There is no await between this
|
|
1407
|
+
// check, installing the controller and creating the runner.
|
|
1408
|
+
if (this.stopping) {
|
|
1409
|
+
json(res, 503, { error: 'The daemon is stopping.' });
|
|
1410
|
+
return;
|
|
1411
|
+
}
|
|
1412
|
+
if (this.folderPickerBusy) {
|
|
1413
|
+
json(res, 409, { error: 'A folder picker is already open.' });
|
|
1414
|
+
return;
|
|
1415
|
+
}
|
|
1416
|
+
this.folderPickerBusy = true;
|
|
1417
|
+
const controller = new AbortController();
|
|
1418
|
+
this.folderPickerAbort = controller;
|
|
1419
|
+
let finishPicker;
|
|
1420
|
+
this.folderPickerDone = new Promise((resolve) => { finishPicker = resolve; });
|
|
1421
|
+
let rejectAbort;
|
|
1422
|
+
const aborted = new Promise((_resolve, reject) => { rejectAbort = reject; });
|
|
1423
|
+
const onAbort = () => {
|
|
1424
|
+
rejectAbort?.(controller.signal.reason instanceof Error
|
|
1425
|
+
? controller.signal.reason : new FolderPickerFailureError('The folder picker was cancelled.'));
|
|
1426
|
+
};
|
|
1427
|
+
controller.signal.addEventListener('abort', onAbort, { once: true });
|
|
1428
|
+
const timer = setTimeout(() => controller.abort(new FolderPickerTimeoutError('The folder picker timed out.')), this.options.folderPickerTimeoutMs ?? FOLDER_PICKER_TIMEOUT_MS);
|
|
1429
|
+
let run;
|
|
1430
|
+
try {
|
|
1431
|
+
run = (this.options.folderPicker ?? chooseFolder)(controller.signal);
|
|
1432
|
+
}
|
|
1433
|
+
catch (error) {
|
|
1434
|
+
run = Promise.reject(error instanceof Error ? error : new FolderPickerFailureError('The folder picker failed.'));
|
|
1435
|
+
}
|
|
1436
|
+
const finish = () => {
|
|
1437
|
+
if (this.folderPickerAbort === controller) {
|
|
1438
|
+
this.folderPickerBusy = false;
|
|
1439
|
+
this.folderPickerAbort = null;
|
|
1440
|
+
this.folderPickerDone = null;
|
|
1441
|
+
}
|
|
1442
|
+
finishPicker?.();
|
|
1443
|
+
};
|
|
1444
|
+
void run.then(finish, finish);
|
|
1445
|
+
try {
|
|
1446
|
+
const selected = await Promise.race([run, aborted]);
|
|
1447
|
+
if (controller.signal.aborted)
|
|
1448
|
+
throw controller.signal.reason;
|
|
1449
|
+
if (selected === null || selected === '') {
|
|
1450
|
+
res.writeHead(204);
|
|
1451
|
+
res.end();
|
|
1452
|
+
return;
|
|
1453
|
+
}
|
|
1454
|
+
json(res, 200, { path: selected });
|
|
1455
|
+
}
|
|
1456
|
+
catch (error) {
|
|
1457
|
+
const failure = controller.signal.aborted && controller.signal.reason instanceof Error ? controller.signal.reason : error;
|
|
1458
|
+
if (failure instanceof FolderPickerTimeoutError)
|
|
1459
|
+
json(res, 504, { error: failure.message });
|
|
1460
|
+
else if (failure instanceof FolderPickerUnavailableError)
|
|
1461
|
+
json(res, 503, { error: failure.message });
|
|
1462
|
+
else if (failure instanceof FolderPickerFailureError)
|
|
1463
|
+
json(res, 502, { error: failure.message });
|
|
1464
|
+
else
|
|
1465
|
+
json(res, 502, { error: 'The folder picker failed.' });
|
|
1466
|
+
}
|
|
1467
|
+
finally {
|
|
1468
|
+
clearTimeout(timer);
|
|
1469
|
+
controller.signal.removeEventListener('abort', onAbort);
|
|
1470
|
+
}
|
|
1471
|
+
}
|
|
1472
|
+
/**
|
|
1473
|
+
* The directory a launch starts in: the selected folder's configured path,
|
|
1474
|
+
* the profile's fixed path, or the user's home. Relative paths are taken
|
|
1475
|
+
* from the user's home, as a direct `POST /sessions` does. The path is a
|
|
1476
|
+
* spawn `cwd`, never a command-line fragment.
|
|
1477
|
+
*/
|
|
1478
|
+
resolveLaunchCwd(profile, folder) {
|
|
1479
|
+
const configured = folder?.path ?? profile.cwd;
|
|
1480
|
+
const cwd = configured === undefined ? os.homedir() : path.resolve(os.homedir(), configured);
|
|
1481
|
+
try {
|
|
1482
|
+
if (!fs.statSync(cwd).isDirectory())
|
|
1483
|
+
return { error: `Working directory is not a directory: ${cwd}` };
|
|
1484
|
+
}
|
|
1485
|
+
catch {
|
|
1486
|
+
return { error: `Working directory does not exist: ${cwd}` };
|
|
1487
|
+
}
|
|
1488
|
+
return { cwd };
|
|
1489
|
+
}
|
|
1490
|
+
/** Accepted launch times inside the last sixty seconds, oldest first. */
|
|
1491
|
+
pruneLaunchTimes(now) {
|
|
1492
|
+
while (this.launchTimes.length > 0 && (this.launchTimes[0] ?? now) <= now - 60_000) {
|
|
1493
|
+
this.launchTimes.shift();
|
|
1494
|
+
}
|
|
1495
|
+
}
|
|
1496
|
+
/**
|
|
1497
|
+
* `POST /dashboard/launch`: one configured profile, and nothing else. The
|
|
1498
|
+
* body names a profile and, when that profile asks, a folder. Only profiles
|
|
1499
|
+
* configured for any folder may receive a path. The page cannot supply a
|
|
1500
|
+
* command, arguments or an environment value.
|
|
1501
|
+
*/
|
|
1502
|
+
async handleDashboardLaunch(req, res) {
|
|
1503
|
+
const presented = this.dashboardCookiePresented(req.headers.cookie);
|
|
1504
|
+
const cookie = this.dashboardCookieToken(req.headers.cookie);
|
|
1505
|
+
if (cookie === null) {
|
|
1506
|
+
if (presented)
|
|
1507
|
+
this.auditDashboardRefusal(req, 'unauthenticated');
|
|
1508
|
+
json(res, 401, { error: 'Unauthorised: a valid client token is required.' });
|
|
1509
|
+
return;
|
|
1510
|
+
}
|
|
1511
|
+
if (!this.isSameOriginMutation(req)) {
|
|
1512
|
+
this.auditDashboardRefusal(req, this.mutationRefusalReason(req));
|
|
1513
|
+
json(res, 403, { error: 'Forbidden.' });
|
|
1514
|
+
return;
|
|
1515
|
+
}
|
|
1516
|
+
// Only `application/json`, with optional parameters such as `charset`.
|
|
1517
|
+
// A missing header and `application/jsonp` are both refused: the launch
|
|
1518
|
+
// body is JSON and nothing else.
|
|
1519
|
+
const mediaType = (headerOne(req, 'content-type') ?? '').split(';', 1)[0]?.trim().toLowerCase() ?? '';
|
|
1520
|
+
if (mediaType !== 'application/json') {
|
|
1521
|
+
this.auditDashboardRefusal(req, 'content-type');
|
|
1522
|
+
json(res, 415, { error: 'The launch body must be JSON (application/json).' });
|
|
1523
|
+
return;
|
|
1524
|
+
}
|
|
1525
|
+
if (!this.tokens.acceptsDashboardProof(headerOne(req, 'x-shellpuppet-csrf'))) {
|
|
1526
|
+
this.auditDashboardRefusal(req, 'proof');
|
|
1527
|
+
json(res, 403, { error: 'Forbidden.' });
|
|
1528
|
+
return;
|
|
1529
|
+
}
|
|
1530
|
+
let body;
|
|
1531
|
+
try {
|
|
1532
|
+
body = await readBody(req);
|
|
1533
|
+
}
|
|
1534
|
+
catch (error) {
|
|
1535
|
+
if (error instanceof RequestBodyTooLargeError) {
|
|
1536
|
+
this.auditDashboardRefusal(req, 'body-size');
|
|
1537
|
+
json(res, 413, { error: error.message });
|
|
1538
|
+
return;
|
|
1539
|
+
}
|
|
1540
|
+
if (error instanceof Error && error.message.startsWith('Request body')) {
|
|
1541
|
+
this.auditDashboardRefusal(req, 'body');
|
|
1542
|
+
json(res, 400, { error: error.message });
|
|
1543
|
+
return;
|
|
1544
|
+
}
|
|
1545
|
+
throw error;
|
|
1546
|
+
}
|
|
1547
|
+
const profileName = asString(body['profile']);
|
|
1548
|
+
if (profileName === undefined || profileName === '') {
|
|
1549
|
+
json(res, 400, { error: 'profile (string) is required.' });
|
|
1550
|
+
return;
|
|
1551
|
+
}
|
|
1552
|
+
for (const key of Object.keys(body)) {
|
|
1553
|
+
if (key !== 'profile' && key !== 'folder' && key !== 'rootIndex' && key !== 'folderPath') {
|
|
1554
|
+
this.auditDashboardRefusal(req, 'body');
|
|
1555
|
+
json(res, 400, {
|
|
1556
|
+
error: `The launch body may name only profile, folder, rootIndex and folderPath: "${key}" is not accepted. ` +
|
|
1557
|
+
'A command, arguments and environment value come from the profile.',
|
|
1558
|
+
});
|
|
1559
|
+
return;
|
|
1560
|
+
}
|
|
1561
|
+
}
|
|
1562
|
+
const profile = this.launchProfiles.profiles.find((entry) => entry.name === profileName);
|
|
1563
|
+
if (profile === undefined) {
|
|
1564
|
+
json(res, 400, { error: `No such launch profile: ${profileName}` });
|
|
1565
|
+
return;
|
|
1566
|
+
}
|
|
1567
|
+
const folderName = body['folder'];
|
|
1568
|
+
const rootIndex = body['rootIndex'];
|
|
1569
|
+
const freePath = body['folderPath'];
|
|
1570
|
+
let folder;
|
|
1571
|
+
let rootCwd;
|
|
1572
|
+
let freeCwd;
|
|
1573
|
+
if (profile.askCwd) {
|
|
1574
|
+
if (freePath !== undefined) {
|
|
1575
|
+
if (!profile.anyFolder || folderName !== undefined || rootIndex !== undefined) {
|
|
1576
|
+
this.auditDashboardRefusal(req, 'body');
|
|
1577
|
+
json(res, 400, { error: 'This profile does not accept that folder path.' });
|
|
1578
|
+
return;
|
|
1579
|
+
}
|
|
1580
|
+
const choice = resolveAnyFolder(freePath);
|
|
1581
|
+
if ('error' in choice) {
|
|
1582
|
+
this.auditDashboardRefusal(req, 'body');
|
|
1583
|
+
json(res, 400, { error: choice.error });
|
|
1584
|
+
return;
|
|
1585
|
+
}
|
|
1586
|
+
freeCwd = choice.cwd;
|
|
1587
|
+
}
|
|
1588
|
+
else {
|
|
1589
|
+
if (folderName === undefined) {
|
|
1590
|
+
json(res, 400, { error: `folder (string) is required for profile "${profileName}".` });
|
|
1591
|
+
return;
|
|
1592
|
+
}
|
|
1593
|
+
if (typeof folderName !== 'string') {
|
|
1594
|
+
json(res, 400, { error: 'folder must be a string.' });
|
|
1595
|
+
return;
|
|
1596
|
+
}
|
|
1597
|
+
if (rootIndex !== undefined) {
|
|
1598
|
+
const choice = await resolveRootFolder(profile.folderRoots.map((root) => path.resolve(os.homedir(), root)), rootIndex, folderName);
|
|
1599
|
+
if ('error' in choice) {
|
|
1600
|
+
this.auditDashboardRefusal(req, 'body');
|
|
1601
|
+
json(res, 400, { error: choice.error });
|
|
1602
|
+
return;
|
|
1603
|
+
}
|
|
1604
|
+
rootCwd = choice.cwd;
|
|
1605
|
+
}
|
|
1606
|
+
else {
|
|
1607
|
+
folder = profile.folders.find((entry) => entry.name === folderName);
|
|
1608
|
+
if (folder === undefined) {
|
|
1609
|
+
this.auditDashboardRefusal(req, 'body');
|
|
1610
|
+
json(res, 400, { error: `No such folder for profile "${profileName}": ${folderName}` });
|
|
1611
|
+
return;
|
|
1612
|
+
}
|
|
1613
|
+
}
|
|
1614
|
+
}
|
|
1615
|
+
}
|
|
1616
|
+
else if (folderName !== undefined || rootIndex !== undefined || freePath !== undefined) {
|
|
1617
|
+
this.auditDashboardRefusal(req, 'body');
|
|
1618
|
+
json(res, 400, {
|
|
1619
|
+
error: `Profile "${profileName}" uses a fixed working directory and does not accept a folder.`,
|
|
1620
|
+
});
|
|
1621
|
+
return;
|
|
1622
|
+
}
|
|
1623
|
+
const resolved = freeCwd !== undefined ? { cwd: freeCwd } : rootCwd === undefined ? this.resolveLaunchCwd(profile, folder) : { cwd: rootCwd };
|
|
1624
|
+
if ('error' in resolved) {
|
|
1625
|
+
this.auditDashboardRefusal(req, 'body');
|
|
1626
|
+
json(res, 400, { error: resolved.error });
|
|
1627
|
+
return;
|
|
1628
|
+
}
|
|
1629
|
+
// Global policy runs first, then the profile's own deny and allow lists.
|
|
1630
|
+
// Both see the real command line, before any Windows shell wrap.
|
|
1631
|
+
const globalDecision = evaluateCommand(this.compiledPolicy, profile.command, profile.args);
|
|
1632
|
+
if (!globalDecision.allowed) {
|
|
1633
|
+
this.auditDashboardRefusal(req, 'policy');
|
|
1634
|
+
json(res, 403, { error: globalDecision.reason ?? 'Command refused by policy.' });
|
|
1635
|
+
return;
|
|
1636
|
+
}
|
|
1637
|
+
if (profile.policy !== undefined) {
|
|
1638
|
+
const ownDecision = evaluateCommand(compileProfilePolicy(profile.policy), profile.command, profile.args);
|
|
1639
|
+
if (!ownDecision.allowed) {
|
|
1640
|
+
this.auditDashboardRefusal(req, 'policy');
|
|
1641
|
+
json(res, 403, { error: ownDecision.reason ?? 'Command refused by policy.' });
|
|
1642
|
+
return;
|
|
1643
|
+
}
|
|
1644
|
+
}
|
|
1645
|
+
// Resolve the command to the file that will run before anything starts.
|
|
1646
|
+
// Policy and the page keep the written command; the spawn gets the
|
|
1647
|
+
// absolute path, so the folder's contents cannot choose the program.
|
|
1648
|
+
const resolvedCommand = resolveLaunchCommand(profile.command, resolved.cwd);
|
|
1649
|
+
if ('error' in resolvedCommand) {
|
|
1650
|
+
this.auditDashboardRefusal(req, 'command');
|
|
1651
|
+
json(res, 400, {
|
|
1652
|
+
error: `Profile "${profile.name}" cannot be started: ${resolvedCommand.error}`,
|
|
1653
|
+
});
|
|
1654
|
+
return;
|
|
1655
|
+
}
|
|
1656
|
+
const now = this.now();
|
|
1657
|
+
this.pruneLaunchTimes(now);
|
|
1658
|
+
if (this.launchTimes.length >= 8) {
|
|
1659
|
+
this.auditDashboardRefusal(req, 'rate');
|
|
1660
|
+
json(res, 429, {
|
|
1661
|
+
error: 'Dashboard launch rate reached (8 in 60 seconds). Wait before starting another profile.',
|
|
1662
|
+
});
|
|
1663
|
+
return;
|
|
1664
|
+
}
|
|
1665
|
+
const live = this.manager.liveCount();
|
|
1666
|
+
if (this.compiledPolicy.maxSessions === undefined) {
|
|
1667
|
+
if (live >= 32) {
|
|
1668
|
+
this.auditDashboardRefusal(req, 'limit');
|
|
1669
|
+
json(res, 403, {
|
|
1670
|
+
error: 'Session limit reached (32 live sessions). Kill a session or set policy.maxSessions.',
|
|
1671
|
+
});
|
|
1672
|
+
return;
|
|
1673
|
+
}
|
|
1674
|
+
}
|
|
1675
|
+
else {
|
|
1676
|
+
const capacity = checkSessionCapacity(this.compiledPolicy, live);
|
|
1677
|
+
if (!capacity.allowed) {
|
|
1678
|
+
this.auditDashboardRefusal(req, 'limit');
|
|
1679
|
+
json(res, 403, { error: capacity.reason ?? 'Session limit reached.' });
|
|
1680
|
+
return;
|
|
1681
|
+
}
|
|
1682
|
+
}
|
|
1683
|
+
const { env, copied } = copyDaemonEnv(profile.envFromDaemon, this.daemonEnv);
|
|
1684
|
+
const envNames = Object.keys(env);
|
|
1685
|
+
const folderLabel = freeCwd !== undefined ? freeCwd : folder?.name ?? (rootCwd !== undefined ? folderName : undefined);
|
|
1686
|
+
const options = {
|
|
1687
|
+
command: resolvedCommand.file,
|
|
1688
|
+
args: [...profile.args],
|
|
1689
|
+
cwd: resolved.cwd,
|
|
1690
|
+
...(profile.shell !== undefined ? { shell: profile.shell } : {}),
|
|
1691
|
+
...(profile.agent !== undefined ? { agent: profile.agent } : {}),
|
|
1692
|
+
...(profile.readyText !== undefined ? { readyText: profile.readyText } : {}),
|
|
1693
|
+
...(profile.readyQuiet !== undefined ? { readyQuiet: profile.readyQuiet } : {}),
|
|
1694
|
+
// The written command stays the session's label, as it was before the
|
|
1695
|
+
// path was resolved: the page shows the profile, not a machine path.
|
|
1696
|
+
...(profile.label !== undefined
|
|
1697
|
+
? { label: expandProfileText(profile.label, profile.name, folderLabel) }
|
|
1698
|
+
: { label: profile.command }),
|
|
1699
|
+
...(profile.purpose !== undefined
|
|
1700
|
+
? { purpose: expandProfileText(profile.purpose, profile.name, folderLabel) }
|
|
1701
|
+
: {}),
|
|
1702
|
+
...(envNames.length > 0 ? { env } : {}),
|
|
1703
|
+
// The audit actor, not a caller-declared identity: the dashboard page
|
|
1704
|
+
// has no client environment and no other way to name itself.
|
|
1705
|
+
startedBy: 'dashboard',
|
|
1706
|
+
};
|
|
1707
|
+
// Keep the path check adjacent to spawn. A local writer can still replace
|
|
1708
|
+
// a directory after this check, as the security model records.
|
|
1709
|
+
if (rootCwd !== undefined) {
|
|
1710
|
+
const latest = await resolveRootFolder(profile.folderRoots.map((root) => path.resolve(os.homedir(), root)), rootIndex, folderName);
|
|
1711
|
+
if ('error' in latest || latest.cwd !== rootCwd) {
|
|
1712
|
+
this.auditDashboardRefusal(req, 'body');
|
|
1713
|
+
json(res, 400, { error: 'Folder is no longer available from this root.' });
|
|
1714
|
+
return;
|
|
1715
|
+
}
|
|
1716
|
+
}
|
|
1717
|
+
if (freeCwd !== undefined) {
|
|
1718
|
+
const latest = resolveAnyFolder(freePath);
|
|
1719
|
+
if ('error' in latest || latest.cwd !== freeCwd) {
|
|
1720
|
+
this.auditDashboardRefusal(req, 'body');
|
|
1721
|
+
json(res, 400, { error: 'The chosen folder is no longer available.' });
|
|
1722
|
+
return;
|
|
1723
|
+
}
|
|
1724
|
+
}
|
|
1725
|
+
let session;
|
|
1726
|
+
try {
|
|
1727
|
+
session = (this.options.dashboardSessionFactory ?? ((value) => this.manager.create(value)))(options);
|
|
1728
|
+
}
|
|
1729
|
+
catch (error) {
|
|
1730
|
+
if (error instanceof PolicyViolationError) {
|
|
1731
|
+
this.auditDashboardRefusal(req, 'policy');
|
|
1732
|
+
json(res, 403, { error: error.message });
|
|
1733
|
+
return;
|
|
1734
|
+
}
|
|
1735
|
+
if (error instanceof CommandNotFoundError) {
|
|
1736
|
+
json(res, 400, { error: error.message });
|
|
1737
|
+
return;
|
|
1738
|
+
}
|
|
1739
|
+
if (error instanceof WindowsWithoutConPTYError) {
|
|
1740
|
+
json(res, 400, { error: error.message });
|
|
1741
|
+
return;
|
|
1742
|
+
}
|
|
1743
|
+
this.logger.error('dashboard session start failed', {
|
|
1744
|
+
error: error instanceof Error ? (error.stack ?? String(error)) : String(error),
|
|
1745
|
+
});
|
|
1746
|
+
if (error instanceof NativePtyUnavailableError) {
|
|
1747
|
+
json(res, 500, { error: error.message });
|
|
1748
|
+
return;
|
|
1749
|
+
}
|
|
1750
|
+
json(res, 500, { error: `Failed to start session: ${String(error)}` });
|
|
1751
|
+
return;
|
|
1752
|
+
}
|
|
1753
|
+
// Counted the moment the launch is accepted, before the start contract's
|
|
1754
|
+
// wait: the rate check above and this record must sit in the same
|
|
1755
|
+
// synchronous stretch, or twelve launches fired together would all pass
|
|
1756
|
+
// the check before any of them was counted.
|
|
1757
|
+
this.launchTimes.push(now);
|
|
1758
|
+
// The same start contract as `POST /sessions`: the dashboard's pane is a
|
|
1759
|
+
// session only once its program exists, and a start that ends before any
|
|
1760
|
+
// program did fails as 1.1.0's spawn did, leaving nothing in the grid.
|
|
1761
|
+
const startedSession = await this.programStarted(session, options, res, 'dashboard session start failed');
|
|
1762
|
+
if (startedSession === null)
|
|
1763
|
+
return;
|
|
1764
|
+
session = startedSession;
|
|
1765
|
+
// A launch is an API call: the idle timer counts from it, so a session
|
|
1766
|
+
// that has just started is not reaped sooner than `idleMinutes` allows.
|
|
1767
|
+
this.lastActivity = Date.now();
|
|
1768
|
+
this.sessionFeed.add(this.summaryWithPrompt(session.summary()));
|
|
1769
|
+
session.onExit(() => {
|
|
1770
|
+
this.geometryController.delete(session.id);
|
|
1771
|
+
this.dashboardGeometryOwner.delete(session.id);
|
|
1772
|
+
this.updateFeedSession(session.id);
|
|
1773
|
+
});
|
|
1774
|
+
session.onReady(() => this.updateFeedSession(session.id));
|
|
1775
|
+
// The profile name and the written command line, the file that was
|
|
1776
|
+
// actually resolved and started, and copied variable names or "all".
|
|
1777
|
+
// Never a value.
|
|
1778
|
+
this.audit.record('dashboard', 'start', session.id, {
|
|
1779
|
+
profile: profile.name,
|
|
1780
|
+
command: profile.command,
|
|
1781
|
+
args: profile.args,
|
|
1782
|
+
resolvedCommand: resolvedCommand.file,
|
|
1783
|
+
...(profile.envFromDaemon === 'all'
|
|
1784
|
+
? { envFromDaemon: 'all' }
|
|
1785
|
+
: copied.length > 0 ? { envFromDaemon: copied } : {}),
|
|
1786
|
+
...(folderLabel !== undefined ? { folder: folderLabel } : {}),
|
|
1787
|
+
...(rootCwd !== undefined ? { rootIndex } : {}),
|
|
1788
|
+
...(freeCwd !== undefined ? { folderPath: freeCwd } : {}),
|
|
1789
|
+
...(session.label !== '' ? { label: session.label } : {}),
|
|
1790
|
+
});
|
|
1791
|
+
// No viewer window and no viewer grant: the dashboard page is the
|
|
1792
|
+
// window, and it acts on the profile's `open` value.
|
|
1793
|
+
json(res, 200, {
|
|
1794
|
+
id: session.id,
|
|
1795
|
+
open: profile.open,
|
|
1796
|
+
profile: profile.name,
|
|
1797
|
+
...(profile.envFromDaemon === 'all'
|
|
1798
|
+
? { envFromDaemon: 'all' }
|
|
1799
|
+
: copied.length > 0 ? { envFromDaemon: [...copied] } : {}),
|
|
1800
|
+
});
|
|
1801
|
+
}
|
|
1802
|
+
/**
|
|
1803
|
+
* `DELETE /sessions/<id>` for the dashboard cookie. Origin, Fetch Metadata
|
|
1804
|
+
* and the document proof are the same checks as launch. One call kills the
|
|
1805
|
+
* session and audits actor `dashboard`. A client token never reaches here.
|
|
1806
|
+
*/
|
|
1807
|
+
async handleDashboardKill(req, res, id) {
|
|
1808
|
+
const presented = this.dashboardCookiePresented(req.headers.cookie);
|
|
1809
|
+
const cookie = this.dashboardCookieToken(req.headers.cookie);
|
|
1810
|
+
if (cookie === null) {
|
|
1811
|
+
if (presented)
|
|
1812
|
+
this.auditDashboardRefusal(req, 'unauthenticated');
|
|
1813
|
+
json(res, 401, { error: 'Unauthorised: a valid client token is required.' });
|
|
1814
|
+
return;
|
|
1815
|
+
}
|
|
1816
|
+
if (!this.isSameOriginMutation(req)) {
|
|
1817
|
+
this.auditDashboardRefusal(req, this.mutationRefusalReason(req));
|
|
1818
|
+
json(res, 403, { error: 'Forbidden.' });
|
|
1819
|
+
return;
|
|
1820
|
+
}
|
|
1821
|
+
if (!this.tokens.acceptsDashboardProof(headerOne(req, 'x-shellpuppet-csrf'))) {
|
|
1822
|
+
this.auditDashboardRefusal(req, 'proof');
|
|
1823
|
+
json(res, 403, { error: 'Forbidden.' });
|
|
1824
|
+
return;
|
|
1825
|
+
}
|
|
1826
|
+
// Drain the body so a keep-alive connection is not left holding it. The
|
|
1827
|
+
// kill takes nothing from the body: a command there cannot change it.
|
|
1828
|
+
try {
|
|
1829
|
+
await readBody(req);
|
|
1830
|
+
}
|
|
1831
|
+
catch (error) {
|
|
1832
|
+
if (error instanceof RequestBodyTooLargeError) {
|
|
1833
|
+
this.auditDashboardRefusal(req, 'body-size');
|
|
1834
|
+
json(res, 413, { error: error.message });
|
|
1835
|
+
return;
|
|
684
1836
|
}
|
|
685
|
-
|
|
686
|
-
|
|
1837
|
+
if (error instanceof Error && error.message.startsWith('Request body')) {
|
|
1838
|
+
this.auditDashboardRefusal(req, 'body');
|
|
1839
|
+
json(res, 400, { error: error.message });
|
|
1840
|
+
return;
|
|
687
1841
|
}
|
|
1842
|
+
throw error;
|
|
688
1843
|
}
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
1844
|
+
if (this.manager.get(id) === undefined) {
|
|
1845
|
+
json(res, 404, { error: `No such session: ${id}` });
|
|
1846
|
+
return;
|
|
1847
|
+
}
|
|
1848
|
+
this.lastActivity = Date.now();
|
|
1849
|
+
this.audit.record('dashboard', 'kill', id);
|
|
1850
|
+
await this.manager.kill(id);
|
|
1851
|
+
this.dropSessionArtifacts(id);
|
|
1852
|
+
json(res, 200, { ok: true, killed: id });
|
|
693
1853
|
}
|
|
694
1854
|
/**
|
|
695
|
-
*
|
|
696
|
-
*
|
|
1855
|
+
* Why a `/dashboard/events` upgrade is refused, or null when it may attach.
|
|
1856
|
+
* The client token on the query is not a way in. The proof is the
|
|
1857
|
+
* subprotocol, not `X-ShellPuppet-CSRF`.
|
|
697
1858
|
*/
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
1859
|
+
dashboardUpgradeRefusal(req) {
|
|
1860
|
+
if (this.dashboardCookieToken(req.headers.cookie) === null) {
|
|
1861
|
+
return { code: 401, reason: 'Unauthorized', audit: 'unauthenticated' };
|
|
1862
|
+
}
|
|
1863
|
+
if (!this.originMatchesRequest(req)) {
|
|
1864
|
+
return { code: 403, reason: 'Forbidden', audit: 'origin' };
|
|
1865
|
+
}
|
|
1866
|
+
// Chromium's WebSocket handshake omits both Fetch Metadata headers. The
|
|
1867
|
+
// exact Origin and document proof above still bind it to this page. When
|
|
1868
|
+
// either header is present, require the complete same-origin pair.
|
|
1869
|
+
const site = headerOne(req, 'sec-fetch-site');
|
|
1870
|
+
const mode = headerOne(req, 'sec-fetch-mode');
|
|
1871
|
+
if (!((site === 'same-origin' && mode === 'websocket') ||
|
|
1872
|
+
(site === undefined && mode === undefined))) {
|
|
1873
|
+
return { code: 403, reason: 'Forbidden', audit: 'fetch-site' };
|
|
1874
|
+
}
|
|
1875
|
+
const accepted = offeredProtocols(req).some((protocol) => {
|
|
1876
|
+
const proof = dashboardProofFromProtocol(protocol);
|
|
1877
|
+
return proof !== null && this.tokens.acceptsDashboardProof(proof);
|
|
1878
|
+
});
|
|
1879
|
+
if (!accepted)
|
|
1880
|
+
return { code: 403, reason: 'Forbidden', audit: 'proof' };
|
|
1881
|
+
return null;
|
|
703
1882
|
}
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
1883
|
+
/**
|
|
1884
|
+
* Select `sp-csrf.<proof>` when this upgrade's credential is the dashboard
|
|
1885
|
+
* cookie: the dashboard feed, or a session stream the client token did not
|
|
1886
|
+
* take. The echo names that credential. A viewer or client socket, including
|
|
1887
|
+
* a client token that also carries the cookie and offers a live proof,
|
|
1888
|
+
* selects none. Returning false leaves the upgrade with none selected.
|
|
1889
|
+
*/
|
|
1890
|
+
dashboardProtocol(protocols, request) {
|
|
1891
|
+
let url;
|
|
1892
|
+
try {
|
|
1893
|
+
url = new URL(request.url ?? '/', 'http://127.0.0.1');
|
|
1894
|
+
}
|
|
1895
|
+
catch {
|
|
707
1896
|
return false;
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
originAllowed(origin) {
|
|
713
|
-
if (origin === undefined)
|
|
714
|
-
return true; // non-browser clients send none
|
|
715
|
-
if (this.portValue === null)
|
|
1897
|
+
}
|
|
1898
|
+
const segments = url.pathname.split('/').filter((part) => part !== '');
|
|
1899
|
+
const sessionStream = segments.length === 3 && segments[0] === 'sessions' && segments[2] === 'stream';
|
|
1900
|
+
if (url.pathname !== '/dashboard/events' && !sessionStream)
|
|
716
1901
|
return false;
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
1902
|
+
// Same preference as sessionStreamDecision: a live client token opens a
|
|
1903
|
+
// client socket, so the echoed protocol must not say this is the dashboard.
|
|
1904
|
+
if (sessionStream && this.tokens.verify(url.searchParams.get('token'))?.kind === 'client') {
|
|
1905
|
+
return false;
|
|
1906
|
+
}
|
|
1907
|
+
if (this.dashboardCookieToken(request.headers.cookie) === null)
|
|
1908
|
+
return false;
|
|
1909
|
+
for (const protocol of protocols) {
|
|
1910
|
+
const proof = dashboardProofFromProtocol(protocol);
|
|
1911
|
+
if (proof !== null && this.tokens.acceptsDashboardProof(proof))
|
|
1912
|
+
return protocol;
|
|
1913
|
+
}
|
|
1914
|
+
return false;
|
|
1915
|
+
}
|
|
1916
|
+
/**
|
|
1917
|
+
* Who may open `/sessions/<id>/stream`, or why not.
|
|
1918
|
+
*
|
|
1919
|
+
* A client token and a viewer cookie for this session keep the check they
|
|
1920
|
+
* already have: a missing Origin is allowed, and a foreign one is refused.
|
|
1921
|
+
* The dashboard cookie is a third way in, and only with the events
|
|
1922
|
+
* upgrade's rules: a live `sp-csrf` subprotocol, a matching Origin, and
|
|
1923
|
+
* same-origin Fetch Metadata. A header is not the proof. A viewer cookie,
|
|
1924
|
+
* including a read-only one, is never treated as the dashboard credential.
|
|
1925
|
+
* When both are present and the proof is live, the dashboard cookie is the
|
|
1926
|
+
* one that opens the socket, so a read-only viewer cookie in the same jar
|
|
1927
|
+
* does not mask it. When the proof is missing, a viewer cookie for this
|
|
1928
|
+
* session still opens the socket on its own rules.
|
|
1929
|
+
*/
|
|
1930
|
+
sessionStreamDecision(req, url, sessionId) {
|
|
1931
|
+
const client = this.tokens.verify(url.searchParams.get('token'));
|
|
1932
|
+
if (client?.kind === 'client') {
|
|
1933
|
+
if (!this.originAllowed(req.headers.origin)) {
|
|
1934
|
+
return { ok: false, code: 403, reason: 'Forbidden', audit: null };
|
|
1935
|
+
}
|
|
1936
|
+
return { ok: true, credential: { kind: 'client', readOnly: false } };
|
|
1937
|
+
}
|
|
1938
|
+
const dashboard = this.dashboardUpgradeRefusal(req);
|
|
1939
|
+
if (dashboard === null) {
|
|
1940
|
+
return { ok: true, credential: { kind: 'dashboard', readOnly: false } };
|
|
1941
|
+
}
|
|
1942
|
+
const viewer = cookieValues(req.headers.cookie, VIEWER_COOKIE)
|
|
1943
|
+
.map((value) => ({ value, credential: this.tokens.verifyStreamToken(value) }))
|
|
1944
|
+
.find((found) => found.credential?.kind === 'viewer' && found.credential.sessionId === sessionId);
|
|
1945
|
+
if (viewer?.credential?.kind === 'viewer') {
|
|
1946
|
+
if (!this.originAllowed(req.headers.origin)) {
|
|
1947
|
+
return { ok: false, code: 403, reason: 'Forbidden', audit: null };
|
|
1948
|
+
}
|
|
1949
|
+
const frozen = [...this.captureSnapshots.values()]
|
|
1950
|
+
.find((snapshot) => snapshot.streamToken === viewer.value);
|
|
1951
|
+
return {
|
|
1952
|
+
ok: true,
|
|
1953
|
+
credential: { kind: 'viewer', readOnly: viewer.credential.readOnly },
|
|
1954
|
+
...(frozen === undefined ? {} : { frozen }),
|
|
1955
|
+
};
|
|
1956
|
+
}
|
|
1957
|
+
// The dashboard cookie was offered and did not authenticate. Say why,
|
|
1958
|
+
// including a planted value. A stream with no dashboard cookie and no
|
|
1959
|
+
// other credential is the ordinary 401, and it is not a dashboard refusal.
|
|
1960
|
+
if (this.dashboardCookiePresented(req.headers.cookie)) {
|
|
1961
|
+
return { ok: false, code: dashboard.code, reason: dashboard.reason, audit: dashboard.audit };
|
|
1962
|
+
}
|
|
1963
|
+
return { ok: false, code: 401, reason: 'Unauthorized', audit: null };
|
|
720
1964
|
}
|
|
721
1965
|
async handleRequest(req, res) {
|
|
1966
|
+
res.setHeader('Referrer-Policy', 'no-referrer');
|
|
722
1967
|
// DNS-rebinding defence (design §4.2): a browser on any website can make
|
|
723
1968
|
// requests reach a loopback port; the Host header gives the rebind away.
|
|
724
1969
|
if (!this.hostAllowed(req.headers.host)) {
|
|
1970
|
+
if (pathOnly(req.url).startsWith('/dashboard'))
|
|
1971
|
+
this.auditDashboardRefusal(req, 'host');
|
|
725
1972
|
json(res, 403, { error: 'Forbidden: unexpected Host header.' });
|
|
726
1973
|
return;
|
|
727
1974
|
}
|
|
728
1975
|
const url = new URL(req.url ?? '/', `http://127.0.0.1:${String(this.portValue ?? 0)}`);
|
|
729
1976
|
const segments = url.pathname.split('/').filter((s) => s !== '');
|
|
730
1977
|
// Unauthenticated by design (§4.1): clients must be able to poll before
|
|
731
|
-
// the token file settles
|
|
1978
|
+
// the token file settles. The instance id is an identity, not a secret.
|
|
732
1979
|
if (req.method === 'GET' && url.pathname === '/health') {
|
|
733
|
-
json(res, 200, { ok: true, version: this.version, pid: process.pid });
|
|
1980
|
+
json(res, 200, { ok: true, version: this.version, pid: process.pid, instanceId: this.instanceId });
|
|
734
1981
|
return;
|
|
735
1982
|
}
|
|
736
1983
|
// The viewer page itself is served without auth, and must stay that way:
|
|
@@ -754,10 +2001,13 @@ export class Daemon {
|
|
|
754
2001
|
// without it. Scripts stay strict under `default-src 'self'`: inline
|
|
755
2002
|
// styles cannot execute code, and terminal output never reaches the
|
|
756
2003
|
// DOM as markup (xterm renders it as text).
|
|
757
|
-
'content-security-policy':
|
|
2004
|
+
'content-security-policy': PAGE_CSP,
|
|
758
2005
|
};
|
|
759
2006
|
const redeemed = this.tokens.redeemViewerGrant(url.searchParams.get('vt'));
|
|
760
2007
|
if (redeemed !== null) {
|
|
2008
|
+
const frozen = this.captureSnapshots.get(url.searchParams.get('vt') ?? '');
|
|
2009
|
+
if (frozen !== undefined)
|
|
2010
|
+
frozen.streamToken = redeemed.streamToken;
|
|
761
2011
|
headers['set-cookie'] = viewerCookie(redeemed.sessionId, redeemed.streamToken);
|
|
762
2012
|
this.audit.record('viewer', 'grant-redeem', redeemed.sessionId, {
|
|
763
2013
|
readOnly: redeemed.readOnly,
|
|
@@ -799,11 +2049,56 @@ export class Daemon {
|
|
|
799
2049
|
return;
|
|
800
2050
|
}
|
|
801
2051
|
}
|
|
2052
|
+
// The dashboard page is served without a client token. A live grant is
|
|
2053
|
+
// redeemed only on an accepted document navigation. Anything else gets
|
|
2054
|
+
// the page with no cookie and no proof, unless Fetch Metadata forbids it.
|
|
2055
|
+
if ((req.method === 'GET' || req.method === 'HEAD') && url.pathname === '/dashboard') {
|
|
2056
|
+
this.handleDashboardPage(req, res, url);
|
|
2057
|
+
return;
|
|
2058
|
+
}
|
|
2059
|
+
// The two launch routes are dashboard-cookie routes. They are checked
|
|
2060
|
+
// before the client token so a bearer token cannot take the profile list
|
|
2061
|
+
// or the launch path as an ordinary API call.
|
|
2062
|
+
if (req.method === 'GET' && url.pathname === '/dashboard/profiles') {
|
|
2063
|
+
await this.serveDashboardProfiles(req, res);
|
|
2064
|
+
return;
|
|
2065
|
+
}
|
|
2066
|
+
if (req.method === 'POST' && url.pathname === '/dashboard/launch') {
|
|
2067
|
+
await this.handleDashboardLaunch(req, res);
|
|
2068
|
+
return;
|
|
2069
|
+
}
|
|
2070
|
+
if (req.method === 'POST' && url.pathname === '/dashboard/folder-picker') {
|
|
2071
|
+
const handler = this.handleDashboardFolderPicker(req, res);
|
|
2072
|
+
this.folderPickerHandlers.add(handler);
|
|
2073
|
+
try {
|
|
2074
|
+
await handler;
|
|
2075
|
+
}
|
|
2076
|
+
finally {
|
|
2077
|
+
this.folderPickerHandlers.delete(handler);
|
|
2078
|
+
}
|
|
2079
|
+
return;
|
|
2080
|
+
}
|
|
802
2081
|
const auth = this.tokens.verify(bearerToken(req.headers.authorization));
|
|
803
2082
|
if (auth === null || auth.kind !== 'client') {
|
|
804
|
-
//
|
|
805
|
-
//
|
|
806
|
-
//
|
|
2083
|
+
// `GET /sessions` is the HTTP read the dashboard cookie may make.
|
|
2084
|
+
// `DELETE /sessions/<id>` is the kill: the same origin, Fetch Metadata
|
|
2085
|
+
// and document proof as launch. A bearer token, handled above, does
|
|
2086
|
+
// not reach this branch, so a client-token kill keeps its own actor.
|
|
2087
|
+
if (req.method === 'GET' && segments.length === 1 && segments[0] === 'sessions') {
|
|
2088
|
+
this.serveDashboardSessionList(req, res, url);
|
|
2089
|
+
return;
|
|
2090
|
+
}
|
|
2091
|
+
if (req.method === 'DELETE' && segments.length === 2 && segments[0] === 'sessions') {
|
|
2092
|
+
await this.handleDashboardKill(req, res, segments[1] ?? '');
|
|
2093
|
+
return;
|
|
2094
|
+
}
|
|
2095
|
+
// A dashboard cookie on any other route, and any other dashboard path,
|
|
2096
|
+
// is a refusal. An ordinary missing client token is not: that 401 is
|
|
2097
|
+
// what every unauthenticated API call already gets.
|
|
2098
|
+
if (this.dashboardCookiePresented(req.headers.cookie) ||
|
|
2099
|
+
url.pathname.startsWith('/dashboard')) {
|
|
2100
|
+
this.auditDashboardRefusal(req, 'unauthenticated');
|
|
2101
|
+
}
|
|
807
2102
|
json(res, 401, { error: 'Unauthorised: a valid client token is required.' });
|
|
808
2103
|
return;
|
|
809
2104
|
}
|
|
@@ -841,18 +2136,30 @@ export class Daemon {
|
|
|
841
2136
|
json(res, 200, this.environmentReport());
|
|
842
2137
|
return;
|
|
843
2138
|
}
|
|
2139
|
+
if (req.method === 'POST' && segments[0] === 'dashboard' && segments[1] === 'open' && segments.length === 2) {
|
|
2140
|
+
await this.handleDashboardOpen(req, res, actor);
|
|
2141
|
+
return;
|
|
2142
|
+
}
|
|
2143
|
+
if (req.method === 'POST' && segments[0] === 'desktop' && segments[1] === 'open' && segments.length === 2) {
|
|
2144
|
+
await this.handleDesktopOpen(req, res, actor);
|
|
2145
|
+
return;
|
|
2146
|
+
}
|
|
844
2147
|
if (segments[0] !== 'sessions') {
|
|
845
2148
|
json(res, 404, { error: 'Not found.', path: url.pathname });
|
|
846
2149
|
return;
|
|
847
2150
|
}
|
|
848
2151
|
if (req.method === 'GET' && segments.length === 1) {
|
|
849
|
-
|
|
2152
|
+
this.writeSessionList(res, url);
|
|
850
2153
|
return;
|
|
851
2154
|
}
|
|
852
2155
|
if (req.method === 'POST' && segments.length === 1) {
|
|
853
2156
|
await this.handleStart(req, res, actor);
|
|
854
2157
|
return;
|
|
855
2158
|
}
|
|
2159
|
+
if (req.method === 'GET' && segments.length === 2 && segments[1] === 'wait') {
|
|
2160
|
+
await this.waitAcrossSessions(res, url);
|
|
2161
|
+
return;
|
|
2162
|
+
}
|
|
856
2163
|
const id = segments[1] ?? '';
|
|
857
2164
|
const session = this.manager.get(id);
|
|
858
2165
|
if (session === undefined) {
|
|
@@ -890,6 +2197,14 @@ export class Daemon {
|
|
|
890
2197
|
// Also the faithful way to illustrate documentation.
|
|
891
2198
|
if (req.method === 'POST' && action === 'screenshot') {
|
|
892
2199
|
const body = await readBody(req);
|
|
2200
|
+
if (body['hideReasoning'] !== undefined && typeof body['hideReasoning'] !== 'boolean') {
|
|
2201
|
+
json(res, 400, { error: BAD_HIDE_REASONING });
|
|
2202
|
+
return;
|
|
2203
|
+
}
|
|
2204
|
+
const hide = body['hideReasoning'] === true;
|
|
2205
|
+
const signature = hide ? this.readerFor(session, res) : null;
|
|
2206
|
+
if (hide && signature === null)
|
|
2207
|
+
return;
|
|
893
2208
|
// Absent means the default; present and not a number is a mistake to
|
|
894
2209
|
// report, not to paper over with the default.
|
|
895
2210
|
const width = body['width'] === undefined ? CAPTURE_WIDTH : asNumber(body['width']);
|
|
@@ -920,7 +2235,7 @@ export class Daemon {
|
|
|
920
2235
|
});
|
|
921
2236
|
return;
|
|
922
2237
|
}
|
|
923
|
-
const browser = await findBrowser(this.options.viewer?.browserPath);
|
|
2238
|
+
const browser = await findBrowser(this.options.viewer?.browserPath, this.logger);
|
|
924
2239
|
if (browser === null) {
|
|
925
2240
|
// No silent fallback to re-rendering the cells ourselves: that would
|
|
926
2241
|
// return a picture of what the daemon thinks, labelled as what the
|
|
@@ -931,9 +2246,38 @@ export class Daemon {
|
|
|
931
2246
|
});
|
|
932
2247
|
return;
|
|
933
2248
|
}
|
|
2249
|
+
const capturedScreen = await session.captureViewerScreen(signature === null ? 0 : REASONING_CONTEXT_LINES, VIEWER_SNAPSHOT_SCROLLBACK_LINES);
|
|
2250
|
+
let redactedRows;
|
|
2251
|
+
let expectedRows;
|
|
2252
|
+
if (signature !== null) {
|
|
2253
|
+
const view = capturedScreen.view;
|
|
2254
|
+
const filtered = hideReasoning(view.lines, signature, view.firstVisible);
|
|
2255
|
+
if (filtered === null) {
|
|
2256
|
+
json(res, 400, { error: overBudgetMessage(signature) });
|
|
2257
|
+
return;
|
|
2258
|
+
}
|
|
2259
|
+
redactedRows = new Map();
|
|
2260
|
+
const visibleRows = view.lines.length - view.firstVisible;
|
|
2261
|
+
expectedRows = view.lines.slice(view.firstVisible).map((line) => line.text.replace(/\s+$/, ''));
|
|
2262
|
+
while (expectedRows.length > 0 && expectedRows.at(-1) === '')
|
|
2263
|
+
expectedRows.pop();
|
|
2264
|
+
filtered.lines.forEach((line, index) => {
|
|
2265
|
+
if (!filtered.markers[index])
|
|
2266
|
+
return;
|
|
2267
|
+
const from = filtered.rows[index];
|
|
2268
|
+
const to = filtered.rows[index + 1] ?? visibleRows;
|
|
2269
|
+
for (let row = from; row < to; row++)
|
|
2270
|
+
redactedRows.set(row, row === from ? line : '');
|
|
2271
|
+
});
|
|
2272
|
+
}
|
|
934
2273
|
// Read-only, because a photograph must not be able to type into the
|
|
935
2274
|
// thing it is photographing.
|
|
936
2275
|
const grant = this.tokens.mintViewerGrant(id, { readOnly: true });
|
|
2276
|
+
this.captureSnapshots.set(grant, {
|
|
2277
|
+
bytes: VIEWER_WIPE + capturedScreen.state,
|
|
2278
|
+
cols: capturedScreen.cols,
|
|
2279
|
+
rows: capturedScreen.rows,
|
|
2280
|
+
});
|
|
937
2281
|
try {
|
|
938
2282
|
const capture = await (this.options.capture ?? captureViewer)({
|
|
939
2283
|
browser,
|
|
@@ -941,17 +2285,31 @@ export class Daemon {
|
|
|
941
2285
|
width,
|
|
942
2286
|
height,
|
|
943
2287
|
timeoutMs,
|
|
2288
|
+
profileRoot: captureProfileRoot(this.options.home),
|
|
2289
|
+
...(redactedRows === undefined ? {} : { hiddenRows: [...redactedRows.keys()] }),
|
|
944
2290
|
logger: this.logger,
|
|
945
2291
|
});
|
|
2292
|
+
if (expectedRows !== undefined &&
|
|
2293
|
+
JSON.stringify(capture.rows) !== JSON.stringify(expectedRows)) {
|
|
2294
|
+
const diagnostics = rowDifferenceDiagnostics(expectedRows, capture.rows);
|
|
2295
|
+
this.logger.warn('filtered screenshot rows differ', { id, ...diagnostics });
|
|
2296
|
+
json(res, 409, {
|
|
2297
|
+
error: 'The screen changed before its filtered picture could be taken. Try again.',
|
|
2298
|
+
diagnostics,
|
|
2299
|
+
});
|
|
2300
|
+
return;
|
|
2301
|
+
}
|
|
946
2302
|
this.audit.record(actor, 'screenshot', id, { width, height });
|
|
947
2303
|
json(res, 200, {
|
|
948
2304
|
png: capture.png.toString('base64'),
|
|
949
2305
|
// The picture's own dimensions, read from it rather than the request.
|
|
950
2306
|
width: capture.width,
|
|
951
2307
|
height: capture.height,
|
|
952
|
-
cols:
|
|
953
|
-
rows:
|
|
954
|
-
lines:
|
|
2308
|
+
cols: capturedScreen.cols,
|
|
2309
|
+
rows: capturedScreen.rows,
|
|
2310
|
+
lines: redactedRows === undefined
|
|
2311
|
+
? capture.rows
|
|
2312
|
+
: capture.rows.map((line, row) => redactedRows.get(row) ?? line),
|
|
955
2313
|
});
|
|
956
2314
|
}
|
|
957
2315
|
catch (error) {
|
|
@@ -968,6 +2326,7 @@ export class Daemon {
|
|
|
968
2326
|
// capture that failed leaves the same credential behind as one that
|
|
969
2327
|
// worked.
|
|
970
2328
|
this.tokens.revokeViewerGrant(grant);
|
|
2329
|
+
this.captureSnapshots.delete(grant);
|
|
971
2330
|
}
|
|
972
2331
|
return;
|
|
973
2332
|
}
|
|
@@ -1000,9 +2359,10 @@ export class Daemon {
|
|
|
1000
2359
|
const view = await session.styledScreen(REASONING_CONTEXT_LINES);
|
|
1001
2360
|
const screen = hideReasoning(view.lines, signature, view.firstVisible);
|
|
1002
2361
|
let tail;
|
|
2362
|
+
let tailSource;
|
|
1003
2363
|
if (count !== undefined) {
|
|
1004
|
-
|
|
1005
|
-
tail = hideReasoning(
|
|
2364
|
+
tailSource = await session.styledTail(count, REASONING_CONTEXT_LINES);
|
|
2365
|
+
tail = hideReasoning(tailSource.lines, signature, tailSource.firstVisible);
|
|
1006
2366
|
}
|
|
1007
2367
|
if (screen === null || tail === null) {
|
|
1008
2368
|
json(res, 400, { error: overBudgetMessage(signature) });
|
|
@@ -1010,9 +2370,11 @@ export class Daemon {
|
|
|
1010
2370
|
}
|
|
1011
2371
|
json(res, 200, {
|
|
1012
2372
|
...snapshot,
|
|
1013
|
-
screen: screen.lines.join('\n'),
|
|
2373
|
+
screen: markFilteredSelectedOption(screen.lines, view.lines).join('\n'),
|
|
1014
2374
|
cursor: filteredCursor(snapshot.cursor, screen),
|
|
1015
|
-
...(tail !== undefined
|
|
2375
|
+
...(tail !== undefined && tailSource !== undefined
|
|
2376
|
+
? { lastLines: markFilteredSelectedOption(tail.lines, tailSource.lines) }
|
|
2377
|
+
: {}),
|
|
1016
2378
|
reasoning: {
|
|
1017
2379
|
agent: signature.name,
|
|
1018
2380
|
hiddenLines: screen.hiddenLines,
|
|
@@ -1036,13 +2398,13 @@ export class Daemon {
|
|
|
1036
2398
|
});
|
|
1037
2399
|
return;
|
|
1038
2400
|
}
|
|
1039
|
-
// resize is
|
|
1040
|
-
//
|
|
2401
|
+
// resize is refused alongside input/key once the session has ended. In
|
|
2402
|
+
// the moment before that, once node-pty has seen the program end,
|
|
2403
|
+
// `Session.resize` refuses it itself, and the route below answers that
|
|
2404
|
+
// with the same 409.
|
|
1041
2405
|
if ((action === 'input' || action === 'key' || action === 'resize') &&
|
|
1042
2406
|
session.exited) {
|
|
1043
|
-
json(res, 409, {
|
|
1044
|
-
error: `Session ${id} has exited (code ${String(session.exitCode)}) and no longer accepts input or geometry changes.`,
|
|
1045
|
-
});
|
|
2407
|
+
json(res, 409, { error: endedRefusal(id, session.exitCode) });
|
|
1046
2408
|
return;
|
|
1047
2409
|
}
|
|
1048
2410
|
if (req.method === 'POST' && action === 'input') {
|
|
@@ -1062,14 +2424,18 @@ export class Daemon {
|
|
|
1062
2424
|
// real time, so the session can die between the guard and the last
|
|
1063
2425
|
// chunk. That is the same "you are writing to a dead session" condition
|
|
1064
2426
|
// the guard reports, so it gets the same 409. A 500 would blame the
|
|
1065
|
-
// caller's request for a race in the session's lifetime.
|
|
2427
|
+
// caller's request for a race in the session's lifetime. A session
|
|
2428
|
+
// whose input pipe has failed refuses the write too, and its error
|
|
2429
|
+
// says what to do.
|
|
1066
2430
|
let before;
|
|
1067
2431
|
try {
|
|
1068
2432
|
before = await session.write(data);
|
|
1069
2433
|
}
|
|
1070
2434
|
catch (error) {
|
|
1071
2435
|
json(res, 409, {
|
|
1072
|
-
error:
|
|
2436
|
+
error: error instanceof SessionInputFailedError
|
|
2437
|
+
? error.message
|
|
2438
|
+
: `Session ${id} exited while the input was being written: ${String(error)}`,
|
|
1073
2439
|
});
|
|
1074
2440
|
return;
|
|
1075
2441
|
}
|
|
@@ -1105,13 +2471,16 @@ export class Daemon {
|
|
|
1105
2471
|
});
|
|
1106
2472
|
return;
|
|
1107
2473
|
}
|
|
1108
|
-
// Same exit race as the input endpoint above:
|
|
2474
|
+
// Same exit race and failed input pipe as the input endpoint above:
|
|
2475
|
+
// 409, not 500.
|
|
1109
2476
|
try {
|
|
1110
2477
|
await session.write(bytes);
|
|
1111
2478
|
}
|
|
1112
2479
|
catch (error) {
|
|
1113
2480
|
json(res, 409, {
|
|
1114
|
-
error:
|
|
2481
|
+
error: error instanceof SessionInputFailedError
|
|
2482
|
+
? error.message
|
|
2483
|
+
: `Session ${id} exited while the key was being written: ${String(error)}`,
|
|
1115
2484
|
});
|
|
1116
2485
|
return;
|
|
1117
2486
|
}
|
|
@@ -1147,6 +2516,9 @@ export class Daemon {
|
|
|
1147
2516
|
// `prompt === true` only.
|
|
1148
2517
|
if (prompt !== null)
|
|
1149
2518
|
condition.prompt = prompt !== 'false' && prompt !== '0';
|
|
2519
|
+
const filteredMatch = reader !== null && (condition.text !== undefined || condition.regex !== undefined || condition.prompt === true);
|
|
2520
|
+
const muse = signatureFor(session.agent, session.command);
|
|
2521
|
+
let matchView;
|
|
1150
2522
|
const timeoutParam = url.searchParams.get('timeout');
|
|
1151
2523
|
const debounceParam = url.searchParams.get('debounce');
|
|
1152
2524
|
const afterInputParam = url.searchParams.get('matchAfterInput');
|
|
@@ -1172,6 +2544,16 @@ export class Daemon {
|
|
|
1172
2544
|
...(afterInputParam !== null
|
|
1173
2545
|
? { matchAfterInput: afterInputParam !== 'false' && afterInputParam !== '0' }
|
|
1174
2546
|
: {}),
|
|
2547
|
+
...(filteredMatch ? { screenForMatch: () => {
|
|
2548
|
+
matchView = filteredWaitScreen(session, reader);
|
|
2549
|
+
return matchView.screen;
|
|
2550
|
+
} } : {}),
|
|
2551
|
+
...(muse?.name === 'muse' ? {
|
|
2552
|
+
composerPending: () => {
|
|
2553
|
+
const result = latestResult(session.styledScreenNow(REASONING_CONTEXT_LINES).lines, muse);
|
|
2554
|
+
return !result.found && result.reason === 'prompt-typed';
|
|
2555
|
+
},
|
|
2556
|
+
} : {}),
|
|
1175
2557
|
signal: abort.signal,
|
|
1176
2558
|
});
|
|
1177
2559
|
}
|
|
@@ -1183,6 +2565,16 @@ export class Daemon {
|
|
|
1183
2565
|
if (abort.signal.aborted)
|
|
1184
2566
|
return;
|
|
1185
2567
|
if (reader !== null) {
|
|
2568
|
+
if (filteredMatch && matchView !== undefined) {
|
|
2569
|
+
json(res, 200, {
|
|
2570
|
+
...result,
|
|
2571
|
+
reasoning: { agent: reader.name, hiddenLines: matchView.filtered.hiddenLines, hiddenBlocks: matchView.filtered.hiddenBlocks },
|
|
2572
|
+
id: session.id,
|
|
2573
|
+
exited: session.exited,
|
|
2574
|
+
exitCode: session.exitCode,
|
|
2575
|
+
});
|
|
2576
|
+
return;
|
|
2577
|
+
}
|
|
1186
2578
|
// The screen as it stands now, a moment after the wait resolved,
|
|
1187
2579
|
// with the reasoning left out.
|
|
1188
2580
|
const view = await session.styledScreen(REASONING_CONTEXT_LINES);
|
|
@@ -1191,9 +2583,22 @@ export class Daemon {
|
|
|
1191
2583
|
json(res, 400, { error: overBudgetMessage(reader) });
|
|
1192
2584
|
return;
|
|
1193
2585
|
}
|
|
2586
|
+
const marked = markFilteredSelectedOption(filtered.lines, view.lines);
|
|
2587
|
+
const visiblePrompt = result.prompt === undefined
|
|
2588
|
+
? null
|
|
2589
|
+
: detectPrompt(marked.join('\n'));
|
|
2590
|
+
const prompt = visiblePrompt !== null && visiblePrompt.signature === result.prompt?.signature
|
|
2591
|
+
? {
|
|
2592
|
+
question: visiblePrompt.question,
|
|
2593
|
+
options: visiblePrompt.options,
|
|
2594
|
+
signature: visiblePrompt.signature,
|
|
2595
|
+
...(visiblePrompt.selectedOption === undefined ? {} : { selectedOption: visiblePrompt.selectedOption }),
|
|
2596
|
+
}
|
|
2597
|
+
: undefined;
|
|
1194
2598
|
json(res, 200, {
|
|
1195
2599
|
...result,
|
|
1196
|
-
screen:
|
|
2600
|
+
screen: marked.join('\n'),
|
|
2601
|
+
...(result.prompt === undefined ? {} : { prompt }),
|
|
1197
2602
|
reasoning: { agent: reader.name, hiddenLines: filtered.hiddenLines, hiddenBlocks: filtered.hiddenBlocks },
|
|
1198
2603
|
id: session.id,
|
|
1199
2604
|
exited: session.exited,
|
|
@@ -1276,7 +2681,15 @@ export class Daemon {
|
|
|
1276
2681
|
return;
|
|
1277
2682
|
}
|
|
1278
2683
|
const hold = body['hold'] === true;
|
|
1279
|
-
|
|
2684
|
+
try {
|
|
2685
|
+
await session.resize(cols, rows, { hold });
|
|
2686
|
+
}
|
|
2687
|
+
catch (error) {
|
|
2688
|
+
if (!(error instanceof SessionProgramEndedError))
|
|
2689
|
+
throw error;
|
|
2690
|
+
json(res, 409, { error: endedRefusal(id, error.exitCode) });
|
|
2691
|
+
return;
|
|
2692
|
+
}
|
|
1280
2693
|
this.audit.record(actor, 'resize', id, { cols, rows, hold });
|
|
1281
2694
|
// An API resize takes the grid away from whichever viewport had it, so
|
|
1282
2695
|
// nobody is left believing they still drive it. It does NOT hold
|
|
@@ -1284,6 +2697,7 @@ export class Daemon {
|
|
|
1284
2697
|
// back by moving that window, which is the only escape they have while
|
|
1285
2698
|
// there is no takeover control to press (§5).
|
|
1286
2699
|
this.geometryController.delete(id);
|
|
2700
|
+
this.dashboardGeometryOwner.delete(id);
|
|
1287
2701
|
this.announceGeometry(id, session);
|
|
1288
2702
|
json(res, 200, { ok: true, cols, rows, geometryHeld: session.geometryHeld });
|
|
1289
2703
|
return;
|
|
@@ -1295,6 +2709,10 @@ export class Daemon {
|
|
|
1295
2709
|
json(res, 400, { error: error.message });
|
|
1296
2710
|
return;
|
|
1297
2711
|
}
|
|
2712
|
+
if (error instanceof RequestBodyTooLargeError) {
|
|
2713
|
+
json(res, 413, { error: error.message });
|
|
2714
|
+
return;
|
|
2715
|
+
}
|
|
1298
2716
|
if (error instanceof Error && error.message.startsWith('Request body')) {
|
|
1299
2717
|
json(res, 400, { error: error.message });
|
|
1300
2718
|
return;
|
|
@@ -1326,28 +2744,32 @@ export class Daemon {
|
|
|
1326
2744
|
});
|
|
1327
2745
|
return;
|
|
1328
2746
|
}
|
|
2747
|
+
// A session starts in the user's home directory unless the caller names a
|
|
2748
|
+
// folder, and a relative one is taken from there. Never the daemon's own
|
|
2749
|
+
// working directory: that is wherever the daemon happened to be started,
|
|
2750
|
+
// and the ShellPuppet home would put a program beside daemon.json and its
|
|
2751
|
+
// token. The CLI and the MCP server send their own working directory, so
|
|
2752
|
+
// this default is for a direct caller of the API.
|
|
2753
|
+
const cwd = path.resolve(os.homedir(), asString(body['cwd']) ?? '.');
|
|
1329
2754
|
// A working directory that is not one is a caller mistake, reported as
|
|
1330
2755
|
// one here rather than left to fail deep inside ConPTY as "Cannot create
|
|
1331
2756
|
// process, error code: 267", which gives the caller nothing to act on.
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
}
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
}
|
|
1342
|
-
|
|
1343
|
-
json(res, 400, { error: `cwd is not a directory: ${cwd}` });
|
|
1344
|
-
return;
|
|
1345
|
-
}
|
|
2757
|
+
let isDirectory;
|
|
2758
|
+
try {
|
|
2759
|
+
isDirectory = fs.statSync(cwd).isDirectory();
|
|
2760
|
+
}
|
|
2761
|
+
catch {
|
|
2762
|
+
json(res, 400, { error: `cwd does not exist: ${cwd}` });
|
|
2763
|
+
return;
|
|
2764
|
+
}
|
|
2765
|
+
if (!isDirectory) {
|
|
2766
|
+
json(res, 400, { error: `cwd is not a directory: ${cwd}` });
|
|
2767
|
+
return;
|
|
1346
2768
|
}
|
|
1347
2769
|
const options = {
|
|
1348
2770
|
command,
|
|
1349
2771
|
...(asStringArray(body['args']) !== undefined ? { args: asStringArray(body['args']) } : {}),
|
|
1350
|
-
|
|
2772
|
+
cwd,
|
|
1351
2773
|
...(asNumber(body['cols']) !== undefined ? { cols: asNumber(body['cols']) } : {}),
|
|
1352
2774
|
...(asNumber(body['rows']) !== undefined ? { rows: asNumber(body['rows']) } : {}),
|
|
1353
2775
|
...(body['hold'] === true ? { hold: true } : {}),
|
|
@@ -1382,6 +2804,15 @@ export class Daemon {
|
|
|
1382
2804
|
json(res, 400, { error: error.message });
|
|
1383
2805
|
return;
|
|
1384
2806
|
}
|
|
2807
|
+
// The Windows build cannot run a terminal at all: named and refused,
|
|
2808
|
+
// like any other start the caller cannot get.
|
|
2809
|
+
if (error instanceof WindowsWithoutConPTYError) {
|
|
2810
|
+
json(res, 400, { error: error.message });
|
|
2811
|
+
return;
|
|
2812
|
+
}
|
|
2813
|
+
this.logger.error('session start failed', {
|
|
2814
|
+
error: error instanceof Error ? (error.stack ?? String(error)) : String(error),
|
|
2815
|
+
});
|
|
1385
2816
|
// The install cannot open a terminal at all. The message says what to
|
|
1386
2817
|
// do, so it goes out as written.
|
|
1387
2818
|
if (error instanceof NativePtyUnavailableError) {
|
|
@@ -1391,6 +2822,25 @@ export class Daemon {
|
|
|
1391
2822
|
json(res, 500, { error: `Failed to start session: ${String(error)}` });
|
|
1392
2823
|
return;
|
|
1393
2824
|
}
|
|
2825
|
+
// node-pty 1.2.0-beta.18 creates a Windows terminal's program only once
|
|
2826
|
+
// its output worker has connected, a few hundred milliseconds after the
|
|
2827
|
+
// spawn returns, and reports pid 0 until then. The start contract is what
|
|
2828
|
+
// it always was: a started session has a program, and its pid is real.
|
|
2829
|
+
const startedSession = await this.programStarted(session, options, res, 'session start failed');
|
|
2830
|
+
if (startedSession === null)
|
|
2831
|
+
return;
|
|
2832
|
+
session = startedSession;
|
|
2833
|
+
// Registration is synchronous with creation, before any asynchronous
|
|
2834
|
+
// viewer launch or readiness work can publish a change for this id.
|
|
2835
|
+
this.sessionFeed.add(this.summaryWithPrompt(session.summary()));
|
|
2836
|
+
session.onExit(() => {
|
|
2837
|
+
this.clearPromptGraceCheck(session.id);
|
|
2838
|
+
this.promptStates.delete(session.id);
|
|
2839
|
+
this.geometryController.delete(session.id);
|
|
2840
|
+
this.dashboardGeometryOwner.delete(session.id);
|
|
2841
|
+
this.updateFeedSession(session.id);
|
|
2842
|
+
});
|
|
2843
|
+
session.onReady(() => this.updateFeedSession(session.id));
|
|
1394
2844
|
// Commands are policy-visible by definition, so the command line IS
|
|
1395
2845
|
// audited (§4.5), unlike typed content. Passed variables are audited by
|
|
1396
2846
|
// name only, whatever `audit.captureContent` says: a value is a secret
|
|
@@ -1402,9 +2852,9 @@ export class Daemon {
|
|
|
1402
2852
|
...(agent !== undefined ? { agent } : {}),
|
|
1403
2853
|
label: session.label,
|
|
1404
2854
|
});
|
|
1405
|
-
// The human's way in (design §3.1):
|
|
1406
|
-
//
|
|
1407
|
-
//
|
|
2855
|
+
// The human's way in (design §3.1): the dashboard, a single-session viewer
|
|
2856
|
+
// window, or a viewer URL the caller hands them when no window opened.
|
|
2857
|
+
// Dashboard and viewer grants are separate; neither is the client token.
|
|
1408
2858
|
// The session id goes in the QUERY, not the path, and that is load-bearing
|
|
1409
2859
|
// on Windows. Chrome derives an `--app` window's AppUserModelID from
|
|
1410
2860
|
// host + PATH only, and Windows groups taskbar buttons
|
|
@@ -1420,7 +2870,11 @@ export class Daemon {
|
|
|
1420
2870
|
// nothing; the session is listed as any other, and `viewer-url` gives a
|
|
1421
2871
|
// link to it whenever someone asks.
|
|
1422
2872
|
const wantsViewer = body['openViewer'] !== false;
|
|
1423
|
-
|
|
2873
|
+
// A connected dashboard is the human's window. Do not mint a viewer grant
|
|
2874
|
+
// that would sit unused, and do not open a second window.
|
|
2875
|
+
const dashboardWatching = wantsViewer && this.hasLiveDashboardSocket();
|
|
2876
|
+
const mode = this.options.viewer?.launchMode ?? 'no-window';
|
|
2877
|
+
let viewerUrl = wantsViewer && !dashboardWatching && mode !== 'dashboard'
|
|
1424
2878
|
? this.viewerUrlFor(session.id, this.tokens.mintViewerGrant(session.id))
|
|
1425
2879
|
: '';
|
|
1426
2880
|
// Open the window for the human, and wait to hear whether anything
|
|
@@ -1431,8 +2885,17 @@ export class Daemon {
|
|
|
1431
2885
|
// failure here is logged and counts as "nothing opened".
|
|
1432
2886
|
const launch = this.options.launcher ?? launchViewer;
|
|
1433
2887
|
let opened;
|
|
1434
|
-
if (
|
|
1435
|
-
opened = { launched: false, mode: '
|
|
2888
|
+
if (dashboardWatching) {
|
|
2889
|
+
opened = { launched: false, mode: 'dashboard', reason: 'a dashboard is connected' };
|
|
2890
|
+
}
|
|
2891
|
+
else if (!wantsViewer) {
|
|
2892
|
+
opened = { launched: false, mode: 'no-window', reason: 'not requested at start' };
|
|
2893
|
+
}
|
|
2894
|
+
else if (mode === 'dashboard') {
|
|
2895
|
+
opened = await this.openDashboardForStart(req, actor);
|
|
2896
|
+
if (!opened.launched && opened.reason === 'the dashboard window did not open') {
|
|
2897
|
+
viewerUrl = this.viewerUrlFor(session.id, this.tokens.mintViewerGrant(session.id));
|
|
2898
|
+
}
|
|
1436
2899
|
}
|
|
1437
2900
|
else {
|
|
1438
2901
|
try {
|
|
@@ -1442,19 +2905,18 @@ export class Daemon {
|
|
|
1442
2905
|
this.logger.warn('viewer launch failed', { id: session.id, error: String(error) });
|
|
1443
2906
|
opened = {
|
|
1444
2907
|
launched: false,
|
|
1445
|
-
mode: this.options.viewer?.launchMode ?? '
|
|
2908
|
+
mode: this.options.viewer?.launchMode ?? 'no-window',
|
|
1446
2909
|
reason: String(error),
|
|
1447
2910
|
};
|
|
1448
2911
|
}
|
|
1449
2912
|
}
|
|
1450
|
-
//
|
|
1451
|
-
//
|
|
1452
|
-
// a
|
|
1453
|
-
//
|
|
1454
|
-
//
|
|
1455
|
-
// for the session.
|
|
1456
|
-
|
|
1457
|
-
const handOver = wantsViewer && !opened.launched;
|
|
2913
|
+
// A window that opened gives the caller no link: a link nobody asked for
|
|
2914
|
+
// would sit in a transcript as a live capability until it expired (§4.1).
|
|
2915
|
+
// When a viewer window did not open, its unspent link goes to the caller.
|
|
2916
|
+
// When a dashboard launch failed, the revoked dashboard grant is replaced
|
|
2917
|
+
// with a fresh viewer link. A handed-over link is audited under the actor
|
|
2918
|
+
// that asked for the session.
|
|
2919
|
+
const handOver = wantsViewer && !dashboardWatching && !opened.launched && viewerUrl !== '';
|
|
1458
2920
|
if (handOver)
|
|
1459
2921
|
this.audit.record(actor, 'grant-mint', session.id, { readOnly: false });
|
|
1460
2922
|
json(res, 200, {
|
|
@@ -1571,6 +3033,7 @@ export class Daemon {
|
|
|
1571
3033
|
}
|
|
1572
3034
|
this.sessionSockets.delete(id);
|
|
1573
3035
|
this.geometryController.delete(id);
|
|
3036
|
+
this.dashboardGeometryOwner.delete(id);
|
|
1574
3037
|
}
|
|
1575
3038
|
/** Whether a live viewport is currently driving this session's grid. */
|
|
1576
3039
|
hasGeometryController(sessionId) {
|
|
@@ -1583,6 +3046,41 @@ export class Daemon {
|
|
|
1583
3046
|
return false;
|
|
1584
3047
|
}
|
|
1585
3048
|
// ---------------------------------------------------- prompt-stall alerts
|
|
3049
|
+
/**
|
|
3050
|
+
* Wait, for a session just created, until its program exists (the start
|
|
3051
|
+
* contract; bounded by node-pty's five-second connection bound plus a
|
|
3052
|
+
* margin). Until then the session is starting: it holds a capacity slot but
|
|
3053
|
+
* is not listed and not in the dashboard feed, so nobody sees a session
|
|
3054
|
+
* that may never exist. A session that ends before any program did fails
|
|
3055
|
+
* the start with the status and shape 1.1.0's thrown spawn had (500,
|
|
3056
|
+
* "Failed to start session: Error: ..."), is ended and discarded, and null
|
|
3057
|
+
* is returned with the response already sent. Only the proven ConPTY worker
|
|
3058
|
+
* timeout gets one replacement attempt under the same id.
|
|
3059
|
+
*/
|
|
3060
|
+
async programStarted(session, options, res, logMessage) {
|
|
3061
|
+
this.startingIds.add(session.id);
|
|
3062
|
+
try {
|
|
3063
|
+
if (this.manager.get(session.id) === session)
|
|
3064
|
+
return await this.manager.finishStart(session, options);
|
|
3065
|
+
// Test-only dashboard factories may supply a session outside the manager.
|
|
3066
|
+
if (await session.startedProgramPid() !== null)
|
|
3067
|
+
return session;
|
|
3068
|
+
throw new SessionStartError(session.startFailure());
|
|
3069
|
+
}
|
|
3070
|
+
catch (error) {
|
|
3071
|
+
const failure = `Failed to start session: Error: ${error instanceof Error ? error.message : String(error)}`;
|
|
3072
|
+
this.logger.error(logMessage, { id: session.id, error: failure });
|
|
3073
|
+
json(res, 500, { error: failure });
|
|
3074
|
+
return null;
|
|
3075
|
+
}
|
|
3076
|
+
finally {
|
|
3077
|
+
this.startingIds.delete(session.id);
|
|
3078
|
+
}
|
|
3079
|
+
}
|
|
3080
|
+
/** The sessions a client or the dashboard may see: every one but those still starting. */
|
|
3081
|
+
listedSummaries() {
|
|
3082
|
+
return this.manager.list().filter((summary) => !this.startingIds.has(summary.id));
|
|
3083
|
+
}
|
|
1586
3084
|
/**
|
|
1587
3085
|
* Session list decorated with whatever prompt each session is holding. The
|
|
1588
3086
|
* stall alert also goes to `daemon.log` and the `/events` socket, but an
|
|
@@ -1597,23 +3095,65 @@ export class Daemon {
|
|
|
1597
3095
|
* The cost is staleness bounded by the scan interval: 5 s, immaterial
|
|
1598
3096
|
* against prompts that sit for minutes.
|
|
1599
3097
|
*/
|
|
1600
|
-
listWithPrompts() {
|
|
3098
|
+
listWithPrompts(hideReasoning = false) {
|
|
1601
3099
|
const now = Date.now();
|
|
1602
|
-
return this.
|
|
1603
|
-
const
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
waitingOnPrompt: {
|
|
1609
|
-
question: state.prompt.question,
|
|
1610
|
-
options: state.prompt.options,
|
|
1611
|
-
waitingMs: now - state.since,
|
|
1612
|
-
alerted: state.alerted,
|
|
1613
|
-
},
|
|
1614
|
-
};
|
|
3100
|
+
return this.listedSummaries().map((summary) => {
|
|
3101
|
+
const full = this.summaryWithPrompt(summary, now);
|
|
3102
|
+
const waiting = full.waitingOnPrompt;
|
|
3103
|
+
if (!hideReasoning || waiting === undefined)
|
|
3104
|
+
return full;
|
|
3105
|
+
return { ...full, waitingOnPrompt: { waitingMs: waiting.waitingMs, alerted: waiting.alerted } };
|
|
1615
3106
|
});
|
|
1616
3107
|
}
|
|
3108
|
+
summaryWithPrompt(summary, now = Date.now()) {
|
|
3109
|
+
const state = this.promptStates.get(summary.id);
|
|
3110
|
+
if (state === undefined)
|
|
3111
|
+
return summary;
|
|
3112
|
+
return {
|
|
3113
|
+
...summary,
|
|
3114
|
+
waitingOnPrompt: {
|
|
3115
|
+
question: state.prompt.question,
|
|
3116
|
+
options: state.prompt.options,
|
|
3117
|
+
...(state.prompt.selectedOption === undefined ? {} : { selectedOption: state.prompt.selectedOption }),
|
|
3118
|
+
waitingMs: now - state.since,
|
|
3119
|
+
alerted: state.alerted,
|
|
3120
|
+
},
|
|
3121
|
+
};
|
|
3122
|
+
}
|
|
3123
|
+
updateFeedSession(id) {
|
|
3124
|
+
const session = this.manager.get(id);
|
|
3125
|
+
if (session !== undefined)
|
|
3126
|
+
this.sessionFeed.update(this.summaryWithPrompt(session.summary()));
|
|
3127
|
+
}
|
|
3128
|
+
clearPromptGraceCheck(id) {
|
|
3129
|
+
const timer = this.promptGraceTimers.get(id);
|
|
3130
|
+
if (timer !== undefined)
|
|
3131
|
+
clearTimeout(timer);
|
|
3132
|
+
this.promptGraceTimers.delete(id);
|
|
3133
|
+
}
|
|
3134
|
+
schedulePromptGraceCheck(id, delayMs) {
|
|
3135
|
+
if (this.promptGraceTimers.has(id))
|
|
3136
|
+
return;
|
|
3137
|
+
const timer = setTimeout(() => {
|
|
3138
|
+
this.promptGraceTimers.delete(id);
|
|
3139
|
+
if (this.stopPromise !== null || !this.promptStates.has(id))
|
|
3140
|
+
return;
|
|
3141
|
+
if (this.promptScanRunning) {
|
|
3142
|
+
this.schedulePromptGraceCheck(id, 25);
|
|
3143
|
+
return;
|
|
3144
|
+
}
|
|
3145
|
+
this.promptScanRunning = true;
|
|
3146
|
+
this.scanForPromptStalls()
|
|
3147
|
+
.catch((error) => {
|
|
3148
|
+
this.logger.warn('prompt grace check failed', { id, error: String(error) });
|
|
3149
|
+
})
|
|
3150
|
+
.finally(() => {
|
|
3151
|
+
this.promptScanRunning = false;
|
|
3152
|
+
});
|
|
3153
|
+
}, delayMs);
|
|
3154
|
+
timer.unref();
|
|
3155
|
+
this.promptGraceTimers.set(id, timer);
|
|
3156
|
+
}
|
|
1617
3157
|
/**
|
|
1618
3158
|
* Scan every live session's screen for a permission prompt and alert when
|
|
1619
3159
|
* the SAME prompt has been waiting longer than the stall threshold, so an
|
|
@@ -1631,7 +3171,7 @@ export class Daemon {
|
|
|
1631
3171
|
let detected;
|
|
1632
3172
|
try {
|
|
1633
3173
|
const snapshot = await session.snapshot();
|
|
1634
|
-
detected =
|
|
3174
|
+
detected = session.answerablePrompt(snapshot.screen);
|
|
1635
3175
|
}
|
|
1636
3176
|
catch (error) {
|
|
1637
3177
|
// One session's render fault must not blind the scan for every
|
|
@@ -1645,19 +3185,19 @@ export class Daemon {
|
|
|
1645
3185
|
}
|
|
1646
3186
|
const previous = this.promptStates.get(session.id);
|
|
1647
3187
|
if (detected === null) {
|
|
1648
|
-
//
|
|
1649
|
-
//
|
|
1650
|
-
//
|
|
1651
|
-
|
|
1652
|
-
|
|
1653
|
-
|
|
1654
|
-
|
|
1655
|
-
|
|
1656
|
-
|
|
1657
|
-
|
|
1658
|
-
|
|
1659
|
-
continue;
|
|
3188
|
+
// A snapshot may land midway through a repaint. Keep the prompt and
|
|
3189
|
+
// its clock for a short wall-clock grace period, independent of the
|
|
3190
|
+
// scan interval; a lasting disappearance still clears it.
|
|
3191
|
+
if (previous !== undefined) {
|
|
3192
|
+
if (previous.missingSince === null)
|
|
3193
|
+
previous.missingSince = Date.now();
|
|
3194
|
+
const remaining = previous.missingSince + PROMPT_REPAINT_GRACE_MS - Date.now();
|
|
3195
|
+
if (remaining > 0) {
|
|
3196
|
+
this.schedulePromptGraceCheck(session.id, remaining);
|
|
3197
|
+
continue;
|
|
3198
|
+
}
|
|
1660
3199
|
}
|
|
3200
|
+
this.clearPromptGraceCheck(session.id);
|
|
1661
3201
|
if (previous?.alerted === true) {
|
|
1662
3202
|
this.emitEvent({
|
|
1663
3203
|
type: 'prompt-clear',
|
|
@@ -1668,21 +3208,35 @@ export class Daemon {
|
|
|
1668
3208
|
// over, or a badge raised by the stall alert never comes down.
|
|
1669
3209
|
this.broadcastControl(session.id, { type: 'prompt-clear' });
|
|
1670
3210
|
}
|
|
1671
|
-
|
|
3211
|
+
if (previous !== undefined) {
|
|
3212
|
+
this.promptStates.delete(session.id);
|
|
3213
|
+
this.updateFeedSession(session.id);
|
|
3214
|
+
}
|
|
1672
3215
|
continue;
|
|
1673
3216
|
}
|
|
1674
|
-
// A real sighting cancels a pending
|
|
3217
|
+
// A real sighting cancels a pending repaint gap: the prompt is still there.
|
|
1675
3218
|
// Refresh the stored prompt with it, too: the signature deliberately
|
|
1676
3219
|
// normalises Grok's radio markers so that MOVING the selection does not
|
|
1677
3220
|
// restart the stall clock, which means the same signature can describe a
|
|
1678
3221
|
// visibly different set of options. Storing only on signature change
|
|
1679
3222
|
// would serve a stale selection to `terminal_list` and to a viewer
|
|
1680
3223
|
// joining late.
|
|
3224
|
+
const promptChanged = previous === undefined ||
|
|
3225
|
+
previous.prompt.question !== detected.question ||
|
|
3226
|
+
previous.prompt.selectedOption !== detected.selectedOption ||
|
|
3227
|
+
previous.prompt.options.length !== detected.options.length ||
|
|
3228
|
+
previous.prompt.options.some((option, index) => option !== detected.options[index]);
|
|
1681
3229
|
if (previous !== undefined) {
|
|
1682
|
-
|
|
3230
|
+
this.clearPromptGraceCheck(session.id);
|
|
3231
|
+
previous.missingSince = null;
|
|
1683
3232
|
previous.prompt = detected;
|
|
1684
3233
|
}
|
|
1685
|
-
|
|
3234
|
+
// A dialog can redraw at another width, or alongside changing sidebar
|
|
3235
|
+
// text, without changing its question or choices. Its rendered signature
|
|
3236
|
+
// then changes although the person still faces the same decision.
|
|
3237
|
+
// A stable signature also covers focus markers moving among options.
|
|
3238
|
+
const sameContent = previous !== undefined && !promptChanged;
|
|
3239
|
+
if (previous === undefined || (previous.signature !== detected.signature && !sameContent)) {
|
|
1686
3240
|
// A new (or changed) prompt starts its stall clock; it has not
|
|
1687
3241
|
// alerted yet, so a prompt answered promptly stays silent.
|
|
1688
3242
|
if (previous?.alerted === true) {
|
|
@@ -1708,18 +3262,24 @@ export class Daemon {
|
|
|
1708
3262
|
since: Date.now(),
|
|
1709
3263
|
alerted: false,
|
|
1710
3264
|
prompt: detected,
|
|
1711
|
-
|
|
3265
|
+
missingSince: null,
|
|
1712
3266
|
});
|
|
3267
|
+
if (promptChanged || previous?.alerted === true)
|
|
3268
|
+
this.updateFeedSession(session.id);
|
|
1713
3269
|
continue;
|
|
1714
3270
|
}
|
|
3271
|
+
previous.signature = detected.signature;
|
|
3272
|
+
if (promptChanged)
|
|
3273
|
+
this.updateFeedSession(session.id);
|
|
1715
3274
|
if (!previous.alerted && Date.now() - previous.since >= stallMs) {
|
|
1716
3275
|
previous.alerted = true;
|
|
3276
|
+
this.updateFeedSession(session.id);
|
|
1717
3277
|
const waitingMs = Date.now() - previous.since;
|
|
1718
3278
|
this.audit.record('daemon', 'prompt-stall', session.id);
|
|
1719
3279
|
this.logger.warn('session waiting on a prompt', {
|
|
1720
3280
|
id: session.id,
|
|
1721
3281
|
waitingMs,
|
|
1722
|
-
|
|
3282
|
+
options: detected.options.length,
|
|
1723
3283
|
});
|
|
1724
3284
|
this.emitEvent({
|
|
1725
3285
|
type: 'prompt-stall',
|
|
@@ -1728,6 +3288,7 @@ export class Daemon {
|
|
|
1728
3288
|
waitingMs,
|
|
1729
3289
|
question: detected.question,
|
|
1730
3290
|
options: detected.options,
|
|
3291
|
+
...(detected.selectedOption === undefined ? {} : { selectedOption: detected.selectedOption }),
|
|
1731
3292
|
});
|
|
1732
3293
|
// The session's own viewers get the same signal, so an open viewer
|
|
1733
3294
|
// tab can badge itself without subscribing to the daemon stream.
|
|
@@ -1739,13 +3300,17 @@ export class Daemon {
|
|
|
1739
3300
|
// can say what the choices are, not only THAT something is being
|
|
1740
3301
|
// asked.
|
|
1741
3302
|
options: detected.options,
|
|
3303
|
+
...(detected.selectedOption === undefined ? {} : { selectedOption: detected.selectedOption }),
|
|
1742
3304
|
});
|
|
1743
3305
|
}
|
|
1744
3306
|
}
|
|
1745
3307
|
// Sessions that exited or were reaped take their prompt state with them.
|
|
1746
3308
|
for (const id of [...this.promptStates.keys()]) {
|
|
1747
|
-
if (!seen.has(id))
|
|
3309
|
+
if (!seen.has(id)) {
|
|
3310
|
+
this.clearPromptGraceCheck(id);
|
|
1748
3311
|
this.promptStates.delete(id);
|
|
3312
|
+
this.updateFeedSession(id);
|
|
3313
|
+
}
|
|
1749
3314
|
}
|
|
1750
3315
|
}
|
|
1751
3316
|
/** Fan an event out to every `/events` subscriber (TEXT JSON frames). */
|
|
@@ -1758,17 +3323,29 @@ export class Daemon {
|
|
|
1758
3323
|
}
|
|
1759
3324
|
// ------------------------------------------------------------- websockets
|
|
1760
3325
|
handleUpgrade(req, socket, head) {
|
|
3326
|
+
// Node takes its own 'error' listener off the socket before it emits
|
|
3327
|
+
// 'upgrade', and ws adds one only inside its handleUpgrade, which a
|
|
3328
|
+
// refusal never reaches. An error with no listener would be an uncaught
|
|
3329
|
+
// exception, on which the daemon shuts down with every session.
|
|
3330
|
+
socket.on('error', () => socket.destroy());
|
|
1761
3331
|
const reject = (code, reason) => {
|
|
1762
|
-
socket.write(`HTTP/1.1 ${String(code)} ${reason}\r\nConnection: close\r\n\r\n`);
|
|
3332
|
+
socket.write(`HTTP/1.1 ${String(code)} ${reason}\r\nReferrer-Policy: no-referrer\r\nConnection: close\r\n\r\n`);
|
|
1763
3333
|
socket.destroy();
|
|
1764
3334
|
};
|
|
1765
3335
|
if (!this.hostAllowed(req.headers.host)) {
|
|
3336
|
+
if (pathOnly(req.url).startsWith('/dashboard'))
|
|
3337
|
+
this.auditDashboardRefusal(req, 'host');
|
|
1766
3338
|
reject(403, 'Forbidden');
|
|
1767
3339
|
return;
|
|
1768
3340
|
}
|
|
1769
|
-
//
|
|
1770
|
-
// is
|
|
3341
|
+
// A foreign Origin is refused before the target is parsed and before any
|
|
3342
|
+
// credential is read, on every upgrade (design §4.2). A missing Origin
|
|
3343
|
+
// stays allowed here: non-browser clients send none on `/events` and on a
|
|
3344
|
+
// session stream. `/dashboard/events` still requires a present Origin
|
|
3345
|
+
// whose host matches `Host`, with its other cookie rules, below.
|
|
1771
3346
|
if (!this.originAllowed(req.headers.origin)) {
|
|
3347
|
+
if (pathOnly(req.url).startsWith('/dashboard'))
|
|
3348
|
+
this.auditDashboardRefusal(req, 'origin');
|
|
1772
3349
|
reject(403, 'Forbidden');
|
|
1773
3350
|
return;
|
|
1774
3351
|
}
|
|
@@ -1785,9 +3362,24 @@ export class Daemon {
|
|
|
1785
3362
|
return;
|
|
1786
3363
|
}
|
|
1787
3364
|
const segments = url.pathname.split('/').filter((s) => s !== '');
|
|
3365
|
+
// The dashboard feed is cookie-only. Its Origin rule is stricter than the
|
|
3366
|
+
// client-token sockets below, which still allow a missing Origin.
|
|
3367
|
+
if (segments[0] === 'dashboard' && segments[1] === 'events' && segments.length === 2) {
|
|
3368
|
+
const refusal = this.dashboardUpgradeRefusal(req);
|
|
3369
|
+
if (refusal !== null) {
|
|
3370
|
+
this.auditDashboardRefusal(req, refusal.audit);
|
|
3371
|
+
reject(refusal.code, refusal.reason);
|
|
3372
|
+
return;
|
|
3373
|
+
}
|
|
3374
|
+
this.wss.handleUpgrade(req, socket, head, (ws) => {
|
|
3375
|
+
this.attachDashboardSocket(ws);
|
|
3376
|
+
});
|
|
3377
|
+
return;
|
|
3378
|
+
}
|
|
1788
3379
|
// Daemon-wide event stream: prompt-stall alerts and their clears, as TEXT
|
|
1789
3380
|
// JSON frames. CLIENT token only: viewer credentials are session-scoped
|
|
1790
|
-
// and must not see other sessions' prompts.
|
|
3381
|
+
// and must not see other sessions' prompts. A foreign Origin was refused
|
|
3382
|
+
// above. A missing Origin stays allowed: non-browser clients send none.
|
|
1791
3383
|
if (segments.length === 1 && segments[0] === 'events') {
|
|
1792
3384
|
const auth = this.tokens.verify(url.searchParams.get('token'));
|
|
1793
3385
|
if (auth === null || auth.kind !== 'client') {
|
|
@@ -1804,41 +3396,39 @@ export class Daemon {
|
|
|
1804
3396
|
return;
|
|
1805
3397
|
}
|
|
1806
3398
|
const sessionId = segments[1] ?? '';
|
|
1807
|
-
// Auth BEFORE existence: session ids are sequential, and answering 404
|
|
1808
|
-
// an unauthenticated prober would let it enumerate which ones exist,
|
|
3399
|
+
// Auth BEFORE existence: session ids are sequential, and answering 404
|
|
3400
|
+
// to an unauthenticated prober would let it enumerate which ones exist,
|
|
1809
3401
|
// the same leak the unauthenticated viewer route deliberately avoids.
|
|
1810
|
-
//
|
|
1811
|
-
//
|
|
1812
|
-
//
|
|
1813
|
-
//
|
|
1814
|
-
//
|
|
1815
|
-
//
|
|
1816
|
-
//
|
|
1817
|
-
//
|
|
1818
|
-
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
.find((found) => found?.kind === 'viewer' && found.sessionId === sessionId) ??
|
|
1826
|
-
null;
|
|
1827
|
-
if (auth === null || (auth.kind === 'viewer' && auth.sessionId !== sessionId)) {
|
|
1828
|
-
reject(401, 'Unauthorized');
|
|
1829
|
-
return;
|
|
1830
|
-
}
|
|
1831
|
-
const readOnly = auth.kind === 'viewer' && auth.readOnly;
|
|
3402
|
+
// A foreign Origin was already refused above, so that probe is a 403
|
|
3403
|
+
// and never a 401.
|
|
3404
|
+
// A viewer grant is not a way in (§4.1). A client token may ride the
|
|
3405
|
+
// query, because it is the same-user secret from `daemon.json` and never
|
|
3406
|
+
// travels in a URL a human sees. A browser presents the HttpOnly cookie
|
|
3407
|
+
// it was given when its grant was redeemed. The dashboard cookie is the
|
|
3408
|
+
// third way in, with the proof as the subprotocol and the events
|
|
3409
|
+
// upgrade's Origin rules, which are stricter than a viewer cookie's.
|
|
3410
|
+
const decision = this.sessionStreamDecision(req, url, sessionId);
|
|
3411
|
+
if (!decision.ok) {
|
|
3412
|
+
if (decision.audit !== null)
|
|
3413
|
+
this.auditDashboardRefusal(req, decision.audit);
|
|
3414
|
+
reject(decision.code, decision.reason);
|
|
3415
|
+
return;
|
|
3416
|
+
}
|
|
1832
3417
|
const session = this.manager.get(sessionId);
|
|
1833
3418
|
if (session === undefined) {
|
|
1834
3419
|
reject(404, 'Not Found');
|
|
1835
3420
|
return;
|
|
1836
3421
|
}
|
|
3422
|
+
// `drive=0` opts a viewer or client socket out of taking the grid. A
|
|
3423
|
+
// dashboard credential is made passive in attachSocket, whatever the
|
|
3424
|
+
// query says, so this flag cannot turn that socket into a driver.
|
|
3425
|
+
const passive = passiveDrive(url);
|
|
1837
3426
|
this.wss.handleUpgrade(req, socket, head, (ws) => {
|
|
1838
3427
|
// Which credential opened the socket travels with it, so the audit log
|
|
1839
3428
|
// names that credential rather than assuming a browser: `client` for
|
|
1840
|
-
// the client token on the query, `viewer` for a viewer cookie
|
|
1841
|
-
|
|
3429
|
+
// the client token on the query, `viewer` for a viewer cookie,
|
|
3430
|
+
// `dashboard` for the dashboard cookie.
|
|
3431
|
+
this.attachSocket(ws, session, decision.credential, { passive, frozen: decision.frozen });
|
|
1842
3432
|
});
|
|
1843
3433
|
}
|
|
1844
3434
|
/** Attach a subscriber to the daemon-wide event stream. */
|
|
@@ -1858,6 +3448,100 @@ export class Daemon {
|
|
|
1858
3448
|
});
|
|
1859
3449
|
// The stream is outbound-only; inbound frames are ignored by design.
|
|
1860
3450
|
}
|
|
3451
|
+
/**
|
|
3452
|
+
* Attach a subscriber to the dashboard session feed. Frames are the feed's
|
|
3453
|
+
* own: hello, a snapshot, then session deltas. The only inbound frame read is
|
|
3454
|
+
* one small window registration; every other inbound frame is ignored.
|
|
3455
|
+
* The socket counts as connected so idle shutdown waits while the dashboard
|
|
3456
|
+
* is open.
|
|
3457
|
+
*/
|
|
3458
|
+
attachDashboardSocket(ws) {
|
|
3459
|
+
this.sockets.add(ws);
|
|
3460
|
+
this.dashboardEventSockets.add(ws);
|
|
3461
|
+
this.liveDashboardEventSockets.add(ws);
|
|
3462
|
+
this.dashboardWindowStartedAt = 0;
|
|
3463
|
+
this.lastActivity = Date.now();
|
|
3464
|
+
const heartbeatIntervalMs = this.options.dashboardHeartbeatIntervalMs ?? DASHBOARD_HEARTBEAT_INTERVAL_MS;
|
|
3465
|
+
const heartbeatTimeoutMs = this.options.dashboardHeartbeatTimeoutMs ?? DASHBOARD_HEARTBEAT_TIMEOUT_MS;
|
|
3466
|
+
let deadline = null;
|
|
3467
|
+
const heartbeat = setInterval(() => {
|
|
3468
|
+
if (ws.readyState !== ws.OPEN || deadline !== null)
|
|
3469
|
+
return;
|
|
3470
|
+
deadline = setTimeout(() => {
|
|
3471
|
+
this.liveDashboardEventSockets.delete(ws);
|
|
3472
|
+
ws.terminate();
|
|
3473
|
+
}, heartbeatTimeoutMs);
|
|
3474
|
+
deadline.unref();
|
|
3475
|
+
ws.ping();
|
|
3476
|
+
}, heartbeatIntervalMs);
|
|
3477
|
+
heartbeat.unref();
|
|
3478
|
+
ws.on('pong', () => {
|
|
3479
|
+
if (deadline !== null)
|
|
3480
|
+
clearTimeout(deadline);
|
|
3481
|
+
deadline = null;
|
|
3482
|
+
});
|
|
3483
|
+
const unsubscribe = this.subscribeDashboardFeed((frame) => {
|
|
3484
|
+
if (ws.readyState === ws.OPEN)
|
|
3485
|
+
ws.send(JSON.stringify(frame));
|
|
3486
|
+
});
|
|
3487
|
+
ws.on('message', (raw) => {
|
|
3488
|
+
// This id only speeds roster departure. It grants no daemon action.
|
|
3489
|
+
if (this.dashboardWindowIds.has(ws))
|
|
3490
|
+
return;
|
|
3491
|
+
let frame;
|
|
3492
|
+
try {
|
|
3493
|
+
const bytes = Array.isArray(raw) ? Buffer.concat(raw) : Buffer.from(raw);
|
|
3494
|
+
// A registration is a few dozen bytes: never parse anything larger.
|
|
3495
|
+
if (bytes.length > MAX_WINDOW_REGISTRATION_BYTES)
|
|
3496
|
+
return;
|
|
3497
|
+
frame = JSON.parse(bytes.toString('utf8'));
|
|
3498
|
+
}
|
|
3499
|
+
catch {
|
|
3500
|
+
return;
|
|
3501
|
+
}
|
|
3502
|
+
if (typeof frame !== 'object' || frame === null)
|
|
3503
|
+
return;
|
|
3504
|
+
const claim = frame;
|
|
3505
|
+
if (claim.type !== 'window-register' || typeof claim.id !== 'string' ||
|
|
3506
|
+
!/^[a-z0-9]+-[a-z0-9]+(?:-[1-9][0-9]*)?$/.test(claim.id) || claim.id.length > 100 ||
|
|
3507
|
+
typeof claim.instance !== 'string' ||
|
|
3508
|
+
!/^[a-z0-9]+-[a-z0-9]+(?:-[1-9][0-9]*)?$/.test(claim.instance) ||
|
|
3509
|
+
claim.instance.length > 100)
|
|
3510
|
+
return;
|
|
3511
|
+
this.dashboardWindowIds.set(ws, { id: claim.id, instance: claim.instance });
|
|
3512
|
+
});
|
|
3513
|
+
ws.on('close', () => {
|
|
3514
|
+
const windowClaim = this.dashboardWindowIds.get(ws);
|
|
3515
|
+
this.dashboardWindowIds.delete(ws);
|
|
3516
|
+
unsubscribe();
|
|
3517
|
+
this.sockets.delete(ws);
|
|
3518
|
+
this.dashboardEventSockets.delete(ws);
|
|
3519
|
+
if (windowClaim !== undefined && ![...this.dashboardWindowIds.values()].some((other) => other.id === windowClaim.id && other.instance === windowClaim.instance)) {
|
|
3520
|
+
const notice = JSON.stringify({ type: 'window-gone', ...windowClaim });
|
|
3521
|
+
for (const peer of this.dashboardEventSockets) {
|
|
3522
|
+
if (peer.readyState === peer.OPEN)
|
|
3523
|
+
peer.send(notice);
|
|
3524
|
+
}
|
|
3525
|
+
}
|
|
3526
|
+
clearInterval(heartbeat);
|
|
3527
|
+
if (deadline !== null)
|
|
3528
|
+
clearTimeout(deadline);
|
|
3529
|
+
this.liveDashboardEventSockets.delete(ws);
|
|
3530
|
+
if (this.dashboardEventSockets.size === 0)
|
|
3531
|
+
this.dashboardWindowStartedAt = 0;
|
|
3532
|
+
this.lastActivity = Date.now();
|
|
3533
|
+
});
|
|
3534
|
+
ws.on('error', () => {
|
|
3535
|
+
ws.close();
|
|
3536
|
+
});
|
|
3537
|
+
}
|
|
3538
|
+
hasLiveDashboardSocket() {
|
|
3539
|
+
for (const ws of this.liveDashboardEventSockets) {
|
|
3540
|
+
if (ws.readyState === ws.OPEN)
|
|
3541
|
+
return true;
|
|
3542
|
+
}
|
|
3543
|
+
return false;
|
|
3544
|
+
}
|
|
1861
3545
|
/** Send a JSON control message (TEXT frame) to every watcher of a session. */
|
|
1862
3546
|
broadcastControl(sessionId, control) {
|
|
1863
3547
|
const watchers = this.sessionSockets.get(sessionId);
|
|
@@ -1883,6 +3567,7 @@ export class Daemon {
|
|
|
1883
3567
|
if (options.resync !== false)
|
|
1884
3568
|
sync.resync();
|
|
1885
3569
|
}
|
|
3570
|
+
this.updateFeedSession(sessionId);
|
|
1886
3571
|
}
|
|
1887
3572
|
/** What one watcher is told about the grid, from its own point of view. */
|
|
1888
3573
|
geometryFrame(session, ws) {
|
|
@@ -1927,13 +3612,20 @@ export class Daemon {
|
|
|
1927
3612
|
* keystrokes, or the viewer's terminal answering the program
|
|
1928
3613
|
* (terminalReports.ts).
|
|
1929
3614
|
*/
|
|
1930
|
-
attachSocket(ws, session, credential) {
|
|
3615
|
+
attachSocket(ws, session, credential, options = {}) {
|
|
1931
3616
|
const { readOnly } = credential;
|
|
3617
|
+
// A dashboard credential is always passive, whatever the query says.
|
|
3618
|
+
// Connecting does not make it the controller, and a resize is ignored
|
|
3619
|
+
// unless the frame says `take`. `drive=0` is that same opt-out for a
|
|
3620
|
+
// viewer or client socket. The query cannot turn a dashboard socket
|
|
3621
|
+
// into a driver.
|
|
3622
|
+
const passive = credential.kind === 'dashboard' || options.passive === true;
|
|
1932
3623
|
// The audit actor is the credential that opened this socket, not the
|
|
1933
3624
|
// route: `viewer` means the socket presented a viewer cookie (what a
|
|
1934
|
-
// viewer link's grant becomes when it is opened),
|
|
1935
|
-
// same-user client token rode the query
|
|
1936
|
-
//
|
|
3625
|
+
// viewer link's grant becomes when it is opened), `client` means the
|
|
3626
|
+
// same-user client token rode the query, and `dashboard` means the
|
|
3627
|
+
// dashboard cookie did. The actor names the credential, not the person
|
|
3628
|
+
// or program behind it.
|
|
1937
3629
|
const actor = credential.kind;
|
|
1938
3630
|
this.sockets.add(ws);
|
|
1939
3631
|
let watchers = this.sessionSockets.get(session.id);
|
|
@@ -1945,7 +3637,8 @@ export class Daemon {
|
|
|
1945
3637
|
if (ws.readyState === ws.OPEN)
|
|
1946
3638
|
ws.send(Buffer.from(bytes, 'utf8'));
|
|
1947
3639
|
}, () => this.snapshotForViewer(session));
|
|
1948
|
-
|
|
3640
|
+
if (options.frozen === undefined)
|
|
3641
|
+
watchers.set(ws, sync);
|
|
1949
3642
|
this.lastActivity = Date.now();
|
|
1950
3643
|
this.audit.record(actor, 'ws-connect', session.id);
|
|
1951
3644
|
// Who this session belongs to and what it is for. Sent before anything
|
|
@@ -1967,6 +3660,8 @@ export class Daemon {
|
|
|
1967
3660
|
// rather than shown a terminal that looks alive.
|
|
1968
3661
|
exited: session.exited,
|
|
1969
3662
|
exitCode: session.exitCode,
|
|
3663
|
+
// Likewise a session whose input has failed, before the viewer types.
|
|
3664
|
+
inputFailed: session.inputFailed,
|
|
1970
3665
|
}));
|
|
1971
3666
|
// Settle geometry from the SERVER on connect, before the viewer decides
|
|
1972
3667
|
// anything for itself. A viewer that fitted on open would resize the PTY
|
|
@@ -1980,19 +3675,50 @@ export class Daemon {
|
|
|
1980
3675
|
//
|
|
1981
3676
|
// Nobody driving, and free to be driven: this viewport picks it up, and
|
|
1982
3677
|
// will propose a grid that fills its window. A read-only credential never
|
|
1983
|
-
// drives, because choosing the grid is a write.
|
|
1984
|
-
|
|
3678
|
+
// drives, because choosing the grid is a write. A dashboard credential
|
|
3679
|
+
// never picks it up by connecting, whatever the query says, and neither
|
|
3680
|
+
// does a `drive=0` socket. Neither inherits a controller that has left:
|
|
3681
|
+
// this is the only place a socket becomes the controller without sending
|
|
3682
|
+
// `take`.
|
|
3683
|
+
if (credential.kind === 'dashboard' &&
|
|
3684
|
+
// The remembered proof identifies the dashboard credential, not a browser window;
|
|
3685
|
+
// any holder may already take this grid deliberately, so restoring it is enough.
|
|
3686
|
+
this.dashboardGeometryOwner.has(session.id) &&
|
|
3687
|
+
tokensEqual(this.dashboardGeometryOwner.get(session.id), ws.protocol) &&
|
|
3688
|
+
!session.exited &&
|
|
3689
|
+
!this.hasGeometryController(session.id)) {
|
|
3690
|
+
this.geometryController.set(session.id, ws);
|
|
3691
|
+
}
|
|
3692
|
+
else if (!session.geometryHeld &&
|
|
1985
3693
|
!readOnly &&
|
|
3694
|
+
!passive &&
|
|
1986
3695
|
!this.hasGeometryController(session.id)) {
|
|
1987
3696
|
this.geometryController.set(session.id, ws);
|
|
3697
|
+
this.dashboardGeometryOwner.delete(session.id);
|
|
1988
3698
|
}
|
|
1989
|
-
ws.send(JSON.stringify(
|
|
3699
|
+
ws.send(JSON.stringify(options.frozen === undefined
|
|
3700
|
+
? this.geometryFrame(session, ws)
|
|
3701
|
+
: { ...this.geometryFrame(session, ws), cols: options.frozen.cols, rows: options.frozen.rows }));
|
|
1990
3702
|
// What the daemon renders, as the bytes that rebuild it (design §5). Not
|
|
1991
3703
|
// a slice of the raw stream: a slice starts mid-frame, and a program that
|
|
1992
3704
|
// only repaints what changed never puts the rest of its frame back. Every
|
|
1993
3705
|
// agent CLI repaints that way once its chrome is up, and on Windows every
|
|
1994
3706
|
// program does as ConPTY relays it. Live bytes queue behind the
|
|
1995
3707
|
// snapshot in the gate.
|
|
3708
|
+
if (options.frozen !== undefined) {
|
|
3709
|
+
ws.send(Buffer.from(options.frozen.bytes, 'utf8'));
|
|
3710
|
+
ws.on('message', () => { this.lastActivity = Date.now(); });
|
|
3711
|
+
ws.on('close', () => {
|
|
3712
|
+
this.sockets.delete(ws);
|
|
3713
|
+
this.lastActivity = Date.now();
|
|
3714
|
+
this.audit.record(actor, 'ws-disconnect', session.id);
|
|
3715
|
+
});
|
|
3716
|
+
ws.on('error', (error) => {
|
|
3717
|
+
this.logger.warn('viewer socket error', { id: session.id, error: String(error) });
|
|
3718
|
+
ws.close();
|
|
3719
|
+
});
|
|
3720
|
+
return;
|
|
3721
|
+
}
|
|
1996
3722
|
sync.resync();
|
|
1997
3723
|
// Whoever was watching when the process exited got this notice on the
|
|
1998
3724
|
// wire, and someone who arrives inside the fifteen-minute grace is owed
|
|
@@ -2014,9 +3740,11 @@ export class Daemon {
|
|
|
2014
3740
|
waitingMs: Date.now() - held.since,
|
|
2015
3741
|
question: held.prompt.question,
|
|
2016
3742
|
options: held.prompt.options,
|
|
3743
|
+
...(held.prompt.selectedOption === undefined ? {} : { selectedOption: held.prompt.selectedOption }),
|
|
2017
3744
|
}));
|
|
2018
3745
|
}
|
|
2019
3746
|
const unsubscribeData = session.onData((data) => sync.deliver(data));
|
|
3747
|
+
this.updateFeedSession(session.id);
|
|
2020
3748
|
const unsubscribeExit = session.onExit((exitCode) => {
|
|
2021
3749
|
sync.deliver(exitNotice(exitCode));
|
|
2022
3750
|
// The notice is bytes on the terminal; the page needs a frame to change
|
|
@@ -2032,7 +3760,9 @@ export class Daemon {
|
|
|
2032
3760
|
this.logger.warn('viewer socket error', { id: session.id, error: String(error) });
|
|
2033
3761
|
ws.close();
|
|
2034
3762
|
});
|
|
2035
|
-
|
|
3763
|
+
/** Whether this socket has been told that the session's input has failed. */
|
|
3764
|
+
let toldInputFailed = false;
|
|
3765
|
+
const onViewerMessage = async (message) => {
|
|
2036
3766
|
this.lastActivity = Date.now();
|
|
2037
3767
|
const text = typeof message === 'string' ? message : message.toString('utf8');
|
|
2038
3768
|
try {
|
|
@@ -2040,7 +3770,14 @@ export class Daemon {
|
|
|
2040
3770
|
if (typeof parsed === 'object' &&
|
|
2041
3771
|
parsed !== null &&
|
|
2042
3772
|
parsed.type === 'resize') {
|
|
2043
|
-
const { cols, rows } = parsed;
|
|
3773
|
+
const { cols, rows, take } = parsed;
|
|
3774
|
+
// Fit, Enlarge, Focus and Restore are a resize that says `take`.
|
|
3775
|
+
// A passive socket's other resizes, including one a dashboard pane
|
|
3776
|
+
// sends because the window moved, are not that act: the grid stays,
|
|
3777
|
+
// nobody is handed it, and nothing is audited. Passivity is the
|
|
3778
|
+
// dashboard credential, or `drive=0` on a viewer or client socket.
|
|
3779
|
+
if (passive && take !== true)
|
|
3780
|
+
return;
|
|
2044
3781
|
if (!readOnly &&
|
|
2045
3782
|
typeof cols === 'number' &&
|
|
2046
3783
|
typeof rows === 'number' &&
|
|
@@ -2061,34 +3798,46 @@ export class Daemon {
|
|
|
2061
3798
|
cols: Math.min(cols, MAX_VIEWPORT_COLS),
|
|
2062
3799
|
rows: Math.min(rows, MAX_VIEWPORT_ROWS),
|
|
2063
3800
|
};
|
|
2064
|
-
// Asking is the deliberate act that takes control, whether or not
|
|
2065
|
-
// the grid actually moves: a viewport that already fits is still
|
|
2066
|
-
// the one driving.
|
|
2067
3801
|
const handedOver = this.geometryController.get(session.id) !== ws;
|
|
2068
|
-
this.geometryController.set(session.id, ws);
|
|
2069
3802
|
const changed = wanted.cols !== session.cols || wanted.rows !== session.rows;
|
|
2070
3803
|
let applied = false;
|
|
2071
3804
|
try {
|
|
2072
|
-
session.resize(wanted.cols, wanted.rows);
|
|
3805
|
+
await session.resize(wanted.cols, wanted.rows);
|
|
2073
3806
|
applied = true;
|
|
2074
3807
|
}
|
|
2075
3808
|
catch (error) {
|
|
2076
|
-
//
|
|
2077
|
-
//
|
|
2078
|
-
// a
|
|
2079
|
-
//
|
|
3809
|
+
// The program has ended (a viewer fitting its window while
|
|
3810
|
+
// looking at a dying session), and the session's exit follows
|
|
3811
|
+
// within about a second, with an `exited` frame to every
|
|
3812
|
+
// watcher. Nothing moved and nobody takes the grid, so nothing
|
|
3813
|
+
// is said: an answer would have a driving page whose window
|
|
3814
|
+
// does not fit the grid propose again at once, over and over
|
|
3815
|
+
// until the exit arrives.
|
|
3816
|
+
if (error instanceof SessionProgramEndedError)
|
|
3817
|
+
return;
|
|
3818
|
+
// Any other failure is logged rather than left to escape: an
|
|
3819
|
+
// exception from a WS handler would take the whole daemon down
|
|
3820
|
+
// via the uncaughtException path.
|
|
2080
3821
|
this.logger.warn('viewer resize failed', {
|
|
2081
3822
|
id: session.id,
|
|
2082
3823
|
error: String(error),
|
|
2083
3824
|
});
|
|
2084
3825
|
}
|
|
3826
|
+
// Asking is the deliberate act that takes control, whether or not
|
|
3827
|
+
// the grid actually moves: a viewport that already fits is still
|
|
3828
|
+
// the one driving.
|
|
3829
|
+
this.geometryController.set(session.id, ws);
|
|
3830
|
+
if (credential.kind === 'dashboard')
|
|
3831
|
+
this.dashboardGeometryOwner.set(session.id, ws.protocol);
|
|
3832
|
+
else
|
|
3833
|
+
this.dashboardGeometryOwner.delete(session.id);
|
|
2085
3834
|
// A geometry change is a geometry change whoever made it, and
|
|
2086
3835
|
// `resize` is on the list of audited actions the security page
|
|
2087
3836
|
// publishes. Only the ones that actually took: a proposal the
|
|
2088
|
-
// grid already satisfied moved nothing, and one that
|
|
2089
|
-
//
|
|
2090
|
-
//
|
|
2091
|
-
//
|
|
3837
|
+
// grid already satisfied moved nothing, and one that failed moved
|
|
3838
|
+
// nothing either, so neither is recorded as a success. `hold` is
|
|
3839
|
+
// false because a viewport never holds: holding is asked for
|
|
3840
|
+
// explicitly, over the API (§5).
|
|
2092
3841
|
if (changed && applied) {
|
|
2093
3842
|
this.audit.record(actor, 'resize', session.id, {
|
|
2094
3843
|
cols: wanted.cols,
|
|
@@ -2105,6 +3854,8 @@ export class Daemon {
|
|
|
2105
3854
|
this.announceGeometry(session.id, session);
|
|
2106
3855
|
else if (handedOver)
|
|
2107
3856
|
this.announceGeometry(session.id, session, { resync: false });
|
|
3857
|
+
else if (take === true)
|
|
3858
|
+
ws.send(JSON.stringify(this.geometryFrame(session, ws)));
|
|
2108
3859
|
}
|
|
2109
3860
|
return;
|
|
2110
3861
|
}
|
|
@@ -2134,6 +3885,17 @@ export class Daemon {
|
|
|
2134
3885
|
}
|
|
2135
3886
|
return;
|
|
2136
3887
|
}
|
|
3888
|
+
if (session.inputFailed) {
|
|
3889
|
+
// The input pipe has failed (Windows): nothing typed reaches the
|
|
3890
|
+
// program, so nothing is written, audited or logged. This socket is
|
|
3891
|
+
// told once, and the page says so; the 409 on the HTTP path is the
|
|
3892
|
+
// same refusal.
|
|
3893
|
+
if (!toldInputFailed && ws.readyState === ws.OPEN) {
|
|
3894
|
+
toldInputFailed = true;
|
|
3895
|
+
ws.send(JSON.stringify({ type: 'input-refused', reason: 'input-failed' }));
|
|
3896
|
+
}
|
|
3897
|
+
return;
|
|
3898
|
+
}
|
|
2137
3899
|
// write() is async, so a failure arrives as a rejection and never as a
|
|
2138
3900
|
// synchronous throw: a try/catch here would be dead code. Not awaited:
|
|
2139
3901
|
// this is the viewer's data handler and must stay responsive, and
|
|
@@ -2167,6 +3929,11 @@ export class Daemon {
|
|
|
2167
3929
|
...(this.audit.captureContent ? { data: text } : {}),
|
|
2168
3930
|
});
|
|
2169
3931
|
this.broadcastControl(session.id, { type: 'input-source', source: 'human' });
|
|
3932
|
+
};
|
|
3933
|
+
ws.on('message', (message) => {
|
|
3934
|
+
void onViewerMessage(message).catch((error) => {
|
|
3935
|
+
this.logger.warn('viewer message failed', { id: session.id, error: String(error) });
|
|
3936
|
+
});
|
|
2170
3937
|
});
|
|
2171
3938
|
ws.on('close', () => {
|
|
2172
3939
|
unsubscribeData();
|
|
@@ -2174,8 +3941,11 @@ export class Daemon {
|
|
|
2174
3941
|
sync.close();
|
|
2175
3942
|
this.sockets.delete(ws);
|
|
2176
3943
|
this.sessionSockets.get(session.id)?.delete(ws);
|
|
2177
|
-
|
|
2178
|
-
//
|
|
3944
|
+
this.updateFeedSession(session.id);
|
|
3945
|
+
// The grid stays where it is; it simply no longer belongs to anyone.
|
|
3946
|
+
// The next single-session viewport to arrive, or a `take`, picks it
|
|
3947
|
+
// up. A dashboard socket, and a `drive=0` socket, that is already
|
|
3948
|
+
// connected does not inherit it.
|
|
2179
3949
|
if (this.geometryController.get(session.id) === ws) {
|
|
2180
3950
|
this.geometryController.delete(session.id);
|
|
2181
3951
|
}
|