febe-sonda legge un HAR troncato senza perdere la parte buona

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>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-13 00:19:24 +01:00
1 parent 8d2f85693c
commit 78aa32bdb2
8 files changed
+831 -41

No files matched your search

+1
View File
@@ -318,3 +318,4 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15).
| 2026-11-12 | `febe-sonda richieste --har <file> --a <file .json>`: descrive la forma delle richieste XHR/Fetch della pagina al sito (metodo, percorso con `{numero}`/`{testo}` al posto delle parti che non sono parole note del sito, nomi di parametri, intestazioni e campi del corpo, struttura delle variabili, nella query come nel corpo); dei valori solo il tipo, tranne elenchi chiusi uguali per tutti (`x-ig-app-id`, `x-asbd-id`, nomi e `doc_id`/`query_hash` delle operazioni, grandezza delle pagine solo per i nomi che la indicano, vero/falso). Un nome si tiene se è in un elenco chiuso, o se ha la forma di un nome del codice (senza punto, senza tre cifre di fila) e non compare da nessuna parte nel HAR come valore (indirizzi, cookie, intestazioni, corpi delle richieste e delle risposte, dati incorporati nelle pagine); altrimenti «(nome tolto)». Un corpo che non è un modulo né JSON si descrive intero, mai spezzato su «&» e «=». Le forme si distinguono per metodo, percorso, operazione (nome, intestazione `x-fb-friendly-name` o `x-root-field-name`) e identificativo dell'interrogazione, e le occorrenze si uniscono chiave per chiave. `OperationName` accetta anche il suffisso della pagina successiva (`…Query_connection`). Rifiuta HAR e file d'uscita dentro un repository, una cartella e un file d'uscita che esiste già | `da-har` butta via di proposito intestazioni, parametri e corpi delle richieste; per scrivere `richieste.instagram.json` serve la loro forma, e deve poter uscire dalla macchina di Alberto senza ripulitura: per costruzione non contiene valori personali | | 2026-11-12 | `febe-sonda richieste --har <file> --a <file .json>`: descrive la forma delle richieste XHR/Fetch della pagina al sito (metodo, percorso con `{numero}`/`{testo}` al posto delle parti che non sono parole note del sito, nomi di parametri, intestazioni e campi del corpo, struttura delle variabili, nella query come nel corpo); dei valori solo il tipo, tranne elenchi chiusi uguali per tutti (`x-ig-app-id`, `x-asbd-id`, nomi e `doc_id`/`query_hash` delle operazioni, grandezza delle pagine solo per i nomi che la indicano, vero/falso). Un nome si tiene se è in un elenco chiuso, o se ha la forma di un nome del codice (senza punto, senza tre cifre di fila) e non compare da nessuna parte nel HAR come valore (indirizzi, cookie, intestazioni, corpi delle richieste e delle risposte, dati incorporati nelle pagine); altrimenti «(nome tolto)». Un corpo che non è un modulo né JSON si descrive intero, mai spezzato su «&» e «=». Le forme si distinguono per metodo, percorso, operazione (nome, intestazione `x-fb-friendly-name` o `x-root-field-name`) e identificativo dell'interrogazione, e le occorrenze si uniscono chiave per chiave. `OperationName` accetta anche il suffisso della pagina successiva (`…Query_connection`). Rifiuta HAR e file d'uscita dentro un repository, una cartella e un file d'uscita che esiste già | `da-har` butta via di proposito intestazioni, parametri e corpi delle richieste; per scrivere `richieste.instagram.json` serve la loro forma, e deve poter uscire dalla macchina di Alberto senza ripulitura: per costruzione non contiene valori personali |
| 2026-11-12 | Ripulitura e verifica sul HAR vero: (1) un numero lungo con esponente o virgola (`1.2e+21`) si falsifica cifra per cifra, lasciando segno, punto ed esponente, così resta un numero JSON valido; (2) la verifica non cerca dentro i valori che l'elenco ammesso tiene di proposito (un tipo di file, una data, una dimensione), mai però nelle chiavi di dati, che la ripulitura falsifica sempre, e indica sotto quale chiave sopravvive un frammento, mai il frammento; (3) le parole degli indirizzi finti (`sito`, `altro`, `esempio`) e le estensioni dei file non contano come frammenti. Campioni del secondo HAR accorciati sulla copia **ripulita** e già verificata, non sui grezzi | Sul HAR del 12/11 `ripulisci` si fermava su un numero con esponente e `verifica` dava 223 falsi allarmi (frammenti come «script» dentro `text/javascript`). Accorciare la copia ripulita evita di aprire i grezzi anche solo per tagliarli: togliere elementi da una copia verificata non può aggiungere valori dei grezzi | | 2026-11-12 | Ripulitura e verifica sul HAR vero: (1) un numero lungo con esponente o virgola (`1.2e+21`) si falsifica cifra per cifra, lasciando segno, punto ed esponente, così resta un numero JSON valido; (2) la verifica non cerca dentro i valori che l'elenco ammesso tiene di proposito (un tipo di file, una data, una dimensione), mai però nelle chiavi di dati, che la ripulitura falsifica sempre, e indica sotto quale chiave sopravvive un frammento, mai il frammento; (3) le parole degli indirizzi finti (`sito`, `altro`, `esempio`) e le estensioni dei file non contano come frammenti. Campioni del secondo HAR accorciati sulla copia **ripulita** e già verificata, non sui grezzi | Sul HAR del 12/11 `ripulisci` si fermava su un numero con esponente e `verifica` dava 223 falsi allarmi (frammenti come «script» dentro `text/javascript`). Accorciare la copia ripulita evita di aprire i grezzi anche solo per tagliarli: togliere elementi da una copia verificata non può aggiungere valori dei grezzi |
| 2026-11-12 | Vocabolario dei lettori di Instagram: `profile.postCount` = `media_count` e una chiave nuova `highlight.cover` (`cover_media.cropped_image_version`), letta come una versione. Le griglie delle schede Reel e Con tag restano anteprime, non contenuti | Dal secondo HAR: `media_count` compare solo nella scheda del profilo; la copertina delle raccolte è nell'elenco delle raccolte del profilo; le anteprime delle schede non hanno `taken_at` né `video_versions` (regola 9: si legge solo ciò che i campioni mostrano) | | 2026-11-12 | Vocabolario dei lettori di Instagram: `profile.postCount` = `media_count` e una chiave nuova `highlight.cover` (`cover_media.cropped_image_version`), letta come una versione. Le griglie delle schede Reel e Con tag restano anteprime, non contenuti | Dal secondo HAR: `media_count` compare solo nella scheda del profilo; la copertina delle raccolte è nell'elenco delle raccolte del profilo; le anteprime delle schede non hanno `taken_at` né `video_versions` (regola 9: si legge solo ciò che i campioni mostrano) |
| 2026-11-13 | `febe-sonda da-har` e `richieste` leggono anche un HAR **troncato**: se il file finisce prima del suo JSON, e solo in quel caso, tengono le voci complete di `log.entries`, scartano quella dentro cui il file finisce e lo dicono a schermo e nel resoconto (`Truncated`, `DroppedEntry`). Per riconoscere il caso il lettore JSON lavora in modalità «dati non finiti»: la fine del file non è un errore, un errore di sintassi sì, e un file rotto in qualunque altro modo resta rifiutato. Per `richieste` la voce scartata conta comunque come dati: si chiude dove si ferma (il testo interrotto tenuto fino al taglio) e passa per le stesse regole di una voce intera (base64, pagine con blocchi incorporati, intestazioni, moduli); in più ogni stringa JSON del testo interrotto conta come valore, così un nome che è un dato solo lì viene tolto lo stesso. Resta fuori solo un valore tagliato a metà, di cui c'è solo l'inizio. Lettura comune in `HarFile` | Il 12/11 sera Chrome ha troncato due esportazioni dello stesso giro: la prima a 200 000 byte esatti, la seconda a 57 MB a metà di un corpo di risposta. Prima la sonda diceva solo «non è un file HAR valido (riga …)», senza distinguere un file tagliato da uno sbagliato, e non dava nulla della parte buona. La revisione avversaria ha trovato che la prima versione non contava i valori del testo interrotto né applicava alla voce scartata le regole di base64 e pagine: corretto prima del commit |
+15
View File
@@ -300,6 +300,21 @@ stessa preparazione (A ter 1 e A ter 2) e la stessa procedura alla fine (A ter 4
Niente storie questa volta: guardarle le segna come viste. Niente storie questa volta: guardarle le segna come viste.
**Perché il HAR non si tronchi.** Il primo tentativo (12 novembre, sera) è arrivato troncato due volte: la prima
esportazione a 200 000 byte esatti, la seconda a 57 MB, quando Chrome ha smesso di scrivere a metà di una risposta,
dopo 141 voci. La parte completa arrivava solo alla pagina iniziale. Quasi tutto il peso sono i corpi di immagini e video che il pannello Rete tiene
insieme alle risposte di dati. Per restare leggeri:
- apri Instagram e aspetta che la pagina iniziale sia caricata, poi **svuota il pannello Rete** (il cerchio barrato
in alto a sinistra) e solo allora comincia il giro: così nel file c'è solo il giro;
- non aprire post, reel o video e non lasciare che la pagina iniziale li faccia partire: per i seguiti e per la
griglia di un profilo bastano le miniature;
- esporta appena hai finito, e aspetta che il file sia scritto del tutto prima di rinominarlo.
Se il file è troncato lo stesso, `febe-sonda` lo dice («Il file HAR è troncato») e legge comunque le voci complete,
scartando quella dentro cui il file finisce. Conta che cosa è arrivato con `febe-sonda richieste`: se mancano i seguiti o la seconda
pagina dei post, rifai il giro più corto (per esempio i seguiti in un file e lo scorrimento in un altro).
--- ---
## B. Prima sessione dal vivo, dopo M3 ## B. Prima sessione dal vivo, dopo M3
+16
View File
@@ -7,6 +7,22 @@ fra le sessioni; ciò che è da fare si legge nelle issue aperte.
## In breve ## In breve
**13 novembre 2026, notte: il HAR dello scorrimento è troncato** (#35).
- Alberto ha esportato il giro corto della parte A quater (seguiti e seconda pagina dei post). Il file è arrivato
troncato due volte: la prima a 200 000 byte esatti, la seconda a 57 MB, a metà del corpo di una risposta.
- `febe-sonda` ora legge un HAR troncato: tiene le voci complete, scarta quella dentro cui il file finisce e lo dice;
un file rotto altrove resta rifiutato. Per `richieste` i valori della voce scartata contano lo stesso, testo
interrotto compreso, così nessun nome che è un dato passa per via del taglio (`HarFile`, 16 casi in
`HarFileTests`, riga in `docs/decisioni.md`). Revisione avversaria (21 agenti): 6 rilievi confermati, tutti
corretti. Il principale: la prima versione non contava i valori del testo interrotto, né applicava alla voce
scartata le regole di base64 e delle pagine.
- Del giro sono arrivate 141 voci, e la parte completa si ferma alla pagina iniziale. Dopo la ripulitura restano 6
campioni: pagina successiva del feed, griglia di Esplora, promozioni e configurazione della pagina. «Verifica
superata». Nessuno è fra i pezzi che servono: **seguiti e seconda pagina dei post mancano ancora.** In
`docs/prove-dal-vivo.md` (A quater) ora c'è come esportare senza che il file si tronchi: svuotare il pannello Rete
dopo il caricamento della pagina iniziale, niente video, esportare subito.
**12 novembre 2026, sera: il secondo HAR** (#35). **12 novembre 2026, sera: il secondo HAR** (#35).
- Alberto ha mandato un HAR senza filtro, un giro veloce su Instagram. Sulla sua macchina, fuori dal repository: - Alberto ha mandato un HAR senza filtro, un giro veloce su Instagram. Sulla sua macchina, fuori dal repository:
+298
View File
@@ -0,0 +1,298 @@
using System.Text;
using System.Text.Json.Nodes;
using Febe.Sonda;
using Febe.Tests.Support;
namespace Febe.Tests.Collection;
/// <summary>
/// A HAR export that the browser cut short. On 12 November 2026 Chrome stopped writing the same round twice: once at
/// exactly 200 000 bytes, once at 57 MB in the middle of a response body. The probe keeps the complete entries, leaves
/// out the one the file ends inside and says so; a file broken in any other way is still refused. For <c>richieste</c>
/// the left-out entry still counts as data, so that a name that is someone's value only there is removed all the same.
/// The HAR is synthetic, written by the test with invented values.
/// </summary>
[TestClass]
public sealed class HarFileTests
{
/// <summary>Where the synthetic HAR is cut: inside the body of its last entry.</summary>
private const string CutMark = "CORPO-INTERROTTO";
/// <summary>A key of the first request's variables that is someone's name: a value only in the last entry.</summary>
private const string Person = "carla_verdi";
[TestMethod]
public void AWholeFileIsReadAsItIsEvenWithAByteOrderMark()
{
using var temp = new TempFolder("har");
var har = temp.Combine("intero.har");
File.WriteAllText(har, Har().ToJsonString(), new UTF8Encoding(encoderShouldEmitUTF8Identifier: true));
using var file = HarFile.Open(har, 256);
Assert.IsFalse(file.Truncated);
Assert.IsFalse(file.DroppedAnEntry);
Assert.AreEqual(3, file.Entries.GetArrayLength());
Assert.IsNull(file.ReadDroppedEntry());
}
[TestMethod]
public void AFileCutInsideAnEntryKeepsTheEntriesBeforeIt()
{
using var temp = new TempFolder("har");
using var file = HarFile.Open(Write(temp, "tagliato.har", CutInsideTheLastBody(Har())), 256);
Assert.IsTrue(file.Truncated);
Assert.IsTrue(file.DroppedAnEntry);
Assert.AreEqual(2, file.Entries.GetArrayLength());
Assert.AreEqual("https://www.instagram.com/api/v1/prima/", file.Entries[0].GetProperty("request").GetProperty("url").GetString());
Assert.AreEqual("https://www.instagram.com/api/v1/seconda/", file.Entries[1].GetProperty("request").GetProperty("url").GetString());
// The left-out entry, closed where it stops: the cut body is kept up to the cut.
using var dropped = file.ReadDroppedEntry()!;
var entry = dropped.Document.RootElement[0];
Assert.AreEqual("https://www.instagram.com/api/v1/terza/", entry.GetProperty("request").GetProperty("url").GetString());
var body = entry.GetProperty("response").GetProperty("content").GetProperty("text").GetString()!;
Assert.StartsWith("{\"utente\":{\"username\":\"" + Person + "\"}", body);
Assert.AreEqual(body, dropped.CutText);
}
[TestMethod]
public void AFileCutBetweenEntriesOrAfterThemKeepsThemAll()
{
using var temp = new TempFolder("har");
var text = Har().ToJsonString();
// Right after the comma that follows the second entry.
var third = text.IndexOf("https://www.instagram.com/api/v1/terza/", StringComparison.Ordinal);
var between = text.LastIndexOf("},{", third, StringComparison.Ordinal) + 2;
using (var file = HarFile.Open(Write(temp, "fra.har", text[..between]), 256))
{
Assert.IsTrue(file.Truncated);
Assert.IsFalse(file.DroppedAnEntry);
Assert.AreEqual(2, file.Entries.GetArrayLength());
Assert.IsNull(file.ReadDroppedEntry());
}
// After the array of entries, before the closing braces and the rest of «log».
var whole = Har();
whole["log"]!["pages"] = new JsonArray(new JsonObject { ["id"] = "pagina" });
var withPages = whole.ToJsonString();
var afterEntries = withPages.IndexOf(",\"pages\"", StringComparison.Ordinal) + 3;
using (var file = HarFile.Open(Write(temp, "dopo.har", withPages[..afterEntries]), 256))
{
Assert.IsTrue(file.Truncated);
Assert.IsFalse(file.DroppedAnEntry);
Assert.AreEqual(3, file.Entries.GetArrayLength());
}
}
[TestMethod]
public void AFileBrokenAnywhereElseIsStillRefused()
{
using var temp = new TempFolder("har");
var text = Har().ToJsonString();
var cut = CutInsideTheLastBody(Har());
// A syntax error in the second entry only, the first one whole, and the file also cut later.
var second = cut.IndexOf("/api/v1/seconda/", StringComparison.Ordinal);
var status = cut.IndexOf("\"status\":200,", second, StringComparison.Ordinal);
var broken = cut[..status] + "\"status\":200;" + cut[(status + "\"status\":200,".Length)..];
StringAssert.Contains(Assert.ThrowsExactly<InvalidDataException>(() => HarFile.Open(Write(temp, "sbagliato.har", broken), 256)).Message, "non è un file HAR valido");
// An entry that is not an object, after a whole one.
Assert.ThrowsExactly<InvalidDataException>(() => HarFile.Open(Write(temp, "numeri.har", """{"log":{"entries":[{"a":1},2,{"b":"""), 256));
// Cut before the first entry is complete: nothing to keep.
var first = text[..(text.IndexOf("/api/v1/prima/", StringComparison.Ordinal) + 5)];
Assert.ThrowsExactly<InvalidDataException>(() => HarFile.Open(Write(temp, "presto.har", first), 256));
// Something after a whole file.
Assert.ThrowsExactly<InvalidDataException>(() => HarFile.Open(Write(temp, "coda.har", text + "{}"), 256));
// Not a HAR: entries that are not under «log».
Assert.ThrowsExactly<InvalidDataException>(() => HarFile.Open(Write(temp, "altro.har", """{"altro":{"entries":[{"a":1},{"b":"""), 256));
}
[TestMethod]
public void TextThatIsNotValidUnicodeInTheDroppedEntryDoesNotStopTheReading()
{
using var temp = new TempFolder("har");
var head = Encoding.UTF8.GetBytes("""{"log":{"entries":[{"request":{"url":"https://www.instagram.com/api/v1/prima/"}},{"request":{"url":"x""");
byte[] badUtf8 = [0xC3, 0x28];
var tail = Encoding.UTF8.GetBytes("""y","headers":[{"name":"a","value":"\ud800"}]},"response":{"content":{"text":"CORPO""");
var har = temp.Combine("unicode.har");
File.WriteAllBytes(har, [.. head, .. badUtf8, .. tail]);
using (var file = HarFile.Open(har, 256))
{
Assert.IsTrue(file.DroppedAnEntry);
Assert.AreEqual(1, file.Entries.GetArrayLength());
using var dropped = file.ReadDroppedEntry()!;
Assert.AreEqual("CORPO", dropped.CutText);
}
Assert.AreEqual(1, HarImporter.Import(har, temp.Combine("grezzi")).Entries);
Assert.IsTrue(RequestShapes.Extract(har, temp.Combine("richieste.json")).DroppedEntry);
}
[TestMethod]
[DataRow("abc", "abc")]
[DataRow("abc\\", "abc")]
[DataRow("abc\\u00", "abc")]
[DataRow("abc\\u00e8", "abcè")]
[DataRow("a\\\\", "a\\")]
[DataRow("a\\n", "a\n")]
public void AStringCutShortKeepsWhatWasWhole(string raw, string expected) =>
Assert.AreEqual(expected, HarFile.PartialString(Encoding.UTF8.GetBytes(raw)));
[TestMethod]
public void AStringCutInsideACharacterKeepsTheCharactersBeforeIt()
{
var bytes = Encoding.UTF8.GetBytes("perché");
Assert.AreEqual("perch", HarFile.PartialString(bytes.AsSpan(0, bytes.Length - 1)));
}
[TestMethod]
public void TheConversionOfACutFileWritesTheCompleteAnswersAndSaysItIsTruncated()
{
using var temp = new TempFolder("har");
var har = Write(temp, "tagliato.har", CutInsideTheLastBody(Har()));
var report = HarImporter.Import(har, temp.Combine("grezzi"));
Assert.IsTrue(report.Truncated);
Assert.IsTrue(report.DroppedEntry);
Assert.AreEqual(2, report.Entries);
Assert.AreEqual(2, report.DataResponses);
Assert.AreEqual(2, Directory.GetFiles(temp.Combine("grezzi"), "*.json").Length);
var whole = Write(temp, "intero.har", Har().ToJsonString());
Assert.IsFalse(HarImporter.Import(whole, temp.Combine("grezzi-interi")).Truncated);
}
[TestMethod]
public void ANameThatIsAValueOnlyInsideTheCutBodyIsStillRemoved()
{
using var temp = new TempFolder("richieste");
var report = RequestShapes.Extract(Write(temp, "tagliato.har", CutInsideTheLastBody(Har())), temp.Combine("tagliato.json"));
Assert.IsTrue(report.Truncated);
Assert.IsTrue(report.DroppedEntry);
Assert.AreEqual(2, report.Entries);
var output = File.ReadAllText(temp.Combine("tagliato.json"));
Assert.IsFalse(output.Contains(Person, StringComparison.Ordinal), output);
// Control: without the third entry at all, the same key is a name like any other and stays.
var two = Har();
two["log"]!["entries"]!.AsArray().RemoveAt(2);
Assert.IsFalse(RequestShapes.Extract(Write(temp, "corto.har", two.ToJsonString()), temp.Combine("corto.json")).Truncated);
StringAssert.Contains(File.ReadAllText(temp.Combine("corto.json")), Person);
}
[TestMethod]
public void ANameInsideTheCutPartOfAnEmbeddedBlockIsStillRemoved()
{
using var temp = new TempFolder("richieste");
// A page cut inside the JSON block it embeds: the block never closes, so only its literals still name it.
var page = Har(body: "<html><script type=\"application/json\">{\"utente\":{\"username\":\"" + Person + "\",\"testo\":\"" + CutMark + new string('x', 200) + "\"}}</script></html>", mime: "text/html");
RequestShapes.Extract(Write(temp, "pagina.har", CutInsideTheLastBody(page)), temp.Combine("pagina.json"));
Assert.IsFalse(File.ReadAllText(temp.Combine("pagina.json")).Contains(Person, StringComparison.Ordinal));
}
[TestMethod]
public void TheDroppedEntryCountsWithTheSameRulesAsAWholeOne()
{
using var temp = new TempFolder("richieste");
// A body in base64 and a page with an embedded block, both whole, in an entry cut later (in its timings).
var base64 = Convert.ToBase64String(Encoding.UTF8.GetBytes("{\"utente\":{\"username\":\"" + Person + "\"}}"));
var page = "<html><script type=\"application/json\">{\"utente\":{\"username\":\"" + Person + "\"}}</script></html>";
foreach (var (name, har) in new[] { ("base64", Har(body: base64, encoding: "base64")), ("pagina", Har(body: page, mime: "text/html")) })
{
var entries = har["log"]!["entries"]!.AsArray();
entries[2]!["timings"] = new JsonObject { ["wait"] = CutMark + new string('x', 200) };
var text = har.ToJsonString();
var cut = text[..(text.LastIndexOf(CutMark, StringComparison.Ordinal) + 6)];
var output = temp.Combine(name + ".json");
Assert.IsTrue(RequestShapes.Extract(Write(temp, name + ".har", cut), output).DroppedEntry, name);
Assert.IsFalse(File.ReadAllText(output).Contains(Person, StringComparison.Ordinal), name);
}
// A base64 body cut in the middle: its first whole groups still decode.
var long64 = Convert.ToBase64String(Encoding.UTF8.GetBytes("{\"utente\":{\"username\":\"" + Person + "\",\"testo\":\"" + new string('x', 300) + "\"}}"));
var cut64 = Har(body: long64, encoding: "base64").ToJsonString();
cut64 = cut64[..(cut64.IndexOf(long64, StringComparison.Ordinal) + 120)];
RequestShapes.Extract(Write(temp, "base64-tagliato.har", cut64), temp.Combine("base64-tagliato.json"));
Assert.IsFalse(File.ReadAllText(temp.Combine("base64-tagliato.json")).Contains(Person, StringComparison.Ordinal));
}
private static string Write(TempFolder temp, string name, string text)
{
var path = temp.Combine(name);
File.WriteAllText(path, text);
return path;
}
/// <summary>The HAR as text, cut a few characters after the mark in the body of its last entry.</summary>
private static string CutInsideTheLastBody(JsonObject har)
{
var text = har.ToJsonString();
return text[..(text.LastIndexOf(CutMark, StringComparison.Ordinal) + 6)];
}
/// <summary>
/// Three answers of the site. The first is a GraphQL POST whose variables are keyed by <see cref="Person"/>; that text
/// is a value only in the body of the third entry, which a cut file ends inside.
/// </summary>
private static JsonObject Har(string? body = null, string mime = "application/json", string? encoding = null)
{
static JsonObject Entry(string method, string url, string body, string mime = "application/json", string? encoding = null, JsonObject? postData = null)
{
var request = new JsonObject
{
["method"] = method,
["url"] = url,
["headers"] = new JsonArray(new JsonObject { ["name"] = "Referer", ["value"] = "https://www.instagram.com/" }),
};
if (postData is not null)
{
request["postData"] = postData;
}
var content = new JsonObject { ["mimeType"] = mime, ["text"] = body };
if (encoding is not null)
{
content["encoding"] = encoding;
}
return new JsonObject
{
["_resourceType"] = "xhr",
["startedDateTime"] = "2026-11-12T23:40:00.000+01:00",
["request"] = request,
["response"] = new JsonObject
{
["status"] = 200,
["headers"] = new JsonArray(),
["content"] = content,
},
};
}
body ??= "{\"utente\":{\"username\":\"" + Person + "\"},\"testo\":\"" + CutMark + new string('x', 200) + "\"}";
return new JsonObject
{
["log"] = new JsonObject
{
["version"] = "1.2",
["entries"] = new JsonArray(
Entry("POST", "https://www.instagram.com/api/v1/prima/", """{"elementi":[{"nome":"mario"}]}""",
postData: new JsonObject
{
["mimeType"] = "application/x-www-form-urlencoded",
["text"] = "doc_id=1000000000001&variables=" + Uri.EscapeDataString("{\"seen\":{\"" + Person + "\":1}}"),
}),
Entry("GET", "https://www.instagram.com/api/v1/seconda/", """{"elementi":[{"nome":"lucia"}]}"""),
Entry("GET", "https://www.instagram.com/api/v1/terza/", body, mime, encoding)),
},
};
}
}
+388
View File
@@ -0,0 +1,388 @@
using System.Buffers;
using System.Text;
using System.Text.Json;
namespace Febe.Sonda;
/// <summary>
/// A HAR exported from the browser's DevTools, read whole into one <see cref="JsonDocument"/>, with its
/// <c>log.entries</c>. An export cut short (Chrome may stop writing a large HAR in the middle of a response body) is
/// still read: the entries that are complete are kept, the one the file ends inside is left out of
/// <see cref="Entries"/>, and <see cref="Truncated"/> says so. A file broken in any other way is refused, as before.
/// </summary>
internal sealed class HarFile : IDisposable
{
private static readonly byte[] Utf8Bom = [0xEF, 0xBB, 0xBF];
private static readonly byte[] Prefix = Encoding.UTF8.GetBytes("{\"log\":{\"entries\":[");
private static readonly byte[] Suffix = Encoding.UTF8.GetBytes("]}}");
private readonly ReadOnlyMemory<byte> _dropped;
private readonly int _maxDepth;
private HarFile(JsonDocument document, JsonElement entries, bool truncated, ReadOnlyMemory<byte> dropped, int maxDepth)
{
Document = document;
Entries = entries;
Truncated = truncated;
_dropped = dropped;
_maxDepth = maxDepth;
}
public JsonDocument Document { get; }
/// <summary>The array <c>log.entries</c>: in a cut file, its complete entries only.</summary>
public JsonElement Entries { get; }
/// <summary>The file ends before its JSON does.</summary>
public bool Truncated { get; }
/// <summary>The file ends inside an entry, which is not in <see cref="Entries"/> (false if it ends between entries or after them).</summary>
public bool DroppedAnEntry => !_dropped.IsEmpty;
/// <exception cref="InvalidDataException">The file is not JSON, or not a HAR, or is broken other than by being cut short.</exception>
public static HarFile Open(string path, int maxDepth)
{
ReadOnlyMemory<byte> json = File.ReadAllBytes(path);
if (json.Span.StartsWith(Utf8Bom))
{
json = json[Utf8Bom.Length..];
}
var name = Path.GetFileName(path);
JsonDocument document;
var truncated = false;
var dropped = ReadOnlyMemory<byte>.Empty;
try
{
document = JsonDocument.Parse(json, new JsonDocumentOptions { MaxDepth = maxDepth });
}
catch (JsonException ex)
{
if (Recover(json, maxDepth) is not { } recovered)
{
throw new InvalidDataException($"{name}: non è un file HAR valido (riga {ex.LineNumber + 1}).", ex);
}
(document, dropped) = recovered;
truncated = true;
}
if (document.RootElement.ValueKind != JsonValueKind.Object
|| !document.RootElement.TryGetProperty("log", out var log) || log.ValueKind != JsonValueKind.Object
|| !log.TryGetProperty("entries", out var entries) || entries.ValueKind != JsonValueKind.Array)
{
document.Dispose();
throw new InvalidDataException($"{name}: non è un file HAR (manca «log.entries»).");
}
return new HarFile(document, entries, truncated, dropped, maxDepth);
}
/// <summary>
/// The entry the file ends inside, closed where it stops (<see cref="CloseCut"/>), so that <c>richieste</c> can
/// collect its values with the same rules as a whole entry; null if no entry was cut. Never written anywhere.
/// </summary>
public DroppedEntry? ReadDroppedEntry() => _dropped.IsEmpty ? null : CloseCut(_dropped.Span, _maxDepth);
public void Dispose() => Document.Dispose();
/// <summary>
/// The complete entries of a HAR whose file ends early, as a new document <c>{"log":{"entries":[…]}}</c>, and the
/// bytes of the entry the file ends inside (empty if it ends between entries or after them); null when the file is
/// broken in any other way (a syntax error, a shape that is not a HAR, no complete entry).
/// </summary>
/// <remarks>
/// The reader is told the data is NOT final: where the file simply stops, <see cref="Utf8JsonReader.Read"/> and
/// <see cref="Utf8JsonReader.TrySkip"/> return false instead of throwing, while a real syntax error still throws.
/// </remarks>
internal static (JsonDocument Document, ReadOnlyMemory<byte> Dropped)? Recover(ReadOnlyMemory<byte> json, int maxDepth)
{
var options = new JsonReaderOptions { MaxDepth = maxDepth };
var ranges = new List<(int Start, int End)>();
var droppedFrom = -1;
try
{
var reader = new Utf8JsonReader(json.Span, isFinalBlock: false, new JsonReaderState(options));
if (!reader.Read() || reader.TokenType != JsonTokenType.StartObject
|| !MoveToProperty(ref reader, "log") || !reader.Read() || reader.TokenType != JsonTokenType.StartObject
|| !MoveToProperty(ref reader, "entries") || !reader.Read() || reader.TokenType != JsonTokenType.StartArray)
{
return null;
}
while (true)
{
if (!reader.Read())
{
break; // the file ends between two entries
}
if (reader.TokenType == JsonTokenType.EndArray)
{
// Every entry is whole: the file must end later, after the array, and not because of a syntax error.
while (reader.Read())
{
}
break;
}
if (reader.TokenType != JsonTokenType.StartObject)
{
return null;
}
var start = (int)reader.TokenStartIndex;
if (!reader.TrySkip())
{
droppedFrom = start; // the file ends inside this entry
break;
}
ranges.Add((start, (int)reader.BytesConsumed));
}
}
catch (JsonException)
{
return null;
}
if (ranges.Count == 0)
{
return null;
}
var length = Prefix.Length + Suffix.Length + ranges.Sum(r => r.End - r.Start + 1);
var buffer = new byte[length];
var at = 0;
Prefix.CopyTo(buffer, at);
at += Prefix.Length;
for (var i = 0; i < ranges.Count; i++)
{
if (i > 0)
{
buffer[at++] = (byte)',';
}
var (start, end) = ranges[i];
json.Span[start..end].CopyTo(buffer.AsSpan(at));
at += end - start;
}
Suffix.CopyTo(buffer, at);
at += Suffix.Length;
var document = JsonDocument.Parse(buffer.AsMemory(0, at), new JsonDocumentOptions { MaxDepth = maxDepth });
return (document, droppedFrom < 0 ? ReadOnlyMemory<byte>.Empty : json[droppedFrom..]);
}
/// <summary>
/// Closes a JSON object that stops early: every token read whole is kept; a string value the data ends inside is
/// kept up to the cut (it is <see cref="DroppedEntry.CutText"/> too, usually the response body Chrome stopped
/// writing); a name left without its value gets null; then the open objects and arrays are closed.
/// </summary>
internal static DroppedEntry CloseCut(ReadOnlySpan<byte> json, int maxDepth)
{
var buffer = new ArrayBufferWriter<byte>();
var open = new Stack<JsonTokenType>();
var pendingName = false;
string? cut = null;
using (var writer = new Utf8JsonWriter(buffer, new JsonWriterOptions { MaxDepth = maxDepth + 1 }))
{
writer.WriteStartArray();
var reader = new Utf8JsonReader(json, isFinalBlock: false, new JsonReaderState(new JsonReaderOptions { MaxDepth = maxDepth }));
while (reader.Read())
{
switch (reader.TokenType)
{
case JsonTokenType.StartObject:
writer.WriteStartObject();
open.Push(JsonTokenType.StartObject);
pendingName = false;
break;
case JsonTokenType.StartArray:
writer.WriteStartArray();
open.Push(JsonTokenType.StartArray);
pendingName = false;
break;
case JsonTokenType.EndObject:
writer.WriteEndObject();
open.Pop();
break;
case JsonTokenType.EndArray:
writer.WriteEndArray();
open.Pop();
break;
case JsonTokenType.PropertyName:
writer.WritePropertyName(Text(ref reader));
pendingName = true;
break;
case JsonTokenType.String:
writer.WriteStringValue(Text(ref reader));
pendingName = false;
break;
case JsonTokenType.Number:
writer.WriteRawValue(reader.ValueSpan, skipInputValidation: true);
pendingName = false;
break;
case JsonTokenType.True:
case JsonTokenType.False:
writer.WriteBooleanValue(reader.TokenType == JsonTokenType.True);
pendingName = false;
break;
default:
writer.WriteNullValue();
pendingName = false;
break;
}
if (open.Count == 0)
{
break;
}
}
// What the reader could not finish: separators, then perhaps the start of a string.
var rest = json[(int)reader.BytesConsumed..];
var skip = 0;
while (skip < rest.Length && rest[skip] is (byte)' ' or (byte)'\t' or (byte)'\r' or (byte)'\n' or (byte)',' or (byte)':')
{
skip++;
}
rest = rest[skip..];
var valueExpected = pendingName || (open.Count > 0 && open.Peek() == JsonTokenType.StartArray);
if (valueExpected && rest.Length > 0 && rest[0] == (byte)'"')
{
cut = PartialString(rest[1..]);
writer.WriteStringValue(cut);
pendingName = false;
}
if (pendingName)
{
writer.WriteNullValue();
}
while (open.Count > 0)
{
if (open.Pop() == JsonTokenType.StartObject)
{
writer.WriteEndObject();
}
else
{
writer.WriteEndArray();
}
}
writer.WriteEndArray();
}
return new DroppedEntry(JsonDocument.Parse(buffer.WrittenMemory, new JsonDocumentOptions { MaxDepth = maxDepth + 1 }), cut);
}
/// <summary>
/// Moves the reader to the value of the property <paramref name="name"/> of the object it is in, skipping the others;
/// false if the object ends, or the file does, first.
/// </summary>
private static bool MoveToProperty(ref Utf8JsonReader reader, string name)
{
while (reader.Read())
{
if (reader.TokenType != JsonTokenType.PropertyName)
{
return false;
}
if (reader.ValueTextEquals(name))
{
return true;
}
if (!reader.Read() || !reader.TrySkip())
{
return false;
}
}
return false;
}
/// <summary>A string token as text; one that is not valid UTF-8 or UTF-16 is decoded leniently, never refused.</summary>
private static string Text(ref Utf8JsonReader reader)
{
try
{
return reader.GetString() ?? string.Empty;
}
catch (InvalidOperationException)
{
return Encoding.UTF8.GetString(reader.HasValueSequence ? reader.ValueSequence.ToArray() : reader.ValueSpan);
}
}
/// <summary>
/// The text of a JSON string whose closing quote never came: the bytes after the opening quote, without an escape
/// or a UTF-8 character the cut left half written, unescaped; decoded leniently if it still does not read.
/// </summary>
internal static string PartialString(ReadOnlySpan<byte> raw)
{
// A closing quote inside the rest would mean the reader stopped for another reason: keep only up to it.
var end = 0;
while (end < raw.Length && raw[end] != (byte)'"')
{
end += raw[end] == (byte)'\\' ? 2 : 1;
}
var text = raw[..Math.Min(end, raw.Length)];
// An escape cut in two: a lone backslash, or «\u» with fewer than four hexadecimal digits.
var backslash = text.LastIndexOf((byte)'\\');
if (backslash >= 0 && text.Length - backslash < 6)
{
var run = 0;
while (backslash - run >= 0 && text[backslash - run] == (byte)'\\')
{
run++;
}
var escape = text[backslash..];
var whole = run % 2 == 0 || (escape.Length >= 2 && escape[1] != (byte)'u') || escape.Length == 6;
if (!whole)
{
text = text[..backslash];
}
}
for (var trim = 0; trim <= 3 && trim <= text.Length; trim++)
{
var candidate = new byte[text.Length - trim + 2];
candidate[0] = (byte)'"';
text[..^trim].CopyTo(candidate.AsSpan(1));
candidate[^1] = (byte)'"';
try
{
var reader = new Utf8JsonReader(candidate);
if (reader.Read() && reader.TokenType == JsonTokenType.String)
{
return reader.GetString() ?? string.Empty;
}
}
catch (Exception ex) when (ex is JsonException or InvalidOperationException)
{
// A UTF-8 character cut in two, or bytes that are not UTF-8: one byte less, then lenient decoding.
}
}
return Encoding.UTF8.GetString(text);
}
}
/// <summary>The entry a cut HAR ends inside, closed where it stops, as a one-element array; and the text cut short.</summary>
internal sealed record DroppedEntry(JsonDocument Document, string? CutText) : IDisposable
{
public void Dispose() => Document.Dispose();
}
+10 -20
View File
@@ -20,6 +20,13 @@ namespace Febe.Sonda;
/// <param name="DocumentsWithoutData">Left out: page documents that embed no JSON.</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) 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; public int Written => DataResponses + DocumentBlocks;
} }
@@ -67,26 +74,9 @@ public static partial class HarImporter
throw new InvalidOperationException($"La cartella «{folder}» non è vuota: indica una cartella nuova, solo per questa conversione."); throw new InvalidOperationException($"La cartella «{folder}» non è vuota: indica una cartella nuova, solo per questa conversione.");
} }
JsonDocument document; using (var file = HarFile.Open(har, BodyOptions.MaxDepth))
try
{ {
using var stream = File.OpenRead(har); var entries = file.Entries;
document = JsonDocument.Parse(stream);
}
catch (JsonException ex)
{
throw new InvalidDataException($"{Path.GetFileName(har)}: non è un file HAR valido (riga {ex.LineNumber + 1}).", ex);
}
using (document)
{
if (document.RootElement.ValueKind != JsonValueKind.Object
|| !document.RootElement.TryGetProperty("log", out var log) || log.ValueKind != JsonValueKind.Object
|| !log.TryGetProperty("entries", out var entries) || entries.ValueKind != JsonValueKind.Array)
{
throw new InvalidDataException($"{Path.GetFileName(har)}: non è un file HAR (manca «log.entries»).");
}
Directory.CreateDirectory(folder); Directory.CreateDirectory(folder);
File.WriteAllText( File.WriteAllText(
Path.Combine(folder, "LEGGIMI.txt"), Path.Combine(folder, "LEGGIMI.txt"),
@@ -147,7 +137,7 @@ public static partial class HarImporter
} }
} }
return new HarImportReport(count, data, documents, blocks, otherHosts, notData, withoutBody, notJson, documentsWithoutData); return new HarImportReport(count, data, documents, blocks, otherHosts, notData, withoutBody, notJson, documentsWithoutData) { Truncated = file.Truncated, DroppedEntry = file.DroppedAnEntry };
} }
} }
+20
View File
@@ -143,6 +143,7 @@ static int FromHar(string[] args)
} }
// Counts only: what the answers contain stays on this machine. // 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($"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."); 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) if (report.Written == 0 && report.WithoutBody > 0)
@@ -155,6 +156,24 @@ static int FromHar(string[] args)
return report.Written > 0 ? 0 : 1; 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) static int RequestsFromHar(string[] args)
{ {
var har = Option(args, "--har"); var har = Option(args, "--har");
@@ -176,6 +195,7 @@ static int RequestsFromHar(string[] args)
return 3; 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($"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($"Nomi tolti perché potevano essere dati: {report.RemovedNames}.");
Console.WriteLine($"Forme delle richieste in: {Path.GetFullPath(to)}"); Console.WriteLine($"Forme delle richieste in: {Path.GetFullPath(to)}");
+83 -21
View File
@@ -12,7 +12,14 @@ namespace Febe.Sonda;
/// <param name="SiteRequests">Requests the page made to the site (XHR, Fetch) that were described.</param> /// <param name="SiteRequests">Requests the page made to the site (XHR, Fetch) that were described.</param>
/// <param name="Shapes">Distinct shapes written: same method, path pattern, operation and query identifier.</param> /// <param name="Shapes">Distinct shapes written: same method, path pattern, operation and query identifier.</param>
/// <param name="RemovedNames">Names (parameters, fields, keys) replaced because they could be data.</param> /// <param name="RemovedNames">Names (parameters, fields, keys) replaced because they could be data.</param>
public sealed record RequestShapesReport(int Entries, int SiteRequests, int Shapes, int RemovedNames); public sealed record RequestShapesReport(int Entries, int SiteRequests, int Shapes, int RemovedNames)
{
/// <summary>The file ends before its JSON does: only its complete entries are described (<see cref="HarFile"/>).</summary>
public bool Truncated { get; init; }
/// <summary>The file ends inside an entry, which is not described (its values still count as data).</summary>
public bool DroppedEntry { get; init; }
}
/// <summary> /// <summary>
/// Describes the SHAPE of the requests Instagram's own page makes to the site (decision of 12 November 2026, issue #34: /// Describes the SHAPE of the requests Instagram's own page makes to the site (decision of 12 November 2026, issue #34:
@@ -126,31 +133,29 @@ public static partial class RequestShapes
throw new InvalidOperationException($"Il file «{output}» esiste già: indica un file nuovo."); throw new InvalidOperationException($"Il file «{output}» esiste già: indica un file nuovo.");
} }
JsonDocument document;
try
{
using var stream = File.OpenRead(har);
document = JsonDocument.Parse(stream, DeepDocuments);
}
catch (JsonException ex)
{
throw new InvalidDataException($"{Path.GetFileName(har)}: non è un file HAR valido (riga {ex.LineNumber + 1}).", ex);
}
var shapes = new Dictionary<string, Shape>(StringComparer.Ordinal); var shapes = new Dictionary<string, Shape>(StringComparer.Ordinal);
int count = 0, described = 0; int count = 0, described = 0;
Names names; Names names;
using (document) bool truncated, droppedEntry;
using (var file = HarFile.Open(har, DeepDocuments.MaxDepth))
{ {
if (document.RootElement.ValueKind != JsonValueKind.Object var entries = file.Entries;
|| !document.RootElement.TryGetProperty("log", out var log) || log.ValueKind != JsonValueKind.Object truncated = file.Truncated;
|| !log.TryGetProperty("entries", out var entries) || entries.ValueKind != JsonValueKind.Array)
// First pass: every value the HAR holds, wherever it is, the entry a cut file ends inside included. A name
// equal to one of them is never written.
var values = ValueCollector.Collect(entries);
droppedEntry = file.DroppedAnEntry;
if (file.ReadDroppedEntry() is { } dropped)
{ {
throw new InvalidDataException($"{Path.GetFileName(har)}: non è un file HAR (manca «log.entries»)."); using (dropped)
{
values.UnionWith(ValueCollector.Collect(dropped.Document.RootElement));
ValueCollector.AddCutText(values, dropped.CutText);
}
} }
// First pass: every value the HAR holds, wherever it is. A name equal to one of them is never written. names = new Names(values);
names = new Names(ValueCollector.Collect(entries));
foreach (var entry in entries.EnumerateArray()) foreach (var entry in entries.EnumerateArray())
{ {
count++; count++;
@@ -191,7 +196,7 @@ public static partial class RequestShapes
writer.Write('\n'); writer.Write('\n');
} }
return new RequestShapesReport(count, described, shapes.Count, names.Removed); return new RequestShapesReport(count, described, shapes.Count, names.Removed) { Truncated = truncated, DroppedEntry = droppedEntry };
} }
/// <summary>The path with each segment that is not a known word replaced by <c>{numero}</c> or <c>{testo}</c>.</summary> /// <summary>The path with each segment that is not a known word replaced by <c>{numero}</c> or <c>{testo}</c>.</summary>
@@ -705,7 +710,7 @@ public static partial class RequestShapes
/// Every value a HAR holds (addresses, cookies, header values, form values, strings of JSON requests and responses, /// Every value a HAR holds (addresses, cookies, header values, form values, strings of JSON requests and responses,
/// data embedded in pages), to tell a name of the site's code from a piece of data used as a name. /// data embedded in pages), to tell a name of the site's code from a piece of data used as a name.
/// </summary> /// </summary>
internal static class ValueCollector internal static partial class ValueCollector
{ {
private const int MaxBodyChars = 64 * 1024 * 1024; private const int MaxBodyChars = 64 * 1024 * 1024;
@@ -780,6 +785,63 @@ internal static class ValueCollector
return values; return values;
} }
/// <summary>
/// The text a cut HAR ends inside (usually a response body, possibly base64 or a page): besides what
/// <see cref="Collect"/> already took from the closed entry, every JSON string literal in it counts as a value, keys
/// included, so that names inside a body or an embedded block cut in two are found too. More values only remove
/// more names.
/// </summary>
public static void AddCutText(HashSet<string> values, string? text, bool decoded = false)
{
if (string.IsNullOrEmpty(text))
{
return;
}
Body(values, text);
foreach (Match literal in StringLiteral().Matches(text))
{
string? value;
try
{
value = JsonSerializer.Deserialize<string>(literal.Value);
}
catch (JsonException)
{
value = literal.Groups[1].Value;
}
Add(values, value);
if (value is not null)
{
Address(values, value);
}
}
// A base64 body cut anywhere: its first whole groups of four characters still decode.
if (!decoded && text.Length >= 8 && Base64Text().IsMatch(text))
{
var length = text.Length / 4 * 4;
try
{
var bytes = Convert.FromBase64String(text[..length]);
AddCutText(values, Encoding.UTF8.GetString(bytes), decoded: true);
}
catch (FormatException)
{
// Not base64 after all.
}
}
}
[GeneratedRegex("""
"((?:[^"\\\r\n]|\\.){1,512})"
""", RegexOptions.CultureInvariant)]
private static partial Regex StringLiteral();
[GeneratedRegex("^[A-Za-z0-9+/]+=*$", RegexOptions.CultureInvariant)]
private static partial Regex Base64Text();
private static void Add(HashSet<string> values, string? value) private static void Add(HashSet<string> values, string? value)
{ {
var text = value?.Trim(); var text = value?.Trim();