Files
Febe/tools/Febe.SitoDiProva/TestSite.cs
T
Alby96andClaude Opus 5.5 c87768766c
verifica / controlli (push) Successful in 22s
verifica / prove (push) Successful in 16m46s
verifica / installatore (push) Successful in 4m43s
verifica / immagine (push) Successful in 21m2s
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>
2026-11-17 16:43:43 +01:00

647 lines
25 KiB
C#

using System.Globalization;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.Json.Nodes;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Febe.SitoDiProva;
/// <summary>Options of the test site.</summary>
public sealed record TestSiteOptions
{
/// <summary>Port of the site on 127.0.0.1; 0 picks a free one.</summary>
public int Port { get; init; }
/// <summary>Port of the «CDN»; 0 picks a free one.</summary>
public int CdnPort { get; init; }
/// <summary>Address of the «CDN»: a second loopback address, so cookies of the site do not reach it.</summary>
public string CdnAddress { get; init; } = "127.0.0.2";
/// <summary>Seed of the synthetic data.</summary>
public int Seed { get; init; } = 13;
/// <summary>Clock of the site (dates, address expiry).</summary>
public TimeProvider Time { get; init; } = TimeProvider.System;
/// <summary>Write requests to the console (the command-line tool does; tests do not).</summary>
public bool ConsoleLog { get; init; }
}
/// <summary>
/// The local test site of spec §14.2, served on 127.0.0.1 with its «CDN» on a second address. Pages are plain and
/// fetch JSON in a synthetic format of our own; stop cases are switched through <see cref="Control"/> or the
/// <c>/_controllo</c> endpoints. Never Instagram, never anything that looks like it.
/// </summary>
public sealed partial class TestSite : IAsyncDisposable
{
/// <summary>Name of the session cookie of the site.</summary>
public const string SessionCookie = "sessione_prova";
private readonly WebApplication _app;
private readonly TimeProvider _time;
private TestSite(WebApplication app, World world, SiteControl control, MediaFactory media, CdnSigner signer, int sitePort, string cdnAddress, int cdnPort, TimeProvider time)
{
_app = app;
World = world;
Control = control;
Media = media;
Signer = signer;
SitePort = sitePort;
CdnAddress = cdnAddress;
CdnPort = cdnPort;
_time = time;
}
public World World { get; }
public SiteControl Control { get; }
public MediaFactory Media { get; }
public CdnSigner Signer { get; }
public int SitePort { get; }
public string CdnAddress { get; }
public int CdnPort { get; }
/// <summary>«127.0.0.1:port»: an entry for the host classifier.</summary>
public string SiteHost => $"127.0.0.1:{SitePort.ToString(CultureInfo.InvariantCulture)}";
public string CdnHost => $"{CdnAddress}:{CdnPort.ToString(CultureInfo.InvariantCulture)}";
public string SiteUrl => $"http://{SiteHost}";
public string CdnUrl => $"http://{CdnHost}";
public string Url(string path) => SiteUrl + path;
public static async Task<TestSite> StartAsync(TestSiteOptions? options = null, CancellationToken ct = default)
{
options ??= new TestSiteOptions();
var cdnAddress = CanBind(options.CdnAddress) ? options.CdnAddress : "127.0.0.1";
var sitePort = options.Port > 0 ? options.Port : FreePort(IPAddress.Loopback);
var cdnPort = options.CdnPort > 0 ? options.CdnPort : FreePort(IPAddress.Parse(cdnAddress));
if (cdnAddress == "127.0.0.1" && cdnPort == sitePort)
{
cdnPort = FreePort(IPAddress.Loopback);
}
var world = World.Generate(options.Seed, options.Time.GetUtcNow());
var control = new SiteControl();
var media = new MediaFactory();
var signer = new CdnSigner();
var builder = WebApplication.CreateSlimBuilder();
builder.Services.Configure<Microsoft.Extensions.Hosting.HostOptions>(o => o.ShutdownTimeout = TimeSpan.FromSeconds(2));
builder.Logging.ClearProviders();
if (options.ConsoleLog)
{
builder.Logging.AddSimpleConsole(o => o.SingleLine = true);
builder.Logging.SetMinimumLevel(LogLevel.Warning);
}
builder.WebHost.UseKestrel(k =>
{
k.Listen(IPAddress.Loopback, sitePort);
k.Listen(IPAddress.Parse(cdnAddress), cdnPort);
});
var app = builder.Build();
var site = new TestSite(app, world, control, media, signer, sitePort, cdnAddress, cdnPort, options.Time);
app.Run(site.HandleAsync);
await app.StartAsync(ct).ConfigureAwait(false);
return site;
}
public async ValueTask DisposeAsync()
{
await _app.StopAsync().ConfigureAwait(false);
await _app.DisposeAsync().ConfigureAwait(false);
}
/// <summary>The JSON of a data endpoint as the page would receive it (sample capture, tests).</summary>
public async Task<string> GetDataAsync(string pathAndQuery, CancellationToken ct = default)
{
using var client = new HttpClient(new SocketsHttpHandler { UseProxy = false, UseCookies = false });
return await client.GetStringAsync(new Uri(Url(pathAndQuery)), ct).ConfigureAwait(false);
}
private DataApi Api => new(World, Signer, Control, () => CdnUrl, _time);
private async Task HandleAsync(HttpContext context)
{
context.Response.Headers.CacheControl = "no-store";
if (context.Connection.LocalPort == CdnPort && context.Connection.LocalIpAddress?.ToString() == CdnAddress)
{
await ServeCdnAsync(context).ConfigureAwait(false);
return;
}
var path = context.Request.Path.Value ?? "/";
if (path.StartsWith("/_controllo/", StringComparison.Ordinal))
{
await ControlAsync(context, path["/_controllo/".Length..]).ConfigureAwait(false);
return;
}
if (path.StartsWith("/risorse/", StringComparison.Ordinal))
{
await ResourceAsync(context, path["/risorse/".Length..]).ConfigureAwait(false);
return;
}
if (path.StartsWith("/dati/", StringComparison.Ordinal))
{
await DataAsync(context, path).ConfigureAwait(false);
return;
}
if (path.StartsWith("/api/", StringComparison.Ordinal))
{
await DirectAsync(context, path).ConfigureAwait(false);
return;
}
await PageAsync(context, path).ConfigureAwait(false);
}
private async Task PageAsync(HttpContext context, string path)
{
var mode = Control.Mode;
Control.OnPageVisit(path);
if (path is "/verifica" or "/verifica/")
{
await HtmlAsync(context, 200, Pages.Challenge()).ConfigureAwait(false);
return;
}
if (path is "/sessione-scaduta" or "/sessione-scaduta/")
{
await HtmlAsync(context, 200, Pages.SessionEnded()).ConfigureAwait(false);
return;
}
if (path == "/favicon.ico")
{
context.Response.StatusCode = 404;
return;
}
switch (mode)
{
case StopMode.Challenge:
context.Response.Redirect("/verifica?motivo=prova");
return;
case StopMode.SessionEnded:
EndSession(context);
context.Response.Redirect("/sessione-scaduta");
return;
}
var opened = !Control.IsSession(context.Request.Cookies[SessionCookie]);
if (opened)
{
// No cookie, or one the site ended (a session that expired, a reset): the visit is a new login, with a new
// value that the site client accepts too once copied.
context.Response.Cookies.Append(SessionCookie, Control.OpenSession(), new CookieOptions { Path = "/", MaxAge = TimeSpan.FromDays(1), SameSite = SameSiteMode.Lax, HttpOnly = true });
}
if (opened || string.IsNullOrEmpty(context.Request.Cookies[CsrfCookie]))
{
// What a real site gives its pages besides the session (issue #36, S4): the token the page reads and sends
// back in x-csrftoken, and a cookie only for the addresses under /api/, which the copy at «Ho finito» must
// keep with its path.
context.Response.Cookies.Append(CsrfCookie, Control.NextCsrf(), new CookieOptions { Path = "/", MaxAge = TimeSpan.FromDays(1), SameSite = SameSiteMode.Lax });
context.Response.Cookies.Append(ApiPathCookie, ApiPathCookieValue, new CookieOptions { Path = ApiPath, MaxAge = TimeSpan.FromDays(1), SameSite = SameSiteMode.Lax, HttpOnly = true });
}
var segments = path.Split('/', StringSplitOptions.RemoveEmptyEntries).Select(Uri.UnescapeDataString).ToArray();
string html;
var status = 200;
lock (World.Gate)
{
switch (segments)
{
case []:
html = Pages.Home();
break;
case ["benvenuto"]:
// The «pagina di accesso» Febe opens on the test site (LoginUrl): the cookie above already opened the session.
html = Pages.Welcome();
break;
case ["profilo", var user, ..] when World.FindByUsername(user) is null:
html = Pages.ProfileNotFound(user);
status = 404;
break;
case ["profilo", var user]:
html = Pages.Profile(user, ProfileTab.Posts);
break;
case ["profilo", var user, "reel"]:
html = Pages.Profile(user, ProfileTab.Reels);
break;
case ["profilo", var user, "taggati"]:
html = Pages.Profile(user, ProfileTab.Tagged);
break;
case ["profilo", var user, "seguiti"] when World.FindByUsername(user)?.IsViewer == true:
html = Pages.Following(user);
break;
case ["post", var code, ..]:
html = Pages.Post(code);
break;
case ["storie", _, ..]:
html = Pages.Viewer("storie", Control.StoryDuration);
break;
case ["evidenza", _, ..]:
html = Pages.Viewer("evidenza", Control.StoryDuration);
break;
default:
html = Pages.NotFound();
status = 404;
break;
}
}
if (Control.SearchMemory)
{
html = html.Replace("<body ", "<body data-memoria-ricerca=\"si\" ", StringComparison.Ordinal);
}
// The modules of the page (issue #36, S4): what the copy at «Ho finito» reads, by the names of richieste.prova.json.
string registry;
lock (World.Gate)
{
registry = ModuleRegistryScript(World.Viewer.Id);
}
html = InsertAfterHead(html, registry);
await HtmlAsync(context, status, html).ConfigureAwait(false);
}
private async Task DataAsync(HttpContext context, string path)
{
var query = context.Request.Query;
var mode = Control.OnDataRequest(path + context.Request.QueryString.Value);
switch (mode)
{
case StopMode.TooManyRequests:
await JsonAsync(context, 429, new JsonObject { ["errore"] = "troppe-richieste", ["messaggio"] = "Troppe richieste: riprova più tardi." }).ConfigureAwait(false);
return;
case StopMode.Challenge:
await JsonAsync(context, 403, new JsonObject { ["errore"] = "verifica" }).ConfigureAwait(false);
return;
case StopMode.SessionEnded:
EndSession(context);
await JsonAsync(context, 401, new JsonObject { ["errore"] = "sessione" }).ConfigureAwait(false);
return;
case StopMode.EmptyPages:
await JsonAsync(context, 200, DataApi.EmptyPage()).ConfigureAwait(false);
return;
case StopMode.UnknownFormat:
await JsonAsync(context, 200, DataApi.UnknownShape()).ConfigureAwait(false);
return;
}
var segments = path.Split('/', StringSplitOptions.RemoveEmptyEntries).Select(Uri.UnescapeDataString).ToArray();
if (segments is ["dati", "cerca"])
{
await SearchAsync(context, query["testo"].ToString()).ConfigureAwait(false);
return;
}
if (segments is ["dati", "ricerche-recenti"])
{
if (HttpMethods.IsPost(context.Request.Method))
{
// The analogue of Instagram registering a search in the recent ones: a write Febe must never cause.
Control.OnRecentSearchWritten();
await JsonAsync(context, 200, new JsonObject { ["ok"] = true }).ConfigureAwait(false);
return;
}
JsonObject recent;
lock (World.Gate)
{
recent = Api.RecentSearches([.. World.Following.Take(3).Select(a => a.Username)]);
}
await JsonAsync(context, 200, recent).ConfigureAwait(false);
return;
}
var result = Lookup(segments, query);
if (result is null)
{
await JsonAsync(context, 404, new JsonObject { ["errore"] = "non-trovato" }).ConfigureAwait(false);
return;
}
await JsonAsync(context, 200, result).ConfigureAwait(false);
}
/// <summary>
/// The JSON of a data address (<c>/dati/…</c> for the pages, the same under <c>/api/dati/…</c> for the site client),
/// by its segments from «dati» on; null when there is nothing there.
/// </summary>
private JsonObject? Lookup(string[] segments, IQueryCollection query)
{
var tab = query["scheda"].ToString() switch { "reel" => ProfileTab.Reels, "taggati" => ProfileTab.Tagged, _ => ProfileTab.Posts };
var after = query["dopo"].ToString();
lock (World.Gate)
{
var api = Api;
return segments switch
{
["dati", "inizio"] => api.Home(),
["dati", "inizio", "altri"] => api.HomeMore(after),
["dati", "profilo", var user] => api.Profile(user, tab, after),
["dati", "profilo", var user, "altri"] => api.ProfileMore(user, tab, after),
["dati", "post", var code] => api.SinglePost(code),
["dati", "storie", var user] => api.Stories(user),
["dati", "evidenza", var id] => api.HighlightItems(id),
["dati", "seguiti"] => api.Following(after),
_ => null,
};
}
}
/// <summary>The answer of the search box, after the waits the control asks for (slow, out of order).</summary>
private async Task SearchAsync(HttpContext context, string text)
{
var delay = Control.SearchDelay;
if (Control.SearchDisorder)
{
delay += TimeSpan.FromMilliseconds(Math.Max(0, 8 - text.Trim().Length) * 250);
}
if (delay > TimeSpan.Zero)
{
await Task.Delay(delay, context.RequestAborted).ConfigureAwait(false);
}
JsonObject answer;
lock (World.Gate)
{
answer = Api.Search(text);
}
await JsonAsync(context, 200, answer).ConfigureAwait(false);
}
private async Task ServeCdnAsync(HttpContext context)
{
var path = context.Request.Path.Value ?? string.Empty;
if (Control.CdnTooManyRequests)
{
Control.OnCdnThrottled();
context.Response.StatusCode = 429;
context.Response.ContentType = "text/plain; charset=utf-8";
await context.Response.WriteAsync("Troppe richieste.").ConfigureAwait(false);
return;
}
var query = context.Request.Query;
var check = Signer.Check(path, query["scad"].ToString(), query["firma"].ToString(), _time.GetUtcNow());
if (check != CdnCheck.Valid)
{
if (check == CdnCheck.Expired)
{
Control.OnCdnExpired();
}
context.Response.StatusCode = 403;
context.Response.ContentType = "text/plain; charset=utf-8";
await context.Response.WriteAsync(check == CdnCheck.Expired ? "Indirizzo scaduto." : "Firma non valida.").ConfigureAwait(false);
return;
}
// /m/{key}/{w}x{h}.jpg, /m/{key}/{w}x{h}.mp4, /m/{key}/{w}x{h}-muto.mp4
var segments = path.Split('/', StringSplitOptions.RemoveEmptyEntries);
if (segments is not ["m", var key, var file] || !TryParseSize(file, out var width, out var height, out var extension, out var silent))
{
context.Response.StatusCode = 404;
return;
}
var bytes = extension == "mp4" ? Media.Video(key, width, height, !silent) : Media.Picture(key, width, height);
Control.OnCdnServed();
context.Response.ContentType = extension == "mp4" ? "video/mp4" : "image/jpeg";
context.Response.ContentLength = bytes.Length;
await context.Response.Body.WriteAsync(bytes).ConfigureAwait(false);
}
private async Task ControlAsync(HttpContext context, string command)
{
var q = context.Request.Query;
JsonObject answer = new() { ["ok"] = true };
lock (World.Gate)
{
switch (command)
{
case "stato":
answer["modo"] = Control.Mode.ToString();
answer["richieste"] = Control.DataRequests.Count;
answer["dirette"] = Control.DirectRequests.Count;
answer["accesso"] = Control.LoginPageVisits;
answer["verifica"] = Control.ChallengePageVisits;
break;
case "diretto":
var reply = q["valore"].ToString() switch
{
"troppe-richieste" => DirectReply.TooManyRequests,
"accesso" => DirectReply.RedirectToLogin,
"verifica" => DirectReply.RedirectToChallenge,
"html" => DirectReply.HtmlInsteadOfJson,
"senza-campi" => DirectReply.MissingRootField,
"rinnova-cookie" => DirectReply.RenewSessionCookie,
"cancella-cookie" => DirectReply.DeleteSessionCookie,
"claim" => DirectReply.SetClaim,
_ => DirectReply.Normal,
};
Control.ReplyToDirect(reply, always: q["sempre"].ToString() is "si" or "sì" or "true");
answer["risposta"] = reply.ToString();
break;
case "diretto/ritardo":
Control.DirectDelay = TimeSpan.FromMilliseconds(int.Parse(q["ms"].ToString(), CultureInfo.InvariantCulture));
break;
case "modo":
var mode = q["valore"].ToString() switch
{
"troppe-richieste" => StopMode.TooManyRequests,
"verifica" => StopMode.Challenge,
"sessione-scaduta" => StopMode.SessionEnded,
"vuoto" => StopMode.EmptyPages,
"formato-sconosciuto" => StopMode.UnknownFormat,
_ => StopMode.Normal,
};
Control.Set(mode, int.TryParse(q["dopo"], NumberStyles.Integer, CultureInfo.InvariantCulture, out var after) ? after : 0);
answer["modo"] = mode.ToString();
break;
case "reimposta":
Control.Reset();
break;
case "durata-storie":
Control.StoryDuration = TimeSpan.FromMilliseconds(int.Parse(q["ms"].ToString(), CultureInfo.InvariantCulture));
break;
case "ricerca/ritardo":
Control.SearchDelay = TimeSpan.FromMilliseconds(int.Parse(q["ms"].ToString(), CultureInfo.InvariantCulture));
break;
case "ricerca/disordine":
Control.SearchDisorder = q["valore"].ToString() is not ("no" or "false");
break;
case "ricerca/memoria":
Control.SearchMemory = q["valore"].ToString() is not ("no" or "false");
break;
case "ricerca/recenti":
answer["scritte"] = Control.RecentSearchWrites;
break;
case "cdn-troppe-richieste":
Control.CdnTooManyRequests = q["valore"].ToString() is "si" or "sì" or "true";
break;
case "scadenza-indirizzi":
Control.AddressLifetime = TimeSpan.FromSeconds(int.Parse(q["secondi"].ToString(), CultureInfo.InvariantCulture));
break;
case "rinomina":
var account = World.FindByUsername(q["da"].ToString());
if (account is null)
{
answer["ok"] = false;
}
else
{
account.Username = q["a"].ToString();
}
break;
case "ritratto":
if (World.FindByUsername(q["nome"].ToString()) is { } owner)
{
owner.PictureVersion++;
}
break;
case "pubblica":
if (World.FindByUsername(q["nome"].ToString()) is { } author)
{
var post = World.Publish(author, q["tipo"].ToString() is { Length: > 0 } t ? t : "foto", _time.GetUtcNow());
answer["sigla"] = post.Code;
answer["numero"] = post.Id;
}
break;
default:
answer["ok"] = false;
break;
}
}
await JsonAsync(context, answer["ok"]!.GetValue<bool>() ? 200 : 400, answer).ConfigureAwait(false);
}
private static async Task ResourceAsync(HttpContext context, string name)
{
if (name is not ("sito.js" or "sito.css"))
{
context.Response.StatusCode = 404;
return;
}
await using var stream = typeof(TestSite).Assembly.GetManifestResourceStream($"Febe.SitoDiProva.Risorse.{name}");
if (stream is null)
{
context.Response.StatusCode = 404;
return;
}
context.Response.ContentType = name.EndsWith(".js", StringComparison.Ordinal) ? "text/javascript; charset=utf-8" : "text/css; charset=utf-8";
await stream.CopyToAsync(context.Response.Body).ConfigureAwait(false);
}
/// <summary>
/// The session of the request ends on the site (pages and site client alike) and its cookie is deleted: a copy of
/// the same value held elsewhere stops working too.
/// </summary>
private void EndSession(HttpContext context)
{
if (context.Request.Cookies[SessionCookie] is { Length: > 0 } ended)
{
Control.EndSession(ended);
}
context.Response.Cookies.Delete(SessionCookie, new CookieOptions { Path = "/" });
}
private static Task HtmlAsync(HttpContext context, int status, string html)
{
context.Response.StatusCode = status;
context.Response.ContentType = "text/html; charset=utf-8";
return context.Response.WriteAsync(html);
}
private static Task JsonAsync(HttpContext context, int status, JsonObject body)
{
context.Response.StatusCode = status;
context.Response.ContentType = "application/json; charset=utf-8";
return context.Response.WriteAsync(body.ToJsonString(), Encoding.UTF8);
}
private static bool TryParseSize(string file, out int width, out int height, out string extension, out bool silent)
{
width = height = 0;
extension = string.Empty;
silent = false;
var dot = file.LastIndexOf('.');
if (dot < 0)
{
return false;
}
extension = file[(dot + 1)..];
var name = file[..dot];
if (name.EndsWith("-muto", StringComparison.Ordinal))
{
silent = true;
name = name[..^"-muto".Length];
}
var x = name.IndexOf('x', StringComparison.Ordinal);
return x > 0
&& int.TryParse(name.AsSpan(0, x), NumberStyles.Integer, CultureInfo.InvariantCulture, out width)
&& int.TryParse(name.AsSpan(x + 1), NumberStyles.Integer, CultureInfo.InvariantCulture, out height)
&& extension is "jpg" or "mp4";
}
private static bool CanBind(string address)
{
try
{
using var probe = new TcpListener(IPAddress.Parse(address), 0);
probe.Start();
probe.Stop();
return true;
}
catch (Exception ex) when (ex is SocketException or FormatException)
{
return false;
}
}
private static int FreePort(IPAddress address)
{
var probe = new TcpListener(address, 0);
probe.Start();
var port = ((IPEndPoint)probe.LocalEndpoint).Port;
probe.Stop();
return port;
}
}