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

+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.");