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.
Files changed (137) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +31 -0
  3. package/README.md +499 -8
  4. package/dist/cli/desktopShortcut.d.ts +22 -0
  5. package/dist/cli/desktopShortcut.js +157 -0
  6. package/dist/cli/desktopShortcut.js.map +1 -0
  7. package/dist/cli/index.d.ts +13 -0
  8. package/dist/cli/index.js +846 -0
  9. package/dist/cli/index.js.map +1 -0
  10. package/dist/client/http.d.ts +143 -0
  11. package/dist/client/http.js +581 -0
  12. package/dist/client/http.js.map +1 -0
  13. package/dist/core/dialogs.d.ts +96 -0
  14. package/dist/core/dialogs.js +226 -0
  15. package/dist/core/dialogs.js.map +1 -0
  16. package/dist/core/echo.d.ts +71 -0
  17. package/dist/core/echo.js +249 -0
  18. package/dist/core/echo.js.map +1 -0
  19. package/dist/core/find.d.ts +34 -0
  20. package/dist/core/find.js +41 -0
  21. package/dist/core/find.js.map +1 -0
  22. package/dist/core/keys.d.ts +22 -0
  23. package/dist/core/keys.js +80 -0
  24. package/dist/core/keys.js.map +1 -0
  25. package/dist/core/manager.d.ts +96 -0
  26. package/dist/core/manager.js +271 -0
  27. package/dist/core/manager.js.map +1 -0
  28. package/dist/core/nativePty.d.ts +73 -0
  29. package/dist/core/nativePty.js +161 -0
  30. package/dist/core/nativePty.js.map +1 -0
  31. package/dist/core/policy.d.ts +61 -0
  32. package/dist/core/policy.js +143 -0
  33. package/dist/core/policy.js.map +1 -0
  34. package/dist/core/promptDetector.d.ts +109 -0
  35. package/dist/core/promptDetector.js +897 -0
  36. package/dist/core/promptDetector.js.map +1 -0
  37. package/dist/core/reasoning.d.ts +265 -0
  38. package/dist/core/reasoning.js +933 -0
  39. package/dist/core/reasoning.js.map +1 -0
  40. package/dist/core/regexBudget.d.ts +64 -0
  41. package/dist/core/regexBudget.js +103 -0
  42. package/dist/core/regexBudget.js.map +1 -0
  43. package/dist/core/renderer.d.ts +127 -0
  44. package/dist/core/renderer.js +316 -0
  45. package/dist/core/renderer.js.map +1 -0
  46. package/dist/core/selection.d.ts +6 -0
  47. package/dist/core/selection.js +48 -0
  48. package/dist/core/selection.js.map +1 -0
  49. package/dist/core/session.d.ts +565 -0
  50. package/dist/core/session.js +1450 -0
  51. package/dist/core/session.js.map +1 -0
  52. package/dist/core/types.d.ts +316 -0
  53. package/dist/core/types.js +71 -0
  54. package/dist/core/types.js.map +1 -0
  55. package/dist/core/waiter.d.ts +94 -0
  56. package/dist/core/waiter.js +310 -0
  57. package/dist/core/waiter.js.map +1 -0
  58. package/dist/core/windowsConsoleHost.d.ts +147 -0
  59. package/dist/core/windowsConsoleHost.js +588 -0
  60. package/dist/core/windowsConsoleHost.js.map +1 -0
  61. package/dist/core/windowsPtyStart.d.ts +161 -0
  62. package/dist/core/windowsPtyStart.js +236 -0
  63. package/dist/core/windowsPtyStart.js.map +1 -0
  64. package/dist/daemon/audit.d.ts +23 -0
  65. package/dist/daemon/audit.js +51 -0
  66. package/dist/daemon/audit.js.map +1 -0
  67. package/dist/daemon/auth.d.ts +197 -0
  68. package/dist/daemon/auth.js +366 -0
  69. package/dist/daemon/auth.js.map +1 -0
  70. package/dist/daemon/config.d.ts +119 -0
  71. package/dist/daemon/config.js +568 -0
  72. package/dist/daemon/config.js.map +1 -0
  73. package/dist/daemon/folderPicker.d.ts +27 -0
  74. package/dist/daemon/folderPicker.js +115 -0
  75. package/dist/daemon/folderPicker.js.map +1 -0
  76. package/dist/daemon/index.d.ts +7 -0
  77. package/dist/daemon/index.js +88 -0
  78. package/dist/daemon/index.js.map +1 -0
  79. package/dist/daemon/launchProfiles.d.ts +155 -0
  80. package/dist/daemon/launchProfiles.js +554 -0
  81. package/dist/daemon/launchProfiles.js.map +1 -0
  82. package/dist/daemon/liveness.d.ts +36 -0
  83. package/dist/daemon/liveness.js +71 -0
  84. package/dist/daemon/liveness.js.map +1 -0
  85. package/dist/daemon/logger.d.ts +7 -0
  86. package/dist/daemon/logger.js +29 -0
  87. package/dist/daemon/logger.js.map +1 -0
  88. package/dist/daemon/meta.d.ts +9 -0
  89. package/dist/daemon/meta.js +24 -0
  90. package/dist/daemon/meta.js.map +1 -0
  91. package/dist/daemon/paths.d.ts +85 -0
  92. package/dist/daemon/paths.js +154 -0
  93. package/dist/daemon/paths.js.map +1 -0
  94. package/dist/daemon/screenshot.d.ts +144 -0
  95. package/dist/daemon/screenshot.js +402 -0
  96. package/dist/daemon/screenshot.js.map +1 -0
  97. package/dist/daemon/server.d.ts +453 -0
  98. package/dist/daemon/server.js +3954 -0
  99. package/dist/daemon/server.js.map +1 -0
  100. package/dist/daemon/sessionFeed.d.ts +48 -0
  101. package/dist/daemon/sessionFeed.js +101 -0
  102. package/dist/daemon/sessionFeed.js.map +1 -0
  103. package/dist/daemon/terminalReports.d.ts +38 -0
  104. package/dist/daemon/terminalReports.js +84 -0
  105. package/dist/daemon/terminalReports.js.map +1 -0
  106. package/dist/daemon/viewerLauncher.d.ts +226 -0
  107. package/dist/daemon/viewerLauncher.js +562 -0
  108. package/dist/daemon/viewerLauncher.js.map +1 -0
  109. package/dist/daemon/viewerSync.d.ts +38 -0
  110. package/dist/daemon/viewerSync.js +83 -0
  111. package/dist/daemon/viewerSync.js.map +1 -0
  112. package/dist/mcp/config.d.ts +50 -0
  113. package/dist/mcp/config.js +95 -0
  114. package/dist/mcp/config.js.map +1 -0
  115. package/dist/mcp/index.d.ts +10 -0
  116. package/dist/mcp/index.js +78 -0
  117. package/dist/mcp/index.js.map +1 -0
  118. package/dist/mcp/tools.d.ts +66 -0
  119. package/dist/mcp/tools.js +638 -0
  120. package/dist/mcp/tools.js.map +1 -0
  121. package/dist/viewer/dashboard-folders.js +20 -0
  122. package/dist/viewer/dashboard-layout.js +52 -0
  123. package/dist/viewer/dashboard.css +67 -0
  124. package/dist/viewer/dashboard.html +44 -0
  125. package/dist/viewer/dashboard.js +1518 -0
  126. package/dist/viewer/icon-16.png +0 -0
  127. package/dist/viewer/icon-180.png +0 -0
  128. package/dist/viewer/icon-32.png +0 -0
  129. package/dist/viewer/icon-512.png +0 -0
  130. package/dist/viewer/icon.ico +0 -0
  131. package/dist/viewer/icon.svg +66 -0
  132. package/dist/viewer/index.html +61 -0
  133. package/dist/viewer/pane.js +736 -0
  134. package/dist/viewer/viewer.css +95 -0
  135. package/dist/viewer/viewer.js +84 -0
  136. package/package.json +66 -7
  137. package/index.js +0 -4
