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>
357 lines
16 KiB
C#
357 lines
16 KiB
C#
using System.Globalization;
|
|
using System.Text;
|
|
using System.Text.Json;
|
|
using System.Text.RegularExpressions;
|
|
using Febe.Core.Abstractions;
|
|
using Febe.Core.Collection;
|
|
|
|
namespace Febe.Sonda;
|
|
|
|
/// <summary>What a HAR conversion did: counts only, never a value.</summary>
|
|
/// <param name="Entries">Entries of the HAR.</param>
|
|
/// <param name="DataResponses">Site answers written because their body is data (<see cref="DataResponses.IsData"/>).</param>
|
|
/// <param name="Documents">Page documents that embed JSON: each of their blocks is written as a sample of its own.</param>
|
|
/// <param name="DocumentBlocks">Samples written from page documents: one per JSON block they embed, the way Febe's capture
|
|
/// hands the blocks to the readers.</param>
|
|
/// <param name="OtherHosts">Left out: not an answer of the site (CDN, other sites).</param>
|
|
/// <param name="NotData">Left out: files, images, scripts, styles, or a type or status that is not data.</param>
|
|
/// <param name="WithoutBody">Left out: the HAR does not hold the body.</param>
|
|
/// <param name="NotJson">Left out: a body that is not valid JSON (for example one that starts with <c>for (;;);</c>).</param>
|
|
/// <param name="DocumentsWithoutData">Left out: page documents that embed no JSON.</param>
|
|
public sealed record HarImportReport(int Entries, int DataResponses, int Documents, int DocumentBlocks, int OtherHosts, int NotData, int WithoutBody, int NotJson, int DocumentsWithoutData)
|
|
{
|
|
/// <summary>The file ends before its JSON does: <see cref="Entries"/> counts the complete entries only, the one the
|
|
/// file ends inside is left out (<see cref="HarFile"/>).</summary>
|
|
public bool Truncated { get; init; }
|
|
|
|
/// <summary>The file ends inside an entry, which is left out (not counted in <see cref="Entries"/>).</summary>
|
|
public bool DroppedEntry { get; init; }
|
|
|
|
public int Written => DataResponses + DocumentBlocks;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Converts a HAR exported from the browser's DevTools (Chrome, Edge) into the probe's RAW format (spec §14.5), so that
|
|
/// <c>ripulisci</c> and <c>verifica</c> work on it as on a recording of the probe: flat files <c>NNNNNN-<kind>.json</c>,
|
|
/// each <c>{"descrittore":{indirizzo, host, stato, tipo, risorsa, quando}, "corpo": <body>}</c>.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// It keeps what Febe's own capture keeps (<c>ResponseTap</c>), in the same pieces: site answers whose body is data, and
|
|
/// the JSON blocks embedded in page documents, one sample per block with the document's descriptor
|
|
/// (<see cref="DataResponses.EmbeddedJsonBlocks"/>). Everything else is left out. Headers, cookies, query strings and
|
|
/// request bodies are never copied: the address keeps scheme, host and path only, and of the request body only the
|
|
/// GraphQL operation name is read, to name the file, when it has the shape of a name in the site's code (never a path:
|
|
/// paths contain user names).
|
|
/// The output is still RAW (bodies hold other people's data): it must stay outside any repository.
|
|
/// </remarks>
|
|
public static partial class HarImporter
|
|
{
|
|
/// <summary>Request parameter that names the GraphQL operation of a POST (a fixed name in the site's code).</summary>
|
|
public const string OperationParameter = "fb_api_req_friendly_name";
|
|
|
|
private static readonly JsonDocumentOptions BodyOptions = new() { MaxDepth = 256 };
|
|
|
|
/// <summary>Converts <paramref name="harPath"/> into the new, empty folder <paramref name="rawFolder"/>.</summary>
|
|
/// <exception cref="InvalidOperationException">A folder is inside a git repository, or the output folder is not empty.</exception>
|
|
/// <exception cref="InvalidDataException">The file is not a HAR.</exception>
|
|
public static HarImportReport Import(string harPath, string rawFolder, HostClassifier? hosts = null)
|
|
{
|
|
ArgumentException.ThrowIfNullOrWhiteSpace(harPath);
|
|
ArgumentException.ThrowIfNullOrWhiteSpace(rawFolder);
|
|
hosts ??= HostClassifier.Instagram;
|
|
var har = Path.GetFullPath(harPath);
|
|
if (!File.Exists(har))
|
|
{
|
|
throw new FileNotFoundException($"Il file HAR non esiste: {har}", har);
|
|
}
|
|
|
|
// The HAR holds cookies and other people's data, and so does the output: neither belongs in a repository.
|
|
RepositoryGuard.EnsureOutside(Path.GetDirectoryName(har)!);
|
|
var folder = Path.GetFullPath(rawFolder);
|
|
RepositoryGuard.EnsureOutside(folder);
|
|
if (Directory.Exists(folder) && Directory.EnumerateFileSystemEntries(folder).Any())
|
|
{
|
|
throw new InvalidOperationException($"La cartella «{folder}» non è vuota: indica una cartella nuova, solo per questa conversione.");
|
|
}
|
|
|
|
using (var file = HarFile.Open(har, BodyOptions.MaxDepth))
|
|
{
|
|
var entries = file.Entries;
|
|
Directory.CreateDirectory(folder);
|
|
File.WriteAllText(
|
|
Path.Combine(folder, "LEGGIMI.txt"),
|
|
"Campioni GREZZI convertiti da un file HAR con «febe-sonda da-har»: contengono dati personali di Alberto e di altre persone.\n"
|
|
+ "Non vanno nel repository e non si inviano: si ripuliscono con «febe-sonda ripulisci», si controllano con «febe-sonda verifica»\n"
|
|
+ "e si cancellano, insieme al file HAR, quando lettori e mappa sono scritti (specifica §14.5).\n");
|
|
|
|
int count = 0, written = 0, data = 0, documents = 0, blocks = 0, otherHosts = 0, notData = 0, withoutBody = 0, notJson = 0, documentsWithoutData = 0;
|
|
foreach (var entry in entries.EnumerateArray())
|
|
{
|
|
count++;
|
|
var outcome = ConvertEntry(entry, hosts, out var sample);
|
|
if (sample is not null)
|
|
{
|
|
// One block at a time: each is written and disposed before the next one is parsed.
|
|
var bodies = 0;
|
|
foreach (var body in sample.Bodies)
|
|
{
|
|
using (body)
|
|
{
|
|
written++;
|
|
Write(Path.Combine(folder, $"{written.ToString("000000", CultureInfo.InvariantCulture)}-{sample.Kind}.json"), sample, body);
|
|
}
|
|
|
|
bodies++;
|
|
}
|
|
|
|
if (outcome == EntryOutcome.Document)
|
|
{
|
|
blocks += bodies;
|
|
outcome = bodies > 0 ? EntryOutcome.Document : EntryOutcome.DocumentWithoutData;
|
|
}
|
|
}
|
|
|
|
switch (outcome)
|
|
{
|
|
case EntryOutcome.Data:
|
|
data++;
|
|
break;
|
|
case EntryOutcome.Document:
|
|
documents++;
|
|
break;
|
|
case EntryOutcome.OtherHost:
|
|
otherHosts++;
|
|
break;
|
|
case EntryOutcome.WithoutBody:
|
|
withoutBody++;
|
|
break;
|
|
case EntryOutcome.NotJson:
|
|
notJson++;
|
|
break;
|
|
case EntryOutcome.DocumentWithoutData:
|
|
documentsWithoutData++;
|
|
break;
|
|
default:
|
|
notData++;
|
|
break;
|
|
}
|
|
}
|
|
|
|
return new HarImportReport(count, data, documents, blocks, otherHosts, notData, withoutBody, notJson, documentsWithoutData) { Truncated = file.Truncated, DroppedEntry = file.DroppedAnEntry };
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// The name of the GraphQL operation of a request, when it is one: a word of the site's code (letters and digits,
|
|
/// ending in Query, Mutation or Subscription, no run of three digits), the same for everyone. Otherwise null.
|
|
/// </summary>
|
|
public static string? OperationName(string? value)
|
|
{
|
|
var name = value?.Trim();
|
|
return name is not null && OperationShape().IsMatch(name) && !DigitRun().IsMatch(name) ? name : null;
|
|
}
|
|
|
|
private static EntryOutcome ConvertEntry(JsonElement entry, HostClassifier hosts, out RawSample? sample)
|
|
{
|
|
sample = null;
|
|
if (entry.ValueKind != JsonValueKind.Object
|
|
|| !entry.TryGetProperty("request", out var request) || request.ValueKind != JsonValueKind.Object
|
|
|| !entry.TryGetProperty("response", out var response) || response.ValueKind != JsonValueKind.Object)
|
|
{
|
|
return EntryOutcome.NotData;
|
|
}
|
|
|
|
// Chrome's resource types, written as the browser's protocol names them (what ResponseTap sees).
|
|
var resource = Text(entry, "_resourceType")?.ToLowerInvariant() switch
|
|
{
|
|
"xhr" => "XHR",
|
|
"fetch" => "Fetch",
|
|
"document" => "Document",
|
|
_ => null,
|
|
};
|
|
if (resource is null)
|
|
{
|
|
return EntryOutcome.NotData;
|
|
}
|
|
|
|
var url = Text(request, "url");
|
|
var host = hosts.Classify(url);
|
|
if (host != HostKind.Site)
|
|
{
|
|
return EntryOutcome.OtherHost;
|
|
}
|
|
|
|
var status = response.TryGetProperty("status", out var s) && s.TryGetInt32(out var code) ? code : 0;
|
|
var content = response.TryGetProperty("content", out var c) && c.ValueKind == JsonValueKind.Object ? c : default;
|
|
var mime = (content.ValueKind == JsonValueKind.Object ? Text(content, "mimeType") : null)?.Split(';')[0].Trim().ToLowerInvariant() ?? string.Empty;
|
|
var isData = DataResponses.IsData(mime, resource) && status is >= 200 and < 600 && status != 204;
|
|
var isDocument = !isData && resource == "Document" && status is >= 200 and < 300 && DataResponses.IsPageDocument(mime, isMainFrameDocument: true);
|
|
if (!isData && !isDocument)
|
|
{
|
|
return EntryOutcome.NotData;
|
|
}
|
|
|
|
var bytes = Body(content);
|
|
if (bytes is null)
|
|
{
|
|
return EntryOutcome.WithoutBody;
|
|
}
|
|
|
|
var address = UrlSanitizer.Sanitize(url).Url;
|
|
var at = When(Text(entry, "startedDateTime"));
|
|
if (isDocument)
|
|
{
|
|
// Only the JSON the page embeds, one block per sample, as Febe's capture hands it to the readers: parsed
|
|
// while the samples are written (a document without any becomes DocumentWithoutData there).
|
|
sample = new RawSample("documento", address, host, status, mime, resource, at, DataResponses.EmbeddedJsonBlocks(Encoding.UTF8.GetString(bytes)));
|
|
return EntryOutcome.Document;
|
|
}
|
|
|
|
JsonDocument body;
|
|
try
|
|
{
|
|
body = JsonDocument.Parse(bytes, BodyOptions);
|
|
}
|
|
catch (JsonException)
|
|
{
|
|
return EntryOutcome.NotJson;
|
|
}
|
|
|
|
var kind = resource == "Document" ? "documento" : OperationName(Operation(request)) ?? "risposta";
|
|
sample = new RawSample(kind, address, host, status, mime, resource, at, [body]);
|
|
return EntryOutcome.Data;
|
|
}
|
|
|
|
/// <summary>The value of <see cref="OperationParameter"/> in a form-encoded request body; nothing else is read.</summary>
|
|
private static string? Operation(JsonElement request)
|
|
{
|
|
if (!request.TryGetProperty("postData", out var post) || post.ValueKind != JsonValueKind.Object)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
if (post.TryGetProperty("params", out var parameters) && parameters.ValueKind == JsonValueKind.Array)
|
|
{
|
|
foreach (var parameter in parameters.EnumerateArray())
|
|
{
|
|
if (parameter.ValueKind == JsonValueKind.Object && Text(parameter, "name") == OperationParameter)
|
|
{
|
|
return Unescape(Text(parameter, "value"));
|
|
}
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
if ((Text(post, "mimeType") ?? string.Empty).Contains("x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase) && Text(post, "text") is { } text)
|
|
{
|
|
foreach (var pair in text.Split('&'))
|
|
{
|
|
var equals = pair.IndexOf('=', StringComparison.Ordinal);
|
|
if (equals > 0 && Unescape(pair[..equals]) == OperationParameter)
|
|
{
|
|
return Unescape(pair[(equals + 1)..]);
|
|
}
|
|
}
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
private static string? Unescape(string? value)
|
|
{
|
|
if (value is null)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
try
|
|
{
|
|
return Uri.UnescapeDataString(value.Replace('+', ' '));
|
|
}
|
|
catch (UriFormatException)
|
|
{
|
|
return null;
|
|
}
|
|
}
|
|
|
|
private static byte[]? Body(JsonElement content)
|
|
{
|
|
if (content.ValueKind != JsonValueKind.Object || Text(content, "text") is not { Length: > 0 } text)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
if (!string.Equals(Text(content, "encoding"), "base64", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
return Encoding.UTF8.GetBytes(text);
|
|
}
|
|
|
|
try
|
|
{
|
|
return Convert.FromBase64String(text);
|
|
}
|
|
catch (FormatException)
|
|
{
|
|
return null;
|
|
}
|
|
}
|
|
|
|
private static string? When(string? value) =>
|
|
DateTimeOffset.TryParse(value, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var at)
|
|
? at.UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture)
|
|
: null;
|
|
|
|
private static string? Text(JsonElement element, string property) =>
|
|
element.TryGetProperty(property, out var value) && value.ValueKind == JsonValueKind.String ? value.GetString() : null;
|
|
|
|
/// <summary>The same descriptor the probe writes (<see cref="ProbeRecorder"/>), then the body as it arrived.</summary>
|
|
private static void Write(string path, RawSample sample, JsonDocument body)
|
|
{
|
|
using var stream = new FileStream(path, FileMode.CreateNew, FileAccess.Write);
|
|
using var writer = new Utf8JsonWriter(stream, new JsonWriterOptions { MaxDepth = 300 });
|
|
writer.WriteStartObject();
|
|
writer.WriteStartObject("descrittore");
|
|
writer.WriteString("indirizzo", sample.Url);
|
|
writer.WriteString("host", sample.Host switch { HostKind.Site => "sito", HostKind.Cdn => "cdn", _ => "altro" });
|
|
writer.WriteNumber("stato", sample.Status);
|
|
writer.WriteString("tipo", sample.MimeType);
|
|
writer.WriteString("risorsa", sample.ResourceType);
|
|
if (sample.At is { } at)
|
|
{
|
|
writer.WriteString("quando", at);
|
|
}
|
|
else
|
|
{
|
|
writer.WriteNull("quando");
|
|
}
|
|
|
|
writer.WriteEndObject();
|
|
writer.WritePropertyName("corpo");
|
|
body.RootElement.WriteTo(writer);
|
|
writer.WriteEndObject();
|
|
}
|
|
|
|
// A GraphQL operation name: an identifier of the site's code (e.g. a «...PageQuery», or «...Query_connection» for
|
|
// the following page of a connection), never free text.
|
|
[GeneratedRegex("^[A-Za-z][A-Za-z0-9_]{1,96}(Query|Mutation|Subscription)(_[a-z]{1,32})?$", RegexOptions.CultureInvariant)]
|
|
private static partial Regex OperationShape();
|
|
|
|
[GeneratedRegex("[0-9]{3}", RegexOptions.CultureInvariant)]
|
|
private static partial Regex DigitRun();
|
|
|
|
private enum EntryOutcome
|
|
{
|
|
Data,
|
|
Document,
|
|
OtherHost,
|
|
NotData,
|
|
WithoutBody,
|
|
NotJson,
|
|
DocumentWithoutData,
|
|
}
|
|
|
|
/// <summary>What is written of one entry: its descriptor, and its body (a data answer) or the JSON blocks it embeds (a page document).</summary>
|
|
private sealed record RawSample(string Kind, string Url, HostKind Host, int Status, string MimeType, string ResourceType, string? At, IEnumerable<JsonDocument> Bodies);
|
|
}
|