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",
};
}
+2 -1
View File
@@ -31,7 +31,8 @@ public static class CdpCommandPolicy
"Page.screencastFrameAck",
"Page.stopScreencast",
"Page.captureScreenshot",
// Check the session: existence of the session cookie only.
// Check the session: existence of the session cookie only. Copy the session (§6.1 «Copiare la sessione»,
// issue #36, S4): the values too, once at «Ho finito» and only with a saved session (Session/SessionCapture).
"Network.getCookies");
/// <summary>Commands explicitly forbidden by spec §2 rule 2 and §6.1, refused with a specific message.</summary>
@@ -2,6 +2,7 @@ using System.Diagnostics;
using Febe.Browser.Cdp;
using Febe.Browser.Diagnostics;
using Febe.Core.Abstractions;
using Febe.Core.Security;
namespace Febe.Browser.Hosting;
@@ -199,7 +200,11 @@ public sealed class ChromiumProcessHost : IBrowserHost
/// <summary>Same as <see cref="StopAsync"/>. A stopped host cannot be started again: create a new one.</summary>
public ValueTask DisposeAsync() => new(StopAsync());
private ProcessStartInfo BuildStartInfo(string executable, IReadOnlyList<string> arguments, BrowserOptions options)
/// <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)
@@ -224,7 +229,7 @@ public sealed class ChromiumProcessHost : IBrowserHost
}
}
return info;
return info.WithoutSecrets();
}
private async Task WaitReadyAndConnectAsync(Process process, CancellationToken ct)
+2 -1
View File
@@ -98,7 +98,8 @@ public sealed class UserDrivingGate
/// <summary>
/// Tells whether the session cookie exists (spec §6.1, §7.6) through <c>Network.getCookies</c>.
/// Only the cookie names are looked at: values are never read, kept or logged.
/// Only the cookie names are looked at: values are never read, kept or logged here. The values are read only by the
/// copy of the session at «Ho finito» (§6.1 «Copiare la sessione», <c>Febe.Browser.Session.SessionCapture</c>).
/// </summary>
public static class SessionCookieProbe
{
+4 -2
View File
@@ -2,6 +2,7 @@ using System.Diagnostics;
using System.Globalization;
using Febe.Browser.Diagnostics;
using Febe.Core.Abstractions;
using Febe.Core.Security;
namespace Febe.Browser.Hosting;
@@ -98,7 +99,8 @@ public sealed class XvfbProcess : IAsyncDisposable
return null;
}
private ProcessStartInfo BuildStartInfo(string exe)
/// <summary>The start of Xvfb, without Febe's secrets in its environment (<see cref="ChildProcessEnvironment"/>).</summary>
internal ProcessStartInfo BuildStartInfo(string exe)
{
var info = new ProcessStartInfo(exe);
info.ArgumentList.Add(Display);
@@ -108,7 +110,7 @@ public sealed class XvfbProcess : IAsyncDisposable
info.ArgumentList.Add("-nolisten");
info.ArgumentList.Add("tcp");
info.ArgumentList.Add("-noreset");
return info;
return info.WithoutSecrets();
}
private async Task WaitForSocketAsync(Process process, IClock clock, CancellationToken ct)
@@ -108,7 +108,8 @@ public sealed record CollectionPipelineOptions
/// <summary>
/// The site client and its catalog (issue #36, S3): the recipes whose roles are all configured go by requests.
/// Null: every recipe goes by the browser. Production leaves it unset until S4.
/// Null: every recipe goes by the browser. Since S4 production sets it only with the option «raccolta» on
/// «richieste» and a catalog with configured operations (never with Instagram while none is configured).
/// </summary>
public SiteRequestOptions? Requests { get; init; }
}
+464
View File
@@ -0,0 +1,464 @@
using System.Globalization;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.RegularExpressions;
using Febe.Browser.Cdp;
using Febe.Browser.Recipes;
using Febe.Core.Abstractions;
using Febe.Core.Collection;
using Febe.Core.Collection.Requests;
namespace Febe.Browser.Session;
/// <summary>One value of the page the copy reads: the session field, and the module and property that hold it.</summary>
/// <param name="Field">The session field (<see cref="SiteSessionValues.PageFields"/>).</param>
/// <param name="Module">The module of the page's <c>require</c>.</param>
/// <param name="Property">The property of the module; null for a module whose export is the value (a doc_id).</param>
public sealed record PageRead(string Field, string Module, string? Property);
/// <summary>
/// What the copy at «Ho finito» reads from the browser (issue #36, S4, spec §6.0, §6.1 «Copiare la sessione»): the
/// cookies of the site for its root and for every path of the catalog, the user agent, and only the modules the
/// <c>page</c> section of <c>richieste.&lt;sito&gt;.json</c> names (checked identifiers). Holds names only.
/// </summary>
public sealed class SessionCapturePlan
{
private SessionCapturePlan(Uri site, HostClassifier hosts, IReadOnlyList<Uri> cookieUrls, IReadOnlyList<PageRead> values, IReadOnlyList<PageRead> docIds, IReadOnlyList<Regex> refusedPaths, IReadOnlySet<string> neededValues, IReadOnlySet<string> neededDocIds)
{
Site = site;
Hosts = hosts;
CookieUrls = cookieUrls;
Values = values;
DocIds = docIds;
RefusedPaths = refusedPaths;
NeededValues = neededValues;
NeededDocIds = neededDocIds;
}
/// <summary>The root of the site (<c>https://www.instagram.com/</c>, <c>http://127.0.0.1:port/</c>).</summary>
public Uri Site { get; }
/// <summary>The hosts of the site: the page must be on one of them.</summary>
public HostClassifier Hosts { get; }
/// <summary>
/// The addresses <c>Network.getCookies</c> is asked for: the root and, for each path of the catalog, the path up to
/// its first value (<c>/api/dati/profilo/{nome}</c> → <c>/api/dati/profilo/</c>), so a cookie limited to a path of the
/// site client is copied with it.
/// </summary>
public IReadOnlyList<Uri> CookieUrls { get; }
/// <summary>The values of the page, in the order of the catalog's <c>page</c> section.</summary>
public IReadOnlyList<PageRead> Values { get; }
/// <summary>The doc_id of every GraphQL operation of the catalog (configured or not): <see cref="PageRead.Field"/> is the operation.</summary>
public IReadOnlyList<PageRead> DocIds { get; }
/// <summary>Paths of the site where no copy is made: the login and verification pages of the stop rules (§7.6).</summary>
public IReadOnlyList<Regex> RefusedPaths { get; }
/// <summary>
/// The values of the page a configured operation sends (<c>session:&lt;field&gt;</c>): only these, when missing, stop
/// a request of the site client (a disconnection, §6.0); the others are read but no request waits for them.
/// </summary>
public IReadOnlySet<string> NeededValues { get; }
/// <summary>The configured GraphQL operations that send their <c>doc_id</c> from the saved session.</summary>
public IReadOnlySet<string> NeededDocIds { get; }
/// <summary>The plan of <paramref name="site"/> from its catalog and its stop rules.</summary>
/// <param name="site">The site of the composition.</param>
/// <param name="catalog">Its <c>richieste.&lt;sito&gt;.json</c>; without a <c>page</c> section only cookies and user agent are read.</param>
/// <param name="rules">Its stop rules: every path rule for the site is a page where no copy is made. Null: none.</param>
public static SessionCapturePlan For(CollectionSite site, RequestCatalog catalog, SignalRules? rules)
{
ArgumentNullException.ThrowIfNull(site);
ArgumentNullException.ThrowIfNull(catalog);
var root = new Uri(site.BaseUrl.TrimEnd('/') + "/", UriKind.Absolute);
var urls = new List<Uri> { root };
foreach (var operation in catalog.Operations)
{
var cut = operation.Path.IndexOf('{', StringComparison.Ordinal);
var prefix = cut < 0 ? operation.Path : operation.Path[..cut];
if (prefix.StartsWith('/') && Uri.TryCreate(root, prefix, out var address) && !urls.Contains(address))
{
urls.Add(address);
}
}
var values = new List<PageRead>();
var docIds = new List<PageRead>();
if (catalog.Page is { } page)
{
foreach (var field in page.Order)
{
var source = page.Values[field];
values.Add(new PageRead(field, source.Module, source.Property));
}
foreach (var operation in catalog.Operations.Where(o => o.Kind == OperationKind.GraphQl))
{
if (page.DocIdModuleFor(operation.Name) is { } module)
{
docIds.Add(new PageRead(operation.Name, module, null));
}
}
}
// What the configured operations actually send from the saved session: a missing value no configured operation
// uses stops nothing, and «Ho finito» does not count it as missing.
var neededValues = new HashSet<string>(StringComparer.Ordinal);
var neededDocIds = new HashSet<string>(StringComparer.Ordinal);
foreach (var operation in catalog.Configured)
{
foreach (var source in operation.Headers.Values.Concat(operation.Body.Values).Where(v => v.Kind == ValueSourceKind.Session))
{
if (source.Argument == "doc_id")
{
neededDocIds.Add(operation.Name);
}
else if (catalog.Page?.Values.ContainsKey(source.Argument!) == true)
{
neededValues.Add(source.Argument!);
}
}
}
var refused = rules?.Rules
.Where(r => r.Path is not null && r.HostKinds.Contains(HostKind.Site))
.Select(r => r.Path!)
.ToList() ?? [];
return new SessionCapturePlan(root, site.Hosts, urls, values, docIds, refused, neededValues, neededDocIds);
}
/// <summary>Counts only.</summary>
public override string ToString() => string.Create(
CultureInfo.InvariantCulture,
$"Copia della sessione: {CookieUrls.Count} indirizzi per i cookie, {Values.Count} valori della pagina, {DocIds.Count} doc_id.");
}
/// <summary>Why a copy was not made.</summary>
public enum CaptureRefusal
{
/// <summary>The page is not on the site (the rest page, another host).</summary>
NotOnSite,
/// <summary>The page is a login or verification page of the site (a path of the stop rules).</summary>
CheckpointPage,
/// <summary>The browser gave no user agent.</summary>
NoUserAgent,
/// <summary>The browser did not answer, or refused (restarting, closed, too slow).</summary>
BrowserError,
}
/// <summary>
/// What a copy found. Its text and its members hold counts and names only; the values are in <see cref="Values"/>,
/// whose text shows counts too (rule 10).
/// </summary>
public sealed class SessionCaptureResult
{
internal SessionCaptureResult(SiteSessionValues? values, CaptureRefusal? refusal, int droppedCookies, IReadOnlyList<string> missingValues, IReadOnlyList<string> missingDocIds, int expectedValues, int expectedDocIds)
{
Values = values;
Refusal = refusal;
DroppedCookies = droppedCookies;
MissingValues = missingValues;
MissingDocIds = missingDocIds;
ExpectedValues = expectedValues;
ExpectedDocIds = expectedDocIds;
}
/// <summary>The copied session; null when the copy was refused.</summary>
public SiteSessionValues? Values { get; }
/// <summary>Why nothing was copied; null when <see cref="Values"/> is there.</summary>
public CaptureRefusal? Refusal { get; }
/// <summary>How many cookies were copied.</summary>
public int Cookies => Values?.Cookies.Count ?? 0;
/// <summary>Cookies of the site left out: partitioned, or with a name or value a browser would not send back.</summary>
public int DroppedCookies { get; }
/// <summary>The session fields the page did not give (left absent, never guessed: rule 9).</summary>
public IReadOnlyList<string> MissingValues { get; }
/// <summary>The GraphQL operations whose doc_id the page did not give.</summary>
public IReadOnlyList<string> MissingDocIds { get; }
/// <summary>How many values of the page the plan asked for.</summary>
public int ExpectedValues { get; }
/// <summary>How many doc_id the plan asked for.</summary>
public int ExpectedDocIds { get; }
internal static SessionCaptureResult Refused(CaptureRefusal refusal) => new(null, refusal, 0, [], [], 0, 0);
/// <summary>Counts and names only.</summary>
public override string ToString() => Refusal is { } refusal
? $"Copia della sessione rifiutata: {refusal}."
: string.Create(
CultureInfo.InvariantCulture,
$"Copia della sessione: {Cookies} cookie ({DroppedCookies} scartati), {ExpectedValues - MissingValues.Count} valori della pagina su {ExpectedValues}, {ExpectedDocIds - MissingDocIds.Count} doc_id su {ExpectedDocIds}.");
}
/// <summary>
/// The copy of the browser's session into a saved session (issue #36, S4, spec §6.0, §6.1 «Copiare la sessione»): only
/// <c>Page.getFrameTree</c> (where the page is), <c>Network.getCookies</c> with the values for the site's addresses,
/// and ONE read-only <c>Runtime.evaluate</c> that reads <c>navigator.userAgent</c> and the modules of the plan. Nothing
/// is navigated, nothing is written into the browser, nothing is logged here: the caller logs counts and names.
/// </summary>
/// <remarks>
/// A value the page does not give is left out, never invented (rule 9): a missing module, a property that is not a
/// string or a number, a value too long or with control or non-ASCII characters. Cookies are kept as the browser has
/// them (name, value, domain, path, host-only, secure, HTTP-only, expiry); a partitioned cookie, or one a browser would
/// not send back, is left out and counted.
/// </remarks>
public static class SessionCapture
{
/// <summary>The longest page value kept.</summary>
public const int MaxValueLength = 4096;
/// <summary>
/// Copies the session the page holds now.
/// </summary>
/// <exception cref="OperationCanceledException"><paramref name="ct"/> was cancelled.</exception>
public static async Task<SessionCaptureResult> CaptureAsync(ICdpSession cdp, SessionCapturePlan plan, IClock clock, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(cdp);
ArgumentNullException.ThrowIfNull(plan);
ArgumentNullException.ThrowIfNull(clock);
try
{
// (a) Only on a page of the site, not on its login or verification page. The address is never logged.
var url = await cdp.GetMainFrameUrlAsync(ct).ConfigureAwait(false);
if (!Uri.TryCreate(url, UriKind.Absolute, out var page) || plan.Hosts.Classify(page) != HostKind.Site)
{
return SessionCaptureResult.Refused(CaptureRefusal.NotOnSite);
}
var path = string.IsNullOrEmpty(page.AbsolutePath) ? "/" : page.AbsolutePath;
if (plan.RefusedPaths.Any(rule => IsMatch(rule, path)))
{
return SessionCaptureResult.Refused(CaptureRefusal.CheckpointPage);
}
// (b) The cookies of the site, with their values.
var urls = new JsonArray();
foreach (var address in plan.CookieUrls)
{
urls.Add(address.AbsoluteUri);
}
var answer = await cdp.SendAsync("Network.getCookies", new JsonObject { ["urls"] = urls }, ct).ConfigureAwait(false);
var (cookies, dropped) = ReadCookies(answer, plan);
// (c) One read-only evaluation: the user agent and the modules of the plan.
var read = await cdp.EvaluateAsync(SessionCaptureScript.Build(plan), ct).ConfigureAwait(false);
var userAgent = read.ValueKind == JsonValueKind.Object && read.TryGetProperty("ua", out var ua) ? Accept(ua) : null;
if (userAgent is null)
{
return SessionCaptureResult.Refused(CaptureRefusal.NoUserAgent);
}
var fields = Collect(read, "values", plan.Values, out var missingValues);
var docIds = Collect(read, "docIds", plan.DocIds, out var missingDocIds);
// (d) The values present; the absent stay absent.
var values = new SiteSessionValues(cookies, userAgent, fields, docIds, clock.Now);
return new SessionCaptureResult(values, null, dropped, missingValues, missingDocIds, plan.Values.Count, plan.DocIds.Count);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
throw;
}
catch (Exception ex) when (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException
or TimeoutException or CdpEvaluationException or CdpCommandNotAllowedException or OperationCanceledException
or KeyNotFoundException or InvalidOperationException)
{
// Never the text of the browser or the page: it may hold what the page holds.
return SessionCaptureResult.Refused(CaptureRefusal.BrowserError);
}
}
private static bool IsMatch(Regex rule, string path)
{
try
{
return rule.IsMatch(path);
}
catch (RegexMatchTimeoutException)
{
// An expression too slow on this address: as if it matched, no copy.
return true;
}
}
/// <summary>The cookies of <paramref name="answer"/> for a host of the site, and how many were left out.</summary>
private static (List<SiteCookie> Cookies, int Dropped) ReadCookies(JsonElement answer, SessionCapturePlan plan)
{
var kept = new List<SiteCookie>();
var dropped = 0;
if (answer.ValueKind != JsonValueKind.Object || !answer.TryGetProperty("cookies", out var list) || list.ValueKind != JsonValueKind.Array)
{
return (kept, dropped);
}
var hosts = plan.CookieUrls.Select(SiteCookies.HostOf).Distinct(StringComparer.Ordinal).ToList();
foreach (var item in list.EnumerateArray())
{
if (item.ValueKind != JsonValueKind.Object)
{
continue;
}
var name = Text(item, "name");
var value = Text(item, "value");
var rawDomain = Text(item, "domain");
if (rawDomain is null)
{
dropped++;
continue;
}
var hostOnly = !rawDomain.StartsWith('.');
var domain = SiteCookies.NormalizeDomain(rawDomain);
// Another host's cookie (the browser answers by address, so this is only a second guard): not the site's.
if (domain is null || !hosts.Any(h => SiteCookies.DomainMatches(h, domain, hostOnly)))
{
continue;
}
// A partitioned cookie belongs to the page that embeds the site, not to the site: never sent by the client.
if (item.TryGetProperty("partitionKey", out var partition) && partition.ValueKind is not (JsonValueKind.Null or JsonValueKind.Undefined))
{
dropped++;
continue;
}
if (name is null || value is null || !SiteCookies.IsPlainName(name) || !SiteCookies.IsSendableValue(value))
{
dropped++;
continue;
}
var cookiePath = Text(item, "path") ?? "/";
var secure = Flag(item, "secure");
var httpOnly = Flag(item, "httpOnly");
DateTimeOffset? expires = null;
if (!Flag(item, "session") && item.TryGetProperty("expires", out var e) && e.ValueKind == JsonValueKind.Number && e.TryGetDouble(out var seconds) && seconds > 0)
{
expires = seconds >= DateTimeOffset.MaxValue.ToUnixTimeSeconds()
? DateTimeOffset.MaxValue
: DateTimeOffset.FromUnixTimeMilliseconds((long)(seconds * 1000));
}
try
{
kept.Add(new SiteCookie(name, value, domain, cookiePath, hostOnly, secure, httpOnly, expires));
}
catch (ArgumentException)
{
// A path or domain a browser would not keep: left out (the message would name the cookie only).
dropped++;
}
}
return (kept, dropped);
}
/// <summary>The values of <paramref name="section"/> the plan asked for and the page gave; the names of the others.</summary>
private static Dictionary<string, string> Collect(JsonElement read, string section, IReadOnlyList<PageRead> asked, out IReadOnlyList<string> missing)
{
var found = new Dictionary<string, string>(StringComparer.Ordinal);
var absent = new List<string>();
var hasSection = read.TryGetProperty(section, out var given) && given.ValueKind == JsonValueKind.Object;
foreach (var entry in asked)
{
if (hasSection && given.TryGetProperty(entry.Field, out var value) && Accept(value) is { } text)
{
found[entry.Field] = text;
}
else
{
absent.Add(entry.Field);
}
}
missing = absent;
return found;
}
/// <summary>A string of at most <see cref="MaxValueLength"/> printable ASCII characters, or null.</summary>
private static string? Accept(JsonElement value)
{
if (value.ValueKind != JsonValueKind.String)
{
return null;
}
var text = value.GetString();
return text is { Length: > 0 and <= MaxValueLength } && text.All(c => c is >= ' ' and <= '~') ? text : null;
}
private static string? Text(JsonElement item, string name) =>
item.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String ? value.GetString() : null;
private static bool Flag(JsonElement item, string name) =>
item.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.True;
}
/// <summary>
/// The one expression of the copy (§6.1: <c>Runtime.evaluate</c> read-only): written only from the identifiers of the
/// plan, each embedded as a JSON string, so a catalog file cannot put code in it; it passes
/// <see cref="ReadOnlyScriptGuard"/>. Every module is read in its own <c>try</c>: an unknown module, or one the page
/// refuses, is a missing value and never an error that leaves the expression.
/// </summary>
public static class SessionCaptureScript
{
/// <summary>The expression for <paramref name="plan"/>.</summary>
public static string Build(SessionCapturePlan plan)
{
ArgumentNullException.ThrowIfNull(plan);
var text = new StringBuilder();
text.Append("(() => {\n");
text.Append(" const out = { ua: null, values: {}, docIds: {} };\n");
text.Append(" try { out.ua = String(navigator.userAgent); } catch (e) { out.ua = null; }\n");
text.Append(" const has = typeof require === 'function';\n");
text.Append(" const read = (m, p) => {\n");
text.Append(" if (!has) { return null; }\n");
text.Append(" try {\n");
text.Append(" const x = require(m);\n");
text.Append(" const v = p === null ? x : (x === null || x === undefined ? undefined : x[p]);\n");
text.Append(" return typeof v === 'string' || typeof v === 'number' ? String(v) : null;\n");
text.Append(" } catch (e) { return null; }\n");
text.Append(" };\n");
Append(text, "values", plan.Values);
Append(text, "docIds", plan.DocIds);
text.Append(" return out;\n");
text.Append("})()");
return text.ToString();
}
/// <summary>A JavaScript string literal (JSON) for <paramref name="name"/>.</summary>
private static string Quote(string name) => JsonValue.Create(name).ToJsonString();
private static void Append(StringBuilder text, string section, IReadOnlyList<PageRead> reads)
{
foreach (var read in reads)
{
// Checked identifiers, embedded as JSON strings all the same: never code.
if (!PageSources.IsIdentifier(read.Module) || (read.Property is not null && !PageSources.IsIdentifier(read.Property)))
{
throw new ArgumentException("Un nome della sezione «page» non è un identificatore.", nameof(reads));
}
var property = read.Property is null ? "null" : Quote(read.Property);
text.Append(CultureInfo.InvariantCulture, $" {{ const v = read({Quote(read.Module)}, {property}); if (v !== null) {{ out.{section}[{Quote(read.Field)}] = v; }} }}\n");
}
}
}
@@ -0,0 +1,258 @@
using System.Globalization;
using System.Security.Cryptography;
using Febe.Core.Security;
namespace Febe.Core.Collection.Requests;
/// <summary>
/// The saved session on disk (issue #36, S4, spec §6.0, §13.2): <c>Dati/sessione/sessione.json</c>, encrypted by an
/// <see cref="ISessionProtector"/> (DPAPI on Windows, AES-256-GCM in Docker), owner-only, replaced at once. Only the
/// copy from the browser and the site client touch it; it is not in the database, so never in the daily copies, and
/// the diagnostic report never reads it.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item>Loaded once, when built: no file is no session; a file that cannot be read (another key or user, damaged,
/// another format) is no session too, logged as such and left as it is, until a new copy replaces it.</item>
/// <item>One gate for <see cref="ReplaceAsync"/>, <see cref="UpdateAsync"/> and <see cref="DeleteAsync"/>; an update
/// checks the session and its capture again once it holds the gate, so a late answer never brings back a session
/// «Scollega» deleted, nor touches one a new login replaced.</item>
/// <item>The memory counts first: the site already rotated its cookies, so a write the disk refuses keeps the new
/// values in memory, logs one line with the kind of error, and is tried again with the next write.</item>
/// <item>Logs say counts and kinds only, never a value, a cookie name or a path (rule 10).</item>
/// </list>
/// </remarks>
public sealed class FileSiteSession : ISavedSiteSession
{
private readonly ISessionProtector _protector;
private readonly Action<string> _log;
private readonly Lock _snapshotGate = new();
// Never disposed: no wait handle is ever asked of it.
private readonly SemaphoreSlim _writes = new(1, 1);
private SiteSessionValues? _values;
private SavedSessionState _state;
private bool _unsaved;
private int _failedWrites;
/// <param name="file">The file (<c>DataFolderLayout.SessionFile</c>); its folder is made owner-only when first written.</param>
/// <param name="protector">The encryption of the platform.</param>
/// <param name="log">Receives the Italian log lines (counts and kinds only); null discards them.</param>
public FileSiteSession(string file, ISessionProtector protector, Action<string>? log = null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(file);
FilePath = Path.GetFullPath(file);
_protector = protector ?? throw new ArgumentNullException(nameof(protector));
_log = log ?? (_ => { });
Load();
}
/// <summary>The file of the session.</summary>
public string FilePath { get; }
public SavedSessionState State
{
get
{
lock (_snapshotGate)
{
return _state;
}
}
}
/// <summary>True while the values in memory are newer than the file (a write the disk refused).</summary>
public bool Unsaved
{
get
{
lock (_snapshotGate)
{
return _unsaved;
}
}
}
public SiteSessionValues? Read()
{
lock (_snapshotGate)
{
return _values;
}
}
public async Task<bool> ReplaceAsync(SiteSessionValues values, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(values);
await _writes.WaitAsync(ct).ConfigureAwait(false);
try
{
Swap(values, unsaved: true);
var saved = Persist(values);
if (saved)
{
_log(string.Create(CultureInfo.InvariantCulture, $"Sessione salvata scritta: {values.Cookies.Count} cookie, {values.Fields.Count} valori della pagina, {values.DocIds.Count} doc_id ({_protector.Scheme})."));
}
return saved;
}
finally
{
_writes.Release();
}
}
public async Task UpdateAsync(SiteSessionUpdate update, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(update);
ct.ThrowIfCancellationRequested();
if (update.IsEmpty)
{
return;
}
// Never cancelled once asked: the site already sent the renewal (HttpSiteRequester passes None anyway).
await _writes.WaitAsync(CancellationToken.None).ConfigureAwait(false);
try
{
// Checked again under the gate: «Scollega» or a new login may have come while this one waited.
var current = Read();
if (current is null || (update.Capture is { } capture && capture != current.Capture))
{
return;
}
var next = current.With(update);
Swap(next, unsaved: true);
Persist(next);
}
finally
{
_writes.Release();
}
}
public async Task DeleteAsync(CancellationToken ct)
{
// Not cancellable: «Scollega» must not stop halfway because the page that asked it went away.
await _writes.WaitAsync(CancellationToken.None).ConfigureAwait(false);
try
{
// Memory first: from here no update finds a session to renew.
lock (_snapshotGate)
{
_values = null;
_state = SavedSessionState.None;
_unsaved = false;
}
OwnerOnlyFiles.DeleteWithLeftovers(FilePath);
_log("Sessione salvata cancellata.");
}
finally
{
_writes.Release();
}
}
/// <summary>Counts only.</summary>
public override string ToString() => State switch
{
SavedSessionState.Present => Read()?.ToString() ?? "Nessuna sessione salvata.",
SavedSessionState.Unreadable => "Sessione salvata illeggibile.",
_ => "Nessuna sessione salvata.",
};
private void Load()
{
byte[]? blob = null;
byte[]? plain = null;
try
{
if (!File.Exists(FilePath))
{
_state = SavedSessionState.None;
return;
}
blob = File.ReadAllBytes(FilePath);
plain = _protector.Unprotect(blob);
_values = SavedSessionFile.Deserialize(plain);
_state = SavedSessionState.Present;
_log(string.Create(CultureInfo.InvariantCulture, $"Sessione salvata letta: {_values.Cookies.Count} cookie, {_values.Fields.Count} valori della pagina, {_values.DocIds.Count} doc_id ({_protector.Scheme})."));
}
catch (Exception ex) when (ex is SessionUnreadableException or InvalidDataException or CryptographicException)
{
_values = null;
_state = SavedSessionState.Unreadable;
_log("Sessione salvata illeggibile (cifratura o formato): serve un nuovo accesso. Il file resta com'è finché un nuovo accesso non lo sostituisce.");
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
_values = null;
_state = SavedSessionState.Unreadable;
_log($"Sessione salvata non letta ({ex.GetType().Name}): serve un nuovo accesso.");
}
finally
{
if (plain is not null)
{
CryptographicOperations.ZeroMemory(plain);
}
}
}
private void Swap(SiteSessionValues values, bool unsaved)
{
lock (_snapshotGate)
{
_values = values;
_state = SavedSessionState.Present;
_unsaved = unsaved;
}
}
/// <summary>Writes <paramref name="values"/> (always the newest, under the gate); false when the disk refused it.</summary>
private bool Persist(SiteSessionValues values)
{
byte[]? plain = null;
try
{
plain = SavedSessionFile.Serialize(values);
var blob = _protector.Protect(plain);
OwnerOnlyFiles.EnsureFolder(Path.GetDirectoryName(FilePath)!);
OwnerOnlyFiles.WriteAtomic(FilePath, blob);
lock (_snapshotGate)
{
if (ReferenceEquals(_values, values))
{
_unsaved = false;
}
}
if (Interlocked.Exchange(ref _failedWrites, 0) > 0)
{
_log("Sessione salvata scritta di nuovo: il disco ora accetta le scritture.");
}
return true;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or CryptographicException)
{
// One line per run of failures: the kind of error only, never the path or a value.
if (Interlocked.Increment(ref _failedWrites) == 1)
{
_log($"Sessione salvata non scritta ({ex.GetType().Name}): resta in memoria e si riprova alla prossima scrittura.");
}
return false;
}
finally
{
if (plain is not null)
{
CryptographicOperations.ZeroMemory(plain);
}
}
}
}
@@ -127,7 +127,9 @@ public sealed class SiteSessionMissingException : SiteRequestRefusedException
/// <item>Only to <see cref="HttpSiteRequesterOptions.SiteAddress"/>: https only for Instagram, http only for a loopback
/// test site; every address it builds is checked again before it leaves.</item>
/// <item>No redirect is followed (<c>AllowAutoRedirect = false</c>): a 3xx comes back as an answer, a signal (§7.6).</item>
/// <item>Cookies are written by hand, as one <c>Cookie</c> header (<c>UseCookies = false</c>), in the session's order.</item>
/// <item>Cookies are written by hand, as one <c>Cookie</c> header (<c>UseCookies = false</c>): only those whose domain
/// and path match the request and, when secure, only over https (RFC 6265 §5.4), longer paths first, then the session's
/// order; a renewal from <c>Set-Cookie</c> keeps or sets domain and path as a browser does.</item>
/// <item>HTTP/2 with fallback to HTTP/1.1 (<see cref="HttpVersionPolicy.RequestVersionOrLower"/>), never HTTP/3;
/// gzip, deflate and brotli (the HTTP stack adds <c>Accept-Encoding: gzip, deflate, br</c> to say so: with
/// <c>Host</c> and <c>Content-Length</c> the only headers not in the catalog, besides the <c>Cookie</c> line; no
@@ -284,12 +286,15 @@ public sealed class HttpSiteRequester : ISiteRequester, IDisposable
{
var values = _session.Read()
?? throw new SiteSessionMissingException($"Richiesta «{operation.Name}» non inviata: non c'è una sessione salvata.", missing: null);
if (values.CookieAt(_options.SessionCookie, _clock.Now) is null)
var address = Address(operation, request);
// The session cookie the browser would send to this address: one limited to another path or host is not it.
if (values.CookieFor(_options.SessionCookie, address, _clock.Now) is null)
{
throw new SiteSessionMissingException($"Richiesta «{operation.Name}» non inviata: la sessione salvata non ha il cookie di sessione, o è scaduto.", _options.SessionCookie);
}
using var message = Build(operation, request, values);
using var message = Build(operation, request, address, values);
return await ExchangeAsync(operation, message, values.Capture, ct).ConfigureAwait(false);
}
finally
@@ -338,7 +343,7 @@ public sealed class HttpSiteRequester : ISiteRequester, IDisposable
{
// What the site renewed counts as soon as the headers are here, as for a browser: the site may already have
// dropped the old values, whatever happens to the body or to the caller next. Never cancelled.
var update = SessionUpdate(response, capture, out var set, out var deleted);
var update = SessionUpdate(response, message.RequestUri!, capture, out var set, out var deleted);
if (!update.IsEmpty)
{
await _session.UpdateAsync(update, CancellationToken.None).ConfigureAwait(false);
@@ -405,15 +410,9 @@ public sealed class HttpSiteRequester : ISiteRequester, IDisposable
? cancelled
: new OperationCanceledException("Client del sito chiuso: la richiesta in corso è stata interrotta.", _closing.Token);
private HttpRequestMessage Build(SiteOperation operation, SiteRequest request, SiteSessionValues values)
/// <summary>The address of <paramref name="request"/>: the site and the catalog path, checked to stay on the site.</summary>
private Uri Address(SiteOperation operation, SiteRequest request)
{
// The catalog refuses a configured operation without it; checked again: no request leaves without the
// browser's user agent (rule 4), and the HTTP stack would add none.
if (!operation.Headers.TryGetValue("user-agent", out var agent) || agent != new ValueSource(ValueSourceKind.Session, "user_agent"))
{
throw new SiteRequestRefusedException($"Richiesta «{operation.Name}» non inviata: il modello non manda l'user agent del browser («user-agent»: «session:user_agent»).");
}
var address = new Uri(_site, PathAndQuery(operation, request));
// Built from the site and a catalog path the catalog checked: checked again, so nothing leaves for another host.
@@ -422,6 +421,18 @@ public sealed class HttpSiteRequester : ISiteRequester, IDisposable
throw new SiteRequestRefusedException($"Richiesta «{operation.Name}» non inviata: l'indirizzo non è del sito.");
}
return address;
}
private HttpRequestMessage Build(SiteOperation operation, SiteRequest request, Uri address, SiteSessionValues values)
{
// The catalog refuses a configured operation without it; checked again: no request leaves without the
// browser's user agent (rule 4), and the HTTP stack would add none.
if (!operation.Headers.TryGetValue("user-agent", out var agent) || agent != new ValueSource(ValueSourceKind.Session, "user_agent"))
{
throw new SiteRequestRefusedException($"Richiesta «{operation.Name}» non inviata: il modello non manda l'user agent del browser («user-agent»: «session:user_agent»).");
}
var message = new HttpRequestMessage(new HttpMethod(operation.Method), address)
{
Version = HttpVersion.Version20,
@@ -444,7 +455,7 @@ public sealed class HttpSiteRequester : ISiteRequester, IDisposable
continue;
}
var value = Resolve(operation, name, source, values, variables: null, now);
var value = Resolve(operation, name, source, values, address, variables: null, now);
if (name == "content-type")
{
contentType = value;
@@ -457,7 +468,8 @@ public sealed class HttpSiteRequester : ISiteRequester, IDisposable
}
}
var cookies = string.Join("; ", values.CookiesAt(now).Select(c => $"{c.Key}={c.Value}"));
// Only the cookies whose domain and path match this address, longer paths first (RFC 6265 §5.4).
var cookies = string.Join("; ", values.CookiesFor(address, now).Select(c => $"{c.Name}={c.Value}"));
message.Headers.TryAddWithoutValidation("cookie", cookies);
if (operation.Kind == OperationKind.GraphQl)
@@ -466,7 +478,7 @@ public sealed class HttpSiteRequester : ISiteRequester, IDisposable
var form = new StringBuilder();
foreach (var field in operation.BodyOrder)
{
var value = Resolve(operation, field, operation.Body[field], values, variables, now);
var value = Resolve(operation, field, operation.Body[field], values, address, variables, now);
if (form.Length > 0)
{
form.Append('&');
@@ -530,12 +542,14 @@ public sealed class HttpSiteRequester : ISiteRequester, IDisposable
return path + query;
}
private static string Resolve(SiteOperation operation, string name, ValueSource source, SiteSessionValues values, string? variables, DateTimeOffset now)
private static string Resolve(SiteOperation operation, string name, ValueSource source, SiteSessionValues values, Uri address, string? variables, DateTimeOffset now)
{
var value = source.Kind switch
{
ValueSourceKind.Constant => source.Argument,
ValueSourceKind.Cookie => values.CookieAt(source.Argument!, now),
// The cookie the browser would send with this request (x-csrftoken is the csrftoken of this path).
ValueSourceKind.Cookie => values.CookieFor(source.Argument!, address, now),
ValueSourceKind.Session => values.Field(source.Argument!, operation.Name),
ValueSourceKind.Operation => operation.Name,
ValueSourceKind.Variables => variables,
@@ -693,75 +707,67 @@ public sealed class HttpSiteRequester : ISiteRequester, IDisposable
return text.ToString();
}
private SiteSessionUpdate SessionUpdate(HttpResponseMessage response, long capture, out List<string> set, out List<string> deleted)
/// <summary>
/// What the answer renews in the session, read as a browser reads it: each <c>Set-Cookie</c> line against the
/// request address (its domain and path, or host-only on the site and the default path), in order, the last line of
/// a cookie winning; and the names of the cookies set and deleted, for the answer.
/// </summary>
private SiteSessionUpdate SessionUpdate(HttpResponseMessage response, Uri request, long capture, out List<string> set, out List<string> deleted)
{
set = [];
deleted = [];
// In the order of the Set-Cookie lines: a cookie new to the session goes after the others in that order.
var renewed = new List<KeyValuePair<string, string>>();
var expires = new Dictionary<string, DateTimeOffset>(StringComparer.Ordinal);
var renewed = new List<SiteCookie>();
var removed = new List<SiteCookieKey>();
if (response.Headers.TryGetValues("set-cookie", out var lines))
{
var now = _clock.Now;
foreach (var line in lines)
{
if (SiteCookies.Parse(line, _site.IdnHost, now) is not { } cookie)
if (SiteCookies.Parse(line, request, now) is not { } parsed)
{
continue;
}
var index = renewed.FindIndex(c => c.Key == cookie.Name);
if (cookie.Deletes)
var key = parsed.Cookie.Key;
var index = renewed.FindIndex(c => c.Key == key);
if (parsed.Deletes)
{
if (index >= 0)
{
renewed.RemoveAt(index);
}
expires.Remove(cookie.Name);
set.Remove(cookie.Name);
if (!deleted.Contains(cookie.Name))
if (!removed.Contains(key))
{
deleted.Add(cookie.Name);
removed.Add(key);
}
}
else
{
if (index >= 0)
{
renewed[index] = new(cookie.Name, cookie.Value);
renewed[index] = parsed.Cookie;
}
else
{
renewed.Add(new(cookie.Name, cookie.Value));
renewed.Add(parsed.Cookie);
}
if (cookie.Expires is { } until)
{
expires[cookie.Name] = until;
}
else
{
expires.Remove(cookie.Name);
}
deleted.Remove(cookie.Name);
if (!set.Contains(cookie.Name))
{
set.Add(cookie.Name);
}
removed.Remove(key);
}
}
}
var setNames = renewed.Select(c => c.Name).Distinct(StringComparer.Ordinal).ToList();
set = setNames;
deleted = [.. removed.Select(k => k.Name).Distinct(StringComparer.Ordinal).Where(n => !setNames.Contains(n, StringComparer.Ordinal))];
string? claim = null;
if (response.Headers.TryGetValues("x-ig-set-www-claim", out var claims))
{
claim = claims.LastOrDefault(c => !string.IsNullOrWhiteSpace(c))?.Trim();
}
return new SiteSessionUpdate(renewed, deleted, claim, expires, capture);
return new SiteSessionUpdate(renewed, removed, claim, capture);
}
private TimeSpan? RetryAfter(RetryConditionHeaderValue? header)
+148 -175
View File
@@ -5,9 +5,10 @@ namespace Febe.Core.Collection.Requests;
/// <summary>
/// The saved session the site client reads its values from and writes the site's renewals to (issue #36, spec §6.0,
/// §13.2): the cookies of the site with their values, the user agent of the browser as it is, the tokens and
/// identifiers the page holds, the <c>doc_id</c> of each catalog operation and the <c>x-ig-www-claim</c>. Tappa S4 adds
/// the encrypted file of <c>Dati/sessione</c>; <see cref="InMemorySiteSession"/> serves the tests and the test site.
/// §13.2): the cookies of the site with their values, domains and paths, the user agent of the browser as it is, the
/// tokens and identifiers the page holds, the <c>doc_id</c> of each catalog operation and the <c>x-ig-www-claim</c>.
/// <see cref="FileSiteSession"/> keeps it in the encrypted file of <c>Dati/sessione</c> (tappa S4);
/// <see cref="InMemorySiteSession"/> serves the tests and the simulation.
/// </summary>
/// <remarks>
/// Only the site client and the copy from the browser («Ho finito», S4) touch it. Its values never reach a log, a
@@ -22,19 +23,55 @@ public interface ISiteSession
/// Applies what the site sent with one answer (renewed or deleted cookies, a new claim) in one write, so a stored
/// session never holds half an answer. Does nothing when there is no saved session, and nothing when
/// <see cref="SiteSessionUpdate.Capture"/> names another capture than the stored one: the late answer of a session
/// a new login replaced never touches the new one (§6.0: «un nuovo accesso ricopia tutto e sostituisce»).
/// a new login replaced never touches the new one (§6.0: «un nuovo accesso ricopia tutto e sostituisce»). Never
/// throws because of the disk: a store that cannot write keeps the renewal in memory and tries again later.
/// </summary>
Task UpdateAsync(SiteSessionUpdate update, CancellationToken ct);
}
/// <summary>Whether a saved session is there (never what it holds).</summary>
public enum SavedSessionState
{
/// <summary>No saved session: never copied, or deleted by «Scollega».</summary>
None,
/// <summary>A saved session is there.</summary>
Present,
/// <summary>A file is there but cannot be read (another key, damaged, another format): counts as no session.</summary>
Unreadable,
}
/// <summary>
/// The saved session a new copy from the browser replaces and «Scollega» deletes (issue #36, S4, §6.0, §13.2).
/// </summary>
public interface ISavedSiteSession : ISiteSession
{
/// <summary>Whether a session is there; <see cref="SavedSessionState.Unreadable"/> counts as none.</summary>
SavedSessionState State { get; }
/// <summary>
/// Replaces the whole session with a new copy (a new login: «un nuovo accesso ricopia tutto e sostituisce»). The new
/// values count at once, also when the disk refuses them; true when they are also on disk.
/// </summary>
Task<bool> ReplaceAsync(SiteSessionValues values, CancellationToken ct);
/// <summary>
/// Deletes the session («Scollega»): first in memory, so no later renewal can bring it back, then on disk.
/// </summary>
/// <exception cref="IOException">The file could not be deleted (the session is already gone from memory).</exception>
/// <exception cref="UnauthorizedAccessException">The file could not be deleted.</exception>
Task DeleteAsync(CancellationToken ct);
}
/// <summary>
/// A snapshot of the saved session. Its text (<see cref="ToString"/>) shows counts only, never a name of the account,
/// a value of a cookie or of a token.
/// </summary>
/// <remarks>
/// Cookies are the ones the browser would send to the site's address (S4 copies them with <c>Network.getCookies</c>
/// for that address, so domain and path are already resolved by the browser), each with its expiry when it has one: an
/// expired cookie is not sent, an expired session cookie is a missing session (§7.6, Disconnessione).
/// Cookies keep domain, path, secure and expiry as the browser had them (S4 copies them with <c>Network.getCookies</c>):
/// the site client sends a cookie only to an address it matches (<see cref="SiteCookie.Matches"/>); an expired cookie is
/// not sent, an expired session cookie is a missing session (§7.6, Disconnessione).
/// </remarks>
public sealed class SiteSessionValues
{
@@ -43,59 +80,57 @@ public sealed class SiteSessionValues
private static long s_captures;
/// <param name="cookies">Cookies of the site, by name, in the order the browser had them, values as they are.</param>
/// <param name="userAgent">The user agent of Febe's browser, copied as it is (rule 4).</param>
/// <param name="fields">
/// Values of the page by the names of <see cref="ValueSource.SessionFields"/> other than <c>user_agent</c> and
/// <c>doc_id</c>: <c>lsd</c>, <c>fb_dtsg</c>, <c>app_id</c>, <c>claim</c>, <c>account_id</c>.
/// <param name="cookies">
/// Cookies of the site, in the order the browser had them (its order stands for the creation order, RFC 6265 §5.4);
/// a second cookie with the same <see cref="SiteCookie.Key"/> replaces the first in its place.
/// </param>
/// <param name="userAgent">The user agent of Febe's browser, copied as it is (rule 4).</param>
/// <param name="fields">Values of the page by the names of <see cref="PageFields"/> (and <c>claim</c>).</param>
/// <param name="docIds">The <c>doc_id</c> of each GraphQL operation of the catalog, by operation name.</param>
/// <param name="expires">When cookies expire, by name; a cookie not listed lasts as long as the session.</param>
/// <exception cref="ArgumentException">A cookie name that is not a plain name, or a field that is not a session field.</exception>
/// <param name="copiedAt">When the browser's session was copied; null when not known.</param>
/// <exception cref="ArgumentException">A field that is not a session field (the message names the field, never a value).</exception>
public SiteSessionValues(
IEnumerable<KeyValuePair<string, string>> cookies,
IEnumerable<SiteCookie> cookies,
string userAgent,
IReadOnlyDictionary<string, string>? fields = null,
IReadOnlyDictionary<string, string>? docIds = null,
IReadOnlyDictionary<string, DateTimeOffset>? expires = null)
: this(cookies, userAgent, fields, docIds, expires, Interlocked.Increment(ref s_captures))
DateTimeOffset? copiedAt = null)
: this(cookies, userAgent, fields, docIds, copiedAt, Interlocked.Increment(ref s_captures))
{
}
private SiteSessionValues(
IEnumerable<KeyValuePair<string, string>> cookies,
IEnumerable<SiteCookie> cookies,
string userAgent,
IReadOnlyDictionary<string, string>? fields,
IReadOnlyDictionary<string, string>? docIds,
IReadOnlyDictionary<string, DateTimeOffset>? expires,
DateTimeOffset? copiedAt,
long capture)
{
ArgumentNullException.ThrowIfNull(cookies);
ArgumentNullException.ThrowIfNull(userAgent);
var list = new List<KeyValuePair<string, string>>();
foreach (var (name, value) in cookies)
var list = new List<SiteCookie>();
foreach (var cookie in cookies)
{
if (!SiteCookies.IsPlainName(name))
{
throw new ArgumentException("Un nome di cookie della sessione non è un nome semplice.", nameof(cookies));
}
var index = list.FindIndex(c => c.Key == name);
ArgumentNullException.ThrowIfNull(cookie, nameof(cookies));
var index = list.FindIndex(c => c.Key == cookie.Key);
if (index >= 0)
{
list[index] = new(name, value ?? string.Empty);
list[index] = cookie;
}
else
{
list.Add(new(name, value ?? string.Empty));
list.Add(cookie);
}
}
foreach (var name in (fields ?? new Dictionary<string, string>()).Keys)
{
if (!ValueSource.SessionFields.Contains(name) || name is "user_agent" or "doc_id")
if (!StoredFields.Contains(name))
{
throw new ArgumentException($"«{name}» non è un valore della sessione (ammessi: lsd, fb_dtsg, app_id, claim, account_id).", nameof(fields));
throw new ArgumentException(
$"«{name}» non è un valore della sessione (ammessi: {string.Join(", ", StoredFields.Order(StringComparer.Ordinal))}).",
nameof(fields));
}
}
@@ -103,55 +138,65 @@ public sealed class SiteSessionValues
UserAgent = userAgent;
Fields = (fields ?? new Dictionary<string, string>()).ToFrozenDictionary(StringComparer.Ordinal);
DocIds = (docIds ?? new Dictionary<string, string>()).ToFrozenDictionary(StringComparer.Ordinal);
Expires = (expires ?? new Dictionary<string, DateTimeOffset>())
.Where(e => list.Exists(c => c.Key == e.Key))
.ToFrozenDictionary(StringComparer.Ordinal);
CopiedAt = copiedAt;
Capture = capture;
}
/// <summary>
/// The session fields read from the page (the <c>page</c> section of the catalog says where): every name of
/// <see cref="ValueSource.SessionFields"/> but <c>user_agent</c> (the browser's), <c>doc_id</c> (by operation) and
/// <c>claim</c> (set by the site).
/// </summary>
public static IReadOnlySet<string> PageFields { get; } = ValueSource.SessionFields
.Where(f => f is not ("user_agent" or "doc_id" or "claim")).ToFrozenSet(StringComparer.Ordinal);
/// <summary>The names <see cref="Fields"/> may hold: <see cref="PageFields"/> and <c>claim</c>.</summary>
public static IReadOnlySet<string> StoredFields { get; } = PageFields.Append("claim").ToFrozenSet(StringComparer.Ordinal);
/// <summary>
/// Which capture from the browser these values come from: the same through every renewal (<see cref="With"/>),
/// another for a new login. Says nothing of the account.
/// another for a new login or a new start. Says nothing of the account.
/// </summary>
public long Capture { get; }
/// <summary>Cookies of the site, by name, in order (never logged).</summary>
public IReadOnlyList<KeyValuePair<string, string>> Cookies { get; }
/// <summary>When cookies expire, by name; a cookie not listed lasts as long as the session.</summary>
public IReadOnlyDictionary<string, DateTimeOffset> Expires { get; }
/// <summary>Cookies of the site, in order (values never logged).</summary>
public IReadOnlyList<SiteCookie> Cookies { get; }
/// <summary>The user agent of Febe's browser, as it is.</summary>
public string UserAgent { get; }
/// <summary>Values of the page (<c>lsd</c>, <c>fb_dtsg</c>, <c>app_id</c>, <c>claim</c>, <c>account_id</c>).</summary>
/// <summary>Values of the page (<see cref="PageFields"/>) and the claim.</summary>
public IReadOnlyDictionary<string, string> Fields { get; }
/// <summary>The <c>doc_id</c> of each GraphQL operation, by operation name.</summary>
public IReadOnlyDictionary<string, string> DocIds { get; }
/// <summary>The value of the cookie <paramref name="name"/>, or null.</summary>
public string? Cookie(string name)
/// <summary>When the browser's session was copied; null when not known.</summary>
public DateTimeOffset? CopiedAt { get; }
/// <summary>The value of the first stored cookie named <paramref name="name"/>, whatever its domain and path, or null (tests and checks).</summary>
public string? Cookie(string name) => Cookies.FirstOrDefault(c => c.Name == name)?.Value;
/// <summary>
/// The value of the cookie <paramref name="name"/> a browser would send to <paramref name="address"/> at
/// <paramref name="now"/> (the matching one with the longest path, RFC 6265 §5.4), or null when none matches,
/// it is empty or it expired.
/// </summary>
public string? CookieFor(string name, Uri address, DateTimeOffset now) =>
CookiesFor(address, now).FirstOrDefault(c => c.Name == name)?.Value;
/// <summary>
/// The cookies a browser would send to <paramref name="address"/> at <paramref name="now"/>, in the order of the
/// <c>Cookie</c> line (RFC 6265 §5.4): longer paths first, then the stored order. No empty and no expired one.
/// </summary>
public IReadOnlyList<SiteCookie> CookiesFor(Uri address, DateTimeOffset now)
{
foreach (var (key, value) in Cookies)
{
if (key == name)
{
return value;
}
}
ArgumentNullException.ThrowIfNull(address);
return null;
// OrderByDescending is stable: cookies with paths of the same length keep the stored order.
return [.. Cookies.Where(c => c.Matches(address, now)).OrderByDescending(c => c.Path.Length)];
}
/// <summary>The value of the cookie <paramref name="name"/> the browser would still send at <paramref name="now"/>: null when missing, empty or expired.</summary>
public string? CookieAt(string name, DateTimeOffset now) =>
Cookie(name) is { Length: > 0 } value && !IsExpired(name, now) ? value : null;
/// <summary>The cookies the browser would still send at <paramref name="now"/>, in order: no empty and no expired one.</summary>
public IEnumerable<KeyValuePair<string, string>> CookiesAt(DateTimeOffset now) =>
Cookies.Where(c => c.Value.Length > 0 && !IsExpired(c.Key, now));
/// <summary>
/// The value of a session field of the catalog (<see cref="ValueSource.SessionFields"/>) for
/// <paramref name="operation"/>: <c>user_agent</c>, the <c>doc_id</c> of the operation, or a value of the page. Null
@@ -166,32 +211,24 @@ public sealed class SiteSessionValues
_ => Fields.TryGetValue(name, out var value) && value.Length > 0 ? value : null,
};
/// <summary>These values with <paramref name="update"/> applied (same <see cref="Capture"/>).</summary>
/// <summary>
/// These values with <paramref name="update"/> applied (same <see cref="Capture"/>): deleted cookies go, a renewed
/// cookie keeps its place (the browser keeps the creation time of a cookie it overwrites), a new one goes at the end.
/// </summary>
public SiteSessionValues With(SiteSessionUpdate update)
{
ArgumentNullException.ThrowIfNull(update);
var cookies = Cookies.Where(c => !update.CookiesDeleted.Contains(c.Key, StringComparer.Ordinal)).ToList();
var expires = Expires.Where(e => !update.CookiesDeleted.Contains(e.Key, StringComparer.Ordinal)).ToDictionary(StringComparer.Ordinal);
foreach (var (name, value) in update.CookiesSet)
var cookies = Cookies.Where(c => !update.CookiesDeleted.Contains(c.Key)).ToList();
foreach (var cookie in update.CookiesSet)
{
var index = cookies.FindIndex(c => c.Key == name);
var index = cookies.FindIndex(c => c.Key == cookie.Key);
if (index >= 0)
{
// Renewed in place: the browser keeps the creation time of a cookie it overwrites, so its place.
cookies[index] = new(name, value);
cookies[index] = cookie;
}
else
{
cookies.Add(new(name, value));
}
if (update.Expires.TryGetValue(name, out var until))
{
expires[name] = until;
}
else
{
expires.Remove(name);
cookies.Add(cookie);
}
}
@@ -201,11 +238,9 @@ public sealed class SiteSessionValues
fields["claim"] = claim;
}
return new SiteSessionValues(cookies, UserAgent, fields, DocIds, expires, Capture);
return new SiteSessionValues(cookies, UserAgent, fields, DocIds, CopiedAt, Capture);
}
private bool IsExpired(string name, DateTimeOffset now) => Expires.TryGetValue(name, out var until) && until <= now;
/// <summary>Counts only.</summary>
public override string ToString() => string.Create(
CultureInfo.InvariantCulture,
@@ -213,55 +248,50 @@ public sealed class SiteSessionValues
}
/// <summary>
/// What the site sent with one answer for the saved session: cookies it renewed (with their values), cookies it
/// deleted (names), a new <c>x-ig-www-claim</c>. Its text shows counts only.
/// What the site sent with one answer for the saved session: cookies it set or renewed (with their values, domains and
/// paths), cookies it deleted (their keys), a new <c>x-ig-www-claim</c>. Its text shows counts only.
/// </summary>
public sealed class SiteSessionUpdate
{
/// <param name="cookiesSet">Cookies set or renewed, in the order of the <c>Set-Cookie</c> lines (a name twice: the last value, the first place).</param>
/// <param name="cookiesDeleted">Names of the cookies deleted.</param>
/// <param name="cookiesSet">Cookies set or renewed, in the order of the <c>Set-Cookie</c> lines (the same key twice: the last value, the first place).</param>
/// <param name="cookiesDeleted">Keys of the cookies deleted.</param>
/// <param name="claim">The new claim, or null.</param>
/// <param name="expires">When the cookies set expire, by name; one not listed lasts as long as the session.</param>
/// <param name="capture">The <see cref="SiteSessionValues.Capture"/> the request was sent with; null applies to any.</param>
public SiteSessionUpdate(
IEnumerable<KeyValuePair<string, string>>? cookiesSet = null,
IEnumerable<string>? cookiesDeleted = null,
IEnumerable<SiteCookie>? cookiesSet = null,
IEnumerable<SiteCookieKey>? cookiesDeleted = null,
string? claim = null,
IReadOnlyDictionary<string, DateTimeOffset>? expires = null,
long? capture = null)
{
var set = new List<KeyValuePair<string, string>>();
foreach (var (name, value) in cookiesSet ?? [])
var set = new List<SiteCookie>();
foreach (var cookie in cookiesSet ?? [])
{
var index = set.FindIndex(c => c.Key == name);
ArgumentNullException.ThrowIfNull(cookie, nameof(cookiesSet));
var index = set.FindIndex(c => c.Key == cookie.Key);
if (index >= 0)
{
set[index] = new(name, value);
set[index] = cookie;
}
else
{
set.Add(new(name, value));
set.Add(cookie);
}
}
CookiesSet = set;
CookiesDeleted = [.. (cookiesDeleted ?? []).Distinct(StringComparer.Ordinal)];
CookiesDeleted = [.. (cookiesDeleted ?? []).Distinct()];
Claim = string.IsNullOrEmpty(claim) ? null : claim;
Expires = (expires ?? new Dictionary<string, DateTimeOffset>()).ToFrozenDictionary(StringComparer.Ordinal);
Capture = capture;
}
/// <summary>Cookies set or renewed, with their values, in the order the site set them (never logged).</summary>
public IReadOnlyList<KeyValuePair<string, string>> CookiesSet { get; }
/// <summary>When the cookies set expire, by name.</summary>
public IReadOnlyDictionary<string, DateTimeOffset> Expires { get; }
public IReadOnlyList<SiteCookie> CookiesSet { get; }
/// <summary>The capture the request was sent with: the update applies only to that one (null: to any).</summary>
public long? Capture { get; }
/// <summary>Names of the cookies the site deleted.</summary>
public IReadOnlyList<string> CookiesDeleted { get; }
/// <summary>Keys of the cookies the site deleted.</summary>
public IReadOnlyList<SiteCookieKey> CookiesDeleted { get; }
/// <summary>The new claim (<c>x-ig-set-www-claim</c>), or null.</summary>
public string? Claim { get; }
@@ -276,10 +306,10 @@ public sealed class SiteSessionUpdate
}
/// <summary>
/// The saved session in memory (issue #36, S2): for the tests, the simulation and the test site, until tappa S4 adds the
/// encrypted file. Thread-safe; every update replaces the snapshot at once.
/// The saved session in memory (issue #36, S2): for the tests and the simulation; Febe keeps it in
/// <see cref="FileSiteSession"/>. Thread-safe; every update replaces the snapshot at once.
/// </summary>
public sealed class InMemorySiteSession : ISiteSession
public sealed class InMemorySiteSession : ISavedSiteSession
{
private readonly Lock _gate = new();
private SiteSessionValues? _values;
@@ -291,6 +321,8 @@ public sealed class InMemorySiteSession : ISiteSession
/// <summary>How many non-empty updates were applied.</summary>
public int Updates => Volatile.Read(ref _updates);
public SavedSessionState State => Read() is null ? SavedSessionState.None : SavedSessionState.Present;
public SiteSessionValues? Read()
{
lock (_gate)
@@ -308,6 +340,19 @@ public sealed class InMemorySiteSession : ISiteSession
}
}
public Task<bool> ReplaceAsync(SiteSessionValues values, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(values);
Replace(values);
return Task.FromResult(true);
}
public Task DeleteAsync(CancellationToken ct)
{
Replace(null);
return Task.CompletedTask;
}
public Task UpdateAsync(SiteSessionUpdate update, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(update);
@@ -335,75 +380,3 @@ public sealed class InMemorySiteSession : ISiteSession
/// <summary>Counts only.</summary>
public override string ToString() => Read()?.ToString() ?? "Nessuna sessione salvata.";
}
/// <summary>Cookie names and the <c>Set-Cookie</c> lines of the site, read the way a browser reads them (RFC 6265).</summary>
public static class SiteCookies
{
/// <summary>True for a plain cookie name: no separator, space, quote or control character.</summary>
public static bool IsPlainName(string? name) =>
!string.IsNullOrEmpty(name) && name.Length <= 256
&& !name.Any(c => c is '=' or ';' or ',' or '"' or '\\' || char.IsWhiteSpace(c) || char.IsControl(c) || c > '\x7e');
/// <summary>
/// One <c>Set-Cookie</c> line: its name, its value as the browser keeps it (RFC 6265 §5.2: double quotes are part
/// of the value), whether it deletes the cookie (an empty value or <c>""</c>, a <c>Max-Age</c> of zero or less, an
/// <c>Expires</c> not after <paramref name="now"/>), and when it expires (null: with the session). Null for a line
/// that is not a cookie, or one for another domain than <paramref name="host"/> (a browser would refuse it).
/// </summary>
public static (string Name, string Value, bool Deletes, DateTimeOffset? Expires)? Parse(string line, string host, DateTimeOffset now)
{
ArgumentNullException.ThrowIfNull(line);
ArgumentNullException.ThrowIfNull(host);
var parts = line.Split(';');
var pair = parts[0];
var equals = pair.IndexOf('=', StringComparison.Ordinal);
if (equals <= 0)
{
return null;
}
var name = pair[..equals].Trim();
var value = pair[(equals + 1)..].Trim();
if (!IsPlainName(name))
{
return null;
}
var empty = value.Length == 0 || value == "\"\"";
DateTimeOffset? byAge = null;
DateTimeOffset? byDate = null;
foreach (var attribute in parts.Skip(1))
{
var cut = attribute.IndexOf('=', StringComparison.Ordinal);
var key = (cut < 0 ? attribute : attribute[..cut]).Trim();
var argument = cut < 0 ? string.Empty : attribute[(cut + 1)..].Trim();
if (key.Equals("max-age", StringComparison.OrdinalIgnoreCase)
&& long.TryParse(argument, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var seconds))
{
// The last Max-Age counts (RFC 6265 §5.3: attributes are read in order).
byAge = seconds <= 0 ? DateTimeOffset.MinValue
: seconds >= (DateTimeOffset.MaxValue - now).TotalSeconds ? DateTimeOffset.MaxValue
: now.AddSeconds(seconds);
}
else if (key.Equals("expires", StringComparison.OrdinalIgnoreCase)
&& DateTimeOffset.TryParse(argument, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AllowWhiteSpaces, out var expires))
{
byDate = expires;
}
else if (key.Equals("domain", StringComparison.OrdinalIgnoreCase) && argument.Length > 0)
{
var domain = argument.TrimStart('.');
if (!host.Equals(domain, StringComparison.OrdinalIgnoreCase)
&& !host.EndsWith("." + domain, StringComparison.OrdinalIgnoreCase))
{
return null;
}
}
}
// Max-Age wins over Expires (RFC 6265 §5.3 step 3).
var until = byAge ?? byDate;
var deletes = empty || until <= now;
return (name, value, deletes, deletes ? null : until);
}
}
@@ -39,8 +39,9 @@ public enum ValueSourceKind
Computed,
/// <summary>
/// Not settled yet: the request shapes show the name but not where its value comes from (a value of the page, of
/// the browser, or a name the probe removed). The site client cannot send it until it is settled (tappa S4).
/// Not settled yet: the request shapes show the name but not where its value comes from (a value the page computes
/// while it runs, a header of the browser, or a name the probe removed). The site client cannot send it, and an
/// operation that has one cannot be configured, until it is settled.
/// </summary>
Pending,
}
@@ -50,12 +51,23 @@ public enum ValueSourceKind
/// <param name="Argument">The constant, the cookie name or the session field; null for the other kinds.</param>
public sealed record ValueSource(ValueSourceKind Kind, string? Argument)
{
/// <summary>The session fields a header or field may take (§6.0, what «Ho finito» copies).</summary>
/// <summary>
/// The session fields a header or field may take (§6.0, what «Ho finito» copies): the browser's <c>user_agent</c>,
/// the <c>claim</c> the site sets, the <c>doc_id</c> of the operation, and the values of the page, which the
/// <c>page</c> section of the catalog says where to read (<see cref="PageSources"/>): <c>lsd</c>, <c>fb_dtsg</c>,
/// <c>app_id</c>, <c>account_id</c>, and since S4 <c>rev</c> (<c>__rev</c>), <c>hs</c> (<c>__hs</c>), <c>hsi</c>
/// (<c>__hsi</c>), <c>dpr</c>, <c>ccg</c> (<c>__ccg</c>), <c>comet_req</c> (<c>__comet_req</c>) and
/// <c>entry_nonce</c> (<c>x-fb-entry-nonce</c>).
/// </summary>
public static IReadOnlySet<string> SessionFields { get; } = new[]
{
"user_agent", "lsd", "fb_dtsg", "app_id", "claim", "account_id", "doc_id",
"rev", "hs", "hsi", "dpr", "ccg", "comet_req", "entry_nonce",
}.ToFrozenSet(StringComparer.Ordinal);
/// <summary>The session fields that need no <c>page</c> entry: the browser's user agent and the claim the site sets (H13).</summary>
public static IReadOnlySet<string> FieldsWithoutPage { get; } = new[] { "user_agent", "claim" }.ToFrozenSet(StringComparer.Ordinal);
/// <summary>The text form of the catalog file: <c>constant:…</c>, <c>cookie:…</c>, <c>session:…</c>, <c>operation</c>, <c>variables</c>, <c>computed</c>, <c>pending</c>.</summary>
public override string ToString() => Kind switch
{
@@ -153,11 +165,125 @@ public static class RequestRoles
role is RequestRole.PostsNext or RequestRole.TaggedNext or RequestRole.ReelsNext or RequestRole.HighlightNext or RequestRole.FollowingNext;
}
/// <summary>Where the page keeps one value of the session: a module of its <c>require</c> and a property of it.</summary>
/// <param name="Module">The module name (an identifier: letters, digits, «_», «$»).</param>
/// <param name="Property">The property of the module that holds the value (an identifier).</param>
public sealed record PageValueSource(string Module, string Property)
{
/// <summary>The form of the file: <c>Module.property</c>.</summary>
public override string ToString() => $"{Module}.{Property}";
}
/// <summary>
/// The <c>page</c> section of <c>richieste.&lt;sito&gt;.json</c> (issue #36, S4, §6.0): where the page of the site keeps
/// the values «Ho finito» copies into the saved session. The copy reads only these modules and properties, through one
/// read-only evaluation generated from them; so every name is an identifier, checked at load, and an edited file
/// cannot put code in it.
/// </summary>
/// <remarks>
/// <c>docIdModule</c> names the module of each GraphQL operation's <c>doc_id</c>, with <c>{operation}</c> for the name
/// of the operation (on Instagram <c>{operation}_instagramRelayOperation</c>, whose export is the doc_id). Each entry
/// of <c>values</c> names a session field of <see cref="SiteSessionValues.PageFields"/> and its
/// <c>Module.property</c>. A configured operation that sends a <c>session:</c> value with no source here is refused at
/// load (rule 9: a value whose place in the page is not known is not guessed).
/// </remarks>
public sealed partial class PageSources
{
/// <summary>The placeholder of <see cref="DocIdModule"/>.</summary>
public const string OperationPlaceholder = "{operation}";
internal PageSources(string? docIdModule, IReadOnlyDictionary<string, PageValueSource> values, IReadOnlyList<string> order)
{
DocIdModule = docIdModule;
Values = values;
Order = order;
}
/// <summary>The module name of a <c>doc_id</c>, with <see cref="OperationPlaceholder"/>; null when the page gives none.</summary>
public string? DocIdModule { get; }
/// <summary>Where each page value of the session is, by session field.</summary>
public IReadOnlyDictionary<string, PageValueSource> Values { get; }
/// <summary>The fields of <see cref="Values"/> in the order of the file.</summary>
public IReadOnlyList<string> Order { get; }
/// <summary>The module that holds the <c>doc_id</c> of <paramref name="operation"/>, or null when there is none or the result is not an identifier.</summary>
public string? DocIdModuleFor(string operation)
{
ArgumentNullException.ThrowIfNull(operation);
if (DocIdModule is null)
{
return null;
}
var module = DocIdModule.Replace(OperationPlaceholder, operation, StringComparison.Ordinal);
return IsIdentifier(module) ? module : null;
}
/// <summary>True for a name the copy may write in its expression: <c>^[A-Za-z_$][A-Za-z0-9_$]*$</c>, at most 128 characters.</summary>
public static bool IsIdentifier(string? name) => name is not null && Identifier().IsMatch(name);
/// <summary>Names and counts only.</summary>
public override string ToString() => string.Create(
CultureInfo.InvariantCulture,
$"Sezione page: {Values.Count} valori{(DocIdModule is null ? string.Empty : ", doc_id da " + DocIdModule)}.");
/// <summary>Reads the section; every name checked.</summary>
internal static PageSources? Parse(PageDto? dto, string where)
{
if (dto is null)
{
return null;
}
where = $"{where}, sezione «page»";
string? docIdModule = null;
if (dto.DocIdModule is not null)
{
docIdModule = dto.DocIdModule.Trim();
var at = docIdModule.IndexOf(OperationPlaceholder, StringComparison.Ordinal);
if (at < 0 || docIdModule.IndexOf(OperationPlaceholder, at + 1, StringComparison.Ordinal) >= 0
|| !IsIdentifier(docIdModule.Replace(OperationPlaceholder, "x", StringComparison.Ordinal)))
{
throw new InvalidDataException($"{where}: «docIdModule» è un nome di modulo con «{OperationPlaceholder}» una volta sola e altrimenti solo lettere, cifre, «_» e «$».");
}
}
var values = new Dictionary<string, PageValueSource>(StringComparer.Ordinal);
var order = new List<string>();
foreach (var (field, text) in dto.Values ?? new Dictionary<string, string?>())
{
if (!SiteSessionValues.PageFields.Contains(field))
{
throw new InvalidDataException(
$"{where}: «{field}» non è un valore della pagina (ammessi: {string.Join(", ", SiteSessionValues.PageFields.Order(StringComparer.Ordinal))}; user_agent, claim e doc_id non stanno qui).");
}
var dot = text?.IndexOf('.', StringComparison.Ordinal) ?? -1;
var module = dot > 0 ? text![..dot] : null;
var property = dot > 0 ? text![(dot + 1)..] : null;
if (!IsIdentifier(module) || !IsIdentifier(property))
{
throw new InvalidDataException($"{where}: il valore «{field}» si scrive «Modulo.proprietà», con nomi fatti solo di lettere, cifre, «_» e «$».");
}
values[field] = new PageValueSource(module!, property!);
order.Add(field);
}
return new PageSources(docIdModule, values.ToFrozenDictionary(StringComparer.Ordinal), order);
}
[GeneratedRegex(@"^[A-Za-z_$][A-Za-z0-9_$]{0,127}$", RegexOptions.CultureInvariant)]
private static partial Regex Identifier();
}
/// <summary>
/// One operation of <c>richieste.&lt;sito&gt;.json</c>: what the site client may ask (issue #36, spec §6.0). Written from
/// the real request shapes of <c>febe-sonda richieste</c> (§14.5) and documented by a cleaned sample of its answer
/// (rule 9). It holds no value of a session: the <c>doc_id</c> of a GraphQL query, the tokens and the account are read
/// from the page at login (tappa S4) and named here only by their source.
/// from the page at login (tappa S4, the <c>page</c> section) and named here only by their source.
/// </summary>
public sealed partial class SiteOperation
{
@@ -433,9 +559,10 @@ public sealed partial class RequestCatalog
private readonly FrozenDictionary<string, SiteOperation> _byName;
private readonly FrozenDictionary<RequestRole, SiteOperation> _byRole;
private RequestCatalog(string site, IReadOnlyList<SiteOperation> operations, string? source)
private RequestCatalog(string site, IReadOnlyList<SiteOperation> operations, PageSources? page, string? source)
{
Site = site;
Page = page;
Operations = operations;
Source = source ?? $"richieste.{site}.json";
_byName = operations.ToFrozenDictionary(o => o.Name, StringComparer.Ordinal);
@@ -448,6 +575,9 @@ public sealed partial class RequestCatalog
/// <summary>Every operation, in the order of the file.</summary>
public IReadOnlyList<SiteOperation> Operations { get; }
/// <summary>Where the page keeps the session values «Ho finito» copies (the <c>page</c> section); null when the file has none.</summary>
public PageSources? Page { get; }
/// <summary>Where it came from (file path or embedded name), for messages.</summary>
public string Source { get; }
@@ -506,13 +636,14 @@ public sealed partial class RequestCatalog
throw new InvalidDataException($"{name}: manca l'elenco «operations».");
}
var page = PageSources.Parse(file.Page, name);
var operations = new List<SiteOperation>(file.Operations.Count);
var names = new HashSet<string>(StringComparer.Ordinal);
var roleHolders = new Dictionary<RequestRole, string>();
for (var i = 0; i < file.Operations.Count; i++)
{
var dto = file.Operations[i] ?? throw new InvalidDataException($"{name}, operazione {(i + 1).ToString(CultureInfo.InvariantCulture)}: voce vuota.");
var operation = ToOperation(dto, $"{name}, operazione {(i + 1).ToString(CultureInfo.InvariantCulture)}");
var operation = ToOperation(dto, $"{name}, operazione {(i + 1).ToString(CultureInfo.InvariantCulture)}", page);
if (!names.Add(operation.Name))
{
throw new InvalidDataException($"{name}: l'operazione «{operation.Name}» compare due volte.");
@@ -529,7 +660,7 @@ public sealed partial class RequestCatalog
operations.Add(operation);
}
return new RequestCatalog(file.Site.Trim(), operations, source);
return new RequestCatalog(file.Site.Trim(), operations, page, source);
}
/// <summary>Why the code refuses an operation with this name, whatever the file says; null when it does not.</summary>
@@ -606,7 +737,7 @@ public sealed partial class RequestCatalog
return null;
}
private static SiteOperation ToOperation(OperationDto dto, string where)
private static SiteOperation ToOperation(OperationDto dto, string where, PageSources? page)
{
if (string.IsNullOrWhiteSpace(dto.Name))
{
@@ -806,6 +937,19 @@ public sealed partial class RequestCatalog
{
throw new InvalidDataException($"{where}: un'operazione configurata dice il campione della risposta («sample») e i campi attesi («rootFields»).");
}
// A value of the session the copy at «Ho finito» does not know where to read would be missing, or guessed
// (rule 9): the page section names a module for every one, a doc_id module for a GraphQL query.
foreach (var field in headers.Values.Concat(body.Values).Where(v => v.Kind == ValueSourceKind.Session).Select(v => v.Argument!).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal))
{
var known = field == "doc_id"
? page?.DocIdModuleFor(name) is not null
: ValueSource.FieldsWithoutPage.Contains(field) || page?.Values.ContainsKey(field) == true;
if (!known)
{
throw new InvalidDataException($"{where}: il valore session:{field} non ha un modulo nella sezione «page»: non può essere configurata finché non si sa dove la pagina lo tiene (regola 9).");
}
}
}
else if (reason is null)
{
@@ -1030,9 +1174,20 @@ internal sealed class CatalogFile
public string? Note { get; set; }
public PageDto? Page { get; set; }
public List<OperationDto?>? Operations { get; set; }
}
internal sealed class PageDto
{
public string? DocIdModule { get; set; }
public Dictionary<string, string?>? Values { get; set; }
public string? Note { get; set; }
}
internal sealed class OperationDto
{
public string? Name { get; set; }
@@ -0,0 +1,124 @@
using System.Security.Cryptography;
using System.Text.Json;
namespace Febe.Core.Collection.Requests;
/// <summary>
/// The plain form of the saved session before it is encrypted (issue #36, S4, §13.2): UTF-8 JSON with English keys,
/// <c>{"format":1,"copiedAt":…,"userAgent":…,"cookies":[{name,value,domain,hostOnly,path,secure,httpOnly,expires}],"fields":{…},"docIds":{…}}</c>.
/// The capture id is not kept: values read back count as a new capture, so a late answer of the process before can
/// never touch them.
/// </summary>
internal static class SavedSessionFile
{
/// <summary>The format version.</summary>
public const int Format = 1;
/// <summary>The JSON of <paramref name="values"/>; the caller zeroes it once encrypted.</summary>
public static byte[] Serialize(SiteSessionValues values)
{
ArgumentNullException.ThrowIfNull(values);
using var buffer = new MemoryStream();
using (var writer = new Utf8JsonWriter(buffer))
{
writer.WriteStartObject();
writer.WriteNumber("format", Format);
if (values.CopiedAt is { } copiedAt)
{
writer.WriteString("copiedAt", copiedAt);
}
writer.WriteString("userAgent", values.UserAgent);
writer.WriteStartArray("cookies");
foreach (var cookie in values.Cookies)
{
writer.WriteStartObject();
writer.WriteString("name", cookie.Name);
writer.WriteString("value", cookie.Value);
writer.WriteString("domain", cookie.Domain);
writer.WriteBoolean("hostOnly", cookie.HostOnly);
writer.WriteString("path", cookie.Path);
writer.WriteBoolean("secure", cookie.Secure);
writer.WriteBoolean("httpOnly", cookie.HttpOnly);
if (cookie.Expires is { } expires)
{
writer.WriteString("expires", expires);
}
writer.WriteEndObject();
}
writer.WriteEndArray();
WriteMap(writer, "fields", values.Fields);
WriteMap(writer, "docIds", values.DocIds);
writer.WriteEndObject();
}
var bytes = buffer.ToArray();
CryptographicOperations.ZeroMemory(buffer.GetBuffer());
return bytes;
}
/// <summary>The values of <paramref name="json"/>, as a new capture.</summary>
/// <exception cref="InvalidDataException">Not the format of Febe, or a cookie or field it would refuse; the message names no value.</exception>
public static SiteSessionValues Deserialize(ReadOnlySpan<byte> json)
{
try
{
using var document = JsonDocument.Parse(json.ToArray(), new JsonDocumentOptions { MaxDepth = 8 });
var root = document.RootElement;
if (root.ValueKind != JsonValueKind.Object || !root.TryGetProperty("format", out var format) || format.GetInt32() != Format)
{
throw new InvalidDataException("Sessione salvata in un formato che Febe non conosce.");
}
var cookies = new List<SiteCookie>();
foreach (var item in root.GetProperty("cookies").EnumerateArray())
{
cookies.Add(new SiteCookie(
item.GetProperty("name").GetString()!,
item.GetProperty("value").GetString()!,
item.GetProperty("domain").GetString()!,
item.GetProperty("path").GetString()!,
item.GetProperty("hostOnly").GetBoolean(),
item.GetProperty("secure").GetBoolean(),
item.GetProperty("httpOnly").GetBoolean(),
item.TryGetProperty("expires", out var expires) ? expires.GetDateTimeOffset() : null));
}
return new SiteSessionValues(
cookies,
root.GetProperty("userAgent").GetString()!,
ReadMap(root.GetProperty("fields")),
ReadMap(root.GetProperty("docIds")),
root.TryGetProperty("copiedAt", out var copiedAt) ? copiedAt.GetDateTimeOffset() : null);
}
catch (Exception ex) when (ex is JsonException or KeyNotFoundException or InvalidOperationException or FormatException or ArgumentException)
{
// The texts of these exceptions may quote the file: none is passed on.
throw new InvalidDataException("Sessione salvata non leggibile: il contenuto non è quello che Febe scrive.");
}
}
private static void WriteMap(Utf8JsonWriter writer, string name, IReadOnlyDictionary<string, string> map)
{
writer.WriteStartObject(name);
foreach (var (key, value) in map.OrderBy(p => p.Key, StringComparer.Ordinal))
{
writer.WriteString(key, value);
}
writer.WriteEndObject();
}
private static Dictionary<string, string> ReadMap(JsonElement element)
{
var map = new Dictionary<string, string>(StringComparer.Ordinal);
foreach (var property in element.EnumerateObject())
{
map[property.Name] = property.Value.GetString() ?? throw new InvalidDataException("Valore vuoto.");
}
return map;
}
}
@@ -0,0 +1,346 @@
using System.Globalization;
using System.Net;
namespace Febe.Core.Collection.Requests;
/// <summary>
/// One cookie of the saved session as the browser keeps it (issue #36, S4, RFC 6265 §5.3): name, value, domain and
/// path, whether it is host-only, secure or HTTP-only, and when it expires. The site client sends it only to an address
/// whose host and path match and, when it is secure, only over https (<see cref="Matches"/>).
/// </summary>
/// <remarks>
/// A class, not a record: its text (<see cref="ToString"/>) names the cookie, its domain and path, never the value
/// (rule 10). Its identity is name, domain, path and host-only (<see cref="Key"/>), as Chromium keeps it: a host-only
/// cookie of <c>www.instagram.com</c> and a cookie with <c>Domain=www.instagram.com</c> are two cookies.
/// </remarks>
public sealed class SiteCookie
{
/// <param name="name">A plain cookie name (<see cref="SiteCookies.IsPlainName"/>).</param>
/// <param name="value">The value as the browser keeps it, quotes included (<see cref="SiteCookies.IsSendableValue"/>).</param>
/// <param name="domain">The host (host-only) or the domain it is sent to; stored lower-case without the leading dot.</param>
/// <param name="path">The path it is sent under; starts with «/».</param>
/// <param name="hostOnly">True when it goes only to the host <paramref name="domain"/>, not to its subdomains.</param>
/// <param name="secure">True when it goes only over https.</param>
/// <param name="httpOnly">True when the page cannot read it (kept for the record; the client sends it the same).</param>
/// <param name="expires">When it expires; null: it lasts as long as the session.</param>
/// <exception cref="ArgumentException">A name, value, domain or path a browser would not keep; the message names no value.</exception>
public SiteCookie(string name, string value, string domain, string path = "/", bool hostOnly = true, bool secure = false, bool httpOnly = false, DateTimeOffset? expires = null)
{
if (!SiteCookies.IsPlainName(name))
{
throw new ArgumentException("Un nome di cookie della sessione non è un nome semplice.", nameof(name));
}
ArgumentNullException.ThrowIfNull(value);
if (!SiteCookies.IsSendableValue(value))
{
throw new ArgumentException($"Il valore del cookie «{name}» ha caratteri che un browser non manda.", nameof(value));
}
var normalized = SiteCookies.NormalizeDomain(domain)
?? throw new ArgumentException($"Il dominio del cookie «{name}» non è un nome di host.", nameof(domain));
if (!SiteCookies.IsCookiePath(path))
{
throw new ArgumentException($"Il percorso del cookie «{name}» non comincia con «/» o ha caratteri non ammessi.", nameof(path));
}
Name = name;
Value = value;
Domain = normalized;
Path = path;
HostOnly = hostOnly;
Secure = secure;
HttpOnly = httpOnly;
Expires = expires;
}
/// <summary>The name.</summary>
public string Name { get; }
/// <summary>The value, as the browser keeps it (never logged).</summary>
public string Value { get; }
/// <summary>The host (host-only) or the domain, lower-case, without the leading dot.</summary>
public string Domain { get; }
/// <summary>The path, starting with «/».</summary>
public string Path { get; }
/// <summary>True when it goes only to the host <see cref="Domain"/>.</summary>
public bool HostOnly { get; }
/// <summary>True when it goes only over https.</summary>
public bool Secure { get; }
/// <summary>True when the page cannot read it.</summary>
public bool HttpOnly { get; }
/// <summary>When it expires; null: with the session.</summary>
public DateTimeOffset? Expires { get; }
/// <summary>Its identity in the store: a cookie with the same key replaces it.</summary>
public SiteCookieKey Key => new(Name, Domain, Path, HostOnly);
/// <summary>A host-only cookie for <paramref name="host"/> (tests and the test site).</summary>
public static SiteCookie ForHost(string name, string value, string host, string path = "/", bool secure = false, DateTimeOffset? expires = null) =>
new(name, value, host, path, hostOnly: true, secure: secure, expires: expires);
/// <summary>True when it has expired at <paramref name="now"/>.</summary>
public bool IsExpired(DateTimeOffset now) => Expires is { } until && until <= now;
/// <summary>
/// True when a browser would send it with a request to <paramref name="address"/> at <paramref name="now"/>: the
/// host domain-matches (host-only: the same host), the path path-matches (RFC 6265 §5.1.3, §5.1.4), a secure
/// cookie only over https, not expired and not empty.
/// </summary>
public bool Matches(Uri address, DateTimeOffset now)
{
ArgumentNullException.ThrowIfNull(address);
if (!address.IsAbsoluteUri || Value.Length == 0 || IsExpired(now))
{
return false;
}
if (Secure && address.Scheme != Uri.UriSchemeHttps)
{
return false;
}
return SiteCookies.DomainMatches(SiteCookies.HostOf(address), Domain, HostOnly)
&& SiteCookies.PathMatches(address.AbsolutePath, Path);
}
/// <summary>The same cookie with another value and expiry (a renewal keeps everything else).</summary>
internal SiteCookie WithValue(string value, DateTimeOffset? expires) =>
new(Name, value, Domain, Path, HostOnly, Secure, HttpOnly, expires);
/// <summary>Name, domain and path: never the value.</summary>
public override string ToString() => string.Create(
CultureInfo.InvariantCulture,
$"Cookie «{Name}» ({(HostOnly ? string.Empty : ".")}{Domain}{Path}{(Secure ? ", sicuro" : string.Empty)})");
}
/// <summary>The identity of a cookie in the store (RFC 6265 §5.3 step 11, plus host-only as Chromium keeps it). Holds no value.</summary>
/// <param name="Name">The name.</param>
/// <param name="Domain">The domain, lower-case, without the leading dot.</param>
/// <param name="Path">The path.</param>
/// <param name="HostOnly">True for a host-only cookie.</param>
public readonly record struct SiteCookieKey(string Name, string Domain, string Path, bool HostOnly);
/// <summary>
/// One <c>Set-Cookie</c> line read as a browser reads it: the cookie it sets (domain and path resolved against the
/// request), or the key of the cookie it deletes. Its text shows the name only.
/// </summary>
public sealed class SetCookieLine
{
internal SetCookieLine(SiteCookie cookie, bool deletes)
{
Cookie = cookie;
Deletes = deletes;
}
/// <summary>The cookie as the line sets it (for a deletion only its <see cref="SiteCookie.Key"/> counts; no expiry).</summary>
public SiteCookie Cookie { get; }
/// <summary>True when the line deletes the cookie (empty value, <c>Max-Age</c> of zero or less, an <c>Expires</c> not later than now).</summary>
public bool Deletes { get; }
/// <summary>Name and what the line does, never the value.</summary>
public override string ToString() => $"Set-Cookie «{Cookie.Name}»{(Deletes ? " (cancella)" : string.Empty)}";
}
/// <summary>Cookie names and the <c>Set-Cookie</c> lines of the site, read the way a browser reads them (RFC 6265).</summary>
public static class SiteCookies
{
/// <summary>True for a plain cookie name: no separator, space, quote or control character.</summary>
public static bool IsPlainName(string? name) =>
!string.IsNullOrEmpty(name) && name.Length <= 256
&& !name.Any(c => c is '=' or ';' or ',' or '"' or '\\' || char.IsWhiteSpace(c) || char.IsControl(c) || c > '\x7e');
/// <summary>
/// True for a value a browser sends back as it is: ASCII, no control character and no «;» (the separator of the
/// <c>Cookie</c> line). Quotes and backslashes stay part of the value (RFC 6265 §5.2).
/// </summary>
public static bool IsSendableValue(string? value) =>
value is not null && value.Length <= 4096 && !value.Any(c => c is ';' || c < ' ' || c > '\x7e');
/// <summary>The domain as the store keeps it (lower-case, no leading dot), or null when it is not a host name or address.</summary>
public static string? NormalizeDomain(string? domain)
{
if (string.IsNullOrWhiteSpace(domain))
{
return null;
}
var trimmed = domain.Trim().TrimStart('.').ToLowerInvariant();
if (trimmed.StartsWith('[') && trimmed.EndsWith(']'))
{
trimmed = trimmed[1..^1];
}
return trimmed.Length is > 0 and <= 253 && trimmed.All(c => char.IsAsciiLetterOrDigit(c) || c is '.' or '-' or '_' or ':')
? trimmed
: null;
}
/// <summary>True for a cookie path: starts with «/», no control character and no «;».</summary>
public static bool IsCookiePath(string? path) =>
!string.IsNullOrEmpty(path) && path[0] == '/' && path.Length <= 1024 && !path.Any(c => c is ';' || c < ' ' || c == '\x7f');
/// <summary>The host of <paramref name="address"/> as cookies compare it: lower-case, IPv6 without brackets.</summary>
public static string HostOf(Uri address)
{
ArgumentNullException.ThrowIfNull(address);
return address.IdnHost.Trim('[', ']').ToLowerInvariant();
}
/// <summary>
/// RFC 6265 §5.1.3: a host-only cookie goes to its host only; a domain cookie to the domain and its subdomains, never
/// by suffix to an IP address.
/// </summary>
public static bool DomainMatches(string host, string domain, bool hostOnly)
{
ArgumentNullException.ThrowIfNull(host);
ArgumentNullException.ThrowIfNull(domain);
if (host.Equals(domain, StringComparison.OrdinalIgnoreCase))
{
return true;
}
return !hostOnly
&& !IPAddress.TryParse(host, out _)
&& host.EndsWith("." + domain, StringComparison.OrdinalIgnoreCase);
}
/// <summary>RFC 6265 §5.1.4: the request path is the cookie path, or starts with it at a «/».</summary>
public static bool PathMatches(string requestPath, string cookiePath)
{
ArgumentNullException.ThrowIfNull(requestPath);
ArgumentNullException.ThrowIfNull(cookiePath);
var path = requestPath.Length == 0 ? "/" : requestPath;
if (path == cookiePath)
{
return true;
}
return path.StartsWith(cookiePath, StringComparison.Ordinal)
&& (cookiePath.EndsWith('/') || path[cookiePath.Length] == '/');
}
/// <summary>RFC 6265 §5.1.4: the path a cookie without a <c>Path</c> takes from the request (up to the last «/», excluded).</summary>
public static string DefaultPath(Uri address)
{
ArgumentNullException.ThrowIfNull(address);
var path = address.AbsolutePath;
if (path.Length == 0 || path[0] != '/')
{
return "/";
}
var last = path.LastIndexOf('/');
return last <= 0 ? "/" : path[..last];
}
/// <summary>
/// One <c>Set-Cookie</c> line of an answer to <paramref name="request"/>: name, value as the browser keeps it
/// (RFC 6265 §5.2: double quotes are part of the value), domain (the <c>Domain</c> attribute, or host-only on the
/// request host), path (the <c>Path</c> attribute when it starts with «/», otherwise the default path of the request),
/// <c>Secure</c>, <c>HttpOnly</c>, and when it expires; whether it deletes the cookie (an empty value or <c>""</c>, a
/// <c>Max-Age</c> of zero or less, an <c>Expires</c> not after <paramref name="now"/>). Null for a line that is not a
/// cookie, one for a domain the request host does not domain-match (a browser would refuse it), or a value a
/// browser would not send back.
/// </summary>
public static SetCookieLine? Parse(string line, Uri request, DateTimeOffset now)
{
ArgumentNullException.ThrowIfNull(line);
ArgumentNullException.ThrowIfNull(request);
var host = HostOf(request);
var parts = line.Split(';');
var pair = parts[0];
var equals = pair.IndexOf('=', StringComparison.Ordinal);
if (equals <= 0)
{
return null;
}
var name = pair[..equals].Trim();
var value = pair[(equals + 1)..].Trim();
if (!IsPlainName(name) || !IsSendableValue(value))
{
return null;
}
var empty = value.Length == 0 || value == "\"\"";
DateTimeOffset? byAge = null;
DateTimeOffset? byDate = null;
string? domain = null;
string? path = null;
var secure = false;
var httpOnly = false;
foreach (var attribute in parts.Skip(1))
{
var cut = attribute.IndexOf('=', StringComparison.Ordinal);
var key = (cut < 0 ? attribute : attribute[..cut]).Trim();
var argument = cut < 0 ? string.Empty : attribute[(cut + 1)..].Trim();
if (key.Equals("max-age", StringComparison.OrdinalIgnoreCase)
&& long.TryParse(argument, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var seconds))
{
// The last Max-Age counts (RFC 6265 §5.3: attributes are read in order).
byAge = seconds <= 0 ? DateTimeOffset.MinValue
: seconds >= (DateTimeOffset.MaxValue - now).TotalSeconds ? DateTimeOffset.MaxValue
: now.AddSeconds(seconds);
}
else if (key.Equals("expires", StringComparison.OrdinalIgnoreCase)
&& DateTimeOffset.TryParse(argument, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AllowWhiteSpaces, out var expires))
{
byDate = expires;
}
else if (key.Equals("domain", StringComparison.OrdinalIgnoreCase))
{
// RFC 6265 §5.2.3: an empty Domain is ignored; the last one counts.
if (argument.Length > 0)
{
domain = NormalizeDomain(argument) ?? string.Empty;
}
}
else if (key.Equals("path", StringComparison.OrdinalIgnoreCase))
{
// §5.2.4: a Path that does not start with «/» is the default path.
path = argument.StartsWith('/') ? argument : null;
}
else if (key.Equals("secure", StringComparison.OrdinalIgnoreCase))
{
secure = true;
}
else if (key.Equals("httponly", StringComparison.OrdinalIgnoreCase))
{
httpOnly = true;
}
}
var hostOnly = domain is null;
if (domain is not null)
{
// A Domain the host does not domain-match, or an IP address set as a wider domain, a browser refuses; a
// single label other than the host (Domain=com) is a public suffix and refused too.
if (domain.Length == 0
|| !DomainMatches(host, domain, hostOnly: false)
|| (!domain.Contains('.', StringComparison.Ordinal) && domain != host))
{
return null;
}
}
path ??= DefaultPath(request);
if (!IsCookiePath(path))
{
return null;
}
// Max-Age wins over Expires (RFC 6265 §5.3 step 3).
var until = byAge ?? byDate;
var deletes = empty || until <= now;
var cookie = new SiteCookie(name, value, domain ?? host, path, hostOnly, secure, httpOnly, deletes ? null : until);
return new SetCookieLine(cookie, deletes);
}
}
+85 -68
View File
@@ -1,6 +1,23 @@
{
"site": "instagram",
"note": "Operazioni che il client del sito può chiedere a Instagram (issue #36, specifica §6.0). Scritte il 16 novembre 2026 dalle forme reali delle richieste ricavate con «febe-sonda richieste» dai file HAR del 12 novembre (con e senza scorrimento) e del 16 novembre, fuori dal repository e senza valori; le risposte sono documentate dai campioni ripuliti di tests/Febe.Tests/campioni/instagram (regola 9). Solo letture: il codice rifiuta ogni «Mutation», la telemetria, la navigazione della pagina e le famiglie di chat, messaggi, presenza e promozioni, anche se una copia modificata le elencasse. Nessun doc_id qui: si legge dai moduli della pagina all'accesso (tappa S4). Fonti dei valori: constant (dalle forme), cookie:csrftoken, session:… (copiato a «Ho finito»: user_agent, lsd, fb_dtsg, app_id, claim, account_id, doc_id), operation, variables, computed, pending (nome noto, fonte ancora da stabilire: tappa S4). Le forme scrivono i vero/falso del JSON come true/false, ma non distinguono un numero da un testo di cifre: i numeri delle variabili (count 12, first 3) sono scritti come numeri, da confermare. «(nome tolto)» e «(valore tolto)» sono ciò che la sonda non mostra: un'operazione che li ha nelle variabili resta non configurata. L'elenco dei seguiti manca: nessuna forma con la risposta.",
"note": "Operazioni che il client del sito può chiedere a Instagram (issue #36, specifica §6.0). Scritte il 16 novembre 2026 dalle forme reali delle richieste ricavate con «febe-sonda richieste» dai file HAR del 12 novembre (con e senza scorrimento) e del 16 novembre, fuori dal repository e senza valori; le risposte sono documentate dai campioni ripuliti di tests/Febe.Tests/campioni/instagram (regola 9). Solo letture: il codice rifiuta ogni «Mutation», la telemetria, la navigazione della pagina e le famiglie di chat, messaggi, presenza e promozioni, anche se una copia modificata le elencasse. Nessun doc_id né altro valore qui: la sezione «page» dice in quale modulo della pagina si trova ciascuno, e «Ho finito» li copia nella sessione salvata (tappa S4). I posti della sezione «page» vengono dal codice pubblico della pagina del HAR, solo forme e nomi: __rev da SiteData.client_revision, __hs da SiteData.haste_session, __hsi da SiteData.hsi, dpr da SiteData.pr, __comet_req da SiteData.comet_env, __ccg da WebConnectionClassServerGuess.connectionClass, x-fb-entry-nonce da BootloaderConfig.nonce, i doc_id dal modulo «<operazione>_instagramRelayOperation»; dpr e __comet_req erano costanti (1 e 7) e ora si leggono dalla pagina. Fonti dei valori: constant (dalle forme), cookie:csrftoken, session:… (copiato a «Ho finito»: user_agent, claim, doc_id e i valori della sezione «page»: lsd, fb_dtsg, app_id, account_id, rev, hs, hsi, dpr, ccg, comet_req, entry_nonce), operation, variables, computed, pending (nome noto, fonte da stabilire: valori che la pagina calcola mentre gira come __req, __s, __dyn, __csr, __hblp, __hsdp, __sjsp, __crn, __d e __spin_r/__spin_b/__spin_t, le intestazioni del browser come referer, priority e sec-ch-ua, e i nomi tolti dalla sonda). Un'operazione configurata con un valore session:… senza posto nella sezione «page» è rifiutata. Le forme scrivono i vero/falso del JSON come true/false, ma non distinguono un numero da un testo di cifre: i numeri delle variabili (count 12, first 3) sono scritti come numeri, da confermare. «(nome tolto)» e «(valore tolto)» sono ciò che la sonda non mostra: un'operazione che li ha nelle variabili resta non configurata. L'elenco dei seguiti manca: nessuna forma con la risposta.",
"page": {
"note": "Dove la pagina tiene i valori della sessione: «Modulo.proprietà» del require della pagina; docIdModule con {operation} per il nome dell'operazione. Solo nomi, nessun valore.",
"docIdModule": "{operation}_instagramRelayOperation",
"values": {
"lsd": "LSD.token",
"fb_dtsg": "DTSGInitialData.token",
"account_id": "CurrentUserInitialData.USER_ID",
"app_id": "CurrentUserInitialData.APP_ID",
"rev": "SiteData.client_revision",
"hs": "SiteData.haste_session",
"hsi": "SiteData.hsi",
"dpr": "SiteData.pr",
"comet_req": "SiteData.comet_env",
"ccg": "WebConnectionClassServerGuess.connectionClass",
"entry_nonce": "BootloaderConfig.nonce"
}
},
"operations": [
{
"name": "PolarisSearchBoxRefetchableQuery",
@@ -26,7 +43,7 @@
"user-agent": "session:user_agent",
"x-asbd-id": "constant:359341",
"x-csrftoken": "cookie:csrftoken",
"x-fb-entry-nonce": "pending",
"x-fb-entry-nonce": "session:entry_nonce",
"x-fb-friendly-name": "operation",
"x-fb-lsd": "session:lsd",
"x-ig-app-id": "session:app_id",
@@ -35,18 +52,18 @@
"body": {
"(nome tolto)": "pending",
"__a": "constant:1",
"__ccg": "pending",
"__comet_req": "constant:7",
"__ccg": "session:ccg",
"__comet_req": "session:comet_req",
"__crn": "pending",
"__csr": "pending",
"__d": "pending",
"__dyn": "pending",
"__hblp": "pending",
"__hs": "pending",
"__hs": "session:hs",
"__hsdp": "pending",
"__hsi": "pending",
"__hsi": "session:hsi",
"__req": "pending",
"__rev": "pending",
"__rev": "session:rev",
"__s": "pending",
"__sjsp": "pending",
"__spin_b": "pending",
@@ -55,7 +72,7 @@
"__user": "session:account_id",
"av": "session:account_id",
"doc_id": "session:doc_id",
"dpr": "constant:1",
"dpr": "session:dpr",
"fb_api_caller_class": "constant:RelayModern",
"fb_api_req_friendly_name": "operation",
"fb_dtsg": "session:fb_dtsg",
@@ -108,7 +125,7 @@
"user-agent": "session:user_agent",
"x-asbd-id": "constant:359341",
"x-csrftoken": "cookie:csrftoken",
"x-fb-entry-nonce": "pending",
"x-fb-entry-nonce": "session:entry_nonce",
"x-fb-friendly-name": "operation",
"x-fb-lsd": "session:lsd",
"x-ig-app-id": "session:app_id",
@@ -117,18 +134,18 @@
"body": {
"(nome tolto)": "pending",
"__a": "constant:1",
"__ccg": "pending",
"__comet_req": "constant:7",
"__ccg": "session:ccg",
"__comet_req": "session:comet_req",
"__crn": "pending",
"__csr": "pending",
"__d": "pending",
"__dyn": "pending",
"__hblp": "pending",
"__hs": "pending",
"__hs": "session:hs",
"__hsdp": "pending",
"__hsi": "pending",
"__hsi": "session:hsi",
"__req": "pending",
"__rev": "pending",
"__rev": "session:rev",
"__s": "pending",
"__sjsp": "pending",
"__spin_b": "pending",
@@ -137,7 +154,7 @@
"__user": "session:account_id",
"av": "session:account_id",
"doc_id": "session:doc_id",
"dpr": "constant:1",
"dpr": "session:dpr",
"fb_api_caller_class": "constant:RelayModern",
"fb_api_req_friendly_name": "operation",
"fb_dtsg": "session:fb_dtsg",
@@ -186,7 +203,7 @@
"user-agent": "session:user_agent",
"x-asbd-id": "constant:359341",
"x-csrftoken": "cookie:csrftoken",
"x-fb-entry-nonce": "pending",
"x-fb-entry-nonce": "session:entry_nonce",
"x-fb-friendly-name": "operation",
"x-fb-lsd": "session:lsd",
"x-ig-app-id": "session:app_id",
@@ -195,18 +212,18 @@
"body": {
"(nome tolto)": "pending",
"__a": "constant:1",
"__ccg": "pending",
"__comet_req": "constant:7",
"__ccg": "session:ccg",
"__comet_req": "session:comet_req",
"__crn": "pending",
"__csr": "pending",
"__d": "pending",
"__dyn": "pending",
"__hblp": "pending",
"__hs": "pending",
"__hs": "session:hs",
"__hsdp": "pending",
"__hsi": "pending",
"__hsi": "session:hsi",
"__req": "pending",
"__rev": "pending",
"__rev": "session:rev",
"__s": "pending",
"__sjsp": "pending",
"__spin_b": "pending",
@@ -215,7 +232,7 @@
"__user": "session:account_id",
"av": "session:account_id",
"doc_id": "session:doc_id",
"dpr": "constant:1",
"dpr": "session:dpr",
"fb_api_caller_class": "constant:RelayModern",
"fb_api_req_friendly_name": "operation",
"fb_dtsg": "session:fb_dtsg",
@@ -253,7 +270,7 @@
"category": "storico",
"roles": ["reels"],
"configured": false,
"reason": "le variabili sono note, ma intestazioni e campi della pagina e del browser (come __dyn, __csr, referer, sec-ch-ua e quello con il nome tolto dalla sonda) hanno ancora la fonte «pending»: finché non si sa da dove vengono i valori la richiesta non si scrive (regola 9, tappa S4)",
"reason": "le variabili sono note, ma intestazioni e campi della pagina e del browser (come __dyn, __csr, referer, sec-ch-ua e quello con il nome tolto dalla sonda) hanno ancora la fonte «pending»: finché non si sa da dove vengono i valori la richiesta non si scrive (regola 9)",
"headers": {
"(nome tolto)": "pending",
"accept": "constant:*/*",
@@ -270,7 +287,7 @@
"user-agent": "session:user_agent",
"x-asbd-id": "constant:359341",
"x-csrftoken": "cookie:csrftoken",
"x-fb-entry-nonce": "pending",
"x-fb-entry-nonce": "session:entry_nonce",
"x-fb-friendly-name": "operation",
"x-fb-lsd": "session:lsd",
"x-ig-app-id": "session:app_id",
@@ -279,18 +296,18 @@
"body": {
"(nome tolto)": "pending",
"__a": "constant:1",
"__ccg": "pending",
"__comet_req": "constant:7",
"__ccg": "session:ccg",
"__comet_req": "session:comet_req",
"__crn": "pending",
"__csr": "pending",
"__d": "pending",
"__dyn": "pending",
"__hblp": "pending",
"__hs": "pending",
"__hs": "session:hs",
"__hsdp": "pending",
"__hsi": "pending",
"__hsi": "session:hsi",
"__req": "pending",
"__rev": "pending",
"__rev": "session:rev",
"__s": "pending",
"__sjsp": "pending",
"__spin_b": "pending",
@@ -299,7 +316,7 @@
"__user": "session:account_id",
"av": "session:account_id",
"doc_id": "session:doc_id",
"dpr": "constant:1",
"dpr": "session:dpr",
"fb_api_caller_class": "constant:RelayModern",
"fb_api_req_friendly_name": "operation",
"fb_dtsg": "session:fb_dtsg",
@@ -332,7 +349,7 @@
"category": "storico",
"roles": ["tagged"],
"configured": false,
"reason": "le variabili sono note, ma intestazioni e campi della pagina e del browser (come __dyn, __csr, referer, sec-ch-ua e quello con il nome tolto dalla sonda) hanno ancora la fonte «pending»: finché non si sa da dove vengono i valori la richiesta non si scrive (regola 9, tappa S4)",
"reason": "le variabili sono note, ma intestazioni e campi della pagina e del browser (come __dyn, __csr, referer, sec-ch-ua e quello con il nome tolto dalla sonda) hanno ancora la fonte «pending»: finché non si sa da dove vengono i valori la richiesta non si scrive (regola 9)",
"headers": {
"(nome tolto)": "pending",
"accept": "constant:*/*",
@@ -349,7 +366,7 @@
"user-agent": "session:user_agent",
"x-asbd-id": "constant:359341",
"x-csrftoken": "cookie:csrftoken",
"x-fb-entry-nonce": "pending",
"x-fb-entry-nonce": "session:entry_nonce",
"x-fb-friendly-name": "operation",
"x-fb-lsd": "session:lsd",
"x-ig-app-id": "session:app_id",
@@ -358,18 +375,18 @@
"body": {
"(nome tolto)": "pending",
"__a": "constant:1",
"__ccg": "pending",
"__comet_req": "constant:7",
"__ccg": "session:ccg",
"__comet_req": "session:comet_req",
"__crn": "pending",
"__csr": "pending",
"__d": "pending",
"__dyn": "pending",
"__hblp": "pending",
"__hs": "pending",
"__hs": "session:hs",
"__hsdp": "pending",
"__hsi": "pending",
"__hsi": "session:hsi",
"__req": "pending",
"__rev": "pending",
"__rev": "session:rev",
"__s": "pending",
"__sjsp": "pending",
"__spin_b": "pending",
@@ -378,7 +395,7 @@
"__user": "session:account_id",
"av": "session:account_id",
"doc_id": "session:doc_id",
"dpr": "constant:1",
"dpr": "session:dpr",
"fb_api_caller_class": "constant:RelayModern",
"fb_api_req_friendly_name": "operation",
"fb_dtsg": "session:fb_dtsg",
@@ -408,7 +425,7 @@
"category": "profilo",
"roles": ["highlights"],
"configured": false,
"reason": "le variabili sono note, ma intestazioni e campi della pagina e del browser (come __dyn, __csr, referer, sec-ch-ua e quello con il nome tolto dalla sonda) hanno ancora la fonte «pending»: finché non si sa da dove vengono i valori la richiesta non si scrive (regola 9, tappa S4)",
"reason": "le variabili sono note, ma intestazioni e campi della pagina e del browser (come __dyn, __csr, referer, sec-ch-ua e quello con il nome tolto dalla sonda) hanno ancora la fonte «pending»: finché non si sa da dove vengono i valori la richiesta non si scrive (regola 9)",
"headers": {
"(nome tolto)": "pending",
"accept": "constant:*/*",
@@ -425,7 +442,7 @@
"user-agent": "session:user_agent",
"x-asbd-id": "constant:359341",
"x-csrftoken": "cookie:csrftoken",
"x-fb-entry-nonce": "pending",
"x-fb-entry-nonce": "session:entry_nonce",
"x-fb-friendly-name": "operation",
"x-fb-lsd": "session:lsd",
"x-ig-app-id": "session:app_id",
@@ -434,18 +451,18 @@
"body": {
"(nome tolto)": "pending",
"__a": "constant:1",
"__ccg": "pending",
"__comet_req": "constant:7",
"__ccg": "session:ccg",
"__comet_req": "session:comet_req",
"__crn": "pending",
"__csr": "pending",
"__d": "pending",
"__dyn": "pending",
"__hblp": "pending",
"__hs": "pending",
"__hs": "session:hs",
"__hsdp": "pending",
"__hsi": "pending",
"__hsi": "session:hsi",
"__req": "pending",
"__rev": "pending",
"__rev": "session:rev",
"__s": "pending",
"__sjsp": "pending",
"__spin_b": "pending",
@@ -454,7 +471,7 @@
"__user": "session:account_id",
"av": "session:account_id",
"doc_id": "session:doc_id",
"dpr": "constant:1",
"dpr": "session:dpr",
"fb_api_caller_class": "constant:RelayModern",
"fb_api_req_friendly_name": "operation",
"fb_dtsg": "session:fb_dtsg",
@@ -498,7 +515,7 @@
"user-agent": "session:user_agent",
"x-asbd-id": "constant:359341",
"x-csrftoken": "cookie:csrftoken",
"x-fb-entry-nonce": "pending",
"x-fb-entry-nonce": "session:entry_nonce",
"x-fb-friendly-name": "operation",
"x-fb-lsd": "session:lsd",
"x-ig-app-id": "session:app_id",
@@ -507,18 +524,18 @@
"body": {
"(nome tolto)": "pending",
"__a": "constant:1",
"__ccg": "pending",
"__comet_req": "constant:7",
"__ccg": "session:ccg",
"__comet_req": "session:comet_req",
"__crn": "pending",
"__csr": "pending",
"__d": "pending",
"__dyn": "pending",
"__hblp": "pending",
"__hs": "pending",
"__hs": "session:hs",
"__hsdp": "pending",
"__hsi": "pending",
"__hsi": "session:hsi",
"__req": "pending",
"__rev": "pending",
"__rev": "session:rev",
"__s": "pending",
"__sjsp": "pending",
"__spin_b": "pending",
@@ -527,7 +544,7 @@
"__user": "session:account_id",
"av": "session:account_id",
"doc_id": "session:doc_id",
"dpr": "constant:1",
"dpr": "session:dpr",
"fb_api_analytics_tags": "pending",
"fb_api_caller_class": "constant:RelayModern",
"fb_api_req_friendly_name": "operation",
@@ -577,7 +594,7 @@
"x-asbd-id": "constant:359341",
"x-bloks-version-id": "constant:e9f7142825abe6e3e169776ae34e2fc4aeb2fa7ccdf139d43730b2f13505e200",
"x-csrftoken": "cookie:csrftoken",
"x-fb-entry-nonce": "pending",
"x-fb-entry-nonce": "session:entry_nonce",
"x-fb-friendly-name": "operation",
"x-fb-lsd": "session:lsd",
"x-ig-app-id": "session:app_id",
@@ -587,18 +604,18 @@
"body": {
"(nome tolto)": "pending",
"__a": "constant:1",
"__ccg": "pending",
"__comet_req": "constant:7",
"__ccg": "session:ccg",
"__comet_req": "session:comet_req",
"__crn": "pending",
"__csr": "pending",
"__d": "pending",
"__dyn": "pending",
"__hblp": "pending",
"__hs": "pending",
"__hs": "session:hs",
"__hsdp": "pending",
"__hsi": "pending",
"__hsi": "session:hsi",
"__req": "pending",
"__rev": "pending",
"__rev": "session:rev",
"__s": "pending",
"__sjsp": "pending",
"__spin_b": "pending",
@@ -607,7 +624,7 @@
"__user": "session:account_id",
"av": "session:account_id",
"doc_id": "session:doc_id",
"dpr": "constant:1",
"dpr": "session:dpr",
"fb_api_caller_class": "constant:RelayModern",
"fb_api_req_friendly_name": "operation",
"fb_dtsg": "session:fb_dtsg",
@@ -658,7 +675,7 @@
"x-asbd-id": "constant:359341",
"x-bloks-version-id": "constant:e9f7142825abe6e3e169776ae34e2fc4aeb2fa7ccdf139d43730b2f13505e200",
"x-csrftoken": "cookie:csrftoken",
"x-fb-entry-nonce": "pending",
"x-fb-entry-nonce": "session:entry_nonce",
"x-fb-friendly-name": "operation",
"x-fb-lsd": "session:lsd",
"x-ig-app-id": "session:app_id",
@@ -668,18 +685,18 @@
"body": {
"(nome tolto)": "pending",
"__a": "constant:1",
"__ccg": "pending",
"__comet_req": "constant:7",
"__ccg": "session:ccg",
"__comet_req": "session:comet_req",
"__crn": "pending",
"__csr": "pending",
"__d": "pending",
"__dyn": "pending",
"__hblp": "pending",
"__hs": "pending",
"__hs": "session:hs",
"__hsdp": "pending",
"__hsi": "pending",
"__hsi": "session:hsi",
"__req": "pending",
"__rev": "pending",
"__rev": "session:rev",
"__s": "pending",
"__sjsp": "pending",
"__spin_b": "pending",
@@ -688,7 +705,7 @@
"__user": "session:account_id",
"av": "session:account_id",
"doc_id": "session:doc_id",
"dpr": "constant:1",
"dpr": "session:dpr",
"fb_api_analytics_tags": "pending",
"fb_api_caller_class": "constant:RelayModern",
"fb_api_req_friendly_name": "operation",
@@ -726,7 +743,7 @@
"category": "post",
"roles": ["post"],
"configured": false,
"reason": "il percorso è noto, ma intestazioni della pagina e del browser (come referer, sec-ch-ua e quella con il nome tolto dalla sonda) hanno ancora la fonte «pending»: finché non si sa da dove vengono i valori la richiesta non si scrive (regola 9, tappa S4)",
"reason": "il percorso è noto, ma intestazioni della pagina e del browser (come referer, sec-ch-ua e quella con il nome tolto dalla sonda) hanno ancora la fonte «pending»: finché non si sa da dove vengono i valori la richiesta non si scrive (regola 9)",
"headers": {
"(nome tolto)": "pending",
"accept": "constant:*/*",
+26 -2
View File
@@ -1,6 +1,23 @@
{
"site": "prova",
"note": "Operazioni che il client del sito chiede al sito di prova locale (tools/Febe.SitoDiProva, specifica §14.2) dalla tappa S2 di #36: le stesse risposte JSON che la pagina chiede a /dati/, servite sotto /api/ dove il sito controlla ciò che controlla un sito vero (cookie sessione_prova, x-csrftoken uguale al cookie csrftoken, x-app-id e le altre intestazioni e i campi del modello), documentate dai campioni ripuliti di tests/Febe.Tests/campioni/prova. Le pagine continuano a chiedere /dati/, che non controlla nulla. ProvaProfiloQuery è una richiesta GraphQL (POST /api/graphql con doc_id, nome dell'operazione e variabili) che risponde con il JSON di /dati/profilo/{nome}. Le regole di rifiuto sono le stesse di Instagram (nel codice). La scrittura /dati/ricerche-recenti (POST) non c'è e non può esserci: un indirizzo semplice si legge solo con GET.",
"note": "Operazioni che il client del sito chiede al sito di prova locale (tools/Febe.SitoDiProva, specifica §14.2) dalla tappa S2 di #36: le stesse risposte JSON che la pagina chiede a /dati/, servite sotto /api/ dove il sito controlla ciò che controlla un sito vero (cookie sessione_prova, x-csrftoken uguale al cookie csrftoken, x-app-id e le altre intestazioni e i campi del modello), documentate dai campioni ripuliti di tests/Febe.Tests/campioni/prova. Le pagine continuano a chiedere /dati/, che non controlla nulla. ProvaProfiloQuery è una richiesta GraphQL (POST /api/graphql con doc_id, nome dell'operazione e variabili) che risponde con il JSON di /dati/profilo/{nome}. Le regole di rifiuto sono le stesse di Instagram (nel codice). La scrittura /dati/ricerche-recenti (POST) non c'è e non può esserci: un indirizzo semplice si legge solo con GET. La sezione «page» dice dove le pagine del sito di prova tengono i valori della sessione, con nomi di moduli suoi, mai quelli di Instagram: GettoniProva (lsd, dtsg), UtenteProva (id, applicazione), VersioneProva (revisione, hs, hsi, dpr, comet), ConnessioneProva (classe), AvvioProva (nonce) e un modulo «<operazione>_operazioneProva» per ogni doc_id (ProvaProfiloQuery_operazioneProva); i valori sono le costanti di TestSite (tools/Febe.SitoDiProva/DirectApi.cs).",
"page": {
"note": "Moduli del registro require/__d delle pagine del sito di prova (tools/Febe.SitoDiProva): stessi nomi qui e là.",
"docIdModule": "{operation}_operazioneProva",
"values": {
"lsd": "GettoniProva.lsd",
"fb_dtsg": "GettoniProva.dtsg",
"account_id": "UtenteProva.id",
"app_id": "UtenteProva.applicazione",
"rev": "VersioneProva.revisione",
"hs": "VersioneProva.hs",
"hsi": "VersioneProva.hsi",
"dpr": "VersioneProva.dpr",
"comet_req": "VersioneProva.comet",
"ccg": "ConnessioneProva.classe",
"entry_nonce": "AvvioProva.nonce"
}
},
"operations": [
{
"name": "inizio",
@@ -75,12 +92,19 @@
"user-agent": "session:user_agent",
"x-app-id": "session:app_id",
"x-csrftoken": "cookie:csrftoken",
"x-fb-entry-nonce": "session:entry_nonce",
"x-fb-friendly-name": "operation",
"x-ig-www-claim": "session:claim"
},
"body": {
"av": "session:account_id",
"__a": "constant:1",
"__ccg": "session:ccg",
"__comet_req": "session:comet_req",
"__hs": "session:hs",
"__hsi": "session:hsi",
"__rev": "session:rev",
"dpr": "session:dpr",
"fb_dtsg": "session:fb_dtsg",
"lsd": "session:lsd",
"fb_api_req_friendly_name": "operation",
@@ -97,7 +121,7 @@
"profilo"
],
"sample": "000002-profilo-pubblico",
"note": "Una richiesta GraphQL del sito di prova: le stesse forme di Instagram (form con doc_id, fb_api_req_friendly_name e variables; x-csrftoken, x-fb-friendly-name, x-ig-www-claim), la risposta di /dati/profilo/{nome}. Il sito controlla doc_id, nome, gettoni e i tipi delle variabili (primi è il numero 12, raccolte un vero/falso)."
"note": "Una richiesta GraphQL del sito di prova: le stesse forme di Instagram (form con doc_id, fb_api_req_friendly_name e variables; x-csrftoken, x-fb-friendly-name, x-ig-www-claim), la risposta di /dati/profilo/{nome}. Il sito controlla doc_id, nome, gettoni e i tipi delle variabili (primi è il numero 12, raccolte un vero/falso). I campi di versione (__rev, __hs, __hsi, __ccg, dpr, __comet_req) e x-fb-entry-nonce vengono dalla sessione salvata, come su Instagram."
},
{
"name": "profilo-altri",
+13 -3
View File
@@ -1,6 +1,7 @@
using System.Diagnostics;
using System.Globalization;
using System.Text.Json;
using Febe.Core.Security;
namespace Febe.Core.Import;
@@ -58,9 +59,12 @@ public sealed class FfprobeVideoMetadataProbe : IVideoMetadataProbe
return null;
}
public async Task<VideoMetadata?> ProbeAsync(string path, CancellationToken ct = default)
/// <summary>
/// The start of ffprobe for <paramref name="path"/>: its arguments, and the environment of Febe without
/// <c>FEBE_PASSWORD</c> and <c>FEBE_CHIAVE_SESSIONE</c>, removed last (spec §13.2).
/// </summary>
internal ProcessStartInfo BuildStartInfo(string path)
{
ArgumentException.ThrowIfNullOrWhiteSpace(path);
var start = new ProcessStartInfo(Executable)
{
RedirectStandardOutput = true,
@@ -78,7 +82,13 @@ public sealed class FfprobeVideoMetadataProbe : IVideoMetadataProbe
start.ArgumentList.Add(argument);
}
using var process = new Process { StartInfo = start };
return start.WithoutSecrets();
}
public async Task<VideoMetadata?> ProbeAsync(string path, CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(path);
using var process = new Process { StartInfo = BuildStartInfo(path) };
try
{
if (!process.Start())
+12
View File
@@ -133,4 +133,16 @@ public sealed record DataFolderLayout
/// <summary>Dati/segnali.json.</summary>
public string SignalsFile => Path.Combine(Root, "segnali.json");
/// <summary>
/// Dati/sessione: the saved session of the site client, encrypted, owner-only (issue #36, §13.2). Not in the
/// database, so never in the daily copies; never read by the diagnostic report.
/// </summary>
public string Session => Path.Combine(Root, "sessione");
/// <summary>Dati/sessione/sessione.json: the encrypted saved session.</summary>
public string SessionFile => Path.Combine(Session, "sessione.json");
/// <summary>Dati/sessione/chiave.bin: the AES key in Docker when FEBE_CHIAVE_SESSIONE is not set.</summary>
public string SessionKeyFile => Path.Combine(Session, "chiave.bin");
}
+13 -2
View File
@@ -1,4 +1,5 @@
using System.Diagnostics;
using Febe.Core.Security;
namespace Febe.Core.Library;
@@ -63,7 +64,12 @@ public sealed class VideoFrameExtractor
return null;
}
private async Task<byte[]?> RunAsync(string videoPath, string seek, CancellationToken ct)
/// <summary>
/// The start of ffmpeg for one frame of <paramref name="videoPath"/> at <paramref name="seek"/> seconds: its
/// arguments, and the environment of Febe without <c>FEBE_PASSWORD</c> and <c>FEBE_CHIAVE_SESSIONE</c>, removed last
/// (spec §13.2).
/// </summary>
internal ProcessStartInfo BuildStartInfo(string videoPath, string seek)
{
var start = new ProcessStartInfo(Executable)
{
@@ -78,7 +84,12 @@ public sealed class VideoFrameExtractor
start.ArgumentList.Add(argument);
}
using var process = new Process { StartInfo = start };
return start.WithoutSecrets();
}
private async Task<byte[]?> RunAsync(string videoPath, string seek, CancellationToken ct)
{
using var process = new Process { StartInfo = BuildStartInfo(videoPath, seek) };
try
{
if (!process.Start())
@@ -0,0 +1,73 @@
using System.Security.Cryptography;
namespace Febe.Core.Security;
/// <summary>
/// AES-256-GCM for the saved session in Docker (issue #36, S4, spec §13.2), from the base library
/// (<c>System.Security.Cryptography</c>, §3): header (6 bytes) | nonce (12, fresh for every write) | tag (16) |
/// ciphertext; the header is the associated data, so a changed header is a damaged file.
/// </summary>
public sealed class AesGcmSessionProtector : ISessionProtector
{
private const int NonceLength = 12;
private const int TagLength = 16;
private readonly byte[] _key;
/// <param name="key">Exactly 32 bytes (<see cref="SessionKey"/>); copied, never logged.</param>
/// <exception cref="ArgumentException">A key that is not 32 bytes (the message names the length only).</exception>
public AesGcmSessionProtector(ReadOnlySpan<byte> key)
{
if (key.Length != SessionKey.Length)
{
throw new ArgumentException($"La chiave della sessione salvata è di {SessionKey.Length} byte.", nameof(key));
}
_key = key.ToArray();
}
public string Scheme => "aes-gcm";
public byte[] Protect(ReadOnlySpan<byte> plain)
{
var header = SessionBlob.Header(SessionBlob.AesGcm);
var blob = new byte[SessionBlob.HeaderLength + NonceLength + TagLength + plain.Length];
header.CopyTo(blob, 0);
var nonce = blob.AsSpan(SessionBlob.HeaderLength, NonceLength);
RandomNumberGenerator.Fill(nonce);
var tag = blob.AsSpan(SessionBlob.HeaderLength + NonceLength, TagLength);
var cipher = blob.AsSpan(SessionBlob.HeaderLength + NonceLength + TagLength);
using var aes = new AesGcm(_key, TagLength);
aes.Encrypt(nonce, plain, cipher, tag, header);
return blob;
}
public byte[] Unprotect(ReadOnlySpan<byte> blob)
{
if (!SessionBlob.HasHeader(blob, SessionBlob.AesGcm) || blob.Length < SessionBlob.HeaderLength + NonceLength + TagLength)
{
throw new SessionUnreadableException();
}
var header = blob[..SessionBlob.HeaderLength];
var nonce = blob.Slice(SessionBlob.HeaderLength, NonceLength);
var tag = blob.Slice(SessionBlob.HeaderLength + NonceLength, TagLength);
var cipher = blob[(SessionBlob.HeaderLength + NonceLength + TagLength)..];
var plain = new byte[cipher.Length];
try
{
using var aes = new AesGcm(_key, TagLength);
aes.Decrypt(nonce, cipher, tag, plain, header);
return plain;
}
catch (CryptographicException)
{
// Another key or a changed byte: nothing of the inner text is passed on.
CryptographicOperations.ZeroMemory(plain);
throw new SessionUnreadableException();
}
}
/// <summary>The scheme only, never the key.</summary>
public override string ToString() => "Cifratura della sessione: AES-256-GCM.";
}
@@ -0,0 +1,42 @@
using System.Diagnostics;
namespace Febe.Core.Security;
/// <summary>
/// What a process Febe starts (Chromium, Edge, Xvfb, ffmpeg, ffprobe, Explorer) must not inherit from Febe (issue #36,
/// S4, rule 10): the interface password and the key of the saved session. A child process copies the environment of its
/// parent; Chromium runs the site's code, so a secret in its environment is a secret one step from the site.
/// </summary>
public static class ChildProcessEnvironment
{
/// <summary>The interface password of Docker (spec §11).</summary>
public const string PasswordVariable = "FEBE_PASSWORD";
/// <summary>The variables taken out of every child process's environment.</summary>
public static IReadOnlyList<string> SecretVariables { get; } = [PasswordVariable, SessionKey.EnvironmentVariable];
/// <summary>
/// Removes <see cref="SecretVariables"/> from <paramref name="info"/>'s environment. Call it last, after anything
/// else that sets variables. Only for <c>UseShellExecute = false</c> (with the shell, .NET passes no environment).
/// </summary>
public static ProcessStartInfo WithoutSecrets(this ProcessStartInfo info)
{
ArgumentNullException.ThrowIfNull(info);
RemoveSecrets(info.Environment);
return info;
}
/// <summary>Removes <see cref="SecretVariables"/> from <paramref name="environment"/> (whatever the case of the name).</summary>
public static void RemoveSecrets(IDictionary<string, string?> environment)
{
ArgumentNullException.ThrowIfNull(environment);
foreach (var name in environment.Keys.Where(IsSecret).ToList())
{
environment.Remove(name);
}
}
/// <summary>True for a name of <see cref="SecretVariables"/>, in any case (Windows names ignore it).</summary>
public static bool IsSecret(string name) =>
SecretVariables.Any(secret => string.Equals(secret, name, StringComparison.OrdinalIgnoreCase));
}
@@ -0,0 +1,70 @@
namespace Febe.Core.Security;
/// <summary>
/// Encrypts the saved session before it touches the disk (issue #36, S4, spec §13.2): DPAPI for the current user on
/// Windows (in Febe.Desktop, the only project with <c>ProtectedData</c> and no package), AES-256-GCM with a key of its
/// own in Docker (<see cref="AesGcmSessionProtector"/>). The text it protects never reaches a log or an exception.
/// </summary>
public interface ISessionProtector
{
/// <summary>The scheme, for the log: <c>dpapi</c> or <c>aes-gcm</c>.</summary>
string Scheme { get; }
/// <summary>The encrypted form of <paramref name="plain"/>, starting with <see cref="SessionBlob"/>'s header.</summary>
byte[] Protect(ReadOnlySpan<byte> plain);
/// <summary>The plain text of <paramref name="blob"/>.</summary>
/// <exception cref="SessionUnreadableException">Another key or user, a damaged file, another scheme or format.</exception>
byte[] Unprotect(ReadOnlySpan<byte> blob);
}
/// <summary>
/// The header every protected session starts with: <c>FEBS</c>, the format version, the scheme. It says only what the
/// file is, never what it holds; the AES scheme authenticates it.
/// </summary>
public static class SessionBlob
{
/// <summary>The scheme byte of DPAPI.</summary>
public const byte Dpapi = 1;
/// <summary>The scheme byte of AES-256-GCM.</summary>
public const byte AesGcm = 2;
/// <summary>The format version.</summary>
public const byte Version = 1;
/// <summary>The length of the header.</summary>
public const int HeaderLength = 6;
/// <summary>The header for <paramref name="scheme"/>.</summary>
public static byte[] Header(byte scheme) => [(byte)'F', (byte)'E', (byte)'B', (byte)'S', Version, scheme];
/// <summary>True when <paramref name="blob"/> starts with the header of <paramref name="scheme"/>.</summary>
public static bool HasHeader(ReadOnlySpan<byte> blob, byte scheme) =>
blob.Length >= HeaderLength && blob[..HeaderLength].SequenceEqual(Header(scheme));
}
/// <summary>
/// The saved session cannot be read: another key or user, a damaged file, another format. Its message is fixed and
/// carries no inner text: Febe treats it as no session and asks for a new login.
/// </summary>
public sealed class SessionUnreadableException : Exception
{
/// <summary>The fixed message.</summary>
public const string Text = "La sessione salvata non si legge (cifratura o formato): serve un nuovo accesso.";
public SessionUnreadableException()
: base(Text)
{
}
public SessionUnreadableException(string message)
: base(message)
{
}
public SessionUnreadableException(string message, Exception innerException)
: base(message, innerException)
{
}
}
+179
View File
@@ -0,0 +1,179 @@
namespace Febe.Core.Security;
/// <summary>
/// Files only their owner reads (issue #36, S4, spec §13.2): the folder <c>Dati/sessione</c> at 0700 and its files at
/// 0600 on Unix, set when they are created (no window with wider rights); a file replaced at once (a part file in the
/// same folder, then a rename over the old one), never half written. On Windows the modes do not apply: the Data folder
/// is under the user's profile and DPAPI ties the session to the user.
/// </summary>
public static class OwnerOnlyFiles
{
/// <summary>The suffix of a file still being written.</summary>
public const string PartSuffix = ".part";
/// <summary>Read and write for the owner only.</summary>
public const UnixFileMode OwnerFile = UnixFileMode.UserRead | UnixFileMode.UserWrite;
/// <summary>Read, write and enter for the owner only.</summary>
public const UnixFileMode OwnerFolder = UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute;
private const UnixFileMode Others =
UnixFileMode.GroupRead | UnixFileMode.GroupWrite | UnixFileMode.GroupExecute
| UnixFileMode.OtherRead | UnixFileMode.OtherWrite | UnixFileMode.OtherExecute;
/// <summary>Creates <paramref name="folder"/> owner-only (0700 on Unix); an existing one with wider rights is narrowed.</summary>
public static void EnsureFolder(string folder)
{
ArgumentException.ThrowIfNullOrWhiteSpace(folder);
if (OperatingSystem.IsWindows())
{
Directory.CreateDirectory(folder);
return;
}
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder, OwnerFolder);
}
else if ((File.GetUnixFileMode(folder) & Others) != 0)
{
File.SetUnixFileMode(folder, OwnerFolder);
}
}
/// <summary>
/// Narrows <paramref name="file"/> to 0600 when group or others have any right on it (Unix only); true when it did.
/// </summary>
public static bool Tighten(string file)
{
ArgumentException.ThrowIfNullOrWhiteSpace(file);
if (OperatingSystem.IsWindows() || !File.Exists(file) || (File.GetUnixFileMode(file) & Others) == 0)
{
return false;
}
File.SetUnixFileMode(file, OwnerFile);
return true;
}
/// <summary>Writes the bytes of a new file into its stream (a seam for the tests of a disk that refuses the write).</summary>
internal delegate void BytesWriter(Stream stream, ReadOnlySpan<byte> bytes);
/// <summary>
/// Writes <paramref name="bytes"/> as a new owner-only file, whole or not at all: a part file in the same folder,
/// written through to the disk, then renamed to <paramref name="path"/> without replacing. Never replaces a file
/// that is there, and a failed write never leaves a short file at <paramref name="path"/> (nor a part file).
/// </summary>
/// <exception cref="IOException">The file is already there, or the disk refused it.</exception>
public static void CreateNew(string path, ReadOnlySpan<byte> bytes) => CreateNew(path, bytes, static (stream, data) => stream.Write(data));
/// <inheritdoc cref="CreateNew(string, ReadOnlySpan{byte})"/>
/// <param name="path">The new file.</param>
/// <param name="bytes">Its content.</param>
/// <param name="write">How the bytes go into the part file.</param>
internal static void CreateNew(string path, ReadOnlySpan<byte> bytes, BytesWriter write)
{
ArgumentException.ThrowIfNullOrWhiteSpace(path);
ArgumentNullException.ThrowIfNull(write);
if (File.Exists(path))
{
throw new IOException($"{Path.GetFileName(path)} c'è già: Febe non lo sostituisce.");
}
var part = path + "." + Guid.NewGuid().ToString("N")[..8] + PartSuffix;
try
{
using (var stream = new FileStream(part, Options(FileMode.CreateNew, FileOptions.WriteThrough)))
{
write(stream, bytes);
stream.Flush(flushToDisk: true);
}
// Without replacing: a file made meanwhile by someone else stays, and this one throws IOException.
File.Move(part, path, overwrite: false);
}
finally
{
TryDelete(part);
}
}
/// <summary>
/// Replaces <paramref name="path"/> with <paramref name="bytes"/> at once: a part file in the same folder, owner-only
/// from its creation, written through to the disk, then renamed over the old file. A failure leaves the old file and
/// no part file.
/// </summary>
/// <exception cref="IOException">The disk refused the write or the rename.</exception>
/// <exception cref="UnauthorizedAccessException">The folder or the file is not writable.</exception>
public static void WriteAtomic(string path, ReadOnlySpan<byte> bytes)
{
ArgumentException.ThrowIfNullOrWhiteSpace(path);
var part = path + "." + Guid.NewGuid().ToString("N")[..8] + PartSuffix;
try
{
using (var stream = new FileStream(part, Options(FileMode.CreateNew, FileOptions.WriteThrough)))
{
stream.Write(bytes);
stream.Flush(flushToDisk: true);
}
File.Move(part, path, overwrite: true);
}
finally
{
TryDelete(part);
}
}
/// <summary>
/// Deletes <paramref name="path"/> and the part files a broken write may have left next to it. A file that is not
/// there is no error.
/// </summary>
/// <exception cref="IOException">The file could not be deleted.</exception>
/// <exception cref="UnauthorizedAccessException">The file could not be deleted.</exception>
public static void DeleteWithLeftovers(string path)
{
ArgumentException.ThrowIfNullOrWhiteSpace(path);
var folder = Path.GetDirectoryName(Path.GetFullPath(path))!;
if (!Directory.Exists(folder))
{
// No folder, no file: on Windows File.Delete would throw DirectoryNotFoundException.
return;
}
foreach (var part in Directory.EnumerateFiles(folder, Path.GetFileName(path) + ".*" + PartSuffix))
{
File.Delete(part);
}
File.Delete(path);
}
private static FileStreamOptions Options(FileMode mode, FileOptions options = FileOptions.None)
{
var result = new FileStreamOptions { Mode = mode, Access = FileAccess.Write, Share = FileShare.None, Options = options };
if (!OperatingSystem.IsWindows())
{
result.UnixCreateMode = OwnerFile;
}
return result;
}
private static void TryDelete(string path)
{
try
{
if (File.Exists(path))
{
File.Delete(path);
}
}
catch (IOException)
{
}
catch (UnauthorizedAccessException)
{
}
}
}
+165
View File
@@ -0,0 +1,165 @@
using System.Globalization;
using System.Security.Cryptography;
namespace Febe.Core.Security;
/// <summary>
/// The key of the saved session in Docker (issue #36, S4, spec §13.2): from <c>FEBE_CHIAVE_SESSIONE</c> (32 bytes in
/// base64, or 64 hexadecimal digits), otherwise <c>Dati/sessione/chiave.bin</c>, made once with
/// <see cref="RandomNumberGenerator"/> (not <c>IRandomSource</c>, which is for the timing of the engine), owner-only,
/// never replaced. No text of this class ever holds the key or a part of it.
/// </summary>
public static class SessionKey
{
/// <summary>The length of the key: AES-256.</summary>
public const int Length = 32;
/// <summary>The environment variable that holds the key outside the Data folder.</summary>
public const string EnvironmentVariable = "FEBE_CHIAVE_SESSIONE";
/// <summary>
/// Reads a key written as text: base64 of exactly 32 bytes or 64 hexadecimal digits, spaces around it ignored.
/// The problem names the format only, never the value.
/// </summary>
public static bool TryParse(string? text, out byte[]? key, out string? problem)
{
key = null;
var trimmed = text?.Trim() ?? string.Empty;
if (trimmed.Length == 0)
{
problem = $"{EnvironmentVariable} è vuota.";
return false;
}
if (trimmed.Length == 2 * Length && trimmed.All(char.IsAsciiHexDigit))
{
key = Convert.FromHexString(trimmed);
problem = null;
return true;
}
var buffer = new byte[trimmed.Length];
if (Convert.TryFromBase64String(trimmed, buffer, out var written) && written == Length)
{
key = buffer[..Length];
CryptographicOperations.ZeroMemory(buffer);
problem = null;
return true;
}
CryptographicOperations.ZeroMemory(buffer);
problem = string.Create(
CultureInfo.InvariantCulture,
$"{EnvironmentVariable} deve essere una chiave di {Length} byte in base64 (per esempio quella di «openssl rand -base64 32») o di {2 * Length} cifre esadecimali.");
return false;
}
/// <summary>
/// What is wrong with <paramref name="keyFile"/>, or null when it is a key of Febe or is not there (it will be made).
/// The text names the file and the length, never the content.
/// </summary>
public static string? CheckFile(string keyFile)
{
ArgumentException.ThrowIfNullOrWhiteSpace(keyFile);
try
{
if (!File.Exists(keyFile))
{
return null;
}
var length = new FileInfo(keyFile).Length;
return length == Length
? null
: string.Create(CultureInfo.InvariantCulture, $"{Path.GetFileName(keyFile)} non è una chiave di Febe ({length} byte invece di {Length}): cancellalo e rifai l'accesso.");
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
return $"{Path.GetFileName(keyFile)} non si legge: controlla i permessi della cartella dei dati.";
}
}
/// <summary>
/// The key in <paramref name="keyFile"/>, made when it is not there: 32 random bytes, a new owner-only file in an
/// owner-only folder, never replacing one that is there. A file with wider rights on Unix is narrowed to 0600 and
/// <paramref name="warn"/> says so.
/// </summary>
/// <exception cref="InvalidDataException">The file is there but is not a key of Febe (32 bytes).</exception>
/// <exception cref="IOException">The disk refused to make or read the file.</exception>
public static byte[] LoadOrCreate(string keyFile, Action<string>? warn = null) =>
LoadOrCreate(keyFile, warn, static (stream, bytes) => stream.Write(bytes));
/// <inheritdoc cref="LoadOrCreate(string, Action{string})"/>
/// <param name="keyFile">The key file.</param>
/// <param name="warn">Says when the rights of the file were narrowed.</param>
/// <param name="write">How the bytes of a new key go to the disk (a seam for a disk that refuses the write).</param>
internal static byte[] LoadOrCreate(string keyFile, Action<string>? warn, OwnerOnlyFiles.BytesWriter write)
{
ArgumentException.ThrowIfNullOrWhiteSpace(keyFile);
var full = Path.GetFullPath(keyFile);
OwnerOnlyFiles.EnsureFolder(Path.GetDirectoryName(full)!);
if (!File.Exists(full))
{
var fresh = RandomNumberGenerator.GetBytes(Length);
try
{
// Whole or not at all: a write the disk refuses (full, I/O error) leaves no short chiave.bin behind,
// so the next start tries again instead of stopping at a file that is not a key.
OwnerOnlyFiles.CreateNew(full, fresh, write);
return fresh;
}
catch (IOException) when (File.Exists(full))
{
// Made by someone else in the meantime (only a whole file is ever renamed there): that one is the key.
CryptographicOperations.ZeroMemory(fresh);
}
catch
{
CryptographicOperations.ZeroMemory(fresh);
throw;
}
}
if (CheckFile(full) is { } problem)
{
throw new InvalidDataException(problem);
}
if (OwnerOnlyFiles.Tighten(full))
{
warn?.Invoke($"{Path.GetFileName(full)} era leggibile da altri utenti: ora lo legge solo il proprietario.");
}
return File.ReadAllBytes(full);
}
/// <summary>
/// The key of the saved session: <paramref name="environmentValue"/> (the value of <see cref="EnvironmentVariable"/>)
/// when it is set, otherwise <paramref name="keyFile"/> (<see cref="LoadOrCreate"/>). <paramref name="log"/> says
/// where the key comes from, never the key; with the variable set, an old <c>chiave.bin</c> is named as unused.
/// </summary>
/// <exception cref="InvalidDataException">The variable is set but is not a key, or the file is not a key of Febe.</exception>
public static byte[] Resolve(string? environmentValue, string keyFile, Action<string>? log = null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(keyFile);
if (!string.IsNullOrWhiteSpace(environmentValue))
{
if (!TryParse(environmentValue, out var key, out var problem))
{
throw new InvalidDataException(problem);
}
log?.Invoke($"Sessione salvata: chiave da {EnvironmentVariable}.");
if (File.Exists(keyFile))
{
log?.Invoke($"Sessione salvata: {Path.GetFileName(keyFile)} non si usa, la chiave viene da {EnvironmentVariable}.");
}
return key!;
}
var stored = LoadOrCreate(keyFile, log);
log?.Invoke($"Sessione salvata: chiave da Dati/sessione/{Path.GetFileName(keyFile)} (solo il proprietario la legge).");
return stored;
}
}
+22 -1
View File
@@ -104,6 +104,12 @@ public sealed record DesktopOptions
/// <summary>Development: the first session after this delay instead of 2–10 minutes.</summary>
public TimeSpan? FirstSessionDelay { get; init; }
/// <summary>
/// <c>--raccolta pagine|richieste</c> (issue #36, S4): by the pages (default, as before S4) or by requests with the
/// saved session, only for the operations the site's catalog configures.
/// </summary>
public CollectionRoute Collection { get; init; } = CollectionRoute.Pages;
/// <summary>The fixed DevTools port of Edge (fallback «edge» only), on 127.0.0.1.</summary>
public int EdgeDebugPort { get; init; } = 9222;
@@ -135,6 +141,7 @@ public sealed record DesktopOptions
TestSite = TestSite,
TestSiteAutoLogin = TestSiteAutoLogin,
FirstSessionDelay = FirstSessionDelay,
Collection = Collection,
};
private static Uri DefaultCdn(Uri site) => new UriBuilder(site) { Host = "127.0.0.2", Port = site.Port + 1, Path = "/" }.Uri;
@@ -145,7 +152,8 @@ public static class DesktopCommandLine
{
public const string Usage =
"Uso: Febe.exe [--nascosto] [--dati cartella] [--libreria cartella] [--browser finestra|composizione|edge] [--sviluppo]\n"
+ " [--sito-di-prova http://127.0.0.1:8481 [--cdn-di-prova http://127.0.0.2:8482] [--accesso-di-prova]] [--prima-sessione secondi]";
+ " [--sito-di-prova http://127.0.0.1:8481 [--cdn-di-prova http://127.0.0.2:8482] [--accesso-di-prova]] [--prima-sessione secondi]\n"
+ " [--raccolta pagine|richieste]";
public static bool TryParse(string[] args, out DesktopOptions options, out string problem)
{
@@ -222,6 +230,19 @@ public static class DesktopCommandLine
case "--accesso-di-prova":
options = options with { TestSiteAutoLogin = true };
break;
case CollectionRouteNames.Option:
{
var text = Next();
if (!CollectionRouteNames.TryParse(text, out var route))
{
problem = CollectionRouteNames.Problem(CollectionRouteNames.Option, text);
return false;
}
options = options with { Collection = route };
break;
}
case "--prima-sessione":
{
var text = Next();
+16
View File
@@ -4,6 +4,7 @@ using Febe.Browser.Cdp;
using Febe.Browser.Hosting;
using Febe.Core.Abstractions;
using Febe.Core.Library;
using Febe.Core.Security;
using Febe.Web;
using Febe.Web.Api;
using Febe.Web.Connection;
@@ -54,6 +55,12 @@ public interface IDesktopShell
/// debugging port. False when Windows refused (the process then lives on its own, as before).
/// </summary>
bool EndWithFebe(System.Diagnostics.Process process);
/// <summary>
/// How the saved session is encrypted on Windows (issue #36, S4, spec §13.2): DPAPI for the current user, from the
/// desktop framework of .NET (no package). Tests on Linux pass AES-256-GCM with a key made at run time.
/// </summary>
ISessionProtector SessionProtector { get; }
}
/// <summary>
@@ -147,6 +154,15 @@ public sealed class DesktopPlatform : IFebePlatform
context);
}
/// <summary>DPAPI for the current Windows user (the shell's): no key file, nothing in the Data folder but the session.</summary>
public ISessionProtector CreateSessionProtector(FebePlatformContext context)
{
ArgumentNullException.ThrowIfNull(context);
var protector = _shell.SessionProtector;
context.Log.Info("sessione", $"Sessione salvata: cifrata con {protector.Scheme} (solo questo utente di Windows la legge).");
return protector;
}
public void RegisterServices(IServiceCollection services, FebeApp app)
{
ArgumentNullException.ThrowIfNull(services);
+4
View File
@@ -5,7 +5,9 @@ using System.Windows.Threading;
using Febe.App;
using Febe.Desktop.Browser;
using Febe.Desktop.Core;
using Febe.Core.Security;
using Febe.Desktop.Native;
using Febe.Desktop.Security;
using Febe.Web.Native;
using Microsoft.Web.WebView2.Core;
using Microsoft.Win32;
@@ -17,6 +19,8 @@ internal sealed class DesktopShell(Dispatcher ui, ImageSource? icon, INativeShel
{
public INativeShell Native { get; } = native;
public ISessionProtector SessionProtector { get; } = new DpapiSessionProtector();
public string? WebView2Version()
{
try
@@ -0,0 +1,62 @@
using System.Security.Cryptography;
using System.Text;
using Febe.Core.Security;
namespace Febe.Desktop.Security;
/// <summary>
/// DPAPI for the saved session on Windows (issue #36, S4, spec §13.2): <see cref="ProtectedData"/> for the current
/// user, from the desktop framework of .NET (no package, decisioni.md). The blob is the shared header (scheme
/// <see cref="SessionBlob.Dpapi"/>) followed by what DPAPI gives; the header is also part of the entropy, so a blob with
/// a changed header does not open. Another Windows user, another computer or a damaged byte is
/// <see cref="SessionUnreadableException"/>, never the inner text.
/// </summary>
internal sealed class DpapiSessionProtector : ISessionProtector
{
/// <summary>The fixed entropy of Febe's blobs: not a secret, it keeps other programs' DPAPI blobs apart.</summary>
private static readonly byte[] Entropy = Encoding.UTF8.GetBytes("Febe sessione salvata v1");
public string Scheme => "dpapi";
public byte[] Protect(ReadOnlySpan<byte> plain)
{
var header = SessionBlob.Header(SessionBlob.Dpapi);
var copy = plain.ToArray();
try
{
var sealedBytes = ProtectedData.Protect(copy, EntropyFor(header), DataProtectionScope.CurrentUser);
var blob = new byte[header.Length + sealedBytes.Length];
header.CopyTo(blob, 0);
sealedBytes.CopyTo(blob, header.Length);
return blob;
}
finally
{
CryptographicOperations.ZeroMemory(copy);
}
}
public byte[] Unprotect(ReadOnlySpan<byte> blob)
{
if (!SessionBlob.HasHeader(blob, SessionBlob.Dpapi) || blob.Length == SessionBlob.HeaderLength)
{
throw new SessionUnreadableException();
}
var header = blob[..SessionBlob.HeaderLength].ToArray();
try
{
return ProtectedData.Unprotect(blob[SessionBlob.HeaderLength..].ToArray(), EntropyFor(header), DataProtectionScope.CurrentUser);
}
catch (CryptographicException)
{
// Another user or computer, or a changed byte: nothing of the inner text is passed on.
throw new SessionUnreadableException();
}
}
/// <summary>The scheme only.</summary>
public override string ToString() => "Cifratura della sessione: DPAPI dell'utente di Windows.";
private static byte[] EntropyFor(byte[] header) => [.. Entropy, .. header];
}
+34
View File
@@ -1,5 +1,6 @@
using Febe.App;
using Febe.Core.Library;
using Febe.Core.Security;
using Febe.Web;
using Febe.Web.Connection;
using Microsoft.Extensions.DependencyInjection;
@@ -49,6 +50,39 @@ internal sealed class DockerPlatform(ServerOptions options) : IFebePlatform
context.Log));
}
/// <summary>
/// AES-256-GCM (spec §13.2): the key of <c>FEBE_CHIAVE_SESSIONE</c> when it is set (already checked at start-up),
/// otherwise <c>Dati/sessione/chiave.bin</c>, made once owner-only. The same on Windows while developing with
/// Febe.Server (no Unix modes there). The log says where the key comes from, never the key.
/// </summary>
public ISessionProtector CreateSessionProtector(FebePlatformContext context)
{
ArgumentNullException.ThrowIfNull(context);
var keyFile = context.Data.SessionKeyFile;
if (Options.SessionKey is { } fromEnvironment)
{
context.Log.Info("sessione", $"Sessione salvata: chiave da {SessionKey.EnvironmentVariable}.");
if (File.Exists(keyFile))
{
context.Log.Warn("sessione", $"Sessione salvata: Dati/sessione/{Path.GetFileName(keyFile)} non si usa, la chiave viene da {SessionKey.EnvironmentVariable}.");
}
return new AesGcmSessionProtector(fromEnvironment);
}
var stored = SessionKey.LoadOrCreate(keyFile, message => context.Log.Warn("sessione", message));
try
{
context.Log.Info("sessione", $"Sessione salvata: chiave da Dati/sessione/{Path.GetFileName(keyFile)} (solo il proprietario la legge).");
return new AesGcmSessionProtector(stored);
}
finally
{
// The protector keeps its own copy.
System.Security.Cryptography.CryptographicOperations.ZeroMemory(stored);
}
}
public void RegisterServices(IServiceCollection services, FebeApp app)
{
ArgumentNullException.ThrowIfNull(services);
+3 -1
View File
@@ -13,7 +13,9 @@ internal static class ServerCommand
"Uso: febe [--dati /dati] [--libreria /libreria] [--importa /importa] [--porta 8480] [--ascolta 0.0.0.0]\n"
+ " [--porta-debug 9222] [--display :99] [--chromium percorso] [--senza-sandbox]\n"
+ " [--sito-di-prova http://127.0.0.1:8481 [--cdn-di-prova http://127.0.0.2:8482] [--accesso-di-prova]] [--prima-sessione secondi]\n"
+ "Variabili: FEBE_PASSWORD (obbligatoria), FEBE_PORTA, TZ, LANG, FEBE_HOST, FEBE_PROXY_FIDATO, FEBE_SENZA_SANDBOX, FEBE_CHROMIUM.\n"
+ " [--raccolta pagine|richieste]\n"
+ "Variabili: FEBE_PASSWORD (obbligatoria), FEBE_PORTA, TZ, LANG, FEBE_HOST, FEBE_PROXY_FIDATO, FEBE_SENZA_SANDBOX, FEBE_CHROMIUM,\n"
+ " FEBE_RACCOLTA, FEBE_CHIAVE_SESSIONE.\n"
+ "Altri comandi: --demo, --simula 30g --profilo prudente, --controllo-salute.";
public static async Task<int> RunAsync(string[] args, TextWriter output, TextWriter error)
+67 -3
View File
@@ -3,14 +3,16 @@ using System.Net;
using Febe.App;
using Febe.Browser.Hosting;
using Febe.Browser.Recipes;
using Febe.Core.Security;
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).
/// options for development (other folders, the local test site, a short first-session delay). The password and the key
/// of the saved session come only from the environment, never from the command line (which other users of the machine
/// can read), and never appear in <see cref="ToString"/>, in <see cref="Warnings"/> or in a problem.
/// </summary>
internal sealed record ServerOptions
{
@@ -25,6 +27,22 @@ internal sealed record ServerOptions
/// <summary>FEBE_PASSWORD: the interface password. Mandatory; never logged or shown.</summary>
public string? Password { get; init; }
/// <summary>
/// FEBE_CHIAVE_SESSIONE, decoded (issue #36, S4, spec §13.2): the 32-byte AES key of the saved session, kept out of
/// the Data folder. Null when the variable is not set (the key is then <c>Dati/sessione/chiave.bin</c>) or is not a
/// key (<see cref="SessionKeyProblem"/>). Never logged or shown.
/// </summary>
public byte[]? SessionKey { get; init; }
/// <summary>What is wrong with FEBE_CHIAVE_SESSIONE (its format only, never its value); null when it is right or unset.</summary>
public string? SessionKeyProblem { get; init; }
/// <summary>
/// Option «raccolta» (<c>--raccolta</c>, FEBE_RACCOLTA; the command line wins): by the pages (default) or by requests
/// (issue #36, S4).
/// </summary>
public CollectionRoute Collection { get; init; } = CollectionRoute.Pages;
/// <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;
@@ -115,6 +133,7 @@ internal sealed record ServerOptions
TestSite = TestSite,
TestSiteAutoLogin = TestSiteAutoLogin,
FirstSessionDelay = FirstSessionDelay,
Collection = Collection,
Warnings = Warnings,
};
@@ -188,9 +207,28 @@ internal sealed record ServerOptions
return false;
}
var collection = CollectionRoute.Pages;
if (Env(CollectionRouteNames.EnvironmentVariable) is { } collectionText && !CollectionRouteNames.TryParse(collectionText, out collection))
{
problem = CollectionRouteNames.Problem(CollectionRouteNames.EnvironmentVariable, collectionText);
return false;
}
// Raw, like the password: the value never reaches a warning, a problem or the log.
byte[]? sessionKey = null;
string? sessionKeyProblem = null;
if (environment(Core.Security.SessionKey.EnvironmentVariable) is { Length: > 0 } keyText
&& !Core.Security.SessionKey.TryParse(keyText, out sessionKey, out sessionKeyProblem))
{
sessionKey = null;
}
options = options with
{
Password = environment("FEBE_PASSWORD") is { Length: > 0 } password ? password : null,
Password = environment(ChildProcessEnvironment.PasswordVariable) is { Length: > 0 } password ? password : null,
SessionKey = sessionKey,
SessionKeyProblem = sessionKeyProblem,
Collection = collection,
Port = port,
ZoneId = zoneId,
Zone = zone,
@@ -286,6 +324,19 @@ internal sealed record ServerOptions
case "--accesso-di-prova":
options = options with { TestSiteAutoLogin = true };
break;
case CollectionRouteNames.Option:
{
var text = Next();
if (!CollectionRouteNames.TryParse(text, out var route))
{
problem = CollectionRouteNames.Problem(CollectionRouteNames.Option, text);
return false;
}
options = options with { Collection = route };
break;
}
case "--prima-sessione":
{
var text = Next();
@@ -339,6 +390,19 @@ internal sealed record ServerOptions
return true;
}
/// <summary>
/// What the options are, for a debugger or an exception: the secrets only as «impostata» or «assente», never their
/// value (the generated text of a record would print them).
/// </summary>
public override string ToString()
{
var password = string.IsNullOrEmpty(Password) ? "assente" : "impostata";
var key = SessionKey is not null ? "impostata" : SessionKeyProblem is not null ? "non valida" : "assente";
return string.Create(
CultureInfo.InvariantCulture,
$"ServerOptions {{ Dati = {DataFolder}, Libreria = {LibraryFolder}, Porta = {Port}, Sito = {Site.Name}, Raccolta = {CollectionRouteNames.Name(Collection)}, {ChildProcessEnvironment.PasswordVariable} = {password}, {Core.Security.SessionKey.EnvironmentVariable} = {key} }}");
}
/// <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;
+32 -2
View File
@@ -1,12 +1,14 @@
using Febe.App;
using Febe.Core.Library;
using Febe.Core.Security;
using Febe.Web.Connection;
namespace Febe.Server;
/// <summary>
/// The checks made before anything starts (spec §8.2, §11): the interface password and the Data folder. With a problem
/// the engine and the browser do not start, and the interface shows only the page that explains it.
/// The checks made before anything starts (spec §8.2, §11): the interface password, the Data folder and the key of the
/// saved session (issue #36, S4). With a problem the engine and the browser do not start, and the interface shows only
/// the page that explains it. No text ever holds the password or the key.
/// </summary>
internal static class StartupChecks
{
@@ -16,6 +18,12 @@ internal static class StartupChecks
public const string DataOnNetwork = DataFolderProblems.DataOnNetwork;
/// <summary>FEBE_CHIAVE_SESSIONE is set but is not a key of 32 bytes.</summary>
public const string SessionKeyInvalid = "chiave-sessione-non-valida";
/// <summary>Dati/sessione/chiave.bin is there but is not a key of Febe (or cannot be read).</summary>
public const string SessionKeyFileInvalid = "chiave-sessione-file";
/// <summary>Every problem found, in the order the error page shows them.</summary>
public static IReadOnlyList<ConfigurationProblem> Run(ServerOptions options, DataFolderCheck? check = null)
{
@@ -36,6 +44,28 @@ internal static class StartupChecks
problems.Add(data);
}
// A key set by hand that is wrong is always said, whatever the «raccolta»: left silent, it would surprise later.
if (options.SessionKeyProblem is { } keyProblem)
{
problems.Add(new ConfigurationProblem(
SessionKeyInvalid,
"La chiave della sessione salvata non è valida",
keyProblem + " Febe non ha avviato né il motore né il browser, per non cifrare la sessione con una chiave sbagliata.",
$"Correggi {SessionKey.EnvironmentVariable} (nel modello di Unraid o in compose.yml) con 32 byte in base64, per esempio il risultato di «openssl rand -base64 32», oppure toglila: Febe userà Dati/sessione/chiave.bin. Poi riavvia il contenitore."));
}
// chiave.bin is read only by the requests route, and only when the variable does not give the key.
if (options.Collection == CollectionRoute.Requests && options.SessionKey is null && options.SessionKeyProblem is null
&& SessionKey.CheckFile(new DataFolderLayout(options.DataFolder).SessionKeyFile) is { } fileProblem)
{
problems.Add(new ConfigurationProblem(
SessionKeyFileInvalid,
"La chiave della sessione salvata non si legge",
fileProblem + " Febe non ha avviato né il motore né il browser.",
"Cancella Dati/sessione/chiave.bin (la sessione salvata non si leggerà più: basta rifare l'accesso), oppure imposta "
+ $"{SessionKey.EnvironmentVariable}, poi riavvia il contenitore."));
}
return problems;
}
}
+1 -1
View File
@@ -726,7 +726,7 @@
"usaBrowserTesto": "Per controllare qualcosa a mano. Mentre usi il browser il motore resta fermo.",
"scollega": "Scollega…",
"scollegaTitolo": "Scollegare Febe da Instagram?",
"scollegaTesto": "Febe ferma il motore e cancella il profilo del suo browser, con la sessione. Per chiudere la sessione anche dal lato di Instagram, prima esci dal sito usando tu il browser (menu del profilo, «Esci»), poi torna qui.",
"scollegaTesto": "Febe ferma il motore e cancella il profilo del suo browser, con la sessione, e la copia della sessione salvata per le richieste, se c'è. Per chiudere la sessione anche dal lato di Instagram, prima esci dal sito usando tu il browser (menu del profilo, «Esci»), poi torna qui.",
"scollegaConferma": "Scollega e cancella la sessione",
"usaPrima": "Usa prima il browser",
"scollegato": "Febe è scollegato da Instagram.",