Secondo HAR: campioni, lettori e richieste della pagina di Instagram (#45)
verifica / controlli (push) Successful in 12s
verifica / prove (push) Successful in 11m27s
verifica / installatore (push) Successful in 3m39s
verifica / immagine (push) Successful in 13m10s

This commit was merged in pull request #45.
This commit is contained in:
Alby96 committed 2026-11-13 10:24:06 +01:00
commit 305791f57b
28 files changed
+6834 -70

No files matched your search

+3
View File
@@ -316,3 +316,6 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15).
| 2026-11-12 | Le attività di Febe stanno nelle issue di Gitea, come negli altri repository di Alberto: etichette Area/Kind/Priority/Status, un traguardo per tappa (M0–M8) e per versione, il lavoro finito come issue chiusa con il suo resoconto «Fatto». `docs/stato.md` resta il resoconto fra le sessioni e rimanda alle issue per ciò che è da fare. Motivo: richiesta di Alberto del 12/11; un posto solo per le cose da fare, visibile anche fuori dal repository. | | 2026-11-12 | Le attività di Febe stanno nelle issue di Gitea, come negli altri repository di Alberto: etichette Area/Kind/Priority/Status, un traguardo per tappa (M0–M8) e per versione, il lavoro finito come issue chiusa con il suo resoconto «Fatto». `docs/stato.md` resta il resoconto fra le sessioni e rimanda alle issue per ciò che è da fare. Motivo: richiesta di Alberto del 12/11; un posto solo per le cose da fare, visibile anche fuori dal repository. |
| 2026-11-12 | **Strada B: la pagina chiede i dati** (issue #34). Dalla pagina di Instagram già aperta Febe chiede al sito gli stessi dati che chiede la sua applicazione web, con `Runtime.evaluate` + `fetch`, solo verso gli indirizzi di `richieste.<sito>.json` scritti da campioni reali, in sola lettura, una richiesta per volta col permesso del Governatore; i gettoni restano nella pagina e allo script torna solo il corpo. Cambiano §2 regola 2 (eccezione), §6.1 (nuova riga dei comandi e regole delle richieste), §14.5 e la regola 4 di `CLAUDE.md`; il resto di §2 non cambia | La prova dal vivo di Alberto è fallita: le ricette passive dipendono da una mappa dei bersagli e da indirizzi che si scoprono solo su Instagram, e nessuno dei 9 bersagli era compilato. Scelta di Alberto fra A (indirizzi e tastiera), B e C (misto), sapendo che B lascia una traccia diversa da una visita normale | | 2026-11-12 | **Strada B: la pagina chiede i dati** (issue #34). Dalla pagina di Instagram già aperta Febe chiede al sito gli stessi dati che chiede la sua applicazione web, con `Runtime.evaluate` + `fetch`, solo verso gli indirizzi di `richieste.<sito>.json` scritti da campioni reali, in sola lettura, una richiesta per volta col permesso del Governatore; i gettoni restano nella pagina e allo script torna solo il corpo. Cambiano §2 regola 2 (eccezione), §6.1 (nuova riga dei comandi e regole delle richieste), §14.5 e la regola 4 di `CLAUDE.md`; il resto di §2 non cambia | La prova dal vivo di Alberto è fallita: le ricette passive dipendono da una mappa dei bersagli e da indirizzi che si scoprono solo su Instagram, e nessuno dei 9 bersagli era compilato. Scelta di Alberto fra A (indirizzi e tastiera), B e C (misto), sapendo che B lascia una traccia diversa da una visita normale |
| 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 | 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 |
+3 -1
View File
@@ -94,7 +94,9 @@ Docker del server, lo stesso che costruisce Encelado, Mimante e gli altri proget
La verifica gira a ogni push su qualunque ramo e a mano (Actions ▸ verifica ▸ Esegui, con un seme facoltativo). Su un La verifica gira a ogni push su qualunque ramo e a mano (Actions ▸ verifica ▸ Esegui, con un seme facoltativo). Su un
ramo un push nuovo annulla l'esecuzione in corso; su `main` ogni unione arriva fino in fondo. Un'esecuzione a mano non ramo un push nuovo annulla l'esecuzione in corso; su `main` ogni unione arriva fino in fondo. Un'esecuzione a mano non
annulla mai quella di un push (l'evento fa parte del gruppo di concorrenza): solo il push scrive gli stati del commit annulla mai quella di un push (l'evento fa parte del gruppo di concorrenza): solo il push scrive gli stati del commit
che servono per unire, e un lavoro annullato lascerebbe lo stato «failure». che servono per unire, e un lavoro annullato lascerebbe lo stato «failure». Se Gitea perde l'evento di un push (è successo
il 13 novembre 2026, con il server che rispondeva 500), un'esecuzione a mano verde non basta per unire, nemmeno da
amministratore, perché la regola vale anche per loro: si spinge un commit nuovo sul ramo e si unisce sulla sua verifica.
Altri flussi: `rilascio.yml` a ogni tag (vedi «Rilasci») e `pulizia.yml` ogni lunedì e a mano (vedi «Pulizia»). Altri flussi: `rilascio.yml` a ogni tag (vedi «Rilasci») e `pulizia.yml` ogni lunedì e a mano (vedi «Pulizia»).
+28
View File
@@ -287,6 +287,34 @@ Dal repository: `dotnet run --project tools/Febe.Sonda -- richieste …`, e cos
Mai: il file HAR, la cartella `grezzi`. Quando richieste e lettori sono stati scritti, **cancella il file HAR e la Mai: il file HAR, la cartella `grezzi`. Quando richieste e lettori sono stati scritti, **cancella il file HAR e la
cartella `grezzi`** (§14.5). cartella `grezzi`** (§14.5).
## A quater. I pezzi che mancano al HAR del 12 novembre
Il HAR del 12 novembre (un giro veloce) ha dato quasi tutto: profilo, schede, raccolte, storie, ricerca, pagina
iniziale (esito in `docs/sonda/richieste-instagram.md`). Mancano due cose, e per quelle basta un giro corto, con la
stessa preparazione (A ter 1 e A ter 2) e la stessa procedura alla fine (A ter 4, 5 e 6), in una cartella nuova:
1. **I tuoi seguiti** (A ter passo 8): clicca la tua foto nella barra a sinistra, poi **«Seguiti»**, e scorri
l'elenco finché si caricano **almeno due** pagine in più. Senza questo il giro dei seguiti non si può scrivere.
2. **Le pagine successive dei post** (A ter passo 2): apri cliccando un profilo che segui e che abbia molti post,
e scorri la griglia finché si caricano **almeno due** pagine in più (3–4 schermate).
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
+25 -2
View File
@@ -9,6 +9,28 @@ della sonda fuori dal repository, ripulite e verificate («Verifica superata»):
`bersagli.instagram.json` sono compilate le pagine con una prova reale (vedi in fondo). Le colonne «Stato» qui sotto `bersagli.instagram.json` sono compilate le pagine con una prova reale (vedi in fondo). Le colonne «Stato» qui sotto
dicono che cosa il HAR ha provato e che cosa no. dicono che cosa il HAR ha provato e che cosa no.
**12 novembre 2026: il secondo HAR** (senza filtro, documenti compresi; #35). Risultati in
`docs/sonda/richieste-instagram.md`, otto campioni nuovi in `tests/Febe.Tests/campioni/instagram` (da `000009` a
`000016`). Che cosa cambia per le ipotesi, senza riscrivere la tabella qui sotto, che resta quella della raccolta coi
bersagli:
- **H1**: la prima pagina del feed è incorporata nel documento della pagina iniziale
(`xdt_api__v1__feed__timeline__connection`), le successive con `PolarisFeedRootPaginationCachedQuery_subscribe`.
- **H2: provata.** Il vassoio delle storie è incorporato nella pagina iniziale (`xdt_api__v1__feed__reels_tray`): per
ogni profilo `latest_reel_media`, `expiring_at` e se è già stato visto.
- **H3: provata, salvo le pagine successive.** Scheda (`PolarisProfilePageContentQuery`, con `media_count`), post
(`PolarisProfilePostsQuery`, reel e serie compresi, con `end_cursor`), elenco delle raccolte con la copertina. La
richiesta della seconda pagina non è nel HAR.
- **H4**: le storie attive di un profilo arrivano con `PolarisStoriesV3ReelPageStandaloneQuery`, con scadenza e durata
e senza dimensioni dei video; guardarle nel visualizzatore manda `PolarisStoriesV3SeenMutation`.
- **H6: risposta diversa dall'ipotesi.** Le schede Reel e Con tag danno anteprime senza data né video, non contenuti
completi; i reel del profilo sono comunque fra i post.
- **H10: un passo avanti.** Nel blocco incorporato della pagina iniziale `xdt_viewer.user` ha identificativo, nome
utente e foto dell'account collegato (`000015-vassoio-storie`), e il lettore lo legge come `Viewer`; nelle
risposte alle richieste della pagina ha il solo identificativo. Resta da provare con la raccolta vera (#36).
- **La JSON incorporata nel documento** è confermata: 69 blocchi nella pagina iniziale.
- **Manca l'elenco dei seguiti**: nessuna richiesta nel HAR (`docs/prove-dal-vivo.md`, parte A quater).
Legenda: **provato in locale** = misurato su questa macchina con Chromium su Xvfb e pagine locali, mai Instagram; Legenda: **provato in locale** = misurato su questa macchina con Chromium su Xvfb e pagine locali, mai Instagram;
**da provare dal vivo** = serve Alberto, con l'account di prova e la sonda (`docs/prove-dal-vivo.md`, parte A). **da provare dal vivo** = serve Alberto, con l'account di prova e la sonda (`docs/prove-dal-vivo.md`, parte A).
@@ -36,8 +58,9 @@ Legenda: **provato in locale** = misurato su questa macchina con Chromium su Xvf
- `src/Febe.Core/Config/lettori.instagram.json`: **confermato** il 25 ottobre sui campioni reali ripuliti; ogni sua - `src/Febe.Core/Config/lettori.instagram.json`: **confermato** il 25 ottobre sui campioni reali ripuliti; ogni sua
chiave compare in quei campioni (lo controlla `InstagramReaderTests`). Le risposte che non parlano di contenuti chiave compare in quei campioni (lo controlla `InstagramReaderTests`). Le risposte che non parlano di contenuti
(promozioni, «storia vista») si ignorano (`relevance`). Senza riscontro restano vuoti `pinned`, `postCount` e (promozioni, «storia vista») si ignorano (`relevance`). Senza riscontro restano vuoti `pinned` e
`version.hasAudio`; le serie (`carousel_media`) sono una chiave vista ma sempre vuota nei campioni. `version.hasAudio`. Il 12 novembre, con il secondo HAR: `postCount` = `media_count`, le serie con i loro figli
(`carousel_media`, anche video) e la copertina delle raccolte (`highlight.cover`).
- `src/Febe.Core/Config/bersagli.instagram.json`: compilate le **pagine** con una prova reale (home, profilo, post, - `src/Febe.Core/Config/bersagli.instagram.json`: compilate le **pagine** con una prova reale (home, profilo, post,
visualizzatore delle storie e delle raccolte, dalle definizioni delle pagine e dai Referer del HAR); i **bersagli** visualizzatore delle storie e delle raccolte, dalle definizioni delle pagine e dai Referer del HAR); i **bersagli**
sono vuoti (H11). Le ricette che non ne hanno bisogno girano; quelle che li usano (storie, raccolte, schede Taggati e sono vuoti (H11). Le ricette che non ne hanno bisogno girano; quelle che li usano (storie, raccolte, schede Taggati e
+118
View File
@@ -0,0 +1,118 @@
# Le richieste della pagina di Instagram (HAR del 12 novembre 2026)
Che cosa chiede l'applicazione web di Instagram al sito, ricavato dal secondo HAR di Alberto (#35) per scrivere
`richieste.instagram.json` e la raccolta della strada B (#36, decisione #34). Qui ci sono solo **forme**: nomi di
operazioni, percorsi, nomi delle variabili e delle chiavi delle risposte. Nessun valore del HAR, nessun `doc_id`.
## Da dove viene
- HAR esportato da Alberto il 12 novembre 2026, **senza filtro**, seguendo `docs/prove-dal-vivo.md` parte A ter:
pagina iniziale, ricerca di un profilo, il profilo aperto cliccando, le schede Reel, Con tag e Ripubblicati, le
raccolte in evidenza, una storia, un post.
- Fuori dal repository (`C:\Users\alber\febe-har\2026-11-12`), sulla macchina di Alberto:
- `febe-sonda richieste` → `richieste.json`: 45 forme di richieste della pagina al sito;
- `febe-sonda da-har` → 142 campioni grezzi (69 blocchi incorporati nell'unico documento, la pagina iniziale, più 73
risposte di dati);
- `febe-sonda ripulisci` e `febe-sonda verifica` → «Verifica superata» su 142 file (44 102 frammenti controllati).
- Nel repository: otto di quelle risposte, accorciate sulla copia ripulita, in `tests/Febe.Tests/campioni/instagram`
(file da `000009` a `000016`, vedi il suo `LEGGIMI.md`).
## Che cosa serve a Febe e da dove arriva
Le operazioni GraphQL sono `POST` con corpo `application/x-www-form-urlencoded`, su due indirizzi:
- `/api/graphql`: scheda, post, Reel, Con tag ed elenco delle raccolte del profilo, ricerca, storie di un profilo;
- `/graphql/query`: pagina iniziale e contenuti delle raccolte in evidenza (con le intestazioni `x-root-field-name`
e `x-bloks-version-id`), e la scheda Ripubblicati (senza quelle intestazioni).
La pagina manda anche `PolarisStoriesV3AdsPoolQuery` (le pubblicità fra le storie) a un terzo indirizzo: a Febe non
serve. Le risposte arrivano come `text/javascript`, tranne le pagine successive della pagina iniziale
(`PolarisFeedRootPaginationCachedQuery_subscribe`), che arrivano come `application/json`; la cattura le legge tutte e
due (`DataResponses`).
| Che cosa serve | Operazione | Variabili (`variables`) | Radice della risposta | Pagina successiva | Campione |
|---|---|---|---|---|---|
| Intestazione del profilo: nome, foto grande, privato, seguito, numero dei post | `PolarisProfilePageContentQuery` | `id` (numero), `enable_integrity_filters` | `data.user` | — | `000009-scheda-profilo` |
| Post del profilo, reel e serie compresi | `PolarisProfilePostsQuery` | `username` (testo), `data.count` = 12 e quattro `include_*`/`latest_*` | `data.xdt_api__v1__feed__user_timeline_graphql_connection` | `page_info.end_cursor` e `has_next_page`; la richiesta della pagina 2 **non è nel HAR** | `000010-post-del-profilo`, `000016-serie-con-video` |
| Scheda Reel | `PolarisProfileReelsTabContentQuery` | `user_id`, `data.target_user_id`, `data.page_size` = 12, `data.include_feed_video` | `data.fetch__XDTUserDict.clips_connection` | `page_info` | `000011-reel-del-profilo` (anteprime) |
| Scheda Con tag | `PolarisProfileTaggedTabContentQuery` | `user_id`, `count` = 12 | `data.xdt_api__v1__usertags__user_id__feed_connection` | `page_info` (il cursore è un numero) | `000012-con-tag` (anteprime) |
| Scheda Ripubblicati | `PolarisProfileRepostsTabContentQuery` (su `/graphql/query`) | `user_id` | `data.fetch__XDTUserDict.user_reposts_timeline` | `repost_more_available`, `repost_next_max_id` | non copiato |
| Elenco delle raccolte in evidenza | `PolarisProfileStoryHighlightsTrayContentQuery` | `user_id` | `data.highlights` (`edges[].node`: `id`, `title`, `cover_media`, `user`) | `page_info` | `000013-raccolte-del-profilo` |
| Contenuti delle raccolte | `PolarisStoriesV3HighlightsPageQuery`, poi `…PaginationQuery` | `reel_ids` (elenco di `highlight:<numero>`), `initial_reel_id`, `first`, `last`; la seconda anche `after`, `before`, `is_highlight` | `xdt_api__v1__feed__reels_media__connection` | `after` | `000006`, `000007` (primo HAR) |
| Storie attive di un profilo | `PolarisStoriesV3ReelPageStandaloneQuery` | `reel_ids_arr` (elenco di identificativi di profilo) | `data.xdt_api__v1__feed__reels_media.reels_media[]` | — | `000014-storie-di-un-profilo` |
| Chi ha storie attive | nessuna richiesta: blocco incorporato nella pagina iniziale | — | `xdt_api__v1__feed__reels_tray.tray[]` (`user`, `latest_reel_media`, `expiring_at`, `seen`) | — | `000015-vassoio-storie` |
| Ricerca dei profili (#37) | `PolarisSearchBoxRefetchableQuery` | `data.query`, `data.context`, `data.search_surface`, `data.search_session_id`, `data.rank_token` (vuoto alla prima), `data.include_reel`, `hasQuery` | `data.xdt_api__v1__fbsearch__topsearch_connection.users[]` (`position`, `user` con `pk`, `username`, `full_name`, `profile_pic_url`, `hd_profile_pic_url_info.url`) | — | `000002-ricerca-profili` (primo HAR) |
| Un post intero | `GET /api/v1/media/{numero}/info/` | nessun parametro | `items[]` | — | `000005-post-video` (primo HAR) |
| Pagina iniziale | `PolarisFeedRootPaginationCachedQuery_subscribe`; la prima pagina è incorporata nel documento | `after`, `first` = 12, `data.device_id`, `variant` e altro | `xdt_api__v1__feed__timeline__connection` | `after` | non copiato |
Che cosa dicono i campioni (le prove sono in `InstagramReaderTests`):
- **I post del profilo bastano per il profilo**: la griglia comprende i reel (`product_type` `clips`) con
`video_versions` e le serie (`media_type` 8) con i figli in `carousel_media`, anche video (`serie-con-video`: 20
figli, il tredicesimo un video con la sua copertina). Le schede Reel e Con tag invece
danno **anteprime** senza `taken_at` né `video_versions`: per un contenuto di quelle schede serve
`/api/v1/media/{numero}/info/`.
- **`media_count`** (numero dei post) c'è solo nella scheda del profilo; ora è `profile.postCount` del vocabolario.
- **Copertina delle raccolte**: `cover_media.cropped_image_version.url` (jpg o webp); ora è `highlight.cover`.
- **Le storie di un profilo si chiedono senza aprire il visualizzatore**: `PolarisStoriesV3ReelPageStandaloneQuery`
risponde con le storie, la scadenza e la durata. Le versioni video delle storie non hanno dimensioni. Questo
riguarda la domanda 11 di §16 (le storie con la strada B), che resta di Alberto.
- **Chi ha storie** si legge dal vassoio incorporato nella pagina iniziale, senza richieste: 120 voci nel HAR.
- **L'account collegato** (H10): nello stesso blocco della pagina iniziale `xdt_viewer.user` ha identificativo, nome
utente e foto; nelle risposte alle richieste della pagina ha il solo identificativo. Il lettore lo legge già come
`Viewer`.
- **`ProfilePostsQuery` vuole il nome utente, le altre operazioni del profilo l'identificativo numerico**: Febe deve
tenere tutti e due (la ricerca e la scheda del profilo li danno insieme).
## Richieste di scrittura che Febe non deve mai mandare
Nel HAR la pagina le ha mandate da sola, durante l'uso normale. Con la strada B Febe chiede solo operazioni di lettura
dell'elenco chiuso, quindi queste non partono mai da Febe; ma vanno escluse per nome anche dalla configurazione
(`richieste.instagram.json` deve rifiutare ogni nome che finisce per `Mutation`):
| Operazione | Quando la manda la pagina | Che cosa fa |
|---|---|---|
| `PolarisStoriesV3SeenMutation` | a ogni storia guardata nel visualizzatore (6 volte nel HAR) | segna la storia come vista: chi l'ha pubblicata vede Alberto fra gli spettatori |
| `usePolarisRegisterInRecentSearchesMutation` | cliccando un risultato della ricerca | aggiunge il profilo alle ricerche recenti di Alberto |
| `usePolarisLikeMediaXIGLikeMutation` | un «mi piace» dato durante la sessione | mette «mi piace» a un post |
Corollario: la raccolta di oggi, che guarda le storie **nel visualizzatore**, le segna come viste. Chiederle con
`ReelPageStandaloneQuery` no, perché il segno «vista» è una richiesta a parte.
## Che cosa porta ogni richiesta, oltre alle variabili
Uguali per tutte le operazioni GraphQL del HAR, da prendere **dalla pagina al momento della richiesta** (mai salvati,
mai nei registri, regola 10):
- campi del corpo: `doc_id` (17 cifre, uno per operazione; cambia quando Instagram pubblica una versione nuova
dell'applicazione web), `fb_api_req_friendly_name` (il nome dell'operazione), `fb_api_caller_class` =
`RelayModern`, `server_timestamps`, `variables`, e i campi di sessione `fb_dtsg`, `av`, `__user`, `__a`,
`__comet_req`, `__req`, `__rev`, `__s`, `__hs`, `__hsi`, `__hsdp`, `__hblp`, `__sjsp`, `__csr`, `__dyn`,
`__spin_r`, `__spin_b`, `__spin_t`, `__ccg`, `__crn`, `__d`, `dpr`, più un campo il cui nome `febe-sonda richieste`
ha tolto perché nel HAR compare anche come valore;
- intestazioni: `x-csrftoken`, `x-fb-lsd`, `x-ig-app-id`, `x-asbd-id`, `x-fb-friendly-name`, `x-fb-entry-nonce`,
`x-ig-max-touch-points` e, su `/graphql/query`, `x-root-field-name` e `x-bloks-version-id`. Le altre
(`user-agent`, `sec-ch-ua*`, `referer`, i cookie) le mette il browser da solo e restano come sono (regola 4).
Il punto aperto per #36 è **da dove prendere `doc_id` e i campi di sessione**. Inventarli è vietato (regola 9), e
copiarli dal HAR non funziona perché cambiano. §6.1 vuole che i gettoni restino nella pagina e che allo script torni
solo il corpo della risposta. Le vie da valutare:
1. **solo dentro la pagina**: lo script di `Runtime.evaluate` (la riga di §6.1 della strada B) prende `doc_id` e i
campi di sessione dal codice della pagina e manda la richiesta; dipende dai nomi interni dell'applicazione web;
2. **`doc_id` dalle richieste della pagina, il resto dentro la pagina**: `doc_id` e il nome dell'operazione sono
uguali per tutti e non segreti, e si possono ricavare dall'ultima richiesta della stessa operazione che la pagina
ha mandato da sé; i campi di sessione restano allo script nella pagina. Serve però che il client CDP legga i corpi
delle richieste, cosa che oggi non fa (`ResponseTap` ascolta solo le risposte): `Network.requestWillBeSent` con
`postData`, ed eventualmente `Network.getRequestPostData`, che non è nell'elenco di §6.1. Va deciso con Alberto;
3. leggere dalle richieste della pagina anche i campi di sessione e le intestazioni (`fb_dtsg`, `x-csrftoken`,
`x-fb-lsd`) è escluso: i gettoni uscirebbero dalla pagina, contro §6.1.
## Che cosa manca e serve un altro HAR
- **L'elenco dei seguiti**: nel HAR non c'è nessuna richiesta dell'elenco (né `friendships` né un'operazione
GraphQL). Senza, il giro dei seguiti non si può scrivere.
- **La seconda pagina dei post di un profilo** (`PolarisProfilePostsQuery` con `after`, o un'altra operazione): nel
HAR c'è solo la prima.
La procedura per raccoglierli è in `docs/prove-dal-vivo.md`, parte A quater.
+55
View File
@@ -7,6 +7,61 @@ 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.
- PR #45 (secondo HAR, lettori, sonda per i HAR troncati): Gitea, che quella notte rispondeva 500, ha perso
l'evento del push di 78aa32b, e la verifica non è partita. Lanciata a mano (esecuzione 262) è verde in tutti e
quattro i lavori, ma un'esecuzione a mano non scrive gli stati del commit, e la protezione di `main` non lascia
unire neanche un amministratore. Per questo c'è un commit in più, che riporta questo caso anche in
`docs/processo.md`: il suo push fa girare la verifica che serve. L'unione restava rifiutata (405) anche dopo,
perché il ramo era indietro rispetto a `main`, che aveva il commit di unione di #44: `main` è stato unito nel
ramo, senza cambiare il contenuto, e la verifica è girata di nuovo.
- PR #44 è unita; anche la verifica di `main` del 12/11 (esecuzione 250) è caduta solo sul caricamento del rapporto
di Trivy, per le risposte 500 di Gitea.
**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:
`febe-sonda richieste` (45 forme di richieste), `da-har` (142 campioni grezzi), `ripulisci` e `verifica` →
«Verifica superata». Per arrivarci sono serviti tre correttivi alla sonda (numeri con esponente, falsi allarmi
della verifica, parole degli indirizzi finti; `docs/decisioni.md`), con tre prove nuove.
- **Esito** in `docs/sonda/richieste-instagram.md`: quale operazione dà che cosa (scheda e post del profilo, raccolte,
storie di un profilo, ricerca, pagina iniziale), i campi che ogni richiesta porta e che vanno presi dalla pagina, e
le tre scritture che la pagina manda da sola e Febe mai (storia vista, ricerca recente, «mi piace»). Riassunto per
ipotesi in `docs/sonda/esito.md`.
- **Otto campioni nuovi** (`000009`–`000016`), accorciati sulla copia ripulita; il lettore li legge già, con due
aggiunte al vocabolario (`postCount` = `media_count`, `highlight.cover`) e sette prove nuove in
`InstagramReaderTests`. Il blocco della pagina iniziale dà anche nome e foto dell'account collegato (H10).
- **Manca ancora**: l'elenco dei seguiti e la seconda pagina dei post. Giro corto per Alberto in
`docs/prove-dal-vivo.md`, parte **A quater**. Punto aperto per #36: da dove prendere `doc_id` e i campi di sessione,
che per §6.1 restano nella pagina (tre vie in `docs/sonda/richieste-instagram.md`).
- **Revisione avversaria** prima del commit (18 agenti): 8 rilievi confermati, tutti corretti. Fra questi due difetti
della verifica (una chiave di dati grezza poteva passare sotto la regola della chiave che la contiene; un carattere
come il segno Kelvin poteva fermarla invece di segnalare la fuga), una serie con un video che era già nel HAR e che
i documenti davano per mancante, e la via «riusa l'ultima richiesta della pagina», che come era scritta faceva
uscire i gettoni dalla pagina.
- PR #44 (strada B nei documenti e `febe-sonda richieste`): **unita in `main`** (0153280) con la verifica verde al
quinto tentativo. I primi tre sono caduti su prove di tempi del runner sovraccarico, ogni volta prove diverse e mai
su codice cambiato:
- riempimento della libreria in 291 s;
- Chromium che non risponde sulla porta di debug;
- spostamento della cartella con la shell nativa.
Il quarto si è interrotto per il riavvio del PC. Queste prove instabili meritano una issue a parte.
**12 novembre 2026: la prova dal vivo non è andata, la raccolta va ripensata.** **12 novembre 2026: la prova dal vivo non è andata, la raccolta va ripensata.**
- Alberto: con i dati veri Febe non trova gli account e non scarica nulla (#33). - Alberto: con i dati veri Febe non trova gli account e non scarica nulla (#33).
@@ -136,6 +136,9 @@ public sealed record HighlightKeys
/// <summary>The contents of the collection, when the response carries them.</summary> /// <summary>The contents of the collection, when the response carries them.</summary>
public VocabularyKeys Items { get; init; } = VocabularyKeys.None; public VocabularyKeys Items { get; init; } = VocabularyKeys.None;
/// <summary>The cover image of the collection, read as a version.</summary>
public VocabularyKeys Cover { get; init; } = VocabularyKeys.None;
} }
/// <summary>Keys of the pagination information that comes with a page of data.</summary> /// <summary>Keys of the pagination information that comes with a page of data.</summary>
@@ -325,7 +328,7 @@ public sealed record ReaderVocabulary
Picture = K(p.Picture), Picture = K(p.Picture),
LatestStoryAt = K(p.LatestStoryAt), LatestStoryAt = K(p.LatestStoryAt),
}, },
Highlight = new HighlightKeys { Id = K(h.Id), Title = K(h.Title), Owner = K(h.Owner), Items = K(h.Items) }, Highlight = new HighlightKeys { Id = K(h.Id), Title = K(h.Title), Owner = K(h.Owner), Items = K(h.Items), Cover = K(h.Cover) },
Page = new PageKeys { HasMore = K(g.HasMore), Cursor = K(g.Cursor) }, Page = new PageKeys { HasMore = K(g.HasMore), Cursor = K(g.Cursor) },
Viewer = K(file.Viewer), Viewer = K(file.Viewer),
Relevance = [.. (file.Relevance?.Keys ?? []).Where(k => !string.IsNullOrWhiteSpace(k)).Select(k => k.Trim()).Distinct(StringComparer.Ordinal)], Relevance = [.. (file.Relevance?.Keys ?? []).Where(k => !string.IsNullOrWhiteSpace(k)).Select(k => k.Trim()).Distinct(StringComparer.Ordinal)],
@@ -437,6 +440,8 @@ internal sealed class HighlightDto
public List<string>? Owner { get; set; } public List<string>? Owner { get; set; }
public List<string>? Items { get; set; } public List<string>? Items { get; set; }
public List<string>? Cover { get; set; }
} }
internal sealed class PageDto internal sealed class PageDto
@@ -151,6 +151,7 @@ public sealed class ShapeReader
Id = id, Id = id,
Title = AsText(Get(_v.Highlight.Title, node)) ?? string.Empty, Title = AsText(Get(_v.Highlight.Title, node)) ?? string.Empty,
Owner = highlightOwner, Owner = highlightOwner,
Cover = _v.Highlight.Cover.TryGet(node, out var cover) ? ReadVersion(cover) : null,
Items = walk.Contents.Skip(before).ToList(), Items = walk.Contents.Skip(before).ToList(),
Order = walk.Highlights.Count, Order = walk.Highlights.Count,
}); });
+7 -6
View File
@@ -1,9 +1,9 @@
{ {
"site": "instagram", "site": "instagram",
"status": "confermato", "status": "confermato",
"note": "Vocabolario dei lettori per Instagram, compilato il 25 ottobre 2026 sulle risposte reali che il browser di Alberto ha ricevuto il 21 ottobre (file HAR), ripulite con «febe-sonda ripulisci» e conservate in tests/Febe.Tests/campioni/instagram (regola 10). Ogni concetto dice da quali campioni viene; quelli senza riscontro restano vuoti o sono segnati come indizio. I dati di storie e raccolte arrivano come «text/javascript», non come JSON dichiarato: la cattura li legge lo stesso (DataResponses). «viewer»: xdt_viewer.user, visto in raccolta-in-evidenza, descrive l'account collegato con il solo identificativo, senza nome, quindi da solo non basta a riconoscerlo (H10 resta aperta).", "note": "Vocabolario dei lettori per Instagram, compilato il 25 ottobre 2026 sulle risposte reali che il browser di Alberto ha ricevuto il 21 ottobre (file HAR) e completato il 12 novembre con quelle del secondo HAR (scheda del profilo, post del profilo, raccolte del profilo, storie), ripulite con «febe-sonda ripulisci» e conservate in tests/Febe.Tests/campioni/instagram (regola 10). Ogni concetto dice da quali campioni viene; quelli senza riscontro restano vuoti o sono segnati come indizio. I dati di storie e raccolte arrivano come «text/javascript», non come JSON dichiarato: la cattura li legge lo stesso (DataResponses). «viewer»: xdt_viewer.user, visto in raccolta-in-evidenza, descrive l'account collegato con il solo identificativo, senza nome; nel blocco incorporato nella pagina iniziale (vassoio-storie, 12 novembre) ha anche username e profile_pic_url, e il lettore lo legge come Viewer (H10, da provare con la raccolta vera).",
"content": { "content": {
"note": "Un contenuto (XDTMediaDict): post, reel, storia o contenuto di una raccolta. Visti in post-video (/api/v1/media/…/info/), raccolta-in-evidenza e raccolta-pagina-successiva. «user» dei contenuti di una storia ha solo l'identificativo, senza nome: l'autore si eredita dalla raccolta o dalla serie di storie che li contiene. La didascalia è un oggetto con il testo in «text». Serie (carousel_media): chiave vista ma sempre vuota nei campioni, il formato dei figli è un indizio di §6.4 da confermare con un campione di un post con più file.", "note": "Un contenuto (XDTMediaDict): post, reel, storia o contenuto di una raccolta. Visti in post-video (/api/v1/media/…/info/), raccolta-in-evidenza, raccolta-pagina-successiva, post-del-profilo (reel e serie) e storie-di-un-profilo. Le griglie delle schede Reel e Con tag (reel-del-profilo, con-tag) sono anteprime senza taken_at né video_versions: non sono contenuti, il contenuto intero arriva da post-del-profilo o da /api/v1/media/…/info/. «user» dei contenuti di una storia ha solo l'identificativo, senza nome: l'autore si eredita dalla raccolta o dalla serie di storie che li contiene. La didascalia è un oggetto con il testo in «text». Serie (carousel_media, media_type 8): i figli sono contenuti con le loro image_versions2 e video_versions, visti in post-del-profilo (6 foto) e serie-con-video (20 figli, uno video).",
"id": ["pk"], "id": ["pk"],
"code": ["code"], "code": ["code"],
"takenAt": ["taken_at"], "takenAt": ["taken_at"],
@@ -25,22 +25,23 @@
"hasAudio": [] "hasAudio": []
}, },
"profile": { "profile": {
"note": "Un profilo (XDTUserDict): visto come autore di un post (user, owner), come proprietario di una raccolta, nella ricerca e nei profili suggeriti. friendship_status.following dice se Alberto lo segue; latest_reel_media è la data dell'ultima storia. Il numero dei post non compare in nessun campione: resta vuoto.", "note": "Un profilo (XDTUserDict): visto come autore di un post (user, owner), come proprietario di una raccolta, nella ricerca e nei profili suggeriti. friendship_status.following dice se Alberto lo segue; latest_reel_media è la data dell'ultima storia; media_count, il numero dei post, compare solo nella scheda del profilo (scheda-profilo, PolarisProfilePageContentQuery). Nel vassoio delle storie (vassoio-storie, incorporato nella pagina iniziale) ogni voce ha l'utente con nome e foto ma senza nome per esteso.",
"id": ["pk", "id"], "id": ["pk", "id"],
"username": ["username"], "username": ["username"],
"displayName": ["full_name"], "displayName": ["full_name"],
"isPrivate": ["is_private"], "isPrivate": ["is_private"],
"isFollowed": ["friendship_status.following"], "isFollowed": ["friendship_status.following"],
"postCount": [], "postCount": ["media_count"],
"picture": ["hd_profile_pic_url_info", "hd_profile_pic_versions", "profile_pic_url"], "picture": ["hd_profile_pic_url_info", "hd_profile_pic_versions", "profile_pic_url"],
"latestStoryAt": ["latest_reel_media"] "latestStoryAt": ["latest_reel_media"]
}, },
"highlight": { "highlight": {
"note": "Una raccolta in evidenza (XDTReelDict con reel_type highlight_reel): id «highlight:<numero>», title, user e i contenuti in items. Vista in raccolta-in-evidenza e raccolta-pagina-successiva.", "note": "Una raccolta in evidenza (XDTReelDict con reel_type highlight_reel): id «highlight:<numero>», title, user e i contenuti in items. Vista in raccolta-in-evidenza e raccolta-pagina-successiva. L'elenco delle raccolte di un profilo (raccolte-del-profilo, PolarisProfileStoryHighlightsTrayContentQuery) ha id, title, user e la copertina in cover_media.cropped_image_version, senza contenuti.",
"id": ["id"], "id": ["id"],
"title": ["title"], "title": ["title"],
"owner": ["user"], "owner": ["user"],
"items": ["items"] "items": ["items"],
"cover": ["cover_media.cropped_image_version"]
}, },
"page": { "page": {
"note": "page_info delle connessioni GraphQL (has_next_page, end_cursor) e more_available delle risposte REST. Visti in raccolta-in-evidenza e post-video.", "note": "page_info delle connessioni GraphQL (has_next_page, end_cursor) e more_available delle risposte REST. Visti in raccolta-in-evidenza e post-video.",
+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)),
},
};
}
}
@@ -68,7 +68,7 @@ public sealed class InstagramReaderTests
Vocabulary.Content.ExpiresAt, Vocabulary.Content.Duration, Vocabulary.Version.Url, Vocabulary.Version.Width, Vocabulary.Version.Height, Vocabulary.Content.ExpiresAt, Vocabulary.Content.Duration, Vocabulary.Version.Url, Vocabulary.Version.Width, Vocabulary.Version.Height,
Vocabulary.Version.HasAudio, Vocabulary.Profile.Id, Vocabulary.Profile.Username, Vocabulary.Profile.DisplayName, Vocabulary.Profile.IsPrivate, Vocabulary.Version.HasAudio, Vocabulary.Profile.Id, Vocabulary.Profile.Username, Vocabulary.Profile.DisplayName, Vocabulary.Profile.IsPrivate,
Vocabulary.Profile.IsFollowed, Vocabulary.Profile.PostCount, Vocabulary.Profile.Picture, Vocabulary.Profile.LatestStoryAt, Vocabulary.Profile.IsFollowed, Vocabulary.Profile.PostCount, Vocabulary.Profile.Picture, Vocabulary.Profile.LatestStoryAt,
Vocabulary.Highlight.Id, Vocabulary.Highlight.Title, Vocabulary.Highlight.Owner, Vocabulary.Highlight.Items, Vocabulary.Highlight.Id, Vocabulary.Highlight.Title, Vocabulary.Highlight.Owner, Vocabulary.Highlight.Items, Vocabulary.Highlight.Cover,
Vocabulary.Page.HasMore, Vocabulary.Page.Cursor, Vocabulary.Viewer, Vocabulary.Page.HasMore, Vocabulary.Page.Cursor, Vocabulary.Viewer,
}; };
foreach (var path in concepts.SelectMany(c => c.Paths)) foreach (var path in concepts.SelectMany(c => c.Paths))
@@ -198,6 +198,131 @@ public sealed class InstagramReaderTests
Assert.AreEqual(post.TakenAt, ReadMapping.ToEntry(post, 1, EntryKind.Post, now).PublishedAt); Assert.AreEqual(post.TakenAt, ReadMapping.ToEntry(post, 1, EntryKind.Post, now).PublishedAt);
} }
[TestMethod]
public void TheProfileCardGivesThePostCountTheNameAndTheLargePicture()
{
// PolarisProfilePageContentQuery, from the second HAR (12 November 2026): the only answer with media_count.
var result = ReadSample("scheda-profilo");
Assert.AreEqual(ReadShape.Recognized, result.Shape);
Assert.AreEqual(0, result.Contents.Count);
var profile = result.Profiles.Single();
Assert.AreEqual(443, profile.PostCount);
Assert.IsFalse(string.IsNullOrWhiteSpace(profile.DisplayName));
Assert.AreEqual(false, profile.IsPrivate);
Assert.AreEqual(false, profile.IsFollowed);
Assert.IsNotNull(profile.LatestStoryAt);
Assert.IsTrue(profile.Picture?.Url.EndsWith(".jpg", StringComparison.Ordinal), "hd_profile_pic_url_info has the address only.");
}
[TestMethod]
public void TheProfilePostsGiveReelsAndSeriesWithTheNextPage()
{
// PolarisProfilePostsQuery: the grid of a profile, reels included, 12 at a time (2 kept: a reel and a series).
var result = ReadSample("post-del-profilo");
Assert.AreEqual(ReadShape.Recognized, result.Shape);
Assert.AreEqual(2, result.Contents.Count);
Assert.IsTrue(result.Contents.All(c => c.Code?.Length == 11 && c.Owner is not null && c.ExpiresAt is null && c.IsComplete));
Assert.AreEqual(1, result.Contents.Select(c => c.Owner!.Username).Distinct().Count());
var reel = result.Contents[0].Files.Single();
Assert.AreEqual(MediaKind.Video, reel.Kind);
Assert.AreEqual((720, 1280), (reel.Best.Width, reel.Best.Height));
Assert.IsNotNull(reel.Cover);
var series = result.Contents[1].Files;
Assert.AreEqual(6, series.Count, "carousel_media: one file for each child.");
Assert.IsTrue(series.All(f => f.Kind == MediaKind.Photo && f.Best.Width == 2160 && f.Best.Height == 2880));
Assert.AreEqual(true, result.Page?.HasMore);
Assert.IsFalse(string.IsNullOrEmpty(result.Page?.Cursor), "page_info.end_cursor, the «after» of the next page.");
Assert.IsNotNull(result.ViewerId);
}
[TestMethod]
public void ASeriesWithAVideoKeepsEveryChildInOrder()
{
// The same answer as «post-del-profilo», another post: 20 children, the 13th a video with its cover.
var result = ReadSample("serie-con-video");
var post = result.Contents.Single();
Assert.IsTrue(post.IsComplete);
Assert.AreEqual(20, post.Files.Count);
Assert.AreEqual(12, post.Files.ToList().FindIndex(f => f.Kind == MediaKind.Video));
var video = post.Files[12];
Assert.IsTrue(video.Best.Url.EndsWith(".mp4", StringComparison.Ordinal));
Assert.IsNotNull(video.Cover);
Assert.AreEqual(19, post.Files.Count(f => f.Kind == MediaKind.Photo));
}
[TestMethod]
public void TheReelsAndTaggedGridsArePreviewsNotContents()
{
// The Reels and Tagged tabs carry thumbnails without taken_at or video versions: the profile and the next page
// are read, the previews are not contents (the whole content comes from the posts or from media/…/info/).
foreach (var name in new[] { "reel-del-profilo", "con-tag" })
{
var result = ReadSample(name);
Assert.AreEqual(ReadShape.Recognized, result.Shape, name);
Assert.AreEqual(0, result.Contents.Count, name);
Assert.IsTrue(result.Profiles.Count > 0, name);
Assert.AreEqual(true, result.Page?.HasMore, name);
}
}
[TestMethod]
public void TheHighlightsOfAProfileComeWithTitleAndCoverButNoItems()
{
// PolarisProfileStoryHighlightsTrayContentQuery: the list under the profile header (3 of 9 kept).
var result = ReadSample("raccolte-del-profilo");
Assert.AreEqual(ReadShape.Recognized, result.Shape);
Assert.AreEqual(3, result.Highlights.Count);
foreach (var highlight in result.Highlights)
{
StringAssert.Matches(highlight.Id, new System.Text.RegularExpressions.Regex("^[0-9]{17}$"));
Assert.IsFalse(string.IsNullOrWhiteSpace(highlight.Title));
Assert.IsNotNull(highlight.Owner);
StringAssert.StartsWith(highlight.Cover?.Url, "https://", "cover_media.cropped_image_version (jpg or webp).");
Assert.AreEqual(0, highlight.Items.Count, "The stories of a collection come with PolarisStoriesV3HighlightsPageQuery.");
}
Assert.AreEqual(false, result.Page?.HasMore);
}
[TestMethod]
public void TheStoriesOfAProfileExpireAndHaveADuration()
{
// PolarisStoriesV3ReelPageStandaloneQuery: the stories of one profile (reels_media, reel_type user_reel).
var result = ReadSample("storie-di-un-profilo");
Assert.AreEqual(ReadShape.Recognized, result.Shape);
var story = result.Contents.Single();
Assert.IsNull(story.HighlightId);
Assert.IsTrue(story.ExpiresAt > story.TakenAt);
Assert.IsNotNull(story.Owner);
var video = story.Files.Single();
Assert.AreEqual(MediaKind.Video, video.Kind);
Assert.IsTrue(video.Duration > TimeSpan.Zero);
Assert.IsNull(video.Best.Width, "Story video versions have no dimensions.");
Assert.IsNotNull(video.Cover);
}
[TestMethod]
public void TheStoriesTrayOfTheHomePageSaysWhoHasStories()
{
// xdt_api__v1__feed__reels_tray, embedded in the home page document (3 of 120 kept): who has stories and when
// the last one was published, without the stories themselves.
var result = ReadSample("vassoio-storie");
Assert.AreEqual(ReadShape.Recognized, result.Shape);
Assert.AreEqual(0, result.Contents.Count);
var withStories = result.Profiles.Where(p => !p.IsViewer).ToList();
Assert.AreEqual(3, withStories.Count);
Assert.IsTrue(withStories.All(p => p.LatestStoryAt is not null && p.Picture is not null));
// H10: in the page document xdt_viewer.user also has the name and the picture of the connected account.
Assert.IsNotNull(result.Viewer);
Assert.AreEqual(result.ViewerId, result.Viewer.Id);
Assert.IsFalse(string.IsNullOrWhiteSpace(result.Viewer.Username));
Assert.IsNotNull(result.Viewer.Picture);
}
[TestMethod] [TestMethod]
public void TheProfilesOfSearchSuggestionsAndCommentsAreProfilesOnly() public void TheProfilesOfSearchSuggestionsAndCommentsAreProfilesOnly()
{ {
@@ -211,6 +211,74 @@ public sealed class SanitizerTests
Assert.IsFalse(SampleSanitizer.LooksLikeSecretKey("username")); Assert.IsFalse(SampleSanitizer.LooksLikeSecretKey("username"));
} }
[TestMethod]
public void WordsOfSomeoneElsesTextInsideKeptValuesAreNotLeaksButTheTextStillIs()
{
// From the HAR of 12 November 2026: the Italian word «altro» and a short word inside a media type or a date
// occur in other people's text; the cleaned samples write «altro.esempio», «.avif», «text/javascript» and keep
// dates on purpose. Those are not leaks. A name put back by hand still is, and the check says under which key.
using var temp = new TempFolder("ripulitura");
var raw = Directory.CreateDirectory(temp.Combine("grezzi")).FullName;
File.WriteAllText(Path.Combine(raw, "000001.json"), """
{
"descrittore": { "indirizzo": "https://www.instagram.com/graphql/query", "host": "sito", "stato": 200, "tipo": "text/javascript" },
"corpo": {
"didascalia": "Altro script di Lucia, 17914",
"link": "https://esterno.example/pagina",
"foto": "https://scontent.cdninstagram.com/v/t51/123_456_n.avif?firma=x",
"taken_at": 1791791400
}
}
""");
var clean = temp.Combine("ripuliti");
new SampleSanitizer(key: new byte[32]).SanitizeFolder(raw, clean);
var verify = SampleVerifier.Verify(raw, clean);
Assert.IsTrue(verify.Passed, string.Join("; ", verify.Leaks.Select(l => $"{l.CleanFile} {l.Length} {l.Kind} {l.Key}")));
var path = Path.Combine(clean, "000001.json");
var node = JsonNode.Parse(File.ReadAllText(path))!;
node["corpo"]!["link"] = "https://altro.esempio/lucia";
File.WriteAllText(path, node.ToJsonString());
var leak = SampleVerifier.Verify(raw, clean).Leaks.Single();
Assert.AreEqual(new SampleLeak("000001.json", 5, "lettere", "link"), leak);
}
[TestMethod]
public void ARawDataKeyLeftInTheCleanCopyFailsWhateverItsParentKeyAllows()
{
// A data key (an identifier or a name used as a key) is always faked: the rule of its parent key («*_at» keeps
// dates, «type» keeps codes) must not make the check skip it when a raw one is left behind.
using var temp = new TempFolder("ripulitura");
var raw = Directory.CreateDirectory(temp.Combine("grezzi")).FullName;
File.WriteAllText(Path.Combine(raw, "000001.json"), """
{
"descrittore": { "indirizzo": "https://www.instagram.com/graphql/query", "host": "sito", "stato": 200, "tipo": "text/javascript" },
"corpo": { "updated_at": { "17841400123": 1 }, "type": { "lucia.rossi": true } }
}
""");
var clean = Directory.CreateDirectory(temp.Combine("ripuliti")).FullName;
File.Copy(Path.Combine(raw, "000001.json"), Path.Combine(clean, "000001.json"));
var leaks = SampleVerifier.Verify(raw, clean).Leaks;
Assert.IsTrue(leaks.Any(l => l.Kind == "cifre" && l.Key == "(chiave di dati)"), string.Join("; ", leaks));
Assert.IsTrue(leaks.Any(l => l.Kind == "lettere" && l.Key == "(chiave di dati)"), string.Join("; ", leaks));
}
[TestMethod]
public void LongNumbersWithAnExponentOrAFractionStayNumbers()
{
// Instagram writes some large numbers with an exponent: only the digits are faked, the «e» and the sign stay.
var sanitizer = new SampleSanitizer(key: new byte[32]);
var node = sanitizer.Sanitize(JsonNode.Parse("""{"a":1.7976931348e+21,"b":-12345.678,"c":98765432109876}"""))!;
foreach (var key in new[] { "a", "b", "c" })
{
Assert.AreEqual(JsonValueKind.Number, node[key]!.GetValueKind(), key);
}
StringAssert.Contains(node["a"]!.ToJsonString(), "e+");
StringAssert.StartsWith(node["b"]!.ToJsonString(), "-");
Assert.AreNotEqual("98765432109876", node["c"]!.ToJsonString());
}
[TestMethod] [TestMethod]
public void TheProbeReadsOnlyThroughAReadOnlyScript() => public void TheProbeReadsOnlyThroughAReadOnlyScript() =>
Febe.Browser.Cdp.ReadOnlyScriptGuard.EnsureReadOnly(ProbeRecorder.InteractionScript); Febe.Browser.Cdp.ReadOnlyScriptGuard.EnsureReadOnly(ProbeRecorder.InteractionScript);
@@ -0,0 +1,155 @@
{
"descrittore": {
"indirizzo": "https://sito.esempio/snj1xswxv2412473",
"host": "sito",
"stato": 200,
"tipo": "text/javascript",
"risorsa": "XHR",
"quando": "2026-11-12T16:33:09Z"
},
"corpo": {
"data": {
"user": {
"pk": "698772114",
"aigm_account_label_info": {
"is_enabled": false,
"attribution_label_text": null,
"is_auto_detected": false,
"is_manually_enabled": false
},
"friendship_status": {
"following": false,
"blocking": false,
"is_feed_favorite": false,
"outgoing_request": false,
"followed_by": false,
"incoming_request": false,
"is_restricted": false,
"is_bestie": false,
"muting": false,
"is_muting_reel": false
},
"gating": null,
"fbid_v2": "64079472552935156",
"is_memorialized": false,
"is_private": false,
"has_story_archive": null,
"is_coppa_enforced": null,
"supervision_info": null,
"is_regulated_c18": false,
"regulated_news_in_locations": [],
"bio_links": [],
"linked_fb_info": null,
"meta_verified_benefits_info": {
"active_meta_verified_benefits": []
},
"text_post_app_badge_label": "kxkdgltnfv",
"show_text_post_app_badge": true,
"username": "kxkdgltnfv",
"live_broadcast_visibility": null,
"live_broadcast_id": null,
"profile_pic_url": "https://cdn.esempio/d32p6rq42tx5d501.jpg",
"hd_profile_pic_url_info": {
"url": "https://cdn.esempio/pw85qt1xwj4nsq48.jpg"
},
"is_unpublished": false,
"latest_reel_media": 1794463637,
"has_profile_pic": null,
"profile_pic_genai_tool_info": [],
"biography": "",
"full_name": "Kbsmpg Mmbtm",
"is_verified": false,
"show_account_transparency_details": true,
"account_type": 2,
"follower_count": 1291,
"mutual_followers_count": 8,
"profile_context_links_with_user_ids": [
{
"username": "bdwfqpskxmsbc",
"id": null
},
{
"username": "znhmrxnjsp",
"id": null
},
{
"username": null,
"id": null
}
],
"profile_context_facepile_users": [
{
"profile_pic_url": "https://cdn.esempio/tnw1s2150g941323.jpg",
"id": "2961391528"
},
{
"profile_pic_url": "https://cdn.esempio/jbt33g48qd69l8g8.jpg",
"id": "122556288"
},
{
"profile_pic_url": "https://cdn.esempio/77d89r9l3643r36b.jpg",
"id": "3305412751"
}
],
"address_street": "",
"city_name": "",
"is_business": true,
"zip": "",
"biography_with_entities": {
"entities": []
},
"category": "Llmp klfpqnsst",
"should_show_category": true,
"is_ring_creator": false,
"show_ring_award": false,
"ring_creator_metadata": {
"profile_background_color": null,
"profile_background_secondary_color": null
},
"account_badges": [],
"ai_agent_type": null,
"external_lynx_url": null,
"external_url": "",
"pronouns": [],
"transparency_label": null,
"transparency_product": null,
"hide_creator_marketplace_badge": false,
"id": "698772114",
"has_chaining": true,
"remove_message_entrypoint": false,
"is_embeds_disabled": false,
"is_cannes": false,
"is_professional_account": null,
"following_count": 2147,
"media_count": 443,
"has_restyle_presets": false,
"total_clips_count": 1,
"has_visible_media_notes": true,
"short_drama_creator": null,
"has_longform_media": false,
"latest_besties_reel_media": 0,
"reel_media_seen_timestamp": null
},
"viewer": {
"user": {
"pk": "646392312",
"id": "646392312",
"can_see_organic_insights": true,
"supervision_info": {
"is_guardian_user": false,
"is_feta_guardian_user": false,
"guardian_hypercard_content": null,
"id": "DXJTlvsjqnnqxhWwfl:595582912"
}
}
}
},
"extensions": {
"server_metadata": {
"request_start_time_ms": 7751987683650,
"time_at_flush_ms": 2304726683043
},
"is_final": true
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,304 @@
{
"descrittore": {
"indirizzo": "https://sito.esempio/snj1xswxv2412473",
"host": "sito",
"stato": 200,
"tipo": "text/javascript",
"risorsa": "XHR",
"quando": "2026-11-12T16:33:13Z"
},
"corpo": {
"data": {
"fetch__XDTUserDict": {
"clips_connection": {
"edges": [
{
"node": {
"media": {
"pk": "4112858797058901390",
"id": "5573622115216393682_225493459",
"code": "XnDVLdfqlj6",
"media_overlay_info": null,
"carousel_media": null,
"boosted_status": null,
"boost_unavailable_identifier": null,
"boost_unavailable_reason": null,
"user": {
"pk": "698772114",
"id": "698772114",
"aigm_account_label_info": {
"attribution_label_text": null,
"is_auto_detected": false,
"is_enabled": false,
"is_manually_enabled": false
},
"username": "kxkdgltnfv",
"full_name": "Kbsmpg Mmbtm",
"profile_pic_url": "https://cdn.esempio/d32p6rq42tx5d501.jpg",
"is_verified": false,
"is_embeds_disabled": false,
"is_private": false,
"is_unpublished": false,
"__typename": "CXPStkmJdmj",
"friendship_status": {
"following": false,
"is_feed_favorite": false
},
"show_account_transparency_details": true
},
"product_type": "clips",
"play_count": 1597,
"view_count": null,
"like_and_view_counts_disabled": false,
"comment_count": 3,
"like_count": 66,
"audience": null,
"clips_tab_pinned_user_ids": [
"698772114"
],
"media_type": 2,
"image_versions2": {
"candidates": [
{
"height": 1280,
"url": "https://cdn.esempio/sb2236hd75m1w7x3.jpg",
"width": 720
},
{
"height": 1138,
"url": "https://cdn.esempio/cl6sl714q40m4rd7.jpg",
"width": 640
},
{
"height": 853,
"url": "https://cdn.esempio/3v5qhq2m35559s71.jpg",
"width": 480
},
{
"height": 569,
"url": "https://cdn.esempio/46408p9d34294518.jpg",
"width": 320
},
{
"height": 427,
"url": "https://cdn.esempio/94k8c832t1rgz3z6.jpg",
"width": 240
},
{
"height": 720,
"url": "https://cdn.esempio/r5g10n37j529gk71.jpg",
"width": 720
},
{
"height": 720,
"url": "https://cdn.esempio/r5g10n37j529gk71.jpg",
"width": 720
},
{
"height": 640,
"url": "https://cdn.esempio/c85htz5zf412c4x5.jpg",
"width": 640
},
{
"height": 480,
"url": "https://cdn.esempio/314kj01lh098798p.jpg",
"width": 480
},
{
"height": 320,
"url": "https://cdn.esempio/0g099mb62n522bl7.jpg",
"width": 320
},
{
"height": 240,
"url": "https://cdn.esempio/x077zx82rq79ztx3.jpg",
"width": 240
},
{
"height": 150,
"url": "https://cdn.esempio/6806pv954x43mf67.jpg",
"width": 150
}
]
},
"preview": null,
"original_height": 2560,
"original_width": 1440,
"ai_interactive_embodiment_attachment_style_info": null,
"coauthor_producers": [],
"is_fb_only": null,
"is_internal_only": null,
"logging_info_token": null,
"linked_media_playlist_data": null,
"can_viewer_reshare": true,
"ig_media_sharing_disabled": false,
"is_active_trial": false,
"is_in_profile_grid": false,
"is_short_drama": false,
"profile_grid_control_enabled": false,
"visibility": null,
"comments_disabled": null,
"feed_demotion_control": null,
"feed_recs_demotion_control": null,
"ai_label_info": null,
"inventory_source": null,
"longform_clip_metadata": null
},
"__typename": "WSBHmqjpNjnjLfrs"
},
"cursor": null
},
{
"node": {
"media": {
"pk": "7804317226943356124",
"id": "7027624897921683868_816415006",
"code": "HDml6NKNvkd",
"media_overlay_info": null,
"carousel_media": null,
"boosted_status": null,
"boost_unavailable_identifier": null,
"boost_unavailable_reason": null,
"user": {
"pk": "698772114",
"id": "698772114",
"aigm_account_label_info": {
"attribution_label_text": null,
"is_auto_detected": false,
"is_enabled": false,
"is_manually_enabled": false
},
"username": "kxkdgltnfv",
"full_name": "Kbsmpg Mmbtm",
"profile_pic_url": "https://cdn.esempio/d32p6rq42tx5d501.jpg",
"is_verified": false,
"is_embeds_disabled": false,
"is_private": false,
"is_unpublished": false,
"__typename": "CXPStkmJdmj",
"friendship_status": {
"following": false,
"is_feed_favorite": false
},
"show_account_transparency_details": true
},
"product_type": "clips",
"play_count": 2627,
"view_count": null,
"like_and_view_counts_disabled": false,
"comment_count": 17,
"like_count": 165,
"audience": null,
"clips_tab_pinned_user_ids": [
"698772114"
],
"media_type": 2,
"image_versions2": {
"candidates": [
{
"height": 1136,
"url": "https://cdn.esempio/50l2bxjp4tst3892.jpg",
"width": 640
},
{
"height": 852,
"url": "https://cdn.esempio/4715fr8t6r84577k.jpg",
"width": 480
},
{
"height": 568,
"url": "https://cdn.esempio/87zn65rv029026p5.jpg",
"width": 320
},
{
"height": 426,
"url": "https://cdn.esempio/5521592qb50882j4.jpg",
"width": 240
},
{
"height": 640,
"url": "https://cdn.esempio/98801w7005080jq5.jpg",
"width": 640
},
{
"height": 640,
"url": "https://cdn.esempio/98801w7005080jq5.jpg",
"width": 640
},
{
"height": 640,
"url": "https://cdn.esempio/98801w7005080jq5.jpg",
"width": 640
},
{
"height": 480,
"url": "https://cdn.esempio/ls06k590h48jcpq0.jpg",
"width": 480
},
{
"height": 320,
"url": "https://cdn.esempio/139f008x014qt028.jpg",
"width": 320
},
{
"height": 240,
"url": "https://cdn.esempio/2t6984740p1gh810.jpg",
"width": 240
},
{
"height": 150,
"url": "https://cdn.esempio/0v487068c81603r7.jpg",
"width": 150
}
]
},
"preview": null,
"original_height": 1920,
"original_width": 1080,
"ai_interactive_embodiment_attachment_style_info": null,
"coauthor_producers": [],
"is_fb_only": null,
"is_internal_only": null,
"logging_info_token": null,
"linked_media_playlist_data": null,
"can_viewer_reshare": true,
"ig_media_sharing_disabled": false,
"is_active_trial": false,
"is_in_profile_grid": false,
"is_short_drama": false,
"profile_grid_control_enabled": false,
"visibility": null,
"comments_disabled": null,
"feed_demotion_control": null,
"feed_recs_demotion_control": null,
"ai_label_info": null,
"inventory_source": null,
"longform_clip_metadata": null
},
"__typename": "WSBHmqjpNjnjLfrs"
},
"cursor": null
}
],
"page_info": {
"end_cursor": "HGBQBtF4QrhgxbVdTwdNqRdCl4Snp33dRr-34TWWZ7pQpd5jcNd1wKq3NJpTssZq1kXVrnrnmnQfBcQNtVWhRRnpbn",
"has_next_page": true
}
},
"id": "698772114"
},
"xdt_viewer": {
"user": {
"id": "646392312"
}
}
},
"extensions": {
"server_metadata": {
"request_start_time_ms": 7289753810004,
"time_at_flush_ms": 7584325505907
},
"is_final": true
}
}
}
@@ -0,0 +1,340 @@
{
"descrittore": {
"indirizzo": "https://sito.esempio/snj1xswxv2412473",
"host": "sito",
"stato": 200,
"tipo": "text/javascript",
"risorsa": "XHR",
"quando": "2026-11-12T16:33:18Z"
},
"corpo": {
"data": {
"xdt_api__v1__usertags__user_id__feed_connection": {
"edges": [
{
"node": {
"pk": "8478520837037116438",
"accessibility_caption": null,
"caption": {
"pk": "59312287886202482",
"text": "Lnbq Stv....."
},
"audience": null,
"carousel_media_count": null,
"display_uri": null,
"media_type": 1,
"carousel_media": null,
"image_versions2": {
"candidates": [
{
"height": 1440,
"url": "https://cdn.esempio/47m1d4nk3fzzrw47.webp",
"width": 1440
},
{
"height": 1080,
"url": "https://cdn.esempio/542f85ksz0wwrd14.webp",
"width": 1080
},
{
"height": 720,
"url": "https://cdn.esempio/72g28q69zs14br83.webp",
"width": 720
},
{
"height": 640,
"url": "https://cdn.esempio/wlsl50rm007mwvfh.webp",
"width": 640
},
{
"height": 480,
"url": "https://cdn.esempio/7jgz9m74qrc53pmv.webp",
"width": 480
},
{
"height": 320,
"url": "https://cdn.esempio/8n2450p41nc59746.webp",
"width": 320
},
{
"height": 240,
"url": "https://cdn.esempio/g44s38gt533290j6.webp",
"width": 240
},
{
"height": 1080,
"url": "https://cdn.esempio/542f85ksz0wwrd14.webp",
"width": 1080
},
{
"height": 750,
"url": "https://cdn.esempio/t05549866r95nkd3.webp",
"width": 750
},
{
"height": 640,
"url": "https://cdn.esempio/wlsl50rm007mwvfh.webp",
"width": 640
},
{
"height": 480,
"url": "https://cdn.esempio/7jgz9m74qrc53pmv.webp",
"width": 480
},
{
"height": 320,
"url": "https://cdn.esempio/8n2450p41nc59746.webp",
"width": 320
},
{
"height": 240,
"url": "https://cdn.esempio/g44s38gt533290j6.webp",
"width": 240
},
{
"height": 150,
"url": "https://cdn.esempio/vzr454psw0hvgs62.webp",
"width": 150
}
]
},
"code": "QvgM0hshks1",
"media_cropping_info": null,
"profile_grid_thumbnail_fitting_style": "GPJRV",
"media_overlay_info": null,
"preview": null,
"product_type": "feed",
"thumbnails": null,
"timeline_pinned_user_ids": [],
"upcoming_event": null,
"user": {
"pk": "5686070924",
"username": "djkbtgpcbxcgkx",
"id": "5686070924",
"aigm_account_label_info": {
"attribution_label_text": null,
"is_auto_detected": false,
"is_enabled": false,
"is_manually_enabled": false
},
"full_name": "Zxwqvc Hrlwtxhm",
"profile_pic_url": "https://cdn.esempio/6v8x5n150q46b93m.jpg",
"is_verified": false,
"is_embeds_disabled": false,
"is_private": false,
"is_unpublished": false,
"__typename": "CXPStkmJdmj",
"friendship_status": {
"following": false,
"is_feed_favorite": false
},
"show_account_transparency_details": true
},
"media_notes": {
"items": []
},
"like_count": 67,
"like_and_view_counts_disabled": false,
"boosted_status": null,
"boost_unavailable_identifier": null,
"boost_unavailable_reason": null,
"comment_count": 1,
"comments_disabled": null,
"view_count": null,
"linked_media_playlist_data": null,
"id": "3014245638444985467_6476577312",
"original_height": 1440,
"original_width": 1440,
"ai_interactive_embodiment_attachment_style_info": null,
"ai_label_info": null,
"coauthor_producers": [],
"longform_clip_metadata": null,
"longform_title": null,
"associated_clip_medias": null,
"is_fb_only": null,
"is_internal_only": null,
"logging_info_token": null,
"can_viewer_reshare": true,
"ig_media_sharing_disabled": false,
"is_active_trial": false,
"is_in_profile_grid": false,
"is_short_drama": null,
"profile_grid_control_enabled": false,
"visibility": null,
"feed_demotion_control": null,
"feed_recs_demotion_control": null,
"inventory_source": null,
"__typename": "BMZBnqqvMklz"
},
"cursor": null
},
{
"node": {
"pk": "4019896705567974389",
"accessibility_caption": null,
"caption": {
"pk": "82123710868938618",
"text": "vdmjnsmprqv t zplv sfrlz qqwjqt tdwtb nqlm"
},
"audience": null,
"carousel_media_count": null,
"display_uri": null,
"media_type": 2,
"carousel_media": null,
"image_versions2": {
"candidates": [
{
"height": 2000,
"url": "https://cdn.esempio/3v592vd846344921.jpg",
"width": 1125
},
{
"height": 1280,
"url": "https://cdn.esempio/1tl78vg0rd33456f.jpg",
"width": 720
},
{
"height": 1138,
"url": "https://cdn.esempio/71tbf928485z1590.jpg",
"width": 640
},
{
"height": 853,
"url": "https://cdn.esempio/1xl948624m77lz0f.jpg",
"width": 480
},
{
"height": 569,
"url": "https://cdn.esempio/z875h90h37k1j5s7.jpg",
"width": 320
},
{
"height": 427,
"url": "https://cdn.esempio/z3r64r8d24xt6lm0.jpg",
"width": 240
},
{
"height": 1080,
"url": "https://cdn.esempio/5087lz20558n7g0b.jpg",
"width": 1080
},
{
"height": 750,
"url": "https://cdn.esempio/r3202b5193252cc4.jpg",
"width": 750
},
{
"height": 640,
"url": "https://cdn.esempio/j7811s815v2q94gq.jpg",
"width": 640
},
{
"height": 480,
"url": "https://cdn.esempio/d6dcfp2332hs065k.jpg",
"width": 480
},
{
"height": 320,
"url": "https://cdn.esempio/13n5375644kww1g6.jpg",
"width": 320
},
{
"height": 240,
"url": "https://cdn.esempio/z4fqg8s49959xb44.jpg",
"width": 240
},
{
"height": 150,
"url": "https://cdn.esempio/1v362j993m9t1w31.jpg",
"width": 150
}
]
},
"code": "RttVHRFVLJJ",
"media_cropping_info": null,
"profile_grid_thumbnail_fitting_style": "GPJRV",
"media_overlay_info": null,
"preview": null,
"product_type": "clips",
"thumbnails": null,
"timeline_pinned_user_ids": [],
"upcoming_event": null,
"user": {
"pk": "37912186165",
"username": "xdmrhrhndhnpzwrf89",
"id": "37912186165",
"aigm_account_label_info": {
"attribution_label_text": null,
"is_auto_detected": false,
"is_enabled": false,
"is_manually_enabled": false
},
"full_name": "JFGNZFHZ BCQRWRMM ··",
"profile_pic_url": "https://cdn.esempio/w34z87909pdfb233.jpg",
"is_verified": false,
"is_embeds_disabled": true,
"is_private": false,
"is_unpublished": false,
"__typename": "CXPStkmJdmj",
"friendship_status": {
"following": false,
"is_feed_favorite": false
},
"show_account_transparency_details": true
},
"media_notes": {
"items": []
},
"like_count": 30,
"like_and_view_counts_disabled": false,
"boosted_status": null,
"boost_unavailable_identifier": null,
"boost_unavailable_reason": null,
"comment_count": 1,
"comments_disabled": null,
"view_count": null,
"linked_media_playlist_data": null,
"id": "3692311157337571127_46303362367",
"original_height": 1024,
"original_width": 576,
"ai_interactive_embodiment_attachment_style_info": null,
"ai_label_info": null,
"coauthor_producers": [],
"longform_clip_metadata": null,
"longform_title": null,
"associated_clip_medias": null,
"is_fb_only": null,
"is_internal_only": null,
"logging_info_token": null,
"can_viewer_reshare": true,
"ig_media_sharing_disabled": false,
"is_active_trial": false,
"is_in_profile_grid": false,
"is_short_drama": false,
"profile_grid_control_enabled": false,
"visibility": null,
"feed_demotion_control": null,
"feed_recs_demotion_control": null,
"inventory_source": null,
"__typename": "BMZBnqqvMklz"
},
"cursor": null
}
],
"page_info": {
"end_cursor": "1895218298366512371",
"has_next_page": true,
"has_previous_page": false,
"start_cursor": null
}
}
},
"extensions": {
"server_metadata": {
"request_start_time_ms": 2650933458999,
"time_at_flush_ms": 4309221142413
},
"is_final": true
}
}
}
@@ -0,0 +1,82 @@
{
"descrittore": {
"indirizzo": "https://sito.esempio/snj1xswxv2412473",
"host": "sito",
"stato": 200,
"tipo": "text/javascript",
"risorsa": "XHR",
"quando": "2026-11-12T16:33:09Z"
},
"corpo": {
"data": {
"highlights": {
"edges": [
{
"node": {
"id": "gcsntzngw:85938794130114635",
"title": "Fdkcvk ····",
"cover_media": {
"cropped_image_version": {
"url": "https://cdn.esempio/l0n86b82p1x964z1.jpg"
}
},
"user": {
"username": "kxkdgltnfv",
"id": "698772114"
},
"__typename": "TPQDqwpRcdx"
},
"cursor": ""
},
{
"node": {
"id": "hvbkgxgdl:22074358537544861",
"title": "Svsfdt ZRC ··",
"cover_media": {
"cropped_image_version": {
"url": "https://cdn.esempio/4988h47301902606.webp"
}
},
"user": {
"username": "kxkdgltnfv",
"id": "698772114"
},
"__typename": "TPQDqwpRcdx"
},
"cursor": ""
},
{
"node": {
"id": "jlcfdcbvn:63944417446934903",
"title": "Nzqv ··",
"cover_media": {
"cropped_image_version": {
"url": "https://cdn.esempio/7z444gb55718d975.webp"
}
},
"user": {
"username": "kxkdgltnfv",
"id": "698772114"
},
"__typename": "TPQDqwpRcdx"
},
"cursor": ""
}
],
"page_info": {
"end_cursor": null,
"has_next_page": false,
"has_previous_page": false,
"start_cursor": null
}
}
},
"extensions": {
"server_metadata": {
"request_start_time_ms": 6543923605463,
"time_at_flush_ms": 8252849124644
},
"is_final": true
}
}
}
@@ -0,0 +1,250 @@
{
"descrittore": {
"indirizzo": "https://sito.esempio/snj1xswxv2412473",
"host": "sito",
"stato": 200,
"tipo": "text/javascript",
"risorsa": "XHR",
"quando": "2026-11-12T16:33:49Z"
},
"corpo": {
"data": {
"xdt_api__v1__feed__reels_media": {
"reels_media": [
{
"id": "698772114",
"reel_type": "user_reel",
"items": [
{
"id": "2444284213587449350_230218833",
"original_height": 1920,
"original_width": 1080,
"image_versions2": {
"candidates": [
{
"url": "https://cdn.esempio/8t5rgxd6h81b00lj.jpg",
"height": 1136,
"width": 640
},
{
"url": "https://cdn.esempio/cr633998717jv12l.jpg",
"height": 852,
"width": 480
},
{
"url": "https://cdn.esempio/7m70b38ff2z62n0f.jpg",
"height": 568,
"width": 320
},
{
"url": "https://cdn.esempio/899c4c7j5m96zrb3.jpg",
"height": 426,
"width": 240
},
{
"url": "https://cdn.esempio/x4vmcm91r0d9b577.jpg",
"height": 640,
"width": 640
},
{
"url": "https://cdn.esempio/x4vmcm91r0d9b577.jpg",
"height": 640,
"width": 640
},
{
"url": "https://cdn.esempio/x4vmcm91r0d9b577.jpg",
"height": 640,
"width": 640
},
{
"url": "https://cdn.esempio/t9zjl61j31438295.jpg",
"height": 480,
"width": 480
},
{
"url": "https://cdn.esempio/6wl9706wv2976nkx.jpg",
"height": 320,
"width": 320
},
{
"url": "https://cdn.esempio/8kbzj8095w5p9346.jpg",
"height": 240,
"width": 240
},
{
"url": "https://cdn.esempio/2l1f6516j62nm421.jpg",
"height": 150,
"width": 150
}
]
},
"media_type": 2,
"taken_at": 1794463637,
"pk": "7512782704400749355",
"has_audio": true,
"story_music_stickers": [
{
"music_asset_info": {
"should_mute_audio": false,
"should_mute_audio_reason": "",
"title": "F.H.X.1.B.H.C.",
"display_artist": "Q6lwhxkkjhj"
},
"id": "1716996485815318"
}
],
"ai_label_info": null,
"carousel_media_count": null,
"carousel_media": null,
"code": "QcwPHMVpQKt",
"is_dash_eligible": 1,
"number_of_qualities": 4,
"video_dash_manifest": "<?xxx xxxxxxx=\"7.7\" xxxxxxxx=\"xxx-7\"?>\n<xxx xxxxx=\"xxx:xxxx:xxxx:xxxxxx:xxx:7777\" xxxxx:xxx=\"xxxx://xxx.x7.xxx/7777/xxxxxxxxx-xxxxxxxx\" xxx:xxxxxxxxxxxxxx=\"xxx:xxxx:xxxx:xxxxxx:xxx:7777 xxxx-xxx.xxx\" xxxxxxxx=\"xxx:xxxx:xxxx:xxxxxxx:xxxxx-xx-xxxxxx:7777\" xxxxxxxxxxxxx=\"xx7x\" xxxx=\"xxxxxx\" xxxxxxxxxxxxxxxxxxxxxxxxx=\"xx77.777777x\" xxxxxxxxxxxxxxxxxxx=\"7777777777\" xxxxxxxxxxxxxxxxxxxx=\"xxxxx77xxxxxx77xxxxxx7xxx7xxx7xxxxxxxx/xx7xx7x+7xx7xxxxxx7xxx7xx77x/xxxxxxxx7x+7xxx7xxxxxxxxxxxxx7xxxx7xxxxxxxxxxxxxx77xxxxxxxxxxxxxxxx7xxxxxxxxxxxxxxxxxxxxxxxxxx7xx7xxxxxxxxxxxxxx\"><xxxxxx xx=\"7\" xxxxxxxx=\"xx77.777777x\"><xxxxxxxxxxxxx xx=\"7\" xxxxxxxxxxx=\"xxxxx\" xxxxxxxxxxxxxxxxxxx=\"xxxx\" xxx=\"7:77\" xxxxxxxxxxxxxxxxxxxxxxxxxxxx=\"777:77\"><xxxxxxxxxxxxxx xx=\"77777777777777777x\" xxxxxxxxx=\"77777\" xxxxxx=\"xx77.77.77.77.77.77.77.77.77\" xxxxxxxx=\"xxxxx/xx7\" xxx=\"7:7\" xxxxxxxxxxxxx=\"xxxx_xx7-xxxxx-xxx7_777x\" xxxxxxxxxxxxxxx=\"777777\" xxxxxxxxxxxxxxxxxxxxxxx=\"7:777,777:77.7,777:77.7,777:77.7,7777:77.7\" xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=\"xxxx\" xxxxxxxxxxxxxxxxxxxxxxxxx=\"7:777,777:77,777:77.7,777:77.7,7777:77.7\" xxxxx=\"777\" xxxxxx=\"777\" xxxxxxxxx=\"77777/777\" xxxxxxxxxxxxxx=\"xx\" xxxxxxxxxxxxxx=\"777x\"><xxxxxxx>xxxxx://xxxxxxxx-xxx7-7.xxxxxxxxxxxx.xxx/x7/x/x7/x7/x777/xxxxxxxxxxxx7xxxxxx7xxxx7xxxx7x_xxxxxxxxxxxxxxxxxxxxx-xxxx-xxxxx7xx77x7xx7xxxxxxx7x7xxxx7xxxx7xxxx7x777xxxxxxx.xx7?_xx_xxx=777&xxx;_xx_xxx=7xx777&xxx;_xx_xx=xxxxxxxx-xxx7-7.xxxxxxxxxxxx.xxx&xxx;_xx_xxx=xx7xxx777xxx7xxxxxxx7xx&xxx;xxx=xxx7xx7xx7xxx7xxxxx7xxxxxxxxxxxxxxx7x7x7xxxxx7x7xxxxxxxxx7xxxxx7xxxxx7xxxxxxxxxxxxxxxxxxxxxxxxxxx7xxxxxxxxxxxxxxxxxxxxxxx7xxx7xxxx7xxxx7xxx7xxx7xxxxxxxxxxx7xxxxxxxxxxxxxxxxxxx7xxxxxxxxxxx7x7xxx7x7x7xxxxxxxxxxxxx7xxx7xxxxxxx7xxxxxxxxxxxxxxxxx7xxxxxxxxxxxxxxx7xxxxxxx7xxxxxxxxxxxxxxxxxxxxxxxxxxxx7xxxxxxxxxxxx7xxx7xxx7xxx7xxxxxxxxxxxxxx7xx7xxx7xxxxx7x7xxxx%7x%7x&xxx;xxx=77-7&xxx;_xx_xxx=xxxx-xxxxxxxxxxxxxx-xx&xxx;_xx_xx=7xxxx&xxx;_xx_xxx=xxxxxx_xxxxxxxxxx&xxx;_xx_xx=77&xxx;xx=77_xxxxxxxxxxxxx7xxxxxxxxx7xxxxx_xxxx7xxxxx7xxxxx&xxx;xx=7xxxx777</xxxxxxx><xxxxxxxxxxx xxxxxxxxxx=\"777-777\" xxxxxxxxx=\"77777\" xxxxxxxxxxxxxxxxxxxxxx=\"777-77777\" xxxxxxxxxxxxxxxxxxxxxxxxx=\"7777\" xxxxxxxxxxxxxxxxxxxxxx=\"777-77777\" xxxxxxxxxxxxxxxxxxx=\"777-77777\" xxxxxxxxxxxxxxxxxxxxxx=\"7777\" xxxxxxxxxxxxxxxxxxxx=\"77777-77777\" xxxxxxxxxxxxxxxxxxxxxx=\"777-77777\" xxxxxxxxxxxxxxxxxxxxxxxxx=\"7777\"><xxxxxxxxxxxxxx xxxxx=\"7-777\"/></xxxxxxxxxxx></xxxxxxxxxxxxxx><xxxxxxxxxxxxxx xx=\"77777777777777777x\" xxxxxxxxx=\"777777\" xxxxxx=\"xx77.77.77.77.77.77.77.77.77\" xxxxxxxx=\"xxxxx/xx7\" xxx=\"7:7\" xxxxxxxxxxxxx=\"xxxx_xx7-xxxxx-xxx7_777x\" xxxxxxxxxxxxxxx=\"777777\" xxxxxxxxxxxxxxxxxxxxxxx=\"7:777,777:77.7,777:77.7,777:77.7,7777:77.7\" xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=\"xxxx\" xxxxxxxxxxxxxxxxxxxxxxxxx=\"7:777,777:77,777:77.7,777:77.7,7777:77.7\" xxxxx=\"777\" xxxxxx=\"777\" xxxxxxxxx=\"77777/777\" xxxxxxxxxxxxxx=\"xx\" xxxxxxxxxxxxxx=\"777x\"><xxxxxxx>xxxxx://xxxxxxxx-xxx7-7.xxxxxxxxxxxx.xxx/x7/x/x7/x7/x777/xxxxxxx77xxxxxxxx77xx77xxxxxxxxxxxxx7x77xxxxxxx7x7xxxxxx7xx77xxxx7xx777xxxxx7xxxxx_xxxxxx7xxxxxxxxx777xxx7xxxx.xx7?_xx_xxx=777&xxx;_xx_xxx=7xx777&xxx;_xx_xx=xxxxxxxx-xxx7-7.xxxxxxxxxxxx.xxx&xxx;_xx_xxx=xxxxxx7xxx7x7xxxxxxx7x7&xxx;xxx=xxx7xx7xx7xxx7xxxxx7xxxxxxxxxxxxxxx7x7x7xxxxx7x7xxxxxxxxx7xxxxx7xxxxx7xxxxxxxxxxxxxxxxxxxxxxxxxxx7xxxxxxxxxxxxxxxxxxxxxxx7xxx7xxxx7xxxx7xxx7xxx7xxxxxxxxxxx7xxxxxxxxxxxxxxxxxxx7xxxxxxxxxxx7x7xxx7x7x7xxxxxxxxxxxxx7xxx7xxxxxxx7xxxxxxxxxxxxxxxxx7xxxxxxxxxxxxxxx7xxxxxxx7xxxxxxxxxxxxxxxxxxxxxxxxxxxx7xxxxxxxxxxxx7xxx7xxx7xxxxxxxxxxx7xxxxxx7xx777xxxxxxxxx7x7xx7%7x&xxx;xxx=77-7&xxx;_xx_xxx=xxxx-xxxxxxxxxxxxxx-xx&xxx;_xx_xx=7xxxx&xxx;_xx_xxx=xxxxxx_xxxxxxxxxx&xxx;_xx_xx=77&xxx;xx=77_xxxxx7x77xxxxxxxxx7xxx_xxxxxx77x-xx7xxxxxxxxxx&xxx;xx=7xxxx7xx</xxxxxxx><xxxxxxxxxxx xxxxxxxxxx=\"777-777\" xxxxxxxxx=\"77777\" xxxxxxxxxxxxxxxxxxxxxx=\"777-77777\" xxxxxxxxxxxxxxxxxxxxxxxxx=\"7777\" xxxxxxxxxxxxxxxxxxxxxx=\"777-77777\" xxxxxxxxxxxxxxxxxxx=\"777-77777\" xxxxxxxxxxxxxxxxxxxxxx=\"7777\" xxxxxxxxxxxxxxxxxxxx=\"77777-777777\" xxxxxxxxxxxxxxxxxxxxxx=\"777-77777\" xxxxxxxxxxxxxxxxxxxxxxxxx=\"7777\"><xxxxxxxxxxxxxx xxxxx=\"7-777\"/></xxxxxxxxxxx></xxxxxxxxxxxxxx><xxxxxxxxxxxxxx xx=\"77777777777777777x\" xxxxxxxxx=\"777777\" xxxxxx=\"xx77.77.77.77.77.77.77.77.77\" xxxxxxxx=\"xxxxx/xx7\" xxx=\"7:7\" xxxxxxxxxxxxx=\"xxxx_xx7-xxxxx-xxx7_777x\" xxxxxxxxxxxxxxx=\"777777\" xxxxxxxxxxxxxxxxxxxxxxx=\"7:777,777:77.7,777:77.7,777:77.7,7777:77\" xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=\"xxxx\" xxxxxxxxxxxxxxxxxxxxxxxxx=\"7:777,777:77.7,777:77.7,777:77.7,7777:77.7\" xxxxx=\"777\" xxxxxx=\"7777\" xxxxxxxxx=\"77777/777\" xxxxxxxxxxxxxx=\"xx\" xxxxxxxxxxxxxx=\"777x\"><xxxxxxx>xxxxx://xxxxxxxx-xxx7-7.xxxxxxxxxxxx.xxx/x7/x/x7/x7/x777/xxxx7xxxxxx77xxxxxx7xxxxx-xxxxxxxxx7xxxxxx7xxxxx-7xxxxx_xxxx_xxxxxxx7xxxxxxx7xxxxxxx7xxxxx77xxx7xxxx7xxxxxxxxx.xx7?_xx_xxx=777&xxxLine truncated
"video_versions": [
{
"type": 101,
"url": "https://cdn.esempio/82qwp380zbhgsx7z.mp4"
},
{
"type": 102,
"url": "https://cdn.esempio/82qwp380zbhgsx7z.mp4"
},
{
"type": 103,
"url": "https://cdn.esempio/82qwp380zbhgsx7z.mp4"
}
],
"visual_comment_reply_sticker_info": null,
"story_bloks_stickers": [
{
"x": 0.5,
"y": 0.5,
"width": 0.5,
"height": 0.5,
"rotation": 0,
"bloks_sticker": {
"sticker_data": {
"ig_mention": {
"full_name": "Cwbgfmxf Wbqvpc Cfmx 6438",
"username": "bcczmfkbkxhkknxfvc0256"
}
},
"id": "pgpfd_mctghmv_dq"
},
"id": "44801441261212653"
}
],
"story_link_stickers": null,
"story_hashtags": null,
"story_locations": null,
"story_bloks_tappables": null,
"story_feed_media": null,
"text_post_share_to_ig_story_stickers": null,
"story_countdowns": null,
"story_questions": null,
"story_sliders": null,
"link": null,
"reel_media_background": null,
"video_duration": 17.166,
"custom_list_info": null,
"is_story_edited": false,
"horizon_attribution_info": null,
"product_type": "story",
"reshared_story_media_author": {
"profile_pic_url": "https://cdn.esempio/4n274j7tz59wttc2.jpg",
"username": "bcczmfkbkxhkknxfvc0256",
"id": "01488147319"
},
"story_app_attribution": null,
"has_translation": false,
"can_see_insights_as_brand": false,
"user": {
"instagram_pk": "698772114",
"pk": "698772114",
"id": "698772114",
"is_ai_user": null,
"aigm_account_label_info": {
"is_enabled": false
},
"interop_messaging_user_fbid": "031414542632368"
},
"audience": null,
"has_liked": false,
"viewer_count": null,
"viewers": [],
"can_reshare": true,
"__typename": "BMZBnqqvMklz",
"inventory_source": null,
"media_overlay_info": null,
"caption": null,
"accessibility_caption": null,
"organic_tracking_token": "xxx7xxxxxx7xxxx7xxxxxxxxx7xxxxx7xxxxx7xxxxx7xxxxx777xxxxx7xxxxx7xxxxxxx7xxxxxxxxx7xxxxxxxxxxxxxxxx77xxxxxxx7xxxxxxxxxxxxxxx7xxx7xxxxxxx7xxx7xxx7xxx7xxxxxxxxxxxxxxxxxx77x7xxxxx7xxx7xxx7xxxxxxx7xxx7xxxxxxx7xxx7xxx7xxx7xxxxxxx7xxxxxxxxxxx7xxxxx7xxxxxxxxxxxxx7xxx7xxx7xxxxxxxxxxxxxxxxxxx7xxxxxxxxxxx7xxxxxxx7xxxxxxx7xxxxxxxxxxx7xxxxxxxxxxx7xxxxxxxxxx··",
"story_cta": null,
"preview": null,
"expiring_at": 1794550037,
"is_paid_partnership": false,
"sponsor_tags": null,
"wearable_attribution_info": null,
"boosted_status": null,
"boost_unavailable_identifier": null,
"boost_unavailable_reason": null,
"can_viewer_reshare": null,
"ig_media_sharing_disabled": false,
"sharing_friction_info": {
"should_have_sharing_friction": false,
"bloks_app_url": null
},
"can_reply": true
}
],
"user": {
"pk": "698772114",
"id": "698772114",
"username": "kxkdgltnfv",
"__typename": "CXPStkmJdmj",
"friendship_status": {
"following": false
},
"interop_messaging_user_fbid": "031414542632368",
"user_id": "698772114",
"profile_pic_url": "https://cdn.esempio/ncd3288d27t03sw4.jpg",
"is_private": false,
"is_verified": false,
"aigm_account_label_info": {
"attribution_label_text": null,
"is_auto_detected": false,
"is_enabled": false,
"is_manually_enabled": false
},
"transparency_label": null,
"transparency_product": null,
"transparency_product_enabled": false
},
"seen": 0,
"cover_media": null,
"title": null,
"can_reshare": true,
"latest_reel_media": 1794463637,
"muted": null
}
],
"unviewable_authors_infos": []
},
"xdt_viewer": {
"user": {
"id": "646392312",
"pk": "646392312",
"user_id": "646392312",
"can_see_organic_insights": true
}
}
},
"extensions": {
"server_metadata": {
"request_start_time_ms": 3412905948341,
"time_at_flush_ms": 2394018701715
},
"is_final": true
}
}
}
@@ -0,0 +1,164 @@
{
"descrittore": {
"indirizzo": "https://sito.esempio/hj8fxfbdww657301",
"host": "sito",
"stato": 200,
"tipo": "text/html",
"risorsa": "Document",
"quando": "2026-11-12T16:32:50Z"
},
"corpo": {
"require": [
[
"SbmbpmbgdPjwwpxSW",
"ltbqsr",
null,
[
{
"__bbox": {
"require": [
[
"XbgrnPjtzlsgbvjDlhwrbNdncf",
"glfk",
[],
[
"dgl_CrbztkcDlwcnngH4ThtwRlkzzxrprVwcxhDwqxvLbvwjsdmw_1lj3rx07j32hn7109833494",
{
"__bbox": {
"complete": true,
"result": {
"data": {
"xdt_api__v1__feed__reels_tray": {
"broadcasts": [],
"tray": [
{
"id": "046680203",
"reel_type": "user_reel",
"has_besties_media": false,
"latest_besties_reel_media": 0,
"muted": false,
"latest_reel_media": 1794493625,
"seen": 0,
"expiring_at": 1794580025,
"ranked_position": 1,
"seen_ranked_position": 1,
"user": {
"pk": "046680203",
"username": "jbrmqr_bngbcqr",
"live_broadcast_visibility": null,
"live_broadcast_id": null,
"profile_pic_url": "https://cdn.esempio/23402xp0qgzpzgt3.jpg",
"is_unpublished": false,
"id": "046680203",
"hd_profile_pic_url_info": {
"url": "https://cdn.esempio/93m8s0986129c3rk.jpg"
},
"latest_reel_media": 1794493625,
"reel_media_seen_timestamp": null
},
"latest_wearables_reel_media_long": 0,
"unseen_wearables_media_igids": [],
"__typename": "TPQDqwpRcdx"
},
{
"id": "45615316107",
"reel_type": "user_reel",
"has_besties_media": false,
"latest_besties_reel_media": 0,
"muted": false,
"latest_reel_media": 1794498177,
"seen": 3431947395,
"expiring_at": 1794584577,
"ranked_position": 2,
"seen_ranked_position": 2,
"user": {
"pk": "45615316107",
"username": "cmkbcgwntkpdfc0",
"live_broadcast_visibility": null,
"live_broadcast_id": null,
"profile_pic_url": "https://cdn.esempio/fn4d2918js8j1fx4.jpg",
"is_unpublished": false,
"id": "45615316107",
"hd_profile_pic_url_info": {
"url": "https://cdn.esempio/f909q8c6x22ld9z7.jpg"
},
"latest_reel_media": 1794498177,
"reel_media_seen_timestamp": null
},
"latest_wearables_reel_media_long": 0,
"unseen_wearables_media_igids": [],
"__typename": "TPQDqwpRcdx"
},
{
"id": "44636574028",
"reel_type": "user_reel",
"has_besties_media": false,
"latest_besties_reel_media": 0,
"muted": false,
"latest_reel_media": 1794476979,
"seen": 0,
"expiring_at": 1794563379,
"ranked_position": 3,
"seen_ranked_position": 3,
"user": {
"pk": "44636574028",
"username": "jxvrnpj",
"live_broadcast_visibility": null,
"live_broadcast_id": null,
"profile_pic_url": "https://cdn.esempio/7r88gb3557105774.jpg",
"is_unpublished": false,
"id": "44636574028",
"hd_profile_pic_url_info": {
"url": "https://cdn.esempio/344612471059mf6d.jpg"
},
"latest_reel_media": 1794476979,
"reel_media_seen_timestamp": null
},
"latest_wearables_reel_media_long": 0,
"unseen_wearables_media_igids": [],
"__typename": "TPQDqwpRcdx"
}
]
},
"xdt_viewer": {
"user": {
"username": "jzbp_zlqtz",
"id": "646392312",
"profile_pic_url": "https://cdn.esempio/1zgvfw0541f0bj75.jpg"
}
}
},
"extensions": {
"is_final": true
}
},
"sequence_number": 0
}
}
]
],
[
"PkzjzPwxlhbglCrqzzzjzc",
"ktbqmndzStdwZlnGphnrx",
null,
[
[
"XwBxRwN",
"1TPXJ·S"
]
]
]
]
}
},
{
"__bbox": null
},
{
"__bbox": null
}
]
]
]
}
}
File diff suppressed because it is too large. Load diff
@@ -30,6 +30,17 @@ Il percorso è quello di specifica §14.5:
Da un nuovo file HAR i grezzi si ricavano con `febe-sonda da-har` (stesso formato, stessi nomi dei file), poi si Da un nuovo file HAR i grezzi si ricavano con `febe-sonda da-har` (stesso formato, stessi nomi dei file), poi si
procede dal punto 2. procede dal punto 2.
### Il secondo HAR (12 novembre 2026)
Alberto ha esportato un secondo HAR, questa volta **senza filtro** (documenti compresi), seguendo la parte A ter di
`docs/prove-dal-vivo.md`: pagina iniziale, ricerca, un profilo aperto cliccando, le sue schede, le raccolte, una storia.
Fuori dal repository: `febe-sonda da-har` (142 campioni grezzi), `febe-sonda ripulisci` e `febe-sonda verifica` →
«Verifica superata» su tutti i 142. I file da `000009` a `000016` vengono da qui, con una differenza rispetto al primo
giro: gli elenchi lunghi sono stati accorciati **sulla copia ripulita** (già verificata), non sui grezzi, così i grezzi
non si aprono nemmeno per accorciarli. Togliere elementi da una copia verificata non può aggiungere valori dei grezzi.
Questi otto file vengono da un'altra esecuzione della ripulitura: i loro valori finti non corrispondono a quelli dei
file da `000001` a `000008`.
## Che cosa resta e che cosa no ## Che cosa resta e che cosa no
Struttura, chiavi, booleani, `null`, dimensioni, durate, conteggi, codici di tipo e date restano come sono (elenco Struttura, chiavi, booleani, `null`, dimensioni, durate, conteggi, codici di tipo e date restano come sono (elenco
@@ -52,6 +63,14 @@ forme, dimensioni, date e conteggi, mai i valori.
| `000006-raccolta-in-evidenza` | `PolarisStoriesV3HighlightsPageQuery` | `text/javascript` | pagina delle raccolte in evidenza (2 × 4) e l'account collegato, con il solo identificativo | | `000006-raccolta-in-evidenza` | `PolarisStoriesV3HighlightsPageQuery` | `text/javascript` | pagina delle raccolte in evidenza (2 × 4) e l'account collegato, con il solo identificativo |
| `000007-raccolta-pagina-successiva` | `PolarisStoriesV3HighlightsPagePaginationQuery` | `text/javascript` | pagina successiva delle raccolte (1 × 3) | | `000007-raccolta-pagina-successiva` | `PolarisStoriesV3HighlightsPagePaginationQuery` | `text/javascript` | pagina successiva delle raccolte (1 × 3) |
| `000008-storia-vista` | `PolarisStoriesV3SeenMutation` | `text/javascript` | la pagina segna una storia come vista: nessun dato (risposta estranea, ignorata) | | `000008-storia-vista` | `PolarisStoriesV3SeenMutation` | `text/javascript` | la pagina segna una storia come vista: nessun dato (risposta estranea, ignorata) |
| `000009-scheda-profilo` | `PolarisProfilePageContentQuery` | `text/javascript` | intestazione di un profilo: nome, foto grande, privato o no, seguito o no, numero dei post (`media_count`) |
| `000010-post-del-profilo` | `PolarisProfilePostsQuery` | `text/javascript` | griglia dei post del profilo, reel compresi (2 di 12: un reel e una serie di 6 foto) e il cursore della pagina successiva |
| `000011-reel-del-profilo` | `PolarisProfileReelsTabContentQuery` | `text/javascript` | scheda Reel (2 di 12): anteprime senza data né video, non sono contenuti |
| `000012-con-tag` | `PolarisProfileTaggedTabContentQuery` | `text/javascript` | scheda Con tag (2 di 12: una foto e un reel): anteprime, come la scheda Reel |
| `000013-raccolte-del-profilo` | `PolarisProfileStoryHighlightsTrayContentQuery` | `text/javascript` | elenco delle raccolte in evidenza del profilo (3 di 9): titolo e copertina, senza contenuti |
| `000014-storie-di-un-profilo` | `PolarisStoriesV3ReelPageStandaloneQuery` | `text/javascript` | le storie attive di un profilo (una, video) con scadenza e durata |
| `000015-vassoio-storie` | blocco incorporato nella pagina iniziale | `text/html` | vassoio delle storie (`xdt_api__v1__feed__reels_tray`, 3 di 120): chi ha storie attive e quando è uscita l'ultima; `xdt_viewer.user` con nome e foto dell'account collegato |
| `000016-serie-con-video` | `PolarisProfilePostsQuery` | `text/javascript` | la stessa risposta di `000010`, un altro post: una serie di 20 figli, il tredicesimo un video |
Le operazioni GraphQL (le righe con un nome) arrivano con il tipo `text/javascript`, non `application/json`: la Le operazioni GraphQL (le righe con un nome) arrivano con il tipo `text/javascript`, non `application/json`: la
cattura le legge lo stesso (`src/Febe.Core/Collection/DataResponses.cs`). cattura le legge lo stesso (`src/Febe.Core/Collection/DataResponses.cs`).
+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 };
} }
} }
+21 -1
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)}");
@@ -222,7 +242,7 @@ static int Verify(string[] args)
foreach (var leak in report.Leaks) foreach (var leak in report.Leaks)
{ {
// Where, never what: the value itself stays on this machine. // Where, never what: the value itself stays on this machine.
Console.WriteLine($"Sopravvive un frammento di {leak.Length} {leak.Kind} in {leak.CleanFile}."); 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."); Console.WriteLine(report.Passed ? "Verifica superata: nessun valore dei grezzi sopravvive fuori dall'elenco ammesso." : "Verifica NON superata.");
+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();
+11 -2
View File
@@ -32,7 +32,8 @@ public sealed partial class SampleSanitizer
/// File extensions an address may keep. Only known file types: the last segment of a page address may be a user /// File extensions an address may keep. Only known file types: the last segment of a page address may be a user
/// name with a dot («nome.cognome»), and its «extension» would leak part of it. /// name with a dot («nome.cognome»), and its «extension» would leak part of it.
/// </summary> /// </summary>
private static readonly HashSet<string> FileExtensions = new(StringComparer.Ordinal) /// <summary>File extensions a fake address keeps (the only part of a real address that survives).</summary>
internal static readonly HashSet<string> FileExtensions = new(StringComparer.Ordinal)
{ {
"jpg", "jpeg", "png", "webp", "heic", "heif", "gif", "avif", "mp4", "m4v", "mov", "webm", "m4a", "mp3", "aac", "jpg", "jpeg", "png", "webp", "heic", "heif", "gif", "avif", "mp4", "m4v", "mov", "webm", "m4a", "mp3", "aac",
"m3u8", "mpd", "ts", "json", "js", "css", "html", "htm", "txt", "xml", "svg", "ico", "woff", "woff2", "m3u8", "mpd", "ts", "json", "js", "css", "html", "htm", "txt", "xml", "svg", "ico", "woff", "woff2",
@@ -216,7 +217,15 @@ public sealed partial class SampleSanitizer
private string FakeNumber(string raw) private string FakeNumber(string raw)
{ {
var fake = Fake(raw, "n"); // Only the digits are faked: sign, point and exponent («1.5e+21») stay as they are, or the fake is not a number.
var faked = Fake(raw, "n");
var fake = string.Create(raw.Length, (raw, faked), static (span, pair) =>
{
for (var i = 0; i < span.Length; i++)
{
span[i] = char.IsAsciiDigit(pair.raw[i]) ? pair.faked[i] : pair.raw[i];
}
});
// A JSON number must not start with 0 (except «0.x»): keep the first digit non-zero. // A JSON number must not start with 0 (except «0.x»): keep the first digit non-zero.
var first = -1; var first = -1;
+29 -13
View File
@@ -1,4 +1,3 @@
using System.Text;
using System.Text.Json; using System.Text.Json;
namespace Febe.Sonda; namespace Febe.Sonda;
@@ -7,7 +6,11 @@ namespace Febe.Sonda;
/// <param name="CleanFile">Cleaned file (relative path) where a raw piece survives.</param> /// <param name="CleanFile">Cleaned file (relative path) where a raw piece survives.</param>
/// <param name="Length">Length of the surviving piece.</param> /// <param name="Length">Length of the surviving piece.</param>
/// <param name="Kind">«lettere» or «cifre».</param> /// <param name="Kind">«lettere» or «cifre».</param>
public sealed record SampleLeak(string CleanFile, int Length, string Kind); /// <param name="Key">
/// The key the piece sits under in the cleaned file when it is a key of the structure (copied from the raw samples on
/// purpose, so it tells nothing); «(chiave di dati)» when the key itself is data, «(radice)» at the top.
/// </param>
public sealed record SampleLeak(string CleanFile, int Length, string Kind, string Key = "(radice)");
/// <summary>Result of the verification of cleaned samples.</summary> /// <summary>Result of the verification of cleaned samples.</summary>
public sealed record VerifyReport(int RawFiles, int CleanFiles, int CheckedTokens, IReadOnlyList<SampleLeak> Leaks, IReadOnlyList<string> MissingCleanFiles) public sealed record VerifyReport(int RawFiles, int CleanFiles, int CheckedTokens, IReadOnlyList<SampleLeak> Leaks, IReadOnlyList<string> MissingCleanFiles)
@@ -21,6 +24,9 @@ public sealed record VerifyReport(int RawFiles, int CleanFiles, int CheckedToken
/// </summary> /// </summary>
public static class SampleVerifier public static class SampleVerifier
{ {
/// <summary>The key reported for a data key and for what sits under it: no allowlist rule matches it.</summary>
private const string DataKey = "(chiave di dati)";
public static VerifyReport Verify(string rawFolder, string cleanFolder, SanitizerAllowlist? allowlist = null) public static VerifyReport Verify(string rawFolder, string cleanFolder, SanitizerAllowlist? allowlist = null)
{ {
var raw = Path.GetFullPath(rawFolder); var raw = Path.GetFullPath(rawFolder);
@@ -42,19 +48,27 @@ public static class SampleVerifier
var leaks = new List<SampleLeak>(); var leaks = new List<SampleLeak>();
foreach (var file in cleanFiles) foreach (var file in cleanFiles)
{ {
var atoms = new StringBuilder(); var atoms = new List<(string Text, string Key, bool Number)>();
foreach (var text in Documents(file)) foreach (var text in Documents(file))
{ {
using var document = JsonDocument.Parse(text, new JsonDocumentOptions { MaxDepth = 256 }); using var document = JsonDocument.Parse(text, new JsonDocumentOptions { MaxDepth = 256 });
Atoms(document.RootElement, atoms, 0); Atoms(document.RootElement, atoms, "(radice)", 0);
} }
var haystack = atoms.ToString().ToLowerInvariant(); // Values the allowlist keeps on purpose (a media type, a date, a size) are not searched: their own tokens are
// allowed already, and a short token of someone else's text that happens to sit inside one («script» in
// «text/javascript», five digits inside a ten-digit date) is a coincidence, not a leak.
atoms.RemoveAll(a => a.Number ? tokens.Allowlist.KeepsNumber(a.Key) : tokens.Allowlist.KeepsString(a.Key, a.Text));
// Separated so that tokens cannot span two atoms.
var haystack = string.Join('\u0001', atoms.Select(a => a.Text)).ToLowerInvariant();
foreach (var token in sensitive) foreach (var token in sensitive)
{ {
if (haystack.Contains(token, StringComparison.Ordinal)) if (haystack.Contains(token, StringComparison.Ordinal))
{ {
leaks.Add(new SampleLeak(Path.GetRelativePath(clean, file), token.Length, token.Any(char.IsLetter) ? "lettere" : "cifre")); // The same comparison as the haystack: OrdinalIgnoreCase folds some letters differently (KELVIN SIGN).
var key = atoms.Where(a => a.Text.ToLowerInvariant().Contains(token, StringComparison.Ordinal)).Select(a => a.Key).FirstOrDefault() ?? "(radice)";
leaks.Add(new SampleLeak(Path.GetRelativePath(clean, file), token.Length, token.Any(char.IsLetter) ? "lettere" : "cifre", key));
} }
} }
} }
@@ -71,7 +85,7 @@ public static class SampleVerifier
/// Every value and every data key of a cleaned document, separated so that tokens cannot span two of them. /// Every value and every data key of a cleaned document, separated so that tokens cannot span two of them.
/// Ordinary keys are structure, copied from the raw samples on purpose: they are not looked at. /// Ordinary keys are structure, copied from the raw samples on purpose: they are not looked at.
/// </summary> /// </summary>
private static void Atoms(JsonElement element, StringBuilder sb, int depth) private static void Atoms(JsonElement element, List<(string Text, string Key, bool Number)> atoms, string key, int depth)
{ {
if (depth > 256) if (depth > 256)
{ {
@@ -83,27 +97,29 @@ public static class SampleVerifier
case JsonValueKind.Object: case JsonValueKind.Object:
foreach (var property in element.EnumerateObject()) foreach (var property in element.EnumerateObject())
{ {
if (SensitiveTokens.IsDataKey(property.Name)) var dataKey = SensitiveTokens.IsDataKey(property.Name);
if (dataKey)
{ {
sb.Append(property.Name).Append('\u0001'); // Never under its parent's rule: the sanitizer fakes every data key, so none may be skipped below.
atoms.Add((property.Name, DataKey, false));
} }
Atoms(property.Value, sb, depth + 1); Atoms(property.Value, atoms, dataKey ? DataKey : property.Name, depth + 1);
} }
break; break;
case JsonValueKind.Array: case JsonValueKind.Array:
foreach (var item in element.EnumerateArray()) foreach (var item in element.EnumerateArray())
{ {
Atoms(item, sb, depth + 1); Atoms(item, atoms, key, depth + 1);
} }
break; break;
case JsonValueKind.String: case JsonValueKind.String:
sb.Append(element.GetString()).Append('\u0001'); atoms.Add((element.GetString() ?? string.Empty, key, false));
break; break;
case JsonValueKind.Number: case JsonValueKind.Number:
sb.Append(element.GetRawText()).Append('\u0001'); atoms.Add((element.GetRawText(), key, true));
break; break;
} }
} }
+6 -2
View File
@@ -11,8 +11,12 @@ namespace Febe.Sonda;
/// </summary> /// </summary>
public sealed class SensitiveTokens public sealed class SensitiveTokens
{ {
/// <summary>Words of address structure that the cleaned samples write themselves.</summary> /// <summary>
private static readonly string[] AddressWords = ["http", "https", "www", "html", "json", "jpeg", "webp", "heic", "esempio"]; /// Words of address structure that the cleaned samples write themselves: scheme, the fake hosts
/// «https://{sito|cdn|altro}.esempio/» and the file extensions a fake address keeps.
/// </summary>
private static readonly string[] AddressWords =
["http", "https", "www", "esempio", "sito", "altro", .. SampleSanitizer.FileExtensions];
private readonly HashSet<string> _tokens = new(StringComparer.Ordinal); private readonly HashSet<string> _tokens = new(StringComparer.Ordinal);
private readonly HashSet<string> _excluded = new(StringComparer.Ordinal); private readonly HashSet<string> _excluded = new(StringComparer.Ordinal);