Sessione salvata cifrata, copiata a «Ho finito» (#36, S4)
verifica / controlli (push) Successful in 22s
verifica / prove (push) Successful in 16m46s
verifica / installatore (push) Successful in 4m43s
verifica / immagine (push) Successful in 21m2s

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>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-17 16:43:43 +01:00
1 parent 3046b2da47
commit c87768766c
69 files changed
+5936 -415

No files matched your search

+131 -1
View File
@@ -1,6 +1,7 @@
using System.Globalization;
using Febe.Browser.Cdp;
using Febe.Browser.Hosting;
using Febe.Browser.Session;
using Febe.Core.Abstractions;
using Febe.Core.Collection;
using Febe.Core.Domain;
@@ -62,6 +63,8 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
private readonly string _loginUrl;
private readonly string _homeUrl;
private readonly SessionCookieOptions _cookie;
private readonly ISessionCopier? _copier;
private readonly Func<CancellationToken, Task>? _forgetSavedSession;
private readonly SemaphoreSlim _commands = new(1, 1);
private readonly Lock _gate = new();
private EngineHost? _engine;
@@ -80,7 +83,14 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
/// <param name="loginUrl">The page «Accedi a Instagram» opens.</param>
/// <param name="homeUrl">The site's home, the start page once connected.</param>
/// <param name="cookie">The session cookie looked for (its name only).</param>
public BrowserConnectionService(IFebeBrowser browser, IFebeStorage storage, BrowserUseTracker tracker, IClock clock, FebeLog log, string loginUrl, string homeUrl, SessionCookieOptions cookie)
/// <param name="copier">
/// The copy of the session into the saved session at «Ho finito» (issue #36, S4); null when the composition keeps no
/// saved session (option «raccolta» on «pagine», or no configured operation): «Ho finito» then reads names only.
/// </param>
/// <param name="forgetSavedSession">
/// What «Scollega» does to the saved session (deletes it, memory and file); null when there is none to delete.
/// </param>
public BrowserConnectionService(IFebeBrowser browser, IFebeStorage storage, BrowserUseTracker tracker, IClock clock, FebeLog log, string loginUrl, string homeUrl, SessionCookieOptions cookie, ISessionCopier? copier = null, Func<CancellationToken, Task>? forgetSavedSession = null)
{
_browser = browser ?? throw new ArgumentNullException(nameof(browser));
_storage = storage ?? throw new ArgumentNullException(nameof(storage));
@@ -90,6 +100,8 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
_loginUrl = loginUrl ?? throw new ArgumentNullException(nameof(loginUrl));
_homeUrl = homeUrl ?? throw new ArgumentNullException(nameof(homeUrl));
_cookie = cookie ?? throw new ArgumentNullException(nameof(cookie));
_copier = copier;
_forgetSavedSession = forgetSavedSession;
}
/// <summary>
@@ -316,6 +328,9 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
var connected = await CheckAsync(force: true, mayReport: false, ct).ConfigureAwait(false) == true;
_tracker.MarkUsed(_clock.Now);
var first = connected && await MarkConnectedAsync(ct).ConfigureAwait(false);
// The copy for the site client (S4): while the page still holds the session and is still Alberto's.
var copy = connected && _copier is not null ? await CopySessionAsync(ct).ConfigureAwait(false) : null;
await RestIfAlbertosAsync().ConfigureAwait(false);
await HideQuietlyAsync().ConfigureAwait(false);
ReleaseLease();
@@ -339,6 +354,11 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
message = "Collegato a Instagram. Febe riprende da solo alla prossima sessione.";
}
if (copy is not null)
{
message += " " + CopyMessage(copy);
}
_log.Info("collegamento", connected ? "«Ho finito»: sessione presente nel browser." : "«Ho finito»: sessione assente nel browser.");
return new FinishResult(connected, message);
}
@@ -385,6 +405,9 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
// Windows: the browser window goes out of view and WebView2 closes before its folder is deleted.
await HideQuietlyAsync().ConfigureAwait(false);
Exception? failure = null;
// The saved session first (S4): no request of the site client may use it any more, whatever the profile does.
var savedSessionFailure = await ForgetSavedSessionAsync().ConfigureAwait(false);
try
{
await _browser.RestartWithEmptyProfileAsync(ct).ConfigureAwait(false);
@@ -412,12 +435,23 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
await engine.StartAsync(CancellationToken.None).ConfigureAwait(false);
}
if (savedSessionFailure is not null)
{
// Never the path or the message of the file system: the kind of error only.
_log.Warn("collegamento", $"«Scollega»: la sessione salvata non si è potuta cancellare dal disco ({savedSessionFailure.GetType().Name}): Febe non la usa più finché resta acceso, ma il file resta e al prossimo avvio con «richieste» la rileggerebbe.");
}
if (failure is not null)
{
_log.Warn("collegamento", "«Scollega»: il profilo del browser non si è potuto cancellare del tutto.", failure);
throw new BadRequestException("«Scollega» non è riuscito del tutto: " + failure.Message);
}
if (savedSessionFailure is not null)
{
throw new BadRequestException("«Scollega» non è riuscito del tutto: la sessione salvata per le richieste non si è potuta cancellare dal disco. Febe non la usa più finché resta acceso, ma al prossimo avvio con la raccolta «richieste» la rileggerebbe: riprova «Scollega» e, se resta, cancella a mano la cartella «sessione» nella cartella dei dati prima di riavviare Febe.");
}
_log.Info("collegamento", "«Scollega»: motore fermo, profilo del browser cancellato, browser ripartito vuoto.");
}
finally
@@ -698,6 +732,102 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
: $"Alberto usa il browser: {what} non aperta (errore di rete del browser).");
}
/// <summary>
/// The copy at «Ho finito» (issue #36, S4, §6.0): only while Alberto's own lease («Accedi», «Usa il browser») still
/// holds — after it ended the page is the engine's, and nothing is read from it (rule 7). A hold of the driving gate
/// keeps the lease from ending by itself meanwhile, and the page turn keeps a step of the profile search off the
/// page; a lease that ended all the same before the copy is saved throws the copy away.
/// </summary>
private async Task<SessionCopyOutcome> CopySessionAsync(CancellationToken ct)
{
IDisposable? lease;
lock (_gate)
{
lease = _lease;
}
if (lease is null || !_browser.UserIsDriving)
{
_log.Info("collegamento", "«Ho finito»: sessione non copiata, il browser era già tornato al motore.");
return new SessionCopyOutcome(SessionCopyStatus.Discarded, null, 0, 0, 0);
}
var hold = _browser.UserDriving.Begin();
try
{
using var turn = await TakePageAsync(ct).ConfigureAwait(false);
if (_engine is not null && turn is null)
{
_log.Info("collegamento", "«Ho finito»: sessione non copiata, la pagina era occupata dalla ricerca dei profili.");
return new SessionCopyOutcome(SessionCopyStatus.Refused, CaptureRefusal.BrowserError, 0, 0, 0);
}
bool StillAlbertos()
{
lock (_gate)
{
return ReferenceEquals(_lease, lease);
}
}
return await _copier!.CopyAsync(StillAlbertos, ct).ConfigureAwait(false);
}
finally
{
hold.Dispose();
}
}
/// <summary>
/// The clause of the «Ho finito» message about the copy, in Italian (counts only). It says what the code does: a
/// value a configured operation needs and the page did not give stops that request as a disconnection (§6.0), never
/// a way back to the browser; and after a refusal a new «Ho finito» needs the browser opened again, because
/// «Ho finito» always ends the lease.
/// </summary>
internal static string CopyMessage(SessionCopyOutcome copy)
{
ArgumentNullException.ThrowIfNull(copy);
const string Again = "Riapri il browser dalla pagina Collegamento («Usa il browser» o «Pagina iniziale») e premi di nuovo «Ho finito» sulla tua pagina iniziale.";
var missing = copy.MissingValues + copy.MissingDocIds;
var missingClause = missing == 0
? string.Empty
: string.Create(
CultureInfo.InvariantCulture,
$" Alla pagina però mancavano {missing} valori che servono alle richieste: la copia ha comunque sostituito quella salvata prima, e le richieste che li usano non partono. Alla prima Febe si ferma come disconnessione e chiede un nuovo accesso. {Again}");
return copy.Status switch
{
SessionCopyStatus.Saved => "Sessione copiata per le richieste di Febe." + missingClause,
SessionCopyStatus.SavedInMemoryOnly =>
"Sessione copiata per le richieste di Febe, ma non ancora scritta su disco: Febe riprova alla prossima scrittura." + missingClause,
SessionCopyStatus.Discarded =>
"La sessione per le richieste non è stata copiata: nel frattempo il browser era tornato al motore. Rifai l'accesso dalla pagina Collegamento e premi «Ho finito» sulla tua pagina iniziale.",
_ when copy.Refusal is CaptureRefusal.NotOnSite or CaptureRefusal.CheckpointPage =>
$"La sessione per le richieste non è stata copiata: {BrowserSessionCopier.Reason(copy.Refusal.Value)}. La sessione salvata resta com'era. {Again}",
_ =>
$"La sessione per le richieste non è stata copiata: {BrowserSessionCopier.Reason(copy.Refusal ?? CaptureRefusal.BrowserError)}. La sessione salvata resta com'era. {Again}",
};
}
/// <summary>«Scollega» deletes the saved session (memory first, then the file); returns the error of the disk, if any.</summary>
private async Task<Exception?> ForgetSavedSessionAsync()
{
if (_forgetSavedSession is null)
{
return null;
}
try
{
// Not cancellable: «Scollega» must not stop halfway because the page that asked it went away.
await _forgetSavedSession(CancellationToken.None).ConfigureAwait(false);
return null;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
return ex;
}
}
/// <summary>The empty rest page (or no document at all): never what Alberto should be shown.</summary>
private static bool IsRest(string? url) => url is "" or CdpPageExtensions.RestUrl;