Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

19.5 KB
Raw Blame
// OPENSCREEN_SYMBOL_FLOOR=host relaxes the one guard that keeps a Linux package
// startable on the distros the README claims. That is the right trade for a developer
// building for their own machine and a shipping bug anywhere else, so the two refusals
// that keep it local — an unknown value, and CI — are tested rather than trusted.
//
// Neither needs a payload to scan: resolveSymbolCeiling() decides from the environment
// alone, which is why it is the seam this file pokes at. The comparison it feeds is
// exercised for real by every `npm run build:linux`.
//
// The mode is read once at module load, so each case re-requires before-pack.cjs with a
// different environment instead of mutating state on an already-loaded copy.

import { createRequire } from "node:module";
import path from "node:path";
import { fileURLToPath } from "node:url";

import { describe, expect, it } from "vitest";

const require = createRequire(import.meta.url);
const BEFORE_PACK = path.join(path.dirname(fileURLToPath(import.meta.url)), "before-pack.cjs");

/**
 * Run `body` against a fresh copy of before-pack.cjs loaded under `env`.
 *
 * The environment has to stay set for the call and not just the require: the mode is
 * captured at module load, but the CI check reads process.env when it runs, and a
 * helper that restored before handing back made that refusal look absent.
 */
function withEnv(env, body) {
	const saved = new Map(Object.keys(env).map((key) => [key, process.env[key]]));
	for (const [key, value] of Object.entries(env)) {
		if (value === undefined) delete process.env[key];
		else process.env[key] = value;
	}
	try {
		delete require.cache[require.resolve(BEFORE_PACK)];
		return body(require(BEFORE_PACK).__testing);
	} finally {
		for (const [key, value] of saved) {
			if (value === undefined) delete process.env[key];
			else process.env[key] = value;
		}
	}
}

describe("symbol-version ceiling", () => {
	it("uses the pinned floor when OPENSCREEN_SYMBOL_FLOOR is unset", () => {
		withEnv({ OPENSCREEN_SYMBOL_FLOOR: undefined, CI: undefined }, (t) => {
			const { ceiling, pinned } = t.resolveSymbolCeiling();

			expect(pinned).toBe(true);
			expect(ceiling).toBe(t.MAX_SYMBOL_VERSION);
		});
	});

	it("refuses an unknown value rather than guessing enforce or waive", () => {
		withEnv({ OPENSCREEN_SYMBOL_FLOOR: "yes-please", CI: undefined }, (t) => {
			expect(() => t.resolveSymbolCeiling()).toThrow(/not a value this guard knows/);
		});
	});

	it("refuses host mode under CI, so it cannot reach a published artifact", () => {
		withEnv({ OPENSCREEN_SYMBOL_FLOOR: "host", CI: "true" }, (t) => {
			expect(() => t.resolveSymbolCeiling()).toThrow(/refused under CI/);
		});
	});

	// Reads this machine's own libc/libstdc++, so it asserts shape rather than values:
	// every prefix the pinned floor names came back, and each one is a version this run
	// actually parsed out of an ELF.
	//
	// Deliberately NOT asserted: that the host ceiling is at least the pinned one. Host
	// mode substitutes, it does not raise — on a distro OLDER than the floor the ceiling
	// legitimately comes back lower, which makes the check stricter rather than weaker.
	// Requiring otherwise would fail this test on a correct machine.
	it.runIf(process.platform === "linux")("takes the ceiling from this machine in host mode", () => {
		withEnv({ OPENSCREEN_SYMBOL_FLOOR: "host", CI: undefined }, (t) => {
			const { ceiling, pinned } = t.resolveSymbolCeiling();

			expect(pinned).toBe(false);
			expect(ceiling).not.toBe(t.MAX_SYMBOL_VERSION);
			expect(Object.keys(ceiling).sort()).toEqual(Object.keys(t.MAX_SYMBOL_VERSION).sort());
			for (const [prefix, version] of Object.entries(ceiling)) {
				expect(version, `${prefix} came back as ${JSON.stringify(version)}`).toMatch(
					/^\d+(\.\d+)*$/,
				);
			}
		});
	});
});

// ---------------------------------------------------------------------------
// macOS deployment floor (issue #515)
// ---------------------------------------------------------------------------
//
// Mach-O headers are synthesised here rather than compiled with clang, so this runs on
// the Linux and Windows CI legs too. That is the same reason the guard parses the file
// itself instead of shelling out to `vtool`: the check has to be present everywhere the
// hook is, not conditionally absent on the hosts where nobody would notice.
//
// The parser is separately cross-checked against the real thing — on a machine with a
// staged macOS payload, every Mach-O in it agreed with `vtool -show-build` (44/44).

