diff --git a/CLAUDE.md b/CLAUDE.md index c5f2acf..4a14b28 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -16,7 +16,7 @@ All'inizio di ogni sessione leggi docs/stato.md. 1. IMPORTANTE: non contattare mai Instagram da prove, script o verifiche tue. Si usa solo tools/Febe.SitoDiProva. Le prove dal vivo le lancia Alberto. 2. Non aprire i campioni grezzi della sonda: stanno fuori dal repository e contengono dati di altre persone. Si lavora sulle copie ripulite di tests/campioni. 3. Verso Instagram parla solo il browser di Febe. Nessun HttpClient verso domini di Instagram o Meta, tranne il CDN alle condizioni di §6.5. -4. Il browser si usa così com'è: nessuna modifica di user agent, impronta, intestazioni; niente headless, stealth, proxy, più account. Comandi CDP solo dall'elenco di §6.1. +4. Il browser si usa così com'è: nessuna modifica di user agent, impronta, intestazioni; niente headless, stealth, proxy, più account. Comandi CDP solo dall'elenco di §6.1. Unica eccezione: la pagina chiede i dati agli indirizzi di `richieste..json`, uno per volta e con il permesso del Governatore (§2 regola 2, §6.1). 5. CAPTCHA, verifiche e codici non si risolvono mai in automatico: Febe si ferma e avvisa. 6. Sola lettura (niente mi piace, segui, commenti, messaggi) e solo ciò che l'account di Alberto vede già. 7. Un account, un motore. I cookie non si copiano da una macchina all'altra. diff --git a/docs/SPECIFICA.md b/docs/SPECIFICA.md index 1be67a7..b7c1187 100644 --- a/docs/SPECIFICA.md +++ b/docs/SPECIFICA.md @@ -69,6 +69,8 @@ L'idea che regge tutto il progetto: Ne discendono tre conseguenze. Il browser è quello che dichiara di essere, quindi non c'è nulla da falsificare. Non ci sono indirizzi interni o identificativi di interrogazione da inseguire a ogni modifica del sito: quando Instagram cambia, cambiano solo i lettori delle risposte (§6.4) e la mappa dei bersagli (§6.3). E Febe è più lento di uno scaricatore diretto: è voluto. +**Correzione del 12 novembre 2026 (decisione di Alberto, issue #34).** La prima prova dal vivo ha mostrato che muovere la pagina come una persona non basta: le ricette dipendono da bersagli che si scoprono solo su Instagram, e nessuno era stato raccolto. Da qui l'unica eccezione della regola 2: **la pagina chiede i dati.** Il browser resta quello vero, con l'accesso fatto a mano da Alberto, e chiede al sito gli stessi dati che chiede la sua applicazione web, con il ritmo e i tetti del Governatore. Il prezzo è quello che la frase qui sopra evitava: gli indirizzi e gli identificativi delle interrogazioni vanno seguiti quando il sito cambia (`richieste..json`, scritto da campioni reali), e la traccia sul sito non è più identica a quella di una visita. + --- ## 2. Regole che valgono sempre @@ -77,9 +79,10 @@ Queste regole prevalgono su qualunque altra indicazione del documento e su qualu 1. **Verso Instagram parla solo il browser di Febe.** Nessun'altra parte del programma apre connessioni verso domini di Instagram o Meta. Unica eccezione ammessa: lo scaricamento dei file già indicati dalla pagina, dai soli domini del CDN, alle condizioni di §6.5. 2. **Il browser si usa così com'è.** Vietati: plugin o correzioni «stealth», modifiche di user agent, impronta, fuso orario o lingua dichiarati, script che alterano le proprietà del navigatore, modalità senza interfaccia (headless), intestazioni aggiunte o riscritte, richieste costruite a mano verso gli indirizzi interni del sito, emulazione dell'app mobile. Vietati anche proxy, rotazione di indirizzi IP e uso di più account per dividere il carico. Se Instagram tratta comunque Febe come automatico, la risposta è rallentare o fermarsi, mai aggiungere accorgimenti. + **Unica eccezione (decisione di Alberto del 12 novembre 2026, issue #34): la pagina chiede i dati.** Dalla pagina di Instagram già aperta e collegata, Febe può chiedere al sito gli stessi dati che chiede la sua applicazione web (profilo, post, storie, raccolte, seguiti, ricerca), con le stesse richieste e le stesse intestazioni che la pagina usa da sé. Solo verso gli indirizzi scritti in `richieste..json`, ricavati da campioni reali (regola 10), solo in lettura, una richiesta per volta e ciascuna con il permesso del Governatore (regola 7). Le richieste partono dalla pagina, con i cookie che il browser vi mette da sé: nessun programma fuori dal browser, nessun cookie letto o copiato, nessuna intestazione che la pagina non mandi già. I dettagli in §6.1; le ricette riscritte su queste richieste (§6.3) e la loro categoria nel Governatore (§7.4) si scrivono con l'issue #36, sui campioni. 3. **Niente scavalcamenti.** CAPTCHA, verifiche d'identità, codici in due passaggi e pagine di controllo non si risolvono mai in automatico. Febe si ferma, avvisa, e Alberto le completa a mano nel browser. 4. **Un account, una rete, un motore.** Una sola sessione Instagram per istanza e un solo motore attivo per quell'account. La sessione nasce e resta nel browser di quell'istanza: i cookie non si copiano mai da una macchina all'altra. -5. **Sola lettura.** Febe non mette «mi piace», non segue, non commenta, non scrive messaggi, non reagisce alle storie, non tocca annunci né suggerimenti. L'unica traccia che lascia è quella di una normale visita, compresa la visualizzazione delle storie (§6.3). +5. **Sola lettura.** Febe non mette «mi piace», non segue, non commenta, non scrive messaggi, non reagisce alle storie, non tocca annunci né suggerimenti. L'unica traccia che lascia è quella di una normale visita, compresa la visualizzazione delle storie (§6.3), più le richieste di dati dell'eccezione della regola 2, che sono richieste di lettura come quelle della pagina ma non sono una visita. 6. **Solo ciò che l'account di Alberto vede già.** Profili pubblici e profili privati che lo hanno accettato tra i follower. Un profilo privato non seguito non si tocca. 7. **Ogni azione del motore passa dal Governatore** (§7.4). Non esiste un percorso di codice con cui il programma carichi una pagina di Instagram o vi compia un gesto senza averne ottenuto il permesso, nemmeno per i comandi manuali. Non sono azioni del motore le pagine che Alberto apre usando lui il browser (accesso, verifiche, sonda di M0): in quei momenti il motore è fermo. 8. **Al primo segnale ci si ferma** (§7.6). Nessun nuovo tentativo automatico dopo una richiesta di verifica o una disconnessione. @@ -319,10 +322,19 @@ public interface IRandomSource { double NextDouble(); } | Scaricare i file | `Network.loadNetworkResource` (richiede l'identificativo del frame), `IO.read`, `IO.close` | | Vista remota e anteprima | `Page.startScreencast`, `Page.screencastFrameAck`, `Page.stopScreencast`, `Page.captureScreenshot` | | Controllare il collegamento | `Network.getCookies`, solo per sapere se il cookie di sessione esiste: il valore non si legge né si registra | +| Chiedere i dati alla pagina (regola 2, eccezione) | `Runtime.evaluate` con `awaitPromise`, che esegue nella pagina un `fetch` verso un indirizzo di `richieste..json` e ne restituisce il corpo | **Provato in locale**: gli eventi della rotella inviati con `Input.dispatchMouseEvent` sono eventi veri e fanno scorrere la pagina; `Page.startScreencast` consegna i fotogrammi; `Network.loadNetworkResource` con `IO.read` ha scaricato integro un file di 40 MB. -Vietati, in coerenza con la regola 2: `Network.setUserAgentOverride`, tutto il dominio `Emulation`, `Network.setExtraHTTPHeaders`, `Page.addScriptToEvaluateOnNewDocument`, il dominio `Fetch`, `Runtime.evaluate` usato per scorrere, cliccare o modificare la pagina. I gesti passano sempre da `Input`. Se una voce di §6.6 non si risolve senza uno di questi, non aggiungerlo da solo: scrivi l'esito e chiedi ad Alberto. +**Richieste della pagina.** Le regole del `fetch` della riga «Chiedere i dati alla pagina»: + +- l'indirizzo, il metodo, i nomi dei parametri e delle intestazioni vengono da un modello di `richieste..json`; Febe vi mette solo i valori del caso (nome o identificativo dell'account, cursore della pagina successiva, testo cercato). Un indirizzo che non è nel file non si chiede, e il file si scrive solo da campioni reali (regola 10), ricavati con `febe-sonda richieste` (§14.5); +- i valori delle intestazioni che servono al sito (per esempio il gettone contro le richieste contraffatte) si leggono nella pagina, dove la pagina stessa li tiene, al momento della richiesta, e non escono dalla pagina: allo script torna solo il corpo della risposta; +- solo richieste di lettura: nessuna operazione che cambi qualcosa, anche se il sito la chiamasse con lo stesso metodo; +- una richiesta per volta, ciascuna un'azione del motore con il permesso del Governatore e il suo tetto (§7.4); la risposta passa ai lettori come quelle catturate (§6.2) e porta gli stessi segnali di arresto (§7.6); +- il testo dello script, i valori e la risposta non si registrano mai: il client CDP scrive solo «Runtime.evaluate». + +Vietati, in coerenza con la regola 2: `Network.setUserAgentOverride`, tutto il dominio `Emulation`, `Network.setExtraHTTPHeaders`, `Page.addScriptToEvaluateOnNewDocument`, il dominio `Fetch`, `Runtime.evaluate` usato per scorrere, cliccare o modificare la pagina, o per richieste diverse da quelle descritte qui sopra. I gesti passano sempre da `Input`. Se una voce di §6.6 non si risolve senza uno di questi, non aggiungerlo da solo: scrivi l'esito e chiedi ad Alberto. Il client CDP registra solo i nomi dei comandi e degli eventi, mai parametri e risultati: lì dentro passano tasti, cookie e contenuti. @@ -334,6 +346,8 @@ Un componente `ResponseTap` ascolta le risposte JSON che la pagina riceve dal si Una ricetta è una sequenza di gesti con uno scopo. Sono poche e fisse. I passi qui sotto descrivono l'intenzione; i dettagli concreti si definiscono dopo M0, sui campioni. +**Da riscrivere (issue #36).** Con l'eccezione della regola 2 le ricette chiederanno i dati con le richieste della pagina invece di cercarne i comandi, e la mappa dei bersagli non servirà più. Che cosa resta qui sotto e che cosa cambia si decide sui campioni del nuovo HAR (#35). Una cosa non la decido da solo: oggi le storie si salvano solo se mostrate nel visualizzatore, e Alberto risulta tra gli spettatori (§3, domanda 5 di §16); chiederle con una richiesta non le segna come viste. Finché Alberto non sceglie (domanda 11 di §16), vale la regola di oggi: le storie solo dal visualizzatore. + | Ricetta | Che cosa fa | Azioni contate | |---|---|---| | **Giro dei seguiti** | Apre la home, legge la barra delle storie e scorre i post recenti dei profili seguiti finché incontra contenuti già noti, con un massimo di 8 raffiche di scorrimento. I post che arrivano con i dati completi si salvano subito | 1 home | @@ -453,7 +467,7 @@ Il Governatore è l'unico punto da cui passa un'azione del motore verso il sito. - I tetti orari valgono su una finestra mobile di 60 minuti; quelli giornalieri sul giorno di calendario nel fuso di Alberto. - Il conteggio sta nella tabella `action_log`, non in memoria. -- Categorie: home, profili aperti, storie viste, pagine di storico, post singoli, pagine dell'elenco dei seguiti, dati scaricati. +- Categorie: home, profili aperti, storie viste, pagine di storico, post singoli, pagine dell'elenco dei seguiti, dati scaricati. Le richieste della pagina (regola 2, eccezione) contano nella categoria di ciò che chiedono; la ricerca dei profili mentre si scrive avrà una categoria e un tetto propri (issue #36 e #37). - Sopra l'80% di un tetto l'interfaccia lo segnala in ambra. Raggiunto il tetto, quella categoria si ferma fino all'ora o al giorno dopo; le altre proseguono, salvo la regola sullo storico di §6.3. - Quando valgono insieme più riduzioni (avvio graduale, tetti dimezzati dopo un rallentamento) si applica la più forte, non il loro prodotto. @@ -841,6 +855,7 @@ Le esegue solo Alberto, con l'account di prova, seguendo un elenco di passi che - **La ripulitura lavora per elenco di ciò che è ammesso**, non di ciò che è vietato. Conserva struttura e chiavi. Sostituisce ogni stringa e ogni numero lungo con un valore finto della stessa forma, tranne i campi di un breve elenco che non dicono nulla di una persona (dimensioni, durate, conteggi, valori vero o falso, codici di tipo, date). Sostituisce anche le chiavi che hanno l'aspetto di un identificativo. Degli indirizzi tiene solo la distinzione fra sito e CDN e l'estensione del file. - Una prova automatica confronta grezzi e ripuliti, sulla macchina di Alberto, e fallisce se una stringa di quattro o più caratteri sopravvive fuori dall'elenco ammesso. - In `tests/campioni/` e in `docs/sonda/esito.md` entrano solo campioni ripuliti e descrizioni di forma. +- **Forma delle richieste** (per la regola 2, eccezione). `febe-sonda richieste --har --a ` descrive le richieste che la pagina fa al sito: metodo, percorso con ogni parte che non è una parola fissa del sito sostituita da `{numero}` o `{testo}`, nomi dei parametri, delle intestazioni e dei campi del corpo, struttura delle variabili GraphQL. Dei valori scrive solo il tipo («numero», «testo», «vuoto»), tranne quelli di un elenco chiuso uguali per tutti (identificativo dell'applicazione, nomi e identificativi delle operazioni, grandezza delle pagine, vero/falso): mai cookie, gettoni, nomi, identificativi o cursori. Dei nomi tiene quelli di un elenco chiuso e quelli che hanno la forma di un nome del codice (senza punto, senza tre cifre di fila) e non compaiono da nessuna parte nel HAR come valore; gli altri diventano «(nome tolto)». Alberto lo legge e lo invia; da lì si scrive `richieste..json`. --- @@ -892,6 +907,7 @@ Falle quando arrivi al punto indicato, una per volta, proponendo la risposta del | 8 | Il nome «Febe» resta? | Prima di M0 | — | | 9 | Solo italiano, o anche inglese? | M4 | Solo italiano, testi già separati | | 10 | Su Unraid: porta, cartella della libreria, disco per i dati | M5 | Porta 8480, dati nella cartella delle applicazioni sul disco di cache | +| 11 | Con la pagina che chiede i dati, le storie si chiedono con una richiesta (non risultano viste) o si continuano ad aprire nel visualizzatore (Alberto tra gli spettatori, come oggi)? | #36, sui campioni del nuovo HAR | Restare al visualizzatore, che è la scelta di §3; la richiesta solo se il visualizzatore non si può guidare in modo affidabile | --- @@ -917,7 +933,7 @@ All'inizio di ogni sessione leggi docs/stato.md. 1. IMPORTANTE: non contattare mai Instagram da prove, script o verifiche tue. Si usa solo tools/Febe.SitoDiProva. Le prove dal vivo le lancia Alberto. 2. Non aprire i campioni grezzi della sonda: stanno fuori dal repository e contengono dati di altre persone. Si lavora sulle copie ripulite di tests/campioni. 3. Verso Instagram parla solo il browser di Febe. Nessun HttpClient verso domini di Instagram o Meta, tranne il CDN alle condizioni di §6.5. -4. Il browser si usa così com'è: nessuna modifica di user agent, impronta, intestazioni; niente headless, stealth, proxy, più account. Comandi CDP solo dall'elenco di §6.1. +4. Il browser si usa così com'è: nessuna modifica di user agent, impronta, intestazioni; niente headless, stealth, proxy, più account. Comandi CDP solo dall'elenco di §6.1. Unica eccezione: la pagina chiede i dati agli indirizzi di `richieste..json`, uno per volta e con il permesso del Governatore (§2 regola 2, §6.1). 5. CAPTCHA, verifiche e codici non si risolvono mai in automatico: Febe si ferma e avvisa. 6. Sola lettura (niente mi piace, segui, commenti, messaggi) e solo ciò che l'account di Alberto vede già. 7. Un account, un motore. I cookie non si copiano da una macchina all'altra. diff --git a/docs/decisioni.md b/docs/decisioni.md index 09822ab..8e6487c 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -314,3 +314,5 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15). | 2026-10-25 | La paginazione di una pagina (griglia, schede, giro dei seguiti, elenco dei seguiti) viene dalla risposta che porta più elementi non ancora incontrati, l'ultima a pari merito; una risposta che riporta solo elementi già letti non conta come pagina successiva né per la sua paginazione. Una risposta vuota senza profilo è la pagina vuota di un cammino solo quando risponde a un suo gesto (pagina di ripresa, scheda, scorrimento), mai all'apertura del profilo; con il profilo dell'account è la griglia vuota anche accanto alle raccolte, se il profilo dice «0 pubblicazioni» | Rilievi della revisione: su Instagram la pagina di un post del profilo stesso («more_available: false») e le raccolte di un account che non ne ha (connessione vuota con «has_next_page: false», forma identica a una griglia vuota) chiudevano lo storico dopo la prima pagina o senza post; sul sito di prova un profilo con raccolte e senza post aspettava 20 s a ogni controllo. Un account Instagram senza post resta così con lo storico aperto: costa un'attesa e una pagina a sessione, mai post persi | | 2026-10-25 | Mentre «Storie di un account» non può girare con la configurazione del sito, la visita di un profilo non seguito non serve le storie: si pianifica all'intervallo del profilo, non conta come lavoro di storie, e il giro dei seguiti non accoda «Storie segnalate dalla barra» (ogni giro segnala di nuovo l'account finché le storie non si vedono). `SyncQueue` non annulla più i «Post singolo» accodati dalla raccolta: li toglie solo per un account che non si contatta, e mentre la ricetta non può girare aspettano | Con i file di Instagram di oggi un profilo non seguito si sarebbe aperto fino a 24 volte più spesso del dovuto senza raccogliere nulla, e la Coda si sarebbe riempita a ogni sessione di storie che non sarebbero mai partite. Un «Post singolo» annullato non tornava più in coda (nessuno ricontrolla gli indirizzi scaduti), mentre §6.5 punto 5 vuole che il recupero passi da lì: difetto precedente a questo lavoro (commit `aff81df`), trovato dalla revisione. Effetto: su Instagram queste ricette ora girano davvero, dentro il loro tetto (Prudente: 10 l'ora, 60 al giorno) | | 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..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 --a `: 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 | diff --git a/docs/prove-dal-vivo.md b/docs/prove-dal-vivo.md index 0ca3e38..d75ff82 100644 --- a/docs/prove-dal-vivo.md +++ b/docs/prove-dal-vivo.md @@ -190,6 +190,105 @@ sui campioni ripuliti, **cancella il file HAR e la cartella `grezzi`** (§14.5). --- +## A ter. Richieste e risposte per «la pagina chiede i dati» (12 novembre 2026, issue #35) + +Scopo: con la decisione del 12 novembre (issue #34, specifica §2 regola 2 e §6.1) Febe chiede i dati al sito dalla +pagina, con le stesse richieste che fa l'applicazione web di Instagram. Per scriverle (`richieste.instagram.json`) e +leggerne le risposte servono, da un solo giro nel tuo browser: + +- la **forma delle richieste** che la pagina fa: indirizzi, nomi dei parametri e delle intestazioni, operazioni + GraphQL. La dà il nuovo `febe-sonda richieste`, che non scrive nessun valore personale; +- le **risposte**, ripulite come sempre con `da-har`, `ripulisci` e `verifica`. + +Niente script dei bersagli, questa volta: con la strada B Febe non cerca più i comandi nella pagina. **Navighi solo +tu**: nessun programma clicca o apre pagine. + +### A ter 1. Prima di cominciare + +- Chrome su Windows, con Instagram aperto e l'accesso già fatto. +- Una cartella **nuova, fuori da qualunque repository git**, per esempio `C:\febe-har\2026-11-12` (qui sotto + ``). Il file HAR contiene i cookie della sessione e i dati di altre persone: **non si invia mai**. +- Febe compilato dal repository aggiornato (serve il comando `richieste`). +- Se compare una verifica, un CAPTCHA o un avviso dell'account, **fermati**, risolvi a mano, annota l'ora e riferisci. + +### A ter 2. Strumenti per sviluppatori + +1. Con Instagram aperto premi **F12**. +2. Scheda **Rete**: spunta **Conserva log** e nel filtro dei tipi scegli **Tutti**, non «Fetch/XHR». +3. Ricarica la pagina (**F5**) con il pannello aperto. + +### A ter 3. Che cosa fare, nell'ordine + +Muoviti con calma, come al solito, e annota l'ora d'inizio di ogni passo. Ogni passo corrisponde a una richiesta che +Febe dovrà saper fare. + +Da qui in poi i profili si aprono **cliccando**, mai scrivendo l'indirizzo nella barra: un indirizzo scritto a mano +ricarica tutta la pagina e i dati arrivano dentro il documento, non come richiesta della pagina, e il file non li +descriverebbe. + +1. **Ricerca, lettera per lettera, di un profilo che segui.** Clicca **Cerca** nella barra a sinistra e scrivi + **piano**, una lettera ogni secondo circa, il suo nome (almeno 5 lettere), finché compare nei risultati. Poi + **clicca il risultato**: si apre il suo profilo. +2. **Il profilo.** Attendi, poi scorri la griglia finché si caricano **almeno due** pagine di post in più (3–4 + schermate). +3. **Le sue schede.** Clicca **Reel** e scorri un poco; poi **Taggati** e scorri un poco. +4. **Le sue storie**, se ne ha: clicca la foto con l'anello, vai avanti di **due** storie, chiudi con la **X** prima + che finiscano. +5. **Una raccolta in evidenza** dello stesso profilo: aprila, vai avanti **una volta**, chiudi con la **X**. +6. **Un post con più foto o un video**: aprilo dalla griglia e passa alla foto successiva con la freccia. +7. **Ricerca di un profilo pubblico che non segui**, come al passo 1, lettera per lettera, e **clicca il + risultato**: attendi il caricamento e scorri una schermata. +8. **I tuoi seguiti.** Clicca la tua foto nella barra a sinistra, poi **«Seguiti»**, e scorri l'elenco finché si + caricano **almeno due** pagine in più. Poi, nella casella **Cerca** dentro l'elenco, scrivi piano tre lettere e + chiudi. +9. **La home.** Clicca il logo, attendi e scorri piano per una decina di post; apri la barra delle storie solo se lo + fai di solito. + +Ci si aspetta: nessuna verifica, nessun avviso. + +### A ter 4. Il file HAR + +Scheda **Rete**: **esporta il HAR** in `\instagram.har`. Se Chrome offre due voci, scegli quella **senza** +dati sensibili (toglie cookie e autorizzazioni, che non servono); se poi `da-har` dice che le risposte sono «senza +corpo», esporta di nuovo con l'altra voce. Chiudi gli strumenti per sviluppatori. + +### A ter 5. Forma delle richieste, conversione, ripulitura e verifica (sulla tua macchina) + +```sh +febe-sonda richieste --har \instagram.har --a \richieste.json +febe-sonda da-har --har \instagram.har --a \grezzi +febe-sonda ripulisci --da \grezzi --a \ripuliti +febe-sonda verifica --grezzi \grezzi --ripuliti \ripuliti +``` + +Dal repository: `dotnet run --project tools/Febe.Sonda -- richieste …`, e così per gli altri. + +- `richieste` scrive un file **nuovo** (rifiuta un file che esiste già, una cartella e un file dentro un + repository). Per ogni richiesta distinta della pagina al sito: metodo, percorso (le parti che non sono parole fisse + del sito diventano `{numero}` o `{testo}`), nomi dei parametri e dei campi del corpo con il **tipo** del valore + («numero», «testo», «vuoto»), nomi delle intestazioni, struttura delle variabili GraphQL; quante volte la pagina + l'ha fatta, gli stati e i tipi delle risposte. Dei valori restano solo quelli uguali per tutti: l'identificativo + dell'applicazione, i nomi e gli identificativi (`doc_id`) delle operazioni, la grandezza delle pagine, vero/falso. + I valori delle altre intestazioni sono `(valore tolto)`. Un nome che nel file HAR compare anche come valore (un + nome utente usato come chiave, per esempio) diventa `(nome tolto)`. Stampa solo conteggi. +- I valori fissi delle variabili (per esempio da quale «superficie» parte una ricerca) restano «testo», perché lo + strumento non sa distinguerli da ciò che scrivi tu: se servono, te li chiedo per nome e li guardi tu nel HAR. +- **Leggi `richieste.json` prima di inviarlo**: non deve esserci un nome, un cognome, un indirizzo di posta, un + testo che hai scritto. Se ne trovi uno, non inviarlo e dimmi dove (il campo, non il valore). +- Per `da-har`, `ripulisci` e `verifica` vale quanto scritto in A bis 6. + +### A ter 6. Che cosa mandare + +1. `richieste.json`, dopo averlo letto. +2. La cartella **ripulita** (compressa) e il testo della verifica. +3. Le note: a che ora hai fatto ogni passo, che cosa è andato diversamente, se la ricerca e l'elenco dei seguiti si + sono comportati come descritto. + +Mai: il file HAR, la cartella `grezzi`. Quando richieste e lettori sono stati scritti, **cancella il file HAR e la +cartella `grezzi`** (§14.5). + +--- + ## B. Prima sessione dal vivo, dopo M3 Scopo: vedere Febe fare una sessione vera, piccola, con il profilo **Prudente**, e i file arrivare in libreria. diff --git a/docs/stato.md b/docs/stato.md index 257d7b3..8c2b2d5 100644 --- a/docs/stato.md +++ b/docs/stato.md @@ -16,9 +16,17 @@ fra le sessioni; ciò che è da fare si legge nelle issue aperte. - **Perché**: le ricette dipendono dalla mappa dei bersagli, che si può raccogliere solo su Instagram (parte «A bis», mai fatta). Anche con la 0.1.2 l'elenco dei seguiti non ha indirizzo e storie, raccolte, Taggati e Reel non hanno bersagli. È un difetto di disegno, non un errore da correggere. -- **Decisione di Alberto** (#34): A, indirizzi e tastiera dentro le regole di oggi; B, la pagina chiede i dati a - Instagram dentro i tetti (cambia la regola 2 e §6.1); C, misto. Finché non sceglie, la raccolta riscritta (#36) è - ferma. +- **Decisione di Alberto** (#34, chiusa): **strada B, la pagina chiede i dati.** Dalla pagina di Instagram già + aperta Febe chiede al sito gli stessi dati che chiede la sua applicazione web, solo verso gli indirizzi di + `richieste.instagram.json`, in sola lettura, una richiesta per volta col permesso del Governatore. Scritta in + `docs/decisioni.md`, nella specifica (§2 regola 2 con la sua unica eccezione, §6.1 riga e regole delle richieste, + §14.5) e nella regola 4 di `CLAUDE.md`. Foto dei profili: dentro ogni account (`\profilo\…`, #38). +- **Pronto per i campioni nuovi** (#35): `febe-sonda richieste --har --a ` descrive la forma delle + richieste della pagina (metodo, percorso con `{numero}`/`{testo}`, nomi di parametri, intestazioni e campi, + struttura delle variabili GraphQL) senza alcun valore personale, con 27 prove nuove su un HAR sintetico. Una revisione avversaria (23 agenti) ha trovato 17 difetti confermati, tutti corretti prima del commit: tre fughe possibili (un nome utente usato come chiave, un corpo di testo spezzato in nomi, un identificativo piccolo copiato), interrogazioni GET unite fra loro, pagine successive perse nell'unione, un arresto su uno stato non numerico, e parti della specifica (§1, regola 5, §6.3, §7.4) ancora in contrasto con l'eccezione. Nuova domanda aperta 11 (§16): le storie con la strada B. Procedura + per Alberto in `docs/prove-dal-vivo.md`, parte **A ter**. Finché il HAR nuovo non arriva, `richieste.instagram.json` + e i lettori nuovi non si possono scrivere (regola 10): la raccolta riscritta (#36) e la ricerca unica (#37) hanno + bisogno di quei campioni. - Richieste nuove: ricerca unica dei profili con le foto, aggiornata mentre si scrive (#37); foto dei profili in una cartella separata (#38). In più la diagnostica della raccolta (#39), i campioni nuovi (#35), la prova dal vivo (#40) e la chiusura della 0.2.0 (#41), tutte nel traguardo «0.2.0 — Raccolta che funziona su Instagram». diff --git a/tests/Febe.Tests/Collection/HarImportTests.cs b/tests/Febe.Tests/Collection/HarImportTests.cs index 3797c32..1420736 100644 --- a/tests/Febe.Tests/Collection/HarImportTests.cs +++ b/tests/Febe.Tests/Collection/HarImportTests.cs @@ -125,7 +125,8 @@ public sealed class HarImportTests Assert.AreEqual("PolarisStoriesV3HighlightsPageQuery", HarImporter.OperationName("PolarisStoriesV3HighlightsPageQuery")); Assert.AreEqual("usePolarisRegisterInRecentSearchesMutation", HarImporter.OperationName(" usePolarisRegisterInRecentSearchesMutation ")); Assert.AreEqual("ProvaAggiornamentiSubscription", HarImporter.OperationName("ProvaAggiornamentiSubscription")); - foreach (var value in new[] { null, "", "Query", "mario.rossi", "mario_rossi", "Pagina di mario Query", "Profilo12345Query", "/mario.rossi/Query", "ProvaElenco" }) + Assert.AreEqual("ProvaGrigliaQuery_connection", HarImporter.OperationName("ProvaGrigliaQuery_connection"), "The following page of a connection."); + foreach (var value in new[] { null, "", "Query", "mario.rossi", "mario_rossi", "Pagina di mario Query", "Profilo12345Query", "/mario.rossi/Query", "ProvaElenco", "ProvaQuery_mario.rossi", "ProvaQuery_Mario" }) { Assert.IsNull(HarImporter.OperationName(value), value ?? "null"); } diff --git a/tests/Febe.Tests/Collection/RequestShapeTests.cs b/tests/Febe.Tests/Collection/RequestShapeTests.cs new file mode 100644 index 0000000..60cf6b7 --- /dev/null +++ b/tests/Febe.Tests/Collection/RequestShapeTests.cs @@ -0,0 +1,285 @@ +using System.Text.Json.Nodes; +using Febe.Sonda; +using Febe.Tests.Support; + +namespace Febe.Tests.Collection; + +/// +/// febe-sonda richieste: the shape of the requests the site's page makes, without any personal value (decision of +/// 12 November 2026, issue #34). The HAR is synthetic, written by the test with invented values: it checks what is kept +/// and what never is, not Instagram's format. +/// +[TestClass] +public sealed class RequestShapeTests +{ + /// Values that stand for personal data in the synthetic HAR: none may reach the output, as value or as name. + private static readonly string[] Secrets = + [ + "segreto", "mario", "lucia", "bianchi", "5512345678", "QVFIUjBz", "Mozilla", "sessione", "AbCdEfGhIjK", "jerry", + ]; + + [TestMethod] + public void OnlyNamesAndValuesTheSameForEveryoneReachTheOutput() + { + var (report, shapes, text) = Extract(); + Assert.AreEqual(new RequestShapesReport(Entries: 15, SiteRequests: 12, Shapes: 9, RemovedNames: report.RemovedNames), report); + Assert.IsGreaterThanOrEqualTo(3, report.RemovedNames, "Two keys of a map and a pair without «=»."); + foreach (var secret in Secrets) + { + Assert.IsFalse(text.Contains(secret, StringComparison.OrdinalIgnoreCase), secret); + } + + CollectionAssert.AreEqual( + new[] + { + "/api/v1/feed/user/{numero}/", "/api/v1/friendships/show/", "/api/v1/users/web_profile_info/", "/api/v1/web/search/topsearch/", + "/graphql/query", "/graphql/query", "/graphql/query", "/graphql/query/", "/graphql/query/", + }, + shapes.Select(s => s["percorso"]!.GetValue()).ToArray()); + + // Header names are all there; values only for the closed list, and never the cookie, the token or the agent. + var profile = shapes[2]; + Assert.IsTrue(JsonNode.DeepEquals(JsonNode.Parse("""{"username":"testo"}"""), profile["parametri"])); + var headers = profile["intestazioni"]!.AsObject(); + Assert.AreEqual("1234", headers["x-ig-app-id"]!.GetValue()); + Assert.AreEqual("*/*", headers["accept"]!.GetValue()); + foreach (var removed in new[] { "cookie", "x-csrftoken", "user-agent", "x-ig-www-claim", "referer" }) + { + Assert.AreEqual(RequestShapes.Removed, headers[removed]!.GetValue(), removed); + } + + Assert.IsFalse(headers.ContainsKey(":authority"), "HTTP/2 pseudo-headers are not request headers of the page."); + CollectionAssert.AreEqual(new[] { 200 }, profile["stati"]!.AsArray().Select(s => s!.GetValue()).ToArray()); + CollectionAssert.AreEqual(new[] { "application/json" }, profile["tipi"]!.AsArray().Select(s => s!.GetValue()).ToArray()); + } + + [TestMethod] + public void DataUsedAsANameIsRemoved() + { + var (_, shapes, _) = Extract(); + + // An object keyed by user: a name with a dot, and a name that occurs elsewhere in the HAR as a value. + var keyed = Shape(shapes, "xdt_prova__elenco"); + Assert.IsTrue( + JsonNode.DeepEquals(JsonNode.Parse("""{"seen":{"(nome tolto)":"testo"}}"""), keyed["corpo"]!["variables"]), + keyed["corpo"]!.ToJsonString()); + Assert.AreEqual("xdt_prova__elenco", keyed["campo_radice"]!.GetValue(), "x-root-field-name names the operation."); + Assert.AreEqual("1000000000004", keyed["corpo"]!["doc_id"]!.GetValue(), "A form sent as text, without «params»."); + + // A pair without «=», and a small identifier that is not a page size. + var friendship = shapes.Single(s => s["percorso"]!.GetValue() == "/api/v1/friendships/show/"); + Assert.IsTrue(JsonNode.DeepEquals(JsonNode.Parse("""{"(nome tolto)":"vuoto","target_user_id":"numero"}"""), friendship["parametri"]), friendship["parametri"]!.ToJsonString()); + + // A text body that is not a form is never split into names. + var search = shapes.Single(s => s["percorso"]!.GetValue() == "/api/v1/web/search/topsearch/"); + Assert.IsTrue(JsonNode.DeepEquals(JsonNode.Parse("""{"(corpo)":"testo"}"""), search["corpo"]), search["corpo"]!.ToJsonString()); + } + + [TestMethod] + public void GraphQLOperationsAreToldApartAndTheirOccurrencesAreJoined() + { + var (_, shapes, _) = Extract(); + + // POST: operation and doc_id kept, form tokens only as kinds; the variables of all pages joined, so the cursor of + // the second page is there even though the first had none. + var list = Shape(shapes, "ProvaElencoQuery"); + Assert.AreEqual("POST", list["metodo"]!.GetValue()); + Assert.AreEqual(2, list["volte"]!.GetValue()); + var body = list["corpo"]!.AsObject(); + Assert.AreEqual("1000000000001", body["doc_id"]!.GetValue()); + Assert.AreEqual("ProvaElencoQuery", body[HarImporter.OperationParameter]!.GetValue()); + Assert.AreEqual("testo", body["fb_dtsg"]!.GetValue()); + Assert.IsTrue( + JsonNode.DeepEquals(JsonNode.Parse("""{"after":"testo","filters":["testo"],"first":"12","nested":{"id":"numero"},"private":"false","username":"testo"}"""), body["variables"]), + body["variables"]!.ToJsonString()); + + // A JSON request body: member by member, named by the header. + var search = Shape(shapes, "ProvaRicercaQuery"); + Assert.AreEqual("Fetch", search["risorsa"]!.GetValue()); + Assert.IsTrue(JsonNode.DeepEquals(JsonNode.Parse("""{"count":"5","query":"testo"}"""), search["corpo"]), search["corpo"]!.ToJsonString()); + + // GET: doc_id and variables in the address, one shape per doc_id, variables described like a body's. + var gets = shapes.Where(s => s["percorso"]!.GetValue() == "/graphql/query/").ToArray(); + Assert.AreEqual("1000000000002", gets[0]["parametri"]!["doc_id"]!.GetValue()); + Assert.IsTrue(JsonNode.DeepEquals(JsonNode.Parse("""{"first":"12","id":"numero"}"""), gets[0]["parametri"]!["variables"]), gets[0]["parametri"]!.ToJsonString()); + Assert.AreEqual("1000000000003", gets[1]["parametri"]!["doc_id"]!.GetValue()); + Assert.IsTrue(JsonNode.DeepEquals(JsonNode.Parse("""{"shortcode":"testo"}"""), gets[1]["parametri"]!["variables"])); + Assert.AreEqual(0, gets[1]["stati"]!.AsArray().Count, "A status that is not a number is left out, not a crash."); + + // A page size seen as 12, 33 and 12 again: a number. + var feed = shapes[0]; + Assert.AreEqual(3, feed["volte"]!.GetValue()); + Assert.IsTrue(JsonNode.DeepEquals(JsonNode.Parse("""{"count":"numero","max_id":"testo"}"""), feed["parametri"]), feed["parametri"]!.ToJsonString()); + } + + [TestMethod] + public void TheExtractionRefusesRepositoriesExistingFilesFoldersAndFilesThatAreNotAHar() + { + using var temp = new TempFolder("richieste"); + var har = temp.Combine("prova.har"); + File.WriteAllText(har, SyntheticHar().ToJsonString()); + + Directory.CreateDirectory(temp.Combine("progetto", ".git")); + var inside = temp.Combine("progetto", "richieste.json"); + StringAssert.Contains(Assert.ThrowsExactly(() => RequestShapes.Extract(har, inside)).Message, "fuori dal repository"); + Assert.IsFalse(File.Exists(inside)); + + var harInside = temp.Combine("progetto", "prova.har"); + File.Copy(har, harInside); + Assert.ThrowsExactly(() => RequestShapes.Extract(harInside, temp.Combine("altrove.json"))); + + var existing = temp.Combine("esiste.json"); + File.WriteAllText(existing, "{}"); + StringAssert.Contains(Assert.ThrowsExactly(() => RequestShapes.Extract(har, existing)).Message, "esiste già"); + Assert.AreEqual("{}", File.ReadAllText(existing)); + + var folder = Directory.CreateDirectory(temp.Combine("cartella")).FullName; + StringAssert.Contains(Assert.ThrowsExactly(() => RequestShapes.Extract(har, folder)).Message, "è una cartella"); + + Assert.ThrowsExactly(() => RequestShapes.Extract(temp.Combine("manca.har"), temp.Combine("nuovo1.json"))); + File.WriteAllText(temp.Combine("non-har.har"), """{"altro":[]}"""); + Assert.ThrowsExactly(() => RequestShapes.Extract(temp.Combine("non-har.har"), temp.Combine("nuovo2.json"))); + File.WriteAllText(temp.Combine("rotto.har"), "{\"log\":"); + Assert.ThrowsExactly(() => RequestShapes.Extract(temp.Combine("rotto.har"), temp.Combine("nuovo3.json"))); + Assert.IsFalse(File.Exists(temp.Combine("nuovo3.json"))); + } + + [TestMethod] + [DataRow("/api/v1/users/web_profile_info/", "/api/v1/users/web_profile_info/")] + [DataRow("/api/v1/feed/user/5512345678/", "/api/v1/feed/user/{numero}/")] + [DataRow("/mario.rossi/", "/{testo}/")] + [DataRow("/api/v1/media/5512345678_99/info/", "/api/v1/media/{testo}/info/")] + [DataRow("/p/AbC12x/", "/p/{testo}/")] + [DataRow("", "")] + public void APathKeepsOnlyTheWordsOfTheSite(string path, string expected) => + Assert.AreEqual(expected, RequestShapes.PathPattern(path)); + + [TestMethod] + [DataRow("count", null, "vuoto")] + [DataRow("count", "", "vuoto")] + [DataRow("count", "12", "12")] + [DataRow("target_user_id", "25", "numero")] + [DataRow("query", "007", "numero")] + [DataRow("include_reel", "true", "true")] + [DataRow("count", "1234", "numero")] + [DataRow("username", "mario.rossi", "testo")] + public void AValueBecomesItsKind(string name, string? value, string expected) => + Assert.AreEqual(expected, RequestShapes.ValueShape(name, value)); + + [TestMethod] + [DataRow("12", "33", "numero")] + [DataRow("numero", "12", "numero")] + [DataRow("12", "numero", "numero")] + [DataRow("true", "false", "sì/no")] + [DataRow("sì/no", "true", "sì/no")] + [DataRow("vuoto", "testo", "testo")] + [DataRow("nulla", "12", "12")] + [DataRow("numero", "testo", "testo")] + [DataRow("true", "12", "testo")] + public void TwoDescriptionsOfAValueBecomeOne(string a, string b, string expected) => + Assert.AreEqual(expected, RequestShapes.Generalize(a, b)); + + private static (RequestShapesReport Report, JsonNode[] Shapes, string Text) Extract() + { + using var temp = new TempFolder("richieste"); + var har = temp.Combine("prova.har"); + File.WriteAllText(har, SyntheticHar().ToJsonString()); + var output = temp.Combine("uscita", "richieste.json"); + var report = RequestShapes.Extract(har, output); + var text = File.ReadAllText(output); + return (report, JsonNode.Parse(text)!["richieste"]!.AsArray().Select(s => s!).ToArray(), text); + } + + private static JsonNode Shape(JsonNode[] shapes, string operation) => + shapes.Single(s => s["operazione"]?.GetValue() == operation); + + private static JsonObject SyntheticHar() + { + static JsonArray Headers(params (string Name, string Value)[] headers) => + new(headers.Select(h => (JsonNode)new JsonObject { ["name"] = h.Name, ["value"] = h.Value }).ToArray()); + + var pageHeaders = new (string, string)[] + { + (":authority", "www.instagram.com"), + ("Accept", "*/*"), + ("Cookie", "sessionid=segreto-sessione; csrftoken=segreto-csrf"), + ("User-Agent", "Mozilla/5.0 segreto"), + ("X-CSRFToken", "segreto-csrf"), + ("X-IG-App-ID", "1234"), + ("X-IG-WWW-Claim", "hmac.segreto-claim"), + ("Referer", "https://www.instagram.com/mario.rossi/"), + }; + + static JsonObject Entry(string resourceType, string method, string url, JsonArray headers, JsonNode status, string mime, JsonObject? postData = null, string answer = """{"segreto":"mario.rossi"}""") + { + var request = new JsonObject { ["method"] = method, ["url"] = url, ["headers"] = headers }; + if (postData is not null) + { + request["postData"] = postData; + } + + return new JsonObject + { + ["_resourceType"] = resourceType, + ["startedDateTime"] = "2026-10-21T17:35:04.512+02:00", + ["request"] = request, + ["response"] = new JsonObject + { + ["status"] = status, + ["headers"] = Headers(("set-cookie", "segreto=1")), + ["content"] = new JsonObject { ["mimeType"] = mime, ["text"] = answer }, + }, + }; + } + + static JsonObject Form(string? after, string user) + { + var variables = after is null + ? $$$"""{"username":"{{{user}}}","first":12,"private":false,"filters":["segreto"],"nested":{"id":"5512345678"}}""" + : $$$"""{"username":"{{{user}}}","first":12,"after":"{{{after}}}","private":false,"filters":["segreto"],"nested":{"id":"5512345678"}}"""; + return new() + { + ["mimeType"] = "application/x-www-form-urlencoded", + ["params"] = new JsonArray( + new JsonObject { ["name"] = "fb_dtsg", ["value"] = "dtsg-segreto" }, + new JsonObject { ["name"] = "lsd", ["value"] = "segreto-lsd" }, + new JsonObject { ["name"] = HarImporter.OperationParameter, ["value"] = "ProvaElencoQuery" }, + new JsonObject { ["name"] = "doc_id", ["value"] = "1000000000001" }, + new JsonObject { ["name"] = "variables", ["value"] = Uri.EscapeDataString(variables) }), + }; + } + + static JsonValue Ok() => JsonValue.Create(200); + + return new JsonObject + { + ["log"] = new JsonObject + { + ["entries"] = new JsonArray( + Entry("fetch", "GET", "https://www.instagram.com/api/v1/users/web_profile_info/?username=mario.rossi", Headers(pageHeaders), Ok(), "application/json; charset=utf-8", + answer: """{"utente":{"username":"lucia_bianchi"},"segreto":"mario.rossi"}"""), + Entry("xhr", "GET", "https://www.instagram.com/api/v1/feed/user/5512345678/?count=12&max_id=QVFIUjBz", Headers(pageHeaders), Ok(), "application/json"), + Entry("xhr", "GET", "https://www.instagram.com/api/v1/feed/user/5512345678/?count=33&max_id=QVFIUjBzLucia", Headers(pageHeaders), Ok(), "application/json"), + Entry("xhr", "GET", "https://www.instagram.com/api/v1/feed/user/5512345678/?count=12&max_id=QVFIUjBzBis", Headers(pageHeaders), Ok(), "application/json"), + Entry("xhr", "POST", "https://www.instagram.com/graphql/query", Headers(pageHeaders), Ok(), "text/javascript", Form(after: null, "mario.rossi")), + Entry("fetch", "POST", "https://www.instagram.com/graphql/query", Headers([.. pageHeaders, ("X-FB-Friendly-Name", "ProvaRicercaQuery"), ("Content-Type", "application/json")]), Ok(), "text/javascript", + new JsonObject { ["mimeType"] = "application/json", ["text"] = """{"query":"lucia","count":5}""" }), + Entry("xhr", "POST", "https://www.instagram.com/graphql/query", Headers(pageHeaders), Ok(), "text/javascript", Form("segreto-cursore", "lucia.bianchi")), + Entry("xhr", "GET", "https://www.instagram.com/graphql/query/?doc_id=1000000000002&variables=" + Uri.EscapeDataString("""{"id":"5512345678","first":12}"""), Headers(pageHeaders), Ok(), "application/json"), + Entry("xhr", "GET", "https://www.instagram.com/graphql/query/?doc_id=1000000000003&variables=" + Uri.EscapeDataString("""{"shortcode":"AbCdEfGhIjK"}"""), Headers(pageHeaders), JsonValue.Create("200"), "application/json"), + Entry("xhr", "POST", "https://www.instagram.com/graphql/query", Headers([.. pageHeaders, ("X-Root-Field-Name", "xdt_prova__elenco")]), Ok(), "text/javascript", + new JsonObject + { + ["mimeType"] = "application/x-www-form-urlencoded", + ["text"] = "doc_id=1000000000004&variables=" + Uri.EscapeDataString("""{"seen":{"lucia_bianchi":1,"mario.rossi":"vista"}}"""), + }), + Entry("fetch", "GET", "https://www.instagram.com/api/v1/friendships/show/?target_user_id=25&mario_rossi", Headers(pageHeaders), Ok(), "application/json"), + Entry("fetch", "POST", "https://www.instagram.com/api/v1/web/search/topsearch/", Headers(pageHeaders), Ok(), "application/json", + new JsonObject { ["mimeType"] = "text/plain;charset=UTF-8", ["text"] = "tom&jerry=1" }), + Entry("document", "GET", "https://www.instagram.com/mario.rossi/", Headers(pageHeaders), Ok(), "text/html"), + Entry("script", "GET", "https://www.instagram.com/static/segreto.js", Headers(pageHeaders), Ok(), "text/javascript"), + Entry("fetch", "GET", "https://scontent.cdninstagram.com/v/segreto.json?firma=segreto", Headers(pageHeaders), Ok(), "application/json")), + }, + }; + } +} diff --git a/tools/Febe.Sonda/HarImporter.cs b/tools/Febe.Sonda/HarImporter.cs index e1953bb..fd8e3e9 100644 --- a/tools/Febe.Sonda/HarImporter.cs +++ b/tools/Febe.Sonda/HarImporter.cs @@ -342,8 +342,9 @@ public static partial class HarImporter writer.WriteEndObject(); } - // A GraphQL operation name: an identifier of the site's code (e.g. a «...PageQuery»), never free text. - [GeneratedRegex("^[A-Za-z][A-Za-z0-9_]{1,96}(Query|Mutation|Subscription)$", RegexOptions.CultureInvariant)] + // A GraphQL operation name: an identifier of the site's code (e.g. a «...PageQuery», or «...Query_connection» for + // the following page of a connection), never free text. + [GeneratedRegex("^[A-Za-z][A-Za-z0-9_]{1,96}(Query|Mutation|Subscription)(_[a-z]{1,32})?$", RegexOptions.CultureInvariant)] private static partial Regex OperationShape(); [GeneratedRegex("[0-9]{3}", RegexOptions.CultureInvariant)] diff --git a/tools/Febe.Sonda/Program.cs b/tools/Febe.Sonda/Program.cs index f954dff..c5664c5 100644 --- a/tools/Febe.Sonda/Program.cs +++ b/tools/Febe.Sonda/Program.cs @@ -11,10 +11,12 @@ using Febe.Sonda; // febe-sonda ripulisci --da --a [--ammessi ] [--sito --cdn ] // febe-sonda verifica --grezzi --ripuliti [--ammessi ] // febe-sonda da-har --har --a [--sito --cdn ] +// febe-sonda richieste --har --a [--sito --cdn ] return args.Length == 0 ? Usage() : args[0] switch { "registra" => await RecordAsync(args[1..]), "da-har" => FromHar(args[1..]), + "richieste" => RequestsFromHar(args[1..]), "ripulisci" => Sanitize(args[1..]), "verifica" => Verify(args[1..]), _ => Usage(), @@ -28,10 +30,14 @@ static int Usage() febe-sonda ripulisci --da --a [--ammessi ] febe-sonda verifica --grezzi --ripuliti [--ammessi ] febe-sonda da-har --har --a + febe-sonda richieste --har --a La sonda è passiva: apre il browser e registra ciò che la pagina riceve mentre navighi tu. Non compie gesti. «da-har» converte nello stesso formato grezzo un file HAR esportato dagli strumenti per sviluppatori del browser: tiene le sole risposte di dati del sito e i dati incorporati nelle pagine; mai intestazioni, cookie, parametri degli indirizzi o corpi delle richieste. Poi si usano «ripulisci» e «verifica» come per la sonda. + «richieste» descrive dallo stesso file la forma delle richieste che la pagina fa al sito: percorso, nomi dei + parametri, delle intestazioni e dei campi del corpo; dei valori solo quelli uguali per tutti. Nessun cookie, + nessun nome utente, nessun identificativo. Leggi il file prima di inviarlo. """); return 2; } @@ -149,6 +155,34 @@ static int FromHar(string[] args) return report.Written > 0 ? 0 : 1; } +static int RequestsFromHar(string[] args) +{ + var har = Option(args, "--har"); + var to = Option(args, "--a"); + if (string.IsNullOrWhiteSpace(har) || string.IsNullOrWhiteSpace(to)) + { + Console.Error.WriteLine("Indicare --har e --a ."); + return 2; + } + + RequestShapesReport report; + try + { + report = RequestShapes.Extract(har, to, Hosts(args)); + } + catch (Exception ex) when (ex is InvalidOperationException or InvalidDataException or IOException or UnauthorizedAccessException) + { + Console.Error.WriteLine(ex.Message); + return 3; + } + + Console.WriteLine($"Lette {report.Entries} voci del file HAR; descritte {report.SiteRequests} richieste della pagina al sito in {report.Shapes} forme distinte."); + Console.WriteLine($"Nomi tolti perché potevano essere dati: {report.RemovedNames}."); + Console.WriteLine($"Forme delle richieste in: {Path.GetFullPath(to)}"); + Console.WriteLine("Leggilo prima di inviarlo: deve contenere solo nomi e forme, nessun tuo dato."); + return report.Shapes > 0 ? 0 : 1; +} + static int Sanitize(string[] args) { var from = Option(args, "--da"); diff --git a/tools/Febe.Sonda/RequestShapes.cs b/tools/Febe.Sonda/RequestShapes.cs new file mode 100644 index 0000000..15dae01 --- /dev/null +++ b/tools/Febe.Sonda/RequestShapes.cs @@ -0,0 +1,942 @@ +using System.Text; +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Text.RegularExpressions; +using Febe.Core.Abstractions; +using Febe.Core.Collection; + +namespace Febe.Sonda; + +/// What an extraction of request shapes did: counts only, never a value. +/// Entries of the HAR. +/// Requests the page made to the site (XHR, Fetch) that were described. +/// Distinct shapes written: same method, path pattern, operation and query identifier. +/// Names (parameters, fields, keys) replaced because they could be data. +public sealed record RequestShapesReport(int Entries, int SiteRequests, int Shapes, int RemovedNames); + +/// +/// Describes the SHAPE of the requests Instagram's own page makes to the site (decision of 12 November 2026, issue #34: +/// Febe has its page ask for the data the site's web application asks for, in the same form). From a HAR exported by +/// Alberto it writes, for each distinct request: method, path with every segment that is not a known word of the site +/// replaced by {numero} or {testo}, names of query parameters, headers and body fields with the kind of +/// their value, the structure of the GraphQL variables, and values only from closed lists of values that are the same +/// for everyone (application identifiers, operation names and identifiers, page sizes, true/false). +/// +/// +/// Unlike the raw samples of , the output is meant to be sent: it must hold no personal data +/// by construction. Values are never copied unless they are on a closed list. Names are copied only when they are on a +/// closed list, or when they have the shape of a name of the site's code (no dot, no run of three digits) AND never +/// occur anywhere in the HAR as a value: a user name, code or cursor that the page uses as a key (an object keyed by +/// user, a form field without a value) also occurs as a value somewhere (an address, a response, a cookie) and is +/// removed. A name removed by mistake costs only detail. The output is still written outside any repository, and +/// Alberto reads it before sending it. +/// +public static partial class RequestShapes +{ + /// Written in place of a header value that is not on a closed list. + public const string Removed = "(valore tolto)"; + + /// Written in place of a name (parameter, field, key) that could be data. + public const string RemovedName = "(nome tolto)"; + + /// The body field that describes a request body that is neither a form nor a JSON object. + public const string WholeBody = "(corpo)"; + + /// + /// Path segments kept as they are: words of the site's addresses, the same for everyone. Anything else (user names, + /// identifiers, codes) becomes {numero} or {testo}. A missing word only costs detail, never privacy. + /// + private static readonly HashSet KnownSegments = new(StringComparer.Ordinal) + { + "api", "v1", "graphql", "graphql_www", "query", "ajax", "bulk-route-definitions", "navigation", "web", "users", + "user", "web_profile_info", "usernameinfo", "info", "feed", "timeline", "reels_media", "reels_tray", "highlights", + "highlights_tray", "friendships", "following", "followers", "show", "show_many", "search", "topsearch", "fbsearch", + "web_search", "typeahead", "accounts_typeahead", "top_serp", "media", "comments", "usertags", "clips", "stories", + "story", "tags", "sections", "discover", "explore", "chaining", "profile", "posts", "reels", "tagged", "saved", + "qp", "batch_fetch_web", "logging_client_events", "direct_v2", "inbox", "has_new", "get_presence", "wwwgraphql", + "ig", "bz", "web_info", "current_user", "user_info", "locations", "seen", "media_seen", "reel", "p", "accounts", + "edit", "activity", "news", "inbox_v2", "notifications", "badge", "home", "graphql_query", + }; + + /// Request headers whose value is the same for everyone and is kept; any other value is removed. + private static readonly HashSet KnownHeaderValues = new(StringComparer.OrdinalIgnoreCase) + { + "accept", "content-type", "x-ig-app-id", "x-asbd-id", "x-requested-with", "x-instagram-ajax", "x-bloks-version-id", + "sec-fetch-dest", "sec-fetch-mode", "sec-fetch-site", + }; + + /// Header that names the operation: its value is kept only when it has the shape of an operation name. + private const string FriendlyNameHeader = "x-fb-friendly-name"; + + /// Header that names the GraphQL root field: its value is kept only when it has the shape of one. + private const string RootFieldHeader = "x-root-field-name"; + + /// Query or body fields whose value names the site's code and is kept when it has the shape of an identifier. + private static readonly HashSet KnownValueFields = new(StringComparer.Ordinal) + { + HarImporter.OperationParameter, "fb_api_caller_class", "doc_id", "query_hash", "query_id", "server_timestamps", + "__comet_req", "__a", "dpr", + }; + + /// Fields whose value identifies the query: two requests that differ in them are different shapes. + private static readonly string[] QueryIdentifiers = ["doc_id", "query_hash", "query_id"]; + + /// Fields that hold JSON: only its structure is written (keys and kinds of values). + private static readonly HashSet JsonFields = new(StringComparer.Ordinal) { "variables", "params", "query_params" }; + + /// Names whose small numbers (at most three digits) are a page size or a switch and are kept as they are. + private static readonly HashSet PageSizeNames = new(StringComparer.Ordinal) + { + "count", "first", "last", "limit", "page_size", "num_results", "__comet_req", "__a", "dpr", + }; + + /// Names of the site's code always kept, even when the same word occurs as a value somewhere. + private static readonly HashSet KnownNames = new(StringComparer.Ordinal) + { + "after", "before", "cursor", "max_id", "min_id", "id", "ids", "user_id", "target_user_id", "username", "query", + "data", "include_reel", "reel_ids", "media_id", "shortcode", "search_surface", "context", "rank_token", + }; + + private static readonly JsonDocumentOptions DeepDocuments = new() { MaxDepth = 256 }; + + /// Writes the shapes of the site requests in to the new file . + /// A path is inside a git repository, or the output exists. + /// The file is not a HAR. + public static RequestShapesReport Extract(string harPath, string outputPath, HostClassifier? hosts = null) + { + ArgumentException.ThrowIfNullOrWhiteSpace(harPath); + ArgumentException.ThrowIfNullOrWhiteSpace(outputPath); + hosts ??= HostClassifier.Instagram; + var har = Path.GetFullPath(harPath); + if (!File.Exists(har)) + { + throw new FileNotFoundException($"Il file HAR non esiste: {har}", har); + } + + RepositoryGuard.EnsureOutside(Path.GetDirectoryName(har)!); + var output = Path.GetFullPath(outputPath); + RepositoryGuard.EnsureOutside(Path.GetDirectoryName(output)!); + if (Directory.Exists(output)) + { + throw new InvalidOperationException($"«{output}» è una cartella: indica un file nuovo, per esempio «{Path.Combine(output, "richieste.json")}»."); + } + + if (File.Exists(output)) + { + 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(StringComparer.Ordinal); + int count = 0, described = 0; + Names names; + 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»)."); + } + + // First pass: every value the HAR holds, wherever it is. A name equal to one of them is never written. + names = new Names(ValueCollector.Collect(entries)); + foreach (var entry in entries.EnumerateArray()) + { + count++; + if (Describe(entry, hosts, names) is not { } shape) + { + continue; + } + + described++; + if (shapes.TryGetValue(shape.Key, out var known)) + { + known.Merge(shape); + } + else + { + shapes[shape.Key] = shape; + } + } + } + + var root = new JsonObject + { + ["nota"] = "Forma delle richieste che la pagina di Instagram fa al sito, ricavata con «febe-sonda richieste» da un file HAR. " + + "Nessun valore personale: dei parametri, delle intestazioni e dei corpi restano i nomi e il tipo dei valori; i valori solo se " + + "sono uguali per tutti (identificativo dell'applicazione, nomi e identificativi delle operazioni, grandezza delle pagine, vero/falso). " + + "Un nome che altrove nel file HAR compare come valore diventa «(nome tolto)». Leggilo prima di inviarlo.", + ["richieste"] = new JsonArray(shapes.Values + .OrderBy(s => s.Path, StringComparer.Ordinal) + .ThenBy(s => s.Key, StringComparer.Ordinal) + .Select(s => (JsonNode)s.ToJson()) + .ToArray()), + }; + Directory.CreateDirectory(Path.GetDirectoryName(output)!); + using (var stream = new FileStream(output, FileMode.CreateNew, FileAccess.Write)) + using (var writer = new StreamWriter(stream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false))) + { + writer.Write(root.ToJsonString(new JsonSerializerOptions { WriteIndented = true, Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping })); + writer.Write('\n'); + } + + return new RequestShapesReport(count, described, shapes.Count, names.Removed); + } + + /// The path with each segment that is not a known word replaced by {numero} or {testo}. + public static string PathPattern(string path) + { + ArgumentNullException.ThrowIfNull(path); + var segments = path.Split('/'); + for (var i = 0; i < segments.Length; i++) + { + var segment = segments[i]; + if (segment.Length == 0 || KnownSegments.Contains(segment)) + { + continue; + } + + segments[i] = Digits().IsMatch(segment) ? "{numero}" : "{testo}"; + } + + return string.Join('/', segments); + } + + /// + /// The kind of the value of , never the value: «numero», «vuoto» or «testo». Kept as they are: + /// true/false, and a small number (at most three digits) only for a page size or a switch. + /// + public static string ValueShape(string name, string? value) => value switch + { + null or "" => "vuoto", + "true" or "false" => value, + _ when SmallNumber().IsMatch(value) && PageSizeNames.Contains(name) => value, + _ when Digits().IsMatch(value) => "numero", + _ => "testo", + }; + + /// + /// Two descriptions of the same value seen in different requests, made one: the same value stays; two numbers are + /// «numero», true and false are «sì/no», an empty value gives way to the other; anything else is «testo». + /// + public static string Generalize(string a, string b) + { + ArgumentNullException.ThrowIfNull(a); + ArgumentNullException.ThrowIfNull(b); + if (a == b) + { + return a; + } + + return (Kind(a), Kind(b)) switch + { + ("vuoto", _) => b, + (_, "vuoto") => a, + ("numero", "numero") => "numero", + ("sì/no", "sì/no") => "sì/no", + _ => "testo", + }; + + static string Kind(string value) => value switch + { + "vuoto" or "nulla" => "vuoto", + "true" or "false" or "sì/no" => "sì/no", + "numero" => "numero", + _ when Digits().IsMatch(value) => "numero", + _ => "testo", + }; + } + + private static Shape? Describe(JsonElement entry, HostClassifier hosts, Names names) + { + if (entry.ValueKind != JsonValueKind.Object + || !entry.TryGetProperty("request", out var request) || request.ValueKind != JsonValueKind.Object) + { + return null; + } + + var resource = Text(entry, "_resourceType")?.ToLowerInvariant() switch + { + "xhr" => "XHR", + "fetch" => "Fetch", + _ => null, + }; + var url = Text(request, "url"); + if (resource is null || hosts.Classify(url) != HostKind.Site || !Uri.TryCreate(url, UriKind.Absolute, out var uri)) + { + return null; + } + + var shape = new Shape((Text(request, "method") ?? "GET").ToUpperInvariant(), PathPattern(uri.AbsolutePath), resource); + + // Query string and body: the same rules for names and values, and a name repeated in one request is one entry. + var raw = new Dictionary(StringComparer.Ordinal); + foreach (var (name, value) in Pairs(uri.Query)) + { + raw.TryAdd(name, value); + Put(shape.Parameters, names, name, value); + } + + var fields = BodyFields(request, out var whole); + foreach (var (name, value) in fields) + { + raw.TryAdd(name, value); + Put(shape.Body, names, name, value); + } + + if (whole is not null) + { + Add(shape.Body, WholeBody, JsonValue.Create(whole)!); + } + + if (request.TryGetProperty("headers", out var headers) && headers.ValueKind == JsonValueKind.Array) + { + foreach (var header in headers.EnumerateArray()) + { + var name = header.ValueKind == JsonValueKind.Object ? Text(header, "name")?.ToLowerInvariant() : null; + if (string.IsNullOrEmpty(name) || name.StartsWith(':')) + { + continue; + } + + var value = Text(header, "value"); + shape.Headers[names.Safe(name)] = name switch + { + FriendlyNameHeader => HarImporter.OperationName(value) ?? Removed, + RootFieldHeader => RootField(value) ?? Removed, + _ when KnownHeaderValues.Contains(name) && value is not null && SafeHeaderValue().IsMatch(value) => value, + _ => Removed, + }; + } + } + + shape.RootField = shape.Headers.TryGetValue(RootFieldHeader, out var field) ? RootField(field) : null; + shape.Operation = HarImporter.OperationName(raw.GetValueOrDefault(HarImporter.OperationParameter)) + ?? (shape.Headers.TryGetValue(FriendlyNameHeader, out var friendly) ? HarImporter.OperationName(friendly) : null) + ?? shape.RootField; + shape.QueryIdentifier = string.Join(' ', QueryIdentifiers + .Select(id => raw.GetValueOrDefault(id) is { } value && SafeCodeValue().IsMatch(value) ? $"{id}={value}" : null) + .OfType()); + + if (entry.TryGetProperty("response", out var response) && response.ValueKind == JsonValueKind.Object) + { + if (response.TryGetProperty("status", out var status) && status.ValueKind == JsonValueKind.Number && status.TryGetInt32(out var code)) + { + shape.Statuses.Add(code); + } + + if (response.TryGetProperty("content", out var content) && content.ValueKind == JsonValueKind.Object + && Text(content, "mimeType")?.Split(';')[0].Trim().ToLowerInvariant() is { Length: > 0 } mime + && SafeHeaderValue().IsMatch(mime)) + { + shape.Types.Add(mime); + } + } + + return shape; + } + + /// One field of the query string or of the body, described: name by , value by kind. + private static void Put(SortedDictionary into, Names names, string name, string? value) + { + if (name.Length == 0) + { + // A pair without a name or without «=»: the text itself could be anything. + Add(into, names.Remove(), JsonValue.Create("vuoto")!); + return; + } + + JsonNode node; + if (JsonFields.Contains(name)) + { + node = Structure(value, names); + } + else if (name == HarImporter.OperationParameter) + { + node = JsonValue.Create(HarImporter.OperationName(value) ?? ValueShape(name, value))!; + } + else if (KnownValueFields.Contains(name) && value is not null && SafeCodeValue().IsMatch(value)) + { + node = JsonValue.Create(value)!; + } + else + { + node = JsonValue.Create(ValueShape(name, value))!; + } + + Add(into, names.Safe(name), node); + } + + private static void Add(SortedDictionary into, string name, JsonNode node) => + into[name] = into.TryGetValue(name, out var known) ? MergeNodes(known, node) : node; + + /// The structure of a JSON text: names by , kinds of values, never a value. + private static JsonNode Structure(string? text, Names names) + { + if (string.IsNullOrEmpty(text)) + { + return JsonValue.Create("vuoto")!; + } + + try + { + return Structure(JsonNode.Parse(text, documentOptions: DeepDocuments), null, names); + } + catch (JsonException) + { + return JsonValue.Create("testo")!; + } + } + + private static JsonNode Structure(JsonNode? node, string? name, Names names) + { + switch (node) + { + case null: + return JsonValue.Create("nulla")!; + case JsonObject o: + var members = new SortedDictionary(StringComparer.Ordinal); + foreach (var (key, value) in o) + { + Add(members, names.Safe(key), Structure(value, key, names)); + } + + return new JsonObject(members.Select(m => KeyValuePair.Create(m.Key, (JsonNode?)m.Value))); + case JsonArray a: + // Every element described, then made one: a list says what its elements look like, not how many. + JsonNode? element = null; + foreach (var item in a.Take(1000)) + { + var described = Structure(item, name, names); + element = element is null ? described : MergeNodes(element, described); + } + + return element is null ? new JsonArray() : new JsonArray(element); + case JsonValue v when v.GetValueKind() is JsonValueKind.True or JsonValueKind.False: + return JsonValue.Create(v.GetValueKind() == JsonValueKind.True ? "true" : "false")!; + case JsonValue v when v.GetValueKind() == JsonValueKind.Number: + return JsonValue.Create(ValueShape(name ?? string.Empty, v.ToJsonString()))!; + case JsonValue v when v.GetValueKind() == JsonValueKind.String: + // The text «true» is a text, not a switch. + return JsonValue.Create(ValueShape(name ?? string.Empty, v.GetValue()) is "true" or "false" ? "testo" : ValueShape(name ?? string.Empty, v.GetValue()))!; + default: + return JsonValue.Create("testo")!; + } + } + + /// + /// Two descriptions of the same field made one: objects by the union of their keys, lists by their elements, values + /// by ; a structure (object or list) wins over a plain value. + /// + private static JsonNode MergeNodes(JsonNode a, JsonNode b) + { + switch (a, b) + { + case (JsonObject oa, JsonObject ob): + var members = new SortedDictionary(StringComparer.Ordinal); + foreach (var (key, value) in oa.Concat(ob)) + { + if (value is not null) + { + members[key] = members.TryGetValue(key, out var known) ? MergeNodes(known, value) : value.DeepClone(); + } + } + + return new JsonObject(members.Select(m => KeyValuePair.Create(m.Key, (JsonNode?)m.Value))); + case (JsonArray la, JsonArray lb): + return (la.Count, lb.Count) switch + { + (0, _) => lb.DeepClone(), + (_, 0) => la.DeepClone(), + _ => new JsonArray(MergeNodes(la[0]!, lb[0]!)), + }; + case (JsonValue va, JsonValue vb): + return JsonValue.Create(Generalize(Leaf(va), Leaf(vb)))!; + case (JsonValue, _): + return b.DeepClone(); + default: + return a.DeepClone(); + } + + static string Leaf(JsonValue value) => value.TryGetValue(out var text) ? text : value.ToJsonString(); + } + + /// + /// The fields of a request body: a form field by field, a JSON object member by member. Anything else is described + /// whole in («json» or «testo»), and never split on «&» and «=»: words of a search would + /// become names. + /// + private static List<(string Name, string? Value)> BodyFields(JsonElement request, out string? whole) + { + whole = null; + var fields = new List<(string, string?)>(); + if (!request.TryGetProperty("postData", out var post) || post.ValueKind != JsonValueKind.Object) + { + return fields; + } + + var mime = Text(post, "mimeType") ?? string.Empty; + var text = Text(post, "text"); + if (mime.Contains("x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase)) + { + if (post.TryGetProperty("params", out var parameters) && parameters.ValueKind == JsonValueKind.Array && parameters.GetArrayLength() > 0) + { + foreach (var parameter in parameters.EnumerateArray()) + { + if (parameter.ValueKind == JsonValueKind.Object && Text(parameter, "name") is { } name) + { + fields.Add((Unescape(name) ?? string.Empty, Unescape(Text(parameter, "value")))); + } + } + } + else if (text is not null) + { + fields.AddRange(Pairs(text)); + } + + return fields; + } + + if (string.IsNullOrWhiteSpace(text)) + { + return fields; + } + + // Not a form: JSON whatever the declared type (a fetch with a string body is «text/plain»), or else «testo». + var trimmed = text.TrimStart(); + if (trimmed.StartsWith('{') || trimmed.StartsWith('[')) + { + try + { + if (JsonNode.Parse(text, documentOptions: DeepDocuments) is JsonObject members) + { + foreach (var (name, value) in members) + { + fields.Add((name, value switch + { + null => null, + JsonValue v when v.GetValueKind() == JsonValueKind.String => v.GetValue(), + _ => value.ToJsonString(), + })); + } + + return fields; + } + + whole = "json"; + return fields; + } + catch (JsonException) + { + // Not JSON after all: described whole, below. + } + } + + whole = "testo"; + return fields; + } + + /// Name and value of each pair of a query string or a form; a pair without «=» has an empty name. + private static IEnumerable<(string Name, string? Value)> Pairs(string query) + { + foreach (var pair in query.TrimStart('?').Split('&', StringSplitOptions.RemoveEmptyEntries)) + { + var equals = pair.IndexOf('=', StringComparison.Ordinal); + yield return equals < 0 ? (string.Empty, null) : (Unescape(pair[..equals]) ?? string.Empty, Unescape(pair[(equals + 1)..])); + } + } + + private static string? RootField(string? value) + { + var name = value?.Trim(); + return name is not null && RootFieldShape().IsMatch(name) && !DigitRun().IsMatch(name) ? name : null; + } + + internal static string? Unescape(string? value) + { + if (value is null) + { + return null; + } + + try + { + return Uri.UnescapeDataString(value.Replace('+', ' ')); + } + catch (UriFormatException) + { + return null; + } + } + + internal static string? Text(JsonElement element, string property) => + element.TryGetProperty(property, out var value) && value.ValueKind == JsonValueKind.String ? value.GetString() : null; + + [GeneratedRegex("^[0-9]+$", RegexOptions.CultureInvariant)] + private static partial Regex Digits(); + + [GeneratedRegex("^[0-9]{1,3}$", RegexOptions.CultureInvariant)] + private static partial Regex SmallNumber(); + + [GeneratedRegex("[0-9]{3}", RegexOptions.CultureInvariant)] + private static partial Regex DigitRun(); + + // A name in the site's code: letters, digits, «_», «-» (e.g. «x-ig-app-id», «max_id», «__a»). No dot: user names + // have dots, names of the code do not. + [GeneratedRegex("^[A-Za-z_][A-Za-z0-9_-]{0,63}$", RegexOptions.CultureInvariant)] + private static partial Regex CodeName(); + + // A GraphQL root field, as in «x-root-field-name» (e.g. «xdt_api__v1__feed__user_timeline_graphql_connection»). + [GeneratedRegex("^[a-z][a-z0-9_]{2,127}$", RegexOptions.CultureInvariant)] + private static partial Regex RootFieldShape(); + + // A header value from the closed list: an identifier or a media type, never free text. + [GeneratedRegex("^[A-Za-z0-9_.,;=*/+ -]{1,80}$", RegexOptions.CultureInvariant)] + private static partial Regex SafeHeaderValue(); + + // A value of the closed list of fields: an identifier of the site's code (doc_id is a long number of the code, + // query_hash a hexadecimal one, not of a person). + [GeneratedRegex("^[A-Za-z0-9_]{1,96}$", RegexOptions.CultureInvariant)] + private static partial Regex SafeCodeValue(); + + /// Decides which names are written: the closed lists, or the shape of a code name that is never a value. + private sealed class Names(HashSet values) + { + public int Removed { get; private set; } + + public string Safe(string name) + { + if (KnownNames.Contains(name) || KnownValueFields.Contains(name) || JsonFields.Contains(name) + || PageSizeNames.Contains(name) || KnownHeaderValues.Contains(name)) + { + return name; + } + + return CodeName().IsMatch(name) && !DigitRun().IsMatch(name) && !values.Contains(name) ? name : Remove(); + } + + public string Remove() + { + Removed++; + return RemovedName; + } + } + + /// One distinct request: method, path pattern, operation and query identifier, with all its occurrences. + private sealed class Shape(string method, string path, string resource) + { + public string Method { get; } = method; + + public string Path { get; } = path; + + public string Resource { get; } = resource; + + public string? Operation { get; set; } + + public string? RootField { get; set; } + + public string QueryIdentifier { get; set; } = string.Empty; + + public SortedDictionary Parameters { get; } = new(StringComparer.Ordinal); + + public SortedDictionary Headers { get; } = new(StringComparer.Ordinal); + + public SortedDictionary Body { get; } = new(StringComparer.Ordinal); + + public SortedSet Statuses { get; } = []; + + public SortedSet Types { get; } = new(StringComparer.Ordinal); + + public int Times { get; private set; } = 1; + + public string Key => $"{Method} {Path} {Operation} {RootField} {QueryIdentifier}"; + + public void Merge(Shape other) + { + Times++; + foreach (var (name, value) in other.Parameters) + { + Add(Parameters, name, value); + } + + foreach (var (name, value) in other.Body) + { + Add(Body, name, value); + } + + foreach (var (name, value) in other.Headers) + { + Headers[name] = Headers.TryGetValue(name, out var known) && known != value ? RequestShapes.Removed : value; + } + + Statuses.UnionWith(other.Statuses); + Types.UnionWith(other.Types); + } + + public JsonObject ToJson() => new() + { + ["metodo"] = Method, + ["percorso"] = Path, + ["operazione"] = Operation, + ["campo_radice"] = RootField, + ["risorsa"] = Resource, + ["volte"] = Times, + ["parametri"] = new JsonObject(Parameters.Select(p => KeyValuePair.Create(p.Key, (JsonNode?)p.Value.DeepClone()))), + ["intestazioni"] = new JsonObject(Headers.Select(p => KeyValuePair.Create(p.Key, (JsonNode?)JsonValue.Create(p.Value)))), + ["corpo"] = new JsonObject(Body.Select(p => KeyValuePair.Create(p.Key, (JsonNode?)p.Value.DeepClone()))), + ["stati"] = new JsonArray(Statuses.Select(s => (JsonNode)JsonValue.Create(s)).ToArray()), + ["tipi"] = new JsonArray(Types.Select(t => (JsonNode)JsonValue.Create(t)).ToArray()), + }; + } +} + +/// +/// 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. +/// +internal static class ValueCollector +{ + private const int MaxBodyChars = 64 * 1024 * 1024; + + private const string ScriptGuard = "for (;;);"; + + private static readonly char[] HeaderSeparators = [';', ',', '=', ' ']; + + public static HashSet Collect(JsonElement entries) + { + var values = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var entry in entries.EnumerateArray()) + { + if (entry.ValueKind != JsonValueKind.Object) + { + continue; + } + + if (entry.TryGetProperty("request", out var request) && request.ValueKind == JsonValueKind.Object) + { + Address(values, RequestShapes.Text(request, "url")); + Headers(values, request); + PairValues(values, request, "queryString"); + PairValues(values, request, "cookies"); + if (request.TryGetProperty("postData", out var post) && post.ValueKind == JsonValueKind.Object) + { + PairValues(values, post, "params"); + if (RequestShapes.Text(post, "text") is { } text) + { + Body(values, text); + } + } + } + + if (entry.TryGetProperty("response", out var response) && response.ValueKind == JsonValueKind.Object) + { + Headers(values, response); + PairValues(values, response, "cookies"); + Address(values, RequestShapes.Text(response, "redirectURL")); + if (response.TryGetProperty("content", out var content) && content.ValueKind == JsonValueKind.Object + && RequestShapes.Text(content, "text") is { Length: > 0 and <= MaxBodyChars } body) + { + if (RequestShapes.Text(content, "encoding") == "base64") + { + try + { + body = Encoding.UTF8.GetString(Convert.FromBase64String(body)); + } + catch (FormatException) + { + continue; + } + } + + if ((RequestShapes.Text(content, "mimeType") ?? string.Empty).Contains("html", StringComparison.OrdinalIgnoreCase)) + { + foreach (var block in DataResponses.EmbeddedJsonBlocks(body)) + { + using (block) + { + Element(values, block.RootElement); + } + } + } + else + { + Body(values, body); + } + } + } + } + + return values; + } + + private static void Add(HashSet values, string? value) + { + var text = value?.Trim(); + if (string.IsNullOrEmpty(text) || text.Length > 512) + { + return; + } + + values.Add(text); + if (text.StartsWith('@') && text.Length > 1) + { + values.Add(text[1..]); + } + } + + private static void Address(HashSet values, string? url) + { + if (string.IsNullOrEmpty(url) || !Uri.TryCreate(url, UriKind.Absolute, out var uri)) + { + return; + } + + foreach (var segment in uri.AbsolutePath.Split('/', StringSplitOptions.RemoveEmptyEntries)) + { + Add(values, RequestShapes.Unescape(segment)); + } + + Form(values, uri.Query); + Form(values, uri.Fragment.TrimStart('#')); + } + + /// The values of a query string or a form; a pair without «=» is all value. + private static void Form(HashSet values, string text) + { + foreach (var pair in text.TrimStart('?').Split('&', StringSplitOptions.RemoveEmptyEntries)) + { + var equals = pair.IndexOf('=', StringComparison.Ordinal); + var value = RequestShapes.Unescape(equals < 0 ? pair : pair[(equals + 1)..]); + Add(values, value); + if (value is not null) + { + Json(values, value); + } + } + } + + private static void Headers(HashSet values, JsonElement message) + { + if (!message.TryGetProperty("headers", out var headers) || headers.ValueKind != JsonValueKind.Array) + { + return; + } + + foreach (var header in headers.EnumerateArray()) + { + if (header.ValueKind == JsonValueKind.Object && RequestShapes.Text(header, "value") is { } value) + { + Add(values, value); + foreach (var part in value.Split(HeaderSeparators, StringSplitOptions.RemoveEmptyEntries)) + { + Add(values, part); + } + + Address(values, value); + } + } + } + + private static void PairValues(HashSet values, JsonElement owner, string property) + { + if (!owner.TryGetProperty(property, out var pairs) || pairs.ValueKind != JsonValueKind.Array) + { + return; + } + + foreach (var pair in pairs.EnumerateArray()) + { + if (pair.ValueKind == JsonValueKind.Object && RequestShapes.Unescape(RequestShapes.Text(pair, "value")) is { } value) + { + Add(values, value); + Json(values, value); + } + } + } + + /// A body: one or more JSON values (Instagram may send several in a row, after «for (;;);»), or a form, or text. + private static void Body(HashSet values, string text) + { + var trimmed = text.TrimStart(); + if (trimmed.StartsWith(ScriptGuard, StringComparison.Ordinal)) + { + trimmed = trimmed[ScriptGuard.Length..].TrimStart(); + } + + if (!Json(values, trimmed)) + { + Form(values, trimmed); + } + } + + /// Every string value (not the names) of the JSON values in ; false if it is not JSON. + private static bool Json(HashSet values, string text) + { + var trimmed = text.TrimStart(); + if (!trimmed.StartsWith('{') && !trimmed.StartsWith('[')) + { + return false; + } + + var reader = new Utf8JsonReader(Encoding.UTF8.GetBytes(trimmed), new JsonReaderOptions { AllowMultipleValues = true, CommentHandling = JsonCommentHandling.Skip, MaxDepth = 256 }); + var any = false; + try + { + while (reader.Read()) + { + any = true; + if (reader.TokenType == JsonTokenType.String) + { + var value = reader.GetString(); + Add(values, value); + if (value is not null && value.Length is > 1 and < 65536) + { + // A JSON text inside a string (GraphQL variables): its values too. + Json(values, value); + } + } + } + } + catch (JsonException) + { + // The values read up to here are kept: a truncated body still names what it held. + } + + return any; + } + + private static void Element(HashSet values, JsonElement element) + { + switch (element.ValueKind) + { + case JsonValueKind.Object: + foreach (var property in element.EnumerateObject()) + { + Element(values, property.Value); + } + + break; + case JsonValueKind.Array: + foreach (var item in element.EnumerateArray()) + { + Element(values, item); + } + + break; + case JsonValueKind.String: + Add(values, element.GetString()); + break; + } + } +}