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);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,23 @@
|
||||
{
|
||||
"site": "instagram",
|
||||
"note": "Operazioni che il client del sito può chiedere a Instagram (issue #36, specifica §6.0). Scritte il 16 novembre 2026 dalle forme reali delle richieste ricavate con «febe-sonda richieste» dai file HAR del 12 novembre (con e senza scorrimento) e del 16 novembre, fuori dal repository e senza valori; le risposte sono documentate dai campioni ripuliti di tests/Febe.Tests/campioni/instagram (regola 9). Solo letture: il codice rifiuta ogni «Mutation», la telemetria, la navigazione della pagina e le famiglie di chat, messaggi, presenza e promozioni, anche se una copia modificata le elencasse. Nessun doc_id qui: si legge dai moduli della pagina all'accesso (tappa S4). Fonti dei valori: constant (dalle forme), cookie:csrftoken, session:… (copiato a «Ho finito»: user_agent, lsd, fb_dtsg, app_id, claim, account_id, doc_id), operation, variables, computed, pending (nome noto, fonte ancora da stabilire: tappa S4). Le forme scrivono i vero/falso del JSON come true/false, ma non distinguono un numero da un testo di cifre: i numeri delle variabili (count 12, first 3) sono scritti come numeri, da confermare. «(nome tolto)» e «(valore tolto)» sono ciò che la sonda non mostra: un'operazione che li ha nelle variabili resta non configurata. L'elenco dei seguiti manca: nessuna forma con la risposta.",
|
||||
"note": "Operazioni che il client del sito può chiedere a Instagram (issue #36, specifica §6.0). Scritte il 16 novembre 2026 dalle forme reali delle richieste ricavate con «febe-sonda richieste» dai file HAR del 12 novembre (con e senza scorrimento) e del 16 novembre, fuori dal repository e senza valori; le risposte sono documentate dai campioni ripuliti di tests/Febe.Tests/campioni/instagram (regola 9). Solo letture: il codice rifiuta ogni «Mutation», la telemetria, la navigazione della pagina e le famiglie di chat, messaggi, presenza e promozioni, anche se una copia modificata le elencasse. Nessun doc_id né altro valore qui: la sezione «page» dice in quale modulo della pagina si trova ciascuno, e «Ho finito» li copia nella sessione salvata (tappa S4). I posti della sezione «page» vengono dal codice pubblico della pagina del HAR, solo forme e nomi: __rev da SiteData.client_revision, __hs da SiteData.haste_session, __hsi da SiteData.hsi, dpr da SiteData.pr, __comet_req da SiteData.comet_env, __ccg da WebConnectionClassServerGuess.connectionClass, x-fb-entry-nonce da BootloaderConfig.nonce, i doc_id dal modulo «<operazione>_instagramRelayOperation»; dpr e __comet_req erano costanti (1 e 7) e ora si leggono dalla pagina. Fonti dei valori: constant (dalle forme), cookie:csrftoken, session:… (copiato a «Ho finito»: user_agent, claim, doc_id e i valori della sezione «page»: lsd, fb_dtsg, app_id, account_id, rev, hs, hsi, dpr, ccg, comet_req, entry_nonce), operation, variables, computed, pending (nome noto, fonte da stabilire: valori che la pagina calcola mentre gira come __req, __s, __dyn, __csr, __hblp, __hsdp, __sjsp, __crn, __d e __spin_r/__spin_b/__spin_t, le intestazioni del browser come referer, priority e sec-ch-ua, e i nomi tolti dalla sonda). Un'operazione configurata con un valore session:… senza posto nella sezione «page» è rifiutata. Le forme scrivono i vero/falso del JSON come true/false, ma non distinguono un numero da un testo di cifre: i numeri delle variabili (count 12, first 3) sono scritti come numeri, da confermare. «(nome tolto)» e «(valore tolto)» sono ciò che la sonda non mostra: un'operazione che li ha nelle variabili resta non configurata. L'elenco dei seguiti manca: nessuna forma con la risposta.",
|
||||
"page": {
|
||||
"note": "Dove la pagina tiene i valori della sessione: «Modulo.proprietà» del require della pagina; docIdModule con {operation} per il nome dell'operazione. Solo nomi, nessun valore.",
|
||||
"docIdModule": "{operation}_instagramRelayOperation",
|
||||
"values": {
|
||||
"lsd": "LSD.token",
|
||||
"fb_dtsg": "DTSGInitialData.token",
|
||||
"account_id": "CurrentUserInitialData.USER_ID",
|
||||
"app_id": "CurrentUserInitialData.APP_ID",
|
||||
"rev": "SiteData.client_revision",
|
||||
"hs": "SiteData.haste_session",
|
||||
"hsi": "SiteData.hsi",
|
||||
"dpr": "SiteData.pr",
|
||||
"comet_req": "SiteData.comet_env",
|
||||
"ccg": "WebConnectionClassServerGuess.connectionClass",
|
||||
"entry_nonce": "BootloaderConfig.nonce"
|
||||
}
|
||||
},
|
||||
"operations": [
|
||||
{
|
||||
"name": "PolarisSearchBoxRefetchableQuery",
|
||||
@@ -26,7 +43,7 @@
|
||||
"user-agent": "session:user_agent",
|
||||
"x-asbd-id": "constant:359341",
|
||||
"x-csrftoken": "cookie:csrftoken",
|
||||
"x-fb-entry-nonce": "pending",
|
||||
"x-fb-entry-nonce": "session:entry_nonce",
|
||||
"x-fb-friendly-name": "operation",
|
||||
"x-fb-lsd": "session:lsd",
|
||||
"x-ig-app-id": "session:app_id",
|
||||
@@ -35,18 +52,18 @@
|
||||
"body": {
|
||||
"(nome tolto)": "pending",
|
||||
"__a": "constant:1",
|
||||
"__ccg": "pending",
|
||||
"__comet_req": "constant:7",
|
||||
"__ccg": "session:ccg",
|
||||
"__comet_req": "session:comet_req",
|
||||
"__crn": "pending",
|
||||
"__csr": "pending",
|
||||
"__d": "pending",
|
||||
"__dyn": "pending",
|
||||
"__hblp": "pending",
|
||||
"__hs": "pending",
|
||||
"__hs": "session:hs",
|
||||
"__hsdp": "pending",
|
||||
"__hsi": "pending",
|
||||
"__hsi": "session:hsi",
|
||||
"__req": "pending",
|
||||
"__rev": "pending",
|
||||
"__rev": "session:rev",
|
||||
"__s": "pending",
|
||||
"__sjsp": "pending",
|
||||
"__spin_b": "pending",
|
||||
@@ -55,7 +72,7 @@
|
||||
"__user": "session:account_id",
|
||||
"av": "session:account_id",
|
||||
"doc_id": "session:doc_id",
|
||||
"dpr": "constant:1",
|
||||
"dpr": "session:dpr",
|
||||
"fb_api_caller_class": "constant:RelayModern",
|
||||
"fb_api_req_friendly_name": "operation",
|
||||
"fb_dtsg": "session:fb_dtsg",
|
||||
@@ -108,7 +125,7 @@
|
||||
"user-agent": "session:user_agent",
|
||||
"x-asbd-id": "constant:359341",
|
||||
"x-csrftoken": "cookie:csrftoken",
|
||||
"x-fb-entry-nonce": "pending",
|
||||
"x-fb-entry-nonce": "session:entry_nonce",
|
||||
"x-fb-friendly-name": "operation",
|
||||
"x-fb-lsd": "session:lsd",
|
||||
"x-ig-app-id": "session:app_id",
|
||||
@@ -117,18 +134,18 @@
|
||||
"body": {
|
||||
"(nome tolto)": "pending",
|
||||
"__a": "constant:1",
|
||||
"__ccg": "pending",
|
||||
"__comet_req": "constant:7",
|
||||
"__ccg": "session:ccg",
|
||||
"__comet_req": "session:comet_req",
|
||||
"__crn": "pending",
|
||||
"__csr": "pending",
|
||||
"__d": "pending",
|
||||
"__dyn": "pending",
|
||||
"__hblp": "pending",
|
||||
"__hs": "pending",
|
||||
"__hs": "session:hs",
|
||||
"__hsdp": "pending",
|
||||
"__hsi": "pending",
|
||||
"__hsi": "session:hsi",
|
||||
"__req": "pending",
|
||||
"__rev": "pending",
|
||||
"__rev": "session:rev",
|
||||
"__s": "pending",
|
||||
"__sjsp": "pending",
|
||||
"__spin_b": "pending",
|
||||
@@ -137,7 +154,7 @@
|
||||
"__user": "session:account_id",
|
||||
"av": "session:account_id",
|
||||
"doc_id": "session:doc_id",
|
||||
"dpr": "constant:1",
|
||||
"dpr": "session:dpr",
|
||||
"fb_api_caller_class": "constant:RelayModern",
|
||||
"fb_api_req_friendly_name": "operation",
|
||||
"fb_dtsg": "session:fb_dtsg",
|
||||
@@ -186,7 +203,7 @@
|
||||
"user-agent": "session:user_agent",
|
||||
"x-asbd-id": "constant:359341",
|
||||
"x-csrftoken": "cookie:csrftoken",
|
||||
"x-fb-entry-nonce": "pending",
|
||||
"x-fb-entry-nonce": "session:entry_nonce",
|
||||
"x-fb-friendly-name": "operation",
|
||||
"x-fb-lsd": "session:lsd",
|
||||
"x-ig-app-id": "session:app_id",
|
||||
@@ -195,18 +212,18 @@
|
||||
"body": {
|
||||
"(nome tolto)": "pending",
|
||||
"__a": "constant:1",
|
||||
"__ccg": "pending",
|
||||
"__comet_req": "constant:7",
|
||||
"__ccg": "session:ccg",
|
||||
"__comet_req": "session:comet_req",
|
||||
"__crn": "pending",
|
||||
"__csr": "pending",
|
||||
"__d": "pending",
|
||||
"__dyn": "pending",
|
||||
"__hblp": "pending",
|
||||
"__hs": "pending",
|
||||
"__hs": "session:hs",
|
||||
"__hsdp": "pending",
|
||||
"__hsi": "pending",
|
||||
"__hsi": "session:hsi",
|
||||
"__req": "pending",
|
||||
"__rev": "pending",
|
||||
"__rev": "session:rev",
|
||||
"__s": "pending",
|
||||
"__sjsp": "pending",
|
||||
"__spin_b": "pending",
|
||||
@@ -215,7 +232,7 @@
|
||||
"__user": "session:account_id",
|
||||
"av": "session:account_id",
|
||||
"doc_id": "session:doc_id",
|
||||
"dpr": "constant:1",
|
||||
"dpr": "session:dpr",
|
||||
"fb_api_caller_class": "constant:RelayModern",
|
||||
"fb_api_req_friendly_name": "operation",
|
||||
"fb_dtsg": "session:fb_dtsg",
|
||||
@@ -253,7 +270,7 @@
|
||||
"category": "storico",
|
||||
"roles": ["reels"],
|
||||
"configured": false,
|
||||
"reason": "le variabili sono note, ma intestazioni e campi della pagina e del browser (come __dyn, __csr, referer, sec-ch-ua e quello con il nome tolto dalla sonda) hanno ancora la fonte «pending»: finché non si sa da dove vengono i valori la richiesta non si scrive (regola 9, tappa S4)",
|
||||
"reason": "le variabili sono note, ma intestazioni e campi della pagina e del browser (come __dyn, __csr, referer, sec-ch-ua e quello con il nome tolto dalla sonda) hanno ancora la fonte «pending»: finché non si sa da dove vengono i valori la richiesta non si scrive (regola 9)",
|
||||
"headers": {
|
||||
"(nome tolto)": "pending",
|
||||
"accept": "constant:*/*",
|
||||
@@ -270,7 +287,7 @@
|
||||
"user-agent": "session:user_agent",
|
||||
"x-asbd-id": "constant:359341",
|
||||
"x-csrftoken": "cookie:csrftoken",
|
||||
"x-fb-entry-nonce": "pending",
|
||||
"x-fb-entry-nonce": "session:entry_nonce",
|
||||
"x-fb-friendly-name": "operation",
|
||||
"x-fb-lsd": "session:lsd",
|
||||
"x-ig-app-id": "session:app_id",
|
||||
@@ -279,18 +296,18 @@
|
||||
"body": {
|
||||
"(nome tolto)": "pending",
|
||||
"__a": "constant:1",
|
||||
"__ccg": "pending",
|
||||
"__comet_req": "constant:7",
|
||||
"__ccg": "session:ccg",
|
||||
"__comet_req": "session:comet_req",
|
||||
"__crn": "pending",
|
||||
"__csr": "pending",
|
||||
"__d": "pending",
|
||||
"__dyn": "pending",
|
||||
"__hblp": "pending",
|
||||
"__hs": "pending",
|
||||
"__hs": "session:hs",
|
||||
"__hsdp": "pending",
|
||||
"__hsi": "pending",
|
||||
"__hsi": "session:hsi",
|
||||
"__req": "pending",
|
||||
"__rev": "pending",
|
||||
"__rev": "session:rev",
|
||||
"__s": "pending",
|
||||
"__sjsp": "pending",
|
||||
"__spin_b": "pending",
|
||||
@@ -299,7 +316,7 @@
|
||||
"__user": "session:account_id",
|
||||
"av": "session:account_id",
|
||||
"doc_id": "session:doc_id",
|
||||
"dpr": "constant:1",
|
||||
"dpr": "session:dpr",
|
||||
"fb_api_caller_class": "constant:RelayModern",
|
||||
"fb_api_req_friendly_name": "operation",
|
||||
"fb_dtsg": "session:fb_dtsg",
|
||||
@@ -332,7 +349,7 @@
|
||||
"category": "storico",
|
||||
"roles": ["tagged"],
|
||||
"configured": false,
|
||||
"reason": "le variabili sono note, ma intestazioni e campi della pagina e del browser (come __dyn, __csr, referer, sec-ch-ua e quello con il nome tolto dalla sonda) hanno ancora la fonte «pending»: finché non si sa da dove vengono i valori la richiesta non si scrive (regola 9, tappa S4)",
|
||||
"reason": "le variabili sono note, ma intestazioni e campi della pagina e del browser (come __dyn, __csr, referer, sec-ch-ua e quello con il nome tolto dalla sonda) hanno ancora la fonte «pending»: finché non si sa da dove vengono i valori la richiesta non si scrive (regola 9)",
|
||||
"headers": {
|
||||
"(nome tolto)": "pending",
|
||||
"accept": "constant:*/*",
|
||||
@@ -349,7 +366,7 @@
|
||||
"user-agent": "session:user_agent",
|
||||
"x-asbd-id": "constant:359341",
|
||||
"x-csrftoken": "cookie:csrftoken",
|
||||
"x-fb-entry-nonce": "pending",
|
||||
"x-fb-entry-nonce": "session:entry_nonce",
|
||||
"x-fb-friendly-name": "operation",
|
||||
"x-fb-lsd": "session:lsd",
|
||||
"x-ig-app-id": "session:app_id",
|
||||
@@ -358,18 +375,18 @@
|
||||
"body": {
|
||||
"(nome tolto)": "pending",
|
||||
"__a": "constant:1",
|
||||
"__ccg": "pending",
|
||||
"__comet_req": "constant:7",
|
||||
"__ccg": "session:ccg",
|
||||
"__comet_req": "session:comet_req",
|
||||
"__crn": "pending",
|
||||
"__csr": "pending",
|
||||
"__d": "pending",
|
||||
"__dyn": "pending",
|
||||
"__hblp": "pending",
|
||||
"__hs": "pending",
|
||||
"__hs": "session:hs",
|
||||
"__hsdp": "pending",
|
||||
"__hsi": "pending",
|
||||
"__hsi": "session:hsi",
|
||||
"__req": "pending",
|
||||
"__rev": "pending",
|
||||
"__rev": "session:rev",
|
||||
"__s": "pending",
|
||||
"__sjsp": "pending",
|
||||
"__spin_b": "pending",
|
||||
@@ -378,7 +395,7 @@
|
||||
"__user": "session:account_id",
|
||||
"av": "session:account_id",
|
||||
"doc_id": "session:doc_id",
|
||||
"dpr": "constant:1",
|
||||
"dpr": "session:dpr",
|
||||
"fb_api_caller_class": "constant:RelayModern",
|
||||
"fb_api_req_friendly_name": "operation",
|
||||
"fb_dtsg": "session:fb_dtsg",
|
||||
@@ -408,7 +425,7 @@
|
||||
"category": "profilo",
|
||||
"roles": ["highlights"],
|
||||
"configured": false,
|
||||
"reason": "le variabili sono note, ma intestazioni e campi della pagina e del browser (come __dyn, __csr, referer, sec-ch-ua e quello con il nome tolto dalla sonda) hanno ancora la fonte «pending»: finché non si sa da dove vengono i valori la richiesta non si scrive (regola 9, tappa S4)",
|
||||
"reason": "le variabili sono note, ma intestazioni e campi della pagina e del browser (come __dyn, __csr, referer, sec-ch-ua e quello con il nome tolto dalla sonda) hanno ancora la fonte «pending»: finché non si sa da dove vengono i valori la richiesta non si scrive (regola 9)",
|
||||
"headers": {
|
||||
"(nome tolto)": "pending",
|
||||
"accept": "constant:*/*",
|
||||
@@ -425,7 +442,7 @@
|
||||
"user-agent": "session:user_agent",
|
||||
"x-asbd-id": "constant:359341",
|
||||
"x-csrftoken": "cookie:csrftoken",
|
||||
"x-fb-entry-nonce": "pending",
|
||||
"x-fb-entry-nonce": "session:entry_nonce",
|
||||
"x-fb-friendly-name": "operation",
|
||||
"x-fb-lsd": "session:lsd",
|
||||
"x-ig-app-id": "session:app_id",
|
||||
@@ -434,18 +451,18 @@
|
||||
"body": {
|
||||
"(nome tolto)": "pending",
|
||||
"__a": "constant:1",
|
||||
"__ccg": "pending",
|
||||
"__comet_req": "constant:7",
|
||||
"__ccg": "session:ccg",
|
||||
"__comet_req": "session:comet_req",
|
||||
"__crn": "pending",
|
||||
"__csr": "pending",
|
||||
"__d": "pending",
|
||||
"__dyn": "pending",
|
||||
"__hblp": "pending",
|
||||
"__hs": "pending",
|
||||
"__hs": "session:hs",
|
||||
"__hsdp": "pending",
|
||||
"__hsi": "pending",
|
||||
"__hsi": "session:hsi",
|
||||
"__req": "pending",
|
||||
"__rev": "pending",
|
||||
"__rev": "session:rev",
|
||||
"__s": "pending",
|
||||
"__sjsp": "pending",
|
||||
"__spin_b": "pending",
|
||||
@@ -454,7 +471,7 @@
|
||||
"__user": "session:account_id",
|
||||
"av": "session:account_id",
|
||||
"doc_id": "session:doc_id",
|
||||
"dpr": "constant:1",
|
||||
"dpr": "session:dpr",
|
||||
"fb_api_caller_class": "constant:RelayModern",
|
||||
"fb_api_req_friendly_name": "operation",
|
||||
"fb_dtsg": "session:fb_dtsg",
|
||||
@@ -498,7 +515,7 @@
|
||||
"user-agent": "session:user_agent",
|
||||
"x-asbd-id": "constant:359341",
|
||||
"x-csrftoken": "cookie:csrftoken",
|
||||
"x-fb-entry-nonce": "pending",
|
||||
"x-fb-entry-nonce": "session:entry_nonce",
|
||||
"x-fb-friendly-name": "operation",
|
||||
"x-fb-lsd": "session:lsd",
|
||||
"x-ig-app-id": "session:app_id",
|
||||
@@ -507,18 +524,18 @@
|
||||
"body": {
|
||||
"(nome tolto)": "pending",
|
||||
"__a": "constant:1",
|
||||
"__ccg": "pending",
|
||||
"__comet_req": "constant:7",
|
||||
"__ccg": "session:ccg",
|
||||
"__comet_req": "session:comet_req",
|
||||
"__crn": "pending",
|
||||
"__csr": "pending",
|
||||
"__d": "pending",
|
||||
"__dyn": "pending",
|
||||
"__hblp": "pending",
|
||||
"__hs": "pending",
|
||||
"__hs": "session:hs",
|
||||
"__hsdp": "pending",
|
||||
"__hsi": "pending",
|
||||
"__hsi": "session:hsi",
|
||||
"__req": "pending",
|
||||
"__rev": "pending",
|
||||
"__rev": "session:rev",
|
||||
"__s": "pending",
|
||||
"__sjsp": "pending",
|
||||
"__spin_b": "pending",
|
||||
@@ -527,7 +544,7 @@
|
||||
"__user": "session:account_id",
|
||||
"av": "session:account_id",
|
||||
"doc_id": "session:doc_id",
|
||||
"dpr": "constant:1",
|
||||
"dpr": "session:dpr",
|
||||
"fb_api_analytics_tags": "pending",
|
||||
"fb_api_caller_class": "constant:RelayModern",
|
||||
"fb_api_req_friendly_name": "operation",
|
||||
@@ -577,7 +594,7 @@
|
||||
"x-asbd-id": "constant:359341",
|
||||
"x-bloks-version-id": "constant:e9f7142825abe6e3e169776ae34e2fc4aeb2fa7ccdf139d43730b2f13505e200",
|
||||
"x-csrftoken": "cookie:csrftoken",
|
||||
"x-fb-entry-nonce": "pending",
|
||||
"x-fb-entry-nonce": "session:entry_nonce",
|
||||
"x-fb-friendly-name": "operation",
|
||||
"x-fb-lsd": "session:lsd",
|
||||
"x-ig-app-id": "session:app_id",
|
||||
@@ -587,18 +604,18 @@
|
||||
"body": {
|
||||
"(nome tolto)": "pending",
|
||||
"__a": "constant:1",
|
||||
"__ccg": "pending",
|
||||
"__comet_req": "constant:7",
|
||||
"__ccg": "session:ccg",
|
||||
"__comet_req": "session:comet_req",
|
||||
"__crn": "pending",
|
||||
"__csr": "pending",
|
||||
"__d": "pending",
|
||||
"__dyn": "pending",
|
||||
"__hblp": "pending",
|
||||
"__hs": "pending",
|
||||
"__hs": "session:hs",
|
||||
"__hsdp": "pending",
|
||||
"__hsi": "pending",
|
||||
"__hsi": "session:hsi",
|
||||
"__req": "pending",
|
||||
"__rev": "pending",
|
||||
"__rev": "session:rev",
|
||||
"__s": "pending",
|
||||
"__sjsp": "pending",
|
||||
"__spin_b": "pending",
|
||||
@@ -607,7 +624,7 @@
|
||||
"__user": "session:account_id",
|
||||
"av": "session:account_id",
|
||||
"doc_id": "session:doc_id",
|
||||
"dpr": "constant:1",
|
||||
"dpr": "session:dpr",
|
||||
"fb_api_caller_class": "constant:RelayModern",
|
||||
"fb_api_req_friendly_name": "operation",
|
||||
"fb_dtsg": "session:fb_dtsg",
|
||||
@@ -658,7 +675,7 @@
|
||||
"x-asbd-id": "constant:359341",
|
||||
"x-bloks-version-id": "constant:e9f7142825abe6e3e169776ae34e2fc4aeb2fa7ccdf139d43730b2f13505e200",
|
||||
"x-csrftoken": "cookie:csrftoken",
|
||||
"x-fb-entry-nonce": "pending",
|
||||
"x-fb-entry-nonce": "session:entry_nonce",
|
||||
"x-fb-friendly-name": "operation",
|
||||
"x-fb-lsd": "session:lsd",
|
||||
"x-ig-app-id": "session:app_id",
|
||||
@@ -668,18 +685,18 @@
|
||||
"body": {
|
||||
"(nome tolto)": "pending",
|
||||
"__a": "constant:1",
|
||||
"__ccg": "pending",
|
||||
"__comet_req": "constant:7",
|
||||
"__ccg": "session:ccg",
|
||||
"__comet_req": "session:comet_req",
|
||||
"__crn": "pending",
|
||||
"__csr": "pending",
|
||||
"__d": "pending",
|
||||
"__dyn": "pending",
|
||||
"__hblp": "pending",
|
||||
"__hs": "pending",
|
||||
"__hs": "session:hs",
|
||||
"__hsdp": "pending",
|
||||
"__hsi": "pending",
|
||||
"__hsi": "session:hsi",
|
||||
"__req": "pending",
|
||||
"__rev": "pending",
|
||||
"__rev": "session:rev",
|
||||
"__s": "pending",
|
||||
"__sjsp": "pending",
|
||||
"__spin_b": "pending",
|
||||
@@ -688,7 +705,7 @@
|
||||
"__user": "session:account_id",
|
||||
"av": "session:account_id",
|
||||
"doc_id": "session:doc_id",
|
||||
"dpr": "constant:1",
|
||||
"dpr": "session:dpr",
|
||||
"fb_api_analytics_tags": "pending",
|
||||
"fb_api_caller_class": "constant:RelayModern",
|
||||
"fb_api_req_friendly_name": "operation",
|
||||
@@ -726,7 +743,7 @@
|
||||
"category": "post",
|
||||
"roles": ["post"],
|
||||
"configured": false,
|
||||
"reason": "il percorso è noto, ma intestazioni della pagina e del browser (come referer, sec-ch-ua e quella con il nome tolto dalla sonda) hanno ancora la fonte «pending»: finché non si sa da dove vengono i valori la richiesta non si scrive (regola 9, tappa S4)",
|
||||
"reason": "il percorso è noto, ma intestazioni della pagina e del browser (come referer, sec-ch-ua e quella con il nome tolto dalla sonda) hanno ancora la fonte «pending»: finché non si sa da dove vengono i valori la richiesta non si scrive (regola 9)",
|
||||
"headers": {
|
||||
"(nome tolto)": "pending",
|
||||
"accept": "constant:*/*",
|
||||
|
||||
@@ -1,6 +1,23 @@
|
||||
{
|
||||
"site": "prova",
|
||||
"note": "Operazioni che il client del sito chiede al sito di prova locale (tools/Febe.SitoDiProva, specifica §14.2) dalla tappa S2 di #36: le stesse risposte JSON che la pagina chiede a /dati/, servite sotto /api/ dove il sito controlla ciò che controlla un sito vero (cookie sessione_prova, x-csrftoken uguale al cookie csrftoken, x-app-id e le altre intestazioni e i campi del modello), documentate dai campioni ripuliti di tests/Febe.Tests/campioni/prova. Le pagine continuano a chiedere /dati/, che non controlla nulla. ProvaProfiloQuery è una richiesta GraphQL (POST /api/graphql con doc_id, nome dell'operazione e variabili) che risponde con il JSON di /dati/profilo/{nome}. Le regole di rifiuto sono le stesse di Instagram (nel codice). La scrittura /dati/ricerche-recenti (POST) non c'è e non può esserci: un indirizzo semplice si legge solo con GET.",
|
||||
"note": "Operazioni che il client del sito chiede al sito di prova locale (tools/Febe.SitoDiProva, specifica §14.2) dalla tappa S2 di #36: le stesse risposte JSON che la pagina chiede a /dati/, servite sotto /api/ dove il sito controlla ciò che controlla un sito vero (cookie sessione_prova, x-csrftoken uguale al cookie csrftoken, x-app-id e le altre intestazioni e i campi del modello), documentate dai campioni ripuliti di tests/Febe.Tests/campioni/prova. Le pagine continuano a chiedere /dati/, che non controlla nulla. ProvaProfiloQuery è una richiesta GraphQL (POST /api/graphql con doc_id, nome dell'operazione e variabili) che risponde con il JSON di /dati/profilo/{nome}. Le regole di rifiuto sono le stesse di Instagram (nel codice). La scrittura /dati/ricerche-recenti (POST) non c'è e non può esserci: un indirizzo semplice si legge solo con GET. La sezione «page» dice dove le pagine del sito di prova tengono i valori della sessione, con nomi di moduli suoi, mai quelli di Instagram: GettoniProva (lsd, dtsg), UtenteProva (id, applicazione), VersioneProva (revisione, hs, hsi, dpr, comet), ConnessioneProva (classe), AvvioProva (nonce) e un modulo «<operazione>_operazioneProva» per ogni doc_id (ProvaProfiloQuery_operazioneProva); i valori sono le costanti di TestSite (tools/Febe.SitoDiProva/DirectApi.cs).",
|
||||
"page": {
|
||||
"note": "Moduli del registro require/__d delle pagine del sito di prova (tools/Febe.SitoDiProva): stessi nomi qui e là.",
|
||||
"docIdModule": "{operation}_operazioneProva",
|
||||
"values": {
|
||||
"lsd": "GettoniProva.lsd",
|
||||
"fb_dtsg": "GettoniProva.dtsg",
|
||||
"account_id": "UtenteProva.id",
|
||||
"app_id": "UtenteProva.applicazione",
|
||||
"rev": "VersioneProva.revisione",
|
||||
"hs": "VersioneProva.hs",
|
||||
"hsi": "VersioneProva.hsi",
|
||||
"dpr": "VersioneProva.dpr",
|
||||
"comet_req": "VersioneProva.comet",
|
||||
"ccg": "ConnessioneProva.classe",
|
||||
"entry_nonce": "AvvioProva.nonce"
|
||||
}
|
||||
},
|
||||
"operations": [
|
||||
{
|
||||
"name": "inizio",
|
||||
@@ -75,12 +92,19 @@
|
||||
"user-agent": "session:user_agent",
|
||||
"x-app-id": "session:app_id",
|
||||
"x-csrftoken": "cookie:csrftoken",
|
||||
"x-fb-entry-nonce": "session:entry_nonce",
|
||||
"x-fb-friendly-name": "operation",
|
||||
"x-ig-www-claim": "session:claim"
|
||||
},
|
||||
"body": {
|
||||
"av": "session:account_id",
|
||||
"__a": "constant:1",
|
||||
"__ccg": "session:ccg",
|
||||
"__comet_req": "session:comet_req",
|
||||
"__hs": "session:hs",
|
||||
"__hsi": "session:hsi",
|
||||
"__rev": "session:rev",
|
||||
"dpr": "session:dpr",
|
||||
"fb_dtsg": "session:fb_dtsg",
|
||||
"lsd": "session:lsd",
|
||||
"fb_api_req_friendly_name": "operation",
|
||||
@@ -97,7 +121,7 @@
|
||||
"profilo"
|
||||
],
|
||||
"sample": "000002-profilo-pubblico",
|
||||
"note": "Una richiesta GraphQL del sito di prova: le stesse forme di Instagram (form con doc_id, fb_api_req_friendly_name e variables; x-csrftoken, x-fb-friendly-name, x-ig-www-claim), la risposta di /dati/profilo/{nome}. Il sito controlla doc_id, nome, gettoni e i tipi delle variabili (primi è il numero 12, raccolte un vero/falso)."
|
||||
"note": "Una richiesta GraphQL del sito di prova: le stesse forme di Instagram (form con doc_id, fb_api_req_friendly_name e variables; x-csrftoken, x-fb-friendly-name, x-ig-www-claim), la risposta di /dati/profilo/{nome}. Il sito controlla doc_id, nome, gettoni e i tipi delle variabili (primi è il numero 12, raccolte un vero/falso). I campi di versione (__rev, __hs, __hsi, __ccg, dpr, __comet_req) e x-fb-entry-nonce vengono dalla sessione salvata, come su Instagram."
|
||||
},
|
||||
{
|
||||
"name": "profilo-altri",
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using Febe.Core.Security;
|
||||
|
||||
namespace Febe.Core.Import;
|
||||
|
||||
@@ -58,9 +59,12 @@ public sealed class FfprobeVideoMetadataProbe : IVideoMetadataProbe
|
||||
return null;
|
||||
}
|
||||
|
||||
public async Task<VideoMetadata?> ProbeAsync(string path, CancellationToken ct = default)
|
||||
/// <summary>
|
||||
/// The start of ffprobe for <paramref name="path"/>: its arguments, and the environment of Febe without
|
||||
/// <c>FEBE_PASSWORD</c> and <c>FEBE_CHIAVE_SESSIONE</c>, removed last (spec §13.2).
|
||||
/// </summary>
|
||||
internal ProcessStartInfo BuildStartInfo(string path)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(path);
|
||||
var start = new ProcessStartInfo(Executable)
|
||||
{
|
||||
RedirectStandardOutput = true,
|
||||
@@ -78,7 +82,13 @@ public sealed class FfprobeVideoMetadataProbe : IVideoMetadataProbe
|
||||
start.ArgumentList.Add(argument);
|
||||
}
|
||||
|
||||
using var process = new Process { StartInfo = start };
|
||||
return start.WithoutSecrets();
|
||||
}
|
||||
|
||||
public async Task<VideoMetadata?> ProbeAsync(string path, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(path);
|
||||
using var process = new Process { StartInfo = BuildStartInfo(path) };
|
||||
try
|
||||
{
|
||||
if (!process.Start())
|
||||
|
||||
@@ -133,4 +133,16 @@ public sealed record DataFolderLayout
|
||||
|
||||
/// <summary>Dati/segnali.json.</summary>
|
||||
public string SignalsFile => Path.Combine(Root, "segnali.json");
|
||||
|
||||
/// <summary>
|
||||
/// Dati/sessione: the saved session of the site client, encrypted, owner-only (issue #36, §13.2). Not in the
|
||||
/// database, so never in the daily copies; never read by the diagnostic report.
|
||||
/// </summary>
|
||||
public string Session => Path.Combine(Root, "sessione");
|
||||
|
||||
/// <summary>Dati/sessione/sessione.json: the encrypted saved session.</summary>
|
||||
public string SessionFile => Path.Combine(Session, "sessione.json");
|
||||
|
||||
/// <summary>Dati/sessione/chiave.bin: the AES key in Docker when FEBE_CHIAVE_SESSIONE is not set.</summary>
|
||||
public string SessionKeyFile => Path.Combine(Session, "chiave.bin");
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using System.Diagnostics;
|
||||
using Febe.Core.Security;
|
||||
|
||||
namespace Febe.Core.Library;
|
||||
|
||||
@@ -63,7 +64,12 @@ public sealed class VideoFrameExtractor
|
||||
return null;
|
||||
}
|
||||
|
||||
private async Task<byte[]?> RunAsync(string videoPath, string seek, CancellationToken ct)
|
||||
/// <summary>
|
||||
/// The start of ffmpeg for one frame of <paramref name="videoPath"/> at <paramref name="seek"/> seconds: its
|
||||
/// arguments, and the environment of Febe without <c>FEBE_PASSWORD</c> and <c>FEBE_CHIAVE_SESSIONE</c>, removed last
|
||||
/// (spec §13.2).
|
||||
/// </summary>
|
||||
internal ProcessStartInfo BuildStartInfo(string videoPath, string seek)
|
||||
{
|
||||
var start = new ProcessStartInfo(Executable)
|
||||
{
|
||||
@@ -78,7 +84,12 @@ public sealed class VideoFrameExtractor
|
||||
start.ArgumentList.Add(argument);
|
||||
}
|
||||
|
||||
using var process = new Process { StartInfo = start };
|
||||
return start.WithoutSecrets();
|
||||
}
|
||||
|
||||
private async Task<byte[]?> RunAsync(string videoPath, string seek, CancellationToken ct)
|
||||
{
|
||||
using var process = new Process { StartInfo = BuildStartInfo(videoPath, seek) };
|
||||
try
|
||||
{
|
||||
if (!process.Start())
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace Febe.Core.Security;
|
||||
|
||||
/// <summary>
|
||||
/// AES-256-GCM for the saved session in Docker (issue #36, S4, spec §13.2), from the base library
|
||||
/// (<c>System.Security.Cryptography</c>, §3): header (6 bytes) | nonce (12, fresh for every write) | tag (16) |
|
||||
/// ciphertext; the header is the associated data, so a changed header is a damaged file.
|
||||
/// </summary>
|
||||
public sealed class AesGcmSessionProtector : ISessionProtector
|
||||
{
|
||||
private const int NonceLength = 12;
|
||||
private const int TagLength = 16;
|
||||
|
||||
private readonly byte[] _key;
|
||||
|
||||
/// <param name="key">Exactly 32 bytes (<see cref="SessionKey"/>); copied, never logged.</param>
|
||||
/// <exception cref="ArgumentException">A key that is not 32 bytes (the message names the length only).</exception>
|
||||
public AesGcmSessionProtector(ReadOnlySpan<byte> key)
|
||||
{
|
||||
if (key.Length != SessionKey.Length)
|
||||
{
|
||||
throw new ArgumentException($"La chiave della sessione salvata è di {SessionKey.Length} byte.", nameof(key));
|
||||
}
|
||||
|
||||
_key = key.ToArray();
|
||||
}
|
||||
|
||||
public string Scheme => "aes-gcm";
|
||||
|
||||
public byte[] Protect(ReadOnlySpan<byte> plain)
|
||||
{
|
||||
var header = SessionBlob.Header(SessionBlob.AesGcm);
|
||||
var blob = new byte[SessionBlob.HeaderLength + NonceLength + TagLength + plain.Length];
|
||||
header.CopyTo(blob, 0);
|
||||
var nonce = blob.AsSpan(SessionBlob.HeaderLength, NonceLength);
|
||||
RandomNumberGenerator.Fill(nonce);
|
||||
var tag = blob.AsSpan(SessionBlob.HeaderLength + NonceLength, TagLength);
|
||||
var cipher = blob.AsSpan(SessionBlob.HeaderLength + NonceLength + TagLength);
|
||||
using var aes = new AesGcm(_key, TagLength);
|
||||
aes.Encrypt(nonce, plain, cipher, tag, header);
|
||||
return blob;
|
||||
}
|
||||
|
||||
public byte[] Unprotect(ReadOnlySpan<byte> blob)
|
||||
{
|
||||
if (!SessionBlob.HasHeader(blob, SessionBlob.AesGcm) || blob.Length < SessionBlob.HeaderLength + NonceLength + TagLength)
|
||||
{
|
||||
throw new SessionUnreadableException();
|
||||
}
|
||||
|
||||
var header = blob[..SessionBlob.HeaderLength];
|
||||
var nonce = blob.Slice(SessionBlob.HeaderLength, NonceLength);
|
||||
var tag = blob.Slice(SessionBlob.HeaderLength + NonceLength, TagLength);
|
||||
var cipher = blob[(SessionBlob.HeaderLength + NonceLength + TagLength)..];
|
||||
var plain = new byte[cipher.Length];
|
||||
try
|
||||
{
|
||||
using var aes = new AesGcm(_key, TagLength);
|
||||
aes.Decrypt(nonce, cipher, tag, plain, header);
|
||||
return plain;
|
||||
}
|
||||
catch (CryptographicException)
|
||||
{
|
||||
// Another key or a changed byte: nothing of the inner text is passed on.
|
||||
CryptographicOperations.ZeroMemory(plain);
|
||||
throw new SessionUnreadableException();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The scheme only, never the key.</summary>
|
||||
public override string ToString() => "Cifratura della sessione: AES-256-GCM.";
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace Febe.Core.Security;
|
||||
|
||||
/// <summary>
|
||||
/// What a process Febe starts (Chromium, Edge, Xvfb, ffmpeg, ffprobe, Explorer) must not inherit from Febe (issue #36,
|
||||
/// S4, rule 10): the interface password and the key of the saved session. A child process copies the environment of its
|
||||
/// parent; Chromium runs the site's code, so a secret in its environment is a secret one step from the site.
|
||||
/// </summary>
|
||||
public static class ChildProcessEnvironment
|
||||
{
|
||||
/// <summary>The interface password of Docker (spec §11).</summary>
|
||||
public const string PasswordVariable = "FEBE_PASSWORD";
|
||||
|
||||
/// <summary>The variables taken out of every child process's environment.</summary>
|
||||
public static IReadOnlyList<string> SecretVariables { get; } = [PasswordVariable, SessionKey.EnvironmentVariable];
|
||||
|
||||
/// <summary>
|
||||
/// Removes <see cref="SecretVariables"/> from <paramref name="info"/>'s environment. Call it last, after anything
|
||||
/// else that sets variables. Only for <c>UseShellExecute = false</c> (with the shell, .NET passes no environment).
|
||||
/// </summary>
|
||||
public static ProcessStartInfo WithoutSecrets(this ProcessStartInfo info)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(info);
|
||||
RemoveSecrets(info.Environment);
|
||||
return info;
|
||||
}
|
||||
|
||||
/// <summary>Removes <see cref="SecretVariables"/> from <paramref name="environment"/> (whatever the case of the name).</summary>
|
||||
public static void RemoveSecrets(IDictionary<string, string?> environment)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(environment);
|
||||
foreach (var name in environment.Keys.Where(IsSecret).ToList())
|
||||
{
|
||||
environment.Remove(name);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>True for a name of <see cref="SecretVariables"/>, in any case (Windows names ignore it).</summary>
|
||||
public static bool IsSecret(string name) =>
|
||||
SecretVariables.Any(secret => string.Equals(secret, name, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
namespace Febe.Core.Security;
|
||||
|
||||
/// <summary>
|
||||
/// Encrypts the saved session before it touches the disk (issue #36, S4, spec §13.2): DPAPI for the current user on
|
||||
/// Windows (in Febe.Desktop, the only project with <c>ProtectedData</c> and no package), AES-256-GCM with a key of its
|
||||
/// own in Docker (<see cref="AesGcmSessionProtector"/>). The text it protects never reaches a log or an exception.
|
||||
/// </summary>
|
||||
public interface ISessionProtector
|
||||
{
|
||||
/// <summary>The scheme, for the log: <c>dpapi</c> or <c>aes-gcm</c>.</summary>
|
||||
string Scheme { get; }
|
||||
|
||||
/// <summary>The encrypted form of <paramref name="plain"/>, starting with <see cref="SessionBlob"/>'s header.</summary>
|
||||
byte[] Protect(ReadOnlySpan<byte> plain);
|
||||
|
||||
/// <summary>The plain text of <paramref name="blob"/>.</summary>
|
||||
/// <exception cref="SessionUnreadableException">Another key or user, a damaged file, another scheme or format.</exception>
|
||||
byte[] Unprotect(ReadOnlySpan<byte> blob);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The header every protected session starts with: <c>FEBS</c>, the format version, the scheme. It says only what the
|
||||
/// file is, never what it holds; the AES scheme authenticates it.
|
||||
/// </summary>
|
||||
public static class SessionBlob
|
||||
{
|
||||
/// <summary>The scheme byte of DPAPI.</summary>
|
||||
public const byte Dpapi = 1;
|
||||
|
||||
/// <summary>The scheme byte of AES-256-GCM.</summary>
|
||||
public const byte AesGcm = 2;
|
||||
|
||||
/// <summary>The format version.</summary>
|
||||
public const byte Version = 1;
|
||||
|
||||
/// <summary>The length of the header.</summary>
|
||||
public const int HeaderLength = 6;
|
||||
|
||||
/// <summary>The header for <paramref name="scheme"/>.</summary>
|
||||
public static byte[] Header(byte scheme) => [(byte)'F', (byte)'E', (byte)'B', (byte)'S', Version, scheme];
|
||||
|
||||
/// <summary>True when <paramref name="blob"/> starts with the header of <paramref name="scheme"/>.</summary>
|
||||
public static bool HasHeader(ReadOnlySpan<byte> blob, byte scheme) =>
|
||||
blob.Length >= HeaderLength && blob[..HeaderLength].SequenceEqual(Header(scheme));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The saved session cannot be read: another key or user, a damaged file, another format. Its message is fixed and
|
||||
/// carries no inner text: Febe treats it as no session and asks for a new login.
|
||||
/// </summary>
|
||||
public sealed class SessionUnreadableException : Exception
|
||||
{
|
||||
/// <summary>The fixed message.</summary>
|
||||
public const string Text = "La sessione salvata non si legge (cifratura o formato): serve un nuovo accesso.";
|
||||
|
||||
public SessionUnreadableException()
|
||||
: base(Text)
|
||||
{
|
||||
}
|
||||
|
||||
public SessionUnreadableException(string message)
|
||||
: base(message)
|
||||
{
|
||||
}
|
||||
|
||||
public SessionUnreadableException(string message, Exception innerException)
|
||||
: base(message, innerException)
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
namespace Febe.Core.Security;
|
||||
|
||||
/// <summary>
|
||||
/// Files only their owner reads (issue #36, S4, spec §13.2): the folder <c>Dati/sessione</c> at 0700 and its files at
|
||||
/// 0600 on Unix, set when they are created (no window with wider rights); a file replaced at once (a part file in the
|
||||
/// same folder, then a rename over the old one), never half written. On Windows the modes do not apply: the Data folder
|
||||
/// is under the user's profile and DPAPI ties the session to the user.
|
||||
/// </summary>
|
||||
public static class OwnerOnlyFiles
|
||||
{
|
||||
/// <summary>The suffix of a file still being written.</summary>
|
||||
public const string PartSuffix = ".part";
|
||||
|
||||
/// <summary>Read and write for the owner only.</summary>
|
||||
public const UnixFileMode OwnerFile = UnixFileMode.UserRead | UnixFileMode.UserWrite;
|
||||
|
||||
/// <summary>Read, write and enter for the owner only.</summary>
|
||||
public const UnixFileMode OwnerFolder = UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute;
|
||||
|
||||
private const UnixFileMode Others =
|
||||
UnixFileMode.GroupRead | UnixFileMode.GroupWrite | UnixFileMode.GroupExecute
|
||||
| UnixFileMode.OtherRead | UnixFileMode.OtherWrite | UnixFileMode.OtherExecute;
|
||||
|
||||
/// <summary>Creates <paramref name="folder"/> owner-only (0700 on Unix); an existing one with wider rights is narrowed.</summary>
|
||||
public static void EnsureFolder(string folder)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(folder);
|
||||
if (OperatingSystem.IsWindows())
|
||||
{
|
||||
Directory.CreateDirectory(folder);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!Directory.Exists(folder))
|
||||
{
|
||||
Directory.CreateDirectory(folder, OwnerFolder);
|
||||
}
|
||||
else if ((File.GetUnixFileMode(folder) & Others) != 0)
|
||||
{
|
||||
File.SetUnixFileMode(folder, OwnerFolder);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Narrows <paramref name="file"/> to 0600 when group or others have any right on it (Unix only); true when it did.
|
||||
/// </summary>
|
||||
public static bool Tighten(string file)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(file);
|
||||
if (OperatingSystem.IsWindows() || !File.Exists(file) || (File.GetUnixFileMode(file) & Others) == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
File.SetUnixFileMode(file, OwnerFile);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Writes the bytes of a new file into its stream (a seam for the tests of a disk that refuses the write).</summary>
|
||||
internal delegate void BytesWriter(Stream stream, ReadOnlySpan<byte> bytes);
|
||||
|
||||
/// <summary>
|
||||
/// Writes <paramref name="bytes"/> as a new owner-only file, whole or not at all: a part file in the same folder,
|
||||
/// written through to the disk, then renamed to <paramref name="path"/> without replacing. Never replaces a file
|
||||
/// that is there, and a failed write never leaves a short file at <paramref name="path"/> (nor a part file).
|
||||
/// </summary>
|
||||
/// <exception cref="IOException">The file is already there, or the disk refused it.</exception>
|
||||
public static void CreateNew(string path, ReadOnlySpan<byte> bytes) => CreateNew(path, bytes, static (stream, data) => stream.Write(data));
|
||||
|
||||
/// <inheritdoc cref="CreateNew(string, ReadOnlySpan{byte})"/>
|
||||
/// <param name="path">The new file.</param>
|
||||
/// <param name="bytes">Its content.</param>
|
||||
/// <param name="write">How the bytes go into the part file.</param>
|
||||
internal static void CreateNew(string path, ReadOnlySpan<byte> bytes, BytesWriter write)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(path);
|
||||
ArgumentNullException.ThrowIfNull(write);
|
||||
if (File.Exists(path))
|
||||
{
|
||||
throw new IOException($"{Path.GetFileName(path)} c'è già: Febe non lo sostituisce.");
|
||||
}
|
||||
|
||||
var part = path + "." + Guid.NewGuid().ToString("N")[..8] + PartSuffix;
|
||||
try
|
||||
{
|
||||
using (var stream = new FileStream(part, Options(FileMode.CreateNew, FileOptions.WriteThrough)))
|
||||
{
|
||||
write(stream, bytes);
|
||||
stream.Flush(flushToDisk: true);
|
||||
}
|
||||
|
||||
// Without replacing: a file made meanwhile by someone else stays, and this one throws IOException.
|
||||
File.Move(part, path, overwrite: false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
TryDelete(part);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Replaces <paramref name="path"/> with <paramref name="bytes"/> at once: a part file in the same folder, owner-only
|
||||
/// from its creation, written through to the disk, then renamed over the old file. A failure leaves the old file and
|
||||
/// no part file.
|
||||
/// </summary>
|
||||
/// <exception cref="IOException">The disk refused the write or the rename.</exception>
|
||||
/// <exception cref="UnauthorizedAccessException">The folder or the file is not writable.</exception>
|
||||
public static void WriteAtomic(string path, ReadOnlySpan<byte> bytes)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(path);
|
||||
var part = path + "." + Guid.NewGuid().ToString("N")[..8] + PartSuffix;
|
||||
try
|
||||
{
|
||||
using (var stream = new FileStream(part, Options(FileMode.CreateNew, FileOptions.WriteThrough)))
|
||||
{
|
||||
stream.Write(bytes);
|
||||
stream.Flush(flushToDisk: true);
|
||||
}
|
||||
|
||||
File.Move(part, path, overwrite: true);
|
||||
}
|
||||
finally
|
||||
{
|
||||
TryDelete(part);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes <paramref name="path"/> and the part files a broken write may have left next to it. A file that is not
|
||||
/// there is no error.
|
||||
/// </summary>
|
||||
/// <exception cref="IOException">The file could not be deleted.</exception>
|
||||
/// <exception cref="UnauthorizedAccessException">The file could not be deleted.</exception>
|
||||
public static void DeleteWithLeftovers(string path)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(path);
|
||||
var folder = Path.GetDirectoryName(Path.GetFullPath(path))!;
|
||||
if (!Directory.Exists(folder))
|
||||
{
|
||||
// No folder, no file: on Windows File.Delete would throw DirectoryNotFoundException.
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var part in Directory.EnumerateFiles(folder, Path.GetFileName(path) + ".*" + PartSuffix))
|
||||
{
|
||||
File.Delete(part);
|
||||
}
|
||||
|
||||
File.Delete(path);
|
||||
}
|
||||
|
||||
private static FileStreamOptions Options(FileMode mode, FileOptions options = FileOptions.None)
|
||||
{
|
||||
var result = new FileStreamOptions { Mode = mode, Access = FileAccess.Write, Share = FileShare.None, Options = options };
|
||||
if (!OperatingSystem.IsWindows())
|
||||
{
|
||||
result.UnixCreateMode = OwnerFile;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static void TryDelete(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (File.Exists(path))
|
||||
{
|
||||
File.Delete(path);
|
||||
}
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
}
|
||||
catch (UnauthorizedAccessException)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
using System.Globalization;
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace Febe.Core.Security;
|
||||
|
||||
/// <summary>
|
||||
/// The key of the saved session in Docker (issue #36, S4, spec §13.2): from <c>FEBE_CHIAVE_SESSIONE</c> (32 bytes in
|
||||
/// base64, or 64 hexadecimal digits), otherwise <c>Dati/sessione/chiave.bin</c>, made once with
|
||||
/// <see cref="RandomNumberGenerator"/> (not <c>IRandomSource</c>, which is for the timing of the engine), owner-only,
|
||||
/// never replaced. No text of this class ever holds the key or a part of it.
|
||||
/// </summary>
|
||||
public static class SessionKey
|
||||
{
|
||||
/// <summary>The length of the key: AES-256.</summary>
|
||||
public const int Length = 32;
|
||||
|
||||
/// <summary>The environment variable that holds the key outside the Data folder.</summary>
|
||||
public const string EnvironmentVariable = "FEBE_CHIAVE_SESSIONE";
|
||||
|
||||
/// <summary>
|
||||
/// Reads a key written as text: base64 of exactly 32 bytes or 64 hexadecimal digits, spaces around it ignored.
|
||||
/// The problem names the format only, never the value.
|
||||
/// </summary>
|
||||
public static bool TryParse(string? text, out byte[]? key, out string? problem)
|
||||
{
|
||||
key = null;
|
||||
var trimmed = text?.Trim() ?? string.Empty;
|
||||
if (trimmed.Length == 0)
|
||||
{
|
||||
problem = $"{EnvironmentVariable} è vuota.";
|
||||
return false;
|
||||
}
|
||||
|
||||
if (trimmed.Length == 2 * Length && trimmed.All(char.IsAsciiHexDigit))
|
||||
{
|
||||
key = Convert.FromHexString(trimmed);
|
||||
problem = null;
|
||||
return true;
|
||||
}
|
||||
|
||||
var buffer = new byte[trimmed.Length];
|
||||
if (Convert.TryFromBase64String(trimmed, buffer, out var written) && written == Length)
|
||||
{
|
||||
key = buffer[..Length];
|
||||
CryptographicOperations.ZeroMemory(buffer);
|
||||
problem = null;
|
||||
return true;
|
||||
}
|
||||
|
||||
CryptographicOperations.ZeroMemory(buffer);
|
||||
problem = string.Create(
|
||||
CultureInfo.InvariantCulture,
|
||||
$"{EnvironmentVariable} deve essere una chiave di {Length} byte in base64 (per esempio quella di «openssl rand -base64 32») o di {2 * Length} cifre esadecimali.");
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What is wrong with <paramref name="keyFile"/>, or null when it is a key of Febe or is not there (it will be made).
|
||||
/// The text names the file and the length, never the content.
|
||||
/// </summary>
|
||||
public static string? CheckFile(string keyFile)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(keyFile);
|
||||
try
|
||||
{
|
||||
if (!File.Exists(keyFile))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var length = new FileInfo(keyFile).Length;
|
||||
return length == Length
|
||||
? null
|
||||
: string.Create(CultureInfo.InvariantCulture, $"{Path.GetFileName(keyFile)} non è una chiave di Febe ({length} byte invece di {Length}): cancellalo e rifai l'accesso.");
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
return $"{Path.GetFileName(keyFile)} non si legge: controlla i permessi della cartella dei dati.";
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The key in <paramref name="keyFile"/>, made when it is not there: 32 random bytes, a new owner-only file in an
|
||||
/// owner-only folder, never replacing one that is there. A file with wider rights on Unix is narrowed to 0600 and
|
||||
/// <paramref name="warn"/> says so.
|
||||
/// </summary>
|
||||
/// <exception cref="InvalidDataException">The file is there but is not a key of Febe (32 bytes).</exception>
|
||||
/// <exception cref="IOException">The disk refused to make or read the file.</exception>
|
||||
public static byte[] LoadOrCreate(string keyFile, Action<string>? warn = null) =>
|
||||
LoadOrCreate(keyFile, warn, static (stream, bytes) => stream.Write(bytes));
|
||||
|
||||
/// <inheritdoc cref="LoadOrCreate(string, Action{string})"/>
|
||||
/// <param name="keyFile">The key file.</param>
|
||||
/// <param name="warn">Says when the rights of the file were narrowed.</param>
|
||||
/// <param name="write">How the bytes of a new key go to the disk (a seam for a disk that refuses the write).</param>
|
||||
internal static byte[] LoadOrCreate(string keyFile, Action<string>? warn, OwnerOnlyFiles.BytesWriter write)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(keyFile);
|
||||
var full = Path.GetFullPath(keyFile);
|
||||
OwnerOnlyFiles.EnsureFolder(Path.GetDirectoryName(full)!);
|
||||
if (!File.Exists(full))
|
||||
{
|
||||
var fresh = RandomNumberGenerator.GetBytes(Length);
|
||||
try
|
||||
{
|
||||
// Whole or not at all: a write the disk refuses (full, I/O error) leaves no short chiave.bin behind,
|
||||
// so the next start tries again instead of stopping at a file that is not a key.
|
||||
OwnerOnlyFiles.CreateNew(full, fresh, write);
|
||||
return fresh;
|
||||
}
|
||||
catch (IOException) when (File.Exists(full))
|
||||
{
|
||||
// Made by someone else in the meantime (only a whole file is ever renamed there): that one is the key.
|
||||
CryptographicOperations.ZeroMemory(fresh);
|
||||
}
|
||||
catch
|
||||
{
|
||||
CryptographicOperations.ZeroMemory(fresh);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
if (CheckFile(full) is { } problem)
|
||||
{
|
||||
throw new InvalidDataException(problem);
|
||||
}
|
||||
|
||||
if (OwnerOnlyFiles.Tighten(full))
|
||||
{
|
||||
warn?.Invoke($"{Path.GetFileName(full)} era leggibile da altri utenti: ora lo legge solo il proprietario.");
|
||||
}
|
||||
|
||||
return File.ReadAllBytes(full);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The key of the saved session: <paramref name="environmentValue"/> (the value of <see cref="EnvironmentVariable"/>)
|
||||
/// when it is set, otherwise <paramref name="keyFile"/> (<see cref="LoadOrCreate"/>). <paramref name="log"/> says
|
||||
/// where the key comes from, never the key; with the variable set, an old <c>chiave.bin</c> is named as unused.
|
||||
/// </summary>
|
||||
/// <exception cref="InvalidDataException">The variable is set but is not a key, or the file is not a key of Febe.</exception>
|
||||
public static byte[] Resolve(string? environmentValue, string keyFile, Action<string>? log = null)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(keyFile);
|
||||
if (!string.IsNullOrWhiteSpace(environmentValue))
|
||||
{
|
||||
if (!TryParse(environmentValue, out var key, out var problem))
|
||||
{
|
||||
throw new InvalidDataException(problem);
|
||||
}
|
||||
|
||||
log?.Invoke($"Sessione salvata: chiave da {EnvironmentVariable}.");
|
||||
if (File.Exists(keyFile))
|
||||
{
|
||||
log?.Invoke($"Sessione salvata: {Path.GetFileName(keyFile)} non si usa, la chiave viene da {EnvironmentVariable}.");
|
||||
}
|
||||
|
||||
return key!;
|
||||
}
|
||||
|
||||
var stored = LoadOrCreate(keyFile, log);
|
||||
log?.Invoke($"Sessione salvata: chiave da Dati/sessione/{Path.GetFileName(keyFile)} (solo il proprietario la legge).");
|
||||
return stored;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user