import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { declaredAppVersionFrom } from "./macos-floor.mjs";

/** Packs X.Y.Z the way LC_BUILD_VERSION does: one byte per component, X in the top half. */
function packVersion(text) {
	const [x = 0, y = 0, z = 0] = text.split(".").map(Number);
	return ((x & 0xffff) << 16) | ((y & 0xff) << 8) | (z & 0xff);
}

/** A 64-bit Mach-O carrying exactly one load command: LC_BUILD_VERSION for macOS. */
function thinMachO(minOs) {
	const header = Buffer.alloc(32);
	header.writeUInt32LE(0xfeedfacf, 0); // MH_MAGIC_64
	header.writeUInt32LE(1, 16); // ncmds
	const lc = Buffer.alloc(24);
	lc.writeUInt32LE(0x32, 0); // LC_BUILD_VERSION
	lc.writeUInt32LE(24, 4); // cmdsize
	lc.writeUInt32LE(1, 8); // PLATFORM_MACOS
	lc.writeUInt32LE(packVersion(minOs), 12);
	return Buffer.concat([header, lc]);
}

/** The older spelling, which anything built against an older SDK carries instead. */
function thinMachOVersionMin(minOs) {
	const header = Buffer.alloc(32);
	header.writeUInt32LE(0xfeedfacf, 0);
	header.writeUInt32LE(1, 16);
	const lc = Buffer.alloc(16);
	lc.writeUInt32LE(0x24, 0); // LC_VERSION_MIN_MACOSX
	lc.writeUInt32LE(16, 4);
	lc.writeUInt32LE(packVersion(minOs), 8);
	return Buffer.concat([header, lc]);
}

/** A universal binary whose slices disagree — the highest floor is the one that counts. */
function fatMachO(minOsPerSlice) {
	const headerSize = 8 + minOsPerSlice.length * 20;
	const head = Buffer.alloc(headerSize);
	head.writeUInt32BE(0xcafebabe, 0);
	head.writeUInt32BE(minOsPerSlice.length, 4);
	const slices = minOsPerSlice.map(thinMachO);
	let offset = headerSize;
	slices.forEach((slice, i) => {
		const entry = 8 + i * 20;
		head.writeUInt32BE(offset, entry + 8); // offset
		head.writeUInt32BE(slice.length, entry + 12); // size
		offset += slice.length;
	});
	return Buffer.concat([head, ...slices]);
}

function withPayload(files, body) {
	const dir = mkdtempSync(path.join(tmpdir(), "openscreen-minos-"));
	try {
		for (const [name, bytes] of Object.entries(files)) {
			writeFileSync(path.join(dir, name), bytes);
		}
		return body(dir);
	} finally {
		rmSync(dir, { recursive: true, force: true });
	}
}

const testing = () => require(BEFORE_PACK).__testing;

describe("machoMinOs", () => {
	it("reads LC_BUILD_VERSION", () => {
		withPayload({ helper: thinMachO("12.0") }, (dir) => {
			expect(testing().machoMinOs(path.join(dir, "helper"))).toBe("12.0.0");
		});
	});

	it("reads the older LC_VERSION_MIN_MACOSX spelling", () => {
		withPayload({ helper: thinMachOVersionMin("11.3") }, (dir) => {
			expect(testing().machoMinOs(path.join(dir, "helper"))).toBe("11.3.0");
		});
	});

	it("takes the HIGHEST floor across a universal binary's slices", () => {
		// An arm64 half built correctly does not rescue an x86_64 half that was not:
		// Intel users are stranded just as thoroughly.
		withPayload({ fat: fatMachO(["12.0", "26.0"]) }, (dir) => {
			expect(testing().machoMinOs(path.join(dir, "fat"))).toBe("26.0.0");
		});
	});

	it("returns null for a Mach-O that declares no deployment target", () => {
		const header = Buffer.alloc(32);
		header.writeUInt32LE(0xfeedfacf, 0);
		withPayload({ bare: header }, (dir) => {
			expect(testing().machoMinOs(path.join(dir, "bare"))).toBeNull();
		});
	});
});

