shellpuppet 0.0.1 → 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/LICENSE +202 -0
- package/NOTICE +31 -0
- package/README.md +499 -8
- 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.d.ts +13 -0
- package/dist/cli/index.js +846 -0
- package/dist/cli/index.js.map +1 -0
- package/dist/client/http.d.ts +143 -0
- package/dist/client/http.js +581 -0
- package/dist/client/http.js.map +1 -0
- package/dist/core/dialogs.d.ts +96 -0
- package/dist/core/dialogs.js +226 -0
- package/dist/core/dialogs.js.map +1 -0
- package/dist/core/echo.d.ts +71 -0
- package/dist/core/echo.js +249 -0
- package/dist/core/echo.js.map +1 -0
- package/dist/core/find.d.ts +34 -0
- package/dist/core/find.js +41 -0
- package/dist/core/find.js.map +1 -0
- package/dist/core/keys.d.ts +22 -0
- package/dist/core/keys.js +80 -0
- package/dist/core/keys.js.map +1 -0
- package/dist/core/manager.d.ts +96 -0
- package/dist/core/manager.js +271 -0
- package/dist/core/manager.js.map +1 -0
- package/dist/core/nativePty.d.ts +73 -0
- package/dist/core/nativePty.js +161 -0
- package/dist/core/nativePty.js.map +1 -0
- package/dist/core/policy.d.ts +61 -0
- package/dist/core/policy.js +143 -0
- package/dist/core/policy.js.map +1 -0
- package/dist/core/promptDetector.d.ts +109 -0
- package/dist/core/promptDetector.js +897 -0
- package/dist/core/promptDetector.js.map +1 -0
- package/dist/core/reasoning.d.ts +265 -0
- package/dist/core/reasoning.js +933 -0
- package/dist/core/reasoning.js.map +1 -0
- package/dist/core/regexBudget.d.ts +64 -0
- package/dist/core/regexBudget.js +103 -0
- package/dist/core/regexBudget.js.map +1 -0
- package/dist/core/renderer.d.ts +127 -0
- package/dist/core/renderer.js +316 -0
- package/dist/core/renderer.js.map +1 -0
- 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 +565 -0
- package/dist/core/session.js +1450 -0
- package/dist/core/session.js.map +1 -0
- package/dist/core/types.d.ts +316 -0
- package/dist/core/types.js +71 -0
- package/dist/core/types.js.map +1 -0
- package/dist/core/waiter.d.ts +94 -0
- package/dist/core/waiter.js +310 -0
- package/dist/core/waiter.js.map +1 -0
- 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 +161 -0
- package/dist/core/windowsPtyStart.js +236 -0
- package/dist/core/windowsPtyStart.js.map +1 -0
- package/dist/daemon/audit.d.ts +23 -0
- package/dist/daemon/audit.js +51 -0
- package/dist/daemon/audit.js.map +1 -0
- package/dist/daemon/auth.d.ts +197 -0
- package/dist/daemon/auth.js +366 -0
- package/dist/daemon/auth.js.map +1 -0
- package/dist/daemon/config.d.ts +119 -0
- package/dist/daemon/config.js +568 -0
- package/dist/daemon/config.js.map +1 -0
- 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.d.ts +7 -0
- package/dist/daemon/index.js +88 -0
- package/dist/daemon/index.js.map +1 -0
- package/dist/daemon/launchProfiles.d.ts +155 -0
- package/dist/daemon/launchProfiles.js +554 -0
- package/dist/daemon/launchProfiles.js.map +1 -0
- package/dist/daemon/liveness.d.ts +36 -0
- package/dist/daemon/liveness.js +71 -0
- package/dist/daemon/liveness.js.map +1 -0
- package/dist/daemon/logger.d.ts +7 -0
- package/dist/daemon/logger.js +29 -0
- package/dist/daemon/logger.js.map +1 -0
- package/dist/daemon/meta.d.ts +9 -0
- package/dist/daemon/meta.js +24 -0
- package/dist/daemon/meta.js.map +1 -0
- package/dist/daemon/paths.d.ts +85 -0
- package/dist/daemon/paths.js +154 -0
- package/dist/daemon/paths.js.map +1 -0
- package/dist/daemon/screenshot.d.ts +144 -0
- package/dist/daemon/screenshot.js +402 -0
- package/dist/daemon/screenshot.js.map +1 -0
- package/dist/daemon/server.d.ts +453 -0
- package/dist/daemon/server.js +3954 -0
- package/dist/daemon/server.js.map +1 -0
- 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/terminalReports.d.ts +38 -0
- package/dist/daemon/terminalReports.js +84 -0
- package/dist/daemon/terminalReports.js.map +1 -0
- package/dist/daemon/viewerLauncher.d.ts +226 -0
- package/dist/daemon/viewerLauncher.js +562 -0
- package/dist/daemon/viewerLauncher.js.map +1 -0
- package/dist/daemon/viewerSync.d.ts +38 -0
- package/dist/daemon/viewerSync.js +83 -0
- package/dist/daemon/viewerSync.js.map +1 -0
- package/dist/mcp/config.d.ts +50 -0
- package/dist/mcp/config.js +95 -0
- package/dist/mcp/config.js.map +1 -0
- package/dist/mcp/index.d.ts +10 -0
- package/dist/mcp/index.js +78 -0
- package/dist/mcp/index.js.map +1 -0
- package/dist/mcp/tools.d.ts +66 -0
- package/dist/mcp/tools.js +638 -0
- package/dist/mcp/tools.js.map +1 -0
- 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-16.png +0 -0
- package/dist/viewer/icon-180.png +0 -0
- package/dist/viewer/icon-32.png +0 -0
- package/dist/viewer/icon-512.png +0 -0
- package/dist/viewer/icon.ico +0 -0
- package/dist/viewer/icon.svg +66 -0
- package/dist/viewer/index.html +61 -0
- package/dist/viewer/pane.js +736 -0
- package/dist/viewer/viewer.css +95 -0
- package/dist/viewer/viewer.js +84 -0
- package/package.json +66 -7
- package/index.js +0 -4
|
@@ -0,0 +1,3954 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The ShellPuppet daemon: one per user, owns every PTY, serves clients and
|
|
3
|
+
* viewers (design §2). Binds 127.0.0.1 on an OS-assigned port, publishes its
|
|
4
|
+
* discovery record atomically and defends the loopback surface (§4.2):
|
|
5
|
+
* Host-header validation on every request, Origin validation on WebSocket
|
|
6
|
+
* upgrades, bearer-token auth on the API, no CORS headers at all.
|
|
7
|
+
*/
|
|
8
|
+
import * as fs from 'node:fs';
|
|
9
|
+
import * as http from 'node:http';
|
|
10
|
+
import { createRequire } from 'node:module';
|
|
11
|
+
import * as os from 'node:os';
|
|
12
|
+
import * as path from 'node:path';
|
|
13
|
+
import { fileURLToPath } from 'node:url';
|
|
14
|
+
import { WebSocketServer } from 'ws';
|
|
15
|
+
import { SessionManager, PolicyViolationError, SessionStartError } from '../core/manager.js';
|
|
16
|
+
import { CommandNotFoundError, DEFAULT_SESSION_ENV, SessionInputFailedError, SessionProgramEndedError, WindowsWithoutConPTYError, credentialShapedNames, } from '../core/session.js';
|
|
17
|
+
import { NativePtyUnavailableError } from '../core/nativePty.js';
|
|
18
|
+
import { checkSessionCapacity, commandLine, compilePolicy, evaluateCommand } from '../core/policy.js';
|
|
19
|
+
import { keyToBytes, knownKeys } from '../core/keys.js';
|
|
20
|
+
import { findOnScreen } from '../core/find.js';
|
|
21
|
+
import { screenShows } from '../core/echo.js';
|
|
22
|
+
import { RegexBudgetError } from '../core/regexBudget.js';
|
|
23
|
+
import { detectPrompt } from '../core/promptDetector.js';
|
|
24
|
+
import { markFilteredSelectedOption } from '../core/selection.js';
|
|
25
|
+
import { WaitConditionError } from '../core/waiter.js';
|
|
26
|
+
import { agentNames, hideReasoning, latestResult, programName, signatureFor } from '../core/reasoning.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';
|
|
29
|
+
import { NULL_AUDITOR } from './audit.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';
|
|
32
|
+
import { claimDaemonState, daemonStatePath, ensureHome, inspectDaemonState, readDaemonState, removeDaemonState, removeDaemonStateIf, removeDaemonStateIfNotARecord, } from './paths.js';
|
|
33
|
+
import { daemonRunning } from './liveness.js';
|
|
34
|
+
import { packageVersion } from './meta.js';
|
|
35
|
+
import { terminalReportKind } from './terminalReports.js';
|
|
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';
|
|
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;
|
|
46
|
+
const IDLE_CHECK_INTERVAL_MS = 60_000;
|
|
47
|
+
/**
|
|
48
|
+
* How often a running daemon checks that daemon.json still names it, and
|
|
49
|
+
* publishes it again when it is missing or names a daemon that has gone.
|
|
50
|
+
*/
|
|
51
|
+
const STATE_PUBLISH_CHECK_MS = 10_000;
|
|
52
|
+
/**
|
|
53
|
+
* How long a naturally-exited session stays readable before it is reaped.
|
|
54
|
+
* Long enough for an agent to come back and read the final screen; short
|
|
55
|
+
* enough that a busy day of short-lived sessions does not ratchet memory.
|
|
56
|
+
*/
|
|
57
|
+
const EXITED_SESSION_GRACE_MS = 15 * 60_000;
|
|
58
|
+
const MAX_BODY_BYTES = 1_000_000;
|
|
59
|
+
/**
|
|
60
|
+
* Prompt-stall detection: how often live screens are scanned for a
|
|
61
|
+
* permission prompt, and how long the SAME prompt must persist before an
|
|
62
|
+
* alert is emitted. The stall threshold exists so a prompt the human answers
|
|
63
|
+
* within seconds never alerts at all: the alert is for prompts NOBODY is
|
|
64
|
+
* looking at.
|
|
65
|
+
*/
|
|
66
|
+
const PROMPT_SCAN_INTERVAL_MS = 5_000;
|
|
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;
|
|
72
|
+
/**
|
|
73
|
+
* How long `verify` looks for typed text: a base, plus time for each
|
|
74
|
+
* character, up to a ceiling. Some TUIs work through every keystroke before
|
|
75
|
+
* they draw any of it: OpenCode draws a 300-character line all at once, about
|
|
76
|
+
* 2.2 s after it arrives (about 7 ms a character). The allowance per
|
|
77
|
+
* character leaves room for a slower machine; it is spent only when the text
|
|
78
|
+
* does not show.
|
|
79
|
+
*/
|
|
80
|
+
const VERIFY_BASE_MS = 600;
|
|
81
|
+
const VERIFY_MS_PER_CHAR = 15;
|
|
82
|
+
const VERIFY_MAX_MS = 15_000;
|
|
83
|
+
/**
|
|
84
|
+
* Scrollback lines carried in the snapshot a viewer receives (design §5). The
|
|
85
|
+
* viewport is always complete; this bounds the history behind it. A 5,000-line
|
|
86
|
+
* buffer at 160 columns serialises to ~700 KB in ~200 ms of daemon time, and
|
|
87
|
+
* every grid change sends a fresh snapshot to every watcher, so the history
|
|
88
|
+
* a snapshot carries is bounded at 2,000 lines.
|
|
89
|
+
*/
|
|
90
|
+
const VIEWER_SNAPSHOT_SCROLLBACK_LINES = 2_000;
|
|
91
|
+
/** Default size of the browser window a screenshot is taken in, in CSS pixels. */
|
|
92
|
+
const CAPTURE_WIDTH = 1_400;
|
|
93
|
+
const CAPTURE_HEIGHT = 900;
|
|
94
|
+
/**
|
|
95
|
+
* Bounds on a grid derived from a browser window (§5).
|
|
96
|
+
*
|
|
97
|
+
* A viewport drives the grid, so the human's monitor would otherwise set what
|
|
98
|
+
* the agent reads: a maximised 4K window at a small font asks for roughly
|
|
99
|
+
* 380x100, and every snapshot the driving agent takes is then about 38,000
|
|
100
|
+
* characters against about 4,000 at the 120x34 default. The bound travels with
|
|
101
|
+
* every geometry frame; past it the page grows its text until this much grid
|
|
102
|
+
* fills the window, then proposes that grid (§5).
|
|
103
|
+
*/
|
|
104
|
+
const MAX_VIEWPORT_COLS = 400;
|
|
105
|
+
const MAX_VIEWPORT_ROWS = 150;
|
|
106
|
+
/**
|
|
107
|
+
* RIS plus erase-saved-lines, ahead of every snapshot: the viewer starts from
|
|
108
|
+
* nothing, THROUGH its write queue, so anything it had queued applies before
|
|
109
|
+
* the wipe and nothing stale can paint after it.
|
|
110
|
+
*/
|
|
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
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* What a watcher is shown when the session ends: grey, on its own line
|
|
141
|
+
* and identical whether it was sent live at the moment of exit or replayed
|
|
142
|
+
* to someone who joined during the fifteen-minute grace. An end with no exit
|
|
143
|
+
* code says why the session ended (`howSessionEnded`).
|
|
144
|
+
*/
|
|
145
|
+
function exitNotice(exitCode) {
|
|
146
|
+
const notice = exitCode === null ? `session ended: ${howSessionEnded(null)}` : `process exited: ${String(exitCode)}`;
|
|
147
|
+
return `\r\n\x1b[90m[${notice}]\x1b[0m\r\n`;
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Static viewer assets, resolved once and served from a fixed allowlist.
|
|
151
|
+
* There is no path concatenation from request input, so no traversal surface.
|
|
152
|
+
* `../viewer/` is `dist/viewer/` in production (copied by the build) and
|
|
153
|
+
* `src/viewer/` under the test runner; the xterm bundles come straight out of
|
|
154
|
+
* node_modules via module resolution.
|
|
155
|
+
*/
|
|
156
|
+
const viewerDir = fileURLToPath(new URL('../viewer/', import.meta.url));
|
|
157
|
+
const nodeRequire = createRequire(import.meta.url);
|
|
158
|
+
const xtermJsPath = nodeRequire.resolve('@xterm/xterm');
|
|
159
|
+
const STATIC_ASSETS = {
|
|
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' },
|
|
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' },
|
|
167
|
+
// The mark. SVG first (crisp at any size, and what the tab uses); the PNGs
|
|
168
|
+
// are for Windows, which wants a raster for the taskbar button of a Chrome
|
|
169
|
+
// --app window. An SVG-only favicon leaves that button showing the generic
|
|
170
|
+
// globe.
|
|
171
|
+
'/viewer/icon.svg': { file: path.join(viewerDir, 'icon.svg'), type: 'image/svg+xml' },
|
|
172
|
+
'/viewer/icon-16.png': { file: path.join(viewerDir, 'icon-16.png'), type: 'image/png', binary: true },
|
|
173
|
+
'/viewer/icon-32.png': { file: path.join(viewerDir, 'icon-32.png'), type: 'image/png', binary: true },
|
|
174
|
+
'/viewer/icon-180.png': { file: path.join(viewerDir, 'icon-180.png'), type: 'image/png', binary: true },
|
|
175
|
+
'/viewer/icon-512.png': { file: path.join(viewerDir, 'icon-512.png'), type: 'image/png', binary: true },
|
|
176
|
+
'/vendor/xterm.js': { file: xtermJsPath, type: 'text/javascript' },
|
|
177
|
+
'/vendor/xterm.css': {
|
|
178
|
+
file: path.join(path.dirname(xtermJsPath), '..', 'css', 'xterm.css'),
|
|
179
|
+
type: 'text/css',
|
|
180
|
+
},
|
|
181
|
+
'/vendor/addon-fit.js': { file: nodeRequire.resolve('@xterm/addon-fit'), type: 'text/javascript' },
|
|
182
|
+
};
|
|
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="">';
|
|
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;
|
|
197
|
+
export class AlreadyRunningError extends Error {
|
|
198
|
+
state;
|
|
199
|
+
constructor(state) {
|
|
200
|
+
super(`A healthy daemon is already running (pid ${String(state.pid)}, ` +
|
|
201
|
+
`port ${String(state.port)}).`);
|
|
202
|
+
this.state = state;
|
|
203
|
+
this.name = 'AlreadyRunningError';
|
|
204
|
+
}
|
|
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
|
+
}
|
|
240
|
+
function isRecord(value) {
|
|
241
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
242
|
+
}
|
|
243
|
+
function json(res, code, body) {
|
|
244
|
+
const payload = JSON.stringify(body, null, 2);
|
|
245
|
+
res.writeHead(code, {
|
|
246
|
+
'content-type': 'application/json; charset=utf-8',
|
|
247
|
+
'content-length': Buffer.byteLength(payload),
|
|
248
|
+
});
|
|
249
|
+
res.end(payload);
|
|
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
|
+
}
|
|
262
|
+
function readBody(req) {
|
|
263
|
+
return new Promise((resolve, reject) => {
|
|
264
|
+
let size = 0;
|
|
265
|
+
let tooLarge = false;
|
|
266
|
+
const chunks = [];
|
|
267
|
+
req.on('data', (chunk) => {
|
|
268
|
+
if (tooLarge)
|
|
269
|
+
return; // discard the rest, so the 413 can be read
|
|
270
|
+
size += chunk.length;
|
|
271
|
+
if (size > MAX_BODY_BYTES) {
|
|
272
|
+
tooLarge = true;
|
|
273
|
+
chunks.length = 0;
|
|
274
|
+
return;
|
|
275
|
+
}
|
|
276
|
+
chunks.push(chunk);
|
|
277
|
+
});
|
|
278
|
+
req.on('end', () => {
|
|
279
|
+
if (tooLarge) {
|
|
280
|
+
reject(new RequestBodyTooLargeError());
|
|
281
|
+
return;
|
|
282
|
+
}
|
|
283
|
+
if (chunks.length === 0) {
|
|
284
|
+
resolve({});
|
|
285
|
+
return;
|
|
286
|
+
}
|
|
287
|
+
try {
|
|
288
|
+
const parsed = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
289
|
+
resolve(isRecord(parsed) ? parsed : {});
|
|
290
|
+
}
|
|
291
|
+
catch {
|
|
292
|
+
reject(new Error('Request body is not valid JSON.'));
|
|
293
|
+
}
|
|
294
|
+
});
|
|
295
|
+
req.on('error', reject);
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
function asString(value) {
|
|
299
|
+
return typeof value === 'string' ? value : undefined;
|
|
300
|
+
}
|
|
301
|
+
function asNumber(value) {
|
|
302
|
+
return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
|
|
303
|
+
}
|
|
304
|
+
function asBoolean(value) {
|
|
305
|
+
return typeof value === 'boolean' ? value : undefined;
|
|
306
|
+
}
|
|
307
|
+
function asStringArray(value) {
|
|
308
|
+
if (!Array.isArray(value))
|
|
309
|
+
return undefined;
|
|
310
|
+
return value.every((v) => typeof v === 'string') ? value : undefined;
|
|
311
|
+
}
|
|
312
|
+
/**
|
|
313
|
+
* The bounds a grid is held to wherever it is asked for, so `start` and
|
|
314
|
+
* `resize` cannot disagree about what a legal grid is. An absent side is the
|
|
315
|
+
* session default and is not checked.
|
|
316
|
+
*/
|
|
317
|
+
const MIN_GRID_SIDE = 2;
|
|
318
|
+
const MAX_GRID_COLS = 1_000;
|
|
319
|
+
const MAX_GRID_ROWS = 500;
|
|
320
|
+
const GRID_BOUNDS_ERROR = 'cols must be an integer from 2 to 1000 and rows from 2 to 500.';
|
|
321
|
+
function gridOutOfBounds(cols, rows) {
|
|
322
|
+
if (cols !== undefined &&
|
|
323
|
+
(!Number.isInteger(cols) || cols < MIN_GRID_SIDE || cols > MAX_GRID_COLS)) {
|
|
324
|
+
return true;
|
|
325
|
+
}
|
|
326
|
+
return (rows !== undefined &&
|
|
327
|
+
(!Number.isInteger(rows) || rows < MIN_GRID_SIDE || rows > MAX_GRID_ROWS));
|
|
328
|
+
}
|
|
329
|
+
/**
|
|
330
|
+
* What is wrong with the SHAPE of a start request, in words, or null.
|
|
331
|
+
*
|
|
332
|
+
* A field that is present but of the wrong type is refused rather than
|
|
333
|
+
* replaced by a default: a caller with a bug in its own serialisation
|
|
334
|
+
* (`{cols: "80", rows: "24", args: 4}`) is told so, not handed a session at
|
|
335
|
+
* the default grid with no arguments. An absent field takes its default;
|
|
336
|
+
* only present-and-wrong is refused.
|
|
337
|
+
*/
|
|
338
|
+
/**
|
|
339
|
+
* Scrollback read over a screen whose reasoning is being hidden: a reasoning
|
|
340
|
+
* block whose first line has scrolled above what is returned is still
|
|
341
|
+
* recognised where it carries on into it (`reasoning.ts`).
|
|
342
|
+
*/
|
|
343
|
+
const REASONING_CONTEXT_LINES = 400;
|
|
344
|
+
/** How far back `terminal_result` looks for the latest turn and its answer. */
|
|
345
|
+
const RESULT_LINES = 3000;
|
|
346
|
+
/** Why a signature could not read a screen just now. */
|
|
347
|
+
function overBudgetMessage(signature) {
|
|
348
|
+
return (`The ${signature.name} signature ran past the regular-expression time budget and is set ` +
|
|
349
|
+
'aside for a minute, so the screen is not returned filtered. Try again shortly.');
|
|
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
|
+
}
|
|
359
|
+
/**
|
|
360
|
+
* A query flag: absent, `0` or `false` is off, `1` or `true` is on, and
|
|
361
|
+
* anything else is null, a mistake the caller is refused for. A flag that
|
|
362
|
+
* guards what leaves the daemon must never read a misspelt "on" as off.
|
|
363
|
+
*/
|
|
364
|
+
function queryFlag(url, name) {
|
|
365
|
+
const value = url.searchParams.get(name);
|
|
366
|
+
if (value === null || value === '0' || value === 'false')
|
|
367
|
+
return false;
|
|
368
|
+
if (value === '1' || value === 'true')
|
|
369
|
+
return true;
|
|
370
|
+
return null;
|
|
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
|
+
}
|
|
382
|
+
const BAD_HIDE_REASONING = 'hideReasoning must be true or false (or 1 or 0).';
|
|
383
|
+
/**
|
|
384
|
+
* The cursor among the lines a filtered screen returns: on its own row when
|
|
385
|
+
* that row is kept, on the marker of the block that hid it otherwise.
|
|
386
|
+
*/
|
|
387
|
+
function filteredCursor(cursor, filtered) {
|
|
388
|
+
let y = 0;
|
|
389
|
+
for (let k = 0; k < filtered.rows.length; k++) {
|
|
390
|
+
if (filtered.rows[k] <= cursor.y)
|
|
391
|
+
y = k;
|
|
392
|
+
else
|
|
393
|
+
break;
|
|
394
|
+
}
|
|
395
|
+
const kept = filtered.rows[y] === cursor.y && filtered.markers[y] !== true;
|
|
396
|
+
return { x: kept ? cursor.x : 0, y };
|
|
397
|
+
}
|
|
398
|
+
function startShapeError(body) {
|
|
399
|
+
const checks = [
|
|
400
|
+
['agent', (value) => typeof value === 'string', 'a string'],
|
|
401
|
+
[
|
|
402
|
+
'args',
|
|
403
|
+
(value) => Array.isArray(value) && value.every((entry) => typeof entry === 'string'),
|
|
404
|
+
'an array of strings',
|
|
405
|
+
],
|
|
406
|
+
['cwd', (value) => typeof value === 'string', 'a string'],
|
|
407
|
+
['cols', (value) => typeof value === 'number', 'a number'],
|
|
408
|
+
['rows', (value) => typeof value === 'number', 'a number'],
|
|
409
|
+
['hold', (value) => typeof value === 'boolean', 'a boolean'],
|
|
410
|
+
['openViewer', (value) => typeof value === 'boolean', 'a boolean'],
|
|
411
|
+
['shell', (value) => typeof value === 'boolean', 'a boolean'],
|
|
412
|
+
['label', (value) => typeof value === 'string', 'a string'],
|
|
413
|
+
['purpose', (value) => typeof value === 'string', 'a string'],
|
|
414
|
+
['readyText', (value) => typeof value === 'string', 'a string'],
|
|
415
|
+
[
|
|
416
|
+
'readyQuiet',
|
|
417
|
+
(value) => typeof value === 'number' && Number.isFinite(value) && value >= 0,
|
|
418
|
+
'a non-negative number of milliseconds',
|
|
419
|
+
],
|
|
420
|
+
];
|
|
421
|
+
for (const [field, accepts, expected] of checks) {
|
|
422
|
+
if (body[field] !== undefined && !accepts(body[field])) {
|
|
423
|
+
return `${field} must be ${expected}.`;
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
// The session's own variables, by name and value (§4.6). A refusal names the
|
|
427
|
+
// variable but never quotes its value: the values are secrets more often
|
|
428
|
+
// than not, and errors travel back to callers and into logs.
|
|
429
|
+
const env = body['env'];
|
|
430
|
+
if (env !== undefined) {
|
|
431
|
+
if (typeof env !== 'object' || env === null || Array.isArray(env)) {
|
|
432
|
+
return 'env must be an object mapping variable names to string values.';
|
|
433
|
+
}
|
|
434
|
+
for (const [name, value] of Object.entries(env)) {
|
|
435
|
+
if (!ENV_NAME_PATTERN.test(name)) {
|
|
436
|
+
return `env name ${JSON.stringify(name)} must be letters, digits and underscores, not starting with a digit.`;
|
|
437
|
+
}
|
|
438
|
+
if (typeof value !== 'string' || value.includes('\0')) {
|
|
439
|
+
return `env value for ${name} must be a string with no NUL characters.`;
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
return null;
|
|
444
|
+
}
|
|
445
|
+
export class Daemon {
|
|
446
|
+
options;
|
|
447
|
+
logger;
|
|
448
|
+
tokens = new TokenStore();
|
|
449
|
+
manager;
|
|
450
|
+
server;
|
|
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
|
+
});
|
|
459
|
+
sockets = new Set();
|
|
460
|
+
/** Every watcher of a session, with the gate that orders its stream across snapshots. */
|
|
461
|
+
sessionSockets = new Map();
|
|
462
|
+
/** Frozen replay bytes belong only to the screenshot's one-use viewer grant. */
|
|
463
|
+
captureSnapshots = new Map();
|
|
464
|
+
/**
|
|
465
|
+
* The viewport currently driving each session's grid (§5).
|
|
466
|
+
*
|
|
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.
|
|
475
|
+
*/
|
|
476
|
+
geometryController = new Map();
|
|
477
|
+
/** A dashboard document keeps its grid while a covered pane reconnects. */
|
|
478
|
+
dashboardGeometryOwner = new Map();
|
|
479
|
+
/** Subscribers to the daemon-wide event stream (`/events`). */
|
|
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;
|
|
494
|
+
/**
|
|
495
|
+
* Per-session prompt tracking for stall alerts: the signature of the prompt
|
|
496
|
+
* currently on screen, when it was first seen and whether it has alerted.
|
|
497
|
+
*/
|
|
498
|
+
promptStates = new Map();
|
|
499
|
+
version = packageVersion();
|
|
500
|
+
sessionFeed;
|
|
501
|
+
portValue = null;
|
|
502
|
+
waitsInFlight = 0;
|
|
503
|
+
lastActivity = Date.now();
|
|
504
|
+
idleTimer = null;
|
|
505
|
+
raceCheckTimer = null;
|
|
506
|
+
statePublishTimer = null;
|
|
507
|
+
statePublishRunning = false;
|
|
508
|
+
/** What this daemon published in daemon.json, once it has claimed it. */
|
|
509
|
+
publishedState = null;
|
|
510
|
+
/** The pid of another running daemon already reported as owning daemon.json. */
|
|
511
|
+
foreignOwnerReported = null;
|
|
512
|
+
promptScanTimer = null;
|
|
513
|
+
promptGraceTimers = new Map();
|
|
514
|
+
promptScanRunning = false;
|
|
515
|
+
stopPromise = null;
|
|
516
|
+
audit;
|
|
517
|
+
/**
|
|
518
|
+
* What sessions get from the daemon's environment (ADR-008), resolved once so
|
|
519
|
+
* that what the daemon reports is what its sessions get.
|
|
520
|
+
*/
|
|
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();
|
|
539
|
+
constructor(options) {
|
|
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 };
|
|
543
|
+
this.logger = options.logger;
|
|
544
|
+
this.audit = options.audit ?? NULL_AUDITOR;
|
|
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);
|
|
549
|
+
this.manager = new SessionManager(compilePolicy(options.policy), this.logger, {
|
|
550
|
+
sessionEnv: this.sessionEnv,
|
|
551
|
+
}, (id) => this.sessionFeed.remove(id));
|
|
552
|
+
this.sessionFeed = new SessionFeed(this.version, () => this.listedSummaries().map((summary) => this.summaryWithPrompt(summary)), this.logger);
|
|
553
|
+
this.server = http.createServer((req, res) => {
|
|
554
|
+
this.handleRequest(req, res).catch((error) => {
|
|
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
|
+
});
|
|
563
|
+
if (!res.headersSent)
|
|
564
|
+
json(res, 500, { error: 'The daemon hit an unexpected error handling this request. Its daemon.log records the error.' });
|
|
565
|
+
});
|
|
566
|
+
});
|
|
567
|
+
this.server.on('upgrade', (req, socket, head) => {
|
|
568
|
+
this.handleUpgrade(req, socket, head);
|
|
569
|
+
});
|
|
570
|
+
}
|
|
571
|
+
get port() {
|
|
572
|
+
if (this.portValue === null)
|
|
573
|
+
throw new Error('Daemon not started.');
|
|
574
|
+
return this.portValue;
|
|
575
|
+
}
|
|
576
|
+
/** Clock for dashboard grant expiry. Tests inject one; otherwise wall time. */
|
|
577
|
+
now() {
|
|
578
|
+
return this.options.now?.() ?? Date.now();
|
|
579
|
+
}
|
|
580
|
+
get token() {
|
|
581
|
+
return this.tokens.token;
|
|
582
|
+
}
|
|
583
|
+
get connectedSockets() {
|
|
584
|
+
return this.sockets.size;
|
|
585
|
+
}
|
|
586
|
+
/**
|
|
587
|
+
* How many waits are polling right now. A counter rather than a log line,
|
|
588
|
+
* because `core/` and `client/` may not write to a stream and a test needs
|
|
589
|
+
* to see that a wait whose caller has gone actually stopped.
|
|
590
|
+
*/
|
|
591
|
+
get waitsPolling() {
|
|
592
|
+
return this.waitsInFlight;
|
|
593
|
+
}
|
|
594
|
+
get liveSessions() {
|
|
595
|
+
return this.manager.liveCount();
|
|
596
|
+
}
|
|
597
|
+
/** Subscribe inside the daemon to the dashboard's session feed. */
|
|
598
|
+
subscribeDashboardFeed(listener) {
|
|
599
|
+
return this.sessionFeed.subscribe(listener);
|
|
600
|
+
}
|
|
601
|
+
// ------------------------------------------------------------------ start
|
|
602
|
+
async start() {
|
|
603
|
+
const { home } = this.options;
|
|
604
|
+
const homeResult = await ensureHome(home);
|
|
605
|
+
if (homeResult.warning !== undefined) {
|
|
606
|
+
this.logger.warn('home hardening warning', { warning: homeResult.warning });
|
|
607
|
+
}
|
|
608
|
+
// Defer to an incumbent that is running, even one too busy to answer its
|
|
609
|
+
// health check; clear a record whose daemon has gone (design §2.3).
|
|
610
|
+
const existing = readDaemonState(home);
|
|
611
|
+
if (existing !== null) {
|
|
612
|
+
if (await this.incumbentRunning(existing))
|
|
613
|
+
throw new AlreadyRunningError(existing);
|
|
614
|
+
this.logger.info('clearing stale daemon state', { stalePid: existing.pid });
|
|
615
|
+
removeDaemonStateIf(home, existing);
|
|
616
|
+
}
|
|
617
|
+
await new Promise((resolve, reject) => {
|
|
618
|
+
this.server.once('error', reject);
|
|
619
|
+
this.server.listen(0, '127.0.0.1', () => {
|
|
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
|
+
});
|
|
628
|
+
resolve();
|
|
629
|
+
});
|
|
630
|
+
});
|
|
631
|
+
const address = this.server.address();
|
|
632
|
+
if (address === null || typeof address === 'string') {
|
|
633
|
+
throw new Error('Failed to determine bound port.');
|
|
634
|
+
}
|
|
635
|
+
this.portValue = address.port;
|
|
636
|
+
// Browser detection is slow the first time it runs (viewerLauncher.ts), and
|
|
637
|
+
// a session start waits for its viewer launch, so look once now and let the
|
|
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);
|
|
642
|
+
}
|
|
643
|
+
const state = {
|
|
644
|
+
port: this.portValue,
|
|
645
|
+
token: this.tokens.token,
|
|
646
|
+
pid: process.pid,
|
|
647
|
+
version: this.version,
|
|
648
|
+
startedAt: new Date().toISOString(),
|
|
649
|
+
startedWrapped: this.options.startedWrapped ?? false,
|
|
650
|
+
};
|
|
651
|
+
// Atomic claim; on losing the race, defer to the winner (design §2.2:
|
|
652
|
+
// the race is normal, not exceptional). A file that holds no record at all,
|
|
653
|
+
// such as an emptied one, is cleared like a stale record.
|
|
654
|
+
if (!claimDaemonState(home, state)) {
|
|
655
|
+
const winner = inspectDaemonState(home);
|
|
656
|
+
if (winner.kind === 'record' && (await this.incumbentRunning(winner.state))) {
|
|
657
|
+
await this.closeServerOnly();
|
|
658
|
+
throw new AlreadyRunningError(winner.state);
|
|
659
|
+
}
|
|
660
|
+
if (winner.kind === 'record')
|
|
661
|
+
removeDaemonStateIf(home, winner.state);
|
|
662
|
+
if (winner.kind === 'not-a-record') {
|
|
663
|
+
this.logger.warn('clearing a daemon.json that holds no daemon record', {
|
|
664
|
+
length: winner.raw.length,
|
|
665
|
+
});
|
|
666
|
+
removeDaemonStateIfNotARecord(home, winner.raw);
|
|
667
|
+
}
|
|
668
|
+
if (!claimDaemonState(home, state)) {
|
|
669
|
+
await this.closeServerOnly();
|
|
670
|
+
throw new Error(`Could not claim ${daemonStatePath(home)}: it could not be read, or another ` +
|
|
671
|
+
`daemon claimed it first.`);
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
// Belt and braces for the unlink/claim TOCTOU sliver: shortly after
|
|
675
|
+
// start-up, if the published record names someone else and nobody is
|
|
676
|
+
// attached to us, bow out quietly. Clients only ever discover the daemon
|
|
677
|
+
// named in the file, so nobody can be depending on us yet.
|
|
678
|
+
this.raceCheckTimer = setTimeout(() => {
|
|
679
|
+
const current = readDaemonState(home);
|
|
680
|
+
if (current !== null &&
|
|
681
|
+
current.pid !== process.pid &&
|
|
682
|
+
this.manager.size() === 0 &&
|
|
683
|
+
this.sockets.size === 0) {
|
|
684
|
+
this.logger.info('lost start-up race after claim, stopping', {
|
|
685
|
+
winnerPid: current.pid,
|
|
686
|
+
});
|
|
687
|
+
void this.stop({ removeState: false }).then(() => {
|
|
688
|
+
this.options.onSelfStop?.('lost-race');
|
|
689
|
+
});
|
|
690
|
+
}
|
|
691
|
+
}, 1_000);
|
|
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);
|
|
697
|
+
// Said once, at start, because passthrough leaks silently otherwise
|
|
698
|
+
// (ADR-008): the names only, never the values.
|
|
699
|
+
const { exposed } = this.environmentReport();
|
|
700
|
+
if (exposed.length > 0) {
|
|
701
|
+
this.logger.warn('sessionEnv "passthrough" hands every session the daemon environment, including ' +
|
|
702
|
+
'these variables whose names look like credentials; use "clean" or a list to keep them out', { names: exposed });
|
|
703
|
+
}
|
|
704
|
+
this.publishedState = state;
|
|
705
|
+
this.statePublishTimer = setInterval(() => {
|
|
706
|
+
void this.keepStatePublished();
|
|
707
|
+
}, this.options.statePublishCheckMs ?? STATE_PUBLISH_CHECK_MS);
|
|
708
|
+
this.statePublishTimer.unref();
|
|
709
|
+
const idleMs = this.options.idleMs ?? DEFAULT_IDLE_MS;
|
|
710
|
+
this.idleTimer = setInterval(() => {
|
|
711
|
+
// Reap sessions whose grace has lapsed before judging idleness. A
|
|
712
|
+
// rejected sweep must be caught here, or it becomes an
|
|
713
|
+
// unhandledRejection and the handler in index.ts stops the daemon.
|
|
714
|
+
this.sweepExited().catch((error) => {
|
|
715
|
+
this.logger.warn('exited-session sweep failed', { error: String(error) });
|
|
716
|
+
});
|
|
717
|
+
// Never exit while any session is live: an unattended agent run with no
|
|
718
|
+
// connected clients is a core use case, not idleness (design §2.3).
|
|
719
|
+
if (this.manager.liveCount() === 0 &&
|
|
720
|
+
this.sockets.size === 0 &&
|
|
721
|
+
Date.now() - this.lastActivity > idleMs) {
|
|
722
|
+
this.logger.info('idle shutdown', { idleMs });
|
|
723
|
+
void this.stop().then(() => {
|
|
724
|
+
this.options.onSelfStop?.('idle');
|
|
725
|
+
});
|
|
726
|
+
}
|
|
727
|
+
}, this.options.idleCheckIntervalMs ?? IDLE_CHECK_INTERVAL_MS);
|
|
728
|
+
this.idleTimer.unref();
|
|
729
|
+
// Prompt-stall scanner: overlap-guarded because snapshots are
|
|
730
|
+
// async: a slow render must skip a beat, never queue a backlog.
|
|
731
|
+
this.promptScanTimer = setInterval(() => {
|
|
732
|
+
if (this.promptScanRunning)
|
|
733
|
+
return;
|
|
734
|
+
this.promptScanRunning = true;
|
|
735
|
+
this.scanForPromptStalls()
|
|
736
|
+
.catch((error) => {
|
|
737
|
+
this.logger.warn('prompt scan failed', { error: String(error) });
|
|
738
|
+
})
|
|
739
|
+
.finally(() => {
|
|
740
|
+
this.promptScanRunning = false;
|
|
741
|
+
});
|
|
742
|
+
}, this.options.promptScanIntervalMs ?? PROMPT_SCAN_INTERVAL_MS);
|
|
743
|
+
this.promptScanTimer.unref();
|
|
744
|
+
this.logger.info('daemon started', {
|
|
745
|
+
port: this.portValue,
|
|
746
|
+
pid: process.pid,
|
|
747
|
+
version: this.version,
|
|
748
|
+
});
|
|
749
|
+
return { port: this.portValue, token: this.tokens.token };
|
|
750
|
+
}
|
|
751
|
+
/**
|
|
752
|
+
* Whether the daemon a record names is running, so that this one must
|
|
753
|
+
* defer to it: one that answers its health check, or one whose process is
|
|
754
|
+
* alive and whose port accepts a connection although it is too busy to
|
|
755
|
+
* answer. A record naming this very daemon is not an incumbent, and one
|
|
756
|
+
* naming this process that does not answer is a leftover from an earlier
|
|
757
|
+
* process that had the same pid.
|
|
758
|
+
*/
|
|
759
|
+
async incumbentRunning(record) {
|
|
760
|
+
if (record.pid === process.pid && record.port === this.portValue)
|
|
761
|
+
return false;
|
|
762
|
+
if (await this.isHealthy(record.port))
|
|
763
|
+
return true;
|
|
764
|
+
if (record.pid === process.pid)
|
|
765
|
+
return false;
|
|
766
|
+
if (await daemonRunning(record)) {
|
|
767
|
+
this.logger.info('deferring to a running daemon that did not answer its health check', {
|
|
768
|
+
pid: record.pid,
|
|
769
|
+
port: record.port,
|
|
770
|
+
});
|
|
771
|
+
return true;
|
|
772
|
+
}
|
|
773
|
+
return false;
|
|
774
|
+
}
|
|
775
|
+
/**
|
|
776
|
+
* Keep daemon.json naming this daemon while it runs. When the file is
|
|
777
|
+
* missing, holds no daemon record or names a daemon that has gone, publish
|
|
778
|
+
* it again, so new clients can still reach this daemon's sessions. When it
|
|
779
|
+
* names another daemon that is running, leave it, but say so once in
|
|
780
|
+
* daemon.log: new clients reach that daemon, and this one's sessions only
|
|
781
|
+
* through clients already connected. A file that cannot be read is left
|
|
782
|
+
* alone, since a failed read says nothing about what it holds.
|
|
783
|
+
*/
|
|
784
|
+
async keepStatePublished() {
|
|
785
|
+
const published = this.publishedState;
|
|
786
|
+
if (published === null || this.stopPromise !== null || this.statePublishRunning)
|
|
787
|
+
return;
|
|
788
|
+
this.statePublishRunning = true;
|
|
789
|
+
try {
|
|
790
|
+
const { home } = this.options;
|
|
791
|
+
const file = inspectDaemonState(home);
|
|
792
|
+
if (file.kind === 'unreadable')
|
|
793
|
+
return;
|
|
794
|
+
if (file.kind === 'record') {
|
|
795
|
+
const current = file.state;
|
|
796
|
+
if (current.pid === published.pid && current.port === published.port) {
|
|
797
|
+
this.foreignOwnerReported = null;
|
|
798
|
+
return;
|
|
799
|
+
}
|
|
800
|
+
if (await daemonRunning(current)) {
|
|
801
|
+
if (this.foreignOwnerReported !== current.pid) {
|
|
802
|
+
this.foreignOwnerReported = current.pid;
|
|
803
|
+
this.logger.warn('daemon.json names another running daemon; new clients reach it, not this one', {
|
|
804
|
+
otherPid: current.pid,
|
|
805
|
+
otherPort: current.port,
|
|
806
|
+
sessions: this.manager.size(),
|
|
807
|
+
});
|
|
808
|
+
}
|
|
809
|
+
return;
|
|
810
|
+
}
|
|
811
|
+
removeDaemonStateIf(home, current);
|
|
812
|
+
}
|
|
813
|
+
else if (file.kind === 'not-a-record') {
|
|
814
|
+
removeDaemonStateIfNotARecord(home, file.raw);
|
|
815
|
+
}
|
|
816
|
+
if (this.stopPromise === null && claimDaemonState(home, published)) {
|
|
817
|
+
this.foreignOwnerReported = null;
|
|
818
|
+
this.logger.warn('daemon.json was missing, held no daemon record or named a daemon that has gone; published it again', { pid: published.pid, port: published.port });
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
catch (error) {
|
|
822
|
+
this.logger.warn('checking daemon.json failed', { error: String(error) });
|
|
823
|
+
}
|
|
824
|
+
finally {
|
|
825
|
+
this.statePublishRunning = false;
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
async isHealthy(port) {
|
|
829
|
+
try {
|
|
830
|
+
const response = await fetch(`http://127.0.0.1:${String(port)}/health`, {
|
|
831
|
+
signal: AbortSignal.timeout(1_500),
|
|
832
|
+
});
|
|
833
|
+
if (!response.ok)
|
|
834
|
+
return false;
|
|
835
|
+
const body = await response.json();
|
|
836
|
+
return typeof body === 'object' && body !== null && body.ok === true;
|
|
837
|
+
}
|
|
838
|
+
catch {
|
|
839
|
+
return false;
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
closeServerOnly() {
|
|
843
|
+
return new Promise((resolve) => {
|
|
844
|
+
this.server.close(() => resolve());
|
|
845
|
+
// close() waits for idle connections; nothing is connected this early.
|
|
846
|
+
});
|
|
847
|
+
}
|
|
848
|
+
// ------------------------------------------------------------------- stop
|
|
849
|
+
/**
|
|
850
|
+
* Kill every session's process tree, close everything, remove the state
|
|
851
|
+
* file (unless we lost the race and it now belongs to the winner).
|
|
852
|
+
* The daemon must never exit and strand running agent CLIs (design §2.3).
|
|
853
|
+
*/
|
|
854
|
+
stop(opts = {}) {
|
|
855
|
+
// Idle-stop, signal handlers and explicit stops can overlap, so everyone
|
|
856
|
+
// awaits the one real shutdown.
|
|
857
|
+
if (this.stopPromise === null) {
|
|
858
|
+
this.stopping = true;
|
|
859
|
+
this.stopPromise = this.doStop(opts);
|
|
860
|
+
}
|
|
861
|
+
return this.stopPromise;
|
|
862
|
+
}
|
|
863
|
+
async doStop(opts) {
|
|
864
|
+
if (this.idleTimer !== null)
|
|
865
|
+
clearInterval(this.idleTimer);
|
|
866
|
+
if (this.raceCheckTimer !== null)
|
|
867
|
+
clearTimeout(this.raceCheckTimer);
|
|
868
|
+
if (this.statePublishTimer !== null)
|
|
869
|
+
clearInterval(this.statePublishTimer);
|
|
870
|
+
if (this.promptScanTimer !== null)
|
|
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.'));
|
|
876
|
+
// Stop LISTENING first, before tearing down session trees. Killing process
|
|
877
|
+
// trees is not fast (`taskkill /T` on a loaded machine can take seconds
|
|
878
|
+
// per session), and a daemon that still answers on its port while shutting
|
|
879
|
+
// down looks alive to every client polling /health. `close()` refuses new
|
|
880
|
+
// connections immediately while letting in-flight responses drain on
|
|
881
|
+
// their existing socket, notably the reply to this very shutdown request.
|
|
882
|
+
const listenerClosed = new Promise((resolve) => {
|
|
883
|
+
this.server.close(() => resolve());
|
|
884
|
+
});
|
|
885
|
+
for (const socket of this.sockets) {
|
|
886
|
+
try {
|
|
887
|
+
socket.close();
|
|
888
|
+
}
|
|
889
|
+
catch {
|
|
890
|
+
// Best effort.
|
|
891
|
+
}
|
|
892
|
+
}
|
|
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;
|
|
1833
|
+
}
|
|
1834
|
+
if (error instanceof Error && error.message.startsWith('Request body')) {
|
|
1835
|
+
this.auditDashboardRefusal(req, 'body');
|
|
1836
|
+
json(res, 400, { error: error.message });
|
|
1837
|
+
return;
|
|
1838
|
+
}
|
|
1839
|
+
throw error;
|
|
1840
|
+
}
|
|
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 });
|
|
1850
|
+
}
|
|
1851
|
+
/**
|
|
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`.
|
|
1855
|
+
*/
|
|
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;
|
|
1879
|
+
}
|
|
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 {
|
|
1893
|
+
return false;
|
|
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)
|
|
1898
|
+
return false;
|
|
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 };
|
|
1961
|
+
}
|
|
1962
|
+
async handleRequest(req, res) {
|
|
1963
|
+
res.setHeader('Referrer-Policy', 'no-referrer');
|
|
1964
|
+
// DNS-rebinding defence (design §4.2): a browser on any website can make
|
|
1965
|
+
// requests reach a loopback port; the Host header gives the rebind away.
|
|
1966
|
+
if (!this.hostAllowed(req.headers.host)) {
|
|
1967
|
+
if (pathOnly(req.url).startsWith('/dashboard'))
|
|
1968
|
+
this.auditDashboardRefusal(req, 'host');
|
|
1969
|
+
json(res, 403, { error: 'Forbidden: unexpected Host header.' });
|
|
1970
|
+
return;
|
|
1971
|
+
}
|
|
1972
|
+
const url = new URL(req.url ?? '/', `http://127.0.0.1:${String(this.portValue ?? 0)}`);
|
|
1973
|
+
const segments = url.pathname.split('/').filter((s) => s !== '');
|
|
1974
|
+
// Unauthenticated by design (§4.1): clients must be able to poll before
|
|
1975
|
+
// the token file settles, and it reveals nothing sensitive.
|
|
1976
|
+
if (req.method === 'GET' && url.pathname === '/health') {
|
|
1977
|
+
json(res, 200, { ok: true, version: this.version, pid: process.pid });
|
|
1978
|
+
return;
|
|
1979
|
+
}
|
|
1980
|
+
// The viewer page itself is served without auth, and must stay that way:
|
|
1981
|
+
// refusing it would tell an unauthenticated caller which session ids
|
|
1982
|
+
// exist. The page holds no secrets either.
|
|
1983
|
+
//
|
|
1984
|
+
// What DOES happen here is the one-use exchange (§4.1): a `vt` in the
|
|
1985
|
+
// query is redeemed, once, for a stream credential delivered as an
|
|
1986
|
+
// HttpOnly cookie. After this the URL is inert, the page's own scripts
|
|
1987
|
+
// never see a credential and the browser attaches the cookie to the
|
|
1988
|
+
// WebSocket upgrade by itself. An absent, stale or already-redeemed grant
|
|
1989
|
+
// is NOT an error here: the page loads and then reports that it could not
|
|
1990
|
+
// connect, which keeps this route's silence about session ids intact.
|
|
1991
|
+
if (req.method === 'GET' && segments[0] === 'view') {
|
|
1992
|
+
const headers = {
|
|
1993
|
+
'content-type': 'text/html; charset=utf-8',
|
|
1994
|
+
'cache-control': 'no-store',
|
|
1995
|
+
// `style-src 'unsafe-inline'` is required: xterm.js sizes
|
|
1996
|
+
// rows, the cursor and its character-measurement element with inline
|
|
1997
|
+
// styles, and a real browser reported ten CSP violations per load
|
|
1998
|
+
// without it. Scripts stay strict under `default-src 'self'`: inline
|
|
1999
|
+
// styles cannot execute code, and terminal output never reaches the
|
|
2000
|
+
// DOM as markup (xterm renders it as text).
|
|
2001
|
+
'content-security-policy': PAGE_CSP,
|
|
2002
|
+
};
|
|
2003
|
+
const redeemed = this.tokens.redeemViewerGrant(url.searchParams.get('vt'));
|
|
2004
|
+
if (redeemed !== null) {
|
|
2005
|
+
const frozen = this.captureSnapshots.get(url.searchParams.get('vt') ?? '');
|
|
2006
|
+
if (frozen !== undefined)
|
|
2007
|
+
frozen.streamToken = redeemed.streamToken;
|
|
2008
|
+
headers['set-cookie'] = viewerCookie(redeemed.sessionId, redeemed.streamToken);
|
|
2009
|
+
this.audit.record('viewer', 'grant-redeem', redeemed.sessionId, {
|
|
2010
|
+
readOnly: redeemed.readOnly,
|
|
2011
|
+
});
|
|
2012
|
+
// The grant says which session this is for; `s=` is only how the page
|
|
2013
|
+
// learns it. A link whose `s=` had been edited would otherwise spend
|
|
2014
|
+
// its grant on a page that then asks for the wrong stream.
|
|
2015
|
+
if (url.searchParams.get('s') !== redeemed.sessionId) {
|
|
2016
|
+
headers['location'] = `/view?s=${encodeURIComponent(redeemed.sessionId)}`;
|
|
2017
|
+
res.writeHead(302, headers);
|
|
2018
|
+
res.end();
|
|
2019
|
+
return;
|
|
2020
|
+
}
|
|
2021
|
+
}
|
|
2022
|
+
res.writeHead(200, headers);
|
|
2023
|
+
res.end(fs.readFileSync(viewerHtmlPath));
|
|
2024
|
+
return;
|
|
2025
|
+
}
|
|
2026
|
+
// Browsers request this unprompted, before any <link rel="icon"> is parsed,
|
|
2027
|
+
// and a Chrome --app window asks for it when it builds the taskbar
|
|
2028
|
+
// button. Serving the real mark here is what stops that button falling
|
|
2029
|
+
// back to the generic globe.
|
|
2030
|
+
if (req.method === 'GET' && url.pathname === '/favicon.ico') {
|
|
2031
|
+
res.writeHead(200, { 'content-type': 'image/png', 'cache-control': 'no-store' });
|
|
2032
|
+
res.end(fs.readFileSync(path.join(viewerDir, 'icon-32.png')));
|
|
2033
|
+
return;
|
|
2034
|
+
}
|
|
2035
|
+
if (req.method === 'GET') {
|
|
2036
|
+
const asset = STATIC_ASSETS[url.pathname];
|
|
2037
|
+
if (asset !== undefined) {
|
|
2038
|
+
res.writeHead(200, {
|
|
2039
|
+
// charset belongs on text only: `image/png; charset=utf-8` is
|
|
2040
|
+
// meaningless, and stating an encoding for binary invites a proxy or
|
|
2041
|
+
// a browser to treat the bytes as text.
|
|
2042
|
+
'content-type': asset.binary === true ? asset.type : `${asset.type}; charset=utf-8`,
|
|
2043
|
+
'cache-control': 'no-store',
|
|
2044
|
+
});
|
|
2045
|
+
res.end(fs.readFileSync(asset.file));
|
|
2046
|
+
return;
|
|
2047
|
+
}
|
|
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
|
+
}
|
|
2078
|
+
const auth = this.tokens.verify(bearerToken(req.headers.authorization));
|
|
2079
|
+
if (auth === null || auth.kind !== 'client') {
|
|
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
|
+
}
|
|
2099
|
+
json(res, 401, { error: 'Unauthorised: a valid client token is required.' });
|
|
2100
|
+
return;
|
|
2101
|
+
}
|
|
2102
|
+
this.lastActivity = Date.now();
|
|
2103
|
+
// Audit actor (design §4.5): adapters self-identify via a header, the MCP
|
|
2104
|
+
// adapter as `mcp:<clientInfo.name>` and the CLI as `cli`. Untrusted input,
|
|
2105
|
+
// so sanitise; it labels log lines and nothing else.
|
|
2106
|
+
const actorHeader = req.headers['x-shellpuppet-actor'];
|
|
2107
|
+
const actor = (typeof actorHeader === 'string'
|
|
2108
|
+
? // eslint-disable-next-line no-control-regex
|
|
2109
|
+
actorHeader.replace(/[\x00-\x1f\x7f]/g, '').slice(0, 64)
|
|
2110
|
+
: '') || 'client';
|
|
2111
|
+
try {
|
|
2112
|
+
if (segments[0] === 'daemon' && segments[1] === 'shutdown' && req.method === 'POST') {
|
|
2113
|
+
const body = await readBody(req);
|
|
2114
|
+
const force = asBoolean(body['force']) ?? false;
|
|
2115
|
+
const live = this.manager.liveCount();
|
|
2116
|
+
if (live > 0 && !force) {
|
|
2117
|
+
json(res, 409, {
|
|
2118
|
+
error: `Refusing to stop: ${String(live)} live session(s). ` +
|
|
2119
|
+
`Pass force to kill them.`,
|
|
2120
|
+
});
|
|
2121
|
+
return;
|
|
2122
|
+
}
|
|
2123
|
+
this.audit.record(actor, 'shutdown', undefined, { force, liveSessions: live });
|
|
2124
|
+
json(res, 200, { ok: true, stopping: true });
|
|
2125
|
+
void this.stop().then(() => {
|
|
2126
|
+
this.options.onSelfStop?.('shutdown-request');
|
|
2127
|
+
});
|
|
2128
|
+
return;
|
|
2129
|
+
}
|
|
2130
|
+
// Behind the token, unlike /health: names of credential-shaped
|
|
2131
|
+
// variables are not for anyone who can reach the port.
|
|
2132
|
+
if (req.method === 'GET' && segments.length === 1 && segments[0] === 'environment') {
|
|
2133
|
+
json(res, 200, this.environmentReport());
|
|
2134
|
+
return;
|
|
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
|
+
}
|
|
2144
|
+
if (segments[0] !== 'sessions') {
|
|
2145
|
+
json(res, 404, { error: 'Not found.', path: url.pathname });
|
|
2146
|
+
return;
|
|
2147
|
+
}
|
|
2148
|
+
if (req.method === 'GET' && segments.length === 1) {
|
|
2149
|
+
this.writeSessionList(res, url);
|
|
2150
|
+
return;
|
|
2151
|
+
}
|
|
2152
|
+
if (req.method === 'POST' && segments.length === 1) {
|
|
2153
|
+
await this.handleStart(req, res, actor);
|
|
2154
|
+
return;
|
|
2155
|
+
}
|
|
2156
|
+
if (req.method === 'GET' && segments.length === 2 && segments[1] === 'wait') {
|
|
2157
|
+
await this.waitAcrossSessions(res, url);
|
|
2158
|
+
return;
|
|
2159
|
+
}
|
|
2160
|
+
const id = segments[1] ?? '';
|
|
2161
|
+
const session = this.manager.get(id);
|
|
2162
|
+
if (session === undefined) {
|
|
2163
|
+
json(res, 404, { error: `No such session: ${id}` });
|
|
2164
|
+
return;
|
|
2165
|
+
}
|
|
2166
|
+
if (req.method === 'DELETE' && segments.length === 2) {
|
|
2167
|
+
this.audit.record(actor, 'kill', id);
|
|
2168
|
+
await this.manager.kill(id);
|
|
2169
|
+
this.dropSessionArtifacts(id);
|
|
2170
|
+
json(res, 200, { ok: true, killed: id });
|
|
2171
|
+
return;
|
|
2172
|
+
}
|
|
2173
|
+
const action = segments[2];
|
|
2174
|
+
// A fresh viewer link (§4.1). Grants are one-use and short-lived, so
|
|
2175
|
+
// there has to be a way to get another without restarting the session:
|
|
2176
|
+
// the human closed the window, the link expired unopened or a second
|
|
2177
|
+
// device wants its own. Client token only: a viewer cannot mint itself
|
|
2178
|
+
// a new credential, let alone a wider one.
|
|
2179
|
+
if (req.method === 'POST' && action === 'viewer') {
|
|
2180
|
+
const body = await readBody(req);
|
|
2181
|
+
const readOnly = body['readOnly'] === true;
|
|
2182
|
+
const grant = this.tokens.mintViewerGrant(id, { readOnly });
|
|
2183
|
+
this.audit.record(actor, 'grant-mint', id, { readOnly });
|
|
2184
|
+
json(res, 200, {
|
|
2185
|
+
viewerUrl: this.viewerUrlFor(id, grant),
|
|
2186
|
+
readOnly,
|
|
2187
|
+
expiresInMs: VIEWER_GRANT_TTL_MS,
|
|
2188
|
+
});
|
|
2189
|
+
return;
|
|
2190
|
+
}
|
|
2191
|
+
// A picture of the viewer, as a browser draws it (§5). The daemon's
|
|
2192
|
+
// text snapshot is what the agent reads; this is what the human sees,
|
|
2193
|
+
// and the two can disagree in ways no text-level check can catch.
|
|
2194
|
+
// Also the faithful way to illustrate documentation.
|
|
2195
|
+
if (req.method === 'POST' && action === 'screenshot') {
|
|
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;
|
|
2205
|
+
// Absent means the default; present and not a number is a mistake to
|
|
2206
|
+
// report, not to paper over with the default.
|
|
2207
|
+
const width = body['width'] === undefined ? CAPTURE_WIDTH : asNumber(body['width']);
|
|
2208
|
+
const height = body['height'] === undefined ? CAPTURE_HEIGHT : asNumber(body['height']);
|
|
2209
|
+
if (width === undefined ||
|
|
2210
|
+
height === undefined ||
|
|
2211
|
+
!Number.isInteger(width) ||
|
|
2212
|
+
!Number.isInteger(height) ||
|
|
2213
|
+
width < 200 ||
|
|
2214
|
+
width > 4_000 ||
|
|
2215
|
+
height < 200 ||
|
|
2216
|
+
height > 4_000) {
|
|
2217
|
+
json(res, 400, { error: 'width and height must be integers between 200 and 4000.' });
|
|
2218
|
+
return;
|
|
2219
|
+
}
|
|
2220
|
+
// A caller who knows its machine is slow, or wants to fail faster,
|
|
2221
|
+
// can say how long a capture may take, within these bounds.
|
|
2222
|
+
const timeoutMs = body['timeoutMs'] === undefined
|
|
2223
|
+
? DEFAULT_CAPTURE_TIMEOUT_MS
|
|
2224
|
+
: asNumber(body['timeoutMs']);
|
|
2225
|
+
if (timeoutMs === undefined ||
|
|
2226
|
+
!Number.isInteger(timeoutMs) ||
|
|
2227
|
+
timeoutMs < MIN_CAPTURE_TIMEOUT_MS ||
|
|
2228
|
+
timeoutMs > MAX_CAPTURE_TIMEOUT_MS) {
|
|
2229
|
+
json(res, 400, {
|
|
2230
|
+
error: `timeoutMs must be an integer between ${String(MIN_CAPTURE_TIMEOUT_MS)} and ` +
|
|
2231
|
+
`${String(MAX_CAPTURE_TIMEOUT_MS)}.`,
|
|
2232
|
+
});
|
|
2233
|
+
return;
|
|
2234
|
+
}
|
|
2235
|
+
const browser = await findBrowser(this.options.viewer?.browserPath, this.logger);
|
|
2236
|
+
if (browser === null) {
|
|
2237
|
+
// No silent fallback to re-rendering the cells ourselves: that would
|
|
2238
|
+
// return a picture of what the daemon thinks, labelled as what the
|
|
2239
|
+
// browser drew, which is exactly the disagreement this exists to find.
|
|
2240
|
+
json(res, 503, {
|
|
2241
|
+
error: 'No Chromium-family browser found, so the viewer cannot be photographed. ' +
|
|
2242
|
+
'Install one, or set viewer.browserPath in config.json.',
|
|
2243
|
+
});
|
|
2244
|
+
return;
|
|
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
|
+
}
|
|
2270
|
+
// Read-only, because a photograph must not be able to type into the
|
|
2271
|
+
// thing it is photographing.
|
|
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
|
+
});
|
|
2278
|
+
try {
|
|
2279
|
+
const capture = await (this.options.capture ?? captureViewer)({
|
|
2280
|
+
browser,
|
|
2281
|
+
viewerUrl: this.viewerUrlFor(id, grant),
|
|
2282
|
+
width,
|
|
2283
|
+
height,
|
|
2284
|
+
timeoutMs,
|
|
2285
|
+
profileRoot: captureProfileRoot(this.options.home),
|
|
2286
|
+
...(redactedRows === undefined ? {} : { hiddenRows: [...redactedRows.keys()] }),
|
|
2287
|
+
logger: this.logger,
|
|
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
|
+
}
|
|
2299
|
+
this.audit.record(actor, 'screenshot', id, { width, height });
|
|
2300
|
+
json(res, 200, {
|
|
2301
|
+
png: capture.png.toString('base64'),
|
|
2302
|
+
// The picture's own dimensions, read from it rather than the request.
|
|
2303
|
+
width: capture.width,
|
|
2304
|
+
height: capture.height,
|
|
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),
|
|
2310
|
+
});
|
|
2311
|
+
}
|
|
2312
|
+
catch (error) {
|
|
2313
|
+
this.logger.warn('screenshot failed', { id, error: String(error) });
|
|
2314
|
+
json(res, 500, {
|
|
2315
|
+
error: `Could not photograph the viewer: ${String(error)}`,
|
|
2316
|
+
});
|
|
2317
|
+
}
|
|
2318
|
+
finally {
|
|
2319
|
+
// The photographer is gone, so its credential goes with it. A human's
|
|
2320
|
+
// viewer keeps theirs until the session ends, because a dropped socket
|
|
2321
|
+
// has to reconnect without a fresh link; a headless browser that has
|
|
2322
|
+
// already closed has nothing to reconnect. In a `finally` because a
|
|
2323
|
+
// capture that failed leaves the same credential behind as one that
|
|
2324
|
+
// worked.
|
|
2325
|
+
this.tokens.revokeViewerGrant(grant);
|
|
2326
|
+
this.captureSnapshots.delete(grant);
|
|
2327
|
+
}
|
|
2328
|
+
return;
|
|
2329
|
+
}
|
|
2330
|
+
if (req.method === 'GET' && action === 'snapshot') {
|
|
2331
|
+
const lastLinesParam = url.searchParams.get('lastLines');
|
|
2332
|
+
let count;
|
|
2333
|
+
if (lastLinesParam !== null) {
|
|
2334
|
+
count = Number(lastLinesParam);
|
|
2335
|
+
if (!Number.isInteger(count) || count < 1 || count > 10_000) {
|
|
2336
|
+
json(res, 400, { error: 'lastLines must be an integer between 1 and 10000.' });
|
|
2337
|
+
return;
|
|
2338
|
+
}
|
|
2339
|
+
}
|
|
2340
|
+
const hide = queryFlag(url, 'hideReasoning');
|
|
2341
|
+
if (hide === null) {
|
|
2342
|
+
json(res, 400, { error: BAD_HIDE_REASONING });
|
|
2343
|
+
return;
|
|
2344
|
+
}
|
|
2345
|
+
if (!hide) {
|
|
2346
|
+
const snapshot = await session.snapshot();
|
|
2347
|
+
json(res, 200, count === undefined ? snapshot : { ...snapshot, lastLines: await session.lastLines(count) });
|
|
2348
|
+
return;
|
|
2349
|
+
}
|
|
2350
|
+
// Fails closed: without a signature to read the screen by, nothing
|
|
2351
|
+
// is returned, never the screen unfiltered.
|
|
2352
|
+
const signature = this.readerFor(session, res);
|
|
2353
|
+
if (signature === null)
|
|
2354
|
+
return;
|
|
2355
|
+
const snapshot = await session.snapshot();
|
|
2356
|
+
const view = await session.styledScreen(REASONING_CONTEXT_LINES);
|
|
2357
|
+
const screen = hideReasoning(view.lines, signature, view.firstVisible);
|
|
2358
|
+
let tail;
|
|
2359
|
+
let tailSource;
|
|
2360
|
+
if (count !== undefined) {
|
|
2361
|
+
tailSource = await session.styledTail(count, REASONING_CONTEXT_LINES);
|
|
2362
|
+
tail = hideReasoning(tailSource.lines, signature, tailSource.firstVisible);
|
|
2363
|
+
}
|
|
2364
|
+
if (screen === null || tail === null) {
|
|
2365
|
+
json(res, 400, { error: overBudgetMessage(signature) });
|
|
2366
|
+
return;
|
|
2367
|
+
}
|
|
2368
|
+
json(res, 200, {
|
|
2369
|
+
...snapshot,
|
|
2370
|
+
screen: markFilteredSelectedOption(screen.lines, view.lines).join('\n'),
|
|
2371
|
+
cursor: filteredCursor(snapshot.cursor, screen),
|
|
2372
|
+
...(tail !== undefined && tailSource !== undefined
|
|
2373
|
+
? { lastLines: markFilteredSelectedOption(tail.lines, tailSource.lines) }
|
|
2374
|
+
: {}),
|
|
2375
|
+
reasoning: {
|
|
2376
|
+
agent: signature.name,
|
|
2377
|
+
hiddenLines: screen.hiddenLines,
|
|
2378
|
+
hiddenBlocks: screen.hiddenBlocks,
|
|
2379
|
+
...(tail !== undefined ? { lastLinesHiddenLines: tail.hiddenLines } : {}),
|
|
2380
|
+
},
|
|
2381
|
+
});
|
|
2382
|
+
return;
|
|
2383
|
+
}
|
|
2384
|
+
if (req.method === 'GET' && action === 'result') {
|
|
2385
|
+
const signature = this.readerFor(session, res);
|
|
2386
|
+
if (signature === null)
|
|
2387
|
+
return;
|
|
2388
|
+
const { lines } = await session.styledTail(RESULT_LINES);
|
|
2389
|
+
json(res, 200, {
|
|
2390
|
+
id: session.id,
|
|
2391
|
+
agent: signature.name,
|
|
2392
|
+
exited: session.exited,
|
|
2393
|
+
exitCode: session.exitCode,
|
|
2394
|
+
...latestResult(lines, signature),
|
|
2395
|
+
});
|
|
2396
|
+
return;
|
|
2397
|
+
}
|
|
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.
|
|
2402
|
+
if ((action === 'input' || action === 'key' || action === 'resize') &&
|
|
2403
|
+
session.exited) {
|
|
2404
|
+
json(res, 409, { error: endedRefusal(id, session.exitCode) });
|
|
2405
|
+
return;
|
|
2406
|
+
}
|
|
2407
|
+
if (req.method === 'POST' && action === 'input') {
|
|
2408
|
+
const body = await readBody(req);
|
|
2409
|
+
const data = asString(body['data']);
|
|
2410
|
+
if (data === undefined) {
|
|
2411
|
+
json(res, 400, { error: 'data (string) is required.' });
|
|
2412
|
+
return;
|
|
2413
|
+
}
|
|
2414
|
+
// Awaited: long input is chunked (Session.write), so verify below must
|
|
2415
|
+
// not read the screen until every chunk has actually been written.
|
|
2416
|
+
// The write resolves with the screen as it was just before this input
|
|
2417
|
+
// went in, which verify compares with, so what was already on screen
|
|
2418
|
+
// cannot make up the typed text's wrapped pieces.
|
|
2419
|
+
//
|
|
2420
|
+
// The exit guard above is not enough on its own: a chunked write spans
|
|
2421
|
+
// real time, so the session can die between the guard and the last
|
|
2422
|
+
// chunk. That is the same "you are writing to a dead session" condition
|
|
2423
|
+
// the guard reports, so it gets the same 409. A 500 would blame the
|
|
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.
|
|
2427
|
+
let before;
|
|
2428
|
+
try {
|
|
2429
|
+
before = await session.write(data);
|
|
2430
|
+
}
|
|
2431
|
+
catch (error) {
|
|
2432
|
+
json(res, 409, {
|
|
2433
|
+
error: error instanceof SessionInputFailedError
|
|
2434
|
+
? error.message
|
|
2435
|
+
: `Session ${id} exited while the input was being written: ${String(error)}`,
|
|
2436
|
+
});
|
|
2437
|
+
return;
|
|
2438
|
+
}
|
|
2439
|
+
// §4.5: content NEVER logged by default, only the length. Keystrokes
|
|
2440
|
+
// are where the secrets are.
|
|
2441
|
+
this.audit.record(actor, 'input', id, {
|
|
2442
|
+
chars: data.length,
|
|
2443
|
+
...(this.audit.captureContent ? { data } : {}),
|
|
2444
|
+
});
|
|
2445
|
+
this.broadcastControl(id, { type: 'input-source', source: 'agent' });
|
|
2446
|
+
// §3.1: TUIs silently swallow input while loading or when a panel has
|
|
2447
|
+
// stolen focus. verify re-reads the screen and reports whether the
|
|
2448
|
+
// text landed (best effort: hidden-input prompts and heavy
|
|
2449
|
+
// transforms legitimately fail it; `escape` is the focus reset).
|
|
2450
|
+
if (asBoolean(body['verify']) === true) {
|
|
2451
|
+
json(res, 200, {
|
|
2452
|
+
ok: true,
|
|
2453
|
+
bytes: data.length,
|
|
2454
|
+
verified: await this.verifyTyped(session, data, before),
|
|
2455
|
+
});
|
|
2456
|
+
return;
|
|
2457
|
+
}
|
|
2458
|
+
json(res, 200, { ok: true, bytes: data.length });
|
|
2459
|
+
return;
|
|
2460
|
+
}
|
|
2461
|
+
if (req.method === 'POST' && action === 'key') {
|
|
2462
|
+
const body = await readBody(req);
|
|
2463
|
+
const key = asString(body['key']);
|
|
2464
|
+
const bytes = key === undefined ? null : keyToBytes(key);
|
|
2465
|
+
if (key === undefined || bytes === null) {
|
|
2466
|
+
json(res, 400, {
|
|
2467
|
+
error: `Unknown key: ${key ?? '(missing)'}. Known keys: ${knownKeys().join(', ')}`,
|
|
2468
|
+
});
|
|
2469
|
+
return;
|
|
2470
|
+
}
|
|
2471
|
+
// Same exit race and failed input pipe as the input endpoint above:
|
|
2472
|
+
// 409, not 500.
|
|
2473
|
+
try {
|
|
2474
|
+
await session.write(bytes);
|
|
2475
|
+
}
|
|
2476
|
+
catch (error) {
|
|
2477
|
+
json(res, 409, {
|
|
2478
|
+
error: error instanceof SessionInputFailedError
|
|
2479
|
+
? error.message
|
|
2480
|
+
: `Session ${id} exited while the key was being written: ${String(error)}`,
|
|
2481
|
+
});
|
|
2482
|
+
return;
|
|
2483
|
+
}
|
|
2484
|
+
this.audit.record(actor, 'key', id, { key });
|
|
2485
|
+
this.broadcastControl(id, { type: 'input-source', source: 'agent' });
|
|
2486
|
+
json(res, 200, { ok: true, key });
|
|
2487
|
+
return;
|
|
2488
|
+
}
|
|
2489
|
+
if (req.method === 'GET' && action === 'wait') {
|
|
2490
|
+
// Checked before waiting, so a wait that could only end refused is
|
|
2491
|
+
// refused at once.
|
|
2492
|
+
const hide = queryFlag(url, 'hideReasoning');
|
|
2493
|
+
if (hide === null) {
|
|
2494
|
+
json(res, 400, { error: BAD_HIDE_REASONING });
|
|
2495
|
+
return;
|
|
2496
|
+
}
|
|
2497
|
+
const reader = hide ? this.readerFor(session, res) : null;
|
|
2498
|
+
if (hide && reader === null)
|
|
2499
|
+
return;
|
|
2500
|
+
const condition = {};
|
|
2501
|
+
const text = url.searchParams.get('text');
|
|
2502
|
+
const regex = url.searchParams.get('regex');
|
|
2503
|
+
const quiet = url.searchParams.get('quiet');
|
|
2504
|
+
const prompt = url.searchParams.get('prompt');
|
|
2505
|
+
if (text !== null)
|
|
2506
|
+
condition.text = text;
|
|
2507
|
+
if (regex !== null)
|
|
2508
|
+
condition.regex = regex;
|
|
2509
|
+
if (quiet !== null)
|
|
2510
|
+
condition.quiet = Number(quiet);
|
|
2511
|
+
// Presence alone is not enough: `?prompt=false` must not silently
|
|
2512
|
+
// become a prompt wait, and the waiter's exactly-one check counts
|
|
2513
|
+
// `prompt === true` only.
|
|
2514
|
+
if (prompt !== null)
|
|
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;
|
|
2519
|
+
const timeoutParam = url.searchParams.get('timeout');
|
|
2520
|
+
const debounceParam = url.searchParams.get('debounce');
|
|
2521
|
+
const afterInputParam = url.searchParams.get('matchAfterInput');
|
|
2522
|
+
// A wait ends with its caller. A response that closes before it has
|
|
2523
|
+
// been written means the client gave up or its process died, so the
|
|
2524
|
+
// wait is aborted rather than left to poll to its full timeout for an
|
|
2525
|
+
// answer nobody would read. A response that completed normally has
|
|
2526
|
+
// already cleared this.
|
|
2527
|
+
const abort = new AbortController();
|
|
2528
|
+
const onClose = () => {
|
|
2529
|
+
if (!res.writableEnded)
|
|
2530
|
+
abort.abort();
|
|
2531
|
+
};
|
|
2532
|
+
res.on('close', onClose);
|
|
2533
|
+
this.waitsInFlight += 1;
|
|
2534
|
+
let result;
|
|
2535
|
+
try {
|
|
2536
|
+
result = await session.waitFor(condition, {
|
|
2537
|
+
...(timeoutParam !== null ? { timeout: Number(timeoutParam) } : {}),
|
|
2538
|
+
...(debounceParam !== null ? { debounce: Number(debounceParam) } : {}),
|
|
2539
|
+
// Same parse as `prompt` above: `false`/`0` mean false, anything
|
|
2540
|
+
// else present means true.
|
|
2541
|
+
...(afterInputParam !== null
|
|
2542
|
+
? { matchAfterInput: afterInputParam !== 'false' && afterInputParam !== '0' }
|
|
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
|
+
} : {}),
|
|
2554
|
+
signal: abort.signal,
|
|
2555
|
+
});
|
|
2556
|
+
}
|
|
2557
|
+
finally {
|
|
2558
|
+
this.waitsInFlight -= 1;
|
|
2559
|
+
res.off('close', onClose);
|
|
2560
|
+
}
|
|
2561
|
+
// Nobody to answer, and writing to a closed response throws.
|
|
2562
|
+
if (abort.signal.aborted)
|
|
2563
|
+
return;
|
|
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
|
+
}
|
|
2575
|
+
// The screen as it stands now, a moment after the wait resolved,
|
|
2576
|
+
// with the reasoning left out.
|
|
2577
|
+
const view = await session.styledScreen(REASONING_CONTEXT_LINES);
|
|
2578
|
+
const filtered = hideReasoning(view.lines, reader, view.firstVisible);
|
|
2579
|
+
if (filtered === null) {
|
|
2580
|
+
json(res, 400, { error: overBudgetMessage(reader) });
|
|
2581
|
+
return;
|
|
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;
|
|
2595
|
+
json(res, 200, {
|
|
2596
|
+
...result,
|
|
2597
|
+
screen: marked.join('\n'),
|
|
2598
|
+
...(result.prompt === undefined ? {} : { prompt }),
|
|
2599
|
+
reasoning: { agent: reader.name, hiddenLines: filtered.hiddenLines, hiddenBlocks: filtered.hiddenBlocks },
|
|
2600
|
+
id: session.id,
|
|
2601
|
+
exited: session.exited,
|
|
2602
|
+
exitCode: session.exitCode,
|
|
2603
|
+
});
|
|
2604
|
+
return;
|
|
2605
|
+
}
|
|
2606
|
+
json(res, 200, {
|
|
2607
|
+
...result,
|
|
2608
|
+
id: session.id,
|
|
2609
|
+
exited: session.exited,
|
|
2610
|
+
exitCode: session.exitCode,
|
|
2611
|
+
});
|
|
2612
|
+
return;
|
|
2613
|
+
}
|
|
2614
|
+
if (req.method === 'GET' && action === 'find') {
|
|
2615
|
+
const pattern = url.searchParams.get('pattern');
|
|
2616
|
+
if (pattern === null || pattern === '') {
|
|
2617
|
+
json(res, 400, { error: 'pattern is required.' });
|
|
2618
|
+
return;
|
|
2619
|
+
}
|
|
2620
|
+
try {
|
|
2621
|
+
const hide = queryFlag(url, 'hideReasoning');
|
|
2622
|
+
if (hide === null) {
|
|
2623
|
+
json(res, 400, { error: BAD_HIDE_REASONING });
|
|
2624
|
+
return;
|
|
2625
|
+
}
|
|
2626
|
+
if (!hide) {
|
|
2627
|
+
const result = findOnScreen(await session.viewportLines(), pattern);
|
|
2628
|
+
json(res, 200, { id: session.id, pattern, ...result });
|
|
2629
|
+
return;
|
|
2630
|
+
}
|
|
2631
|
+
const signature = this.readerFor(session, res);
|
|
2632
|
+
if (signature === null)
|
|
2633
|
+
return;
|
|
2634
|
+
const view = await session.styledScreen(REASONING_CONTEXT_LINES);
|
|
2635
|
+
const filtered = hideReasoning(view.lines, signature, view.firstVisible);
|
|
2636
|
+
if (filtered === null) {
|
|
2637
|
+
json(res, 400, { error: overBudgetMessage(signature) });
|
|
2638
|
+
return;
|
|
2639
|
+
}
|
|
2640
|
+
// Only the kept rows are searched, each reported by the screen's
|
|
2641
|
+
// own row number, so a hidden row can neither match nor count
|
|
2642
|
+
// towards the cap on matches.
|
|
2643
|
+
const keptRows = [];
|
|
2644
|
+
const keptText = [];
|
|
2645
|
+
filtered.lines.forEach((text, k) => {
|
|
2646
|
+
if (filtered.markers[k])
|
|
2647
|
+
return;
|
|
2648
|
+
keptRows.push(filtered.rows[k]);
|
|
2649
|
+
keptText.push(text);
|
|
2650
|
+
});
|
|
2651
|
+
const result = findOnScreen(keptText, pattern);
|
|
2652
|
+
json(res, 200, {
|
|
2653
|
+
id: session.id,
|
|
2654
|
+
pattern,
|
|
2655
|
+
matches: result.matches.map((match) => ({ ...match, line: keptRows[match.line - 1] + 1 })),
|
|
2656
|
+
truncated: result.truncated,
|
|
2657
|
+
reasoning: { agent: signature.name, hiddenLines: filtered.hiddenLines },
|
|
2658
|
+
});
|
|
2659
|
+
}
|
|
2660
|
+
catch (error) {
|
|
2661
|
+
// A pattern that will not finish is a different mistake from one
|
|
2662
|
+
// that will not compile, and the caller can only fix the one it is
|
|
2663
|
+
// told about.
|
|
2664
|
+
json(res, 400, {
|
|
2665
|
+
error: error instanceof RegexBudgetError
|
|
2666
|
+
? error.message
|
|
2667
|
+
: `Invalid pattern: ${pattern}`,
|
|
2668
|
+
});
|
|
2669
|
+
}
|
|
2670
|
+
return;
|
|
2671
|
+
}
|
|
2672
|
+
if (req.method === 'POST' && action === 'resize') {
|
|
2673
|
+
const body = await readBody(req);
|
|
2674
|
+
const cols = asNumber(body['cols']);
|
|
2675
|
+
const rows = asNumber(body['rows']);
|
|
2676
|
+
if (cols === undefined || rows === undefined || gridOutOfBounds(cols, rows)) {
|
|
2677
|
+
json(res, 400, { error: GRID_BOUNDS_ERROR });
|
|
2678
|
+
return;
|
|
2679
|
+
}
|
|
2680
|
+
const hold = body['hold'] === true;
|
|
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
|
+
}
|
|
2690
|
+
this.audit.record(actor, 'resize', id, { cols, rows, hold });
|
|
2691
|
+
// An API resize takes the grid away from whichever viewport had it, so
|
|
2692
|
+
// nobody is left believing they still drive it. It does NOT hold
|
|
2693
|
+
// unless asked: a human whose window is now the wrong shape gets it
|
|
2694
|
+
// back by moving that window, which is the only escape they have while
|
|
2695
|
+
// there is no takeover control to press (§5).
|
|
2696
|
+
this.geometryController.delete(id);
|
|
2697
|
+
this.dashboardGeometryOwner.delete(id);
|
|
2698
|
+
this.announceGeometry(id, session);
|
|
2699
|
+
json(res, 200, { ok: true, cols, rows, geometryHeld: session.geometryHeld });
|
|
2700
|
+
return;
|
|
2701
|
+
}
|
|
2702
|
+
json(res, 404, { error: 'Not found.', path: url.pathname });
|
|
2703
|
+
}
|
|
2704
|
+
catch (error) {
|
|
2705
|
+
if (error instanceof WaitConditionError) {
|
|
2706
|
+
json(res, 400, { error: error.message });
|
|
2707
|
+
return;
|
|
2708
|
+
}
|
|
2709
|
+
if (error instanceof RequestBodyTooLargeError) {
|
|
2710
|
+
json(res, 413, { error: error.message });
|
|
2711
|
+
return;
|
|
2712
|
+
}
|
|
2713
|
+
if (error instanceof Error && error.message.startsWith('Request body')) {
|
|
2714
|
+
json(res, 400, { error: error.message });
|
|
2715
|
+
return;
|
|
2716
|
+
}
|
|
2717
|
+
throw error;
|
|
2718
|
+
}
|
|
2719
|
+
}
|
|
2720
|
+
async handleStart(req, res, actor) {
|
|
2721
|
+
const body = await readBody(req);
|
|
2722
|
+
const command = asString(body['command']);
|
|
2723
|
+
if (command === undefined || command === '') {
|
|
2724
|
+
json(res, 400, { error: 'command (string) is required.' });
|
|
2725
|
+
return;
|
|
2726
|
+
}
|
|
2727
|
+
const shapeError = startShapeError(body);
|
|
2728
|
+
if (shapeError !== null) {
|
|
2729
|
+
json(res, 400, { error: shapeError });
|
|
2730
|
+
return;
|
|
2731
|
+
}
|
|
2732
|
+
if (gridOutOfBounds(asNumber(body['cols']), asNumber(body['rows']))) {
|
|
2733
|
+
json(res, 400, { error: GRID_BOUNDS_ERROR });
|
|
2734
|
+
return;
|
|
2735
|
+
}
|
|
2736
|
+
const agent = asString(body['agent']);
|
|
2737
|
+
if (agent !== undefined && !agentNames().includes(agent)) {
|
|
2738
|
+
json(res, 400, {
|
|
2739
|
+
error: `agent must be one of: ${agentNames().join(', ')}. Config agents.signatures can ` +
|
|
2740
|
+
'describe another.',
|
|
2741
|
+
});
|
|
2742
|
+
return;
|
|
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']) ?? '.');
|
|
2751
|
+
// A working directory that is not one is a caller mistake, reported as
|
|
2752
|
+
// one here rather than left to fail deep inside ConPTY as "Cannot create
|
|
2753
|
+
// process, error code: 267", which gives the caller nothing to act on.
|
|
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;
|
|
2765
|
+
}
|
|
2766
|
+
const options = {
|
|
2767
|
+
command,
|
|
2768
|
+
...(asStringArray(body['args']) !== undefined ? { args: asStringArray(body['args']) } : {}),
|
|
2769
|
+
cwd,
|
|
2770
|
+
...(asNumber(body['cols']) !== undefined ? { cols: asNumber(body['cols']) } : {}),
|
|
2771
|
+
...(asNumber(body['rows']) !== undefined ? { rows: asNumber(body['rows']) } : {}),
|
|
2772
|
+
...(body['hold'] === true ? { hold: true } : {}),
|
|
2773
|
+
...(asString(body['label']) !== undefined ? { label: asString(body['label']) } : {}),
|
|
2774
|
+
...(asString(body['purpose']) !== undefined ? { purpose: asString(body['purpose']) } : {}),
|
|
2775
|
+
...(agent !== undefined ? { agent } : {}),
|
|
2776
|
+
// From the request's audit identity rather than the body, so it cannot
|
|
2777
|
+
// diverge from the audit trail. Self-declared, not authenticated: see
|
|
2778
|
+
// SessionOptions.startedBy.
|
|
2779
|
+
startedBy: actor,
|
|
2780
|
+
...(asString(body['readyText']) !== undefined
|
|
2781
|
+
? { readyText: asString(body['readyText']) }
|
|
2782
|
+
: {}),
|
|
2783
|
+
...(asNumber(body['readyQuiet']) !== undefined
|
|
2784
|
+
? { readyQuiet: asNumber(body['readyQuiet']) }
|
|
2785
|
+
: {}),
|
|
2786
|
+
...(asBoolean(body['shell']) !== undefined ? { shell: asBoolean(body['shell']) } : {}),
|
|
2787
|
+
// Shape-checked above: names to string values.
|
|
2788
|
+
...(body['env'] !== undefined ? { env: body['env'] } : {}),
|
|
2789
|
+
};
|
|
2790
|
+
const envNames = Object.keys(options.env ?? {});
|
|
2791
|
+
let session;
|
|
2792
|
+
try {
|
|
2793
|
+
session = this.manager.create(options);
|
|
2794
|
+
}
|
|
2795
|
+
catch (error) {
|
|
2796
|
+
if (error instanceof PolicyViolationError) {
|
|
2797
|
+
json(res, 403, { error: error.message });
|
|
2798
|
+
return;
|
|
2799
|
+
}
|
|
2800
|
+
if (error instanceof CommandNotFoundError) {
|
|
2801
|
+
json(res, 400, { error: error.message });
|
|
2802
|
+
return;
|
|
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
|
+
});
|
|
2813
|
+
// The install cannot open a terminal at all. The message says what to
|
|
2814
|
+
// do, so it goes out as written.
|
|
2815
|
+
if (error instanceof NativePtyUnavailableError) {
|
|
2816
|
+
json(res, 500, { error: error.message });
|
|
2817
|
+
return;
|
|
2818
|
+
}
|
|
2819
|
+
json(res, 500, { error: `Failed to start session: ${String(error)}` });
|
|
2820
|
+
return;
|
|
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));
|
|
2841
|
+
// Commands are policy-visible by definition, so the command line IS
|
|
2842
|
+
// audited (§4.5), unlike typed content. Passed variables are audited by
|
|
2843
|
+
// name only, whatever `audit.captureContent` says: a value is a secret
|
|
2844
|
+
// the caller handed over, not something anyone typed.
|
|
2845
|
+
this.audit.record(actor, 'start', session.id, {
|
|
2846
|
+
command: options.command,
|
|
2847
|
+
args: options.args ?? [],
|
|
2848
|
+
...(envNames.length > 0 ? { envNames } : {}),
|
|
2849
|
+
...(agent !== undefined ? { agent } : {}),
|
|
2850
|
+
label: session.label,
|
|
2851
|
+
});
|
|
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.
|
|
2855
|
+
// The session id goes in the QUERY, not the path, and that is load-bearing
|
|
2856
|
+
// on Windows. Chrome derives an `--app` window's AppUserModelID from
|
|
2857
|
+
// host + PATH only, and Windows groups taskbar buttons
|
|
2858
|
+
// by AppUserModelID. A per-session path would give every viewer its own
|
|
2859
|
+
// taskbar icon; a constant path puts them all under ONE icon whose hover
|
|
2860
|
+
// list is the open sessions, which is how a human with five agent CLIs
|
|
2861
|
+
// running actually navigates. Measured:
|
|
2862
|
+
// /view/s1 -> Chrome.127.0.0.1_/view/s1.… (separate buttons)
|
|
2863
|
+
// /view?s=s1 -> Chrome.127.0.0.1_/view.… (one button, five windows)
|
|
2864
|
+
// `/view/<id>` serves the same page.
|
|
2865
|
+
// A start that asks for no window (the CLI's `--no-viewer`, for a short
|
|
2866
|
+
// scripted session nobody needs to watch) mints no grant and opens
|
|
2867
|
+
// nothing; the session is listed as any other, and `viewer-url` gives a
|
|
2868
|
+
// link to it whenever someone asks.
|
|
2869
|
+
const wantsViewer = body['openViewer'] !== false;
|
|
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'
|
|
2875
|
+
? this.viewerUrlFor(session.id, this.tokens.mintViewerGrant(session.id))
|
|
2876
|
+
: '';
|
|
2877
|
+
// Open the window for the human, and wait to hear whether anything
|
|
2878
|
+
// opened: the launcher only spawns, detached, so the wait costs the start
|
|
2879
|
+
// milliseconds, and the answer decides what the caller is told. A browser
|
|
2880
|
+
// that will not start must never fail a session start, the one path every
|
|
2881
|
+
// delegate depends on, so the launcher is built not to throw, and a
|
|
2882
|
+
// failure here is logged and counts as "nothing opened".
|
|
2883
|
+
const launch = this.options.launcher ?? launchViewer;
|
|
2884
|
+
let opened;
|
|
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
|
+
}
|
|
2896
|
+
}
|
|
2897
|
+
else {
|
|
2898
|
+
try {
|
|
2899
|
+
opened = await launch(viewerUrl, this.options.home, this.options.viewer ?? {}, this.logger);
|
|
2900
|
+
}
|
|
2901
|
+
catch (error) {
|
|
2902
|
+
this.logger.warn('viewer launch failed', { id: session.id, error: String(error) });
|
|
2903
|
+
opened = {
|
|
2904
|
+
launched: false,
|
|
2905
|
+
mode: this.options.viewer?.launchMode ?? 'no-window',
|
|
2906
|
+
reason: String(error),
|
|
2907
|
+
};
|
|
2908
|
+
}
|
|
2909
|
+
}
|
|
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 !== '';
|
|
2917
|
+
if (handOver)
|
|
2918
|
+
this.audit.record(actor, 'grant-mint', session.id, { readOnly: false });
|
|
2919
|
+
json(res, 200, {
|
|
2920
|
+
id: session.id,
|
|
2921
|
+
label: session.label,
|
|
2922
|
+
pid: session.pid,
|
|
2923
|
+
cols: session.cols,
|
|
2924
|
+
rows: session.rows,
|
|
2925
|
+
ready: session.ready,
|
|
2926
|
+
// Without the reason, `ready: true` is ambiguous: it may mean nothing
|
|
2927
|
+
// was checked. Callers need to tell those apart before they type.
|
|
2928
|
+
readyReason: session.readyReason,
|
|
2929
|
+
geometryHeld: session.geometryHeld,
|
|
2930
|
+
viewer: {
|
|
2931
|
+
opened: opened.launched,
|
|
2932
|
+
mode: opened.mode,
|
|
2933
|
+
...(opened.reason !== undefined ? { reason: opened.reason } : {}),
|
|
2934
|
+
},
|
|
2935
|
+
...(handOver ? { viewerUrl } : {}),
|
|
2936
|
+
});
|
|
2937
|
+
}
|
|
2938
|
+
/**
|
|
2939
|
+
* The signature that reads a session's screen for `hideReasoning` and
|
|
2940
|
+
* `terminal_result`. Without one, a 400 is sent and null returned: those
|
|
2941
|
+
* readers fail closed.
|
|
2942
|
+
*/
|
|
2943
|
+
readerFor(session, res) {
|
|
2944
|
+
const signature = signatureFor(session.agent, session.command);
|
|
2945
|
+
if (signature !== null)
|
|
2946
|
+
return signature;
|
|
2947
|
+
const known = agentNames().join(', ');
|
|
2948
|
+
json(res, 400, {
|
|
2949
|
+
error: session.agent !== undefined
|
|
2950
|
+
? `Session ${session.id} was started as agent "${session.agent}", whose signature is not ` +
|
|
2951
|
+
`available now (removed from config, or set aside for running past its time budget), ` +
|
|
2952
|
+
`so its screen is not read for hideReasoning or a result.`
|
|
2953
|
+
: `Session ${session.id} runs ${programName(session.command)}, which has no agent ` +
|
|
2954
|
+
`signature, so its screen is not returned with hideReasoning or read for a result. ` +
|
|
2955
|
+
`Start it with agent set to one of: ${known}. Read it without hideReasoning only if ` +
|
|
2956
|
+
`no agent's reasoning is on it.`,
|
|
2957
|
+
});
|
|
2958
|
+
return null;
|
|
2959
|
+
}
|
|
2960
|
+
/**
|
|
2961
|
+
* Poll for the typed text to appear on screen, for longer the longer the
|
|
2962
|
+
* text (VERIFY_MS_PER_CHAR). Matches on the last
|
|
2963
|
+
* printable run of the input (up to 40 chars) so a trailing Enter or an
|
|
2964
|
+
* embedded control sequence does not defeat the check. For input long
|
|
2965
|
+
* enough to be lost in pieces, it matches on the FIRST run as well (see the
|
|
2966
|
+
* needle comments below for the loss this exists to catch).
|
|
2967
|
+
*
|
|
2968
|
+
* Both needles must appear, read the way a TUI wraps typed text
|
|
2969
|
+
* (`screenShows`): a long prompt is redrawn across the rows of an input
|
|
2970
|
+
* box, and the line break, the continuation row's indent, the box's border
|
|
2971
|
+
* and any side panel drawn on the same rows land in the middle of the
|
|
2972
|
+
* needle. `before` is the screen as it was before the input: rows still the
|
|
2973
|
+
* same are not read as wrapped pieces of it.
|
|
2974
|
+
*/
|
|
2975
|
+
async verifyTyped(session, typed, before) {
|
|
2976
|
+
// eslint-disable-next-line no-control-regex
|
|
2977
|
+
const printableRuns = typed.split(/[\x00-\x1f\x7f]+/).filter((s) => s.length > 0);
|
|
2978
|
+
// Check the HEAD as well as the tail, and only for input long enough to be
|
|
2979
|
+
// lost in pieces. A long prompt can reach a TUI with its front missing and
|
|
2980
|
+
// its tail intact, so a tail-only check could not fail on the one loss
|
|
2981
|
+
// mode it needs to catch. A check that cannot fail is worse than no check:
|
|
2982
|
+
// it converts a silent problem into a confident wrong answer.
|
|
2983
|
+
const needles = [];
|
|
2984
|
+
const last = printableRuns[printableRuns.length - 1];
|
|
2985
|
+
if (last !== undefined)
|
|
2986
|
+
needles.push(last.slice(-40));
|
|
2987
|
+
const first = printableRuns[0];
|
|
2988
|
+
if (first !== undefined && typed.length > 200)
|
|
2989
|
+
needles.push(first.slice(0, 40));
|
|
2990
|
+
// A false report for text that arrived perfectly is not harmless: an agent
|
|
2991
|
+
// trusting it would retype and DUPLICATE its input, which is worse than
|
|
2992
|
+
// not checking at all.
|
|
2993
|
+
const visible = needles.filter((n) => n.trim() !== '');
|
|
2994
|
+
if (visible.length === 0)
|
|
2995
|
+
return true; // control/whitespace only: nothing to see
|
|
2996
|
+
const deadline = Date.now() + Math.min(VERIFY_BASE_MS + typed.length * VERIFY_MS_PER_CHAR, VERIFY_MAX_MS);
|
|
2997
|
+
for (;;) {
|
|
2998
|
+
const { screen } = await session.snapshot();
|
|
2999
|
+
if (visible.every((needle) => screenShows(screen, needle, before)))
|
|
3000
|
+
return true;
|
|
3001
|
+
if (Date.now() >= deadline)
|
|
3002
|
+
return false;
|
|
3003
|
+
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
3004
|
+
}
|
|
3005
|
+
}
|
|
3006
|
+
/**
|
|
3007
|
+
* Reap naturally-exited sessions once their grace lapses, releasing what a
|
|
3008
|
+
* kill releases: the renderer, the session's viewer grants and credentials, and its
|
|
3009
|
+
* watcher sockets, so an abandoned viewer tab cannot hold off idle shutdown.
|
|
3010
|
+
*/
|
|
3011
|
+
async sweepExited() {
|
|
3012
|
+
const graceMs = this.options.exitedGraceMs ?? EXITED_SESSION_GRACE_MS;
|
|
3013
|
+
const reaped = await this.manager.reapExited(graceMs);
|
|
3014
|
+
for (const id of reaped) {
|
|
3015
|
+
this.audit.record('daemon', 'reap', id);
|
|
3016
|
+
this.dropSessionArtifacts(id);
|
|
3017
|
+
}
|
|
3018
|
+
}
|
|
3019
|
+
/** Revoke a removed session's viewer grants and credentials and close its watcher sockets. */
|
|
3020
|
+
dropSessionArtifacts(id) {
|
|
3021
|
+
this.tokens.revokeViewerTokens(id);
|
|
3022
|
+
for (const [ws, sync] of this.sessionSockets.get(id) ?? []) {
|
|
3023
|
+
sync.close();
|
|
3024
|
+
try {
|
|
3025
|
+
ws.close();
|
|
3026
|
+
}
|
|
3027
|
+
catch {
|
|
3028
|
+
// Best effort.
|
|
3029
|
+
}
|
|
3030
|
+
}
|
|
3031
|
+
this.sessionSockets.delete(id);
|
|
3032
|
+
this.geometryController.delete(id);
|
|
3033
|
+
this.dashboardGeometryOwner.delete(id);
|
|
3034
|
+
}
|
|
3035
|
+
/** Whether a live viewport is currently driving this session's grid. */
|
|
3036
|
+
hasGeometryController(sessionId) {
|
|
3037
|
+
const controller = this.geometryController.get(sessionId);
|
|
3038
|
+
if (controller === undefined)
|
|
3039
|
+
return false;
|
|
3040
|
+
if (controller.readyState === controller.OPEN)
|
|
3041
|
+
return true;
|
|
3042
|
+
this.geometryController.delete(sessionId);
|
|
3043
|
+
return false;
|
|
3044
|
+
}
|
|
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
|
+
}
|
|
3081
|
+
/**
|
|
3082
|
+
* Session list decorated with whatever prompt each session is holding. The
|
|
3083
|
+
* stall alert also goes to `daemon.log` and the `/events` socket, but an
|
|
3084
|
+
* agent reaches the daemon through request-and-answer tool calls or one-shot
|
|
3085
|
+
* CLI runs, so it can never hold that socket: `terminal_list` is how a
|
|
3086
|
+
* manager agent learns that its delegate is blocked, which is the whole
|
|
3087
|
+
* point of detecting it.
|
|
3088
|
+
*
|
|
3089
|
+
* Read from the scanner's own state rather than re-detecting here: one
|
|
3090
|
+
* source of truth means what the list reports and what the log announces
|
|
3091
|
+
* cannot disagree, and a list call stays cheap (no render per session).
|
|
3092
|
+
* The cost is staleness bounded by the scan interval: 5 s, immaterial
|
|
3093
|
+
* against prompts that sit for minutes.
|
|
3094
|
+
*/
|
|
3095
|
+
listWithPrompts(hideReasoning = false) {
|
|
3096
|
+
const now = Date.now();
|
|
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 } };
|
|
3103
|
+
});
|
|
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
|
+
}
|
|
3154
|
+
/**
|
|
3155
|
+
* Scan every live session's screen for a permission prompt and alert when
|
|
3156
|
+
* the SAME prompt has been waiting longer than the stall threshold, so an
|
|
3157
|
+
* unserviced prompt does not cost the delegate tens of idle minutes until
|
|
3158
|
+
* someone happens to snapshot the session.
|
|
3159
|
+
*/
|
|
3160
|
+
async scanForPromptStalls() {
|
|
3161
|
+
const stallMs = this.options.promptStallMs ?? PROMPT_STALL_MS;
|
|
3162
|
+
const seen = new Set();
|
|
3163
|
+
for (const summary of this.manager.list()) {
|
|
3164
|
+
const session = this.manager.get(summary.id);
|
|
3165
|
+
if (session === undefined || session.exited)
|
|
3166
|
+
continue;
|
|
3167
|
+
seen.add(session.id);
|
|
3168
|
+
let detected;
|
|
3169
|
+
try {
|
|
3170
|
+
const snapshot = await session.snapshot();
|
|
3171
|
+
detected = session.answerablePrompt(snapshot.screen);
|
|
3172
|
+
}
|
|
3173
|
+
catch (error) {
|
|
3174
|
+
// One session's render fault must not blind the scan for every
|
|
3175
|
+
// session after it in list order, so skip it and keep scanning; its
|
|
3176
|
+
// own prompt state, if any, waits for a healthier beat.
|
|
3177
|
+
this.logger.warn('prompt scan skipped a session', {
|
|
3178
|
+
id: session.id,
|
|
3179
|
+
error: String(error),
|
|
3180
|
+
});
|
|
3181
|
+
continue;
|
|
3182
|
+
}
|
|
3183
|
+
const previous = this.promptStates.get(session.id);
|
|
3184
|
+
if (detected === null) {
|
|
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
|
+
}
|
|
3196
|
+
}
|
|
3197
|
+
this.clearPromptGraceCheck(session.id);
|
|
3198
|
+
if (previous?.alerted === true) {
|
|
3199
|
+
this.emitEvent({
|
|
3200
|
+
type: 'prompt-clear',
|
|
3201
|
+
session: session.id,
|
|
3202
|
+
label: summary.label ?? null,
|
|
3203
|
+
});
|
|
3204
|
+
// Viewers were told the prompt was waiting; they must be told it is
|
|
3205
|
+
// over, or a badge raised by the stall alert never comes down.
|
|
3206
|
+
this.broadcastControl(session.id, { type: 'prompt-clear' });
|
|
3207
|
+
}
|
|
3208
|
+
if (previous !== undefined) {
|
|
3209
|
+
this.promptStates.delete(session.id);
|
|
3210
|
+
this.updateFeedSession(session.id);
|
|
3211
|
+
}
|
|
3212
|
+
continue;
|
|
3213
|
+
}
|
|
3214
|
+
// A real sighting cancels a pending repaint gap: the prompt is still there.
|
|
3215
|
+
// Refresh the stored prompt with it, too: the signature deliberately
|
|
3216
|
+
// normalises Grok's radio markers so that MOVING the selection does not
|
|
3217
|
+
// restart the stall clock, which means the same signature can describe a
|
|
3218
|
+
// visibly different set of options. Storing only on signature change
|
|
3219
|
+
// would serve a stale selection to `terminal_list` and to a viewer
|
|
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]);
|
|
3226
|
+
if (previous !== undefined) {
|
|
3227
|
+
this.clearPromptGraceCheck(session.id);
|
|
3228
|
+
previous.missingSince = null;
|
|
3229
|
+
previous.prompt = detected;
|
|
3230
|
+
}
|
|
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)) {
|
|
3237
|
+
// A new (or changed) prompt starts its stall clock; it has not
|
|
3238
|
+
// alerted yet, so a prompt answered promptly stays silent.
|
|
3239
|
+
if (previous?.alerted === true) {
|
|
3240
|
+
// The previous prompt was announced and has now been replaced
|
|
3241
|
+
// rather than cleared. Retract it, otherwise a viewer badges the
|
|
3242
|
+
// old question while a different one is on screen.
|
|
3243
|
+
//
|
|
3244
|
+
// BOTH channels, symmetrically with the null path above. Retracting
|
|
3245
|
+
// to viewers only would leave `/events` emitting stall(Q1) then
|
|
3246
|
+
// stall(Q2) with no clear between them, which reads as two concurrent
|
|
3247
|
+
// holds or an unresolved first one. Nothing in this repository
|
|
3248
|
+
// subscribes to it, but the socket is a real API and an asymmetric
|
|
3249
|
+
// one is a trap for the first thing that consumes it.
|
|
3250
|
+
this.emitEvent({
|
|
3251
|
+
type: 'prompt-clear',
|
|
3252
|
+
session: session.id,
|
|
3253
|
+
label: summary.label ?? null,
|
|
3254
|
+
});
|
|
3255
|
+
this.broadcastControl(session.id, { type: 'prompt-clear' });
|
|
3256
|
+
}
|
|
3257
|
+
this.promptStates.set(session.id, {
|
|
3258
|
+
signature: detected.signature,
|
|
3259
|
+
since: Date.now(),
|
|
3260
|
+
alerted: false,
|
|
3261
|
+
prompt: detected,
|
|
3262
|
+
missingSince: null,
|
|
3263
|
+
});
|
|
3264
|
+
if (promptChanged || previous?.alerted === true)
|
|
3265
|
+
this.updateFeedSession(session.id);
|
|
3266
|
+
continue;
|
|
3267
|
+
}
|
|
3268
|
+
previous.signature = detected.signature;
|
|
3269
|
+
if (promptChanged)
|
|
3270
|
+
this.updateFeedSession(session.id);
|
|
3271
|
+
if (!previous.alerted && Date.now() - previous.since >= stallMs) {
|
|
3272
|
+
previous.alerted = true;
|
|
3273
|
+
this.updateFeedSession(session.id);
|
|
3274
|
+
const waitingMs = Date.now() - previous.since;
|
|
3275
|
+
this.audit.record('daemon', 'prompt-stall', session.id);
|
|
3276
|
+
this.logger.warn('session waiting on a prompt', {
|
|
3277
|
+
id: session.id,
|
|
3278
|
+
waitingMs,
|
|
3279
|
+
options: detected.options.length,
|
|
3280
|
+
});
|
|
3281
|
+
this.emitEvent({
|
|
3282
|
+
type: 'prompt-stall',
|
|
3283
|
+
session: session.id,
|
|
3284
|
+
label: summary.label ?? null,
|
|
3285
|
+
waitingMs,
|
|
3286
|
+
question: detected.question,
|
|
3287
|
+
options: detected.options,
|
|
3288
|
+
...(detected.selectedOption === undefined ? {} : { selectedOption: detected.selectedOption }),
|
|
3289
|
+
});
|
|
3290
|
+
// The session's own viewers get the same signal, so an open viewer
|
|
3291
|
+
// tab can badge itself without subscribing to the daemon stream.
|
|
3292
|
+
this.broadcastControl(session.id, {
|
|
3293
|
+
type: 'prompt-stall',
|
|
3294
|
+
waitingMs,
|
|
3295
|
+
question: detected.question,
|
|
3296
|
+
// The options travel to viewers as well as to /events, so the badge
|
|
3297
|
+
// can say what the choices are, not only THAT something is being
|
|
3298
|
+
// asked.
|
|
3299
|
+
options: detected.options,
|
|
3300
|
+
...(detected.selectedOption === undefined ? {} : { selectedOption: detected.selectedOption }),
|
|
3301
|
+
});
|
|
3302
|
+
}
|
|
3303
|
+
}
|
|
3304
|
+
// Sessions that exited or were reaped take their prompt state with them.
|
|
3305
|
+
for (const id of [...this.promptStates.keys()]) {
|
|
3306
|
+
if (!seen.has(id)) {
|
|
3307
|
+
this.clearPromptGraceCheck(id);
|
|
3308
|
+
this.promptStates.delete(id);
|
|
3309
|
+
this.updateFeedSession(id);
|
|
3310
|
+
}
|
|
3311
|
+
}
|
|
3312
|
+
}
|
|
3313
|
+
/** Fan an event out to every `/events` subscriber (TEXT JSON frames). */
|
|
3314
|
+
emitEvent(event) {
|
|
3315
|
+
const message = JSON.stringify({ ...event, at: new Date().toISOString() });
|
|
3316
|
+
for (const ws of this.eventSockets) {
|
|
3317
|
+
if (ws.readyState === ws.OPEN)
|
|
3318
|
+
ws.send(message);
|
|
3319
|
+
}
|
|
3320
|
+
}
|
|
3321
|
+
// ------------------------------------------------------------- websockets
|
|
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());
|
|
3328
|
+
const reject = (code, reason) => {
|
|
3329
|
+
socket.write(`HTTP/1.1 ${String(code)} ${reason}\r\nReferrer-Policy: no-referrer\r\nConnection: close\r\n\r\n`);
|
|
3330
|
+
socket.destroy();
|
|
3331
|
+
};
|
|
3332
|
+
if (!this.hostAllowed(req.headers.host)) {
|
|
3333
|
+
if (pathOnly(req.url).startsWith('/dashboard'))
|
|
3334
|
+
this.auditDashboardRefusal(req, 'host');
|
|
3335
|
+
reject(403, 'Forbidden');
|
|
3336
|
+
return;
|
|
3337
|
+
}
|
|
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.
|
|
3343
|
+
if (!this.originAllowed(req.headers.origin)) {
|
|
3344
|
+
if (pathOnly(req.url).startsWith('/dashboard'))
|
|
3345
|
+
this.auditDashboardRefusal(req, 'origin');
|
|
3346
|
+
reject(403, 'Forbidden');
|
|
3347
|
+
return;
|
|
3348
|
+
}
|
|
3349
|
+
// Parsed inside a guard, before anything is authenticated: Node's HTTP
|
|
3350
|
+
// parser accepts an unparsable request target (`GET http://[ HTTP/1.1`)
|
|
3351
|
+
// and hands it over verbatim, and no exception may escape the upgrade
|
|
3352
|
+
// event. Such a request is refused with a 400.
|
|
3353
|
+
let url;
|
|
3354
|
+
try {
|
|
3355
|
+
url = new URL(req.url ?? '/', `http://127.0.0.1:${String(this.portValue ?? 0)}`);
|
|
3356
|
+
}
|
|
3357
|
+
catch {
|
|
3358
|
+
reject(400, 'Bad Request');
|
|
3359
|
+
return;
|
|
3360
|
+
}
|
|
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
|
+
}
|
|
3376
|
+
// Daemon-wide event stream: prompt-stall alerts and their clears, as TEXT
|
|
3377
|
+
// JSON frames. CLIENT token only: viewer credentials are session-scoped
|
|
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.
|
|
3380
|
+
if (segments.length === 1 && segments[0] === 'events') {
|
|
3381
|
+
const auth = this.tokens.verify(url.searchParams.get('token'));
|
|
3382
|
+
if (auth === null || auth.kind !== 'client') {
|
|
3383
|
+
reject(401, 'Unauthorized');
|
|
3384
|
+
return;
|
|
3385
|
+
}
|
|
3386
|
+
this.wss.handleUpgrade(req, socket, head, (ws) => {
|
|
3387
|
+
this.attachEventSocket(ws);
|
|
3388
|
+
});
|
|
3389
|
+
return;
|
|
3390
|
+
}
|
|
3391
|
+
if (segments[0] !== 'sessions' || segments[2] !== 'stream') {
|
|
3392
|
+
reject(404, 'Not Found');
|
|
3393
|
+
return;
|
|
3394
|
+
}
|
|
3395
|
+
const sessionId = segments[1] ?? '';
|
|
3396
|
+
// Auth BEFORE existence: session ids are sequential, and answering 404
|
|
3397
|
+
// to an unauthenticated prober would let it enumerate which ones exist,
|
|
3398
|
+
// the same leak the unauthenticated viewer route deliberately avoids.
|
|
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
|
+
}
|
|
3414
|
+
const session = this.manager.get(sessionId);
|
|
3415
|
+
if (session === undefined) {
|
|
3416
|
+
reject(404, 'Not Found');
|
|
3417
|
+
return;
|
|
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);
|
|
3423
|
+
this.wss.handleUpgrade(req, socket, head, (ws) => {
|
|
3424
|
+
// Which credential opened the socket travels with it, so the audit log
|
|
3425
|
+
// names that credential rather than assuming a browser: `client` for
|
|
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 });
|
|
3429
|
+
});
|
|
3430
|
+
}
|
|
3431
|
+
/** Attach a subscriber to the daemon-wide event stream. */
|
|
3432
|
+
attachEventSocket(ws) {
|
|
3433
|
+
this.sockets.add(ws);
|
|
3434
|
+
this.eventSockets.add(ws);
|
|
3435
|
+
this.lastActivity = Date.now();
|
|
3436
|
+
this.audit.record('client', 'events-connect', '-');
|
|
3437
|
+
ws.send(JSON.stringify({ type: 'hello', version: this.version }));
|
|
3438
|
+
ws.on('close', () => {
|
|
3439
|
+
this.sockets.delete(ws);
|
|
3440
|
+
this.eventSockets.delete(ws);
|
|
3441
|
+
this.lastActivity = Date.now();
|
|
3442
|
+
});
|
|
3443
|
+
ws.on('error', () => {
|
|
3444
|
+
ws.close();
|
|
3445
|
+
});
|
|
3446
|
+
// The stream is outbound-only; inbound frames are ignored by design.
|
|
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
|
+
}
|
|
3542
|
+
/** Send a JSON control message (TEXT frame) to every watcher of a session. */
|
|
3543
|
+
broadcastControl(sessionId, control) {
|
|
3544
|
+
const watchers = this.sessionSockets.get(sessionId);
|
|
3545
|
+
if (watchers === undefined)
|
|
3546
|
+
return;
|
|
3547
|
+
const message = JSON.stringify(control);
|
|
3548
|
+
for (const ws of watchers.keys()) {
|
|
3549
|
+
if (ws.readyState === ws.OPEN)
|
|
3550
|
+
ws.send(message);
|
|
3551
|
+
}
|
|
3552
|
+
}
|
|
3553
|
+
/**
|
|
3554
|
+
* Tell every watcher the current grid and who drives it, then hand each one
|
|
3555
|
+
* a snapshot at that size. Both halves matter: the frame moves their grid,
|
|
3556
|
+
* and the snapshot repaints it from the daemon's renderer rather than from
|
|
3557
|
+
* xterm's in-place reflow of what they had (§5).
|
|
3558
|
+
*/
|
|
3559
|
+
announceGeometry(sessionId, session, options = {}) {
|
|
3560
|
+
for (const [ws, sync] of this.sessionSockets.get(sessionId) ?? []) {
|
|
3561
|
+
if (ws.readyState === ws.OPEN) {
|
|
3562
|
+
ws.send(JSON.stringify(this.geometryFrame(session, ws)));
|
|
3563
|
+
}
|
|
3564
|
+
if (options.resync !== false)
|
|
3565
|
+
sync.resync();
|
|
3566
|
+
}
|
|
3567
|
+
this.updateFeedSession(sessionId);
|
|
3568
|
+
}
|
|
3569
|
+
/** What one watcher is told about the grid, from its own point of view. */
|
|
3570
|
+
geometryFrame(session, ws) {
|
|
3571
|
+
return {
|
|
3572
|
+
type: 'geometry',
|
|
3573
|
+
cols: session.cols,
|
|
3574
|
+
rows: session.rows,
|
|
3575
|
+
// The most a viewport may ask for (§5), with every frame: a page whose
|
|
3576
|
+
// window wants more can then size its text for the grid it will be
|
|
3577
|
+
// given, rather than proposing one it never will be.
|
|
3578
|
+
max: { cols: MAX_VIEWPORT_COLS, rows: MAX_VIEWPORT_ROWS },
|
|
3579
|
+
control: session.geometryHeld
|
|
3580
|
+
? 'held'
|
|
3581
|
+
: this.geometryController.get(session.id) === ws
|
|
3582
|
+
? 'yours'
|
|
3583
|
+
: 'adopt',
|
|
3584
|
+
};
|
|
3585
|
+
}
|
|
3586
|
+
/** The viewer URL for a session, carrying a one-use grant. */
|
|
3587
|
+
viewerUrlFor(sessionId, grant) {
|
|
3588
|
+
return (`http://127.0.0.1:${String(this.port)}/view` +
|
|
3589
|
+
`?s=${encodeURIComponent(sessionId)}&vt=${grant}`);
|
|
3590
|
+
}
|
|
3591
|
+
/** The daemon's rendered state as viewer bytes: a wipe, then the rebuild. */
|
|
3592
|
+
async snapshotForViewer(session) {
|
|
3593
|
+
try {
|
|
3594
|
+
const state = await session.viewerState({
|
|
3595
|
+
scrollback: VIEWER_SNAPSHOT_SCROLLBACK_LINES,
|
|
3596
|
+
});
|
|
3597
|
+
return VIEWER_WIPE + state;
|
|
3598
|
+
}
|
|
3599
|
+
catch (error) {
|
|
3600
|
+
// The gate releases live bytes anyway; the viewer just misses this repaint.
|
|
3601
|
+
this.logger.warn('viewer snapshot failed', { id: session.id, error: String(error) });
|
|
3602
|
+
throw error;
|
|
3603
|
+
}
|
|
3604
|
+
}
|
|
3605
|
+
/**
|
|
3606
|
+
* Wire protocol: BINARY frames carry terminal bytes (snapshots, live mirror,
|
|
3607
|
+
* exit notice); TEXT frames are JSON control messages. Incoming text frames
|
|
3608
|
+
* are either JSON controls (resize) or bytes for the program: a person's
|
|
3609
|
+
* keystrokes, or the viewer's terminal answering the program
|
|
3610
|
+
* (terminalReports.ts).
|
|
3611
|
+
*/
|
|
3612
|
+
attachSocket(ws, session, credential, options = {}) {
|
|
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;
|
|
3620
|
+
// The audit actor is the credential that opened this socket, not the
|
|
3621
|
+
// route: `viewer` means the socket presented a viewer cookie (what a
|
|
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.
|
|
3626
|
+
const actor = credential.kind;
|
|
3627
|
+
this.sockets.add(ws);
|
|
3628
|
+
let watchers = this.sessionSockets.get(session.id);
|
|
3629
|
+
if (watchers === undefined) {
|
|
3630
|
+
watchers = new Map();
|
|
3631
|
+
this.sessionSockets.set(session.id, watchers);
|
|
3632
|
+
}
|
|
3633
|
+
const sync = new ViewerSync((bytes) => {
|
|
3634
|
+
if (ws.readyState === ws.OPEN)
|
|
3635
|
+
ws.send(Buffer.from(bytes, 'utf8'));
|
|
3636
|
+
}, () => this.snapshotForViewer(session));
|
|
3637
|
+
if (options.frozen === undefined)
|
|
3638
|
+
watchers.set(ws, sync);
|
|
3639
|
+
this.lastActivity = Date.now();
|
|
3640
|
+
this.audit.record(actor, 'ws-connect', session.id);
|
|
3641
|
+
// Who this session belongs to and what it is for. Sent before anything
|
|
3642
|
+
// else so the window is identifiable the instant it paints: with several
|
|
3643
|
+
// viewer windows open, an unlabelled one is indistinguishable from the
|
|
3644
|
+
// rest until you read its terminal content and infer.
|
|
3645
|
+
ws.send(JSON.stringify({
|
|
3646
|
+
type: 'identity',
|
|
3647
|
+
session: session.id,
|
|
3648
|
+
label: session.label,
|
|
3649
|
+
purpose: session.purpose,
|
|
3650
|
+
startedBy: session.startedBy,
|
|
3651
|
+
command: commandLine(session.command, session.args),
|
|
3652
|
+
// The page reflects this rather than deciding it: its own toggle is a
|
|
3653
|
+
// convenience, this is the daemon's answer (§4.1).
|
|
3654
|
+
readOnly,
|
|
3655
|
+
// A session stays reachable for fifteen minutes after its process
|
|
3656
|
+
// exits, and a viewer joining in that window is told so at once,
|
|
3657
|
+
// rather than shown a terminal that looks alive.
|
|
3658
|
+
exited: session.exited,
|
|
3659
|
+
exitCode: session.exitCode,
|
|
3660
|
+
// Likewise a session whose input has failed, before the viewer types.
|
|
3661
|
+
inputFailed: session.inputFailed,
|
|
3662
|
+
}));
|
|
3663
|
+
// Settle geometry from the SERVER on connect, before the viewer decides
|
|
3664
|
+
// anything for itself. A viewer that fitted on open would resize the PTY
|
|
3665
|
+
// before it could learn whether it was entitled to. The frame below says
|
|
3666
|
+
// which of the three positions this viewer is in, so the choice is made
|
|
3667
|
+
// knowing the answer rather than raced against it.
|
|
3668
|
+
//
|
|
3669
|
+
// This MUST precede the snapshot below: the viewer writes snapshot bytes
|
|
3670
|
+
// into whatever grid it currently has, so sizing it afterwards reflows
|
|
3671
|
+
// content that was already laid out at the wrong width.
|
|
3672
|
+
//
|
|
3673
|
+
// Nobody driving, and free to be driven: this viewport picks it up, and
|
|
3674
|
+
// will propose a grid that fills its window. A read-only credential never
|
|
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 &&
|
|
3690
|
+
!readOnly &&
|
|
3691
|
+
!passive &&
|
|
3692
|
+
!this.hasGeometryController(session.id)) {
|
|
3693
|
+
this.geometryController.set(session.id, ws);
|
|
3694
|
+
this.dashboardGeometryOwner.delete(session.id);
|
|
3695
|
+
}
|
|
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 }));
|
|
3699
|
+
// What the daemon renders, as the bytes that rebuild it (design §5). Not
|
|
3700
|
+
// a slice of the raw stream: a slice starts mid-frame, and a program that
|
|
3701
|
+
// only repaints what changed never puts the rest of its frame back. Every
|
|
3702
|
+
// agent CLI repaints that way once its chrome is up, and on Windows every
|
|
3703
|
+
// program does as ConPTY relays it. Live bytes queue behind the
|
|
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
|
+
}
|
|
3719
|
+
sync.resync();
|
|
3720
|
+
// Whoever was watching when the process exited got this notice on the
|
|
3721
|
+
// wire, and someone who arrives inside the fifteen-minute grace is owed
|
|
3722
|
+
// the same thing: without it the screen is just the program's last frame,
|
|
3723
|
+
// which looks exactly like a program that is still there. Delivered
|
|
3724
|
+
// AFTER the resync, so the gate holds it behind the snapshot instead of
|
|
3725
|
+
// letting the snapshot's wipe erase it.
|
|
3726
|
+
if (session.exited) {
|
|
3727
|
+
sync.deliver(exitNotice(session.exitCode));
|
|
3728
|
+
}
|
|
3729
|
+
// A stall is announced once, at the moment it trips. Someone who opens the
|
|
3730
|
+
// viewer BECAUSE they were told a session is stuck arrives after
|
|
3731
|
+
// the only announcement, and is the exact person the badge is for. Replay the
|
|
3732
|
+
// current state to them.
|
|
3733
|
+
const held = this.promptStates.get(session.id);
|
|
3734
|
+
if (held?.alerted === true) {
|
|
3735
|
+
ws.send(JSON.stringify({
|
|
3736
|
+
type: 'prompt-stall',
|
|
3737
|
+
waitingMs: Date.now() - held.since,
|
|
3738
|
+
question: held.prompt.question,
|
|
3739
|
+
options: held.prompt.options,
|
|
3740
|
+
...(held.prompt.selectedOption === undefined ? {} : { selectedOption: held.prompt.selectedOption }),
|
|
3741
|
+
}));
|
|
3742
|
+
}
|
|
3743
|
+
const unsubscribeData = session.onData((data) => sync.deliver(data));
|
|
3744
|
+
this.updateFeedSession(session.id);
|
|
3745
|
+
const unsubscribeExit = session.onExit((exitCode) => {
|
|
3746
|
+
sync.deliver(exitNotice(exitCode));
|
|
3747
|
+
// The notice is bytes on the terminal; the page needs a frame to change
|
|
3748
|
+
// its own state.
|
|
3749
|
+
if (ws.readyState === ws.OPEN) {
|
|
3750
|
+
ws.send(JSON.stringify({ type: 'exited', exitCode }));
|
|
3751
|
+
}
|
|
3752
|
+
});
|
|
3753
|
+
// A protocol error, such as a malformed frame or a reset mid-handshake,
|
|
3754
|
+
// is logged and closes the socket rather than escaping as an uncaught
|
|
3755
|
+
// exception. The close handler below does the bookkeeping either way.
|
|
3756
|
+
ws.on('error', (error) => {
|
|
3757
|
+
this.logger.warn('viewer socket error', { id: session.id, error: String(error) });
|
|
3758
|
+
ws.close();
|
|
3759
|
+
});
|
|
3760
|
+
/** Whether this socket has been told that the session's input has failed. */
|
|
3761
|
+
let toldInputFailed = false;
|
|
3762
|
+
const onViewerMessage = async (message) => {
|
|
3763
|
+
this.lastActivity = Date.now();
|
|
3764
|
+
const text = typeof message === 'string' ? message : message.toString('utf8');
|
|
3765
|
+
try {
|
|
3766
|
+
const parsed = JSON.parse(text);
|
|
3767
|
+
if (typeof parsed === 'object' &&
|
|
3768
|
+
parsed !== null &&
|
|
3769
|
+
parsed.type === 'resize') {
|
|
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;
|
|
3778
|
+
if (!readOnly &&
|
|
3779
|
+
typeof cols === 'number' &&
|
|
3780
|
+
typeof rows === 'number' &&
|
|
3781
|
+
Number.isInteger(cols) &&
|
|
3782
|
+
Number.isInteger(rows) &&
|
|
3783
|
+
cols >= 2 &&
|
|
3784
|
+
cols <= 1_000 &&
|
|
3785
|
+
rows >= 2 &&
|
|
3786
|
+
rows <= 500 &&
|
|
3787
|
+
!session.exited) {
|
|
3788
|
+
if (session.geometryHeld) {
|
|
3789
|
+
// Held against viewports. Answer with the real grid so the page
|
|
3790
|
+
// stops proposing one it will never be given.
|
|
3791
|
+
ws.send(JSON.stringify(this.geometryFrame(session, ws)));
|
|
3792
|
+
return;
|
|
3793
|
+
}
|
|
3794
|
+
const wanted = {
|
|
3795
|
+
cols: Math.min(cols, MAX_VIEWPORT_COLS),
|
|
3796
|
+
rows: Math.min(rows, MAX_VIEWPORT_ROWS),
|
|
3797
|
+
};
|
|
3798
|
+
const handedOver = this.geometryController.get(session.id) !== ws;
|
|
3799
|
+
const changed = wanted.cols !== session.cols || wanted.rows !== session.rows;
|
|
3800
|
+
let applied = false;
|
|
3801
|
+
try {
|
|
3802
|
+
await session.resize(wanted.cols, wanted.rows);
|
|
3803
|
+
applied = true;
|
|
3804
|
+
}
|
|
3805
|
+
catch (error) {
|
|
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.
|
|
3818
|
+
this.logger.warn('viewer resize failed', {
|
|
3819
|
+
id: session.id,
|
|
3820
|
+
error: String(error),
|
|
3821
|
+
});
|
|
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);
|
|
3831
|
+
// A geometry change is a geometry change whoever made it, and
|
|
3832
|
+
// `resize` is on the list of audited actions the security page
|
|
3833
|
+
// publishes. Only the ones that actually took: a proposal the
|
|
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).
|
|
3838
|
+
if (changed && applied) {
|
|
3839
|
+
this.audit.record(actor, 'resize', session.id, {
|
|
3840
|
+
cols: wanted.cols,
|
|
3841
|
+
rows: wanted.rows,
|
|
3842
|
+
hold: false,
|
|
3843
|
+
});
|
|
3844
|
+
}
|
|
3845
|
+
// Everyone sees the same grid, and each is told whether they are
|
|
3846
|
+
// now driving it. A proposal that changed nothing needs no
|
|
3847
|
+
// snapshot, because the page already shows this grid. But if the
|
|
3848
|
+
// grid changed hands, everyone is told that much, or the old
|
|
3849
|
+
// driver goes on believing it is theirs.
|
|
3850
|
+
if (changed)
|
|
3851
|
+
this.announceGeometry(session.id, session);
|
|
3852
|
+
else if (handedOver)
|
|
3853
|
+
this.announceGeometry(session.id, session, { resync: false });
|
|
3854
|
+
else if (take === true)
|
|
3855
|
+
ws.send(JSON.stringify(this.geometryFrame(session, ws)));
|
|
3856
|
+
}
|
|
3857
|
+
return;
|
|
3858
|
+
}
|
|
3859
|
+
}
|
|
3860
|
+
catch {
|
|
3861
|
+
// Not JSON: bytes for the program, a person's keystrokes or the
|
|
3862
|
+
// viewer's terminal answering the program. Straight into the PTY
|
|
3863
|
+
// either way: shared typing is the point of the tool.
|
|
3864
|
+
}
|
|
3865
|
+
if (readOnly) {
|
|
3866
|
+
// A watch-only credential. Dropped silently and on the daemon's side:
|
|
3867
|
+
// the page has already been told it is read-only and disables its own
|
|
3868
|
+
// input, so anything arriving here is not a human mistyping.
|
|
3869
|
+
return;
|
|
3870
|
+
}
|
|
3871
|
+
if (session.exited) {
|
|
3872
|
+
// A session stays reachable for fifteen minutes after its process
|
|
3873
|
+
// exits, and input typed into that window is refused out loud, as the
|
|
3874
|
+
// HTTP path refuses it with a 409.
|
|
3875
|
+
// Told to this socket alone: the other watchers did not type it.
|
|
3876
|
+
if (ws.readyState === ws.OPEN) {
|
|
3877
|
+
ws.send(JSON.stringify({
|
|
3878
|
+
type: 'input-refused',
|
|
3879
|
+
reason: 'exited',
|
|
3880
|
+
exitCode: session.exitCode,
|
|
3881
|
+
}));
|
|
3882
|
+
}
|
|
3883
|
+
return;
|
|
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
|
+
}
|
|
3896
|
+
// write() is async, so a failure arrives as a rejection and never as a
|
|
3897
|
+
// synchronous throw: a try/catch here would be dead code. Not awaited:
|
|
3898
|
+
// this is the viewer's data handler and must stay responsive, and
|
|
3899
|
+
// ordering is guaranteed inside write() by its queue rather than here.
|
|
3900
|
+
// (xterm hands us multi-character strings for pastes and escape
|
|
3901
|
+
// sequences, so this is not always one keystroke.) .catch keeps the exit
|
|
3902
|
+
// race, the session dying mid-write, from escaping as an unhandled
|
|
3903
|
+
// rejection.
|
|
3904
|
+
void session.write(text).catch((error) => {
|
|
3905
|
+
this.logger.warn('viewer input failed', {
|
|
3906
|
+
id: session.id,
|
|
3907
|
+
error: String(error),
|
|
3908
|
+
});
|
|
3909
|
+
});
|
|
3910
|
+
// The viewer's terminal answering the program, such as where the cursor
|
|
3911
|
+
// is or that the window gained focus, is written above like a keystroke
|
|
3912
|
+
// because the program asked for it. Nobody typed it, so it is audited
|
|
3913
|
+
// as a report and leaves the "last input" indicator alone (§4.5, §5).
|
|
3914
|
+
// Content only under captureContent, as for input.
|
|
3915
|
+
const report = terminalReportKind(text);
|
|
3916
|
+
if (report !== null) {
|
|
3917
|
+
this.audit.record(actor, 'report', session.id, {
|
|
3918
|
+
kind: report,
|
|
3919
|
+
chars: text.length,
|
|
3920
|
+
...(this.audit.captureContent ? { data: text } : {}),
|
|
3921
|
+
});
|
|
3922
|
+
return;
|
|
3923
|
+
}
|
|
3924
|
+
this.audit.record(actor, 'input', session.id, {
|
|
3925
|
+
chars: text.length,
|
|
3926
|
+
...(this.audit.captureContent ? { data: text } : {}),
|
|
3927
|
+
});
|
|
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
|
+
});
|
|
3934
|
+
});
|
|
3935
|
+
ws.on('close', () => {
|
|
3936
|
+
unsubscribeData();
|
|
3937
|
+
unsubscribeExit();
|
|
3938
|
+
sync.close();
|
|
3939
|
+
this.sockets.delete(ws);
|
|
3940
|
+
this.sessionSockets.get(session.id)?.delete(ws);
|
|
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.
|
|
3946
|
+
if (this.geometryController.get(session.id) === ws) {
|
|
3947
|
+
this.geometryController.delete(session.id);
|
|
3948
|
+
}
|
|
3949
|
+
this.lastActivity = Date.now();
|
|
3950
|
+
this.audit.record(actor, 'ws-close', session.id);
|
|
3951
|
+
});
|
|
3952
|
+
}
|
|
3953
|
+
}
|
|
3954
|
+
//# sourceMappingURL=server.js.map
|