using System.Collections.Frozen; using System.Text.Json; using System.Text.Json.Nodes; using Microsoft.AspNetCore.Http; namespace Febe.SitoDiProva; /// /// The answers to the site client of Febe (issue #36, spec §6.0, §14.2): the operations of richieste.prova.json, /// served under /api/ in the request shape the catalog describes, with the same JSON the pages fetch from /// /dati/. Here the site checks what a real site checks: the session cookie, x-csrftoken equal to the /// cookie csrftoken, the headers and fields of the catalog. The pages keep their /dati/, which checks /// nothing, so the browser tests do not change. /// /// /// 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 /// /accesso/, a GraphQL query 401 with a short JSON. A wrong or missing x-csrftoken: 403 with an HTML page. /// A missing header, an unknown doc_id, a field or variables that do not match: 400 with a short JSON. /// public sealed partial class TestSite { /// Name of the cookie whose value goes in x-csrftoken. public const string CsrfCookie = "csrftoken"; /// The value of x-app-id the pages of the site would send (a value of the page, session:app_id). public const string AppId = "prova-applicazione-1"; /// The token lsd the pages of the site would hold (session:lsd). public const string Lsd = "lsd-di-prova"; /// The token fb_dtsg the pages of the site would hold (session:fb_dtsg). public const string Dtsg = "dtsg-di-prova"; /// The revision of the pages (session:rev, field __rev; module VersioneProva.revisione of richieste.prova.json). public const string Revision = "revisione-di-prova"; /// The haste session of the pages (session:hs, field __hs; VersioneProva.hs). public const string HasteSession = "hs-di-prova"; /// The id of the page load (session:hsi, field __hsi; VersioneProva.hsi). public const string HasteSessionId = "hsi-di-prova"; /// The pixel ratio the pages send (session:dpr, field dpr; VersioneProva.dpr). public const string Dpr = "1"; /// The comet environment the pages send (session:comet_req, field __comet_req; VersioneProva.comet). public const string CometReq = "7"; /// The connection class the pages send (session:ccg, field __ccg; ConnessioneProva.classe). public const string ConnectionClass = "BUONA"; /// The nonce of the page load (session:entry_nonce, header x-fb-entry-nonce; AvvioProva.nonce). public const string EntryNonce = "nonce-di-prova"; /// A cookie of the pages limited to the addresses under (Path=/api/): the copy keeps it with its path. public const string ApiPathCookie = "percorso_api"; /// The value of . public const string ApiPathCookieValue = "solo-sotto-api"; /// The path of . public const string ApiPath = "/api/"; /// The GraphQL query of the site: a profile page, with the JSON of /dati/profilo/{nome}. public const string ProfileQuery = "ProvaProfiloQuery"; /// The doc_id of each GraphQL query, as the modules of the pages would hold them (session:doc_id). public static IReadOnlyDictionary DocIds { get; } = new Dictionary { [ProfileQuery] = "8000000000000001" }.ToFrozenDictionary(StringComparer.Ordinal); private const string Html = "Sito di prova

Una pagina, non dati.

"; 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, "Vietato

Verifica del gettone non riuscita

").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(); } } /// The stop cases, before any check: the reply the tests asked for, or the mode of the whole site. private async Task 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; } /// /// The GraphQL query: form fields, doc_id, friendly name, tokens and variables as the pages would send them. /// Returns why it is refused, or the data. /// 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); } // The values of the page the saved session copies (S4): a missing or different one gets the same generic 400. if (form["__rev"].ToString() != Revision || form["__hs"].ToString() != HasteSession || form["__hsi"].ToString() != HasteSessionId || form["__ccg"].ToString() != ConnectionClass || form["dpr"].ToString() != Dpr || form["__comet_req"].ToString() != CometReq || request.Headers["x-fb-entry-nonce"].ToString() != EntryNonce) { 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() 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(), profileTab.Value, null)); } } /// What a normal answer carries besides the data, when the tests asked for it. 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 }); }