Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

build(desktop): reject stale sidecars and mismatched Tauri runtimes

Richie McIlroy659247650746
diff --git a/scripts/build-desktop-binaries-cache.mjs b/scripts/build-desktop-binaries-cache.mjs
new file mode 100644
index 000000000..4131b41c5
--- /dev/null
+++ b/scripts/build-desktop-binaries-cache.mjs
@@ -0,0 +1,79 @@
+import { createHash } from "node:crypto";
+import { createReadStream } from "node:fs";
+import * as fs from "node:fs/promises";
+import * as path from "node:path";
+
+async function newestMtimeMs(targetPath) {
+ let newest = 0;
+ const pending = [targetPath];
+ while (pending.length > 0) {
+ const current = pending.pop();
+ const stat = await fs.stat(current).catch(() => null);
+ if (!stat) continue;
+ if (stat.isFile()) {
+ newest = Math.max(newest, stat.mtimeMs);
+ continue;
+ }
+ if (stat.isDirectory()) {
+ const entries = await fs.readdir(current);
+ for (const name of entries) pending.push(path.join(current, name));
+ }
+ }
+ return newest;
+}
+
+async function sha256(filePath) {
+ const hash = createHash("sha256");
+ for await (const chunk of createReadStream(filePath)) hash.update(chunk);
+ return hash.digest("hex");
+}
+
+export async function releaseBinaryMatchesDebugBinary(
+ releaseBinary,
+ debugBinaries,
+) {
+ const releaseStat = await fs.stat(releaseBinary).catch(() => null);
+ if (!releaseStat?.isFile()) return false;
+
+ let releaseHash;
+ for (const debugBinary of debugBinaries) {
+ const debugStat = await fs.stat(debugBinary).catch(() => null);
+ if (!debugStat?.isFile() || debugStat.size !== releaseStat.size) continue;
+ releaseHash ??= await sha256(releaseBinary);
+ if ((await sha256(debugBinary)) === releaseHash) return true;
+ }
+ return false;
+}
+
+export async function stagedBinariesAreCurrent(
+ releaseBinary,
+ stagedBinaries,
+ watchPaths,
+ debugBinaries = [],
+) {
+ const releaseStat = await fs.stat(releaseBinary).catch(() => null);
+ if (!releaseStat?.isFile()) return false;
+ if (await releaseBinaryMatchesDebugBinary(releaseBinary, debugBinaries))
+ return false;
+
+ const newestSource = Math.max(
+ 0,
+ ...(await Promise.all(watchPaths.map(newestMtimeMs))),
+ );
+ if (newestSource > releaseStat.mtimeMs) return false;
+
+ const releaseHash = await sha256(releaseBinary);
+ const stagedMatches = await Promise.all(
+ stagedBinaries.map(async (stagedBinary) => {
+ const stat = await fs.stat(stagedBinary).catch(() => null);
+ if (
+ !stat?.isFile() ||
+ stat.mtimeMs < newestSource ||
+ stat.size !== releaseStat.size
+ )
+ return false;
+ return (await sha256(stagedBinary)) === releaseHash;
+ }),
+ );
+ return stagedMatches.every(Boolean);
+}
diff --git a/scripts/build-desktop-binaries-cache.test.mjs b/scripts/build-desktop-binaries-cache.test.mjs
new file mode 100644
index 000000000..bea865d0c
--- /dev/null
+++ b/scripts/build-desktop-binaries-cache.test.mjs
@@ -0,0 +1,119 @@
+import assert from "node:assert/strict";
+import * as fs from "node:fs/promises";
+import * as os from "node:os";
+import * as path from "node:path";
+import test from "node:test";
+
+import {
+ releaseBinaryMatchesDebugBinary,
+ stagedBinariesAreCurrent,
+} from "./build-desktop-binaries-cache.mjs";
+
+async function fixture(context) {
+ const directory = await fs.mkdtemp(
+ path.join(os.tmpdir(), "cap-sidecar-cache-"),
+ );
+ context.after(async () => fs.rm(directory, { recursive: true, force: true }));
+ const watched = path.join(directory, "source.rs");
+ const release = path.join(directory, "release.exe");
+ const cli = path.join(directory, "cap-cli.exe");
+ const exporter = path.join(directory, "cap-exporter.exe");
+ await fs.writeFile(watched, "source");
+ await fs.writeFile(release, "optimized");
+ await fs.writeFile(cli, "optimized");
+ await fs.writeFile(exporter, "optimized");
+ const sourceTime = new Date("2025-01-01T00:00:00.000Z");
+ const binaryTime = new Date("2025-01-02T00:00:00.000Z");
+ await fs.utimes(watched, sourceTime, sourceTime);
+ for (const file of [release, cli, exporter])
+ await fs.utimes(file, binaryTime, binaryTime);
+ return { watched, release, cli, exporter, binaryTime };
+}
+
+test("rejects a debug binary copied into the release artifact path", async (context) => {
+ const { watched, release, cli, exporter } = await fixture(context);
+ const debug = path.join(path.dirname(release), "debug.exe");
+ await fs.writeFile(debug, "optimized");
+
+ assert.equal(await releaseBinaryMatchesDebugBinary(release, [debug]), true);
+ assert.equal(
+ await stagedBinariesAreCurrent(
+ release,
+ [cli, exporter],
+ [watched],
+ [debug],
+ ),
+ false,
+ );
+});
+
+test("accepts an optimized release artifact when a different debug binary exists", async (context) => {
+ const { watched, release, cli, exporter } = await fixture(context);
+ const debug = path.join(path.dirname(release), "debug.exe");
+ await fs.writeFile(debug, "debug-one");
+
+ assert.equal(await releaseBinaryMatchesDebugBinary(release, [debug]), false);
+ assert.equal(
+ await stagedBinariesAreCurrent(
+ release,
+ [cli, exporter],
+ [watched],
+ [debug],
+ ),
+ true,
+ );
+});
+
+test("accepts current release binary and byte-identical staged sidecars", async (context) => {
+ const { watched, release, cli, exporter } = await fixture(context);
+ assert.equal(
+ await stagedBinariesAreCurrent(release, [cli, exporter], [watched]),
+ true,
+ );
+});
+
+test("rejects staged sidecars when the release binary does not exist", async (context) => {
+ const { watched, release, cli, exporter } = await fixture(context);
+ await fs.rm(release);
+ assert.equal(
+ await stagedBinariesAreCurrent(release, [cli, exporter], [watched]),
+ false,
+ );
+});
+
+test("rejects same-sized debug content even when staged files are newer", async (context) => {
+ const { watched, release, cli, exporter, binaryTime } =
+ await fixture(context);
+ await fs.writeFile(cli, "debug-old");
+ await fs.utimes(cli, binaryTime, binaryTime);
+ assert.equal(
+ await stagedBinariesAreCurrent(release, [cli, exporter], [watched]),
+ false,
+ );
+});
+
+test("rejects a release binary older than watched source", async (context) => {
+ const { watched, release, cli, exporter } = await fixture(context);
+ const newerSource = new Date("2025-01-03T00:00:00.000Z");
+ await fs.utimes(watched, newerSource, newerSource);
+ assert.equal(
+ await stagedBinariesAreCurrent(release, [cli, exporter], [watched]),
+ false,
+ );
+});
+
+test("rejects any missing or mismatched secondary destination", async (context) => {
+ const { watched, release, cli, exporter, binaryTime } =
+ await fixture(context);
+ await fs.writeFile(exporter, "wrong-one");
+ await fs.utimes(exporter, binaryTime, binaryTime);
+ assert.equal(
+ await stagedBinariesAreCurrent(release, [cli, exporter], [watched]),
+ false,
+ );
+ await fs.rm(exporter);
+ assert.equal(
+ await stagedBinariesAreCurrent(release, [cli, exporter], [watched]),
+ false,
+ );
+});
diff --git a/scripts/build-desktop-binaries.mjs b/scripts/build-desktop-binaries.mjs
index 66af8651a..fdda83509 100644
--- a/scripts/build-desktop-binaries.mjs
+++ b/scripts/build-desktop-binaries.mjs
@@ -3,6 +3,11 @@ import * as fs from "node:fs/promises";
import * as path from "node:path";
import { fileURLToPath } from "node:url";
+import {
+ releaseBinaryMatchesDebugBinary,
+ stagedBinariesAreCurrent,
+} from "./build-desktop-binaries-cache.mjs";
+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.resolve(__dirname, "..");
const binariesDir = path.join(
@@ -32,35 +37,6 @@ async function fileExists(p) {
.catch(() => false);
}
-async function newestMtimeMs(targetPath) {
- let max = 0;
- const stack = [targetPath];
- while (stack.length > 0) {
- const current = stack.pop();
- const stat = await fs.stat(current).catch(() => null);
- if (!stat) continue;
- if (stat.isFile()) {
- if (stat.mtimeMs > max) max = stat.mtimeMs;
- continue;
- }
- if (stat.isDirectory()) {
- const entries = await fs.readdir(current);
- for (const name of entries) stack.push(path.join(current, name));
- }
- }
- return max;
-}
-
-async function isUpToDate(destPath, sourcePaths) {
- if (!(await fileExists(destPath))) return false;
- const destStat = await fs.stat(destPath);
- for (const src of sourcePaths) {
- const newest = await newestMtimeMs(src);
- if (newest > destStat.mtimeMs) return false;
- }
- return true;
-}
-
async function main() {
const target =
process.argv[2] || process.env.RUST_TARGET_TRIPLE || detectHostTriple();
@@ -112,13 +88,31 @@ async function buildSidecar(sidecar, target, ext) {
const dests = sidecar.destBinaries.map((destBinary) =>
path.join(binariesDir, `${destBinary}-${target}${ext}`),
);
+ const debugBinaries = [
+ path.join(
+ repoRoot,
+ "target",
+ target,
+ "debug",
+ `${sidecar.sourceBinary}${ext}`,
+ ),
+ path.join(repoRoot, "target", "debug", `${sidecar.sourceBinary}${ext}`),
+ ];
+
+ if (await releaseBinaryMatchesDebugBinary(src, debugBinaries)) {
+ console.warn(
+ `Discarding debug binary found in release artifact path: ${src}`,
+ );
+ await fs.rm(src);
+ }
if (
- (
- await Promise.all(
- dests.map((dest) => isUpToDate(dest, sidecar.watchPaths)),
- )
- ).every(Boolean)
+ await stagedBinariesAreCurrent(
+ src,
+ dests,
+ sidecar.watchPaths,
+ debugBinaries,
+ )
) {
console.log(
`${sidecar.destBinaries.join(", ")} desktop binaries up to date`,
diff --git a/scripts/check-tauri-plugin-versions.js b/scripts/check-tauri-plugin-versions.js
index 80fae5579..46b85d831 100755
--- a/scripts/check-tauri-plugin-versions.js
+++ b/scripts/check-tauri-plugin-versions.js
@@ -30,6 +30,75 @@ function parseVersion(version) {
};
}
+export function parseDesktopTauriVersions(pnpmLock, cargoLock) {
+ const versions = {};
+ let insideDesktop = false;
+ let currentPackage = null;
+
+ for (const line of pnpmLock.split("\n")) {
+ if (/^ {2}\S/.test(line)) {
+ if (insideDesktop) break;
+ insideDesktop = /^ {2}apps\/desktop:\s*$/.test(line);
+ currentPackage = null;
+ continue;
+ }
+ if (!insideDesktop) continue;
+
+ const packageMatch = line.match(
+ /^ {6}['"]?(@tauri-apps\/(?:api|cli))['"]?:\s*$/,
+ );
+ if (packageMatch) {
+ currentPackage = packageMatch[1];
+ continue;
+ }
+ if (!currentPackage) continue;
+
+ const versionMatch = line.match(/^ {8}version:\s*['"]?([^'"\s(]+)/);
+ if (versionMatch) {
+ versions[currentPackage] = versionMatch[1];
+ currentPackage = null;
+ }
+ }
+
+ const rustVersion = cargoLock.match(
+ /^name = "tauri"\r?\nversion = "([^"]+)"/m,
+ )?.[1];
+ for (const packageName of ["@tauri-apps/api", "@tauri-apps/cli"]) {
+ if (!versions[packageName]) {
+ throw new Error(`Missing ${packageName} in apps/desktop pnpm lockfile`);
+ }
+ }
+ if (!rustVersion) throw new Error('Missing "tauri" package in Cargo.lock');
+
+ return {
+ api: versions["@tauri-apps/api"],
+ cli: versions["@tauri-apps/cli"],
+ rust: rustVersion,
+ };
+}
+
+export function compareTauriRuntimeVersions(versions) {
+ return [
+ ["@tauri-apps/api", versions.api],
+ ["@tauri-apps/cli", versions.cli],
+ ].map(([jsName, jsVersion]) => {
+ const jsParsed = parseVersion(jsVersion);
+ const rustParsed = parseVersion(versions.rust);
+ const jsMajorMinor = `${jsParsed.major}.${jsParsed.minor}`;
+ const rustMajorMinor = `${rustParsed.major}.${rustParsed.minor}`;
+ return {
+ jsName,
+ rustName: "tauri",
+ jsVersion,
+ rustVersion: versions.rust,
+ jsMajorMinor,
+ rustMajorMinor,
+ majorMinor: jsMajorMinor,
+ matching: jsMajorMinor === rustMajorMinor,
+ };
+ });
+}
+
// Parse pnpm-lock.yaml to extract Tauri plugin versions
function parsePnpmLock(lockfilePath) {
const content = fs.readFileSync(lockfilePath, "utf8");
@@ -220,6 +289,10 @@ function main() {
// Parse both lockfiles
const jsPlugins = parsePnpmLock(pnpmLockPath);
const rustPlugins = parseCargoLock(cargoLockPath);
+ const runtimeVersions = parseDesktopTauriVersions(
+ fs.readFileSync(pnpmLockPath, "utf8"),
+ fs.readFileSync(cargoLockPath, "utf8"),
+ );
console.log(`Found ${Object.keys(jsPlugins).length} JS Tauri plugins`);
console.log(
@@ -240,6 +313,9 @@ function main() {
// Compare versions
const results = compareVersions(jsPlugins, rustPlugins);
+ for (const runtime of compareTauriRuntimeVersions(runtimeVersions)) {
+ results[runtime.matching ? "matching" : "mismatched"].push(runtime);
+ }
// Report results
if (results.matching.length > 0) {
@@ -334,4 +410,4 @@ Exit codes:
process.exit(0);
}
-main();
+if (process.argv[1] && path.resolve(process.argv[1]) === __filename) main();
diff --git a/scripts/check-tauri-plugin-versions.test.mjs b/scripts/check-tauri-plugin-versions.test.mjs
new file mode 100644
index 000000000..6f5c20316
--- /dev/null
+++ b/scripts/check-tauri-plugin-versions.test.mjs
@@ -0,0 +1,83 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import {
+ compareTauriRuntimeVersions,
+ parseDesktopTauriVersions,
+} from "./check-tauri-plugin-versions.js";
+
+function pnpmLock(cli, api = "2.8.0") {
+ return `importers:
+
+ apps/desktop:
+ dependencies:
+ '@tauri-apps/api':
+ specifier: ${api}
+ version: ${api}
+ devDependencies:
+ '@tauri-apps/cli':
+ specifier: ${cli}
+ version: ${cli}
+
+ apps/legacy:
+ devDependencies:
+ '@tauri-apps/cli':
+ specifier: 1.6.3
+ version: 1.6.3
+`;
+}
+
+function cargoLock(version = "2.8.5") {
+ return `[[package]]
+name = "tauri"
+version = "${version}"
+`;
+}
+
+test("matching Tauri runtime versions allow independent patch releases", () => {
+ const versions = parseDesktopTauriVersions(pnpmLock("2.8.4"), cargoLock());
+ assert.deepEqual(versions, { api: "2.8.0", cli: "2.8.4", rust: "2.8.5" });
+ assert.ok(
+ compareTauriRuntimeVersions(versions).every((entry) => entry.matching),
+ );
+});
+
+test("newer CLI minors cannot silently mismatch the locked Rust runtime", () => {
+ const versions = parseDesktopTauriVersions(pnpmLock("2.11.4"), cargoLock());
+ const results = compareTauriRuntimeVersions(versions);
+ assert.equal(
+ results.find((entry) => entry.jsName.endsWith("api"))?.matching,
+ true,
+ );
+ assert.equal(
+ results.find((entry) => entry.jsName.endsWith("cli"))?.matching,
+ false,
+ );
+});
+
+test("a mismatched JavaScript API minor is rejected independently", () => {
+ const versions = parseDesktopTauriVersions(
+ pnpmLock("2.8.4", "2.9.0"),
+ cargoLock(),
+ );
+ const result = compareTauriRuntimeVersions(versions).find((entry) =>
+ entry.jsName.endsWith("api"),
+ );
+ assert.equal(result?.matching, false);
+});
+
+test("the desktop importer is isolated from legacy Tauri applications", () => {
+ const versions = parseDesktopTauriVersions(pnpmLock("2.8.4"), cargoLock());
+ assert.equal(versions.cli, "2.8.4");
+});
+
+test("missing desktop runtime dependencies fail closed", () => {
+ assert.throws(
+ () =>
+ parseDesktopTauriVersions("importers:\n apps/desktop:\n", cargoLock()),
+ /Missing @tauri-apps\/api/,
+ );
+ assert.throws(
+ () => parseDesktopTauriVersions(pnpmLock("2.8.4"), ""),
+ /Missing "tauri" package/,
+ );
+});