Files
Febe/tools/Febe.SitoDiProva/DirectApi.cs
T
Alby96andClaude Opus 5.5 ce9691fe1c
verifica / controlli (push) Successful in 17s
verifica / prove (push) Successful in 15m4s
verifica / installatore (push) Successful in 4m22s
verifica / immagine (push) Successful in 15m55s
Client del sito contro il sito di prova (#36, S2)
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>
2026-11-16 18:34:12 +01:00

286 lines
12 KiB
C#

using System.Collections.Frozen;
using System.Text.Json;
using System.Text.Json.Nodes;
using Microsoft.AspNetCore.Http;
namespace Febe.SitoDiProva;
/// <summary>
/// The answers to the site client of Febe (issue #36, spec §6.0, §14.2): the operations of <c>richieste.prova.json</c>,
/// served under <c>/api/</c> in the request shape the catalog describes, with the same JSON the pages fetch from
/// <c>/dati/</c>. Here the site checks what a real site checks: the session cookie, <c>x-csrftoken</c> equal to the
/// cookie <c>csrftoken</c>, the headers and fields of the catalog. The pages keep their <c>/dati/</c>, which checks
/// nothing, so the browser tests do not change.
/// </summary>
/// <remarks>
/// What a refused request gets is generic and marked H16: the true answers of Instagram to an expired session, a wrong
/// token or a malformed request are not known from samples. A missing or ended session: a plain address gets 302 to
/// <c>/accesso/</c>, a GraphQL query 401 with a short JSON. A wrong or missing <c>x-csrftoken</c>: 403 with an HTML page.
/// A missing header, an unknown <c>doc_id</c>, a field or variables that do not match: 400 with a short JSON.
/// </remarks>
public sealed partial class TestSite
{
/// <summary>Name of the cookie whose value goes in <c>x-csrftoken</c>.</summary>
public const string CsrfCookie = "csrftoken";
/// <summary>The value of <c>x-app-id</c> the pages of the site would send (a value of the page, session:app_id).</summary>
public const string AppId = "prova-applicazione-1";
/// <summary>The token <c>lsd</c> the pages of the site would hold (session:lsd).</summary>
public const string Lsd = "lsd-di-prova";
/// <summary>The token <c>fb_dtsg</c> the pages of the site would hold (session:fb_dtsg).</summary>
public const string Dtsg = "dtsg-di-prova";
/// <summary>The GraphQL query of the site: a profile page, with the JSON of <c>/dati/profilo/{nome}</c>.</summary>
public const string ProfileQuery = "ProvaProfiloQuery";
/// <summary>The <c>doc_id</c> of each GraphQL query, as the modules of the pages would hold them (session:doc_id).</summary>
public static IReadOnlyDictionary<string, string> DocIds { get; } =
new Dictionary<string, string> { [ProfileQuery] = "8000000000000001" }.ToFrozenDictionary(StringComparer.Ordinal);
private const string Html = "<!DOCTYPE html><html lang=\"it\"><head><meta charset=\"utf-8\"><title>Sito di prova</title></head><body><p>Una pagina, non dati.</p></body></html>";
private async Task DirectAsync(HttpContext context, string path)
{
var request = context.Request;
var (reply, mode) = Control.OnDirectRequest($"{request.Method} {path}{request.QueryString.Value}");
try
{
if (Control.DirectDelay > TimeSpan.Zero)
{
await Task.Delay(Control.DirectDelay, context.RequestAborted).ConfigureAwait(false);
}
if (await StopAsync(context, path, reply, mode).ConfigureAwait(false))
{
return;
}
var isGraphQl = path == "/api/graphql";
var segments = path.Split('/', StringSplitOptions.RemoveEmptyEntries).Select(Uri.UnescapeDataString).ToArray();
if (!isGraphQl && segments is not ["api", "dati", ..])
{
await JsonAsync(context, 404, new JsonObject { ["errore"] = "non-trovato" }).ConfigureAwait(false);
return;
}
if (isGraphQl ? !HttpMethods.IsPost(request.Method) : !HttpMethods.IsGet(request.Method))
{
// A write (POST of a plain address) or a GET of the GraphQL entry: no site answers it with data.
await JsonAsync(context, 405, new JsonObject { ["errore"] = "metodo" }).ConfigureAwait(false);
return;
}
var session = request.Cookies[SessionCookie];
if (!Control.IsSession(session))
{
// H16-generic: what Instagram answers to a missing or ended session is not known from samples.
if (isGraphQl)
{
await JsonAsync(context, 401, new JsonObject { ["errore"] = "sessione", ["accesso_richiesto"] = true }).ConfigureAwait(false);
}
else
{
context.Response.Redirect("/accesso/?next=" + Uri.EscapeDataString(path));
}
return;
}
var csrf = request.Cookies[CsrfCookie];
if (string.IsNullOrEmpty(csrf) || request.Headers["x-csrftoken"].ToString() != csrf)
{
// H16-generic: a token missing or different from its cookie.
await HtmlAsync(context, 403, "<!DOCTYPE html><html lang=\"it\"><head><meta charset=\"utf-8\"><title>Vietato</title></head><body><h1>Verifica del gettone non riuscita</h1></body></html>").ConfigureAwait(false);
return;
}
if (string.IsNullOrWhiteSpace(request.Headers.UserAgent.ToString())
|| request.Headers.Accept.Count == 0
|| request.Headers["x-app-id"].ToString() != AppId)
{
await BadRequestAsync(context, "intestazioni").ConfigureAwait(false);
return;
}
JsonObject? data;
if (isGraphQl)
{
var (problem, answer) = await GraphQlAsync(request).ConfigureAwait(false);
if (problem is not null)
{
await BadRequestAsync(context, problem).ConfigureAwait(false);
return;
}
data = answer;
}
else if (segments is ["api", "dati", "cerca"])
{
lock (World.Gate)
{
data = Api.Search(request.Query["testo"].ToString());
}
}
else if (segments is ["api", "dati", "ricerche-recenti"])
{
// Read only: the site client never writes (a POST was refused above).
lock (World.Gate)
{
data = Api.RecentSearches([.. World.Following.Take(3).Select(a => a.Username)]);
}
}
else
{
data = Lookup(segments[1..], request.Query);
}
if (data is null)
{
await JsonAsync(context, 404, new JsonObject { ["errore"] = "non-trovato" }).ConfigureAwait(false);
return;
}
Decorate(context, reply, session!);
await JsonAsync(context, 200, data).ConfigureAwait(false);
}
finally
{
Control.OnDirectFinished();
}
}
/// <summary>The stop cases, before any check: the reply the tests asked for, or the mode of the whole site.</summary>
private async Task<bool> StopAsync(HttpContext context, string path, DirectReply reply, StopMode mode)
{
if (reply == DirectReply.TooManyRequests || (reply == DirectReply.Normal && mode == StopMode.TooManyRequests))
{
context.Response.Headers.RetryAfter = "60";
await JsonAsync(context, 429, new JsonObject { ["errore"] = "troppe-richieste", ["messaggio"] = "Troppe richieste: riprova più tardi." }).ConfigureAwait(false);
return true;
}
if (reply == DirectReply.RedirectToChallenge || (reply == DirectReply.Normal && mode == StopMode.Challenge))
{
context.Response.Redirect("/verifica?motivo=prova&next=" + Uri.EscapeDataString(path));
return true;
}
if (reply == DirectReply.RedirectToLogin || (reply == DirectReply.Normal && mode == StopMode.SessionEnded))
{
if (mode == StopMode.SessionEnded)
{
// The session ends on the site too: a client that kept the cookie gets the login page after it.
EndSession(context);
}
context.Response.Redirect("/accesso/?next=" + Uri.EscapeDataString(path));
return true;
}
if (reply == DirectReply.HtmlInsteadOfJson)
{
await HtmlAsync(context, 200, Html).ConfigureAwait(false);
return true;
}
if (reply == DirectReply.MissingRootField || (reply == DirectReply.Normal && mode == StopMode.UnknownFormat))
{
await JsonAsync(context, 200, DataApi.UnknownShape()).ConfigureAwait(false);
return true;
}
if (reply == DirectReply.Normal && mode == StopMode.EmptyPages)
{
await JsonAsync(context, 200, DataApi.EmptyPage()).ConfigureAwait(false);
return true;
}
return false;
}
/// <summary>
/// The GraphQL query: form fields, <c>doc_id</c>, friendly name, tokens and variables as the pages would send them.
/// Returns why it is refused, or the data.
/// </summary>
private async Task<(string? Problem, JsonObject? Data)> GraphQlAsync(HttpRequest request)
{
if (!request.HasFormContentType || request.ContentType?.StartsWith("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase) != true)
{
return ("tipo", null);
}
var form = await request.ReadFormAsync().ConfigureAwait(false);
var docId = form["doc_id"].ToString();
var name = form["fb_api_req_friendly_name"].ToString();
if (!DocIds.TryGetValue(name, out var expected) || expected != docId || request.Headers["x-fb-friendly-name"].ToString() != name)
{
return ("doc_id", null);
}
if (form["lsd"].ToString() != Lsd || form["fb_dtsg"].ToString() != Dtsg || form["__a"].ToString() != "1"
|| string.IsNullOrEmpty(request.Headers["x-ig-www-claim"].ToString()))
{
return ("campi", null);
}
JsonObject variables;
try
{
variables = JsonNode.Parse(form["variables"].ToString()) as JsonObject ?? throw new JsonException();
}
catch (JsonException)
{
return ("variabili", null);
}
// ProvaProfiloQuery: {"username": text, "scheda": "post" | "reel" | "taggati", "primi": 12, "raccolte": true | false}.
if (variables.Count != 4
|| variables["username"] is not JsonValue user || user.GetValueKind() != JsonValueKind.String
|| variables["scheda"] is not JsonValue tab || tab.GetValueKind() != JsonValueKind.String
|| variables["primi"] is not JsonValue first || first.GetValueKind() != JsonValueKind.Number || first.ToJsonString() != "12"
|| variables["raccolte"] is not JsonValue highlights || highlights.GetValueKind() is not (JsonValueKind.True or JsonValueKind.False))
{
return ("variabili", null);
}
var profileTab = tab.GetValue<string>() switch
{
"post" => ProfileTab.Posts,
"reel" => ProfileTab.Reels,
"taggati" => ProfileTab.Tagged,
_ => (ProfileTab?)null,
};
if (profileTab is null)
{
return ("variabili", null);
}
lock (World.Gate)
{
return (null, Api.Profile(user.GetValue<string>(), profileTab.Value, null));
}
}
/// <summary>What a normal answer carries besides the data, when the tests asked for it.</summary>
private void Decorate(HttpContext context, DirectReply reply, string session)
{
switch (reply)
{
case DirectReply.RenewSessionCookie:
context.Response.Cookies.Append(SessionCookie, Control.RenewSession(session), new CookieOptions { Path = "/", MaxAge = TimeSpan.FromDays(1), SameSite = SameSiteMode.Lax, HttpOnly = true });
break;
case DirectReply.DeleteSessionCookie:
EndSession(context);
break;
case DirectReply.SetClaim:
context.Response.Headers["x-ig-set-www-claim"] = Control.NextClaim();
break;
}
}
private static Task BadRequestAsync(HttpContext context, string what) =>
JsonAsync(context, 400, new JsonObject { ["errore"] = "richiesta-non-valida", ["dove"] = what });
}