describe("checkMacOsVersionFloor", () => {
	/**
	 * Fixtures are derived from the floor rather than written as literals. An earlier
	 * revision hardcoded the then-current floor as "the offending version", and raising
	 * the floor silently turned the offender into a compliant binary — the guard's own
	 * tests stopped testing it. The exact versions were never the point; being on the
	 * wrong side of the floor is.
	 */
	const floorMajor = Number(testing().MAC_MIN_OS_FLOOR.split(".")[0]);
	const above = (bump = 1) => `${floorMajor + bump}.0`;
	const below = () => `${floorMajor - 1}.0`;

	it("passes a payload built at or below the floor", () => {
		withPayload({ a: thinMachO(testing().MAC_MIN_OS_FLOOR), b: thinMachO(below()) }, (dir) => {
			expect(() => testing().checkMacOsVersionFloor(dir)).not.toThrow();
		});
	});

	/**
	 * The regression test for #515: the helper that stranded Monterey was built for 13,
	 * and nothing in the pipeline looked. The message has to carry enough for whoever
	 * hits it to understand the consequence rather than just raise the constant.
	 */
	it("refuses a binary built above the floor, and says which and why", () => {
		withPayload({ "openscreen-macos-cursor-helper": thinMachO(above()) }, (dir) => {
			let message = "";
			try {
				testing().checkMacOsVersionFloor(dir);
			} catch (err) {
				message = err.message;
			}
			expect(message).toContain("openscreen-macos-cursor-helper");
			expect(message).toContain(`macOS ${above()}.0`);
			expect(message).toContain(testing().MAC_MIN_OS_FLOOR);
			expect(message).toContain("#515");
			// The mechanism, so nobody "fixes" it by assuming dyld gates on the number.
			expect(message).toContain("Symbol not found");
		});
	});

	it("reports every offender, not just the first", () => {
		withPayload(
			{
				ok: thinMachO(testing().MAC_MIN_OS_FLOOR),
				bad1: thinMachO(above(1)),
				bad2: thinMachO(above(2)),
			},
			(dir) => {
				expect(() => testing().checkMacOsVersionFloor(dir)).toThrow(/bad1[\s\S]*bad2/);
			},
		);
	});

	it("shouts if it parsed nothing, rather than reporting a clean payload", () => {
		const header = Buffer.alloc(32);
		header.writeUInt32LE(0xfeedfacf, 0);
		withPayload({ bare: header }, (dir) => {
			expect(() => testing().checkMacOsVersionFloor(dir)).toThrow(/bug in machoMinOs/);
		});
	});

	it("says nothing about a directory with no Mach-O in it", () => {
		// Non-macOS packs reach this only if the tree exists; an empty one is not an error
		// here — checkNativePayload already owns "the payload is incomplete".
		withPayload({ "notes.txt": Buffer.from("hello") }, (dir) => {
			expect(() => testing().checkMacOsVersionFloor(dir)).not.toThrow();
		});
	});
});

describe("MAC_MIN_OS_FLOOR", () => {
	it("matches the floor the .app declares to LaunchServices", () => {
		// Shared parser rather than a regex of its own: electron-builder.json5 is heavily
		// commented, its comments name this very key, and a private copy here is how the
		// two guards drift into one hardened and one not (see scripts/macos-floor.mjs).
		const declared = declaredAppVersionFrom(
			readFileSync(path.join(path.dirname(BEFORE_PACK), "..", "electron-builder.json5"), "utf8"),
		);
		expect(
			declared,
			'no "minimumSystemVersion" in the mac block of electron-builder.json5 — without ' +
				"it the .app inherits Electron's own floor, which is what let #515 ship",
		).not.toBeNull();

		const { MAC_MIN_OS_FLOOR } = testing();
		const norm = (v) => v.split(".").concat(["0", "0"]).slice(0, 2).join(".");
		// Equal, not merely <=: a pack-time guard looser than the app's own declaration
		// would wave through exactly the binaries LaunchServices then refuses to run.
		expect(norm(MAC_MIN_OS_FLOOR)).toBe(norm(declared));
	});
});

