-
Notifications
You must be signed in to change notification settings - Fork 18.4k
Expand file tree
/
Copy pathbrowser-manager-unit.test.ts
More file actions
329 lines (292 loc) · 15.6 KB
/
Copy pathbrowser-manager-unit.test.ts
File metadata and controls
329 lines (292 loc) · 15.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
import { EventEmitter } from 'node:events';
import { afterEach, beforeEach, describe, it, expect } from 'bun:test';
// ─── BrowserManager basic unit tests ─────────────────────────────
describe('BrowserManager defaults', () => {
it('getConnectionMode defaults to launched', async () => {
const { BrowserManager } = await import('../src/browser-manager');
const bm = new BrowserManager();
expect(bm.getConnectionMode()).toBe('launched');
});
it('getRefMap returns empty array initially', async () => {
const { BrowserManager } = await import('../src/browser-manager');
const bm = new BrowserManager();
expect(bm.getRefMap()).toEqual([]);
});
});
// ─── shouldEnableChromiumSandbox ─────────────────────────────────
//
// Pinning this is what prevents the "--no-sandbox" yellow infobar from
// regressing on headed launches. Playwright auto-adds --no-sandbox when
// chromiumSandbox !== true (playwright-core chromium.js:291-292), so all
// three launch sites in browser-manager.ts must pass the policy this
// helper computes.
describe('shouldEnableChromiumSandbox', () => {
const origPlatform = process.platform;
const origCI = process.env.CI;
const origContainer = process.env.CONTAINER;
const origNoSandbox = process.env.GSTACK_CHROMIUM_NO_SANDBOX;
const origGetuid = process.getuid;
beforeEach(() => {
delete process.env.CI;
delete process.env.CONTAINER;
delete process.env.GSTACK_CHROMIUM_NO_SANDBOX;
});
afterEach(() => {
Object.defineProperty(process, 'platform', { value: origPlatform });
if (origCI === undefined) delete process.env.CI; else process.env.CI = origCI;
if (origContainer === undefined) delete process.env.CONTAINER; else process.env.CONTAINER = origContainer;
if (origNoSandbox === undefined) delete process.env.GSTACK_CHROMIUM_NO_SANDBOX; else process.env.GSTACK_CHROMIUM_NO_SANDBOX = origNoSandbox;
process.getuid = origGetuid;
});
function setPlatform(p: NodeJS.Platform) {
Object.defineProperty(process, 'platform', { value: p });
}
it('darwin, no CI/CONTAINER/root → true', async () => {
setPlatform('darwin');
process.getuid = (() => 501) as typeof process.getuid;
const { shouldEnableChromiumSandbox } = await import('../src/browser-manager');
expect(shouldEnableChromiumSandbox()).toBe(true);
});
it('linux, no CI/CONTAINER/root → true', async () => {
setPlatform('linux');
process.getuid = (() => 1000) as typeof process.getuid;
const { shouldEnableChromiumSandbox } = await import('../src/browser-manager');
expect(shouldEnableChromiumSandbox()).toBe(true);
});
it('win32 → false (sandbox fails in Bun→Node→Chromium chain)', async () => {
setPlatform('win32');
process.getuid = (() => 1000) as typeof process.getuid;
const { shouldEnableChromiumSandbox } = await import('../src/browser-manager');
expect(shouldEnableChromiumSandbox()).toBe(false);
});
it('linux + CI=1 → false', async () => {
setPlatform('linux');
process.env.CI = '1';
process.getuid = (() => 1000) as typeof process.getuid;
const { shouldEnableChromiumSandbox } = await import('../src/browser-manager');
expect(shouldEnableChromiumSandbox()).toBe(false);
});
it('linux + CONTAINER=1 → false', async () => {
setPlatform('linux');
process.env.CONTAINER = '1';
process.getuid = (() => 1000) as typeof process.getuid;
const { shouldEnableChromiumSandbox } = await import('../src/browser-manager');
expect(shouldEnableChromiumSandbox()).toBe(false);
});
it('linux + root (uid 0) → false', async () => {
setPlatform('linux');
process.getuid = (() => 0) as typeof process.getuid;
const { shouldEnableChromiumSandbox } = await import('../src/browser-manager');
expect(shouldEnableChromiumSandbox()).toBe(false);
});
// #1562 — Ubuntu/AppArmor opt-in override
it('linux + GSTACK_CHROMIUM_NO_SANDBOX=1 → false (Ubuntu/AppArmor opt-out)', async () => {
setPlatform('linux');
process.env.GSTACK_CHROMIUM_NO_SANDBOX = '1';
process.getuid = (() => 1000) as typeof process.getuid;
const { shouldEnableChromiumSandbox } = await import('../src/browser-manager');
expect(shouldEnableChromiumSandbox()).toBe(false);
});
it('darwin + GSTACK_CHROMIUM_NO_SANDBOX=1 → false (env override wins on any platform)', async () => {
setPlatform('darwin');
process.env.GSTACK_CHROMIUM_NO_SANDBOX = '1';
process.getuid = (() => 501) as typeof process.getuid;
const { shouldEnableChromiumSandbox } = await import('../src/browser-manager');
expect(shouldEnableChromiumSandbox()).toBe(false);
});
it('GSTACK_CHROMIUM_NO_SANDBOX=0 → does NOT trigger override (must be exactly "1")', async () => {
setPlatform('linux');
process.env.GSTACK_CHROMIUM_NO_SANDBOX = '0';
process.getuid = (() => 1000) as typeof process.getuid;
const { shouldEnableChromiumSandbox } = await import('../src/browser-manager');
expect(shouldEnableChromiumSandbox()).toBe(true);
});
});
// ─── resolveDisconnectCause ──────────────────────────────────────
//
// Pinning the clean-vs-crash distinction matters because gbd's
// HealthMonitor consumes our exit code (0 = don't restart, !=0 =
// restart). A regression here brings back the "Cmd+Q makes the browser
// keep coming back" UX bug.
function makeFakeBrowser(opts: {
exitCode: number | null;
signalCode: NodeJS.Signals | null;
/** ms before emitting 'exit'; default = already exited at construction */
exitDelay?: number;
}): { process(): { exitCode: number | null; signalCode: NodeJS.Signals | null; once: EventEmitter['once'] } } {
const ee = new EventEmitter();
const state = {
exitCode: opts.exitDelay != null ? null : opts.exitCode,
signalCode: opts.exitDelay != null ? null : opts.signalCode,
once: ee.once.bind(ee),
};
if (opts.exitDelay != null) {
setTimeout(() => {
state.exitCode = opts.exitCode;
state.signalCode = opts.signalCode;
ee.emit('exit', opts.exitCode, opts.signalCode);
}, opts.exitDelay);
}
return { process: () => state };
}
describe('resolveDisconnectCause', () => {
it('clean: process already exited with code 0', async () => {
const { resolveDisconnectCause } = await import('../src/browser-manager');
const fake = makeFakeBrowser({ exitCode: 0, signalCode: null });
expect(await resolveDisconnectCause(fake as never)).toBe('clean');
});
it('crash: non-zero exit code', async () => {
const { resolveDisconnectCause } = await import('../src/browser-manager');
const fake = makeFakeBrowser({ exitCode: 1, signalCode: null });
expect(await resolveDisconnectCause(fake as never)).toBe('crash');
});
it('crash: SIGSEGV', async () => {
const { resolveDisconnectCause } = await import('../src/browser-manager');
const fake = makeFakeBrowser({ exitCode: null, signalCode: 'SIGSEGV' });
expect(await resolveDisconnectCause(fake as never)).toBe('crash');
});
it('crash: SIGKILL', async () => {
const { resolveDisconnectCause } = await import('../src/browser-manager');
const fake = makeFakeBrowser({ exitCode: null, signalCode: 'SIGKILL' });
expect(await resolveDisconnectCause(fake as never)).toBe('crash');
});
it('clean: process exits asynchronously with code 0 within timeout', async () => {
const { resolveDisconnectCause } = await import('../src/browser-manager');
const fake = makeFakeBrowser({ exitCode: 0, signalCode: null, exitDelay: 50 });
expect(await resolveDisconnectCause(fake as never)).toBe('clean');
});
it('crash: process exits asynchronously with non-zero code', async () => {
const { resolveDisconnectCause } = await import('../src/browser-manager');
const fake = makeFakeBrowser({ exitCode: 137, signalCode: null, exitDelay: 50 });
expect(await resolveDisconnectCause(fake as never)).toBe('crash');
});
it('crash: null browser returns crash (defensive default)', async () => {
const { resolveDisconnectCause } = await import('../src/browser-manager');
expect(await resolveDisconnectCause(null)).toBe('crash');
});
});
// ─── onDisconnect exit-code propagation (regression test) ──────────
//
// The contract: BrowserManager.onDisconnect is called with the resolved
// exit code (0 for clean Cmd+Q, 2 for crash). server.ts then forwards
// that code to activeShutdown(), which exits the process.
//
// Without this propagation, the headed-mode user-visible Cmd+Q respawn
// bug returns: server.ts hardcoded `activeShutdown?.(2)` ignores the
// resolved 0 and gbrowser's gbd HealthMonitor treats the clean quit as
// a crash, restarting the window.
describe('BrowserManager.onDisconnect exit-code propagation', () => {
it('signature accepts an optional exitCode argument', async () => {
const { BrowserManager } = await import('../src/browser-manager');
const bm = new BrowserManager();
const calls: Array<number | undefined> = [];
bm.onDisconnect = (code?: number) => { calls.push(code); };
bm.onDisconnect(0);
bm.onDisconnect(2);
bm.onDisconnect(undefined);
expect(calls).toEqual([0, 2, undefined]);
});
it('server.ts callback forwards exitCode when provided, falls back to 2', async () => {
// Mirror the production wiring in browse/src/server.ts so a refactor
// that drops the forward (e.g. reverting to `() => activeShutdown?.(2)`)
// fails CI before the user-visible bug returns.
const shutdownCalls: number[] = [];
const activeShutdown = (code: number) => { shutdownCalls.push(code); };
const onDisconnect = (code?: number) => activeShutdown(code ?? 2);
onDisconnect(0);
onDisconnect(2);
onDisconnect(undefined);
expect(shutdownCalls).toEqual([0, 2, 2]);
});
});
// ─── Stealth injected on EVERY launch path (regression tripwire) ───
//
// applyStealth must run on launch() (headless), launchHeaded(), AND
// handoff(). The blend of Layer C with extended mode left handoff() building
// cmdline args but never calling applyStealth, so a handed-off browser had
// no JS stealth (no webdriver mask, no chrome.* shape, no toString proxy).
// This static check fails CI if any launch path drops the call again.
describe('stealth injected on every context-creation path', () => {
it('every context-creation path calls applyStealth (>= 4 call sites)', async () => {
const { readFileSync } = await import('node:fs');
const { join } = await import('node:path');
const src = readFileSync(join(import.meta.dir, '..', 'src', 'browser-manager.ts'), 'utf-8');
// Every path that builds a BrowserContext must apply stealth: launch()
// (headless), launchHeaded(), handoff(), and recreateContext() (the
// useragent / viewport --scale rebuild, main + fallback). A path that
// creates a context without applyStealth silently un-stealths its pages.
const callSites = src.match(/applyStealth\(/g) || [];
expect(callSites.length).toBeGreaterThanOrEqual(4);
// handoff() body specifically must call applyStealth, before the resume() JSDoc.
const handoffStart = src.indexOf('async handoff(');
expect(handoffStart).toBeGreaterThan(0);
const resumeAnchor = src.indexOf('Resume AI control after user handoff', handoffStart);
const handoffBody = src.slice(handoffStart, resumeAnchor > 0 ? resumeAnchor : handoffStart + 4000);
expect(handoffBody).toContain('applyStealth(');
// recreateContext() body must call applyStealth too — useragent and
// viewport --scale route through it and would otherwise drop all stealth.
const recreateStart = src.indexOf('recreateContext');
expect(recreateStart).toBeGreaterThan(0);
// Find the method definition (not just the JSDoc/caller references).
const recreateDef = src.indexOf('async recreateContext(');
expect(recreateDef).toBeGreaterThan(0);
const setUaAnchor = src.indexOf('async setDeviceScaleFactor(', recreateDef);
const recreateBody = src.slice(recreateDef, setUaAnchor > 0 ? setUaAnchor : recreateDef + 6000);
expect(recreateBody).toContain('applyStealth(');
});
it('buildGStackLaunchArgs() is spread into all 3 launch sites', async () => {
// Same silent-drop regression class as applyStealth: a launch path that
// omits buildGStackLaunchArgs() loses the per-install GPU/UA/hardware
// cmdline spoof. launch(), launchHeaded(), and handoff() must all call it.
const { readFileSync } = await import('node:fs');
const { join } = await import('node:path');
const src = readFileSync(join(import.meta.dir, '..', 'src', 'browser-manager.ts'), 'utf-8');
const callSites = src.match(/buildGStackLaunchArgs\(\)/g) || [];
expect(callSites.length).toBeGreaterThanOrEqual(3);
});
it('STEALTH_LAUNCH_ARGS is spread into all 3 launch sites (no hardcoded literal)', async () => {
// The --disable-blink-features=AutomationControlled flag must come from the
// shared constant on launch(), launchHeaded(), AND handoff(). handoff()
// previously omitted it, leaving the AutomationControlled tell on the
// handed-off browser. No path may inline the literal instead.
const { readFileSync } = await import('node:fs');
const { join } = await import('node:path');
const src = readFileSync(join(import.meta.dir, '..', 'src', 'browser-manager.ts'), 'utf-8');
const spreads = src.match(/\.\.\.STEALTH_LAUNCH_ARGS/g) || [];
expect(spreads.length).toBeGreaterThanOrEqual(3);
// The literal must not be reintroduced in a launchArgs array (it belongs in
// the STEALTH_LAUNCH_ARGS constant in stealth.ts, not inline here).
expect(src).not.toContain("'--disable-blink-features=AutomationControlled'");
});
it('STEALTH_IGNORE_DEFAULT_ARGS is wired into both persistent-context paths', async () => {
// launchHeaded() and handoff() both launchPersistentContext and must strip
// Playwright's automation-tell defaults via the shared constant.
const { readFileSync } = await import('node:fs');
const { join } = await import('node:path');
const src = readFileSync(join(import.meta.dir, '..', 'src', 'browser-manager.ts'), 'utf-8');
const sites = src.match(/ignoreDefaultArgs:\s*STEALTH_IGNORE_DEFAULT_ARGS/g) || [];
expect(sites.length).toBeGreaterThanOrEqual(2);
});
});
// ─── Extension launch path uses new headless, not an off-screen window (#432) ───
//
// BROWSE_EXTENSIONS_DIR previously launched headed with --window-position=-9999
// + browser.newContext(). On macOS the off-screen window is still shown, and the
// isolated newContext() means the loaded extension never runs. The fix loads the
// extension through launchPersistentContext() with Chrome's new headless mode
// (--headless=new): the extension's service worker loads with no visible window.
describe('extension launch path (issue #432)', () => {
it('loads extensions via new headless, not an off-screen headed window', async () => {
const { readFileSync } = await import('node:fs');
const { join } = await import('node:path');
const src = readFileSync(join(import.meta.dir, '..', 'src', 'browser-manager.ts'), 'utf-8');
// The off-screen-window hack is gone (macOS ignores it; the window shows).
expect(src).not.toContain('--window-position=-9999,-9999');
// New headless keeps the window hidden while still loading extensions.
expect(src).toContain('--headless=new');
// Extensions require a persistent context — launch() + newContext() leaves
// them inert. All three extension-capable paths must use it now.
const persistent = src.match(/launchPersistentContext\(/g) || [];
expect(persistent.length).toBeGreaterThanOrEqual(3);
});
});