@@ -0,0 +1,562 @@
1
+ /**
2
+ * Opening the viewer in its own browser window.
3
+ *
4
+ * Two problems with handing the URL to the default browser
5
+ * (`launchMode: "default-browser"`), which opens it in the user's normal
6
+ * profile:
7
+ *
8
+ * 1. The viewer then shares a browsing context with every other page that
9
+ * profile has open: cookie jar, storage and history. Loopback is not a boundary
10
+ * against the browser itself. The daemon's Host/Origin checks and bearer
11
+ * auth (§4.2) are what holds this; a separate profile removes the exposure
12
+ * rather than defending it.
13
+ * 2. The viewer grant is in the URL, so it lands in that profile's history.
14
+ *
15
+ * **Why no bundled browser.** The viewer IS a web page: a browser is already a
16
+ * hard prerequisite for ShellPuppet to be usable at all. Bundling one
17
+ * (Playwright's ~130 MB download, or Electron) adds a very large dependency to
18
+ * solve a problem every user already has a browser for. Playwright is the
19
+ * wrong shape besides, being built to DRIVE a page while here a human does.
20
+ * So: detect an installed Chromium-family browser, and degrade gracefully when
21
+ * there is none. `chrome-launcher` (Apache-2.0, ~140 KB) does the fiddly
22
+ * cross-platform detection, which is exactly the part that would otherwise
23
+ * be machine-specific guesswork: the install folders on Windows,
24
+ * LaunchServices on macOS, `.desktop` files and PATH on Linux. On macOS and
25
+ * Linux the part of that search which shells out runs in a child process,
26
+ * never in the daemon (`detectBrowser`); on Windows the paths checked by
27
+ * file access are the whole search, so the child is not run. A lookup that
28
+ * times out, crashes or returns something other than a JSON list is logged
29
+ * once. We spawn the browser ourselves, because the detachment discipline
30
+ * below is not negotiable.
31
+ *
32
+ * Nothing here may ever fail a session start. A browser that will not launch is
33
+ * an inconvenience: the launcher reports that nothing opened, the daemon hands
34
+ * the caller the URL instead, and the human can open it themselves. That report
35
+ * has to be truthful, because the caller is told the human needs no link when a
36
+ * window opened: a spawn settles on the child's `spawn` or `error` event, and
37
+ * the system's opener (`start`, `open`, `xdg-open`) on its exit code.
38
+ */
39
+ import { execFile, spawn } from 'node:child_process';
40
+ import * as fs from 'node:fs';
41
+ import { createRequire } from 'node:module';
42
+ import * as path from 'node:path';
43
+ import { pathToFileURL } from 'node:url';
44
+ import { NULL_LOGGER } from '../core/types.js';
45
+ /** A stalled filesystem check cannot hold browser detection indefinitely. */
46
+ const BROWSER_ACCESS_TIMEOUT_MS = 1_500;
47
+ /** Bound the wait for Node's spawn or error event, including dashboard launches. */
48
+ const BROWSER_SPAWN_TIMEOUT_MS = 3_000;
49
+ /**
50
+ * Chromium-family browsers that `chrome-launcher` does NOT look for, checked
51
+ * after it. Edge earns its place: it ships with Windows, so including it means
52
+ * a Windows machine effectively always has a usable browser even with no
53
+ * Chrome installed. Paths only, never a bare name, because a bare name would
54
+ * resolve against PATH and PATH is attacker-influenced on a shared machine.
55
+ */
56
+ export function extraBrowserCandidates() {
57
+ const env = process.env;
58
+ if (process.platform === 'win32') {
59
+ const roots = [env['PROGRAMFILES(X86)'], env['PROGRAMFILES'], env['LOCALAPPDATA']].filter((value) => typeof value === 'string' && value !== '');
60
+ const relative = [
61
+ path.join('Microsoft', 'Edge', 'Application', 'msedge.exe'),
62
+ path.join('BraveSoftware', 'Brave-Browser', 'Application', 'brave.exe'),
63
+ path.join('Vivaldi', 'Application', 'vivaldi.exe'),
64
+ ];
65
+ return roots.flatMap((root) => relative.map((rel) => path.join(root, rel)));
66
+ }
67
+ if (process.platform === 'darwin') {
68
+ return [
69
+ '/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge',
70
+ '/Applications/Brave Browser.app/Contents/MacOS/Brave Browser',
71
+ '/Applications/Vivaldi.app/Contents/MacOS/Vivaldi',
72
+ ];
73
+ }
74
+ return [
75
+ '/usr/bin/microsoft-edge',
76
+ '/usr/bin/brave-browser',
77
+ '/usr/bin/vivaldi',
78
+ '/usr/bin/chromium',
79
+ '/usr/bin/chromium-browser',
80
+ ];
81
+ }
82
+ /**
83
+ * The Chrome installations `chrome-launcher` checks by file access alone,
84
+ * before any lookup that shells out, in the order it ranks them: the
85
+ * `CHROME_PATH` and `LIGHTHOUSE_CHROMIUM_PATH` overrides first everywhere; on
86
+ * Windows its whole search, which is these paths and nothing else; on macOS
87
+ * the two `/Applications` bundles its own `getFirstInstallation()` checks
88
+ * before its LaunchServices query, which rank above anything that query
89
+ * finds. Linux has only the overrides here: its lookup reads `.desktop` files
90
+ * and PATH, which a fixed list cannot match.
91
+ */
92
+ export function wellKnownChromePaths(platform = process.platform, env = process.env) {
93
+ const overrides = [env['CHROME_PATH'], env['LIGHTHOUSE_CHROMIUM_PATH']].filter((value) => typeof value === 'string' && value !== '');
94
+ if (platform === 'win32') {
95
+ const roots = [env['LOCALAPPDATA'], env['PROGRAMFILES'], env['PROGRAMFILES(X86)']].filter((value) => typeof value === 'string' && value !== '');
96
+ const relative = [
97
+ path.join('Google', 'Chrome SxS', 'Application', 'chrome.exe'),
98
+ path.join('Google', 'Chrome', 'Application', 'chrome.exe'),
99
+ ];
100
+ return [...overrides, ...roots.flatMap((root) => relative.map((rel) => path.join(root, rel)))];
101
+ }
102
+ if (platform === 'darwin') {
103
+ return [
104
+ ...overrides,
105
+ '/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary',
106
+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
107
+ ];
108
+ }
109
+ return overrides;
110
+ }
111
+ /**
112
+ * How long chrome-launcher's full lookup may take. Its macOS query took 5.7 s
113
+ * and 9.7 s on macOS CI runners, so this leaves room for a slower machine.
114
+ */
115
+ export const BROWSER_LOOKUP_TIMEOUT_MS = 30_000;
116
+ const nodeRequire = createRequire(import.meta.url);
117
+ /** The detection the daemon runs: chrome-launcher's, then the supplementary list. */
118
+ export function defaultBrowserDetection() {
119
+ let lookupModule = '';
120
+ // On Windows, `wellKnownChromePaths` is chrome-launcher's entire search,
121
+ // so a child lookup cannot find a browser that list missed. macOS and
122
+ // Linux search beyond a fixed list, and that lookup runs in a child.
123
+ if (process.platform !== 'win32') {
124
+ try {
125
+ lookupModule = pathToFileURL(nodeRequire.resolve('chrome-launcher')).href;
126
+ }
127
+ catch {
128
+ // Not installed: the well-known and supplementary paths still apply.
129
+ }
130
+ }
131
+ return {
132
+ wellKnown: wellKnownChromePaths(),
133
+ lookupModule,
134
+ lookupTimeoutMs: BROWSER_LOOKUP_TIMEOUT_MS,
135
+ extra: extraBrowserCandidates(),
136
+ };
137
+ }
138
+ /**
139
+ * Find a Chromium-family browser, or null. Detection can never stop the
140
+ * daemon from serving: nothing here throws, and no part of it holds the
141
+ * daemon's event loop (see `detectBrowser`).
142
+ */
143
+ export async function findBrowser(explicitPath, logger = NULL_LOGGER) {
144
+ if (explicitPath !== undefined && explicitPath !== '') {
145
+ // Never cached: an operator who names a binary means that binary, and the
146
+ // answer is a single file check anyway.
147
+ return (await exists(explicitPath)) ? explicitPath : null;
148
+ }
149
+ // Detection is memoised for the daemon's lifetime because it is NOT cheap:
150
+ // chrome-launcher's macOS lookup (a LaunchServices query) took 5.7 s and
151
+ // 9.7 s on macOS CI runners. A session start waits for the launch, so the
152
+ // daemon looks once as it starts (server.ts) and every start after that
153
+ // finds the answer ready; it changes only when someone installs a browser.
154
+ // A daemon restart re-detects.
155
+ // The promise is memoised, not the value, so a caller that arrives while
156
+ // detection is still running waits for the rest of it instead of starting
157
+ // a second detection of its own.
158
+ cachedDetection ??= detectBrowser(defaultBrowserDetection(), logger);
159
+ return cachedDetection;
160
+ }
161
+ /** Memoised detection; `undefined` means "not looked yet". */
162
+ let cachedDetection;
163
+ /** Test hook: forget the memoised browser so detection runs again. */
164
+ export function resetBrowserCache() {
165
+ cachedDetection = undefined;
166
+ }
167
+ /**
168
+ * Detect a browser without holding the daemon's event loop. chrome-launcher's
169
+ * lookup is synchronous and shells out on macOS (`lsregister -dump`, seconds)
170
+ * and Linux (`grep` over `.desktop` files, `which`). Run in the daemon, it
171
+ * would stop `/health` and every other request being answered while it ran,
172
+ * on macOS for long enough that a client gives up on a daemon it has just
173
+ * started. So the paths chrome-launcher itself checks first are tried with
174
+ * asynchronous file checks; only when none exists does its full lookup run,
175
+ * in a child process; and the supplementary list is checked last. On Windows
176
+ * the default detection leaves that lookup empty, because the well-known
177
+ * paths are the whole search. The answer is the one chrome-launcher's own
178
+ * ranking gives, then the first supplementary browser present. A lookup that
179
+ * times out, crashes or prints something other than a JSON list is logged
180
+ * once, through `logger`.
181
+ */
182
+ export async function detectBrowser(detection = defaultBrowserDetection(), logger = NULL_LOGGER) {
183
+ const known = await firstExisting(detection.wellKnown);
184
+ if (known !== null)
185
+ return known;
186
+ if (detection.lookupModule !== '') {
187
+ const found = await lookUpInChild(detection.lookupModule, detection.lookupTimeoutMs, logger);
188
+ if (found !== null)
189
+ return found;
190
+ }
191
+ return firstExisting(detection.extra);
192
+ }
193
+ async function exists(file) {
194
+ let timer;
195
+ try {
196
+ return await Promise.race([
197
+ fs.promises.access(file).then(() => true, () => false),
198
+ new Promise((resolve) => {
199
+ timer = setTimeout(() => resolve(false), BROWSER_ACCESS_TIMEOUT_MS);
200
+ }),
201
+ ]);
202
+ }
203
+ catch {
204
+ return false;
205
+ }
206
+ finally {
207
+ if (timer !== undefined)
208
+ clearTimeout(timer);
209
+ }
210
+ }
211
+ async function firstExisting(candidates) {
212
+ for (const candidate of candidates) {
213
+ if (await exists(candidate))
214
+ return candidate;
215
+ }
216
+ return null;
217
+ }
218
+ /**
219
+ * What the child process runs: import the module named by its one argument,
220
+ * an absolute file URL, so nothing depends on the child's working directory,
221
+ * and print what `getInstallations()` returns as JSON. A lookup that throws
222
+ * (chrome-launcher's does on Linux when it finds nothing) prints an empty list.
223
+ */
224
+ const LOOKUP_SCRIPT = [
225
+ 'let found = [];',
226
+ 'try {',
227
+ ' const { Launcher } = await import(process.argv[1]);',
228
+ ' found = Launcher.getInstallations();',
229
+ '} catch {',
230
+ ' found = [];',
231
+ '}',
232
+ 'process.stdout.write(JSON.stringify(found));',
233
+ ].join('\n');
234
+ function lookUpInChild(moduleUrl, timeoutMs, logger) {
235
+ const fail = (reason, resolve) => {
236
+ logger.warn('browser lookup failed', { reason });
237
+ resolve(null);
238
+ };
239
+ return new Promise((resolve) => {
240
+ try {
241
+ execFile(process.execPath, ['--input-type=module', '-e', LOOKUP_SCRIPT, moduleUrl], { timeout: timeoutMs, windowsHide: true, encoding: 'utf8', maxBuffer: 1024 * 1024 }, (error, stdout) => {
242
+ if (error !== null) {
243
+ fail(error.message, resolve);
244
+ return;
245
+ }
246
+ try {
247
+ const parsed = JSON.parse(stdout);
248
+ if (!Array.isArray(parsed)) {
249
+ fail('unreadable output', resolve);
250
+ return;
251
+ }
252
+ const first = parsed[0];
253
+ // An empty list is a lookup that found nothing, not a failure.
254
+ resolve(typeof first === 'string' && first !== '' ? first : null);
255
+ }
256
+ catch {
257
+ fail('unreadable output', resolve);
258
+ }
259
+ });
260
+ }
261
+ catch (error) {
262
+ fail(error instanceof Error ? error.message : 'lookup failed', resolve);
263
+ }
264
+ });
265
+ }
266
+ /**
267
+ * Open `url` in a chromeless window backed by its own browser profile.
268
+ *
269
+ * `--app=` removes the address bar, tabs and navigation. A terminal viewer has
270
+ * no use for them, and the address bar is where the viewer grant would
271
+ * otherwise be on display. `--user-data-dir` is the isolation: its own cookie
272
+ * jar, storage and history, invisible to the user's normal browsing and vice
273
+ * versa.
274
+ *
275
+ * The profile directory is per-daemon rather than per-session, so window
276
+ * position and the text-size preference persist across sessions. A per-session
277
+ * profile would isolate marginally harder at the cost of a cold browser start
278
+ * every time, which is the wrong trade for a window a human is meant to keep
279
+ * open and glance at.
280
+ */
281
+ export function isolatedWindowArgs(url, profileDir) {
282
+ return [
283
+ `--app=${url}`,
284
+ `--user-data-dir=${profileDir}`,
285
+ '--new-window',
286
+ // First-run flows would hijack the window with a sign-in wizard; the
287
+ // default-browser prompt would ask to change a setting the user never
288
+ // asked to change from a window they did not open.
289
+ '--no-first-run',
290
+ '--no-default-browser-check',
291
+ ...QUIET_BROWSER_SWITCHES,
292
+ ];
293
+ }
294
+ /**
295
+ * Switches that ask a Chromium-family browser ShellPuppet starts, the viewer
296
+ * window and the screenshot browser alike, to make no network requests of its
297
+ * own: updates, reports and the services a browser contacts in the
298
+ * background. Nothing leaves the machine unless a human sends it or switches
299
+ * it on, and nobody asked these browsers to call anywhere. Each switch is
300
+ * documented in Chromium's source, named beside it; none changes what a page
301
+ * can do, so the viewer and its WebSocket to the daemon work as they would
302
+ * without them.
303
+ *
304
+ * They ask, and they do not reach everything. A NetLog of a fresh Chrome
305
+ * started with them, over its first minute, still showed its component
306
+ * updater, a Safe Browsing key fetch, an account check and a search endpoint
307
+ * contacted, none of which these switches turn off; a vendor's own services,
308
+ * such as Edge's, may be beyond Chromium's switches too.
309
+ */
310
+ export const QUIET_BROWSER_SWITCHES = [
311
+ // chrome/common/chrome_switches.h: "Disable several subsystems which run
312
+ // network requests in the background."
313
+ '--disable-background-networking',
314
+ // chrome/common/chrome_switches.h: no updates for the components listed at
315
+ // chrome://components.
316
+ '--disable-component-update',
317
+ // chrome/common/chrome_switches.h: "Disable default component extensions
318
+ // with background pages."
319
+ '--disable-component-extensions-with-background-pages',
320
+ // chrome/common/chrome_switches.h: "Disables installation of default apps
321
+ // on first run."
322
+ '--disable-default-apps',
323
+ // chrome/common/chrome_switches.h: "Disables Domain Reliability Monitoring."
324
+ '--disable-domain-reliability',
325
+ // components/sync/base/command_line_switches.h: "Disables syncing browser
326
+ // data to a Google Account."
327
+ '--disable-sync',
328
+ // components/metrics/metrics_switches.h: "Enables the recording of metrics
329
+ // reports but disables reporting."
330
+ '--metrics-recording-only',
331
+ // base/base_switches.h: "Disables the crash reporting."
332
+ '--disable-breakpad',
333
+ // components/variations/variations_switches.cc: "Disable fetching of
334
+ // variations seed from the server."
335
+ '--disable-variations-seed-fetch',
336
+ // chrome/common/chrome_switches.h: "Don't use a proxy server, always make
337
+ // direct connections." With the system's proxy detection on, a browser
338
+ // looks for a `wpad` host on the local network. Both pages talk to
339
+ // 127.0.0.1 alone, which Chromium never sends through a proxy.
340
+ '--no-proxy-server',
341
+ // base/base_switches.h: "Comma-separated list of feature names to disable."
342
+ // One switch for every name, because Chromium keeps only the last. The
343
+ // names are features in Chromium's source:
344
+ // components/optimization_guide/core/optimization_guide_features.cc, the
345
+ // Optimization Hints component's syncing and the prediction models a
346
+ // browser downloads; components/network_time/network_time_tracker.cc, the
347
+ // network time queries. A name a later Chromium no longer knows is ignored,
348
+ // and that feature keeps its default.
349
+ '--disable-features=OptimizationHints,OptimizationTargetPrediction,NetworkTimeServiceQuerying',
350
+ ];
351
+ export async function launchViewer(url, home, config, logger, deps = {}) {
352
+ return launchWindow(url, home, config, logger, deps, true);
353
+ }
354
+ /**
355
+ * Open the dashboard in ShellPuppet's isolated browser profile, and never in
356
+ * the person's default browser.
357
+ *
358
+ * The dashboard URL carries the one-use grant, so the profile it lands in has
359
+ * to be the one ShellPuppet owns. `viewer.launchMode` is deliberately not
360
+ * consulted: `shellpuppet dashboard` exists to open a window, and a mode meant
361
+ * for automatic viewer windows must not turn that into a default-browser
362
+ * hand-off. `viewer.browserPath` and `viewer.profileDir` still apply.
363
+ *
364
+ * `deps` is accepted so a test can inject a recording opener and prove that a
365
+ * failure never reaches it.
366
+ */
367
+ export async function launchDashboard(url, home, config, logger, deps = {}) {
368
+ return launchWindow(url, home, { ...config, launchMode: 'isolated-app' }, logger, deps, false);
369
+ }
370
+ /**
371
+ * The launch both windows share. The viewer may fall back to the system's
372
+ * opener so a session start never fails; the dashboard may not, because its
373
+ * grant would then land in a browser profile with extensions.
374
+ */
375
+ async function launchWindow(url, home, config, logger, deps, allowFallback) {
376
+ const mode = config.launchMode ?? 'no-window';
377
+ if (mode === 'no-window')
378
+ return { launched: false, mode, reason: 'viewer.launchMode is "no-window"' };
379
+ if (mode === 'isolated-app') {
380
+ const isolated = await openIsolatedWindow(url, home, config, logger, allowFallback ? 'viewer' : 'dashboard', deps);
381
+ if (isolated.launched)
382
+ return isolated;
383
+ if (!allowFallback)
384
+ return isolated;
385
+ // Degrade rather than fail: the system's opener is tried, and when
386
+ // nothing opens the daemon hands the caller the URL.
387
+ return openInDefaultBrowser(url, logger, 'isolated-app', deps, isolated.reason);
388
+ }
389
+ if (!allowFallback) {
390
+ // Unreachable for the dashboard, which forces `isolated-app`; kept so a
391
+ // future caller cannot make this function hand a grant to the default
392
+ // browser by choosing another mode.
393
+ return {
394
+ launched: false,
395
+ mode: 'isolated-app',
396
+ reason: 'the dashboard opens only in its isolated window',
397
+ };
398
+ }
399
+ return openInDefaultBrowser(url, logger, 'default-browser', deps);
400
+ }
401
+ /** Open `url` in the isolated profile, or report why that was not possible. */
402
+ async function openIsolatedWindow(url, home, config, logger, kind, deps) {
403
+ const mode = 'isolated-app';
404
+ const browser = await (deps.findBrowser ?? findBrowser)(config.browserPath, logger);
405
+ if (deps.shouldLaunch?.() === false) {
406
+ return { launched: false, mode, reason: 'daemon is stopping' };
407
+ }
408
+ if (browser === null) {
409
+ logger.warn(`no Chromium-family browser found for the isolated ${kind} window`, {
410
+ hint: kind === 'viewer'
411
+ ? 'set viewer.browserPath, or viewer.launchMode to "default-browser"'
412
+ : 'set viewer.browserPath',
413
+ });
414
+ return { launched: false, mode, reason: 'no Chromium-family browser found' };
415
+ }
416
+ const profileDir = config.profileDir ?? path.join(home, 'viewer-profile');
417
+ try {
418
+ fs.mkdirSync(profileDir, { recursive: true });
419
+ }
420
+ catch (error) {
421
+ logger.warn(`could not create the ${kind} profile directory`, {
422
+ profileDir,
423
+ error: String(error),
424
+ });
425
+ return { launched: false, mode, reason: 'profile directory unavailable' };
426
+ }
427
+ // The browser is spawned directly, so "opened" means its process started.
428
+ // Its exit is not judged: a Chromium launched beside a running instance of
429
+ // the same profile hands the URL over and exits at once, with code 0, and
430
+ // the window is in the other process.
431
+ if (deps.shouldLaunch?.() === false) {
432
+ return { launched: false, mode, reason: 'daemon is stopping' };
433
+ }
434
+ const outcome = await (deps.spawnIsolated ?? spawnDetached)(browser, isolatedWindowArgs(url, profileDir));
435
+ if (outcome.spawned) {
436
+ logger.info(`${kind} window opened`, { browser, profileDir });
437
+ return { launched: true, mode, browser };
438
+ }
439
+ const error = outcome.error ?? 'the browser did not start';
440
+ logger.warn(`the ${kind} browser failed to launch`, { browser, error });
441
+ return { launched: false, mode, reason: error };
442
+ }
443
+ /**
444
+ * The command that opens `url` in the default browser.
445
+ *
446
+ * On Windows that is cmd's `start` builtin, so the URL passes through cmd's
447
+ * command-line parser, where an unquoted `&` ends a command. The viewer URL
448
+ * holds one (`?s=<id>&vt=<grant>`), and Node quotes an argument only when it
449
+ * holds a space, so the URL goes over verbatim inside double quotes. Within
450
+ * quotes cmd still expands `%NAME%`, and `!NAME!` where delayed expansion is
451
+ * switched on in the registry; a `"` ends the quoting and a line break ends
452
+ * the command. A URL holding any of those is refused rather than handed over.
453
+ * The empty `""` is `start`'s window title, without which it would take the
454
+ * quoted URL as the title. `/d` skips cmd's AutoRun commands.
455
+ */
456
+ export function defaultBrowserCommand(url, platform = process.platform, comspec = process.env['COMSPEC']) {
457
+ if (platform === 'win32') {
458
+ if (/["%!\r\n]/.test(url)) {
459
+ throw new Error('the URL holds a quote, a percent sign, an exclamation mark or a line break, which cmd would act on');
460
+ }
461
+ return {
462
+ command: comspec ?? 'cmd.exe',
463
+ args: ['/d', '/c', 'start', '""', `"${url}"`],
464
+ windowsVerbatimArguments: true,
465
+ };
466
+ }
467
+ const command = platform === 'darwin' ? '/usr/bin/open' : '/usr/bin/xdg-open';
468
+ return { command, args: [url], windowsVerbatimArguments: false };
469
+ }
470
+ /**
471
+ * How long to wait for the system's opener to say whether it managed. `start`,
472
+ * `open` and `xdg-open` return within a fraction of a second, with a non-zero
473
+ * code when they could hand the URL to nothing (no display, no registered
474
+ * browser). An opener still running after this is taken to have become the
475
+ * browser itself, which `xdg-open` does on some desktops.
476
+ */
477
+ export const OPENER_SETTLE_MS = 1500;
478
+ async function openInDefaultBrowser(url, logger, mode, deps, fallbackReason) {
479
+ const withFallback = (reason) => fallbackReason === undefined ? reason : `${reason}; fell back: ${fallbackReason}`;
480
+ let command;
481
+ try {
482
+ command = (deps.opener ?? defaultBrowserCommand)(url);
483
+ }
484
+ catch (error) {
485
+ logger.warn('could not open the viewer in any browser', { error: String(error) });
486
+ return { launched: false, mode, reason: withFallback(String(error)) };
487
+ }
488
+ const outcome = await spawnDetached(command.command, command.args, command.windowsVerbatimArguments, deps.openerSettleMs ?? OPENER_SETTLE_MS);
489
+ if (!outcome.spawned) {
490
+ const error = outcome.error ?? 'the opener did not start';
491
+ logger.warn('could not open the viewer in any browser', { error });
492
+ return { launched: false, mode, reason: withFallback(error) };
493
+ }
494
+ if (outcome.exitCode !== undefined && outcome.exitCode !== 0) {
495
+ const reason = `${path.basename(command.command)} exited with code ${String(outcome.exitCode ?? 'signal')}`;
496
+ logger.warn('the default browser did not open the viewer', { reason, fallbackReason });
497
+ return { launched: false, mode, reason: withFallback(reason) };
498
+ }
499
+ logger.info('viewer opened in the default browser', { fallbackReason });
500
+ return {
501
+ launched: true,
502
+ mode,
503
+ ...(fallbackReason !== undefined ? { reason: `fell back: ${fallbackReason}` } : {}),
504
+ };
505
+ }
506
+ /**
507
+ * Spawn fully detached with `detached`, `stdio: 'ignore'` and `unref()`, the
508
+ * same discipline the daemon's own auto-start requires (§2.2): a browser that
509
+ * inherited this daemon's stdio, or that the daemon waited on, would tie a
510
+ * long-lived GUI process to the daemon's lifetime and hang its shutdown.
511
+ *
512
+ * The promise settles when Node says whether the process started. `spawn`
513
+ * reports a failure to execute, such as ENOENT, EACCES or a path that is a
514
+ * directory, by emitting 'error' ASYNCHRONOUSLY, so a call that returned
515
+ * without throwing has proved nothing, and a ChildProcess 'error' with no
516
+ * listener is re-thrown by Node as an uncaught exception. With `settleMs`, it
517
+ * also waits that long for the process to exit and reports the code, for an
518
+ * opener whose exit code is its answer. Nothing here throws: the caller's
519
+ * contract is that launching a viewer can never fail a session start.
520
+ */
521
+ function spawnDetached(command, args, windowsVerbatimArguments = false, settleMs = 0) {
522
+ return new Promise((resolve) => {
523
+ let settled = false;
524
+ const settle = (outcome) => {
525
+ if (settled)
526
+ return;
527
+ settled = true;
528
+ clearTimeout(launchTimer);
529
+ resolve(outcome);
530
+ };
531
+ const launchTimer = setTimeout(() => settle({ spawned: false, error: 'browser spawn timed out' }), BROWSER_SPAWN_TIMEOUT_MS);
532
+ let child;
533
+ try {
534
+ child = spawn(command, args, {
535
+ detached: true,
536
+ stdio: 'ignore',
537
+ windowsHide: false,
538
+ windowsVerbatimArguments,
539
+ });
540
+ }
541
+ catch (error) {
542
+ settle({ spawned: false, error: String(error) });
543
+ return;
544
+ }
545
+ child.on('error', (error) => settle({ spawned: false, error: String(error) }));
546
+ child.on('spawn', () => {
547
+ if (settled)
548
+ return;
549
+ if (settleMs <= 0) {
550
+ settle({ spawned: true });
551
+ return;
552
+ }
553
+ const timer = setTimeout(() => settle({ spawned: true }), settleMs);
554
+ child.once('exit', (code) => {
555
+ clearTimeout(timer);
556
+ settle({ spawned: true, exitCode: code });
557
+ });
558
+ });
559
+ child.unref();
560
+ });
561
+ }
562
+ //# sourceMappingURL=viewerLauncher.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"viewerLauncher.js","sourceRoot":"","sources":["../../src/daemon/viewerLauncher.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AAEH,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAErD,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,KAAK,IAAI,MAAM,W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,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;YACjD,OAAO;QACT,CAAC;QACD,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,MAAM,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC;QAC/E,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE;YACrB,IAAI,OAAO;gBAAE,OAAO;YACpB,IAAI,QAAQ,IAAI,CAAC,EAAE,CAAC;gBAClB,MAAM,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC;gBAC1B,OAAO;YACT,CAAC;YACD,MAAM,KAAK,GAAG,UAAU,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,EAAE,QAAQ,CAAC,CAAC;YACpE,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,IAAI,EAAE,EAAE;gBAC1B,YAAY,CAAC,KAAK,CAAC,CAAC;gBACpB,MAAM,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC,CAAC;YAC5C,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;QACH,KAAK,CAAC,KAAK,EAAE,CAAC;IAChB,CAAC,CAAC,CAAC;AACL,CAAC"}
@@ -0,0 +1,38 @@
1
+ /**
2
+ * The gate that keeps one viewer socket's byte stream in order across
3
+ * snapshots (design §5).
4
+ *
5
+ * A snapshot of the daemon's renderer is taken asynchronously: it resolves
6
+ * once every byte queued before the request has been parsed, and includes
7
+ * nothing queued after it (`ScreenRenderer.serialize`). Bytes that arrive
8
+ * while it is pending are NOT in it and must reach the viewer
9
+ * AFTER it; bytes that arrived before the request ARE in it and were already
10
+ * forwarded live, so they must not go out again. This class is that
11
+ * bookkeeping, with the socket and the snapshot injected so it can be tested
12
+ * without either.
13
+ *
14
+ * No I/O of its own and no logging.
15
+ */
16
+ export declare class ViewerSync {
17
+ private readonly send;
18
+ private readonly snapshot;
19
+ /** Arrival counter: every delivered chunk takes the next value. */
20
+ private seq;
21
+ /** Chunks held back while a snapshot is pending, with their arrival order. */
22
+ private held;
23
+ /** The arrival counter at each pending snapshot request, oldest first. */
24
+ private readonly pending;
25
+ private closed;
26
+ constructor(send: (bytes: string) => void, snapshot: () => Promise<string>);
27
+ /** Live bytes from the session, in arrival order. */
28
+ deliver(bytes: string): void;
29
+ /**
30
+ * Send a fresh snapshot, then everything that arrived after it was taken.
31
+ * Requests may overlap (a window being dragged): each snapshot goes out
32
+ * once, and no chunk goes out twice or not at all.
33
+ */
34
+ resync(): void;
35
+ private complete;
36
+ /** Nothing goes out after this, including a snapshot that resolves late. */
37
+ close(): void;
38
+ }