Client del sito contro il sito di prova (#36, S2)
verifica / controlli (push) Successful in 17s
verifica / prove (push) Successful in 15m4s
verifica / installatore (push) Successful in 4m22s
verifica / immagine (push) Successful in 15m55s

HttpSiteRequester è l'unica classe che parla col sito: va solo a
https://www.instagram.com/ o a un sito di prova di loopback, non segue i
rinvii, una richiesta per volta col permesso del Governatore, solo le
intestazioni del catalogo con l'user agent della sessione, e registra solo
operazione, forma del percorso e stato. Cookie rinnovati e claim finiscono
nella sessione (ISiteSession, per ora in memoria; la copia cifrata è S4).
SiteAnswerSignals traduce le risposte nei segnali di §7.6: 429 rallenta;
rinvii, 401/403, HTML o campi mancanti valgono come Verifica (H16).
Il sito di prova risponde alle richieste dirette come dice
richieste.prova.json e simula i casi d'arresto; una visita senza sessione
viva apre una sessione nuova anche per il client. Nulla è ancora collegato
al motore (S3).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-16 18:34:12 +01:00
1 parent e10c25d12d
commit ce9691fe1c
19 files changed
+3563 -51

No files matched your search

@@ -0,0 +1,866 @@
using System.Globalization;
using System.Net;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using Febe.Core.Abstractions;
namespace Febe.Core.Collection.Requests;
/// <summary>Options of <see cref="HttpSiteRequester"/>.</summary>
public sealed record HttpSiteRequesterOptions
{
/// <summary>The address of Instagram: the only one the Instagram catalog may be asked at (https, default port).</summary>
public static Uri InstagramAddress { get; } = new("https://www.instagram.com/", UriKind.Absolute);
/// <summary>
/// Scheme, host and port of the site, with the path «/» and nothing else. For the Instagram catalog exactly
/// <see cref="InstagramAddress"/>; for any other catalog a loopback address (127.0.0.0/8 or ::1), http or https.
/// </summary>
public required Uri SiteAddress { get; init; }
/// <summary>Name of the session cookie of the site (<c>sessionid</c>, <c>sessione_prova</c>): without it nothing leaves.</summary>
public required string SessionCookie { get; init; }
/// <summary>How long a request may take, answer read included.</summary>
public TimeSpan Timeout { get; init; } = TimeSpan.FromSeconds(30);
/// <summary>How long opening a connection may take.</summary>
public TimeSpan ConnectTimeout { get; init; } = TimeSpan.FromSeconds(10);
/// <summary>Largest body kept in memory; a larger answer is dropped (<see cref="SiteUnreachableReason.TooLarge"/>).</summary>
public int MaxBodyBytes { get; init; } = 32 * 1024 * 1024;
/// <summary>The options for Instagram.</summary>
public static HttpSiteRequesterOptions Instagram() => new() { SiteAddress = InstagramAddress, SessionCookie = "sessionid" };
/// <summary>The options for the local test site at <paramref name="address"/> (<c>http://127.0.0.1:port/</c>).</summary>
public static HttpSiteRequesterOptions TestSite(Uri address, string sessionCookie = "sessione_prova") =>
new() { SiteAddress = address, SessionCookie = sessionCookie };
}
/// <summary>Why a request got no answer.</summary>
public enum SiteUnreachableReason
{
/// <summary>No answer within <see cref="HttpSiteRequesterOptions.Timeout"/>.</summary>
Timeout,
/// <summary>No connection, or the connection broke.</summary>
Unreachable,
/// <summary>The answer was larger than <see cref="HttpSiteRequesterOptions.MaxBodyBytes"/>.</summary>
TooLarge,
/// <summary>The body could not be decoded (corrupt or truncated gzip, deflate or brotli).</summary>
Broken,
}
/// <summary>
/// The site gave no answer (time out, no connection, an answer too large). The message is in Italian and names only the
/// operation and its path shape, never the address, a value or the text of the network error.
/// </summary>
public sealed class SiteUnreachableException : IOException
{
public SiteUnreachableException()
{
}
public SiteUnreachableException(string message)
: base(message)
{
}
public SiteUnreachableException(string message, Exception innerException)
: base(message, innerException)
{
}
public SiteUnreachableException(string message, SiteUnreachableReason reason)
: base(message) => Reason = reason;
public SiteUnreachableReason Reason { get; }
}
/// <summary>
/// A request that did not leave because the saved session is missing, has no session cookie, or lacks a value the
/// catalog asks for (§7.6: «la sessione salvata manca», Disconnessione). Names only the missing value.
/// </summary>
public sealed class SiteSessionMissingException : SiteRequestRefusedException
{
public SiteSessionMissingException()
{
}
public SiteSessionMissingException(string message)
: base(message)
{
}
public SiteSessionMissingException(string message, Exception innerException)
: base(message, innerException)
{
}
public SiteSessionMissingException(string message, string? missing)
: base(message) => Missing = missing;
/// <summary>The header, field or cookie that has no value (its name), or null when the whole session is missing.</summary>
public string? Missing { get; }
}
/// <summary>
/// The site client (issue #36, spec §6.0): the one class of Febe that asks the site for data without the browser
/// (rule 3). It sends only the operations of the catalog, with the user agent, the cookies and the values of the saved
/// session (<see cref="ISiteSession"/>), the headers of the catalog and nothing else, and keeps in the session what the
/// site renews.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><see cref="SiteRequestGuard.Check"/> before anything, with one <see cref="SpentPermits"/> for its lifetime:
/// a permit per request (rule 8).</item>
/// <item>One request at a time: a second call while one is in flight is refused (<see cref="SiteRequestRefusedException"/>),
/// never queued, so no request leaves before its caller has read the answer of the one before (rule 8: stop at the
/// first signal) and the spacing of §7.7 stays the Governor's.</item>
/// <item>What the site renews (<c>Set-Cookie</c>, <c>x-ig-set-www-claim</c>) is written to the session as soon as the
/// headers arrive, as a browser does, whatever then happens to the body or to the caller's token; and only to the
/// capture the request was sent with.</item>
/// <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>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
/// <c>traceparent</c> from an activity of the host); the system proxy, as WebView2 — except for a loopback test site,
/// which no browser reaches through a proxy. On Windows .NET would read <c>HTTP_PROXY</c>, <c>HTTPS_PROXY</c> and
/// <c>ALL_PROXY</c> before the system settings, which WebView2 ignores: with one of them set the client is not built.</item>
/// <item>Logs name only the operation, its path shape and the status, in Italian (rule 10). Exceptions never carry the
/// address, a value or a body.</item>
/// </list>
/// </remarks>
public sealed class HttpSiteRequester : ISiteRequester, IDisposable
{
private static readonly JsonDocumentOptions BodyOptions = new() { MaxDepth = ResponseDelivery.MaxDepth };
private readonly RequestCatalog _catalog;
private readonly ISiteSession _session;
private readonly HttpSiteRequesterOptions _options;
private readonly IClock _clock;
private readonly Action<string> _log;
private readonly HttpClient _http;
private readonly SpentPermits _spent = new();
// Never disposed: no wait handle is ever asked of it, and a call still in flight at Dispose releases it.
private readonly SemaphoreSlim _oneAtATime = new(1, 1);
// Cancelled by Dispose, so a request in flight ends as a cancellation; never disposed, for the same reason.
private readonly CancellationTokenSource _closing = new();
private readonly Uri _site;
private int _disposed;
/// <param name="catalog">The operations it may ask.</param>
/// <param name="session">The saved session: values read before each request, renewals written after.</param>
/// <param name="options">Address of the site, session cookie, limits.</param>
/// <param name="clock">Time for the expiry of cookies and for <c>Retry-After</c> dates.</param>
/// <param name="log">Receives the Italian log lines (operation, path shape, status only); null discards them.</param>
/// <exception cref="ArgumentException">An address that is not the catalog's site (see <see cref="HttpSiteRequesterOptions.SiteAddress"/>).</exception>
public HttpSiteRequester(RequestCatalog catalog, ISiteSession session, HttpSiteRequesterOptions options, IClock clock, Action<string>? log = null)
{
_catalog = catalog ?? throw new ArgumentNullException(nameof(catalog));
_session = session ?? throw new ArgumentNullException(nameof(session));
_options = options ?? throw new ArgumentNullException(nameof(options));
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
_log = log ?? (_ => { });
if (!SiteCookies.IsPlainName(options.SessionCookie))
{
throw new ArgumentException("Il nome del cookie di sessione non è un nome semplice.", nameof(options));
}
if (options.Timeout <= TimeSpan.Zero || options.ConnectTimeout <= TimeSpan.Zero || options.MaxBodyBytes <= 0)
{
throw new ArgumentException("Tempi e dimensione massima del client del sito devono essere positivi.", nameof(options));
}
_site = CheckAddress(catalog, options.SiteAddress);
if (!IsLoopback(_site) && EnvironmentProxyRefusal(OperatingSystem.IsWindows(), Environment.GetEnvironmentVariable) is { } proxy)
{
throw new InvalidOperationException(proxy);
}
_http = new HttpClient(CreateHandler(_options, IsLoopback(_site)), disposeHandler: true)
{
// The timeout is a token of our own, to tell it from a cancellation of the caller.
Timeout = System.Threading.Timeout.InfiniteTimeSpan,
DefaultRequestVersion = HttpVersion.Version20,
DefaultVersionPolicy = HttpVersionPolicy.RequestVersionOrLower,
};
}
/// <summary>The site it talks to (scheme, host, port).</summary>
public Uri Site => _site;
/// <summary>
/// Why <paramref name="address"/> is not where <paramref name="catalog"/> may be asked, or null when it is: the
/// Instagram catalog only at <see cref="HttpSiteRequesterOptions.InstagramAddress"/>, any other only on loopback.
/// </summary>
public static string? RefusalOfAddress(RequestCatalog catalog, Uri? address)
{
ArgumentNullException.ThrowIfNull(catalog);
if (address is null || !address.IsAbsoluteUri)
{
return "manca l'indirizzo del sito";
}
if (address.UserInfo.Length > 0 || address.AbsolutePath != "/" || address.Query.Length > 0 || address.Fragment.Length > 0)
{
return "l'indirizzo del sito è solo schema, host e porta";
}
if (catalog.Site == "instagram")
{
return address.Scheme == Uri.UriSchemeHttps && address.IdnHost == HttpSiteRequesterOptions.InstagramAddress.IdnHost && address.Port == 443
? null
: "il catalogo di Instagram si chiede solo a https://www.instagram.com/";
}
if (address.Scheme != Uri.UriSchemeHttp && address.Scheme != Uri.UriSchemeHttps)
{
return "un sito di prova si chiede con http o https";
}
return IsLoopback(address) ? null : "un sito di prova sta solo su un indirizzo locale (127.0.0.1 o ::1): Febe non chiede nulla ad altri host";
}
/// <summary>
/// Why the system proxy of .NET would not be the browser's, or null when it is. On Windows <c>HttpClient.DefaultProxy</c>
/// takes <c>HTTP_PROXY</c>, <c>HTTPS_PROXY</c> or <c>ALL_PROXY</c> before the system settings WebView2 uses: the same
/// session would leave from two routes (§6.0, «su Windows le impostazioni proxy del sistema, come WebView2»). In
/// Docker Chromium reads the same variables as .NET, so they are the browser's route. Names the variables, never
/// their values (they may hold a password).
/// </summary>
internal static string? EnvironmentProxyRefusal(bool windows, Func<string, string?> variable)
{
ArgumentNullException.ThrowIfNull(variable);
if (!windows)
{
return null;
}
var set = new[] { "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY" }.Where(n => !string.IsNullOrWhiteSpace(variable(n))).ToList();
return set.Count == 0
? null
: $"Client del sito non avviato: sono impostate le variabili {string.Join(", ", set)}, che WebView2 non usa. Il client del sito uscirebbe da una strada diversa da quella del browser: togli le variabili o imposta il proxy nelle impostazioni di Windows.";
}
/// <summary>The handler of the site client: no redirect, no cookie jar, decompression, HTTP/2, system proxy.</summary>
internal static SocketsHttpHandler CreateHandler(HttpSiteRequesterOptions options, bool loopback) => new()
{
AllowAutoRedirect = false,
UseCookies = false,
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate | DecompressionMethods.Brotli,
// The system proxy (null = HttpClient.DefaultProxy), the way WebView2 and Chromium go out (decision of 16
// November 2026); a loopback test site is never reached through one.
UseProxy = !loopback,
ConnectTimeout = options.ConnectTimeout,
PooledConnectionLifetime = TimeSpan.FromMinutes(10),
MaxConnectionsPerServer = 1,
// No «traceparent» or «Request-Id» from an activity of the host: nothing the catalog does not list (rule 4).
ActivityHeadersPropagator = null,
};
public async Task<SiteAnswer> SendAsync(SiteRequest request, Permit permit, CancellationToken ct)
{
ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this);
var operation = SiteRequestGuard.Check(_catalog, request, permit, _spent);
// Refused, never queued: a queued request would leave as soon as the one before ends, before its caller could
// read a stop signal in that answer (rule 8), and closer to it than the Governor spaced them (§7.7).
if (!_oneAtATime.Wait(0, CancellationToken.None))
{
throw new SiteRequestRefusedException($"Richiesta «{operation.Name}» non inviata: un'altra richiesta è ancora in corso (una per volta, mai in coda).");
}
try
{
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)
{
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);
return await ExchangeAsync(operation, message, values.Capture, ct).ConfigureAwait(false);
}
finally
{
_oneAtATime.Release();
}
}
/// <summary>Closes the client: a request in flight ends with <see cref="OperationCanceledException"/>, later calls with <see cref="ObjectDisposedException"/>.</summary>
public void Dispose()
{
if (Interlocked.Exchange(ref _disposed, 1) != 0)
{
return;
}
_closing.Cancel();
_http.Dispose();
}
private async Task<SiteAnswer> ExchangeAsync(SiteOperation operation, HttpRequestMessage message, long capture, CancellationToken ct)
{
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct, _closing.Token);
timeout.CancelAfter(_options.Timeout);
HttpResponseMessage response;
byte[] body;
try
{
response = await _http.SendAsync(message, HttpCompletionOption.ResponseHeadersRead, timeout.Token).ConfigureAwait(false);
}
catch (Exception ex) when (IsStop(ex, ct))
{
throw Stopped(ex, ct);
}
catch (OperationCanceledException)
{
throw Unreachable(operation, SiteUnreachableReason.Timeout);
}
catch (HttpRequestException)
{
// The text of the network error may name the host and the address: it is not passed on.
throw Unreachable(operation, SiteUnreachableReason.Unreachable);
}
using (response)
{
// 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);
if (!update.IsEmpty)
{
await _session.UpdateAsync(update, CancellationToken.None).ConfigureAwait(false);
}
var deletesSession = deleted.Contains(_options.SessionCookie, StringComparer.Ordinal);
if (deletesSession)
{
_log(string.Create(CultureInfo.InvariantCulture, $"Client del sito: «{operation.Name}» {operation.PathShape}, il sito ha cancellato il cookie di sessione."));
}
try
{
body = await ReadLimitedAsync(response.Content, _options.MaxBodyBytes, timeout.Token).ConfigureAwait(false);
}
catch (Exception ex) when (IsStop(ex, ct))
{
throw Stopped(ex, ct);
}
catch (OperationCanceledException)
{
throw Unreachable(operation, SiteUnreachableReason.Timeout);
}
catch (BodyTooLargeException)
{
throw Unreachable(operation, SiteUnreachableReason.TooLarge);
}
catch (Exception ex) when (ex is InvalidDataException or InvalidOperationException)
{
// GZipStream and DeflateStream throw InvalidDataException on corrupt data, BrotliStream InvalidOperationException.
throw Unreachable(operation, SiteUnreachableReason.Broken);
}
catch (Exception ex) when (ex is HttpRequestException or IOException)
{
throw Unreachable(operation, SiteUnreachableReason.Unreachable);
}
var status = (int)response.StatusCode;
var mime = response.Content.Headers.ContentType?.MediaType;
var answer = new SiteAnswer(
operation,
status,
mime,
body,
redirectTo: response.Headers.Location?.OriginalString,
cookiesSet: set,
cookiesDeleted: deleted,
setsClaim: update.Claim is not null,
retryAfter: RetryAfter(response.Headers.RetryAfter),
rootFieldsPresent: RootFields(operation, body));
_log(string.Create(CultureInfo.InvariantCulture, $"Client del sito: «{operation.Name}» {operation.PathShape}, stato {status}."));
return answer;
}
}
/// <summary>True when <paramref name="error"/> comes from the caller's cancellation or from <see cref="Dispose"/>, not from the site.</summary>
private bool IsStop(Exception error, CancellationToken ct) =>
(ct.IsCancellationRequested && error is OperationCanceledException)
|| (_closing.IsCancellationRequested && error is OperationCanceledException or HttpRequestException or IOException or ObjectDisposedException);
private OperationCanceledException Stopped(Exception error, CancellationToken ct) =>
ct.IsCancellationRequested && error is OperationCanceledException cancelled
? cancelled
: new OperationCanceledException("Client del sito chiuso: la richiesta in corso è stata interrotta.", _closing.Token);
private HttpRequestMessage Build(SiteOperation operation, SiteRequest request, 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 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.
if (address.Scheme != _site.Scheme || address.IdnHost != _site.IdnHost || address.Port != _site.Port)
{
throw new SiteRequestRefusedException($"Richiesta «{operation.Name}» non inviata: l'indirizzo non è del sito.");
}
var message = new HttpRequestMessage(new HttpMethod(operation.Method), address)
{
Version = HttpVersion.Version20,
VersionPolicy = HttpVersionPolicy.RequestVersionOrLower,
};
try
{
var now = _clock.Now;
string? contentType = null;
foreach (var name in operation.HeaderOrder)
{
var source = operation.Headers[name];
if (source.Kind == ValueSourceKind.Computed)
{
if (name != "content-length")
{
throw new SiteRequestRefusedException($"Richiesta «{operation.Name}» non inviata: l'intestazione «{name}» non si può calcolare.");
}
continue;
}
var value = Resolve(operation, name, source, values, variables: null, now);
if (name == "content-type")
{
contentType = value;
continue;
}
if (!message.Headers.TryAddWithoutValidation(name, value))
{
throw new SiteRequestRefusedException($"Richiesta «{operation.Name}» non inviata: l'intestazione «{name}» non si può scrivere.");
}
}
var cookies = string.Join("; ", values.CookiesAt(now).Select(c => $"{c.Key}={c.Value}"));
message.Headers.TryAddWithoutValidation("cookie", cookies);
if (operation.Kind == OperationKind.GraphQl)
{
var variables = Variables(operation, request);
var form = new StringBuilder();
foreach (var field in operation.BodyOrder)
{
var value = Resolve(operation, field, operation.Body[field], values, variables, now);
if (form.Length > 0)
{
form.Append('&');
}
form.Append(FormEncode(field)).Append('=').Append(FormEncode(value));
}
message.Content = new ByteArrayContent(Encoding.UTF8.GetBytes(form.ToString()));
if (contentType is not null && !message.Content.Headers.TryAddWithoutValidation("content-type", contentType))
{
throw new SiteRequestRefusedException($"Richiesta «{operation.Name}» non inviata: «content-type» non si può scrivere.");
}
}
else if (contentType is not null)
{
throw new SiteRequestRefusedException($"Richiesta «{operation.Name}» non inviata: una lettura con GET non ha «content-type».");
}
return message;
}
catch
{
message.Dispose();
throw;
}
}
private static string PathAndQuery(SiteOperation operation, SiteRequest request)
{
var path = operation.Path;
foreach (var name in operation.PathValues)
{
path = path.Replace("{" + name + "}", Uri.EscapeDataString(request.Values[name]), StringComparison.Ordinal);
}
var query = new StringBuilder();
foreach (var key in operation.ParameterOrder)
{
var template = operation.Parameters[key];
string value;
if (template.StartsWith("constant:", StringComparison.Ordinal))
{
value = template["constant:".Length..];
}
else
{
var name = template.Trim('{', '}', '?');
if (!request.Values.TryGetValue(name, out var given))
{
// Only an optional value can be missing here: the guard checked the required ones.
continue;
}
value = given;
}
query.Append(query.Length == 0 ? '?' : '&').Append(Uri.EscapeDataString(key)).Append('=').Append(Uri.EscapeDataString(value));
}
return path + query;
}
private static string Resolve(SiteOperation operation, string name, ValueSource source, SiteSessionValues values, string? variables, DateTimeOffset now)
{
var value = source.Kind switch
{
ValueSourceKind.Constant => source.Argument,
ValueSourceKind.Cookie => values.CookieAt(source.Argument!, now),
ValueSourceKind.Session => values.Field(source.Argument!, operation.Name),
ValueSourceKind.Operation => operation.Name,
ValueSourceKind.Variables => variables,
_ => throw new SiteRequestRefusedException($"Richiesta «{operation.Name}» non inviata: «{name}» non ha una fonte stabilita."),
};
return value ?? throw new SiteSessionMissingException(
$"Richiesta «{operation.Name}» non inviata: la sessione salvata non ha il valore di «{name}» ({source}).", name);
}
/// <summary>
/// The variables of a GraphQL operation: its template, in the order and with the types of the file, with every
/// <c>"{name}"</c> replaced by the value of the case, as a JSON string.
/// </summary>
internal static string Variables(SiteOperation operation, SiteRequest request)
{
ArgumentNullException.ThrowIfNull(operation);
ArgumentNullException.ThrowIfNull(request);
if (operation.Variables is not { } template)
{
throw new SiteRequestRefusedException($"Richiesta «{operation.Name}» non inviata: mancano le variabili.");
}
var text = new StringBuilder();
WriteTemplate(text, template, request);
return text.ToString();
}
private static void WriteTemplate(StringBuilder text, JsonElement element, SiteRequest request)
{
switch (element.ValueKind)
{
case JsonValueKind.Object:
text.Append('{');
var firstProperty = true;
foreach (var property in element.EnumerateObject())
{
if (!firstProperty)
{
text.Append(',');
}
firstProperty = false;
WriteString(text, property.Name);
text.Append(':');
WriteTemplate(text, property.Value, request);
}
text.Append('}');
break;
case JsonValueKind.Array:
text.Append('[');
var firstItem = true;
foreach (var item in element.EnumerateArray())
{
if (!firstItem)
{
text.Append(',');
}
firstItem = false;
WriteTemplate(text, item, request);
}
text.Append(']');
break;
case JsonValueKind.String:
var constant = element.GetString()!;
WriteString(text, constant.Length > 2 && constant[0] == '{' && constant[^1] == '}' && request.Values.TryGetValue(constant[1..^1], out var value) ? value : constant);
break;
default:
// Numbers, true, false and null as the file writes them (12 stays 12, never 12.0).
text.Append(element.GetRawText());
break;
}
}
/// <summary>
/// A JSON string as the page's <c>JSON.stringify</c> writes it (ECMA-262 QuoteJSONString): <c>"</c> and <c>\</c>
/// escaped, <c>\b \f \n \r \t</c> short, the other controls below U+0020 and lone surrogates as <c>\u</c> with
/// lower-case hex; everything else as it is (letters, emoji, U+007F, U+2028 and U+2029 included).
/// </summary>
internal static void WriteString(StringBuilder text, string value)
{
text.Append('"');
for (var i = 0; i < value.Length; i++)
{
var c = value[i];
switch (c)
{
case '"':
text.Append("\\\"");
break;
case '\\':
text.Append("\\\\");
break;
case '\b':
text.Append("\\b");
break;
case '\f':
text.Append("\\f");
break;
case '\n':
text.Append("\\n");
break;
case '\r':
text.Append("\\r");
break;
case '\t':
text.Append("\\t");
break;
default:
if (char.IsHighSurrogate(c) && i + 1 < value.Length && char.IsLowSurrogate(value[i + 1]))
{
text.Append(c).Append(value[++i]);
}
else if (c < ' ' || char.IsSurrogate(c))
{
text.Append("\\u").Append(((int)c).ToString("x4", CultureInfo.InvariantCulture));
}
else
{
text.Append(c);
}
break;
}
}
text.Append('"');
}
/// <summary>The <c>application/x-www-form-urlencoded</c> serializer of the page (URLSearchParams): space as «+».</summary>
internal static string FormEncode(string value)
{
var bytes = Encoding.UTF8.GetBytes(value);
var text = new StringBuilder(bytes.Length);
foreach (var b in bytes)
{
var c = (char)b;
if (char.IsAsciiLetterOrDigit(c) || c is '*' or '-' or '.' or '_')
{
text.Append(c);
}
else if (c == ' ')
{
text.Append('+');
}
else
{
text.Append('%').Append(b.ToString("X2", CultureInfo.InvariantCulture));
}
}
return text.ToString();
}
private SiteSessionUpdate SessionUpdate(HttpResponseMessage response, 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);
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)
{
continue;
}
var index = renewed.FindIndex(c => c.Key == cookie.Name);
if (cookie.Deletes)
{
if (index >= 0)
{
renewed.RemoveAt(index);
}
expires.Remove(cookie.Name);
set.Remove(cookie.Name);
if (!deleted.Contains(cookie.Name))
{
deleted.Add(cookie.Name);
}
}
else
{
if (index >= 0)
{
renewed[index] = new(cookie.Name, cookie.Value);
}
else
{
renewed.Add(new(cookie.Name, cookie.Value));
}
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);
}
}
}
}
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);
}
private TimeSpan? RetryAfter(RetryConditionHeaderValue? header)
{
if (header?.Delta is { } delta)
{
return delta < TimeSpan.Zero ? TimeSpan.Zero : delta;
}
if (header?.Date is { } date)
{
var wait = date - _clock.Now;
return wait < TimeSpan.Zero ? TimeSpan.Zero : wait;
}
return null;
}
private static bool RootFields(SiteOperation operation, byte[] body)
{
try
{
using var document = JsonDocument.Parse(body, BodyOptions);
return operation.HasRootFields(document.RootElement);
}
catch (JsonException)
{
return false;
}
}
private static async Task<byte[]> ReadLimitedAsync(HttpContent content, int limit, CancellationToken ct)
{
if (content.Headers.ContentLength is > 0 and var declared && declared > limit)
{
throw new BodyTooLargeException();
}
await using var stream = await content.ReadAsStreamAsync(ct).ConfigureAwait(false);
using var buffer = new MemoryStream();
var chunk = new byte[16 * 1024];
int read;
while ((read = await stream.ReadAsync(chunk, ct).ConfigureAwait(false)) > 0)
{
if (buffer.Length + read > limit)
{
throw new BodyTooLargeException();
}
buffer.Write(chunk, 0, read);
}
return buffer.ToArray();
}
/// <summary>The body went past <see cref="HttpSiteRequesterOptions.MaxBodyBytes"/>: a type of its own, so no decoder error is taken for it.</summary>
private sealed class BodyTooLargeException : Exception
{
public BodyTooLargeException()
: base("Risposta troppo grande.")
{
}
public BodyTooLargeException(string message)
: base(message)
{
}
public BodyTooLargeException(string message, Exception innerException)
: base(message, innerException)
{
}
}
private SiteUnreachableException Unreachable(SiteOperation operation, SiteUnreachableReason reason)
{
var what = reason switch
{
SiteUnreachableReason.Timeout => string.Create(CultureInfo.InvariantCulture, $"nessuna risposta entro {(long)_options.Timeout.TotalSeconds} s"),
SiteUnreachableReason.TooLarge => "risposta troppo grande, scartata",
SiteUnreachableReason.Broken => "risposta interrotta o non decomprimibile, scartata",
_ => "il sito non si raggiunge",
};
_log($"Client del sito: «{operation.Name}» {operation.PathShape}, {what}.");
return new SiteUnreachableException($"Richiesta «{operation.Name}» ({operation.PathShape}): {what}.", reason);
}
private static Uri CheckAddress(RequestCatalog catalog, Uri address)
{
if (RefusalOfAddress(catalog, address) is { } refusal)
{
throw new ArgumentException($"Client del sito di {catalog.Site}: {refusal}.", nameof(address));
}
return new Uri(address.GetLeftPart(UriPartial.Authority) + "/", UriKind.Absolute);
}
private static bool IsLoopback(Uri address) =>
address.HostNameType is UriHostNameType.IPv4 or UriHostNameType.IPv6
&& IPAddress.TryParse(address.IdnHost.Trim('[', ']'), out var ip)
&& IPAddress.IsLoopback(ip);
}
@@ -36,7 +36,7 @@ public interface ISiteRequester
/// the catalog or not configured, values that do not match. The message is in Italian and names only the operation and
/// value names.
/// </summary>
public sealed class SiteRequestRefusedException : InvalidOperationException
public class SiteRequestRefusedException : InvalidOperationException
{
public SiteRequestRefusedException()
{
@@ -0,0 +1,409 @@
using System.Collections.Frozen;
using System.Globalization;
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.
/// </summary>
/// <remarks>
/// Only the site client and the copy from the browser («Ho finito», S4) touch it. Its values never reach a log, a
/// message or an exception: what an implementation tells about them is counts and names (rule 10).
/// </remarks>
public interface ISiteSession
{
/// <summary>The values as they are now; null when there is no saved session (Disconnessione, §7.6).</summary>
SiteSessionValues? Read();
/// <summary>
/// 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»).
/// </summary>
Task UpdateAsync(SiteSessionUpdate update, 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).
/// </remarks>
public sealed class SiteSessionValues
{
/// <summary>The initial value of <c>x-ig-www-claim</c> the page sends until the site sets one (H13).</summary>
public const string InitialClaim = "0";
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>
/// <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>
public SiteSessionValues(
IEnumerable<KeyValuePair<string, string>> 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))
{
}
private SiteSessionValues(
IEnumerable<KeyValuePair<string, string>> cookies,
string userAgent,
IReadOnlyDictionary<string, string>? fields,
IReadOnlyDictionary<string, string>? docIds,
IReadOnlyDictionary<string, DateTimeOffset>? expires,
long capture)
{
ArgumentNullException.ThrowIfNull(cookies);
ArgumentNullException.ThrowIfNull(userAgent);
var list = new List<KeyValuePair<string, string>>();
foreach (var (name, value) 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);
if (index >= 0)
{
list[index] = new(name, value ?? string.Empty);
}
else
{
list.Add(new(name, value ?? string.Empty));
}
}
foreach (var name in (fields ?? new Dictionary<string, string>()).Keys)
{
if (!ValueSource.SessionFields.Contains(name) || name is "user_agent" or "doc_id")
{
throw new ArgumentException($"«{name}» non è un valore della sessione (ammessi: lsd, fb_dtsg, app_id, claim, account_id).", nameof(fields));
}
}
Cookies = list;
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);
Capture = capture;
}
/// <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.
/// </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>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>
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)
{
foreach (var (key, value) in Cookies)
{
if (key == name)
{
return value;
}
}
return null;
}
/// <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
/// when the session does not have it, or it is empty; the claim the site has not set yet is
/// <see cref="InitialClaim"/>, as the page sends it.
/// </summary>
public string? Field(string name, string operation) => name switch
{
"user_agent" => UserAgent.Length > 0 ? UserAgent : null,
"doc_id" => DocIds.TryGetValue(operation, out var docId) && docId.Length > 0 ? docId : null,
"claim" => Fields.TryGetValue(name, out var claim) && claim.Length > 0 ? claim : InitialClaim,
_ => Fields.TryGetValue(name, out var value) && value.Length > 0 ? value : null,
};
/// <summary>These values with <paramref name="update"/> applied (same <see cref="Capture"/>).</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 index = cookies.FindIndex(c => c.Key == name);
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);
}
else
{
cookies.Add(new(name, value));
}
if (update.Expires.TryGetValue(name, out var until))
{
expires[name] = until;
}
else
{
expires.Remove(name);
}
}
var fields = Fields.ToDictionary(StringComparer.Ordinal);
if (update.Claim is { } claim)
{
fields["claim"] = claim;
}
return new SiteSessionValues(cookies, UserAgent, fields, DocIds, expires, 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,
$"Sessione salvata: {Cookies.Count} cookie, {Fields.Count} valori della pagina, {DocIds.Count} doc_id.");
}
/// <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.
/// </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="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,
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 index = set.FindIndex(c => c.Key == name);
if (index >= 0)
{
set[index] = new(name, value);
}
else
{
set.Add(new(name, value));
}
}
CookiesSet = set;
CookiesDeleted = [.. (cookiesDeleted ?? []).Distinct(StringComparer.Ordinal)];
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; }
/// <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>The new claim (<c>x-ig-set-www-claim</c>), or null.</summary>
public string? Claim { get; }
/// <summary>True when there is nothing to write.</summary>
public bool IsEmpty => CookiesSet.Count == 0 && CookiesDeleted.Count == 0 && Claim is null;
/// <summary>Counts only.</summary>
public override string ToString() => string.Create(
CultureInfo.InvariantCulture,
$"Aggiornamento della sessione: {CookiesSet.Count} cookie rinnovati, {CookiesDeleted.Count} cancellati{(Claim is null ? string.Empty : ", nuovo claim")}.");
}
/// <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.
/// </summary>
public sealed class InMemorySiteSession : ISiteSession
{
private readonly Lock _gate = new();
private SiteSessionValues? _values;
private int _updates;
/// <param name="values">The session; null for none (no saved session).</param>
public InMemorySiteSession(SiteSessionValues? values) => _values = values;
/// <summary>How many non-empty updates were applied.</summary>
public int Updates => Volatile.Read(ref _updates);
public SiteSessionValues? Read()
{
lock (_gate)
{
return _values;
}
}
/// <summary>Replaces the whole session (a new login), or removes it with null («Scollega»).</summary>
public void Replace(SiteSessionValues? values)
{
lock (_gate)
{
_values = values;
}
}
public Task UpdateAsync(SiteSessionUpdate update, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(update);
ct.ThrowIfCancellationRequested();
if (update.IsEmpty)
{
return Task.CompletedTask;
}
lock (_gate)
{
// No session, or the late answer of one a new login replaced: nothing to change.
if (_values is null || (update.Capture is { } capture && capture != _values.Capture))
{
return Task.CompletedTask;
}
_values = _values.With(update);
_updates++;
}
return Task.CompletedTask;
}
/// <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);
}
}
@@ -92,7 +92,10 @@ public sealed partial class SiteOperation
IReadOnlyList<string> rootFields,
string? sample,
IReadOnlySet<string> required,
IReadOnlySet<string> optional)
IReadOnlySet<string> optional,
IReadOnlyList<string> parameterOrder,
IReadOnlyList<string> headerOrder,
IReadOnlyList<string> bodyOrder)
{
Name = name;
Kind = kind;
@@ -109,6 +112,9 @@ public sealed partial class SiteOperation
Sample = sample;
RequiredValues = required;
OptionalValues = optional;
ParameterOrder = parameterOrder;
HeaderOrder = headerOrder;
BodyOrder = bodyOrder;
PathShape = Placeholder().Replace(path, m => CaseValues.ShapeOf(m.Groups[1].Value));
PathValues = Placeholder().Matches(path).Select(m => m.Groups[1].Value).ToFrozenSet(StringComparer.Ordinal);
PendingValues = [.. headers.Where(h => h.Value.Kind == ValueSourceKind.Pending).Select(h => h.Key)
@@ -162,6 +168,15 @@ public sealed partial class SiteOperation
/// <summary>The form fields of a GraphQL query and where each value comes from.</summary>
public IReadOnlyDictionary<string, ValueSource> Body { get; }
/// <summary>The names of <see cref="Parameters"/> in the order of the file: the order the site client writes them in.</summary>
public IReadOnlyList<string> ParameterOrder { get; }
/// <summary>The names of <see cref="Headers"/> in the order of the file (the request shapes keep the browser's order).</summary>
public IReadOnlyList<string> HeaderOrder { get; }
/// <summary>The names of <see cref="Body"/> in the order of the file (the request shapes keep the page's order).</summary>
public IReadOnlyList<string> BodyOrder { get; }
/// <summary>The template of the variables of a GraphQL query: constants as the shapes show them, <c>"{name}"</c> for a value of the case.</summary>
public JsonElement? Variables { get; }
@@ -645,6 +660,12 @@ public sealed partial class RequestCatalog
$"{where}: {pending.Count.ToString(CultureInfo.InvariantCulture)} intestazioni o campi hanno la fonte «pending» (come {string.Join(", ", pending.Take(3).Select(p => $"«{p}»"))}): non può essere configurata finché non si sa da dove vengono i valori (regola 9).");
}
// The HTTP stack adds no user agent: without this line the request would leave without one (rule 4).
if (!headers.ContainsKey("user-agent"))
{
throw new InvalidDataException($"{where}: un'operazione configurata manda l'user agent del browser («user-agent»: «session:user_agent», regola 4).");
}
if (sample is null || rootFields.Count == 0)
{
throw new InvalidDataException($"{where}: un'operazione configurata dice il campione della risposta («sample») e i campi attesi («rootFields»).");
@@ -658,7 +679,8 @@ public sealed partial class RequestCatalog
return new SiteOperation(
name, kind, method!, path, category, configured, reason, parameters.ToFrozenDictionary(StringComparer.Ordinal),
headers.ToFrozenDictionary(StringComparer.Ordinal), body.ToFrozenDictionary(StringComparer.Ordinal), variables,
rootFields, sample, required.ToFrozenSet(StringComparer.Ordinal), optional.ToFrozenSet(StringComparer.Ordinal));
rootFields, sample, required.ToFrozenSet(StringComparer.Ordinal), optional.ToFrozenSet(StringComparer.Ordinal),
[.. parameters.Keys], [.. headers.Keys], [.. body.Keys]);
}
private static Dictionary<string, ValueSource> Sources(Dictionary<string, string?>? entries, string where, string what, bool isBody)
@@ -30,6 +30,10 @@ public sealed class SiteAnswer
/// <param name="cookiesDeleted">Names of the cookies the site deleted (<c>Set-Cookie</c> expired or empty).</param>
/// <param name="setsClaim">True when the site sent a new <c>x-ig-www-claim</c> (<c>x-ig-set-www-claim</c>).</param>
/// <param name="retryAfter">What a <c>Retry-After</c> asked to wait, when the site sent one.</param>
/// <param name="rootFieldsPresent">
/// Whether the body is JSON with every field of <see cref="SiteOperation.RootFields"/>: true or false when the site
/// client looked (it does for every answer), null when nobody did (<see cref="SiteAnswerSignals"/> then looks itself).
/// </param>
/// <exception cref="ArgumentException">A cookie name that is not a plain name (a value must never slip in).</exception>
public SiteAnswer(
SiteOperation operation,
@@ -40,7 +44,8 @@ public sealed class SiteAnswer
IEnumerable<string>? cookiesSet = null,
IEnumerable<string>? cookiesDeleted = null,
bool setsClaim = false,
TimeSpan? retryAfter = null)
TimeSpan? retryAfter = null,
bool? rootFieldsPresent = null)
{
ArgumentNullException.ThrowIfNull(operation);
Operation = operation.Name;
@@ -54,6 +59,7 @@ public sealed class SiteAnswer
CookiesDeleted = Names(cookiesDeleted, nameof(cookiesDeleted));
SetsClaim = setsClaim;
RetryAfter = retryAfter;
RootFieldsPresent = rootFieldsPresent;
}
/// <summary>Name of the catalog operation that was asked.</summary>
@@ -92,6 +98,12 @@ public sealed class SiteAnswer
/// <summary>What a <c>Retry-After</c> asked to wait (§7.6, Rallentamento).</summary>
public TimeSpan? RetryAfter { get; }
/// <summary>
/// True when the body is JSON with every expected field of the operation, false when it is not JSON or misses one
/// (§6.0: stop and warn), null when it was not looked at.
/// </summary>
public bool? RootFieldsPresent { get; }
/// <summary>True when the declared type is JSON, or JavaScript as Instagram serves its GraphQL data (<see cref="DataResponses.IsData"/>).</summary>
public bool IsDeclaredData => DataResponses.IsData(MimeType, "Fetch");
@@ -0,0 +1,194 @@
using System.Globalization;
using System.Text;
using System.Text.Json;
using Febe.Core.Abstractions;
namespace Febe.Core.Collection.Requests;
/// <summary>A stop signal read from an answer of the site client, with the Italian text the interface and the log show.</summary>
/// <param name="Signal">The signal for the circuit breaker; its address is the path shape of the operation, never a value.</param>
/// <param name="Message">What happened, in Italian: operation, status, path shapes, never a value or a body.</param>
/// <param name="Hypothesis">The hypothesis of spec §6.6 the reading depends on (<c>H16</c>), when the true shapes are not known yet.</param>
public sealed record SiteAnswerSignal(Signal Signal, string Message, string? Hypothesis);
/// <summary>
/// Reads the stop signals of spec §7.6 from a <see cref="SiteAnswer"/> (issue #36, S2), whatever brought it: the HTTP
/// site client or its test double. Transport-neutral: status, type, redirect, cookies and body only.
/// </summary>
/// <remarks>
/// In order, the first that applies:
/// <list type="number">
/// <item>the status rules of <c>segnali.json</c> for the site (429 is a Rallentamento, as for the browser);</item>
/// <item>the session cookie deleted by the site;</item>
/// <item>a redirect (3xx, never followed), a 401 or a 403;</item>
/// <item>then, whatever the status: an HTML document where the catalog expects JSON, a body that is not JSON (an empty
/// one included), the text rules of <c>segnali.json</c> on a short JSON;</item>
/// <item>last, for every status but 404 (a JSON «not found» is an answer, the recipe decides) and 5xx (a JSON error of
/// the site, S3 decides whether to try again later): a JSON without the expected fields of the operation.</item>
/// </list>
/// Until the true shapes of an expired or challenged session are known (H16), the cases after the status rules are a
/// <see cref="SignalLevel.Challenge"/> (Verifica): Febe stops, warns, and Alberto decides whether to log in again
/// (decision of 16 November 2026). A JSON answer with its fields and nothing of the above gives no signal.
/// </remarks>
public sealed class SiteAnswerSignals
{
/// <summary>A 3xx: never followed.</summary>
public const string RedirectCode = "site-redirect";
/// <summary>A 401.</summary>
public const string UnauthorizedCode = "site-unauthorized";
/// <summary>A 403.</summary>
public const string ForbiddenCode = "site-forbidden";
/// <summary>An HTML document where the catalog expects JSON.</summary>
public const string HtmlCode = "site-html-instead-of-json";
/// <summary>A body that is not JSON.</summary>
public const string NotJsonCode = "site-not-json";
/// <summary>A JSON without the expected fields of the operation.</summary>
public const string MissingFieldsCode = "site-missing-fields";
/// <summary>A <c>Set-Cookie</c> that deletes the session cookie.</summary>
public const string SessionCookieDeletedCode = "site-session-cookie-deleted";
/// <summary>No saved session, or one without the session cookie or a value the catalog asks for: nothing left.</summary>
public const string SessionMissingCode = "saved-session-missing";
/// <summary>The hypothesis the H16 readings depend on.</summary>
public const string H16 = "H16";
private const string Decides = "Febe si ferma e non rifà l'accesso da sola: decide Alberto.";
private static readonly JsonDocumentOptions BodyOptions = new() { MaxDepth = ResponseDelivery.MaxDepth };
private readonly SignalRules _rules;
private readonly string _sessionCookie;
/// <param name="rules">The rules of the site (<c>segnali.json</c>, <c>segnali.prova.json</c>).</param>
/// <param name="sessionCookie">Name of the session cookie of the site (<c>sessionid</c>, <c>sessione_prova</c>).</param>
public SiteAnswerSignals(SignalRules rules, string sessionCookie)
{
_rules = rules ?? throw new ArgumentNullException(nameof(rules));
ArgumentException.ThrowIfNullOrWhiteSpace(sessionCookie);
_sessionCookie = sessionCookie;
}
/// <summary>The signal <paramref name="answer"/> carries, or null when it carries none.</summary>
/// <param name="operation">The catalog operation that was asked (its expected fields).</param>
/// <param name="answer">What the site answered.</param>
/// <param name="at">When (the engine's clock).</param>
/// <exception cref="ArgumentException"><paramref name="answer"/> is not an answer to <paramref name="operation"/>.</exception>
public SiteAnswerSignal? Classify(SiteOperation operation, SiteAnswer answer, DateTimeOffset at)
{
ArgumentNullException.ThrowIfNull(operation);
ArgumentNullException.ThrowIfNull(answer);
if (answer.Operation != operation.Name)
{
throw new ArgumentException("La risposta non è di questa operazione.", nameof(answer));
}
var what = $"«{operation.Name}» ({operation.PathShape})";
var status = answer.Status.ToString(CultureInfo.InvariantCulture);
foreach (var rule in _rules.Rules)
{
if (rule.Statuses.Contains(answer.Status) && rule.HostKinds.Contains(HostKind.Site) && (rule.Scope & SignalScope.Subresource) != 0)
{
var wait = answer.RetryAfter is { } retry ? string.Create(CultureInfo.InvariantCulture, $", chiede di attendere {(long)retry.TotalSeconds} s") : string.Empty;
return Make(rule.Level, rule.Code, operation, at, $"{what}: il sito ha risposto con lo stato {status}{wait}.", rule.Hypothesis);
}
}
if (answer.Deletes(_sessionCookie))
{
return Challenge(SessionCookieDeletedCode, operation, at, $"{what}: il sito ha cancellato il cookie di sessione (stato {status}). {Decides}");
}
if (answer.IsRedirect)
{
var to = answer.RedirectPathShape is { Length: > 0 } shape ? $" a {shape}" : " senza indirizzo";
return Challenge(RedirectCode, operation, at, $"{what}: il sito ha risposto con un rinvio{to} (stato {status}), non seguito. {Decides}");
}
if (answer.Status is 401 or 403)
{
return Challenge(answer.Status == 401 ? UnauthorizedCode : ForbiddenCode, operation, at, $"{what}: il sito ha rifiutato la richiesta (stato {status}). {Decides}");
}
// A JSON «not found» or site error is an answer for the recipe (S3); an HTML or a body that is not JSON is not,
// whatever the status (§6.0: «una risposta che non è JSON quando il modello si aspetta JSON ferma la sessione»).
var jsonLeftToCaller = answer.Status == 404 || answer.Status >= 500;
if (answer.IsHtml || LooksLikeHtml(answer.Body.Span))
{
return Challenge(HtmlCode, operation, at, $"{what}: il sito ha mandato una pagina HTML al posto dei dati JSON (stato {status}). {Decides}");
}
JsonDocument document;
try
{
document = JsonDocument.Parse(answer.Body, BodyOptions);
}
catch (JsonException)
{
return Challenge(NotJsonCode, operation, at, $"{what}: la risposta non è JSON (stato {status}, {(answer.MimeType.Length == 0 ? "senza tipo" : answer.MimeType)}). {Decides}");
}
using (document)
{
foreach (var rule in _rules.Rules)
{
if (rule.Text is not null && rule.HostKinds.Contains(HostKind.Site) && SignalDetector.ContainsText(document.RootElement, rule.Text, rule.MaxTextChars))
{
return Make(rule.Level, rule.Code, operation, at, $"{what}: la risposta chiede di fermarsi («{rule.Code}», stato {status}).", rule.Hypothesis);
}
}
if (jsonLeftToCaller)
{
return null;
}
var present = answer.RootFieldsPresent ?? operation.HasRootFields(document.RootElement);
if (!present)
{
return Challenge(
MissingFieldsCode,
operation,
at,
$"{what}: nella risposta mancano i campi attesi ({string.Join(", ", operation.RootFields)}; stato {status}). Il formato può essere cambiato o la sessione non vale più. {Decides}");
}
}
return null;
}
/// <summary>
/// The signal of a request that did not leave because the saved session is missing or incomplete (§7.6,
/// Disconnessione: «la sessione salvata manca»).
/// </summary>
public static SiteAnswerSignal ForMissingSession(SiteSessionMissingException refusal, DateTimeOffset at)
{
ArgumentNullException.ThrowIfNull(refusal);
var what = refusal.Missing is null ? "non c'è una sessione salvata" : $"nella sessione salvata manca «{refusal.Missing}»";
return new SiteAnswerSignal(
new Signal(SignalLevel.Disconnect, SessionMissingCode, null, at),
$"Client del sito: {what}. Serve un nuovo accesso dal browser di Febe; Febe non rientra da sola.",
null);
}
private static SiteAnswerSignal Challenge(string code, SiteOperation operation, DateTimeOffset at, string message) =>
Make(SignalLevel.Challenge, code, operation, at, message, H16);
private static SiteAnswerSignal Make(SignalLevel level, string code, SiteOperation operation, DateTimeOffset at, string message, string? hypothesis) =>
new(new Signal(level, code, operation.PathShape, at), message, hypothesis);
/// <summary>A body that starts as an HTML document, whatever its declared type.</summary>
private static bool LooksLikeHtml(ReadOnlySpan<byte> body)
{
var head = Encoding.UTF8.GetString(body[..Math.Min(body.Length, 512)]).TrimStart('', ' ', '\t', '\r', '\n');
return head.StartsWith("<!doctype html", StringComparison.OrdinalIgnoreCase)
|| head.StartsWith("<html", StringComparison.OrdinalIgnoreCase);
}
}
+1 -1
View File
@@ -222,7 +222,7 @@ public sealed class SignalDetector : IResponseObserver, IResponseConsumer, IStop
}
/// <summary>Looks for <paramref name="regex"/> in the string values, giving up when they exceed <paramref name="maxChars"/>.</summary>
private static bool ContainsText(JsonElement root, Regex regex, int maxChars)
internal static bool ContainsText(JsonElement root, Regex regex, int maxChars)
{
var budget = maxChars;
var strings = new List<string>();