// #616: a macOS .app that ships the libav dylibs but no ffmpeg CLI transcribes nothing on
// machines without a system ffmpeg — resolveFfmpeg() finds no candidate, native extraction
// throws, and the renderer can only show "Failed to fetch". The payload guard is the only
// thing that can catch that before the DMG exists; this pins it to the requirement.
describe("MAC_REQUIRED", () => {
	it("demands the ffmpeg CLI, and names transcription as what breaks without it", () => {
		const { MAC_REQUIRED } = testing();
		const entry = MAC_REQUIRED.find((req) => req.match("ffmpeg"));
		expect(entry, "MAC_REQUIRED has no entry matching a file named 'ffmpeg'").toBeDefined();
		expect(entry.breaks).toContain("#616");
	});

	it("refuses a payload that has everything except the ffmpeg binary", () => {
		const { MAC_REQUIRED, checkNativePayload } = testing();
		// One satisfying file per requirement, spelled out rather than derived from the
		// matchers (which cannot be inverted) — except the ffmpeg CLI, deliberately absent.
		const files = Object.fromEntries(
			[
				"compositor_view.node",
				"whisper-stt-server",
				"libggml-base.dylib",
				"openscreen-screencapturekit-helper",
				"libavdevice.62.dylib",
				...["avcodec", "avformat", "avutil", "swresample", "swscale", "avfilter"].map(
					(lib, i) => `lib${lib}.${62 - i}.dylib`,
				),
			].map((name) => [name, Buffer.from("x")]),
		);
		withPayload(files, (dir) => {
			expect(() =>
				checkNativePayload({
					dir,
					required: MAC_REQUIRED,
					osLabel: "macOS",
					bundleNoun: "the .app",
					emptyDirFix: "unused",
				}),
			).toThrow(/ffmpeg CLI/);
		});
	});

	it("refuses a payload whose ffmpeg CLI is missing libavdevice", () => {
		const { MAC_REQUIRED, checkNativePayload } = testing();
		const files = Object.fromEntries(
			[
				"compositor_view.node",
				"ffmpeg",
				"whisper-stt-server",
				"libggml-base.dylib",
				"openscreen-screencapturekit-helper",
				...["avcodec", "avformat", "avutil", "swresample", "swscale", "avfilter"].map(
					(lib, i) => `lib${lib}.${62 - i}.dylib`,
				),
			].map((name) => [name, Buffer.from("x")]),
		);
		withPayload(files, (dir) => {
			expect(() =>
				checkNativePayload({
					dir,
					required: MAC_REQUIRED,
					osLabel: "macOS",
					bundleNoun: "the .app",
					emptyDirFix: "unused",
				}),
			).toThrow(/libavdevice/);
		});
	});
});

// The Linux twin of #616: packages shipped the libav shared objects but no ffmpeg CLI, so
// transcription over MCP and the CLI failed for want of ffmpeg.
describe("LINUX_REQUIRED", () => {
	it("refuses a payload that has everything except the ffmpeg binary", () => {
		const { LINUX_REQUIRED, checkNativePayload } = testing();
		const everything = [
			"libonnxruntime.so",
			"compositor_view.node",
			"openscreen-pipewire-helper",
			"whisper-stt-server",
			"libggml-base.so",
			...["avcodec", "avformat", "avutil", "swresample", "swscale", "avfilter"].map(
				(lib, i) => `lib${lib}.so.${62 - i}`,
			),
		];
		const check = (dir) =>
			checkNativePayload({
				dir,
				required: LINUX_REQUIRED,
				osLabel: "Linux",
				bundleNoun: "the package",
				emptyDirFix: "unused",
			});
		const payload = (names) => Object.fromEntries(names.map((n) => [n, Buffer.from("x")]));
		withPayload(payload(everything), (dir) => {
			expect(() => check(dir)).toThrow(/ffmpeg CLI/);
		});
		withPayload(payload([...everything, "ffmpeg"]), (dir) => {
			expect(() => check(dir)).not.toThrow();
		});
	});
});

// The Windows counterpart. A synthetic PE32+ carrying only what importedDlls() reads: the
// COFF machine, one section, and an import directory naming `imports`. The tests run on
// the Linux CI, where no real Windows binary exists to point the guard at.
const MACHINE = { x64: 0x8664, arm64: 0xaa64 };

function pe(machine, imports) {
	const pe = 0x40;
	const opt = pe + 24;
	const dirs = opt + 112;
	const sectionTable = dirs + 16 * 8;
	const raw = 0x200;
	const va = 0x1000;
	const descriptors = (imports.length + 1) * 20;
	const names = imports.map((name) => Buffer.from(`${name}\0`, "latin1"));
	const b = Buffer.alloc(raw + descriptors + names.reduce((n, name) => n + name.length, 0));
	b.writeUInt16LE(0x5a4d, 0); // "MZ"
	b.writeUInt32LE(pe, 0x3c);
	b.writeUInt32LE(0x00004550, pe); // "PE\0\0"
	b.writeUInt16LE(machine, pe + 4);
	b.writeUInt16LE(1, pe + 6); // NumberOfSections
	b.writeUInt16LE(sectionTable - opt, pe + 20); // SizeOfOptionalHeader
	b.writeUInt16LE(0x20b, opt); // PE32+
	b.writeUInt32LE(16, dirs - 4); // NumberOfRvaAndSizes
	b.writeUInt32LE(va, dirs + 8); // import directory RVA
	b.writeUInt32LE(va, sectionTable + 12); // VirtualAddress
	b.writeUInt32LE(b.length - raw, sectionTable + 16); // VirtualSize
	b.writeUInt32LE(raw, sectionTable + 20); // PointerToRawData
	let at = raw + descriptors;
	names.forEach((name, i) => {
		b.writeUInt32LE(va + (at - raw), raw + i * 20 + 12); // IMAGE_IMPORT_DESCRIPTOR.Name
		name.copy(b, at);
		at += name.length;
	});
	return b;
}

