using System.Globalization; using Febe.Core.Abstractions; namespace Febe.Browser.Hosting; /// Where the session cookie is looked for (existence only, never the value). /// Cookie name. Instagram's is «sessionid» (public knowledge; hypothesis H10, to confirm in M0). /// Address whose cookies are listed. public sealed record SessionCookieOptions(string CookieName, string SiteUrl) { public static SessionCookieOptions Instagram { get; } = new("sessionid", "https://www.instagram.com/"); } /// Chromium-specific launch settings, on top of . public sealed record ChromiumLaunchOptions { /// /// Adds --no-sandbox. Only as the documented compromise of S5 (spec §11), never by default: /// as root Chromium refuses to start without it; as a normal user with user namespaces it is not needed. /// public bool NoSandbox { get; init; } /// Extra arguments, checked by . public IReadOnlyList ExtraArguments { get; init; } = []; /// Environment overrides for the browser process (e.g. LANG, TZ in tests). A null value removes the variable. public IReadOnlyDictionary Environment { get; init; } = new Dictionary(); /// Start page: always the rest page. public string StartUrl { get; init; } = "about:blank"; /// /// How long a Chromium that is alive may take to open its debugging port and its first tab. A crash fails the start /// at once; this only bounds a browser that hangs, so it is generous for a loaded machine (docs/decisioni.md, #46). /// public TimeSpan StartupTimeout { get; init; } = TimeSpan.FromSeconds(120); public RestartPolicy Restart { get; init; } = RestartPolicy.Default; public SessionCookieOptions SessionCookie { get; init; } = SessionCookieOptions.Instagram; /// /// On a new profile, writes preferences that turn off password saving and autofill (spec §6.1, §11). /// The Docker image also ships a policy file for the same purpose. /// public bool SeedProfilePreferences { get; init; } = true; /// /// Called with every browser process right after it starts (also after a restart), before it is ready. Windows: Edge /// is tied to the life of Febe.exe, so that it never outlives a crash of Febe holding the profile and the debugging /// port. Null: nothing. /// public Action? ProcessStarted { get; init; } } /// /// Builds Chromium's command line (spec §6.1, §11): a normal windowed browser with a fixed debugging port on /// 127.0.0.1. Never headless, never automation mode, never user agent, language or proxy overrides: /// language comes from LANG and the time zone from TZ. /// public static class ChromiumCommandLine { /// Arguments refused in , by prefix. public static IReadOnlyList ForbiddenPrefixes { get; } = [ "--headless", "--enable-automation", "--remote-debugging-pipe", "--remote-debugging-port", "--remote-debugging-address", "--remote-allow-origins", "--user-agent", "--lang", "--accept-lang", "--proxy-server", "--proxy-pac-url", "--proxy-auto-detect", "--proxy-bypass-list", "--no-proxy-server", "--host-resolver-rules", "--disable-blink-features", "--enable-blink-features", "--blink-settings", "--disable-web-security", "--load-extension", "--disable-extensions-except", "--user-data-dir", "--window-size", "--use-mobile-user-agent", "--force-device-scale-factor", "--auto-open-devtools-for-tabs", "--no-sandbox", ]; public static IReadOnlyList Build(BrowserOptions options, ChromiumLaunchOptions launch) { ArgumentNullException.ThrowIfNull(options); ArgumentNullException.ThrowIfNull(launch); if (options.DebugPort is < 1024 or > 65535) { throw new ArgumentOutOfRangeException(nameof(options), options.DebugPort, "La porta di debug deve essere fissa, fra 1024 e 65535: mai 0 (specifica §6.1)."); } if (options.WindowWidth < 400 || options.WindowHeight < 300) { throw new ArgumentOutOfRangeException(nameof(options), "La finestra del browser è troppo piccola."); } ArgumentException.ThrowIfNullOrWhiteSpace(options.ProfileDirectory); var inv = CultureInfo.InvariantCulture; var args = new List { $"--remote-debugging-port={options.DebugPort.ToString(inv)}", $"--user-data-dir={Path.GetFullPath(options.ProfileDirectory)}", "--no-first-run", "--no-default-browser-check", $"--window-size={options.WindowWidth.ToString(inv)},{options.WindowHeight.ToString(inv)}", "--window-position=0,0", "--password-store=basic", "--disable-dev-shm-usage", }; if (launch.NoSandbox) { args.Add("--no-sandbox"); } foreach (var extra in launch.ExtraArguments) { EnsureAllowed(extra); args.Add(extra); } // The start page goes last, as a plain argument. args.Add(string.IsNullOrWhiteSpace(launch.StartUrl) ? "about:blank" : launch.StartUrl); return args; } /// Refuses arguments that change what the browser declares, put it in automation mode or are set by Febe itself. public static void EnsureAllowed(string argument) { ArgumentNullException.ThrowIfNull(argument); var trimmed = argument.Trim(); if (!trimmed.StartsWith("--", StringComparison.Ordinal)) { throw new ArgumentException("Gli argomenti aggiuntivi di Chromium devono essere opzioni «--nome».", nameof(argument)); } foreach (var prefix in ForbiddenPrefixes) { if (trimmed.Equals(prefix, StringComparison.OrdinalIgnoreCase) || trimmed.StartsWith(prefix + "=", StringComparison.OrdinalIgnoreCase)) { throw new ArgumentException($"L'opzione «{prefix}» di Chromium è vietata o la imposta già Febe (specifica §2, regola 2; §6.1; §11).", nameof(argument)); } } } /// /// Finds Chromium: explicit path, then the FEBE_CHROMIUM variable, then PATH and the usual places /// (Debian's «chromium» first; Edge on Windows as the S2 fallback). /// public static string? FindExecutable(string? explicitPath = null) { if (!string.IsNullOrWhiteSpace(explicitPath)) { return File.Exists(explicitPath) ? explicitPath : null; } var fromEnv = System.Environment.GetEnvironmentVariable("FEBE_CHROMIUM"); if (!string.IsNullOrWhiteSpace(fromEnv) && File.Exists(fromEnv)) { return fromEnv; } if (OperatingSystem.IsWindows()) { var programFilesX86 = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ProgramFilesX86); var programFiles = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ProgramFiles); return ExecutableSearch.Find( ["msedge", "chrome"], [ Path.Combine(programFilesX86, "Microsoft", "Edge", "Application", "msedge.exe"), Path.Combine(programFiles, "Microsoft", "Edge", "Application", "msedge.exe"), ]); } return ExecutableSearch.Find( ["chromium", "chromium-browser", "google-chrome-stable", "google-chrome"], ["/usr/bin/chromium", "/usr/lib/chromium/chromium"]); } }