Chrome ha troncato due esportazioni del giro A quater (a 200 000 byte e a 57 MB, a meta di un corpo di risposta) e la sonda le rifiutava come file sbagliati. Ora da-har e richieste tengono le voci complete, scartano quella dentro cui il file finisce e lo dicono; un file rotto in qualunque altro modo resta rifiutato. Per richieste la voce scartata conta comunque come dati: si chiude dove si ferma e passa per le stesse regole di una voce intera, e ogni stringa JSON del testo interrotto conta come valore, cosi un nome che e un dato solo li non arriva nel file delle forme. In A quater: come esportare senza che il file si tronchi. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
266 lines
11 KiB
C#
266 lines
11 KiB
C#
using System.Globalization;
|
|
using Febe.Browser.Diagnostics;
|
|
using Febe.Browser.Hosting;
|
|
using Febe.Core.Abstractions;
|
|
using Febe.Core.Collection;
|
|
using Febe.Sonda;
|
|
|
|
// Passive probe of M0 (spec §14.5).
|
|
// febe-sonda registra --cartella <fuori dal repository> [--display :0 | --xvfb] [--porta 9333] [--chromium <file>] [--no-sandbox]
|
|
// [--sito <host> --cdn <host>] (solo per provarla sul sito di prova)
|
|
// febe-sonda ripulisci --da <grezzi> --a <ripuliti> [--ammessi <ripulitura.json>] [--sito <host> --cdn <host>]
|
|
// febe-sonda verifica --grezzi <grezzi> --ripuliti <ripuliti> [--ammessi <ripulitura.json>]
|
|
// febe-sonda da-har --har <file .har> --a <cartella nuova fuori dal repository> [--sito <host> --cdn <host>]
|
|
// febe-sonda richieste --har <file .har> --a <file .json nuovo fuori dal repository> [--sito <host> --cdn <host>]
|
|
return args.Length == 0 ? Usage() : args[0] switch
|
|
{
|
|
"registra" => await RecordAsync(args[1..]),
|
|
"da-har" => FromHar(args[1..]),
|
|
"richieste" => RequestsFromHar(args[1..]),
|
|
"ripulisci" => Sanitize(args[1..]),
|
|
"verifica" => Verify(args[1..]),
|
|
_ => Usage(),
|
|
};
|
|
|
|
static int Usage()
|
|
{
|
|
Console.Error.WriteLine("""
|
|
Uso:
|
|
febe-sonda registra --cartella <cartella fuori dal repository> [--display :0 | --xvfb] [--porta 9333] [--chromium <file>] [--no-sandbox]
|
|
febe-sonda ripulisci --da <campioni grezzi> --a <campioni ripuliti> [--ammessi <ripulitura.json>]
|
|
febe-sonda verifica --grezzi <campioni grezzi> --ripuliti <campioni ripuliti> [--ammessi <ripulitura.json>]
|
|
febe-sonda da-har --har <file .har esportato dal browser> --a <cartella nuova fuori dal repository>
|
|
febe-sonda richieste --har <file .har esportato dal browser> --a <file .json nuovo fuori dal repository>
|
|
La sonda è passiva: apre il browser e registra ciò che la pagina riceve mentre navighi tu. Non compie gesti.
|
|
«da-har» converte nello stesso formato grezzo un file HAR esportato dagli strumenti per sviluppatori del browser:
|
|
tiene le sole risposte di dati del sito e i dati incorporati nelle pagine; mai intestazioni, cookie, parametri
|
|
degli indirizzi o corpi delle richieste. Poi si usano «ripulisci» e «verifica» come per la sonda.
|
|
«richieste» descrive dallo stesso file la forma delle richieste che la pagina fa al sito: percorso, nomi dei
|
|
parametri, delle intestazioni e dei campi del corpo; dei valori solo quelli uguali per tutti. Nessun cookie,
|
|
nessun nome utente, nessun identificativo. Leggi il file prima di inviarlo.
|
|
""");
|
|
return 2;
|
|
}
|
|
|
|
static async Task<int> RecordAsync(string[] args)
|
|
{
|
|
var folder = Option(args, "--cartella");
|
|
if (string.IsNullOrWhiteSpace(folder))
|
|
{
|
|
Console.Error.WriteLine("Indicare --cartella <cartella fuori dal repository>.");
|
|
return 2;
|
|
}
|
|
|
|
try
|
|
{
|
|
RepositoryGuard.EnsureOutside(folder);
|
|
}
|
|
catch (InvalidOperationException ex)
|
|
{
|
|
Console.Error.WriteLine(ex.Message);
|
|
return 3;
|
|
}
|
|
|
|
var log = new DelegateBrowserLog((level, message, _) =>
|
|
{
|
|
if (level >= BrowserLogLevel.Warning)
|
|
{
|
|
Console.Error.WriteLine(message);
|
|
}
|
|
});
|
|
XvfbProcess? xvfb = null;
|
|
var display = Option(args, "--display");
|
|
if (args.Contains("--xvfb"))
|
|
{
|
|
display = XvfbProcess.FindFreeDisplay() ?? throw new InvalidOperationException("Nessun display libero per Xvfb.");
|
|
xvfb = new XvfbProcess(display, 1280, 900, log: log);
|
|
await xvfb.StartAsync(CancellationToken.None);
|
|
Console.WriteLine($"Xvfb avviato su {display}: il browser non è visibile da qui (serve la vista remota di Febe o un display vero con --display).");
|
|
}
|
|
|
|
var hosts = Hosts(args);
|
|
var profile = Path.Combine(Path.GetFullPath(folder), SampleSanitizer.BrowserProfileFolder);
|
|
var host = new ChromiumProcessHost(new ChromiumLaunchOptions { NoSandbox = args.Contains("--no-sandbox") }, log: log);
|
|
try
|
|
{
|
|
await host.StartAsync(
|
|
new BrowserOptions(profile, 1280, 900, int.TryParse(Option(args, "--porta"), NumberStyles.Integer, CultureInfo.InvariantCulture, out var port) ? port : 9333, Option(args, "--chromium"), display),
|
|
CancellationToken.None);
|
|
await using var recorder = new ProbeRecorder(host.Cdp, hosts, folder);
|
|
await recorder.StartAsync();
|
|
Console.WriteLine($"""
|
|
Sonda in ascolto. Campioni grezzi in: {recorder.Folder}
|
|
Accedi e naviga a mano nella finestra del browser seguendo docs/prove-dal-vivo.md.
|
|
La sonda non compie gesti e non apre pagine da sola. Premi Invio (o Ctrl+C) per terminare.
|
|
""");
|
|
var stop = new TaskCompletionSource();
|
|
Console.CancelKeyPress += (_, e) =>
|
|
{
|
|
e.Cancel = true;
|
|
stop.TrySetResult();
|
|
};
|
|
_ = Task.Run(() =>
|
|
{
|
|
Console.ReadLine();
|
|
stop.TrySetResult();
|
|
});
|
|
await stop.Task;
|
|
await recorder.StopAsync();
|
|
var stats = recorder.Stats;
|
|
Console.WriteLine($"Registrate {stats.Responses} risposte, {stats.Navigations} navigazioni, {stats.Interactions} interazioni.");
|
|
Console.WriteLine("Ora: febe-sonda ripulisci --da <cartella> --a <copia ripulita>, poi febe-sonda verifica.");
|
|
return 0;
|
|
}
|
|
finally
|
|
{
|
|
await host.DisposeAsync();
|
|
if (xvfb is not null)
|
|
{
|
|
await xvfb.DisposeAsync();
|
|
}
|
|
}
|
|
}
|
|
|
|
static int FromHar(string[] args)
|
|
{
|
|
var har = Option(args, "--har");
|
|
var to = Option(args, "--a");
|
|
if (string.IsNullOrWhiteSpace(har) || string.IsNullOrWhiteSpace(to))
|
|
{
|
|
Console.Error.WriteLine("Indicare --har <file .har> e --a <cartella nuova fuori dal repository>.");
|
|
return 2;
|
|
}
|
|
|
|
HarImportReport report;
|
|
try
|
|
{
|
|
report = HarImporter.Import(har, to, Hosts(args));
|
|
}
|
|
catch (Exception ex) when (ex is InvalidOperationException or InvalidDataException or FileNotFoundException)
|
|
{
|
|
Console.Error.WriteLine(ex.Message);
|
|
return 3;
|
|
}
|
|
|
|
// Counts only: what the answers contain stays on this machine.
|
|
Truncation(report.Truncated, report.DroppedEntry);
|
|
Console.WriteLine($"Lette {report.Entries} voci del file HAR; scritti {report.Written} campioni grezzi: {report.DataResponses} risposte di dati del sito, {report.DocumentBlocks} blocchi di dati incorporati in {report.Documents} pagine.");
|
|
Console.WriteLine($"Lasciate fuori: {report.OtherHosts} di altri indirizzi (CDN, altri siti), {report.NotData} che non sono dati (file, immagini, script...), {report.WithoutBody} senza corpo, {report.NotJson} non JSON, {report.DocumentsWithoutData} pagine senza dati incorporati.");
|
|
if (report.Written == 0 && report.WithoutBody > 0)
|
|
{
|
|
Console.WriteLine("Il file HAR non contiene i corpi delle risposte: esportalo di nuovo dal pannello Rete con le risposte incluse.");
|
|
}
|
|
|
|
Console.WriteLine($"Campioni grezzi in: {Path.GetFullPath(to)}");
|
|
Console.WriteLine("Ora: febe-sonda ripulisci --da <cartella> --a <copia ripulita>, poi febe-sonda verifica.");
|
|
return report.Written > 0 ? 0 : 1;
|
|
}
|
|
|
|
static void Truncation(bool truncated, bool droppedEntry)
|
|
{
|
|
if (!truncated)
|
|
{
|
|
return;
|
|
}
|
|
|
|
if (droppedEntry)
|
|
{
|
|
Console.WriteLine("Il file HAR è troncato: finisce a metà di una voce, che è stata scartata; le voci complete prima di lei sono tenute.");
|
|
Console.WriteLine("Ciò che la pagina ha ricevuto dopo non c'è. Se manca qualcosa che serve, esporta di nuovo un giro più corto.");
|
|
}
|
|
else
|
|
{
|
|
Console.WriteLine("Il file HAR è troncato, ma fuori dalle voci: sono tutte intere e tutte tenute.");
|
|
}
|
|
}
|
|
|
|
static int RequestsFromHar(string[] args)
|
|
{
|
|
var har = Option(args, "--har");
|
|
var to = Option(args, "--a");
|
|
if (string.IsNullOrWhiteSpace(har) || string.IsNullOrWhiteSpace(to))
|
|
{
|
|
Console.Error.WriteLine("Indicare --har <file .har> e --a <file .json nuovo fuori dal repository>.");
|
|
return 2;
|
|
}
|
|
|
|
RequestShapesReport report;
|
|
try
|
|
{
|
|
report = RequestShapes.Extract(har, to, Hosts(args));
|
|
}
|
|
catch (Exception ex) when (ex is InvalidOperationException or InvalidDataException or IOException or UnauthorizedAccessException)
|
|
{
|
|
Console.Error.WriteLine(ex.Message);
|
|
return 3;
|
|
}
|
|
|
|
Truncation(report.Truncated, report.DroppedEntry);
|
|
Console.WriteLine($"Lette {report.Entries} voci del file HAR; descritte {report.SiteRequests} richieste della pagina al sito in {report.Shapes} forme distinte.");
|
|
Console.WriteLine($"Nomi tolti perché potevano essere dati: {report.RemovedNames}.");
|
|
Console.WriteLine($"Forme delle richieste in: {Path.GetFullPath(to)}");
|
|
Console.WriteLine("Leggilo prima di inviarlo: deve contenere solo nomi e forme, nessun tuo dato.");
|
|
return report.Shapes > 0 ? 0 : 1;
|
|
}
|
|
|
|
static int Sanitize(string[] args)
|
|
{
|
|
var from = Option(args, "--da");
|
|
var to = Option(args, "--a");
|
|
if (string.IsNullOrWhiteSpace(from) || string.IsNullOrWhiteSpace(to))
|
|
{
|
|
Console.Error.WriteLine("Indicare --da <campioni grezzi> e --a <campioni ripuliti>.");
|
|
return 2;
|
|
}
|
|
|
|
var allowlist = Option(args, "--ammessi") is { } path ? SanitizerAllowlist.Load(path) : SanitizerAllowlist.Default;
|
|
var report = new SampleSanitizer(allowlist, Hosts(args)).SanitizeFolder(from, to);
|
|
Console.WriteLine($"Ripuliti {report.Files} file ({report.Lines} righe): {report.ReplacedStrings} testi, {report.ReplacedNumbers} numeri, {report.ReplacedKeys} chiavi, {report.Addresses} indirizzi sostituiti.");
|
|
var verify = SampleVerifier.Verify(from, to, allowlist);
|
|
Console.WriteLine(verify.Passed ? "Verifica superata." : $"Verifica NON superata: {verify.Leaks.Count} frammenti sopravvissuti.");
|
|
return verify.Passed ? 0 : 1;
|
|
}
|
|
|
|
static int Verify(string[] args)
|
|
{
|
|
var raw = Option(args, "--grezzi");
|
|
var clean = Option(args, "--ripuliti");
|
|
if (string.IsNullOrWhiteSpace(raw) || string.IsNullOrWhiteSpace(clean))
|
|
{
|
|
Console.Error.WriteLine("Indicare --grezzi <campioni grezzi> e --ripuliti <campioni ripuliti>.");
|
|
return 2;
|
|
}
|
|
|
|
var allowlist = Option(args, "--ammessi") is { } path ? SanitizerAllowlist.Load(path) : SanitizerAllowlist.Default;
|
|
var report = SampleVerifier.Verify(raw, clean, allowlist);
|
|
Console.WriteLine($"Grezzi: {report.RawFiles} file; ripuliti: {report.CleanFiles}; frammenti controllati: {report.CheckedTokens}.");
|
|
foreach (var missing in report.MissingCleanFiles)
|
|
{
|
|
Console.WriteLine($"Manca la copia ripulita di {missing}.");
|
|
}
|
|
|
|
foreach (var leak in report.Leaks)
|
|
{
|
|
// Where, never what: the value itself stays on this machine.
|
|
Console.WriteLine($"Sopravvive un frammento di {leak.Length} {leak.Kind} in {leak.CleanFile}, sotto «{leak.Key}».");
|
|
}
|
|
|
|
Console.WriteLine(report.Passed ? "Verifica superata: nessun valore dei grezzi sopravvive fuori dall'elenco ammesso." : "Verifica NON superata.");
|
|
return report.Passed ? 0 : 1;
|
|
}
|
|
|
|
static HostClassifier Hosts(string[] args)
|
|
{
|
|
var site = Option(args, "--sito");
|
|
var cdn = Option(args, "--cdn");
|
|
return site is null && cdn is null
|
|
? HostClassifier.Instagram
|
|
: new HostClassifier((site ?? string.Empty).Split(',', StringSplitOptions.RemoveEmptyEntries), (cdn ?? string.Empty).Split(',', StringSplitOptions.RemoveEmptyEntries));
|
|
}
|
|
|
|
static string? Option(string[] args, string name)
|
|
{
|
|
var index = Array.IndexOf(args, name);
|
|
return index >= 0 && index + 1 < args.Length ? args[index + 1] : null;
|
|
}
|