/** A bin/ directory holding one `win32-<arch>` folder per key, the way electron-builder sees it. */
function withWinBin(dirs, body) {
	const bin = mkdtempSync(path.join(tmpdir(), "openscreen-winbin-"));
	try {
		for (const [tag, files] of Object.entries(dirs)) {
			mkdirSync(path.join(bin, tag));
			for (const [name, bytes] of Object.entries(files)) {
				writeFileSync(path.join(bin, tag, name), bytes);
			}
		}
		return body(bin);
	} finally {
		rmSync(bin, { recursive: true, force: true });
	}
}

describe("checkWinShippedRedist", () => {
	// The arm64 installer as CI builds it: the native payload, plus the x64 whisper
	// helper that runs under emulation until a native one is staged. `win32-*/*` ships
	// both directories.
	const arm64Native = {
		"onnxruntime.dll": pe(MACHINE.arm64, ["MSVCP140.dll", "KERNEL32.dll"]),
		"msvcp140.dll": pe(MACHINE.arm64, ["KERNEL32.dll"]),
	};
	const x64Fallback = {
		"whisper-stt-server.exe": pe(MACHINE.x64, ["ggml-base.dll", "KERNEL32.dll"]),
		"ggml-base.dll": pe(MACHINE.x64, ["VCOMP140.DLL", "KERNEL32.dll"]),
	};

	it("refuses the arm64 package when its x64 fallback has no x64 OpenMP runtime", () => {
		withWinBin({ "win32-arm64": arm64Native, "win32-x64": x64Fallback }, (bin) => {
			expect(() => testing().checkWinShippedRedist(bin)).toThrow(
				/win32-x64[\s\S]*ggml-base\.dll imports VCOMP140\.DLL/,
			);
		});
	});

	it("passes once the x64 runtime sits beside the x64 libraries", () => {
		const x64 = { ...x64Fallback, "vcomp140.dll": pe(MACHINE.x64, ["KERNEL32.dll"]) };
		withWinBin({ "win32-arm64": arm64Native, "win32-x64": x64 }, (bin) => {
			expect(() => testing().checkWinShippedRedist(bin)).not.toThrow();
		});
	});

	// The name check alone is satisfied by the wrong file: an ARM64 vcomp140.dll in
	// win32-x64 is exactly the copy the x64 loader cannot use.
	it("refuses a runtime DLL built for the other architecture", () => {
		const x64 = { ...x64Fallback, "vcomp140.dll": pe(MACHINE.arm64, ["KERNEL32.dll"]) };
		withWinBin({ "win32-arm64": arm64Native, "win32-x64": x64 }, (bin) => {
			expect(() => testing().checkWinShippedRedist(bin)).toThrow(
				/vcomp140\.dll in win32-x64 is built for arm64/,
			);
		});
	});

	// The arm64 Redist folder's vcruntime140_1.dll really does carry an x64 header (it is
	// the ARM64EC build for emulated code). Nothing ARM64 imports it, so it must not fail
	// the package — measured on the 1.13.0 arm64 installer, where it sits unused.
	it("ignores a runtime DLL of another machine that nothing in the directory imports", () => {
		const arm64 = { ...arm64Native, "vcruntime140_1.dll": pe(MACHINE.x64, ["KERNEL32.dll"]) };
		withWinBin({ "win32-arm64": arm64 }, (bin) => {
			expect(() => testing().checkWinShippedRedist(bin)).not.toThrow();
		});
	});

	// Not only the runtime: an x64 compositor addon in win32-arm64 has the right name and
	// clean imports, and an ARM64 process still cannot load it.
	it("refuses any native binary built for the other architecture", () => {
		const arm64 = {
			...arm64Native,
			"compositor_view.node": pe(MACHINE.x64, ["KERNEL32.dll"]),
		};
		withWinBin({ "win32-arm64": arm64 }, (bin) => {
			expect(() => testing().checkWinShippedRedist(bin)).toThrow(
				/compositor_view\.node in win32-arm64 is built for x64/,
			);
		});
	});
});