Stealth Chromium that passes every bot detection test. Drop-in Playwright replacement with source-level fingerprint patches. 50+ tests passed.
Python ai-agentsanti-detectantidetect-browserbot-detectionbrowser-automationcaptcha-bypasschromiumcloudflarecloudflare-bypassfingerprintheadless-browserplaywrightpuppeteerpythonrecaptchaseleniumstealth-browserundetectedweb-scrapingwebscraping
fix(download): make concurrent first-run downloads safe (#555)
Shubham9fb05e0fc86a
diff --git a/cloakbrowser/download.py b/cloakbrowser/download.pyindex f51025c..ef8c01e 100644--- a/cloakbrowser/download.py+++ b/cloakbrowser/download.py@@ -18,6 +18,7 @@ import tarfileimport tempfileimport threadingimport time+import uuidfrom pathlib import Pathimport httpx@@ -76,6 +77,15 @@ WELCOME_FREE_INTERVAL = 24 * 3600# version comes from the network, which we don't call just to print a banner).PRO_MAJOR = "154"+# Attempts to rename an extraction into place while concurrent callers are+# replacing the same partial install (see _extract_archive).+INSTALL_RENAME_ATTEMPTS = 5++# Retries for a directory rename that Windows transiently denies (see+# _rename_dir_with_retry): about 2.5 seconds in total.+TRANSIENT_RENAME_ATTEMPTS = 10+TRANSIENT_RENAME_DELAY = 0.25+def _welcome_due(marker: Path, pro: bool) -> bool:"""Whether the welcome banner should be shown now.@@ -898,40 +908,81 @@ def _extract_archive() -> None:"""Extract tar.gz or zip archive to destination directory."""logger.info("Extracting to %s", dest_dir)+ bp = binary_path or get_binary_path()- # Clean existing dir if partial download existed- if dest_dir.exists():- try:- shutil.rmtree(dest_dir)- except OSError:- logger.error("Failed to remove partial extraction directory: %s", dest_dir)- raise+ # Extract into a private sibling dir, then rename it into place. Concurrent+ # first runs (in this process or others) each get their own staging dir, so+ # none of them can see or delete another's half-written install.+ staging_dir = dest_dir.with_name(f"{dest_dir.name}.partial-{uuid.uuid4().hex}")+ staging_dir.mkdir()+ stale_dirs: list[Path] = []+ try:+ if str(archive_path).endswith(".zip"):+ _extract_zip(archive_path, staging_dir)+ else:+ _extract_tar(archive_path, staging_dir)- dest_dir.mkdir(parents=True, exist_ok=True)+ # If extracted into a single subdirectory, flatten it+ # (e.g. fingerprint-chromium-142-custom-v2/chrome → chrome)+ # But never flatten .app bundles: macOS needs the bundle structure intact+ _flatten_single_subdir(staging_dir)- if str(archive_path).endswith(".zip"):- _extract_zip(archive_path, dest_dir)- else:- _extract_tar(archive_path, dest_dir)+ # Make binary executable+ staged_binary_path = staging_dir / bp.relative_to(dest_dir)+ if staged_binary_path.exists():+ _make_executable(staged_binary_path)- # If extracted into a single subdirectory, flatten it- # (e.g. fingerprint-chromium-142-custom-v2/chrome → chrome)- # But never flatten .app bundles — macOS needs the bundle structure intact- _flatten_single_subdir(dest_dir)+ # macOS: remove quarantine/provenance xattrs to prevent Gatekeeper prompts+ if platform.system() == "Darwin":+ _remove_quarantine(staging_dir)- # Make binary executable- bp = binary_path or get_binary_path()- if bp.exists():- _make_executable(bp)-- # macOS: remove quarantine/provenance xattrs to prevent Gatekeeper prompts- if platform.system() == "Darwin":- _remove_quarantine(dest_dir)+ for attempt in range(1, INSTALL_RENAME_ATTEMPTS + 1):+ try:+ _rename_dir_with_retry(staging_dir, dest_dir)+ break+ except OSError:+ # dest_dir is in the way. Keep it if another caller finished a complete+ # install; replace it if it is an incomplete leftover, such as an+ # interrupted in-place extraction from an older release.+ if bp.exists() and _is_executable(bp):+ break+ if attempt == INSTALL_RENAME_ATTEMPTS:+ raise+ # Rename the leftover aside before deleting it. Deleting it in place races+ # other callers renaming their extraction into dest_dir.+ stale_dir = dest_dir.with_name(f"{dest_dir.name}.stale-{uuid.uuid4().hex}")+ try:+ _rename_dir_with_retry(dest_dir, stale_dir)+ except FileNotFoundError:+ continue # another caller moved it aside first+ stale_dirs.append(stale_dir)+ finally:+ shutil.rmtree(staging_dir, ignore_errors=True)+ for stale_dir in stale_dirs:+ shutil.rmtree(stale_dir, ignore_errors=True)if bp.exists():logger.info("Binary ready: %s", bp)+def _rename_dir_with_retry(source: Path, destination: Path) -> None:+ """Rename a directory, retrying while Windows reports it as in use."""+ for attempt in range(1, TRANSIENT_RENAME_ATTEMPTS + 1):+ try:+ source.rename(destination)+ return+ except PermissionError:+ # Windows antivirus briefly holds freshly written files open, which fails the+ # rename with access denied. An existing destination is not transient.+ if (+ platform.system() != "Windows"+ or attempt == TRANSIENT_RENAME_ATTEMPTS+ or destination.exists()+ ):+ raise+ time.sleep(TRANSIENT_RENAME_DELAY)++def _extract_tar(archive_path: Path, dest_dir: Path) -> None:"""Extract tar.gz. Archive is signature-verified before extraction, so unpackas-is. filter="fully_trusted" pins legacy behavior (3.14 defaults to "data",diff --git a/dotnet/src/CloakBrowser/Download.cs b/dotnet/src/CloakBrowser/Download.csindex 2ab6355..72fa94c 100644--- a/dotnet/src/CloakBrowser/Download.cs+++ b/dotnet/src/CloakBrowser/Download.cs@@ -48,6 +48,21 @@ public static class Download// once (see ShowWelcome).internal const long WelcomeFreeInterval = 24L * 3600;+ // Attempts to rename an extraction into place while concurrent callers are+ // replacing the same partial install (see ExtractArchive).+ private const int InstallRenameAttempts = 5;++ // Retries for a directory rename that Windows transiently denies (see+ // MoveDirectoryWithRetry): about 2.5 seconds in total.+ private const int TransientRenameAttempts = 10;+ private const int TransientRenameDelayMs = 250;++ // HRESULTs of the IOException Directory.Move throws on Windows for+ // ERROR_ACCESS_DENIED, ERROR_SHARING_VIOLATION and ERROR_LOCK_VIOLATION.+ private const int AccessDeniedHResult = unchecked((int)0x80070005);+ private const int SharingViolationHResult = unchecked((int)0x80070020);+ private const int LockViolationHResult = unchecked((int)0x80070021);+private static readonly HttpClient Http = CreateHttpClient();private static HttpClient CreateHttpClient()@@ -962,28 +977,70 @@ public static class Downloadprivate static void ExtractArchive(string archivePath, string destDir, string? binaryPath){CloakLog.Info("Extracting to {0}", destDir);+ var bp = binaryPath ?? Config.GetBinaryPath();- // Clean existing dir if partial download existed.- if (Directory.Exists(destDir))- Directory.Delete(destDir, recursive: true);-- Directory.CreateDirectory(destDir);+ // Extract into a private sibling dir, then rename it into place. Concurrent+ // first runs (in this process or others) each get their own staging dir, so+ // none of them can see or delete another's half-written install.+ var stagingDir = $"{destDir}.partial-{Guid.NewGuid():N}";+ Directory.CreateDirectory(stagingDir);+ var staleDirs = new List<string>();+ try+ {+ if (archivePath.EndsWith(".zip", StringComparison.OrdinalIgnoreCase))+ ExtractZip(archivePath, stagingDir);+ else+ ExtractTar(archivePath, stagingDir);- if (archivePath.EndsWith(".zip", StringComparison.OrdinalIgnoreCase))- ExtractZip(archivePath, destDir);- else- ExtractTar(archivePath, destDir);+ // If extracted into a single subdirectory, flatten it (but never .app bundles).+ FlattenSingleSubdir(stagingDir);- // If extracted into a single subdirectory, flatten it (but never .app bundles).- FlattenSingleSubdir(destDir);+ var stagedBinaryPath = Path.Combine(stagingDir, Path.GetRelativePath(destDir, bp));+ if (File.Exists(stagedBinaryPath))+ MakeExecutable(stagedBinaryPath);- var bp = binaryPath ?? Config.GetBinaryPath();- if (File.Exists(bp))- MakeExecutable(bp);+ // macOS: remove quarantine/provenance xattrs to prevent Gatekeeper prompts.+ if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))+ RemoveQuarantine(stagingDir);- // macOS: remove quarantine/provenance xattrs to prevent Gatekeeper prompts.- if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))- RemoveQuarantine(destDir);+ for (var attempt = 1; attempt <= InstallRenameAttempts; attempt++)+ {+ try+ {+ MoveDirectoryWithRetry(stagingDir, destDir);+ break;+ }+ catch (Exception err) when (err is IOException or UnauthorizedAccessException)+ {+ // destDir is in the way. Keep it if another caller finished a complete+ // install; replace it if it is an incomplete leftover, such as an+ // interrupted in-place extraction from an older release.+ if (File.Exists(bp) && IsExecutable(bp)) break;+ if (attempt == InstallRenameAttempts) throw;+ }+ // Rename the leftover aside before deleting it. Deleting it in place races+ // other callers renaming their extraction into destDir.+ var staleDir = $"{destDir}.stale-{Guid.NewGuid():N}";+ try+ {+ MoveDirectoryWithRetry(destDir, staleDir);+ }+ catch (DirectoryNotFoundException)+ {+ continue; // another caller moved it aside first+ }+ staleDirs.Add(staleDir);+ }+ }+ finally+ {+ // Best effort, so a cleanup failure never masks the exception being thrown.+ foreach (var leftoverDir in staleDirs.Prepend(stagingDir))+ {+ try { if (Directory.Exists(leftoverDir)) Directory.Delete(leftoverDir, recursive: true); }+ catch (Exception err) when (err is IOException or UnauthorizedAccessException) { }+ }+ }if (File.Exists(bp))CloakLog.Info("Binary ready: {0}", bp);@@ -998,6 +1055,32 @@ public static class DownloadTarFile.ExtractToDirectory(gzip, destDir, overwriteFiles: true);}+ /// <summary>Rename a directory, retrying while Windows reports it as in use.</summary>+ private static void MoveDirectoryWithRetry(string source, string destination)+ {+ for (var attempt = 1; attempt <= TransientRenameAttempts; attempt++)+ {+ try+ {+ Directory.Move(source, destination);+ return;+ }+ catch (Exception err) when (err is IOException or UnauthorizedAccessException)+ {+ // Windows antivirus briefly holds freshly written files open, which fails the+ // move with access denied. An existing destination is not transient.+ var accessDenied = err is UnauthorizedAccessException+ || err.HResult is AccessDeniedHResult or SharingViolationHResult or LockViolationHResult;+ if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)+ || !accessDenied+ || attempt == TransientRenameAttempts+ || Directory.Exists(destination))+ throw;+ Thread.Sleep(TransientRenameDelayMs);+ }+ }+ }+private static void ExtractZip(string archivePath, string destDir){// Signature-verified before extraction, so unpack as-is.diff --git a/dotnet/tests/CloakBrowser.Tests/DownloadConfigTests.cs b/dotnet/tests/CloakBrowser.Tests/DownloadConfigTests.csindex 6c05463..b0cf03e 100644--- a/dotnet/tests/CloakBrowser.Tests/DownloadConfigTests.cs+++ b/dotnet/tests/CloakBrowser.Tests/DownloadConfigTests.cs@@ -1,5 +1,10 @@+using System.Formats.Tar;using System.IO;using System.IO.Compression;+using System.Net;+using System.Net.Sockets;+using System.Runtime.InteropServices;+using System.Text;using CloakBrowser;using Xunit;@@ -112,3 +117,235 @@ public class WrapperVersionNewerTestsAssert.True(Download.WrapperVersionNewer("0.4.0", "0.x.0"));}}++/// <summary>+/// Concurrent first-run callers of <see cref="Download.EnsureBinaryAsync"/> against one+/// empty cache, with the archive served by a local HttpListener acting as a custom+/// mirror. In env-serial because it sets CLOAKBROWSER_CACHE_DIR and+/// CLOAKBROWSER_DOWNLOAD_URL.+/// </summary>+[Collection("env-serial")]+public class ConcurrentFirstRunTests+{+ private const int Callers = 4;+ private const int FillerFiles = 300;+ private static readonly byte[] BinaryBytes = Encoding.ASCII.GetBytes("#!/bin/sh\necho fake-chrome\n");++ private static readonly string[] IsolatedEnvNames =+ {+ "CLOAKBROWSER_CACHE_DIR", "CLOAKBROWSER_DOWNLOAD_URL", "CLOAKBROWSER_SKIP_CHECKSUM",+ "CLOAKBROWSER_LICENSE_KEY", "CLOAKBROWSER_BINARY_PATH", "CLOAKBROWSER_VERSION",+ };++ /// <summary>+ /// An archive with this platform's binary layout plus enough filler files that an+ /// extraction takes a measurable time.+ /// </summary>+ private static byte[] CreatePlatformArchive()+ {+ var binaryRelPath = Path.GetRelativePath(Config.GetBinaryDir(), Config.GetBinaryPath());+ using var archive = new MemoryStream();+ using (var gzip = new GZipStream(archive, CompressionLevel.Fastest, leaveOpen: true))+ using (var tar = new TarWriter(gzip))+ {+ AddTarFile(tar, binaryRelPath, BinaryBytes);+ for (var i = 0; i < FillerFiles; i++)+ {+ var filler = new byte[16 * 1024];+ Array.Fill(filler, (byte)i);+ AddTarFile(tar, $"lib/part-{i}.bin", filler);+ }+ }+ return archive.ToArray();+ }++ private static void AddTarFile(TarWriter tar, string name, byte[] content) =>+ tar.WriteEntry(new PaxTarEntry(TarEntryType.RegularFile, name)+ {+ DataStream = new MemoryStream(content),+ Mode = UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute+ | UnixFileMode.GroupRead | UnixFileMode.GroupExecute+ | UnixFileMode.OtherRead | UnixFileMode.OtherExecute,+ });++ /// <summary>Reads the install the way a launch would. Returns what is wrong with it, or "complete".</summary>+ private static string InspectInstall()+ {+ try+ {+ var binaryPath = Config.GetBinaryPath();+ if (!File.ReadAllBytes(binaryPath).AsSpan().SequenceEqual(BinaryBytes)) return "binary content differs";+ if (!Config.IsExecutableFile(binaryPath)) return "binary not executable";+ var fillerCount = Directory.GetFiles(Path.Combine(Config.GetBinaryDir(), "lib")).Length;+ return fillerCount == FillerFiles ? "complete" : $"lib has {fillerCount} files";+ }+ catch (IOException err)+ {+ return err.GetType().Name;+ }+ }++ private static int FindFreeTcpPort()+ {+ var probe = new TcpListener(IPAddress.Loopback, 0);+ probe.Start();+ var port = ((IPEndPoint)probe.LocalEndpoint).Port;+ probe.Stop();+ return port;+ }++ [Fact]+ public async Task Install_stays_complete_while_other_callers_finish()+ {+ if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) return;++ var previousEnv = IsolatedEnvNames.ToDictionary(name => name, Environment.GetEnvironmentVariable);+ var cacheDir = Directory.CreateTempSubdirectory("cloakbrowser-concurrent-").FullName;+ var mirrorPort = FindFreeTcpPort();+ using var mirror = new HttpListener();+ mirror.Prefixes.Add($"http://127.0.0.1:{mirrorPort}/");+ mirror.Start();+ try+ {+ UseLocalMirror(cacheDir, mirrorPort);+ var archiveBytes = CreatePlatformArchive();++ // One caller downloads at once. The others have already seen an empty+ // cache but their downloads are held until the first has returned,+ // which is the state a batch of simultaneous cold launches ends up in.+ var releaseHeldDownloads = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);+ var requestCount = 0;+ async Task ServeArchiveAsync(HttpListenerContext request)+ {+ if (Interlocked.Increment(ref requestCount) > 1) await releaseHeldDownloads.Task;+ await RespondWithArchiveAsync(request, archiveBytes);+ }+ _ = Task.Run(async () =>+ {+ for (var i = 0; i < Callers; i++)+ _ = ServeArchiveAsync(await mirror.GetContextAsync());+ });++ var callers = Enumerable.Range(0, Callers).Select(_ => Download.EnsureBinaryAsync()).ToArray();+ Assert.Equal(Config.GetBinaryPath(), await await Task.WhenAny(callers));++ // The first caller would now exec its binary. Keep reading the install+ // while the held callers download and extract.+ releaseHeldDownloads.SetResult();+ var observedStates = new HashSet<string> { InspectInstall() };+ var allCallers = Task.WhenAll(callers);+ while (!allCallers.IsCompleted) observedStates.Add(InspectInstall());+ observedStates.Add(InspectInstall());++ foreach (var caller in callers)+ Assert.Equal(Config.GetBinaryPath(), await caller);+ Assert.Equal(new[] { "complete" }, observedStates);+ Assert.Equal(+ new[] { Path.GetFileName(Config.GetBinaryDir()) },+ Directory.GetFileSystemEntries(cacheDir).Select(Path.GetFileName).Where(name => !name!.StartsWith('.')));+ }+ finally+ {+ mirror.Stop();+ foreach (var (name, value) in previousEnv) Environment.SetEnvironmentVariable(name, value);+ Directory.Delete(cacheDir, recursive: true);+ }+ }++ [Fact]+ public async Task Replaces_partial_install_left_by_interrupted_extraction()+ {+ if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) return;++ var previousEnv = IsolatedEnvNames.ToDictionary(name => name, Environment.GetEnvironmentVariable);+ var cacheDir = Directory.CreateTempSubdirectory("cloakbrowser-concurrent-").FullName;+ var mirrorPort = FindFreeTcpPort();+ using var mirror = new HttpListener();+ mirror.Prefixes.Add($"http://127.0.0.1:{mirrorPort}/");+ mirror.Start();+ try+ {+ UseLocalMirror(cacheDir, mirrorPort);+ var archiveBytes = CreatePlatformArchive();+ _ = Task.Run(async () => await RespondWithArchiveAsync(await mirror.GetContextAsync(), archiveBytes));+ Directory.CreateDirectory(Path.Combine(Config.GetBinaryDir(), "lib"));+ File.WriteAllText(Path.Combine(Config.GetBinaryDir(), "lib", "part-0.bin"), "truncated");++ Assert.Equal(Config.GetBinaryPath(), await Download.EnsureBinaryAsync());+ Assert.Equal("complete", InspectInstall());+ }+ finally+ {+ mirror.Stop();+ foreach (var (name, value) in previousEnv) Environment.SetEnvironmentVariable(name, value);+ Directory.Delete(cacheDir, recursive: true);+ }+ }++ [Fact]+ public async Task Concurrent_callers_replace_partial_install()+ {+ if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) return;++ var previousEnv = IsolatedEnvNames.ToDictionary(name => name, Environment.GetEnvironmentVariable);+ var cacheDir = Directory.CreateTempSubdirectory("cloakbrowser-concurrent-").FullName;+ var mirrorPort = FindFreeTcpPort();+ using var mirror = new HttpListener();+ mirror.Prefixes.Add($"http://127.0.0.1:{mirrorPort}/");+ mirror.Start();+ try+ {+ UseLocalMirror(cacheDir, mirrorPort);+ var archiveBytes = CreatePlatformArchive();++ // Answer only once every caller is downloading, so all of them find the+ // partial install in the way when they move their extraction into place.+ _ = Task.Run(async () =>+ {+ var heldRequests = new List<HttpListenerContext>();+ for (var i = 0; i < Callers; i++)+ heldRequests.Add(await mirror.GetContextAsync());+ foreach (var heldRequest in heldRequests)+ _ = RespondWithArchiveAsync(heldRequest, archiveBytes);+ });+ Directory.CreateDirectory(Path.Combine(Config.GetBinaryDir(), "lib"));+ for (var i = 0; i < FillerFiles; i++)+ File.WriteAllText(Path.Combine(Config.GetBinaryDir(), "lib", $"part-{i}.bin"), "truncated");++ var callers = Enumerable.Range(0, Callers).Select(_ => Download.EnsureBinaryAsync()).ToArray();+ var outcomes = new List<string>();+ foreach (var caller in callers)+ {+ try { outcomes.Add(await caller); }+ catch (Exception err) { outcomes.Add($"{err.GetType().Name}: {err.Message}"); }+ }++ Assert.Equal(Enumerable.Repeat(Config.GetBinaryPath(), Callers), outcomes);+ Assert.Equal("complete", InspectInstall());+ Assert.Equal(+ new[] { Path.GetFileName(Config.GetBinaryDir()) },+ Directory.GetFileSystemEntries(cacheDir).Select(Path.GetFileName).Where(name => !name!.StartsWith('.')));+ }+ finally+ {+ mirror.Stop();+ foreach (var (name, value) in previousEnv) Environment.SetEnvironmentVariable(name, value);+ Directory.Delete(cacheDir, recursive: true);+ }+ }++ private static void UseLocalMirror(string cacheDir, int mirrorPort)+ {+ foreach (var name in IsolatedEnvNames) Environment.SetEnvironmentVariable(name, null);+ Environment.SetEnvironmentVariable("CLOAKBROWSER_CACHE_DIR", cacheDir);+ Environment.SetEnvironmentVariable("CLOAKBROWSER_DOWNLOAD_URL", $"http://127.0.0.1:{mirrorPort}");+ Environment.SetEnvironmentVariable("CLOAKBROWSER_SKIP_CHECKSUM", "true");+ }++ private static async Task RespondWithArchiveAsync(HttpListenerContext request, byte[] archiveBytes)+ {+ request.Response.ContentLength64 = archiveBytes.Length;+ await request.Response.OutputStream.WriteAsync(archiveBytes);+ request.Response.Close();+ }+}diff --git a/js/src/download.ts b/js/src/download.tsindex 6c34c4e..578a811 100644--- a/js/src/download.ts+++ b/js/src/download.ts@@ -5,7 +5,7 @@*/import { execFileSync } from "node:child_process";-import { createHash, createPublicKey, verify as cryptoVerify } from "node:crypto";+import { createHash, createPublicKey, randomUUID, verify as cryptoVerify } from "node:crypto";import fs from "node:fs";import path from "node:path";import { createWriteStream } from "node:fs";@@ -50,6 +50,13 @@ export const WELCOME_FREE_INTERVAL_SEC = 1 * 24 * 60 * 60;// (no local constant to derive it from — the live Pro version comes from the// network, which we don't call just to print a banner). Mirrors download.py.const PRO_MAJOR = "154";+// Attempts to rename an extraction into place while concurrent callers are+// replacing the same partial install (see extractArchive).+const INSTALL_RENAME_ATTEMPTS = 5;+// Retries for a directory rename that Windows transiently denies (see+// renameDirWithRetry): about 2.5 seconds in total.+const TRANSIENT_RENAME_ATTEMPTS = 10;+const TRANSIENT_RENAME_DELAY_MS = 250;/*** A downloaded binary could not be authenticated (bad/missing signature,@@ -417,7 +424,7 @@ async function downloadAndExtract(version?: string): Promise<void> {// Download to temp file (atomic — no partial downloads in cache)const tmpPath = path.join(path.dirname(binaryDir),- `_download_${Date.now()}${getArchiveExt()}`+ `_download_${randomUUID()}${getArchiveExt()}`);try {@@ -926,7 +933,7 @@ export async function downloadProBinary(version: string, licenseKey: string): Prconst tmpPath = path.join(path.dirname(binaryDir),- `_download_${Date.now()}${getArchiveExt()}`+ `_download_${randomUUID()}${getArchiveExt()}`);try {@@ -1030,32 +1037,66 @@ async function extractArchive(binaryPath?: string): Promise<void> {console.log(`[cloakbrowser] Extracting to ${destDir}`);+ const bp = binaryPath || getBinaryPath();- // Clean existing dir if partial download existed- if (fs.existsSync(destDir)) {- fs.rmSync(destDir, { recursive: true, force: true });- }- fs.mkdirSync(destDir, { recursive: true });+ // Extract into a private sibling dir, then rename it into place. Concurrent+ // first runs (in this process or others) each get their own staging dir, so+ // none of them can see or delete another's half-written install.+ const stagingDir = `${destDir}.partial-${randomUUID()}`;+ fs.mkdirSync(stagingDir);+ const staleDirs: string[] = [];+ try {+ if (archivePath.endsWith(".zip")) {+ await extractZip(archivePath, stagingDir);+ } else {+ // Signature-verified before extraction, so unpack as-is.+ await tarExtract({ file: archivePath, cwd: stagingDir, strip: 0 });+ }- if (archivePath.endsWith(".zip")) {- await extractZip(archivePath, destDir);- } else {- // Signature-verified before extraction, so unpack as-is.- await tarExtract({ file: archivePath, cwd: destDir, strip: 0 });- }+ // Flatten single subdirectory if needed+ flattenSingleSubdir(stagingDir);- // Flatten single subdirectory if needed- flattenSingleSubdir(destDir);+ // Make binary executable (skip on Windows: no-op / AV lock risk)+ const stagedBinaryPath = path.join(stagingDir, path.relative(destDir, bp));+ if (process.platform !== "win32" && fs.existsSync(stagedBinaryPath)) {+ fs.chmodSync(stagedBinaryPath, 0o755);+ }- // Make binary executable (skip on Windows — no-op / AV lock risk)- const bp = binaryPath || getBinaryPath();- if (process.platform !== "win32" && fs.existsSync(bp)) {- fs.chmodSync(bp, 0o755);- }+ // macOS: remove quarantine/provenance xattrs to prevent Gatekeeper prompts+ if (process.platform === "darwin") {+ removeQuarantine(stagingDir);+ }- // macOS: remove quarantine/provenance xattrs to prevent Gatekeeper prompts- if (process.platform === "darwin") {- removeQuarantine(destDir);+ for (let attempt = 1; attempt <= INSTALL_RENAME_ATTEMPTS; attempt++) {+ try {+ await renameDirWithRetry(stagingDir, destDir);+ break;+ } catch (err) {+ // destDir is in the way. Keep it if another caller finished a complete+ // install; replace it if it is an incomplete leftover, such as an+ // interrupted in-place extraction from an older release.+ if (fs.existsSync(bp) && isExecutable(bp)) break;+ if (attempt === INSTALL_RENAME_ATTEMPTS) throw err;+ }+ // Rename the leftover aside before deleting it. Deleting it in place races+ // other callers renaming their extraction into destDir.+ const staleDir = `${destDir}.stale-${randomUUID()}`;+ try {+ await renameDirWithRetry(destDir, staleDir);+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code === "ENOENT") continue; // another caller moved it aside first+ throw err;+ }+ staleDirs.push(staleDir);+ }+ } finally {+ for (const leftoverDir of [stagingDir, ...staleDirs]) {+ try {+ fs.rmSync(leftoverDir, { recursive: true, force: true });+ } catch {+ // Best effort, so a cleanup failure never masks the error being thrown.+ }+ }}if (fs.existsSync(bp)) {@@ -1063,6 +1104,29 @@ async function extractArchive(}}+/** Rename a directory, retrying while Windows reports it as in use. */+async function renameDirWithRetry(source: string, destination: string): Promise<void> {+ for (let attempt = 1; attempt <= TRANSIENT_RENAME_ATTEMPTS; attempt++) {+ try {+ fs.renameSync(source, destination);+ return;+ } catch (err) {+ // Windows antivirus briefly holds freshly written files open, which fails the+ // rename with EPERM/EACCES/EBUSY. An existing destination is not transient.+ const code = (err as NodeJS.ErrnoException).code;+ if (+ process.platform !== "win32" ||+ !(code === "EPERM" || code === "EACCES" || code === "EBUSY") ||+ attempt === TRANSIENT_RENAME_ATTEMPTS ||+ fs.existsSync(destination)+ ) {+ throw err;+ }+ await new Promise((resolve) => setTimeout(resolve, TRANSIENT_RENAME_DELAY_MS));+ }+ }+}+async function extractZip(archivePath: string, destDir: string): Promise<void> {// Brief delay to ensure OS fully releases file handles (Windows)await new Promise(resolve => setTimeout(resolve, 500));diff --git a/js/tests/update.test.ts b/js/tests/update.test.tsindex a1fa462..8723031 100644--- a/js/tests/update.test.ts+++ b/js/tests/update.test.ts@@ -1,12 +1,17 @@import { describe, it, expect, vi, afterEach, beforeEach } from "vitest";+import { execFile } from "node:child_process";import * as fs from "node:fs";+import * as http from "node:http";+import type { AddressInfo } from "node:net";import * as os from "node:os";import * as path from "node:path";+import { promisify } from "node:util";import {binarySupportsHeadlessNoViewport,binarySupportsHttpProxyInlineAuth,binarySupportsMaximizedWindow,getChromiumVersion,+ getBinaryDir,getBinaryPath,getDownloadUrl,getEffectiveVersion,@@ -659,3 +664,170 @@ describe("welcome banner cadence", () => {expect(welcomeDue(marker, true)).toBe(false); // pro: existence = already shown});});++describe("concurrent first-run download", () => {+ const CALLERS = 4;+ const FILLER_FILES = 300;+ const PARTIAL_INSTALL_FILES = 2000;+ const binaryBytes = Buffer.from("#!/bin/sh\necho fake-chrome\n");+ let cacheDir: string;+ let archiveBytes: Buffer;+ let originalCacheDir: string | undefined;++ beforeEach(async () => {+ const { create: tarCreate } = await import("tar");+ originalCacheDir = process.env.CLOAKBROWSER_CACHE_DIR;+ cacheDir = fs.mkdtempSync(path.join(os.tmpdir(), "cloakbrowser-concurrent-"));+ process.env.CLOAKBROWSER_CACHE_DIR = cacheDir;+ process.env.CLOAKBROWSER_DOWNLOAD_URL = "https://mirror.invalid";+ process.env.CLOAKBROWSER_SKIP_CHECKSUM = "true";+ delete process.env.CLOAKBROWSER_BINARY_PATH;+ delete process.env.CLOAKBROWSER_VERSION;++ // A small archive with the platform's binary layout plus enough filler+ // files that concurrent extractions overlap in time.+ const staging = fs.mkdtempSync(path.join(os.tmpdir(), "cloakbrowser-archive-"));+ const binaryRelPath = path.relative(getBinaryDir(), getBinaryPath());+ fs.mkdirSync(path.join(staging, path.dirname(binaryRelPath)), { recursive: true });+ fs.writeFileSync(path.join(staging, binaryRelPath), binaryBytes, { mode: 0o755 });+ fs.mkdirSync(path.join(staging, "lib"));+ for (let i = 0; i < FILLER_FILES; i++) {+ fs.writeFileSync(path.join(staging, "lib", `part-${i}.bin`), Buffer.alloc(16 * 1024, i));+ }+ const archivePath = path.join(staging, "..", `${path.basename(staging)}.tar.gz`);+ await tarCreate({ gzip: true, file: archivePath, cwd: staging }, fs.readdirSync(staging));+ archiveBytes = fs.readFileSync(archivePath);+ fs.rmSync(staging, { recursive: true, force: true });+ fs.rmSync(archivePath, { force: true });+ });++ afterEach(() => {+ vi.restoreAllMocks();+ fs.rmSync(cacheDir, { recursive: true, force: true });+ if (originalCacheDir === undefined) delete process.env.CLOAKBROWSER_CACHE_DIR;+ else process.env.CLOAKBROWSER_CACHE_DIR = originalCacheDir;+ delete process.env.CLOAKBROWSER_DOWNLOAD_URL;+ delete process.env.CLOAKBROWSER_SKIP_CHECKSUM;+ });++ // Reads the install the way a launch would. Returns what is wrong with it, or "complete".+ function inspectInstall(): string {+ try {+ const binaryPath = getBinaryPath();+ if (!fs.readFileSync(binaryPath).equals(binaryBytes)) return "binary content differs";+ if ((fs.statSync(binaryPath).mode & 0o111) === 0) return "binary not executable";+ const fillerCount = fs.readdirSync(path.join(getBinaryDir(), "lib")).length;+ return fillerCount === FILLER_FILES ? "complete" : `lib has ${fillerCount} files`;+ } catch (err) {+ return (err as NodeJS.ErrnoException).code ?? String(err);+ }+ }++ it.skipIf(process.platform === "win32")(+ "an install stays complete while other first-run callers finish",+ async () => {+ // Caller 0 downloads at once. The others have already seen an empty+ // cache but their downloads are held until caller 0 has returned, which+ // is the state a batch of simultaneous cold launches ends up in.+ let releaseHeldDownloads!: () => void;+ const heldDownloads = new Promise<void>((resolve) => (releaseHeldDownloads = resolve));+ let fetchCount = 0;+ vi.spyOn(globalThis, "fetch").mockImplementation(async () => {+ if (fetchCount++ > 0) await heldDownloads;+ return new Response(archiveBytes);+ });+ vi.spyOn(console, "log").mockImplementation(() => {});+ vi.spyOn(console, "error").mockImplementation(() => {});++ const callers = Array.from({ length: CALLERS }, () => ensureBinary());+ const firstBinaryPath = await callers[0];+ expect(firstBinaryPath).toBe(getBinaryPath());++ // Caller 0 would now exec its binary. Keep reading the install while+ // the held callers download and extract.+ releaseHeldDownloads();+ const observedStates = new Set<string>([inspectInstall()]);+ const otherCallers = Promise.allSettled(callers.slice(1));+ let otherCallersDone = false;+ otherCallers.then(() => (otherCallersDone = true));+ while (!otherCallersDone) {+ observedStates.add(inspectInstall());+ await new Promise((resolve) => setImmediate(resolve));+ }+ observedStates.add(inspectInstall());++ for (const outcome of await otherCallers) {+ expect(outcome).toEqual({ status: "fulfilled", value: getBinaryPath() });+ }+ expect([...observedStates]).toEqual(["complete"]);+ expect(fs.readdirSync(cacheDir).filter((name) => !name.startsWith("."))).toEqual([+ path.basename(getBinaryDir()),+ ]);+ },+ );++ it.skipIf(process.platform === "win32")(+ "replaces a partial install left by an interrupted extraction",+ async () => {+ vi.spyOn(globalThis, "fetch").mockImplementation(async () => new Response(archiveBytes));+ vi.spyOn(console, "log").mockImplementation(() => {});+ fs.mkdirSync(path.join(getBinaryDir(), "lib"), { recursive: true });+ fs.writeFileSync(path.join(getBinaryDir(), "lib", "part-0.bin"), "truncated");++ expect(await ensureBinary()).toBe(getBinaryPath());+ expect(inspectInstall()).toBe("complete");+ },+ );++ it.skipIf(process.platform === "win32")(+ "concurrent processes replace a partial install left by an interrupted extraction",+ async () => {+ // Enough files that deleting the partial install overlaps other callers.+ fs.mkdirSync(path.join(getBinaryDir(), "lib"), { recursive: true });+ for (let i = 0; i < PARTIAL_INSTALL_FILES; i++) {+ fs.writeFileSync(path.join(getBinaryDir(), "lib", `part-${i}.bin`), "truncated");+ }++ // Answer only once every caller is downloading, so all of them find the+ // partial install in the way when they move their extraction into place.+ const heldResponses: http.ServerResponse[] = [];+ const mirror = http.createServer((_request, response) => {+ heldResponses.push(response);+ if (heldResponses.length === CALLERS) {+ for (const heldResponse of heldResponses) heldResponse.end(archiveBytes);+ }+ });+ await new Promise<void>((resolve) => mirror.listen(0, "127.0.0.1", resolve));+ const mirrorUrl = `http://127.0.0.1:${(mirror.address() as AddressInfo).port}`;++ // Callers in one process cannot interleave inside extractArchive's+ // synchronous rename and cleanup, so each caller is a separate process+ // running the built dist/ (npm run build first, as CI does).+ const downloadModuleUrl = new URL("../dist/download.js", import.meta.url).href;+ const callerScript =+ `const { ensureBinary } = await import(${JSON.stringify(downloadModuleUrl)});` ++ `console.log("BINARY_PATH=" + (await ensureBinary()));`;+ try {+ const callers = await Promise.allSettled(+ Array.from({ length: CALLERS }, () =>+ promisify(execFile)(process.execPath, ["--input-type=module", "-e", callerScript], {+ env: { ...process.env, CLOAKBROWSER_DOWNLOAD_URL: mirrorUrl },+ }),+ ),+ );+ const outcomes = callers.map((caller) =>+ caller.status === "fulfilled"+ ? caller.value.stdout.trim().split("\n").at(-1)+ : String(caller.reason),+ );+ expect(outcomes).toEqual(Array(CALLERS).fill(`BINARY_PATH=${getBinaryPath()}`));+ } finally {+ mirror.close();+ }+ expect(inspectInstall()).toBe("complete");+ expect(fs.readdirSync(cacheDir).filter((name) => !name.startsWith("."))).toEqual([+ path.basename(getBinaryDir()),+ ]);+ },+ );+});diff --git a/tests/test_extract.py b/tests/test_extract.pyindex 59537be..74cfb28 100644--- a/tests/test_extract.py+++ b/tests/test_extract.py@@ -3,12 +3,17 @@import ioimport osimport platform+import queue+import shutilimport statimport tarfile+import threadingimport zipfileimport pytest+import cloakbrowser.download as download+from cloakbrowser.config import get_binary_dir, get_binary_pathfrom cloakbrowser.download import (_extract_tar,_extract_zip,@@ -166,3 +171,156 @@ class TestPermissions:binary.write_bytes(b"binary")binary.chmod(0o644)assert not _is_executable(binary)+++# ---------------------------------------------------------------------------+# Concurrent first-run downloads+# ---------------------------------------------------------------------------+++class TestConcurrentFirstRun:+ CALLERS = 4+ FILLER_FILES = 300+ BINARY_BYTES = b"#!/bin/sh\necho fake-chrome\n"++ def _create_platform_archive(self, tmp_path):+ """An archive with this platform's binary layout plus enough filler+ files that an extraction spans many thread switches."""+ binary_rel_path = get_binary_path().relative_to(get_binary_dir()).as_posix()+ members = {binary_rel_path: self.BINARY_BYTES}+ for i in range(self.FILLER_FILES):+ members[f"lib/part-{i}.bin"] = bytes([i % 256]) * 16 * 1024+ archive = tmp_path / "platform.tar.gz"+ with tarfile.open(archive, "w:gz") as tar:+ for name, content in members.items():+ info = tarfile.TarInfo(name=name)+ info.size = len(content)+ info.mode = 0o755+ tar.addfile(info, io.BytesIO(content))+ return archive++ def _inspect_install(self) -> str:+ """Reads the install the way a launch would. Returns what is wrong+ with it, or "complete"."""+ try:+ binary_path = get_binary_path()+ if binary_path.read_bytes() != self.BINARY_BYTES:+ return "binary content differs"+ if not _is_executable(binary_path):+ return "binary not executable"+ filler_count = len(os.listdir(get_binary_dir() / "lib"))+ if filler_count != self.FILLER_FILES:+ return f"lib has {filler_count} files"+ return "complete"+ except OSError as err:+ return type(err).__name__++ def _use_local_mirror(self, cache_dir, monkeypatch):+ monkeypatch.setenv("CLOAKBROWSER_CACHE_DIR", str(cache_dir))+ monkeypatch.setenv("CLOAKBROWSER_DOWNLOAD_URL", "https://mirror.invalid")+ monkeypatch.setenv("CLOAKBROWSER_SKIP_CHECKSUM", "true")+ for name in ("CLOAKBROWSER_LICENSE_KEY", "CLOAKBROWSER_BINARY_PATH", "CLOAKBROWSER_VERSION"):+ monkeypatch.delenv(name, raising=False)++ @pytest.mark.skipif(platform.system() == "Windows", reason="POSIX exec semantics")+ def test_install_stays_complete_while_other_callers_finish(self, tmp_path, monkeypatch):+ archive = self._create_platform_archive(tmp_path)+ cache_dir = tmp_path / "cache"+ self._use_local_mirror(cache_dir, monkeypatch)++ # One caller downloads at once. The others have already seen an empty+ # cache but their downloads are held until the first has returned,+ # which is the state a batch of simultaneous cold launches ends up in.+ all_callers_downloading = threading.Barrier(self.CALLERS)+ release_held_downloads = threading.Event()++ def fake_download_file(url, dest, headers=None):+ if all_callers_downloading.wait() != 0:+ release_held_downloads.wait()+ shutil.copyfile(archive, dest)++ monkeypatch.setattr(download, "_download_file", fake_download_file)++ caller_outcomes: queue.Queue = queue.Queue()++ def run_caller():+ try:+ caller_outcomes.put(("returned", download.ensure_binary()))+ except Exception as err:+ caller_outcomes.put(("raised", repr(err)))++ callers = [threading.Thread(target=run_caller) for _ in range(self.CALLERS)]+ for caller in callers:+ caller.start()++ outcomes = [caller_outcomes.get(timeout=60)]+ assert outcomes[0] == ("returned", str(get_binary_path()))++ # The first caller would now exec its binary. Keep reading the install+ # while the held callers download and extract.+ release_held_downloads.set()+ observed_states = {self._inspect_install()}+ while any(caller.is_alive() for caller in callers):+ observed_states.add(self._inspect_install())+ observed_states.add(self._inspect_install())++ while not caller_outcomes.empty():+ outcomes.append(caller_outcomes.get())+ assert outcomes == [("returned", str(get_binary_path()))] * self.CALLERS+ assert observed_states == {"complete"}+ assert [p.name for p in cache_dir.iterdir() if not p.name.startswith(".")] == [+ get_binary_dir().name+ ]++ @pytest.mark.skipif(platform.system() == "Windows", reason="POSIX exec semantics")+ def test_replaces_partial_install_left_by_interrupted_extraction(self, tmp_path, monkeypatch):+ archive = self._create_platform_archive(tmp_path)+ self._use_local_mirror(tmp_path / "cache", monkeypatch)+ monkeypatch.setattr(+ download, "_download_file", lambda url, dest, headers=None: shutil.copyfile(archive, dest)+ )+ (get_binary_dir() / "lib").mkdir(parents=True)+ (get_binary_dir() / "lib" / "part-0.bin").write_bytes(b"truncated")++ assert download.ensure_binary() == str(get_binary_path())+ assert self._inspect_install() == "complete"++ @pytest.mark.skipif(platform.system() == "Windows", reason="POSIX exec semantics")+ def test_concurrent_callers_replace_partial_install(self, tmp_path, monkeypatch):+ archive = self._create_platform_archive(tmp_path)+ cache_dir = tmp_path / "cache"+ self._use_local_mirror(cache_dir, monkeypatch)++ # Every caller downloads at the same moment, so all of them find the+ # partial install in the way when they move their extraction into place.+ all_callers_downloading = threading.Barrier(self.CALLERS)++ def fake_download_file(url, dest, headers=None):+ all_callers_downloading.wait()+ shutil.copyfile(archive, dest)++ monkeypatch.setattr(download, "_download_file", fake_download_file)+ (get_binary_dir() / "lib").mkdir(parents=True)+ for i in range(self.FILLER_FILES):+ (get_binary_dir() / "lib" / f"part-{i}.bin").write_bytes(b"truncated")++ caller_outcomes: queue.Queue = queue.Queue()++ def run_caller():+ try:+ caller_outcomes.put(("returned", download.ensure_binary()))+ except Exception as err:+ caller_outcomes.put(("raised", repr(err)))++ callers = [threading.Thread(target=run_caller) for _ in range(self.CALLERS)]+ for caller in callers:+ caller.start()+ for caller in callers:+ caller.join(timeout=60)++ outcomes = [caller_outcomes.get_nowait() for _ in range(caller_outcomes.qsize())]+ assert outcomes == [("returned", str(get_binary_path()))] * self.CALLERS+ assert self._inspect_install() == "complete"+ assert [p.name for p in cache_dir.iterdir() if not p.name.startswith(".")] == [+ get_binary_dir().name+ ]