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;
+52
View File
@@ -0,0 +1,52 @@
namespace Febe.App;
/// <summary>
/// How the engine's recipes reach the site (issue #36, S4): by the pages of the browser, as always, or by the site
/// client's requests with the session saved at «Ho finito». <see cref="Pages"/> is the default and changes nothing;
/// <see cref="Requests"/> takes effect only when <c>richieste.&lt;sito&gt;.json</c> has at least one configured operation
/// (Instagram has none in S4, so with Instagram it changes nothing either). Option «raccolta»: <c>--raccolta</c> and
/// <c>FEBE_RACCOLTA</c> in Docker, <c>--raccolta</c> on Windows.
/// </summary>
public enum CollectionRoute
{
/// <summary>«pagine»: every recipe with the browser; no saved session, no site client.</summary>
Pages,
/// <summary>«richieste»: the saved session and the site client for the configured operations.</summary>
Requests,
}
/// <summary>Italian names of <see cref="CollectionRoute"/>, for the command line, the environment and the log.</summary>
public static class CollectionRouteNames
{
/// <summary>The option on the command line of both shells.</summary>
public const string Option = "--raccolta";
/// <summary>The environment variable of the Docker container.</summary>
public const string EnvironmentVariable = "FEBE_RACCOLTA";
/// <summary>The Italian name: «pagine» or «richieste».</summary>
public static string Name(CollectionRoute route) => route == CollectionRoute.Requests ? "richieste" : "pagine";
/// <summary>Reads «pagine» or «richieste» (any case, spaces around ignored).</summary>
public static bool TryParse(string? text, out CollectionRoute route)
{
switch (text?.Trim().ToLowerInvariant())
{
case "pagine":
route = CollectionRoute.Pages;
return true;
case "richieste":
route = CollectionRoute.Requests;
return true;
default:
route = CollectionRoute.Pages;
return false;
}
}
/// <summary>The Italian problem for a wrong value after <paramref name="source"/> (the option or the variable).</summary>
public static string Problem(string source, string? text) => text is null
? $"Dopo {source} serve pagine o richieste."
: $"Valore non valido per {source} («{text}»): pagine oppure richieste.";
}
+166 -7
View File
@@ -1,15 +1,19 @@
using System.Globalization;
using System.Security.Cryptography;
using Febe.Browser.Recipes;
using Febe.Browser.Session;
using Febe.Core.Abstractions;
using Febe.Core.Alerts;
using Febe.Core.Collection;
using Febe.Core.Collection.Diagnostics;
using Febe.Core.Collection.Downloads;
using Febe.Core.Collection.Requests;
using Febe.Core.Collection.Search;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Core.Import;
using Febe.Core.Library;
using Febe.Core.Security;
using Febe.Core.Storage;
using Febe.Data;
using Febe.Web;
@@ -46,6 +50,8 @@ public sealed class FebeApp : IAsyncDisposable
private readonly TaskCompletionSource _running = new(TaskCreationOptions.RunContinuationsAsynchronously);
private TelegramClient? _telegram;
private string? _temporaryFolder;
private RequestCatalog? _requestCatalog;
private ISessionCopier? _copier;
private int _disposed;
private FebeApp(FebeAppOptions options, IFebePlatform platform, FebeLog log, IClock clock, IReadOnlyList<ConfigurationProblem> problems)
@@ -83,6 +89,15 @@ public sealed class FebeApp : IAsyncDisposable
public BrowserConnectionService? Connection { get; private set; }
/// <summary>
/// The saved session of the site client (issue #36, S4, §6.0, §13.2): built only with the option «raccolta» on
/// «richieste» and a catalog with configured operations; null otherwise (always with Instagram in S4).
/// </summary>
public ISavedSiteSession? SavedSession { get; private set; }
/// <summary>The site client the recipes use (same conditions as <see cref="SavedSession"/>); null when every recipe goes by the browser.</summary>
public HttpSiteRequester? SiteRequester { get; private set; }
public EngineHost? Engine { get; private set; }
public CollectionPipeline? Pipeline { get; private set; }
@@ -249,7 +264,18 @@ public sealed class FebeApp : IAsyncDisposable
var context = new FebePlatformContext(o, data, Database, Clock, Log, Tracker, ct => Connection?.OpenStartPageAsync(ct) ?? Task.CompletedTask);
var browser = await _platform.CreateBrowserAsync(context, ct).ConfigureAwait(false);
Browser = browser;
var connection = new BrowserConnectionService(browser, Database, Tracker, Clock, Log, o.LoginUrl, HomeUrl(o.Site.BaseUrl), o.Site.SessionCookie);
PrepareSavedSession(context, browser);
var savedSession = SavedSession;
var sessionFile = data.SessionFile;
Func<CancellationToken, Task> forget = savedSession is not null
? savedSession.DeleteAsync
: _ =>
{
// Without a saved session in this start («pagine»): a file an earlier start with «richieste» left goes too.
OwnerOnlyFiles.DeleteWithLeftovers(sessionFile);
return Task.CompletedTask;
};
var connection = new BrowserConnectionService(browser, Database, Tracker, Clock, Log, o.LoginUrl, HomeUrl(o.Site.BaseUrl), o.Site.SessionCookie, _copier, forget);
Connection = connection;
var engineOptions = o.FirstSessionDelay is { } delay
? EngineOptions.Default with { StartupDelayMin = delay, StartupDelayMax = delay }
@@ -436,7 +462,9 @@ public sealed class FebeApp : IAsyncDisposable
SearchOptions = search.Options,
SearchPhotos = search.Photos,
// Requests: S4 (#36). Until then every recipe goes by the browser.
// Requests (#36, S4): only with «raccolta» on «richieste» and configured operations; otherwise every
// recipe goes by the browser, as before.
Requests = CreateSiteRequests(),
},
ct).ConfigureAwait(false);
runner.Target = Pipeline.Runner;
@@ -465,7 +493,7 @@ public sealed class FebeApp : IAsyncDisposable
// With the test site's automatic login the first look reports nothing: the session it may not find yet is
// the one the login below opens (issue #52), not a disconnection.
await Connection!.RefreshAsync(ct, mayReport: !o.TestSiteAutoLogin).ConfigureAwait(false);
if (o.TestSiteAutoLogin && Connection.IsConnected != true)
if (o.TestSiteAutoLogin && (Connection.IsConnected != true || (SavedSession is not null && SavedSession.Read() is null)))
{
await TestSiteLoginAsync(ct).ConfigureAwait(false);
}
@@ -497,7 +525,7 @@ public sealed class FebeApp : IAsyncDisposable
{
try
{
var configuration = CollectionConfiguration.Describe(_options.Site.Name, pipeline.Vocabulary, pipeline.SiteMap);
var configuration = CollectionConfiguration.Describe(_options.Site.Name, pipeline.Vocabulary, pipeline.SiteMap, SiteRequester is not null ? _requestCatalog : null);
foreach (var line in configuration.Lines)
{
Log.Info("raccolta", line);
@@ -520,19 +548,150 @@ public sealed class FebeApp : IAsyncDisposable
}
}
/// <summary>
/// The gate of S4 (issue #36, decision of 17 November 2026): the saved session, its copy at «Ho finito» and the site
/// client exist only with the option «raccolta» on «richieste» AND a catalog of the site with at least one
/// configured operation. With «pagine» (the default) nothing is built, and one line of the log says so (§6.0: the
/// log says which route Febe took); with Instagram (no operation configured in S4) nothing is built either: no cookie
/// value is read, no module of the page.
/// </summary>
private void PrepareSavedSession(FebePlatformContext context, IFebeBrowser browser)
{
var o = _options;
if (o.Collection != CollectionRoute.Requests)
{
Log.Info("raccolta", "Raccolta «pagine»: tutte le ricette con il browser (nessuna sessione salvata, nessun client del sito).");
return;
}
var catalog = LoadRequestCatalog(context.Data);
if (catalog is null || !catalog.Configured.Any())
{
Log.Info("raccolta", $"Raccolta «richieste»: nessuna operazione configurata in richieste.{o.Site.Name}.json, tutte le ricette restano al browser (nessuna sessione salvata, nessun client del sito).");
return;
}
try
{
var protector = _platform.CreateSessionProtector(context);
var saved = new FileSiteSession(context.Data.SessionFile, protector, message => Log.Info("sessione", message));
var rules = LoadSignalRules(context.Data);
_copier = new BrowserSessionCopier(browser.Cdp, SessionCapturePlan.For(o.Site, catalog, rules), saved, Clock, message => Log.Info("sessione", message));
_requestCatalog = catalog;
SavedSession = saved;
Log.Info("raccolta", $"Raccolta «richieste»: {catalog.Configured.Count().ToString(CultureInfo.InvariantCulture)} operazioni configurate in {Path.GetFileName(catalog.Source)}; la sessione si copia a «Ho finito».");
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or CryptographicException or PlatformNotSupportedException)
{
// Never a reason not to collect: the browser does every recipe, as with «pagine». The kind of error only.
Log.Error("raccolta", $"Raccolta «richieste» non attivata: la cifratura della sessione salvata non è pronta ({ex.GetType().Name}). Tutte le ricette restano al browser.");
}
}
/// <summary>The catalog of the site: the copy in the Data folder, or the embedded file when there is none or it is not valid.</summary>
private RequestCatalog? LoadRequestCatalog(DataFolderLayout data)
{
var name = $"richieste.{_options.Site.Name}.json";
try
{
return RequestCatalog.LoadOrEmbedded(Path.Combine(data.Root, name), name);
}
catch (InvalidDataException ex)
{
Log.Warn("raccolta", $"{name} nella cartella dei dati non è valido: uso quello di Febe. {ex.Message}");
}
try
{
return RequestCatalog.LoadEmbedded(name);
}
catch (Exception ex) when (ex is InvalidDataException or FileNotFoundException)
{
Log.Warn("raccolta", $"Nessun catalogo delle richieste per il sito «{_options.Site.Name}».");
return null;
}
}
/// <summary>The stop rules of the site as the pipeline loads them: their login and verification paths are pages where no copy is made.</summary>
private SignalRules? LoadSignalRules(DataFolderLayout data)
{
var file = Path.Combine(data.Root, _options.Site.SignalsFile);
try
{
return File.Exists(file) ? SignalRules.Load(file) : SignalRules.LoadEmbedded(_options.Site.SignalsFile);
}
catch (InvalidDataException)
{
return SignalRules.LoadEmbedded(_options.Site.SignalsFile);
}
}
/// <summary>
/// The site client of the recipes, over the saved session (issue #36, S4): only when <see cref="PrepareSavedSession"/>
/// built one. Instagram's options for Instagram, the test site's for the test site; any other site gets none.
/// </summary>
private SiteRequestOptions? CreateSiteRequests()
{
if (SavedSession is not { } session || _requestCatalog is not { } catalog)
{
return null;
}
var o = _options;
HttpSiteRequesterOptions? options = catalog.Site switch
{
"instagram" => HttpSiteRequesterOptions.Instagram(),
"prova" => HttpSiteRequesterOptions.TestSite(new Uri(o.Site.BaseUrl.TrimEnd('/') + "/"), o.Site.SessionCookie.CookieName),
_ => null,
};
if (options is null)
{
Log.Warn("raccolta", $"Client del sito non costruito: il sito «{catalog.Site}» non ha opzioni del client. Tutte le ricette restano al browser.");
return null;
}
try
{
var requester = new HttpSiteRequester(catalog, session, options, Clock, line => Log.Info("client", line));
DisposeOnStop(requester);
SiteRequester = requester;
return new SiteRequestOptions(requester, catalog);
}
catch (Exception ex) when (ex is InvalidOperationException or ArgumentException)
{
// The messages of the client name a variable or an option, never a value of the session.
Log.Warn("raccolta", "Client del sito non costruito: " + ex.Message + " Tutte le ricette restano al browser.");
return null;
}
}
/// <summary>The site's home page as the browser writes it (with its final slash), for «Pagina iniziale».</summary>
private static string HomeUrl(string baseUrl) =>
Uri.TryCreate(baseUrl, UriKind.Absolute, out var home) ? home.AbsoluteUri : baseUrl;
/// <summary>
/// Development with the test site only (<c>--accesso-di-prova</c>): what Alberto does by hand on Instagram — open
/// the site once, so that its session cookie exists — then back to the rest page.
/// the site once, so that its session cookie exists, and with a saved session copy it as «Ho finito» would (S4) —
/// then back to the rest page. Before the engine starts, under a hold of the driving gate as Alberto's own login.
/// </summary>
private async Task TestSiteLoginAsync(CancellationToken ct)
{
var browser = Browser!;
await Febe.Browser.Cdp.CdpPageExtensions.NavigateAsync(browser.Cdp, _options.LoginUrl, ct).ConfigureAwait(false);
await Febe.Browser.Cdp.CdpPageExtensions.WaitForLoadAsync(browser.Cdp, Clock, TimeSpan.FromSeconds(15), ct).ConfigureAwait(false);
var hold = _copier is null ? null : browser.UserDriving.Begin();
try
{
await Febe.Browser.Cdp.CdpPageExtensions.NavigateAsync(browser.Cdp, _options.LoginUrl, ct).ConfigureAwait(false);
await Febe.Browser.Cdp.CdpPageExtensions.WaitForLoadAsync(browser.Cdp, Clock, TimeSpan.FromSeconds(15), ct).ConfigureAwait(false);
if (_copier is not null)
{
await _copier.CopyAsync(() => true, ct).ConfigureAwait(false);
}
}
finally
{
hold?.Dispose();
}
await browser.RestAsync(ct).ConfigureAwait(false);
await Connection!.RefreshAsync(ct).ConfigureAwait(false);
Log.Info("collegamento", "Sito di prova: accesso automatico fatto.");
+19
View File
@@ -2,6 +2,7 @@ using Febe.Browser.Recipes;
using Febe.Core.Abstractions;
using Febe.Core.Alerts;
using Febe.Core.Library;
using Febe.Core.Security;
using Febe.Core.Storage;
using Febe.Web;
using Febe.Web.Connection;
@@ -34,6 +35,17 @@ public interface IFebePlatform
/// <summary>The browser of this shell. Called once, after the database is open and before the engine exists.</summary>
Task<IFebeBrowser> CreateBrowserAsync(FebePlatformContext context, CancellationToken ct);
/// <summary>
/// How this shell encrypts the saved session (issue #36, S4, spec §13.2): DPAPI for the current user on Windows,
/// AES-256-GCM in Docker with the key of <c>FEBE_CHIAVE_SESSIONE</c> or <c>Dati/sessione/chiave.bin</c>. Called at
/// most once, after the database is open, and only when the composition keeps a saved session
/// (<see cref="FebeAppOptions.Collection"/> is <see cref="CollectionRoute.Requests"/>). Says in the log where the
/// key comes from, never the key.
/// </summary>
/// <exception cref="InvalidDataException">The key file is there but is not a key of Febe.</exception>
/// <exception cref="IOException">The key file could not be made or read.</exception>
ISessionProtector CreateSessionProtector(FebePlatformContext context);
/// <summary>
/// Services of this shell for a normal start, registered before the web layer (whose fallbacks use TryAdd):
/// native shell (its notifications are the Windows channel of the alerts), browser window, remote view, change of
@@ -103,6 +115,13 @@ public sealed record FebeAppOptions
/// <summary>Development: the first session comes after this delay instead of 2–10 minutes.</summary>
public TimeSpan? FirstSessionDelay { get; init; }
/// <summary>
/// Option «raccolta» (issue #36, S4): <see cref="CollectionRoute.Pages"/> by default, as before S4.
/// <see cref="CollectionRoute.Requests"/> builds the saved session and the site client only when the site's catalog
/// has configured operations.
/// </summary>
public CollectionRoute Collection { get; init; } = CollectionRoute.Pages;
/// <summary>Warnings found while reading the configuration, for the log.</summary>
public IReadOnlyList<string> Warnings { get; init; } = [];
}
+149
View File
@@ -0,0 +1,149 @@
using System.Globalization;
using Febe.Browser.Session;
using Febe.Core.Abstractions;
using Febe.Core.Collection.Requests;
namespace Febe.App;
/// <summary>How a copy of the browser's session ended (counts and names only).</summary>
public enum SessionCopyStatus
{
/// <summary>Copied and written to the saved session.</summary>
Saved,
/// <summary>Copied; it counts at once, but the disk refused it (tried again with the next write).</summary>
SavedInMemoryOnly,
/// <summary>Not copied: <see cref="SessionCopyOutcome.Refusal"/> says why.</summary>
Refused,
/// <summary>Copied, then thrown away: meanwhile the page was no longer Alberto's (rule 7).</summary>
Discarded,
}
/// <summary>What a copy did, for the message of «Ho finito» and the tests. Never a value.</summary>
/// <param name="Status">How it ended.</param>
/// <param name="Refusal">Why nothing was copied (with <see cref="SessionCopyStatus.Refused"/>).</param>
/// <param name="Cookies">Cookies copied.</param>
/// <param name="MissingValues">Values of the page it did not find that a configured operation sends.</param>
/// <param name="MissingDocIds">doc_id of configured operations it did not find.</param>
public sealed record SessionCopyOutcome(SessionCopyStatus Status, CaptureRefusal? Refusal, int Cookies, int MissingValues, int MissingDocIds)
{
/// <summary>True when the copy now is the saved session.</summary>
public bool Saved => Status is SessionCopyStatus.Saved or SessionCopyStatus.SavedInMemoryOnly;
}
/// <summary>
/// Copies the session of Febe's browser into the saved session (issue #36, S4, spec §6.0): at «Ho finito», and after the
/// automatic login of the test site. A new copy replaces the saved one (§6.0 «un nuovo accesso ricopia tutto e
/// sostituisce»), also when some value of the page is missing: the requests that send it then do not leave and stop
/// the engine as a disconnection until a new copy has it (never a way back to the pages). A refused copy leaves the
/// saved session as it is.
/// </summary>
public interface ISessionCopier
{
/// <summary>
/// Copies the session the page holds now. The caller holds the page (Alberto's lease, the page turn).
/// </summary>
/// <param name="mayKeep">Asked after reading, before saving: false throws the copy away (the page stopped being Alberto's).</param>
/// <param name="ct">Cancels the copy; nothing is saved then.</param>
Task<SessionCopyOutcome> CopyAsync(Func<bool> mayKeep, CancellationToken ct);
}
/// <summary>
/// The copy over the browser's page (<see cref="SessionCapture"/>) into a <see cref="ISavedSiteSession"/>, bounded by
/// <see cref="Timeout"/>. Logs one line with counts and names, never a value (rule 10).
/// </summary>
public sealed class BrowserSessionCopier : ISessionCopier
{
private readonly ICdpSession _cdp;
private readonly SessionCapturePlan _plan;
private readonly ISavedSiteSession _store;
private readonly IClock _clock;
private readonly Action<string> _log;
/// <param name="cdp">The page of Febe's browser.</param>
/// <param name="plan">What to read (from the catalog of the site).</param>
/// <param name="store">The saved session the copy replaces.</param>
/// <param name="clock">The composition's clock (when the copy was made).</param>
/// <param name="log">Receives the Italian log line (counts and names only).</param>
public BrowserSessionCopier(ICdpSession cdp, SessionCapturePlan plan, ISavedSiteSession store, IClock clock, Action<string> log)
{
_cdp = cdp ?? throw new ArgumentNullException(nameof(cdp));
_plan = plan ?? throw new ArgumentNullException(nameof(plan));
_store = store ?? throw new ArgumentNullException(nameof(store));
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
_log = log ?? throw new ArgumentNullException(nameof(log));
}
/// <summary>
/// How long the reading may last before it counts as a browser error: «Ho finito» holds the commands of the
/// connection meanwhile, so a browser that hangs must not hold them for ever (real time).
/// </summary>
public TimeSpan Timeout { get; set; } = TimeSpan.FromSeconds(10);
public async Task<SessionCopyOutcome> CopyAsync(Func<bool> mayKeep, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(mayKeep);
SessionCaptureResult result;
using (var limit = CancellationTokenSource.CreateLinkedTokenSource(ct))
{
limit.CancelAfter(Timeout);
try
{
result = await SessionCapture.CaptureAsync(_cdp, _plan, _clock, limit.Token).ConfigureAwait(false);
}
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
{
_log("Sessione non copiata: il browser non ha risposto in tempo.");
return new SessionCopyOutcome(SessionCopyStatus.Refused, CaptureRefusal.BrowserError, 0, 0, 0);
}
}
if (result.Values is not { } values)
{
var refusal = result.Refusal ?? CaptureRefusal.BrowserError;
_log($"Sessione non copiata: {Reason(refusal)}. La sessione salvata resta com'era.");
return new SessionCopyOutcome(SessionCopyStatus.Refused, refusal, 0, 0, 0);
}
var counts = string.Create(
CultureInfo.InvariantCulture,
$"{result.Cookies} cookie ({result.DroppedCookies} scartati), {result.ExpectedValues - result.MissingValues.Count} valori della pagina su {result.ExpectedValues}, {result.ExpectedDocIds - result.MissingDocIds.Count} doc_id su {result.ExpectedDocIds}");
if (!mayKeep())
{
_log($"Sessione letta ma non salvata: nel frattempo il browser è tornato al motore ({counts}).");
return new SessionCopyOutcome(SessionCopyStatus.Discarded, null, result.Cookies, result.MissingValues.Count, result.MissingDocIds.Count);
}
// Not cancelled from here: the copy was made, and a half-written replacement is never left. It replaces the
// saved session also when a value is missing (§6.0): keeping an older copy could keep another login's cookies.
var onDisk = await _store.ReplaceAsync(values, CancellationToken.None).ConfigureAwait(false);
// Missing counts only what a configured operation sends: that request will not leave (a disconnection, §6.0).
var neededValues = result.MissingValues.Where(_plan.NeededValues.Contains).ToList();
var neededDocIds = result.MissingDocIds.Where(_plan.NeededDocIds.Contains).ToList();
var needed = neededValues.Concat(neededDocIds).ToList();
var unused = result.MissingValues.Concat(result.MissingDocIds).Except(needed, StringComparer.Ordinal).ToList();
_log($"Sessione copiata: {counts}"
+ (needed.Count == 0 ? string.Empty : "; mancano " + string.Join(", ", needed) + ", che servono alle operazioni configurate")
+ (unused.Count == 0 ? string.Empty : "; mancano anche " + string.Join(", ", unused) + ", che nessuna operazione configurata usa")
+ (onDisk ? string.Empty : "; non ancora scritta su disco")
+ ".");
return new SessionCopyOutcome(
onDisk ? SessionCopyStatus.Saved : SessionCopyStatus.SavedInMemoryOnly,
null,
result.Cookies,
neededValues.Count,
neededDocIds.Count);
}
/// <summary>Why a copy was refused, in Italian.</summary>
public static string Reason(CaptureRefusal refusal) => refusal switch
{
CaptureRefusal.NotOnSite => "il browser non era su una pagina del sito",
CaptureRefusal.CheckpointPage => "il browser era sulla pagina di accesso o di verifica",
CaptureRefusal.NoUserAgent => "il browser non ha dato il suo user agent",
_ => "il browser non ha risposto",
};
}