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; /// What a HAR conversion did: counts only, never a value. /// Entries of the HAR. /// Site answers written because their body is data (). /// Page documents that embed JSON: each of their blocks is written as a sample of its own. /// Samples written from page documents: one per JSON block they embed, the way Febe's capture /// hands the blocks to the readers. /// Left out: not an answer of the site (CDN, other sites). /// Left out: files, images, scripts, styles, or a type or status that is not data. /// Left out: the HAR does not hold the body. /// Left out: a body that is not valid JSON (for example one that starts with for (;;);). /// Left out: page documents that embed no JSON. public sealed record HarImportReport(int Entries, int DataResponses, int Documents, int DocumentBlocks, int OtherHosts, int NotData, int WithoutBody, int NotJson, int DocumentsWithoutData) { /// The file ends before its JSON does: counts the complete entries only, the one the /// file ends inside is left out (). public bool Truncated { get; init; } /// The file ends inside an entry, which is left out (not counted in ). public bool DroppedEntry { get; init; } public int Written => DataResponses + DocumentBlocks; } /// /// Converts a HAR exported from the browser's DevTools (Chrome, Edge) into the probe's RAW format (spec §14.5), so that /// ripulisci and verifica work on it as on a recording of the probe: flat files NNNNNN-<kind>.json, /// each {"descrittore":{indirizzo, host, stato, tipo, risorsa, quando}, "corpo": <body>}. /// /// /// It keeps what Febe's own capture keeps (ResponseTap), 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 /// (). 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. /// public static partial class HarImporter { /// Request parameter that names the GraphQL operation of a POST (a fixed name in the site's code). public const string OperationParameter = "fb_api_req_friendly_name"; private static readonly JsonDocumentOptions BodyOptions = new() { MaxDepth = 256 }; /// Converts into the new, empty folder . /// A folder is inside a git repository, or the output folder is not empty. /// The file is not a HAR. 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 }; } } /// /// 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. /// 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; } /// The value of in a form-encoded request body; nothing else is read. 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; /// The same descriptor the probe writes (), then the body as it arrived. 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, } /// What is written of one entry: its descriptor, and its body (a data answer) or the JSON blocks it embeds (a page document). private sealed record RawSample(string Kind, string Url, HostKind Host, int Status, string MimeType, string ResourceType, string? At, IEnumerable Bodies); }