Server reale e veste Docker (M5): composizione, collegamento, vista remota, salute, immagine e modello Unraid

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
Claude committed 2026-10-13 20:17:22 +00:00
1 parent 0515776b04
commit 550c220cd4
35 files changed
+6124 -10

No files matched your search

+381
View File
@@ -0,0 +1,381 @@
using System.Globalization;
using System.Net;
using Febe.Browser.Hosting;
using Febe.Browser.Recipes;
using Febe.Web;
namespace Febe.Server;
/// <summary>
/// Configuration of the real server (spec §11): environment variables of the container, plus a few command-line
/// options for development (other folders, the local test site, a short first-session delay). The password comes only
/// from the environment, never from the command line (which other users of the machine can read).
/// </summary>
internal sealed record ServerOptions
{
public const string DefaultZone = "Europe/Rome";
public const string DefaultLanguage = "it_IT.UTF-8";
public const int DefaultDebugPort = 9222;
public const string DefaultDisplay = ":99";
/// <summary>FEBE_PASSWORD: the interface password. Mandatory; never logged or shown.</summary>
public string? Password { get; init; }
/// <summary>Where Kestrel listens: every address in Docker (the port is published), 127.0.0.1 with <c>--ascolta</c>.</summary>
public IPAddress ListenAddress { get; init; } = IPAddress.Any;
/// <summary>FEBE_PORTA, 8480 by default.</summary>
public int Port { get; init; } = FebeListen.DefaultPort;
/// <summary>TZ, Europe/Rome by default: the clock of the engine, file names, and the browser's time zone.</summary>
public string ZoneId { get; init; } = DefaultZone;
public TimeZoneInfo Zone { get; init; } = FindZone(DefaultZone) ?? TimeZoneInfo.Utc;
/// <summary>LANG, it_IT.UTF-8 by default: the browser's language comes from it (spec §6.1).</summary>
public string Language { get; init; } = DefaultLanguage;
/// <summary>Data folder: database, browser profile, thumbnails, backups, log (/dati).</summary>
public string DataFolder { get; init; } = "/dati";
/// <summary>Library folder (/libreria).</summary>
public string LibraryFolder { get; init; } = "/libreria";
/// <summary>Import sources, read-only (/importa).</summary>
public string ImportFolder { get; init; } = "/importa";
/// <summary>FEBE_HOST: names the interface is reached with (comma separated). Empty: any name.</summary>
public IReadOnlyList<string> Hosts { get; init; } = [];
/// <summary>FEBE_PROXY_FIDATO=1: behind an HTTPS reverse proxy, X-Forwarded-Host counts for the Origin check.</summary>
public bool TrustForwardedHost { get; init; }
/// <summary>FEBE_SENZA_SANDBOX=1: Chromium with <c>--no-sandbox</c> (the compromise of S5, written in docs/docker.md).</summary>
public bool NoSandbox { get; init; }
/// <summary>FEBE_CHROMIUM: Chromium executable (default: Debian's chromium from PATH).</summary>
public string? ChromiumPath { get; init; }
/// <summary>FEBE_PORTA_DEBUG: the fixed DevTools port, on 127.0.0.1 only and never published (spec §6.1).</summary>
public int DebugPort { get; init; } = DefaultDebugPort;
/// <summary>FEBE_DISPLAY: the Xvfb display (:99).</summary>
public string Display { get; init; } = DefaultDisplay;
/// <summary>Size of the browser window, always the same (spec §6.1); Xvfb's screen has the same size.</summary>
public int WindowWidth { get; init; } = 1280;
public int WindowHeight { get; init; } = 900;
/// <summary>Development: the local test site (tools/Febe.SitoDiProva) instead of Instagram.</summary>
public Uri? TestSite { get; init; }
/// <summary>Development: the «CDN» of the test site (default: 127.0.0.2, site port + 1, as the tool starts it).</summary>
public Uri? TestCdn { get; init; }
/// <summary>Development, test site only: opens the site once at start-up so its session cookie exists, as after a login.</summary>
public bool TestSiteAutoLogin { get; init; }
/// <summary>Development: the first session comes after this delay instead of 2–10 minutes.</summary>
public TimeSpan? FirstSessionDelay { get; init; }
/// <summary>FEBE_INTERFACCIA: serve the interface from this folder (development).</summary>
public string? InterfaceFolder { get; init; }
/// <summary>Warnings found while reading the configuration (unknown time zone...), for the log.</summary>
public IReadOnlyList<string> Warnings { get; init; } = [];
/// <summary>The site the browser works on: Instagram, or the local test site in development.</summary>
public CollectionSite Site => TestSite is { } site
? CollectionSite.TestSite(site.Authority, (TestCdn ?? DefaultCdn(site)).Authority)
: CollectionSite.Instagram;
/// <summary>
/// The page «Accedi a Instagram» opens (PROTOCOLLO.md): Instagram's real login page, or a page of the test site,
/// whose first visit starts its session (it has no login form).
/// </summary>
public string LoginUrl => TestSite is { } site ? new Uri(site, "/benvenuto").AbsoluteUri : "https://www.instagram.com/accounts/login/";
/// <summary>The interface options of the Docker edition.</summary>
public FebeWebOptions WebOptions() => new()
{
Edition = FebeEdition.Docker,
Access = AccessMode.Password,
Password = string.IsNullOrEmpty(Password) ? null : Password,
AllowedHosts = AllowedHostList(),
TrustForwardedHost = TrustForwardedHost,
InterfaceFolder = InterfaceFolder,
};
/// <summary>
/// FEBE_HOST names with any port, plus the loopback names (the health check comes from inside the container).
/// Empty when FEBE_HOST is not set: any name, as documented for Docker (password and Origin protect it).
/// </summary>
public IReadOnlyList<string> AllowedHostList()
{
if (Hosts.Count == 0)
{
return [];
}
var list = new List<string>();
foreach (var host in Hosts.Concat(["127.0.0.1", "localhost", "[::1]"]))
{
list.Add(host);
list.Add(host + ":*");
}
return list.Distinct(StringComparer.OrdinalIgnoreCase).ToList();
}
/// <summary>
/// Reads the configuration. <paramref name="environment"/> gives environment variables (tests pass their own).
/// Returns false with an Italian <paramref name="problem"/> for a wrong command line.
/// </summary>
public static bool TryParse(string[] args, Func<string, string?> environment, out ServerOptions options, out string problem)
{
ArgumentNullException.ThrowIfNull(args);
ArgumentNullException.ThrowIfNull(environment);
options = new ServerOptions();
problem = string.Empty;
var warnings = new List<string>();
string? Env(string name) => environment(name) is { Length: > 0 } value ? value.Trim() : null;
bool Flag(string name) => Env(name) is { } value && value is "1" or "true" or "sì" or "si" or "yes";
var zoneId = Env("TZ") ?? DefaultZone;
var zone = FindZone(zoneId);
if (zone is null)
{
warnings.Add($"Fuso orario sconosciuto in TZ («{zoneId}»): uso {DefaultZone}.");
zoneId = DefaultZone;
zone = FindZone(DefaultZone) ?? TimeZoneInfo.Utc;
}
var port = FebeListen.DefaultPort;
if (Env("FEBE_PORTA") is { } portText && !TryPort(portText, out port))
{
problem = $"FEBE_PORTA non valida («{portText}»): un numero fra 1 e 65535.";
return false;
}
var debugPort = DefaultDebugPort;
if (Env("FEBE_PORTA_DEBUG") is { } debugText && (!TryPort(debugText, out debugPort) || debugPort < 1024))
{
problem = $"FEBE_PORTA_DEBUG non valida («{debugText}»): un numero fra 1024 e 65535.";
return false;
}
options = options with
{
Password = environment("FEBE_PASSWORD") is { Length: > 0 } password ? password : null,
Port = port,
ZoneId = zoneId,
Zone = zone,
Language = Env("LANG") ?? DefaultLanguage,
Hosts = SplitHosts(Env("FEBE_HOST")),
TrustForwardedHost = Flag("FEBE_PROXY_FIDATO"),
NoSandbox = Flag("FEBE_SENZA_SANDBOX"),
ChromiumPath = Env("FEBE_CHROMIUM"),
DebugPort = debugPort,
Display = Env("FEBE_DISPLAY") ?? DefaultDisplay,
InterfaceFolder = Env("FEBE_INTERFACCIA") is { } folder && Directory.Exists(folder) ? folder : null,
};
for (var i = 0; i < args.Length; i++)
{
var arg = args[i];
string? Next() => i + 1 < args.Length ? args[++i] : null;
switch (arg.ToLowerInvariant())
{
case "--dati":
options = options with { DataFolder = Next() ?? string.Empty };
break;
case "--libreria":
options = options with { LibraryFolder = Next() ?? string.Empty };
break;
case "--importa":
options = options with { ImportFolder = Next() ?? string.Empty };
break;
case "--porta":
{
var text = Next();
if (!TryPort(text, out var value))
{
problem = $"Porta non valida («{text}»): un numero fra 1 e 65535.";
return false;
}
options = options with { Port = value };
break;
}
case "--ascolta":
{
var text = Next();
if (!IPAddress.TryParse(text, out var address))
{
problem = $"Indirizzo non valido dopo --ascolta («{text}»), per esempio 127.0.0.1.";
return false;
}
options = options with { ListenAddress = address };
break;
}
case "--porta-debug":
{
var text = Next();
if (!TryPort(text, out var value) || value < 1024)
{
problem = $"Porta di debug non valida («{text}»): un numero fra 1024 e 65535.";
return false;
}
options = options with { DebugPort = value };
break;
}
case "--display":
options = options with { Display = Next() ?? string.Empty };
break;
case "--chromium":
options = options with { ChromiumPath = Next() };
break;
case "--senza-sandbox":
options = options with { NoSandbox = true };
break;
case "--sito-di-prova":
case "--cdn-di-prova":
{
var text = Next();
if (!TryLocalAddress(text, out var address))
{
problem = $"Indirizzo non valido dopo {arg} («{text}»): serve un indirizzo http di questo computer, per esempio http://127.0.0.1:8481.";
return false;
}
options = arg.Equals("--sito-di-prova", StringComparison.OrdinalIgnoreCase)
? options with { TestSite = address }
: options with { TestCdn = address };
break;
}
case "--accesso-di-prova":
options = options with { TestSiteAutoLogin = true };
break;
case "--prima-sessione":
{
var text = Next();
if (!int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var seconds) || seconds is < 1 or > 3600)
{
problem = $"Valore non valido dopo --prima-sessione («{text}»): secondi fra 1 e 3600.";
return false;
}
options = options with { FirstSessionDelay = TimeSpan.FromSeconds(seconds) };
break;
}
default:
problem = $"Opzione sconosciuta: {arg}.";
return false;
}
}
if (string.IsNullOrWhiteSpace(options.DataFolder) || string.IsNullOrWhiteSpace(options.LibraryFolder) || string.IsNullOrWhiteSpace(options.ImportFolder))
{
problem = "Dopo --dati, --libreria e --importa serve una cartella.";
return false;
}
if (options.TestSiteAutoLogin && options.TestSite is null)
{
problem = "--accesso-di-prova vale solo con --sito-di-prova: con Instagram l'accesso lo fa sempre Alberto, a mano.";
return false;
}
if (options.TestCdn is not null && options.TestSite is null)
{
problem = "--cdn-di-prova vale solo con --sito-di-prova.";
return false;
}
if (options.Display.Length < 2 || options.Display[0] != ':')
{
problem = $"Display non valido («{options.Display}»): si scrive come «:99».";
return false;
}
if (options.DebugPort == options.Port)
{
problem = "La porta di debug del browser deve essere diversa da quella dell'interfaccia.";
return false;
}
options = options with { Warnings = warnings };
return true;
}
/// <summary>The time zone named by TZ, or null when unknown.</summary>
public static TimeZoneInfo? FindZone(string id) =>
TimeZoneInfo.TryFindSystemTimeZoneById(id, out var zone) ? zone : null;
/// <summary>The environment of Chromium: LANG and TZ (defaults when unset), a home of its own, and no proxy (rule 2).</summary>
public IReadOnlyDictionary<string, string?> BrowserEnvironment(string home) => new Dictionary<string, string?>
{
["LANG"] = Language,
["TZ"] = ZoneId,
["HOME"] = home,
["LANGUAGE"] = null,
["LC_ALL"] = null,
["http_proxy"] = null,
["https_proxy"] = null,
["HTTP_PROXY"] = null,
["HTTPS_PROXY"] = null,
["ALL_PROXY"] = null,
["all_proxy"] = null,
["no_proxy"] = null,
["NO_PROXY"] = null,
};
/// <summary>How the browser is started (spec §6.1, §11).</summary>
public ChromiumLaunchOptions LaunchOptions(string home) => new()
{
NoSandbox = NoSandbox,
Environment = BrowserEnvironment(home),
SessionCookie = Site.SessionCookie,
SeedProfilePreferences = true,
};
private static Uri DefaultCdn(Uri site) => new UriBuilder(site) { Host = "127.0.0.2", Port = site.Port + 1, Path = "/" }.Uri;
private static IReadOnlyList<string> SplitHosts(string? value) => value is null
? []
: [.. value.Split([',', ' ', ';'], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).Select(h => h.ToLowerInvariant())];
private static bool TryPort(string? text, out int port) =>
int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out port) && port is >= 1 and <= 65535;
/// <summary>The test site must be on this computer: the switch can never point the browser elsewhere.</summary>
private static bool TryLocalAddress(string? text, out Uri address)
{
address = null!;
if (!Uri.TryCreate(text, UriKind.Absolute, out var uri) || uri.Scheme != Uri.UriSchemeHttp)
{
return false;
}
var local = uri.IsLoopback || (IPAddress.TryParse(uri.Host, out var ip) && IPAddress.IsLoopback(ip));
if (!local)
{
return false;
}
address = new Uri(uri.GetLeftPart(UriPartial.Authority) + "/");
return true;
}
}