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