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

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

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

465 lines
21 KiB
C#

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");
}
}
}