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>
This commit is contained in:
1 parent
3046b2da47
commit
c87768766c
69 files changed
+5936
-415
No files matched your search
@@ -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)
|
||||
|
||||
@@ -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.<sito>.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.<sito>.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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user