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;
/// One value of the page the copy reads: the session field, and the module and property that hold it.
/// The session field ().
/// The module of the page's require.
/// The property of the module; null for a module whose export is the value (a doc_id).
public sealed record PageRead(string Field, string Module, string? Property);
///
/// 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
/// page section of richieste.<sito>.json names (checked identifiers). Holds names only.
///
public sealed class SessionCapturePlan
{
private SessionCapturePlan(Uri site, HostClassifier hosts, IReadOnlyList cookieUrls, IReadOnlyList values, IReadOnlyList docIds, IReadOnlyList refusedPaths, IReadOnlySet neededValues, IReadOnlySet neededDocIds)
{
Site = site;
Hosts = hosts;
CookieUrls = cookieUrls;
Values = values;
DocIds = docIds;
RefusedPaths = refusedPaths;
NeededValues = neededValues;
NeededDocIds = neededDocIds;
}
/// The root of the site (https://www.instagram.com/, http://127.0.0.1:port/).
public Uri Site { get; }
/// The hosts of the site: the page must be on one of them.
public HostClassifier Hosts { get; }
///
/// The addresses Network.getCookies is asked for: the root and, for each path of the catalog, the path up to
/// its first value (/api/dati/profilo/{nome} → /api/dati/profilo/), so a cookie limited to a path of the
/// site client is copied with it.
///
public IReadOnlyList CookieUrls { get; }
/// The values of the page, in the order of the catalog's page section.
public IReadOnlyList Values { get; }
/// The doc_id of every GraphQL operation of the catalog (configured or not): is the operation.
public IReadOnlyList DocIds { get; }
/// Paths of the site where no copy is made: the login and verification pages of the stop rules (§7.6).
public IReadOnlyList RefusedPaths { get; }
///
/// The values of the page a configured operation sends (session:<field>): 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.
///
public IReadOnlySet NeededValues { get; }
/// The configured GraphQL operations that send their doc_id from the saved session.
public IReadOnlySet NeededDocIds { get; }
/// The plan of from its catalog and its stop rules.
/// The site of the composition.
/// Its richieste.<sito>.json; without a page section only cookies and user agent are read.
/// Its stop rules: every path rule for the site is a page where no copy is made. Null: none.
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 { 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();
var docIds = new List();
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(StringComparer.Ordinal);
var neededDocIds = new HashSet(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);
}
/// Counts only.
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.");
}
/// Why a copy was not made.
public enum CaptureRefusal
{
/// The page is not on the site (the rest page, another host).
NotOnSite,
/// The page is a login or verification page of the site (a path of the stop rules).
CheckpointPage,
/// The browser gave no user agent.
NoUserAgent,
/// The browser did not answer, or refused (restarting, closed, too slow).
BrowserError,
}
///
/// What a copy found. Its text and its members hold counts and names only; the values are in ,
/// whose text shows counts too (rule 10).
///
public sealed class SessionCaptureResult
{
internal SessionCaptureResult(SiteSessionValues? values, CaptureRefusal? refusal, int droppedCookies, IReadOnlyList missingValues, IReadOnlyList missingDocIds, int expectedValues, int expectedDocIds)
{
Values = values;
Refusal = refusal;
DroppedCookies = droppedCookies;
MissingValues = missingValues;
MissingDocIds = missingDocIds;
ExpectedValues = expectedValues;
ExpectedDocIds = expectedDocIds;
}
/// The copied session; null when the copy was refused.
public SiteSessionValues? Values { get; }
/// Why nothing was copied; null when is there.
public CaptureRefusal? Refusal { get; }
/// How many cookies were copied.
public int Cookies => Values?.Cookies.Count ?? 0;
/// Cookies of the site left out: partitioned, or with a name or value a browser would not send back.
public int DroppedCookies { get; }
/// The session fields the page did not give (left absent, never guessed: rule 9).
public IReadOnlyList MissingValues { get; }
/// The GraphQL operations whose doc_id the page did not give.
public IReadOnlyList MissingDocIds { get; }
/// How many values of the page the plan asked for.
public int ExpectedValues { get; }
/// How many doc_id the plan asked for.
public int ExpectedDocIds { get; }
internal static SessionCaptureResult Refused(CaptureRefusal refusal) => new(null, refusal, 0, [], [], 0, 0);
/// Counts and names only.
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}.");
}
///
/// The copy of the browser's session into a saved session (issue #36, S4, spec §6.0, §6.1 «Copiare la sessione»): only
/// Page.getFrameTree (where the page is), Network.getCookies with the values for the site's addresses,
/// and ONE read-only Runtime.evaluate that reads navigator.userAgent 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.
///
///
/// 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.
///
public static class SessionCapture
{
/// The longest page value kept.
public const int MaxValueLength = 4096;
///
/// Copies the session the page holds now.
///
/// was cancelled.
public static async Task 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;
}
}
/// The cookies of for a host of the site, and how many were left out.
private static (List Cookies, int Dropped) ReadCookies(JsonElement answer, SessionCapturePlan plan)
{
var kept = new List();
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);
}
/// The values of the plan asked for and the page gave; the names of the others.
private static Dictionary Collect(JsonElement read, string section, IReadOnlyList asked, out IReadOnlyList missing)
{
var found = new Dictionary(StringComparer.Ordinal);
var absent = new List();
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;
}
/// A string of at most printable ASCII characters, or null.
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;
}
///
/// The one expression of the copy (§6.1: Runtime.evaluate 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
/// . Every module is read in its own try: an unknown module, or one the page
/// refuses, is a missing value and never an error that leaves the expression.
///
public static class SessionCaptureScript
{
/// The expression for .
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();
}
/// A JavaScript string literal (JSON) for .
private static string Quote(string name) => JsonValue.Create(name).ToJsonString();
private static void Append(StringBuilder text, string section, IReadOnlyList 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");
}
}
}