Skip to content

Commit 85f0c9d

Browse files
fix(cli): select host-compatible cached browser (#2861)
* fix(cli): select host-compatible cached browser * test(engine): make browser cache fixture portable * fix(browser): reject foreign ARM cache binaries
1 parent fdc5932 commit 85f0c9d

4 files changed

Lines changed: 314 additions & 35 deletions

File tree

‎packages/cli/src/browser/manager.test.ts‎

Lines changed: 129 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -130,18 +130,25 @@ function installPuppeteerBrowsersMock(
130130
executablePath: string;
131131
path?: string;
132132
buildId?: string;
133+
platform?: string;
133134
}>;
135+
browserPlatform?: string;
134136
installedInHfCacheError?: Error;
135137
installResult?: { executablePath: string };
136138
installImpl?: () => Promise<{ executablePath: string }>;
137139
} = {},
138140
) {
139141
vi.doMock("@puppeteer/browsers", () => ({
140142
Browser: { CHROMEHEADLESSSHELL: "chrome-headless-shell" },
141-
detectBrowserPlatform: () => "linux",
143+
detectBrowserPlatform: () => opts.browserPlatform ?? "linux",
142144
getInstalledBrowsers: opts.installedInHfCacheError
143145
? vi.fn().mockRejectedValue(opts.installedInHfCacheError)
144-
: vi.fn().mockResolvedValue(opts.installedInHfCache ?? []),
146+
: vi.fn().mockResolvedValue(
147+
(opts.installedInHfCache ?? []).map((browser) => ({
148+
platform: opts.browserPlatform ?? "linux",
149+
...browser,
150+
})),
151+
),
145152
install: vi
146153
.fn()
147154
.mockImplementation(
@@ -222,6 +229,41 @@ describe("findBrowser — cache resolution", () => {
222229
expect(result).toEqual({ executablePath: SYSTEM_CHROME, source: "system" });
223230
});
224231

232+
it("ignores a current-version HyperFrames cache entry for another platform", async () => {
233+
Object.defineProperty(process, "platform", { value: "darwin", configurable: true });
234+
Object.defineProperty(process, "arch", { value: "arm64", configurable: true });
235+
const macArm64Binary = join(
236+
HF_CACHE,
237+
"chrome-headless-shell",
238+
"mac_arm-131.0.6778.85",
239+
"chrome-headless-shell-mac-arm64",
240+
"chrome-headless-shell",
241+
);
242+
installFsMocks({ existing: new Set([HF_CACHE, HF_BINARY, macArm64Binary]) });
243+
installPuppeteerBrowsersMock({
244+
browserPlatform: "mac_arm",
245+
installedInHfCache: [
246+
{
247+
browser: "chrome-headless-shell",
248+
executablePath: HF_BINARY,
249+
buildId: CHROME_VERSION,
250+
platform: "linux",
251+
},
252+
{
253+
browser: "chrome-headless-shell",
254+
executablePath: macArm64Binary,
255+
buildId: CHROME_VERSION,
256+
platform: "mac_arm",
257+
},
258+
],
259+
});
260+
261+
const { findBrowser } = await import("./manager.js");
262+
const result = await findBrowser();
263+
264+
expect(result).toEqual({ executablePath: macArm64Binary, source: "cache" });
265+
});
266+
225267
it("re-downloads when the hyperframes cache manifest points at a missing binary", async () => {
226268
const redownloadedBinary = join(
227269
HF_CACHE,
@@ -492,6 +534,91 @@ describe("findBrowser — cache resolution", () => {
492534
expect(result).toEqual({ executablePath: PUPPETEER_BINARY, source: "cache" });
493535
});
494536

537+
it.each([
538+
{
539+
hostPlatform: "darwin",
540+
hostArch: "arm64",
541+
expectedDirectory: "chrome-headless-shell-mac-arm64",
542+
expectedExecutable: "chrome-headless-shell",
543+
},
544+
{
545+
hostPlatform: "darwin",
546+
hostArch: "x64",
547+
expectedDirectory: "chrome-headless-shell-mac-x64",
548+
expectedExecutable: "chrome-headless-shell",
549+
},
550+
{
551+
hostPlatform: "linux",
552+
hostArch: "x64",
553+
expectedDirectory: "chrome-headless-shell-linux64",
554+
expectedExecutable: "chrome-headless-shell",
555+
},
556+
{
557+
hostPlatform: "win32",
558+
hostArch: "ia32",
559+
expectedDirectory: "chrome-headless-shell-win32",
560+
expectedExecutable: "chrome-headless-shell.exe",
561+
},
562+
{
563+
hostPlatform: "win32",
564+
hostArch: "x64",
565+
expectedDirectory: "chrome-headless-shell-win64",
566+
expectedExecutable: "chrome-headless-shell.exe",
567+
},
568+
])(
569+
"selects only the host-compatible cached shell on $hostPlatform/$hostArch when every platform is present",
570+
async ({ hostPlatform, hostArch, expectedDirectory, expectedExecutable }) => {
571+
Object.defineProperty(process, "platform", { value: hostPlatform, configurable: true });
572+
Object.defineProperty(process, "arch", { value: hostArch, configurable: true });
573+
const version = "host-148.0.7778.97";
574+
const candidates = [
575+
["chrome-headless-shell-linux64", "chrome-headless-shell"],
576+
["chrome-headless-shell-mac-arm64", "chrome-headless-shell"],
577+
["chrome-headless-shell-mac-x64", "chrome-headless-shell"],
578+
["chrome-headless-shell-win32", "chrome-headless-shell.exe"],
579+
["chrome-headless-shell-win64", "chrome-headless-shell.exe"],
580+
] as const;
581+
const binaries = candidates.map(([directory, executable]) =>
582+
join(PUPPETEER_CACHE, version, directory, executable),
583+
);
584+
const expectedBinary = join(PUPPETEER_CACHE, version, expectedDirectory, expectedExecutable);
585+
installFsMocks({
586+
existing: new Set([PUPPETEER_CACHE, ...binaries]),
587+
dirs: { [PUPPETEER_CACHE]: [version] },
588+
});
589+
installPuppeteerBrowsersMock();
590+
591+
const { findBrowser } = await import("./manager.js");
592+
const result = await findBrowser();
593+
594+
expect(result).toEqual({ executablePath: expectedBinary, source: "cache" });
595+
},
596+
);
597+
598+
it.each([
599+
{ hostPlatform: "linux", hostArch: "arm64" },
600+
{ hostPlatform: "win32", hostArch: "arm64" },
601+
])(
602+
"does not select a foreign cached shell on unsupported $hostPlatform/$hostArch",
603+
async ({ hostPlatform, hostArch }) => {
604+
Object.defineProperty(process, "platform", { value: hostPlatform, configurable: true });
605+
Object.defineProperty(process, "arch", { value: hostArch, configurable: true });
606+
const version = "host-148.0.7778.97";
607+
const binaries = [
608+
join(PUPPETEER_CACHE, version, "chrome-headless-shell-linux64", "chrome-headless-shell"),
609+
join(PUPPETEER_CACHE, version, "chrome-headless-shell-win64", "chrome-headless-shell.exe"),
610+
];
611+
installFsMocks({
612+
existing: new Set([PUPPETEER_CACHE, ...binaries]),
613+
dirs: { [PUPPETEER_CACHE]: [version] },
614+
});
615+
installPuppeteerBrowsersMock();
616+
617+
const { findBrowser } = await import("./manager.js");
618+
await expect(findBrowser()).resolves.toBeUndefined();
619+
},
620+
);
621+
495622
it("prefers the puppeteer cache over the hyperframes cache when BOTH are populated", async () => {
496623
// The HF cache is pinned to `CHROME_VERSION` (131-era) which lags upstream
497624
// by many releases. The engine's `resolveHeadlessShellPath` scans the

‎packages/cli/src/browser/manager.ts‎

Lines changed: 36 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -282,7 +282,7 @@ function findFromEnv(): BrowserResult | undefined {
282282
*/
283283
async function findFromHyperframesCache(): Promise<CacheLookupResult> {
284284
if (!existsSync(CACHE_DIR)) return {};
285-
const { Browser, getInstalledBrowsers } = await loadPuppeteerBrowsers();
285+
const { Browser, detectBrowserPlatform, getInstalledBrowsers } = await loadPuppeteerBrowsers();
286286
// A corrupt cache (stub file where a browser dir is expected, malformed
287287
// metadata) makes getInstalledBrowsers throw. Treat that as "no cached
288288
// browser" so resolution falls through to system/download instead of
@@ -302,9 +302,14 @@ async function findFromHyperframesCache(): Promise<CacheLookupResult> {
302302
// an older hyperframes version (this pin has moved 131 → 151 → 152 across
303303
// releases) must NOT satisfy resolution, or an upgrade silently keeps
304304
// running whatever build happened to be cached instead of ever fetching
305-
// the version this release actually needs (HF#2060 review).
305+
// the version this release actually needs (HF#2060 review). Match platform
306+
// as well so a shared/migrated cache cannot return a foreign executable.
307+
const hostPlatform = detectBrowserPlatform();
306308
const match = installed.find(
307-
(b) => b.browser === Browser.CHROMEHEADLESSSHELL && b.buildId === CHROME_VERSION,
309+
(b) =>
310+
b.browser === Browser.CHROMEHEADLESSSHELL &&
311+
b.buildId === CHROME_VERSION &&
312+
b.platform === hostPlatform,
308313
);
309314
if (match && existsSync(match.executablePath)) {
310315
return { result: { executablePath: match.executablePath, source: "cache" } };
@@ -383,8 +388,33 @@ function compareVersionDirsDescending(a: string, b: string): number {
383388
return 0;
384389
}
385390

391+
const CACHED_HEADLESS_SHELL_EXECUTABLES: Readonly<
392+
Record<string, readonly [directory: string, executable: string]>
393+
> = {
394+
"darwin/arm64": ["chrome-headless-shell-mac-arm64", "chrome-headless-shell"],
395+
"darwin/x64": ["chrome-headless-shell-mac-x64", "chrome-headless-shell"],
396+
"linux/x64": ["chrome-headless-shell-linux64", "chrome-headless-shell"],
397+
"win32/ia32": ["chrome-headless-shell-win32", "chrome-headless-shell.exe"],
398+
"win32/x64": ["chrome-headless-shell-win64", "chrome-headless-shell.exe"],
399+
};
400+
401+
function cachedHeadlessShellExecutable(
402+
hostPlatform = process.platform,
403+
hostArch = process.arch,
404+
): readonly [directory: string, executable: string] | undefined {
405+
// Chrome for Testing cache entries are host-specific. Resolve exactly one
406+
// platform/architecture directory so a foreign binary cannot win by probe order.
407+
// Chrome for Testing does not publish Linux ARM64 binaries. Windows ARM64 can
408+
// emulate x64 only on supported Windows 11 builds, which this platform/arch-only
409+
// resolver cannot prove, so both hosts deliberately fall through to system
410+
// browser discovery instead of attempting a potentially foreign cached binary.
411+
return CACHED_HEADLESS_SHELL_EXECUTABLES[`${hostPlatform}/${hostArch}`];
412+
}
413+
386414
function findFromPuppeteerCache(): BrowserResult | undefined {
387415
if (!existsSync(PUPPETEER_CACHE_DIR)) return undefined;
416+
const executable = cachedHeadlessShellExecutable();
417+
if (!executable) return undefined;
388418
let versions: string[];
389419
try {
390420
// Numeric semver-style sort, newest first. Lexicographic `.sort().reverse()`
@@ -399,26 +429,9 @@ function findFromPuppeteerCache(): BrowserResult | undefined {
399429
// Same shape as `resolveHeadlessShellPath` in engine/browserManager.ts —
400430
// keep them aligned. If puppeteer ever changes the on-disk layout the two
401431
// need to move together.
402-
const candidates = [
403-
join(PUPPETEER_CACHE_DIR, version, "chrome-headless-shell-linux64", "chrome-headless-shell"),
404-
join(
405-
PUPPETEER_CACHE_DIR,
406-
version,
407-
"chrome-headless-shell-mac-arm64",
408-
"chrome-headless-shell",
409-
),
410-
join(PUPPETEER_CACHE_DIR, version, "chrome-headless-shell-mac-x64", "chrome-headless-shell"),
411-
join(
412-
PUPPETEER_CACHE_DIR,
413-
version,
414-
"chrome-headless-shell-win64",
415-
"chrome-headless-shell.exe",
416-
),
417-
];
418-
for (const binary of candidates) {
419-
if (existsSync(binary)) {
420-
return { executablePath: binary, source: "cache" };
421-
}
432+
const binary = join(PUPPETEER_CACHE_DIR, version, ...executable);
433+
if (existsSync(binary)) {
434+
return { executablePath: binary, source: "cache" };
422435
}
423436
}
424437
return undefined;

‎packages/engine/src/services/browserManager.test.ts‎

Lines changed: 122 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -401,6 +401,127 @@ describe("resolveHeadlessShellPath", () => {
401401
}
402402
});
403403

404+
it.each([
405+
{
406+
hostPlatform: "darwin",
407+
hostArch: "arm64",
408+
expectedDirectory: "chrome-headless-shell-mac-arm64",
409+
expectedExecutable: "chrome-headless-shell",
410+
},
411+
{
412+
hostPlatform: "darwin",
413+
hostArch: "x64",
414+
expectedDirectory: "chrome-headless-shell-mac-x64",
415+
expectedExecutable: "chrome-headless-shell",
416+
},
417+
{
418+
hostPlatform: "linux",
419+
hostArch: "x64",
420+
expectedDirectory: "chrome-headless-shell-linux64",
421+
expectedExecutable: "chrome-headless-shell",
422+
},
423+
{
424+
hostPlatform: "win32",
425+
hostArch: "ia32",
426+
expectedDirectory: "chrome-headless-shell-win32",
427+
expectedExecutable: "chrome-headless-shell.exe",
428+
},
429+
{
430+
hostPlatform: "win32",
431+
hostArch: "x64",
432+
expectedDirectory: "chrome-headless-shell-win64",
433+
expectedExecutable: "chrome-headless-shell.exe",
434+
},
435+
])(
436+
"selects only the host-compatible cached shell on $hostPlatform/$hostArch when every platform is present",
437+
({ hostPlatform, hostArch, expectedDirectory, expectedExecutable }) => {
438+
const home = mkdtempSync(join(tmpdir(), "hyperframes-engine-browser-platform-"));
439+
try {
440+
const cacheVersion = join(
441+
home,
442+
".cache",
443+
"puppeteer",
444+
"chrome-headless-shell",
445+
"host-152.0.7928.2",
446+
);
447+
const candidates = [
448+
["chrome-headless-shell-linux64", "chrome-headless-shell"],
449+
["chrome-headless-shell-mac-arm64", "chrome-headless-shell"],
450+
["chrome-headless-shell-mac-x64", "chrome-headless-shell"],
451+
["chrome-headless-shell-win32", "chrome-headless-shell.exe"],
452+
["chrome-headless-shell-win64", "chrome-headless-shell.exe"],
453+
] as const;
454+
for (const [directory, executable] of candidates) {
455+
const binary = join(cacheVersion, directory, executable);
456+
mkdirSync(join(binary, ".."), { recursive: true });
457+
writeFileSync(binary, "");
458+
}
459+
const expectedBinary = join(cacheVersion, expectedDirectory, expectedExecutable);
460+
461+
const env = { ...process.env, HOME: home, USERPROFILE: home };
462+
delete env.PRODUCER_HEADLESS_SHELL_PATH;
463+
delete env.HYPERFRAMES_BROWSER_PATH;
464+
const moduleUrl = new URL("./browserManager.ts", import.meta.url).href;
465+
const stdout = execFileSync(
466+
"bun",
467+
[
468+
"--eval",
469+
`Object.defineProperty(process, "platform", { value: ${JSON.stringify(hostPlatform)} }); Object.defineProperty(process, "arch", { value: ${JSON.stringify(hostArch)} }); import(${JSON.stringify(moduleUrl)}).then(({ resolveHeadlessShellPath }) => process.stdout.write(resolveHeadlessShellPath({}) ?? ""))`,
470+
],
471+
{ encoding: "utf8", env },
472+
);
473+
474+
expect(stdout).toBe(expectedBinary);
475+
} finally {
476+
rmSync(home, { recursive: true, force: true });
477+
}
478+
},
479+
);
480+
481+
it.each([
482+
{ hostPlatform: "linux", hostArch: "arm64" },
483+
{ hostPlatform: "win32", hostArch: "arm64" },
484+
])(
485+
"does not select a foreign cached shell on unsupported $hostPlatform/$hostArch",
486+
({ hostPlatform, hostArch }) => {
487+
const home = mkdtempSync(join(tmpdir(), "hyperframes-engine-browser-unsupported-"));
488+
try {
489+
const cacheVersion = join(
490+
home,
491+
".cache",
492+
"puppeteer",
493+
"chrome-headless-shell",
494+
"host-152.0.7928.2",
495+
);
496+
for (const [directory, executable] of [
497+
["chrome-headless-shell-linux64", "chrome-headless-shell"],
498+
["chrome-headless-shell-win64", "chrome-headless-shell.exe"],
499+
] as const) {
500+
const binary = join(cacheVersion, directory, executable);
501+
mkdirSync(join(binary, ".."), { recursive: true });
502+
writeFileSync(binary, "");
503+
}
504+
505+
const env = { ...process.env, HOME: home, USERPROFILE: home };
506+
delete env.PRODUCER_HEADLESS_SHELL_PATH;
507+
delete env.HYPERFRAMES_BROWSER_PATH;
508+
const moduleUrl = new URL("./browserManager.ts", import.meta.url).href;
509+
const stdout = execFileSync(
510+
"bun",
511+
[
512+
"--eval",
513+
`Object.defineProperty(process, "platform", { value: ${JSON.stringify(hostPlatform)} }); Object.defineProperty(process, "arch", { value: ${JSON.stringify(hostArch)} }); import(${JSON.stringify(moduleUrl)}).then(({ resolveHeadlessShellPath }) => process.stdout.write(resolveHeadlessShellPath({}) ?? ""))`,
514+
],
515+
{ encoding: "utf8", env },
516+
);
517+
518+
expect(stdout).toBe("");
519+
} finally {
520+
rmSync(home, { recursive: true, force: true });
521+
}
522+
},
523+
);
524+
404525
it("reuses chrome-headless-shell from the HyperFrames-managed cache", () => {
405526
const home = mkdtempSync(join(tmpdir(), "hyperframes-engine-browser-cache-"));
406527
try {
@@ -429,7 +550,7 @@ describe("resolveHeadlessShellPath", () => {
429550
"bun",
430551
[
431552
"--eval",
432-
`import(${JSON.stringify(moduleUrl)}).then(({ resolveHeadlessShellPath }) => process.stdout.write(resolveHeadlessShellPath({}) ?? ""))`,
553+
`Object.defineProperty(process, "platform", { value: "linux" }); Object.defineProperty(process, "arch", { value: "x64" }); import(${JSON.stringify(moduleUrl)}).then(({ resolveHeadlessShellPath }) => process.stdout.write(resolveHeadlessShellPath({}) ?? ""))`,
433554
],
434555
{ encoding: "utf8", env },
435556
);

0 commit comments

Comments
 (0)