Files
Febe/src/Febe.Browser/Hosting/ChromiumProcessHost.cs
T
Alby96andClaude Opus 5.5 c87768766c
verifica / controlli (push) Successful in 22s
verifica / prove (push) Successful in 16m46s
verifica / installatore (push) Successful in 4m43s
verifica / immagine (push) Successful in 21m2s
Sessione salvata cifrata, copiata a «Ho finito» (#36, S4)
Il client del sito ha bisogno della sessione del browser di Febe: ora la copia
c'è, cifrata e dietro un interruttore, senza cambiare nulla di predefinito.

- Opzione «raccolta» (pagine predefinita, richieste): solo con «richieste» e
  almeno un'operazione configurata si costruiscono sessione salvata, client del
  sito e copia. Con Instagram nulla cambia: le dieci operazioni restano non
  configurate (mancano __spin_*, __req, __s, __dyn, __csr e altri).
- Cookie con dominio, percorso, solo-host, Secure, HttpOnly e scadenza, mandati
  solo dove il browser li manderebbe (RFC 6265).
- Sezione «page» del catalogo: dove la pagina tiene ogni valore; nuovi campi rev,
  hs, hsi, dpr, ccg, comet_req, entry_nonce. Il caricatore rifiuta
  un'operazione configurata con un valore di sessione senza fonte nella pagina.
- Dati/sessione/sessione.json: DPAPI su Windows, AES-256-GCM in Docker (chiave
  da FEBE_CHIAVE_SESSIONE o chiave.bin), scrittura atomica, file illeggibile =
  nessuna sessione. «Scollega» la cancella; chiave.bin resta.
- Copia a «Ho finito» con Network.getCookies e una sola Runtime.evaluate in sola
  lettura, solo da una pagina del sito e finché dura il permesso di guida.
- FEBE_PASSWORD e FEBE_CHIAVE_SESSIONE non passano a Chromium, Xvfb, ffmpeg.
- Sito di prova: csrftoken, cookie limitato a /api/, registro di moduli suo.
- Revisione su tre lenti: 11 punti confermati, tutti corretti.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 16:43:43 +01:00

411 lines
16 KiB
C#

using System.Diagnostics;
using Febe.Browser.Cdp;
using Febe.Browser.Diagnostics;
using Febe.Core.Abstractions;
using Febe.Core.Security;
namespace Febe.Browser.Hosting;
/// <summary>
/// The browser host of the Docker version (spec §5, §6.1, §11): the distribution's Chromium, started as a normal
/// windowed browser on a display (Xvfb), driven through its fixed DevTools port on 127.0.0.1.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item>Supervised: if Chromium exits it is restarted with backoff and <see cref="Cdp"/> reconnects by itself
/// (subscriptions survive; see <see cref="ICdpConnectionEvents.Reconnected"/>).</item>
/// <item>The DevTools port must listen on loopback only, or the start is aborted.</item>
/// <item>Stopping sends SIGINT first (not SIGTERM: see <see cref="ProcessSignals.SigInt"/>), so the profile and the
/// session are written to disk; the process tree is killed only if it does not exit within the grace period.</item>
/// </list>
/// </remarks>
public sealed class ChromiumProcessHost : IBrowserHost
{
private static readonly TimeSpan StopGrace = TimeSpan.FromSeconds(10);
private readonly ChromiumLaunchOptions _launch;
private readonly IClock _clock;
private readonly IBrowserLog _log;
private readonly ReconnectingCdpSession _session = new();
private readonly SemaphoreSlim _connectLock = new(1, 1);
private readonly SemaphoreSlim _restartLock = new(1, 1);
// Not disposed on purpose: background reconnection may still read its token; it holds no timer or handle.
private readonly CancellationTokenSource _lifetime = new();
private SupervisedProcess? _supervisor;
private CdpClient? _client;
private BrowserOptions? _options;
private int _stopping;
private int _restarting;
public ChromiumProcessHost(ChromiumLaunchOptions? launch = null, IClock? clock = null, IBrowserLog? log = null)
{
_launch = launch ?? new ChromiumLaunchOptions();
_clock = clock ?? new SystemClock();
_log = log ?? NullBrowserLog.Instance;
}
/// <summary>The page session. Stable across restarts; commands fail with <see cref="BrowserUnavailableException"/> while the browser is down.</summary>
public ICdpSession Cdp => _session;
/// <summary>Raised when the connection was replaced after a restart.</summary>
public ICdpConnectionEvents Connection => _session;
/// <summary>Leases taken while Alberto uses the browser (remote view, connection page).</summary>
public UserDrivingGate UserDriving { get; } = new();
public bool UserIsDriving => UserDriving.IsDriving;
public BrowserOptions? Options => _options;
public SupervisedState State => _supervisor?.State ?? SupervisedState.Stopped;
public int? ProcessId => _supervisor?.ProcessId;
public int Restarts => _supervisor?.Restarts ?? 0;
public event EventHandler<SupervisedState>? StateChanged;
/// <summary>True while a page connection is attached (commands can be sent).</summary>
public bool IsAttached => _session.IsAttached;
public async Task StartAsync(BrowserOptions options, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(options);
if (_supervisor is not null)
{
throw new InvalidOperationException("Il browser è già avviato.");
}
await StartCoreAsync(options, ct).ConfigureAwait(false);
}
/// <summary>
/// Stops the browser (SIGINT, so the profile is written to disk), runs <paramref name="whileStopped"/> — «Scollega»
/// deletes the profile there — and starts it again with the same options. <see cref="Cdp"/> stays the same object:
/// subscriptions survive and <see cref="ICdpConnectionEvents.Reconnected"/> is raised once the new browser is
/// connected.
/// </summary>
public async Task RestartAsync(Action? whileStopped, CancellationToken ct)
{
var options = _options ?? throw new InvalidOperationException("Il browser non è mai partito.");
if (Volatile.Read(ref _stopping) == 1)
{
throw new InvalidOperationException("Il browser si sta fermando.");
}
await _restartLock.WaitAsync(ct).ConfigureAwait(false);
Interlocked.Exchange(ref _restarting, 1);
try
{
if (_supervisor is { } current)
{
await DropClientAsync().ConfigureAwait(false);
await current.StopAsync(StopGrace).ConfigureAwait(false);
_supervisor = null;
_log.Info("Chromium è fermo per un nuovo avvio.");
}
whileStopped?.Invoke();
await StartCoreAsync(options, ct).ConfigureAwait(false);
}
finally
{
Interlocked.Exchange(ref _restarting, 0);
_restartLock.Release();
}
}
private async Task StartCoreAsync(BrowserOptions options, CancellationToken ct)
{
var executable = ChromiumCommandLine.FindExecutable(options.ExecutablePath)
?? throw new FileNotFoundException("Chromium non è installato o non si trova (si può indicare con FEBE_CHROMIUM).");
var arguments = ChromiumCommandLine.Build(options, _launch);
if (LoopbackPortCheck.IsInUse(options.DebugPort))
{
throw new InvalidOperationException($"La porta di debug {options.DebugPort} è già occupata da un altro programma.");
}
ChromiumProfile.Prepare(options.ProfileDirectory, _launch.SeedProfilePreferences);
_options = options;
var supervisor = new SupervisedProcess(
"Chromium",
() => BuildStartInfo(executable, arguments, options),
WaitReadyAndConnectAsync,
_clock,
_log,
_launch.Restart,
// Measured locally: on SIGTERM Chromium exits in ~35 ms and usually loses cookies set in the last 30 s;
// on SIGINT it takes ~100 ms and writes them. The session must survive a restart (S3).
ProcessSignals.SigInt);
supervisor.ExitedUnexpectedly += (_, _) => _ = DropClientAsync();
supervisor.StateChanged += (_, state) => StateChanged?.Invoke(this, state);
_supervisor = supervisor;
try
{
await supervisor.StartAsync(ct).ConfigureAwait(false);
}
catch
{
_supervisor = null;
throw;
}
_log.Info("Chromium è in funzione.");
}
/// <summary>Windows only: the Docker browser is seen through the remote view.</summary>
public Task ShowToUserAsync() => Task.CompletedTask;
public Task HideFromUserAsync() => Task.CompletedTask;
/// <summary>Puts the browser at rest on the blank page (spec §6.1).</summary>
public Task<NavigationResult> RestAsync(CancellationToken ct = default) => _session.RestAsync(ct);
/// <summary>Whether the session cookie exists. Never reads its value.</summary>
public Task<bool> HasSessionCookieAsync(CancellationToken ct = default) =>
SessionCookieProbe.HasSessionCookieAsync(_session, _launch.SessionCookie, ct);
/// <summary>Kills the browser as if it had crashed (tests and «riavvia il browser»). The supervisor restarts it.</summary>
public void KillForRestart() => _supervisor?.KillCurrent();
public async Task StopAsync()
{
if (Interlocked.Exchange(ref _stopping, 1) == 1)
{
return;
}
await _lifetime.CancelAsync().ConfigureAwait(false);
// A restart in progress («Scollega») finishes first, so that no browser is left running behind the stop.
await _restartLock.WaitAsync().ConfigureAwait(false);
try
{
await DropClientAsync().ConfigureAwait(false);
if (_supervisor is { } supervisor)
{
await supervisor.StopAsync(StopGrace).ConfigureAwait(false);
}
}
finally
{
_restartLock.Release();
}
_log.Info("Chromium è fermo.");
}
/// <summary>Same as <see cref="StopAsync"/>. A stopped host cannot be started again: create a new one.</summary>
public ValueTask DisposeAsync() => new(StopAsync());
/// <summary>
/// The start of Chromium (or Edge): its arguments, the display, the variables of <see cref="ChromiumLaunchOptions.Environment"/>,
/// and never Febe's secrets (<see cref="ChildProcessEnvironment"/>), whatever the parent or the options hold.
/// </summary>
internal ProcessStartInfo BuildStartInfo(string executable, IReadOnlyList<string> arguments, BrowserOptions options)
{
var info = new ProcessStartInfo(executable);
foreach (var argument in arguments)
{
info.ArgumentList.Add(argument);
}
if (!string.IsNullOrEmpty(options.Display))
{
info.Environment["DISPLAY"] = options.Display;
}
foreach (var (name, value) in _launch.Environment)
{
if (value is null)
{
info.Environment.Remove(name);
}
else
{
info.Environment[name] = value;
}
}
return info.WithoutSecrets();
}
private async Task WaitReadyAndConnectAsync(Process process, CancellationToken ct)
{
// First of all, as close to the start as possible: the processes the browser opens afterwards follow it.
_launch.ProcessStarted?.Invoke(process);
var options = _options ?? throw new InvalidOperationException("Opzioni mancanti.");
var port = options.DebugPort;
var deadline = _clock.Now + _launch.StartupTimeout;
while (!await CdpTargetDiscovery.IsAvailableAsync(port, ct).ConfigureAwait(false))
{
if (process.HasExited)
{
throw new InvalidOperationException($"Chromium si è chiuso all'avvio (codice {process.ExitCode}). {_supervisor?.StderrTail()}".TrimEnd());
}
if (_clock.Now >= deadline)
{
throw new TimeoutException($"Chromium non ha aperto la porta di debug entro {_launch.StartupTimeout.TotalSeconds:0} s.");
}
await _clock.Delay(TimeSpan.FromMilliseconds(100), ct).ConfigureAwait(false);
}
if (!LoopbackPortCheck.IsLoopbackOnly(port, out var listeners))
{
throw new InvalidOperationException(
$"La porta di debug {port} non è limitata a 127.0.0.1 ({listeners.Count} punti di ascolto): avvio annullato (specifica §6.1).");
}
await ConnectAsync(
port,
deadline,
() => process.HasExited ? $"Chromium si è chiuso all'avvio (codice {process.ExitCode}). {_supervisor?.StderrTail()}".TrimEnd() : null,
ct).ConfigureAwait(false);
}
/// <summary>
/// Connects to the first page target. The first tab may appear a while after the port opens on a loaded machine:
/// the wait shares the start deadline, and ends at once when <paramref name="gone"/> says the process is no longer the
/// one to connect to (it exited, or the supervisor replaced it): nobody waits on the connect lock for a dead browser.
/// </summary>
private async Task ConnectAsync(int port, DateTimeOffset deadline, Func<string?> gone, CancellationToken ct)
{
await _connectLock.WaitAsync(ct).ConfigureAwait(false);
try
{
CdpTarget? page;
while ((page = await TryFindPageAsync(port, ct).ConfigureAwait(false)) is null)
{
if (gone() is { } reason)
{
throw new InvalidOperationException(reason);
}
if (_clock.Now >= deadline)
{
throw new InvalidOperationException("Chromium non ha nessuna scheda aperta.");
}
await _clock.Delay(TimeSpan.FromMilliseconds(100), ct).ConfigureAwait(false);
}
var client = await CdpClient.ConnectAsync(page.WebSocketDebuggerUrl, _log, null, ct).ConfigureAwait(false);
try
{
await client.SendAsync("Page.enable", null, ct).ConfigureAwait(false);
}
catch
{
await client.DisposeAsync().ConfigureAwait(false);
throw;
}
client.Disconnected += OnClientDisconnected;
var previous = Interlocked.Exchange(ref _client, client);
_session.Attach(client);
if (previous is not null)
{
previous.Disconnected -= OnClientDisconnected;
await previous.DisposeAsync().ConfigureAwait(false);
}
}
finally
{
_connectLock.Release();
}
}
/// <summary>The page target, or null when there is none yet or the endpoint did not answer this time.</summary>
private static async Task<CdpTarget?> TryFindPageAsync(int port, CancellationToken ct)
{
try
{
return await CdpTargetDiscovery.FindPageAsync(port, ct).ConfigureAwait(false);
}
catch (HttpRequestException)
{
return null;
}
catch (TaskCanceledException) when (!ct.IsCancellationRequested)
{
return null; // a slow answer of /json/list, not a missing one
}
}
private void OnClientDisconnected(object? sender, Exception? reason)
{
if (Volatile.Read(ref _stopping) == 1 || Volatile.Read(ref _restarting) == 1 || !ReferenceEquals(sender, Volatile.Read(ref _client)))
{
return;
}
_session.Detach();
_ = Task.Run(ReconnectAfterDropAsync);
}
/// <summary>
/// The page connection dropped. If the process is gone the supervisor restarts it (and reconnects);
/// if it is alive, reconnect to its page, or restart it when that fails.
/// </summary>
private async Task ReconnectAfterDropAsync()
{
var ct = _lifetime.Token;
try
{
await _clock.Delay(TimeSpan.FromMilliseconds(500), ct).ConfigureAwait(false);
if (_supervisor is not { } supervisor || supervisor.State != SupervisedState.Running || supervisor.ProcessId is null || _options is null)
{
return;
}
// The process that dropped the connection: if it exits or the supervisor restarts it, stop at once and leave
// the connect lock to the restart, which connects by itself.
var processId = supervisor.ProcessId;
string? Gone() => supervisor.State != SupervisedState.Running || supervisor.ProcessId != processId
? "Chromium è stato riavviato o si è chiuso durante il ricollegamento."
: null;
var deadline = _clock.Now + _launch.StartupTimeout;
for (var attempt = 0; attempt < 3 && Gone() is null; attempt++)
{
try
{
await ConnectAsync(_options.DebugPort, deadline, Gone, ct).ConfigureAwait(false);
_log.Info("Collegamento con Chromium ripristinato.");
return;
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
await _clock.Delay(TimeSpan.FromSeconds(1), ct).ConfigureAwait(false);
}
}
if (Gone() is not null)
{
return;
}
_log.Warn("Collegamento con Chromium perso: riavvio del browser.");
supervisor.KillCurrent();
}
catch (OperationCanceledException)
{
}
}
private async Task DropClientAsync()
{
_session.Detach();
var client = Interlocked.Exchange(ref _client, null);
if (client is not null)
{
client.Disconnected -= OnClientDisconnected;
await client.DisposeAsync().ConfigureAwait(false);
}
}
}