diff --git a/docker/compose.yml b/docker/compose.yml
index 0659eea..c74b49e 100644
--- a/docker/compose.yml
+++ b/docker/compose.yml
@@ -53,4 +53,6 @@ services:
# FEBE_HOST: "tower.local,192.168.1.10" # nomi con cui raggiungi l'interfaccia (gli altri sono rifiutati)
# FEBE_PROXY_FIDATO: "1" # dietro un proxy con HTTPS che passa X-Forwarded-Host e -Proto
# FEBE_SENZA_SANDBOX: "1" # solo se Chromium non parte: vedi docs/docker.md, «Sandbox»
+ # FEBE_RACCOLTA: "pagine" # pagine (predefinito) o richieste: vedi docs/docker.md, «Variabili»
+ # FEBE_CHIAVE_SESSIONE: ${FEBE_CHIAVE_SESSIONE} # chiave della sessione salvata fuori da /dati (openssl rand -base64 32)
# Chromium usa /tmp invece della memoria condivisa (--disable-dev-shm-usage): shm_size non serve.
diff --git a/docker/unraid/febe.xml b/docker/unraid/febe.xml
index 31b7577..c9d1bd9 100644
--- a/docker/unraid/febe.xml
+++ b/docker/unraid/febe.xml
@@ -32,4 +32,6 @@
100
+
+
diff --git a/docs/SPECIFICA.md b/docs/SPECIFICA.md
index 9ad8fd8..844a3ac 100644
--- a/docs/SPECIFICA.md
+++ b/docs/SPECIFICA.md
@@ -314,18 +314,39 @@ public interface IRandomSource { double NextDouble(); }
Decisione di Alberto del 16 novembre 2026 (issue #36). Il lavoro è a tappe (S0–S7 nell'issue); finché una tappa non è unita, il comportamento di Febe è quello delle sezioni che seguono.
-**Come nasce la sessione.** Alberto accede a mano nel browser di Febe (§4.1). Quando preme «Ho finito», Febe copia nella **sessione salvata**:
+**Come nasce la sessione.** Alberto accede a mano nel browser di Febe (§4.1). Quando preme «Ho finito», con la raccolta `richieste` (tappa S4, più sotto), Febe copia nella **sessione salvata**:
-- i cookie di Instagram, valori compresi, con `Network.getCookies` (§6.1);
-- l'user agent del browser, letto con `Runtime.evaluate` in sola lettura (`navigator.userAgent`), tale e quale;
-- i dati che la pagina tiene nei propri moduli, letti con un'espressione in sola lettura: i gettoni (`DTSGInitialData`, `LSD`), l'identificativo dell'account (`CurrentUserInitialData`), i `doc_id` delle sole operazioni di `richieste..json` (moduli `_instagramRelayOperation`) e i campi di versione che il modello chiede. Il valore di `x-csrftoken` è quello del cookie `csrftoken` (decisione del 16 novembre: la pagina stessa lo legge così con `getCSRFToken()`).
+- i cookie del sito, valori compresi, con `Network.getCookies` (§6.1), chiesti per la radice del sito e per ogni percorso di `richieste..json` tagliato prima del primo valore (`/api/dati/profilo/{nome}` → `/api/dati/profilo/`), così un cookie limitato a un percorso arriva con il suo percorso. Di ogni cookie si tengono nome, valore, dominio, percorso, solo-host, `Secure`, `HttpOnly` e scadenza. Un cookie partizionato, o con un valore che il browser non rimanderebbe (caratteri di controllo, non ASCII, `;`), si scarta e si conta;
+- l'user agent del browser (`navigator.userAgent`), tale e quale;
+- i valori che la pagina tiene nei propri moduli, nei soli posti scritti nella sezione `page` di `richieste..json` (tabella qui sotto) e i `doc_id` delle operazioni GraphQL del catalogo (modulo `docIdModule`, su Instagram `_instagramRelayOperation`, che esporta il `doc_id`). Il valore di `x-csrftoken` è quello del cookie `csrftoken` che il browser manderebbe a quell'indirizzo (decisione del 16 novembre: la pagina stessa lo legge così con `getCSRFToken()`).
-La sessione salvata sta in `Dati/sessione/sessione.json`, cifrata (§13.2), fuori dal database e dalle sue copie. Dopo la copia il browser si chiude o torna al riposo; si riapre solo per un nuovo accesso o per una verifica, e intanto il motore è fermo (regola 4). Un nuovo accesso ricopia tutto e sostituisce la sessione salvata. Nei cookie del browser Febe non scrive mai.
+User agent e valori della pagina si leggono con **una sola** `Runtime.evaluate` in sola lettura, scritta solo dai nomi della sezione `page` (identificatori controllati al caricamento del catalogo, `^[A-Za-z_$][A-Za-z0-9_$]*$`, messi nell'espressione come testi JSON: una copia modificata del file non può metterci codice) e passata da `ReadOnlyScriptGuard`. Ogni modulo si legge nel suo `try`: un modulo assente o che la pagina rifiuta, un valore che non è testo o numero, più lungo di 4096 caratteri o con caratteri di controllo o non ASCII **manca**, e non si inventa (regola 9).
+
+La copia si fa solo da una pagina del sito che non sia un percorso di accesso o di verifica delle regole di arresto (§7.6), dentro i comandi del collegamento, dopo il controllo del cookie di sessione e prima del riposo, e solo finché dura il permesso di guida di Alberto («Accedi a Instagram», «Usa il browser»): Febe tiene il permesso e il turno della pagina per tutta la copia, e se il permesso finisce comunque prima del salvataggio la copia si butta. Dura al più 10 secondi; oltre, è un errore del browser. Una copia riuscita **sostituisce** la sessione salvata anche se manca qualche valore: tenere una copia più vecchia potrebbe tenere i cookie di un altro accesso. Il messaggio di «Ho finito» conta solo i valori e i `doc_id` che un'operazione configurata manda, e dice com'è: le richieste che li usano non partono e, alla prima, Febe si ferma come disconnessione e chiede un nuovo accesso (mai un ritorno alle pagine) finché un nuovo «Ho finito» non li trova. Dopo «Ho finito» il permesso di guida è finito: per rifare la copia Alberto riapre il browser dalla pagina Collegamento («Usa il browser» o «Pagina iniziale») e preme di nuovo «Ho finito», ed è ciò che il messaggio di una copia rifiutata gli dice. Una copia rifiutata (pagina fuori dal sito, pagina di accesso o verifica, browser che non risponde, nessun user agent) la lascia com'era. Chiudere la finestra del browser su Windows o lasciar scadere il permesso di guida **non** copia: serve «Ho finito». Con il sito di prova e `--accesso-di-prova` la copia si fa anche dopo l'accesso automatico, come la farebbe Alberto.
+
+| Valore della sessione | Nella richiesta | Dove lo tiene la pagina di Instagram |
+|---|---|---|
+| `lsd` | `x-fb-lsd` | `LSD.token` |
+| `fb_dtsg` | `fb_dtsg` | `DTSGInitialData.token` |
+| `account_id` | `av`, `__user` | `CurrentUserInitialData.USER_ID` |
+| `app_id` | `x-ig-app-id` | `CurrentUserInitialData.APP_ID` |
+| `rev` | `__rev` | `SiteData.client_revision` |
+| `hs` | `__hs` | `SiteData.haste_session` |
+| `hsi` | `__hsi` | `SiteData.hsi` |
+| `dpr` | `dpr` (prima costante 1) | `SiteData.pr` |
+| `comet_req` | `__comet_req` (prima costante 7) | `SiteData.comet_env` |
+| `ccg` | `__ccg` | `WebConnectionClassServerGuess.connectionClass` |
+| `entry_nonce` | `x-fb-entry-nonce` | `BootloaderConfig.nonce` |
+| `doc_id` | `doc_id` | modulo `_instagramRelayOperation` |
+
+I posti vengono dal codice pubblico della pagina nel HAR, solo forme e nomi (regola 9; decisione del 17 novembre 2026). Il catalogo rifiuta, quando si carica, un'operazione configurata che manda un valore `session:` senza posto nella sezione `page` (user agent e claim non ne hanno bisogno).
+
+La sessione salvata sta in `Dati/sessione/sessione.json`, cifrata (§13.2), fuori dal database e dalle sue copie. Dopo la copia il browser si chiude o torna al riposo; si riapre solo per un nuovo accesso o per una verifica, e intanto il motore è fermo (regola 4). Un nuovo accesso ricopia tutto e sostituisce la sessione salvata: i valori della pagina restano quelli copiati fino alla copia dopo. Nei cookie del browser Febe non scrive mai.
**Il client del sito.** Una sola classe di Febe parla con `www.instagram.com` (regola 1):
- chiede solo le operazioni di `richieste..json`, scritto da campioni reali con `febe-sonda richieste` (§14.5): metodo, percorso, nome dell'operazione, variabili con i soli valori del caso (nome o identificativo dell'account, cursore, testo cercato), nomi delle intestazioni. Rifiuta ogni nome che finisce in `Mutation` e ogni percorso fuori dall'elenco, compresi telemetria, chat e sincronizzazione con facebook.com;
-- manda l'user agent e i cookie della sessione salvata, le intestazioni del modello con i valori della sessione, e nient'altro. Aggiorna nella sessione salvata i cookie che il sito rinnova (`Set-Cookie`) e il valore di `x-ig-www-claim` che il sito manda in `x-ig-set-www-claim`;
+- manda l'user agent e i cookie della sessione salvata, le intestazioni del modello con i valori della sessione, e nient'altro. Un cookie va solo all'indirizzo che gli corrisponde per dominio e percorso (RFC 6265 §5.1.3, §5.1.4), i percorsi più lunghi prima, e se è `Secure` solo in https, come lo manderebbe il browser. Aggiorna nella sessione salvata i cookie che il sito rinnova (`Set-Cookie`: senza `Domain` è solo-host sull'host della richiesta, senza `Path` prende il percorso predefinito della richiesta; l'identità di un cookie è nome, dominio, percorso e solo-host, come in Chromium) e il valore di `x-ig-www-claim` che il sito manda in `x-ig-set-www-claim`. Un valore che la richiesta vuole e la sessione salvata non ha non si inventa: la richiesta non parte e la ricetta si ferma come Disconnessione («nella sessione salvata manca …», §7.6), mai con un ritorno alle pagine;
- **non segue i rinvii**: un 3xx è un segnale (§7.6), mai un nuovo indirizzo da visitare;
- una richiesta per volta, ciascuna con il permesso del Governatore (§7.4) e la distanza minima di §7.7; mai in parallelo;
- dalla stessa rete del browser: in Docker lo stesso contenitore, su Windows le impostazioni proxy del sistema, come WebView2;
@@ -336,7 +357,17 @@ Le risposte vanno ai lettori come quelle catturate (§6.2, §6.4), con gli stess
**Che cosa non cambia.** Sola lettura (regola 5), Governatore (regola 7), arresto al primo segnale (regola 8), niente CAPTCHA (regola 3), formati mai inventati (regola 10), browser usato così com'è per l'accesso e le verifiche (regola 2).
-**Le ricette per richieste (tappa S3).** Una ricetta va per richieste quando ogni ruolo che le serve (§6.3) appartiene a un'operazione configurata di `richieste..json`; altrimenti va con il browser, come prima. Con Instagram nessuna delle dieci operazioni è ancora configurata: tutte le ricette restano sulle pagine finché la tappa S4 non porta la sessione salvata e i `doc_id`. Febe per Windows e Febe in Docker non costruiscono ancora il client del sito per il motore (S4); lo usano le prove, con il sito di prova. Una ricetta per richieste non tocca mai la pagina, e dopo un segnale non torna alle pagine (regola 7): si ferma.
+**Le ricette per richieste (tappa S3).** Una ricetta va per richieste quando ogni ruolo che le serve (§6.3) appartiene a un'operazione configurata di `richieste..json`; altrimenti va con il browser, come prima. Una ricetta per richieste non tocca mai la pagina, e dopo un segnale non torna alle pagine (regola 7): si ferma.
+
+**La sessione salvata e l'opzione «raccolta» (tappa S4).** Febe per Windows e Febe in Docker hanno un'opzione **«raccolta»**: `pagine`, il predefinito, oppure `richieste`. In Docker si sceglie con `--raccolta` o con la variabile `FEBE_RACCOLTA` (vince la riga di comando), su Windows con `--raccolta` (Febe.exe non ha altre fonti di opzioni). Solo con `richieste` **e** un catalogo del sito con almeno un'operazione configurata la composizione costruisce la sessione salvata, il client del sito per il motore e la copia a «Ho finito»; altrimenti non costruisce nulla, non legge i valori dei cookie né i moduli della pagina, e tutto resta com'era: con `pagine` sempre, e con Instagram anche con `richieste`, perché le sue dieci operazioni restano non configurate (decisione del 17 novembre 2026). Il registro dice quale delle due strade ha preso. Con il sito di prova e `pagine` nemmeno le prove d'insieme cambiano strada.
+
+Perché la porta resta chiusa con Instagram:
+
+- chiedere `require()` di un modulo dentro la pagina viva di Instagram potrebbe eseguire la fabbrica di un modulo non ancora avviato o far segnalare un errore dalla pagina (H21, da verificare con Alberto prima di accenderla);
+- i moduli dei `doc_id` potrebbero non essere caricati sulla pagina dove Alberto preme «Ho finito» (H22);
+- restano senza fonte stabilita (`pending`) valori che le richieste di Instagram contengono: `__spin_r`, `__spin_b`, `__spin_t` (la pagina ha chiavi con quei nomi, ma non si vede chi le mette nella richiesta), `__req` (contatore delle richieste), `__s` (sessione della pagina), `__dyn`, `__csr`, `__hblp`, `__hsdp`, `__sjsp` (moduli caricati), `__crn` (percorso della pagina), `__d`, `x-web-session-id`, le intestazioni del browser (`referer`, `priority`, `sec-ch-ua…`, `x-ig-max-touch-points`) e i nomi che la sonda ha tolto. Un'operazione che ne usa uno non si può configurare (regola 9, H15).
+
+Il sito di prova ha già tutto: un cookie `csrftoken`, un cookie limitato a `/api/` e un registro di moduli con nomi suoi (§14.2), e le prove copiano a «Ho finito» la sessione del browser di prova e la usano con il client del sito.
### 6.1 Il browser
@@ -359,7 +390,7 @@ Le risposte vanno ai lettori come quelle catturate (§6.2, §6.4), con gli stess
| 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`, per sapere se il cookie di sessione esiste; il valore non si registra mai |
-| Copiare la sessione (§6.0, decisione del 16 novembre 2026) | `Network.getCookies` con i valori, una volta a «Ho finito», direttamente nella sessione salvata; `Runtime.evaluate` in sola lettura per l'user agent e per i dati dei moduli della pagina elencati in §6.0 |
+| Copiare la sessione (§6.0, decisioni del 16 e del 17 novembre 2026) | Solo con la raccolta `richieste` e un catalogo con operazioni configurate (mai con Instagram nella tappa S4), una volta a «Ho finito» (e dopo l'accesso automatico del sito di prova): `Page.getFrameTree` per sapere su che pagina si è; `Network.getCookies` con i valori per la radice del sito e per i percorsi del catalogo, direttamente nella sessione salvata; **una** `Runtime.evaluate` in sola lettura con `returnByValue`, scritta solo dagli identificatori della sezione `page` di `richieste..json`, per l'user agent, i valori della tabella di §6.0 e i `doc_id`, con un `try` per modulo |
| Chiedere i dati alla pagina (storia: decisione del 12 novembre 2026, sostituita dal client del sito) | `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.
@@ -456,6 +487,8 @@ Finché una voce non ha un esito scritto in `docs/sonda/esito.md`, non costruirc
| H18 | I cursori sono gli stessi per pagine e richieste: un punto salvato dalle pagine si riprende con una richiesta, e viceversa |
| H19 | Un 404 con JSON vuol dire risorsa assente, un 5xx errore temporaneo: la ricetta non insiste e si riprova al giro dopo (da confermare, Alberto) |
| H20 | Una raccolta in evidenza si chiede con l'identificativo che il profilo dà nell'elenco delle raccolte, così com'è (sul sito di prova sì; su Instagram potrebbe servire il prefisso `highlight:`) |
+| H21 | Su Instagram `require()` dei moduli della sezione `page` (§6.0), chiesto dalla copia a «Ho finito», non ha effetti: non esegue la fabbrica di un modulo non ancora avviato che faccia qualcosa, e un modulo assente non fa partire dalla pagina una segnalazione d'errore verso il sito. Finché non è verificata (con Alberto), con Instagram la copia non si accende (§6.0, «raccolta») |
+| H22 | Sulla pagina dove Alberto preme «Ho finito» (di solito la pagina iniziale) i moduli dei `doc_id` delle operazioni del catalogo (`_instagramRelayOperation`) e i moduli dei valori sono già caricati; se no, quali pagine li caricano. Un `doc_id` assente manca nella sessione salvata e la richiesta che lo vuole non parte |
| S1 | In WebView2 funzionano attraverso CDP il corpo delle risposte, i gesti e i fotogrammi della pagina |
| S2 | Su Windows la pagina continua a caricare e a rispondere allo scorrimento quando la finestra del browser non è in vista |
| S3 | L'accesso fatto a mano sopravvive al riavvio del programma, in Docker e su Windows |
@@ -836,6 +869,8 @@ Il divieto di modalità headless della regola 2 riguarda il browser che visita I
| `TZ` | Fuso orario | Europe/Rome |
| `LANG` | Lingua del contenitore e del browser | it_IT.UTF-8 |
| `PUID`, `PGID` | Utente e gruppo dei file | 99, 100 |
+| `FEBE_RACCOLTA` | Opzione «raccolta» di §6.0: `pagine` o `richieste` (`--raccolta` sulla riga di comando vince) | `pagine` |
+| `FEBE_CHIAVE_SESSIONE` | Chiave AES-256 della sessione salvata (§13.2), 32 byte in base64; facoltativa, serve a tenerla fuori da `/dati` | `Dati/sessione/chiave.bin` |
- Se `FEBE_PASSWORD` manca, o `/dati` non è scrivibile o è una condivisione di rete, il motore non parte e l'interfaccia mostra una sola pagina che spiega che cosa non va e come rimediare. Vale dal primo contenitore che costruisci, compreso quello di prova di M0: la vista remota non deve mai essere raggiungibile senza password.
- **Accesso a Instagram.** Solo dalla pagina Collegamento, con la vista remota: i fotogrammi del browser arrivano all'interfaccia e i gesti di Alberto tornano al browser. Ciò che scrive, password compresa, attraversa la rete di casa e la memoria del server senza essere registrato: la pagina lo dice (mockup 10). Per questo l'interfaccia non va mai esposta su Internet senza una VPN o un proxy con HTTPS: scrivilo nella guida.
@@ -865,7 +900,14 @@ Il divieto di modalità headless della regola 2 riguarda il browser che visita I
### 13.2 Dati riservati
-- La sessione di Instagram vive nel profilo del browser dentro la cartella dei dati e, dal 16 novembre 2026 (§6.0), nella sessione salvata `Dati/sessione/sessione.json`: cookie, user agent, gettoni e `doc_id`. Il file è cifrato: su Windows con DPAPI dell'utente (`ProtectedData`, nella libreria del desktop di .NET, nessun pacchetto nuovo); in Docker con AES-256-GCM e una chiave a 256 bit presa dalla variabile `FEBE_CHIAVE_SESSIONE` o, se manca, dal file `Dati/sessione/chiave.bin` con permessi del solo proprietario. Si scrive in modo atomico. Non va nel database, nelle copie giornaliere, nel rapporto di diagnostica né nell'interfaccia; Febe non lo esporta e non accetta sessioni incollate da fuori. «Scollega» lo cancella. Chi ha accesso alla cartella dei dati e alla chiave ha accesso alla sessione.
+- La sessione di Instagram vive nel profilo del browser dentro la cartella dei dati e, dal 16 novembre 2026 (§6.0), nella sessione salvata `Dati/sessione/sessione.json`: cookie, user agent, gettoni e `doc_id`. Esiste solo con la raccolta `richieste` e un catalogo con operazioni configurate (§6.0); con Instagram, nella tappa S4, non si crea. Il file è cifrato e porta un'intestazione `FEBS` con versione e schema:
+ - su Windows con DPAPI dell'utente corrente (`ProtectedData`, nella libreria del desktop di .NET, nessun pacchetto nuovo): solo quell'utente di Windows, su quel computer, lo apre; non c'è file della chiave;
+ - in Docker con AES-256-GCM, un nonce nuovo a ogni scrittura e l'intestazione come dati associati, e una chiave a 256 bit presa dalla variabile `FEBE_CHIAVE_SESSIONE` (32 byte in base64, per esempio `openssl rand -base64 32`, o 64 cifre esadecimali) o, se manca, dal file `Dati/sessione/chiave.bin`, creato una volta con `RandomNumberGenerator` e mai rigenerato. Una `FEBE_CHIAVE_SESSIONE` sbagliata è sempre un problema di configurazione all'avvio (motore e browser non partono, la pagina d'errore lo spiega senza ripetere il valore); un `chiave.bin` che non è una chiave lo è solo con `richieste`. Con la variabile impostata un `chiave.bin` rimasto non si usa e il registro lo dice.
+
+ Su Unix la cartella `Dati/sessione` è 0700 e i suoi file 0600 dalla creazione (`File.SetUnixFileMode`); un `chiave.bin` più aperto si restringe e il registro lo dice. Si scrive in modo atomico: un file `.part` nella stessa cartella, scritto fino al disco, poi rinominato sul vecchio. Sostituire, aggiornare e cancellare passano da un solo semaforo; un aggiornamento ricontrolla sessione e copia dopo averlo preso, così una risposta tardiva non riporta in vita una sessione cancellata né tocca quella di un accesso nuovo. Una scrittura che il disco rifiuta tiene i valori nuovi in memoria (il sito ha già cambiato i cookie), scrive nel registro una riga con il solo tipo d'errore e si riprova alla scrittura dopo. Un file che non si legge (altra chiave o altro utente, rovinato, altro formato) è nessuna sessione, detto nel registro e lasciato com'è finché una copia nuova non lo sostituisce: mai un arresto del programma.
+
+ Non va nel database, nelle copie giornaliere, nel rapporto di diagnostica né nell'interfaccia; Febe non lo esporta e non accetta sessioni incollate da fuori. **«Scollega»** cancella la sessione salvata prima del profilo del browser: prima in memoria, poi il file (e i `.part` rimasti), senza annullamento; con `pagine` cancella comunque un `sessione.json` lasciato da un avvio con `richieste`. `chiave.bin` resta. Un file che non si cancella è un fallimento parziale detto ad Alberto: Febe non lo usa più finché resta acceso, ma al prossimo avvio con `richieste` lo rileggerebbe, quindi il messaggio chiede di riprovare «Scollega» o di cancellare a mano la cartella `sessione` prima di riavviare. Chi ha accesso alla cartella dei dati e alla chiave (in Docker), o all'utente di Windows, ha accesso alla sessione.
+- `FEBE_PASSWORD` e `FEBE_CHIAVE_SESSIONE` si tolgono dall'ambiente di ogni processo che Febe avvia (Chromium o Edge, Xvfb, ffmpeg, ffprobe): un figlio eredita l'ambiente del padre, e Chromium esegue il codice del sito. La password e la chiave non si passano mai sulla riga di comando e non compaiono in nessun testo di Febe (registri, problemi, descrizione delle opzioni: solo «impostata», «assente» o «non valida»).
- Password e codici non entrano mai nei registri. Nella vista remota i tasti vanno al browser e non si conservano.
- I registri contengono azioni ed esiti, non contenuti: nomi utente sì, didascalie e corpi delle risposte no. Il client CDP registra solo nomi di comandi (§6.1); il client del sito solo operazione o forma del percorso e stato (§6.0). Il rapporto di diagnostica (§7.9) è più severo dei registri: nemmeno i nomi utente, né indirizzi interi, solo forme, conteggi e codici di elenchi chiusi, perché è fatto per uscire dalla macchina di Alberto. Per le richieste verso Telegram e verso il CDN non si registrano gli indirizzi: contengono il gettone del bot e le firme dei file.
- I campioni grezzi della sonda stanno fuori dal repository e si cancellano a fine M0 (§14.5).
@@ -890,7 +932,7 @@ Eventi che meritano un avviso: verifica richiesta, disconnessione, fermo per ral
### 14.2 Sito di prova
-`tools/Febe.SitoDiProva` è un piccolo sito locale che espone gli stessi dati dei campioni attraverso pagine spoglie: una griglia che carica altre pagine scorrendo, un visualizzatore, un elenco, e i casi di arresto (stato 429, rinvio a una pagina di verifica, uscita dalla sessione). Non ha marchi né grafica di Instagram e non ha un vero modulo d'accesso: non deve somigliargli, deve solo far girare ricette, cattura e motore senza toccare Instagram. Per il client del sito (§6.0) risponde alle stesse forme di richiesta e di risposta dei campioni ripuliti (per esempio `POST /api/graphql` con `doc_id` e le risposte dei campioni), controlla il cookie di sessione di prova e le intestazioni attese, e simula i casi d'arresto: 429, rinvio all'accesso o a una verifica, HTML al posto del JSON, JSON senza i campi attesi, cookie rinnovati o cancellati. Le forme dei casi d'arresto non note da campioni sono generiche e marcate H16. Ha la sua mappa dei bersagli (`bersagli.prova.json`): le ricette sono le stesse, cambia solo dove trovano le cose. Tutte le prove d'insieme passano da qui.
+`tools/Febe.SitoDiProva` è un piccolo sito locale che espone gli stessi dati dei campioni attraverso pagine spoglie: una griglia che carica altre pagine scorrendo, un visualizzatore, un elenco, e i casi di arresto (stato 429, rinvio a una pagina di verifica, uscita dalla sessione). Non ha marchi né grafica di Instagram e non ha un vero modulo d'accesso: non deve somigliargli, deve solo far girare ricette, cattura e motore senza toccare Instagram. Per il client del sito (§6.0) risponde alle stesse forme di richiesta e di risposta dei campioni ripuliti (per esempio `POST /api/graphql` con `doc_id` e le risposte dei campioni), controlla il cookie di sessione di prova e le intestazioni attese, e simula i casi d'arresto: 429, rinvio all'accesso o a una verifica, HTML al posto del JSON, JSON senza i campi attesi, cookie rinnovati o cancellati. Le forme dei casi d'arresto non note da campioni sono generiche e marcate H16. Per la copia a «Ho finito» (tappa S4) le sue pagine danno ciò che darebbe un sito vero: un cookie `csrftoken`, un cookie limitato a `/api/` e un piccolo registro di moduli (`__d`, `require`) con nomi suoi, mai quelli di Instagram, scritti nella sezione `page` di `richieste.prova.json`; un valore mancante o diverso riceve lo stesso 400 generico. Ha la sua mappa dei bersagli (`bersagli.prova.json`): le ricette sono le stesse, cambia solo dove trovano le cose. Tutte le prove d'insieme passano da qui.
### 14.3 Simulazione
diff --git a/docs/decisioni.md b/docs/decisioni.md
index 420cb37..bd24b83 100644
--- a/docs/decisioni.md
+++ b/docs/decisioni.md
@@ -407,3 +407,16 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15).
| 2026-11-17 | Un «non trovato» delle storie di un account per richieste non è ancora «nessuna storia»: la ricetta chiede il profilo (un profilo aperto) e fa ciò che fanno le pagine: profilo sparito o privato non seguito, account non raggiungibile; altrimenti nessuna storia. Quel 404 non conta come pagina vuota; una risposta delle storie riconosciuta conta come dati | Il sito di prova risponde 404 alle storie di un profilo privato che Alberto non segue: senza il profilo l'account restava da contattare a ogni giro (regola 6), e tre 404 di fila sarebbero diventati un Rallentamento di tutto il motore |
| 2026-11-17 | Una raccolta in evidenza per richieste legge al più `PagesPerRun` pagine per volta e collega i contenuti di ogni pagina appena letta; l'ordine della raccolta si salva solo letta fino in fondo | Una raccolta lunga non consuma da sola l'ora delle storie viste, e un arresto su una pagina successiva non butta ciò che si è già letto e pagato |
| 2026-11-17 | Il motore controlla il tetto della prima azione della strada che la ricetta prende (`IRecipeRunner.FirstCategory`): per richieste Taggati e Reel cominciano con una pagina di storico, non con un profilo aperto; per pagine e con Instagram resta `CheckPolicy.CategoryOf`. Una ricetta per richieste può tornare alle pagine per un'esecuzione (valore mancante, pagina successiva senza richiesta): il motore la salta se è esaurito l'uno o l'altro tetto e, dopo un rifiuto, li ricontrolla tutti e due | Con il tetto sbagliato una sessione senza pagine di storico avrebbe fatto partire una dopo l'altra ricette destinate al rifiuto, e dopo il rifiuto non avrebbe segnato esaurita la categoria giusta |
+| 2026-11-17 | I cookie della sessione salvata tengono dominio, percorso, solo-host, `Secure`, `HttpOnly` e scadenza (`SiteCookie`, una classe il cui testo non mostra mai il valore); il client del sito manda un cookie solo all'indirizzo che corrisponde per dominio e percorso (RFC 6265 §5.1.3, §5.1.4) e, se `Secure`, solo in https (anche sul sito di prova in loopback), i percorsi più lunghi prima; `x-csrftoken` prende il `csrftoken` che il browser manderebbe a quel percorso. L'identità di un cookie è nome, dominio, percorso e solo-host, come in Chromium; un `Set-Cookie` senza `Domain` è solo-host sull'host della richiesta e senza `Path` prende il percorso predefinito della richiesta; un valore con caratteri di controllo, non ASCII o `;` non si tiene. Sostituisce «Dominio e percorso non si tengono» della riga del 16 novembre su `ISiteSession` | La issue chiede «cookie con dominio e percorso»; un cookie limitato a `/api/` o a un altro host mandato ovunque non sarebbe la richiesta del browser (regola 4) |
+| 2026-11-17 | Sezione `page` in `richieste..json`: `docIdModule` (`{operation}_instagramRelayOperation`) e per ogni valore della pagina `Modulo.proprietà`, nomi controllati al caricamento (`^[A-Za-z_$][A-Za-z0-9_$]*$`), così l'espressione della copia si scrive solo da identificatori. Nuovi valori della sessione `rev` (`__rev`, `SiteData.client_revision`), `hs` (`__hs`, `SiteData.haste_session`), `hsi` (`__hsi`, `SiteData.hsi`), `dpr` (`SiteData.pr`, prima costante 1), `ccg` (`__ccg`, `WebConnectionClassServerGuess.connectionClass`), `comet_req` (`__comet_req`, `SiteData.comet_env`, prima costante 7), `entry_nonce` (`x-fb-entry-nonce`, `BootloaderConfig.nonce`). Il catalogo rifiuta un'operazione configurata con un valore `session:` senza posto nella sezione `page` (user agent e claim non ne hanno bisogno). Restano `pending` `__spin_r/__spin_b/__spin_t`, `__req`, `__s`, `__dyn`, `__csr`, `__hblp`, `__hsdp`, `__sjsp`, `__crn`, `__d`, `x-web-session-id`, le intestazioni del browser e i nomi tolti: le dieci operazioni di Instagram restano non configurate. Il sito di prova ha moduli con nomi suoi (`GettoniProva`, `UtenteProva`, `VersioneProva`, `ConnessioneProva`, `AvvioProva`, `_operazioneProva`) | Dal codice pubblico della pagina nel HAR, solo forme e nomi (regola 9); per `__spin_*` non si vede chi li aggiunge alla richiesta. Il posto dei valori sta nel file, non nel codice, come il resto del catalogo, ma una copia modificata non può mettere codice nell'espressione |
+| 2026-11-17 | Sessione salvata su file (`FileSiteSession`, Febe.Core) dietro `ISessionProtector`: intestazione `FEBS`, versione, schema (1 DPAPI, 2 AES-GCM); AES-256-GCM in Core con nonce nuovo a ogni scrittura e l'intestazione come dati associati; chiave da `FEBE_CHIAVE_SESSIONE` (32 byte in base64 o 64 cifre esadecimali) o da `Dati/sessione/chiave.bin` creato una volta con `RandomNumberGenerator` (non `IRandomSource`, che è per i tempi del motore), 0600 in una cartella 0700, mai rigenerato: un `chiave.bin` della lunghezza sbagliata è un errore, non una chiave nuova. Scrittura atomica (file `.part` nella stessa cartella, poi rinomina), un solo semaforo per sostituire, aggiornare e cancellare; l'aggiornamento ricontrolla sessione e copia dopo averlo preso. Una scrittura rifiutata dal disco tiene i valori nuovi in memoria, scrive una riga col solo tipo d'errore e si riprova alla scrittura dopo; un file illeggibile (altra chiave, rovinato, altro formato) è nessuna sessione, scritto nel registro e lasciato com'è. Riletta all'avvio la sessione è una copia nuova (`Capture` nuovo, non salvato nel file) | Il sito ha già cambiato i cookie: tornare ai vecchi li manderebbe scaduti. La chiave rigenerata renderebbe illeggibile la sessione senza dirlo. Una risposta tardiva del processo prima non deve toccare la sessione riletta |
+| 2026-11-17 | Opzione «raccolta» in tutti e due gli involucri: `pagine` (predefinita) o `richieste`; Docker `--raccolta` e `FEBE_RACCOLTA` (vince la riga di comando), Windows `--raccolta` (Febe.exe non ha altre fonti di opzioni). Solo con `richieste` e almeno un'operazione configurata nel catalogo la composizione costruisce sessione salvata, client del sito e copia a «Ho finito»; con Instagram (nessuna operazione configurata) e con `pagine` tutto resta com'era | `require()` dentro la pagina viva di Instagram potrebbe eseguire moduli o segnalare errori (da verificare con Alberto) e i moduli dei doc_id potrebbero non essere caricati a «Ho finito»: il percorso nuovo si accende solo a mano, e le prove con il sito di prova tengono il percorso del browser |
+| 2026-11-17 | Cifratura della sessione scelta dall'involucro (`IFebePlatform.CreateSessionProtector`): DPAPI per l'utente corrente in Febe.Desktop (`ProtectedData` dal framework desktop di .NET, nessun `PackageReference`: compilato e provato in `tests/Febe.Tests.Windows`), AES-256-GCM in Docker. `FEBE_CHIAVE_SESSIONE` sbagliata (base64 o lunghezza) è sempre un problema di configurazione all'avvio, qualunque sia la raccolta; un `chiave.bin` che non è una chiave lo è solo con `richieste` (con `pagine` non si legge). Nessun testo ripete il valore; `ServerOptions.ToString` dice solo «impostata», «assente» o «non valida» per password e chiave | Una chiave impostata a mano e ignorata in silenzio sorprenderebbe più tardi; il testo generato di un record avrebbe stampato password e chiave |
+| 2026-11-17 | `FEBE_PASSWORD` e `FEBE_CHIAVE_SESSIONE` si tolgono dall'ambiente di ogni processo che Febe avvia (Chromium o Edge, Xvfb, ffmpeg, ffprobe) con `ChildProcessEnvironment`, per ultime, dopo le variabili delle opzioni | Un figlio eredita l'ambiente del padre, e Chromium esegue il codice del sito: la password già ci arrivava |
+| 2026-11-17 | La copia della sessione (`Febe.Browser.Session.SessionCapture`) manda solo `Page.getFrameTree`, `Network.getCookies` con i valori (per la radice del sito e per ogni percorso del catalogo tagliato prima del primo valore, così un cookie limitato a `/api/` arriva col suo percorso) e una sola `Runtime.evaluate` in sola lettura, scritta solo dagli identificatori della sezione `page` (ognuno come stringa JSON), con un `try` per modulo: un modulo assente, un valore che non è testo o numero, più lungo di 4096 caratteri o con caratteri di controllo o non ASCII manca e non si inventa. Si copia solo da una pagina del sito che non sia un percorso delle regole di arresto (accesso, verifica); un cookie partizionato o con un valore che il browser non rimanderebbe si scarta e si conta. Si fa a «Ho finito» dentro i comandi del collegamento, dopo il controllo del cookie e prima del riposo, solo se c'è ancora il permesso di guida di Alberto, tenendo un secondo permesso e il turno della pagina; se nel frattempo il permesso è finito la copia si butta; dura al più 10 secondi (poi è un errore del browser). Una copia rifiutata lascia la sessione salvata com'era, una riuscita la sostituisce anche se manca qualche valore. Con il sito di prova e `--accesso-di-prova` la copia si fa anche dopo l'accesso automatico | Regola 7 (la pagina dopo il permesso è del motore), regola 9 (nessun valore indovinato), regola 10 (registro con soli conteggi e nomi); l'accesso automatico è solo per lo sviluppo e fa ciò che farebbe Alberto |
+| 2026-11-17 | «Scollega» cancella la sessione salvata (prima in memoria, poi il file, senza annullamento) prima del profilo del browser; un file che non si cancella è un fallimento parziale detto ad Alberto: Febe non lo usa più finché resta acceso, ma al prossimo avvio con «richieste» lo rileggerebbe, e il messaggio lo dice (riprovare «Scollega» o cancellare a mano la cartella `sessione`). Con «pagine» cancella comunque un `sessione.json` lasciato da un avvio con «richieste» (senza file non fa nulla); `chiave.bin` resta | Il server di Instagram non chiude la sessione quando si cancella il profilo: una copia rimasta sul disco tornerebbe in uso al prossimo avvio con «richieste» |
+| 2026-11-17 | Le pagine del sito di prova danno ciò che la copia a «Ho finito» legge: il cookie `csrftoken` (`csrf-prova-N`, leggibile dalla pagina) a una visita che apre la sessione o che non lo ha, il cookie `percorso_api` limitato a `Path=/api/` (non controllato), e in testa a ogni pagina (non la verifica né la sessione scaduta) un registro di moduli suo, `__d(nome, [], fabbrica)` e `require(nome)` con errore per un nome sconosciuto, con i nomi della sezione `page` di `richieste.prova.json` (`GettoniProva`, `UtenteProva`, `VersioneProva`, `ConnessioneProva`, `AvvioProva`, `_operazioneProva`) e i valori costanti di `TestSite`. `POST /api/graphql` controlla anche `__rev`, `__hs`, `__hsi`, `__ccg`, `dpr`, `__comet_req` e `x-fb-entry-nonce`: uno mancante o diverso riceve lo stesso 400 generico degli altri campi | Senza, la copia dal browser di prova non avrebbe trovato nulla e le prove d'insieme non avrebbero provato né il percorso di un cookie né la lettura dei moduli. Nomi propri e non quelli di Instagram: il sito di prova non deve somigliargli (§14.2) |
+| 2026-11-17 | Ipotesi nuove in §6.6: H21 (`require()` dei moduli della sezione `page` nella pagina viva di Instagram non esegue fabbriche con effetti e non fa segnalare errori dalla pagina) e H22 (i moduli dei `doc_id` e dei valori sono già caricati sulla pagina di «Ho finito»). Chiudere la finestra del browser su Windows e la fine del permesso di guida non copiano la sessione: copia solo «Ho finito» (domanda per Alberto, se le vuole anche lì) | Sono le due ragioni per cui la raccolta «richieste» resta spenta con Instagram; una copia fatta quando la pagina potrebbe già essere del motore, o non è più in vista, violerebbe la regola 7 |
+| 2026-11-17 | Il messaggio di «Ho finito» per una copia con valori mancanti conta solo i valori della pagina e i `doc_id` che un'operazione configurata manda (`SessionCapturePlan.NeededValues`, `NeededDocIds`; gli altri si leggono lo stesso e il registro li nomina a parte) e dice com'è: la copia ha sostituito quella di prima, le richieste che li usano non partono e alla prima Febe si ferma come disconnessione. Dopo un rifiuto il messaggio dice di riaprire il browser dalla pagina Collegamento («Usa il browser» o «Pagina iniziale») e premere di nuovo «Ho finito». La copia incompleta sostituisce comunque quella salvata | Il messaggio prometteva che quelle operazioni «restano al browser», ma il codice le ferma come disconnessione (§6.0, mai un ritorno alle pagine); e «Ho finito» chiude sempre il permesso di guida, quindi un secondo «Ho finito» da solo non copia nulla. Tenere una copia più vecchia ma completa potrebbe tenere i cookie di un altro accesso (regola 7) |
+| 2026-11-17 | `chiave.bin` si crea intero o non si crea: file `.part` nella stessa cartella, scritto fino al disco, poi rinominato senza sostituire (`OwnerOnlyFiles.CreateNew`) | Prima il file nasceva vuoto e poi si scriveva: con il disco pieno restava un `chiave.bin` corto, scambiato per la chiave di un altro processo, e da lì ogni avvio con «richieste» si fermava finché Alberto non lo cancellava a mano |
+| 2026-11-17 | Con la raccolta «pagine» il registro scrive una riga «Raccolta «pagine»: tutte le ricette con il browser» all'avvio | §6.0 dice che il registro nomina la strada presa; prima la scriveva solo con «richieste» |
diff --git a/docs/docker.md b/docs/docker.md
index 9fd57cd..c74528d 100644
--- a/docs/docker.md
+++ b/docs/docker.md
@@ -50,7 +50,7 @@ gli altri la pulizia li toglie (`docs/processo.md`, «Pulizia»).
| Volume | Uso | Dove metterlo |
|---|---|---|
-| `/dati` | Database (`febe.sqlite`), **profilo del browser con la sessione di Instagram** (`browser/`), miniature, copie giornaliere del database (`copie/`, sette giorni), registro (`registro/`, quattordici giorni), file temporanei | Su un **disco locale** del server. Su Unraid: `/mnt/user/appdata/febe` (la cartella delle applicazioni sul disco di cache). Mai una condivisione di rete: SQLite e il profilo del browser lì si rovinano, e Febe si rifiuta di partire |
+| `/dati` | Database (`febe.sqlite`), **profilo del browser con la sessione di Instagram** (`browser/`), con la raccolta `richieste` la sessione salvata cifrata e la sua chiave (`sessione/`), miniature, copie giornaliere del database (`copie/`, sette giorni), registro (`registro/`, quattordici giorni), file temporanei | Su un **disco locale** del server. Su Unraid: `/mnt/user/appdata/febe` (la cartella delle applicazioni sul disco di cache). Mai una condivisione di rete: SQLite e il profilo del browser lì si rovinano, e Febe si rifiuta di partire |
| `/libreria` | Foto e video, una cartella per account, con `_febe.jsonl` | Dove vuoi, anche su una condivisione. Febe non cancella e non sostituisce mai un file da solo |
| `/importa` | Cartelle da importare (pagina Importa) | **Sempre in sola lettura** (`:ro`): Febe copia, gli originali non si toccano |
@@ -67,8 +67,11 @@ gli altri la pulizia li toglie (`docs/processo.md`, «Pulizia»).
| `FEBE_PROXY_FIDATO` | `1` se davanti c'è un proxy con HTTPS che passa `X-Forwarded-Host` e `X-Forwarded-Proto`: il controllo dell'origine usa quel nome, e quando il proxy dice `https` il cookie di sessione è `Secure` (il browser non lo manda mai in chiaro) | spenta |
| `FEBE_SENZA_SANDBOX` | `1` avvia Chromium con `--no-sandbox`: è il compromesso descritto sotto, da usare solo se il profilo seccomp non si può usare | spenta |
| `FEBE_CHROMIUM`, `FEBE_PORTA_DEBUG`, `FEBE_DISPLAY` | Avanzate: eseguibile di Chromium, porta di debug (sempre su 127.0.0.1), display di Xvfb | `/usr/bin/chromium`, 9222, `:99` |
+| `FEBE_RACCOLTA` | Come le ricette leggono il sito (specifica §6.0): `pagine` con il browser, come sempre; `richieste` con il client del sito e la sessione copiata a «Ho finito». Vale solo se il catalogo del sito ha operazioni configurate: con Instagram, per ora, `richieste` non cambia nulla. `--raccolta` sulla riga di comando vince | `pagine` |
+| `FEBE_CHIAVE_SESSIONE` | Facoltativa: la chiave che cifra la sessione salvata, 32 byte in base64 (`openssl rand -base64 32`) o 64 cifre esadecimali. Senza, Febe crea una volta `/dati/sessione/chiave.bin`, leggibile solo dal proprietario. Impostala se vuoi la chiave fuori da `/dati` (così una copia di `/dati` da sola non apre la sessione); se la cambi, la sessione salvata non si legge più e basta rifare l'accesso. Un valore sbagliato ferma l'avvio con una pagina che lo spiega | `/dati/sessione/chiave.bin` |
-La password dell'interfaccia non si passa mai sulla riga di comando e non finisce nei registri.
+La password dell'interfaccia e la chiave della sessione non si passano mai sulla riga di comando e non finiscono nei
+registri; Febe le toglie dall'ambiente di Chromium, Xvfb e ffmpeg.
## Porte
@@ -228,5 +231,8 @@ FEBE_PASSWORD=prova dotnet run --project src/Febe.Server -- \
`--cdn-di-prova`. Mappe dei bersagli, lettori e segnali diventano quelli del sito di prova (`*.prova.json`).
- `--accesso-di-prova` apre il sito una volta all'avvio, così il suo cookie di sessione esiste come dopo un accesso.
- `--prima-sessione N` fa partire la prima sessione dopo N secondi invece di 2–10 minuti.
+- `--raccolta richieste` fa andare con il client del sito le ricette che `richieste.prova.json` configura, con la
+ sessione copiata dopo l'accesso automatico (o a «Ho finito») in `/tmp/febe/dati/sessione/` e la chiave in
+ `chiave.bin` accanto; senza, tutto va con il browser.
- Come root servono `--senza-sandbox` (Chromium lo pretende) e, se Chromium non è nel `PATH`, `FEBE_CHROMIUM`.
- Prova d'insieme automatica: `dotnet test tests/Febe.Tests --filter "FullyQualifiedName~Febe.Tests.Server"`.
diff --git a/docs/guida/Installazione-Docker-e-Unraid.md b/docs/guida/Installazione-Docker-e-Unraid.md
index 7e908a9..8798a7e 100644
--- a/docs/guida/Installazione-Docker-e-Unraid.md
+++ b/docs/guida/Installazione-Docker-e-Unraid.md
@@ -19,7 +19,7 @@ pagina Impostazioni ▸ Collegamento a Instagram.
| Volume | Che cosa contiene | Dove metterlo |
|---|---|---|
-| `/dati` | Database (`febe.sqlite`), **profilo del browser con la sessione di Instagram** (`browser/`), miniature, copie giornaliere del database (`copie/`, sette giorni), registro (`registro/`, quattordici giorni), file temporanei | Su un **disco locale** del server. Su Unraid `/mnt/user/appdata/febe`. Mai una condivisione di rete: SQLite e il profilo del browser lì si rovinano, e Febe si rifiuta di partire |
+| `/dati` | Database (`febe.sqlite`), **profilo del browser con la sessione di Instagram** (`browser/`), con la raccolta `richieste` la sessione salvata cifrata e la sua chiave (`sessione/`), miniature, copie giornaliere del database (`copie/`, sette giorni), registro (`registro/`, quattordici giorni), file temporanei | Su un **disco locale** del server. Su Unraid `/mnt/user/appdata/febe`. Mai una condivisione di rete: SQLite e il profilo del browser lì si rovinano, e Febe si rifiuta di partire |
| `/libreria` | Foto e video, una cartella per account, ognuna con il suo `_febe.jsonl` | Dove vuoi, anche su una condivisione. Febe non cancella e non sostituisce mai un file da solo |
| `/importa` | Cartelle da importare (pagina Importa) | **Sempre in sola lettura** (`:ro`): Febe copia, gli originali non si toccano |
@@ -35,8 +35,11 @@ pagina Impostazioni ▸ Collegamento a Instagram.
| `FEBE_HOST` | Facoltativa: i nomi con cui raggiungi l'interfaccia, separati da virgole (`tower.local,192.168.1.10`). Se c'è, ogni altro nome è rifiutato | qualunque nome |
| `FEBE_PROXY_FIDATO` | `1` se davanti c'è un proxy con HTTPS che passa `X-Forwarded-Host` e `X-Forwarded-Proto`: allora il cookie di sessione viaggia solo in HTTPS | spenta |
| `FEBE_SENZA_SANDBOX` | `1` avvia Chromium senza la sua sandbox: è il compromesso descritto sotto, da usare solo se il profilo seccomp non si può usare | spenta |
+| `FEBE_RACCOLTA` | Come Febe legge il sito: `pagine` con il browser, come sempre; `richieste` con le richieste dirette e la sessione copiata quando premi «Ho finito». Con Instagram, per ora, `richieste` non cambia nulla: lasciala vuota | `pagine` |
+| `FEBE_CHIAVE_SESSIONE` | Facoltativa: la chiave che cifra la sessione salvata, 32 byte in base64 (`openssl rand -base64 32`). Senza, Febe crea una volta `/dati/sessione/chiave.bin`, leggibile solo dal proprietario. Mettila qui se vuoi la chiave fuori da `/dati`; se la cambi, rifai l'accesso. Un valore sbagliato ferma l'avvio con una pagina che lo spiega | `/dati/sessione/chiave.bin` |
-La password non si passa mai sulla riga di comando e non finisce nei registri. Febe **non gira come root**: con
+La password e la chiave della sessione non si passano mai sulla riga di comando e non finiscono nei registri; Febe le
+toglie dall'ambiente del browser e degli altri programmi che avvia. Febe **non gira come root**: con
`PUID=0` il contenitore si ferma con un messaggio.
## Porte
diff --git a/docs/guida/Installazione-Windows.md b/docs/guida/Installazione-Windows.md
index 94e372b..18f8b76 100644
--- a/docs/guida/Installazione-Windows.md
+++ b/docs/guida/Installazione-Windows.md
@@ -117,6 +117,7 @@ cartelle condivise o servizi di sincronizzazione. `%LOCALAPPDATA%` non è sincro
| `--dati ` | Cartella dei dati diversa (un secondo account, le prove); «Cambia…» allora non c'è |
| `--libreria ` | Libreria di partenza diversa (una cartella scelta poi nelle Impostazioni vince) |
| `--browser finestra`, `composizione` o `edge` | Come è ospitato il browser di Instagram (prove dell'ipotesi S2); la scelta resta per gli avvii successivi |
+| `--raccolta pagine` o `richieste` | Come le ricette leggono il sito: `pagine`, il predefinito, con il browser; `richieste` con la sessione copiata a «Ho finito». Con Instagram, per ora, `richieste` non cambia nulla |
Le opzioni per lo sviluppo e le prove con il sito di prova sono in `docs/windows.md`.
diff --git a/docs/guida/Primo-collegamento.md b/docs/guida/Primo-collegamento.md
index 93abc81..c18ee78 100644
--- a/docs/guida/Primo-collegamento.md
+++ b/docs/guida/Primo-collegamento.md
@@ -32,6 +32,19 @@ pagina il motore resta fermo.
**Su Windows** il browser è la finestra a parte «Browser di Febe» («Portalo in primo piano» la mostra): accedi lì, poi
premi «Ho finito» nella finestra di Febe.
+Con la raccolta **«richieste»** (`FEBE_RACCOLTA=richieste` in Docker, `--raccolta richieste` su Windows) «Ho finito»
+fa anche una **copia della sessione** per le richieste dirette di Febe: i cookie con i loro valori, l'user agent del
+browser e i pochi valori che la pagina tiene per le sue richieste, cifrati nella cartella dei dati
+(`sessione/sessione.json`). La copia si fa solo se il browser è su una pagina del sito (non sulla pagina di accesso o
+di una verifica) e mentre il browser è ancora tuo; il messaggio di «Ho finito» dice se è riuscita e se alla pagina
+mancava qualche valore che serve alle richieste. Una copia così sostituisce comunque quella di prima, e le richieste
+che usano il valore mancante non partono: alla prima Febe si ferma come disconnessione e chiede un nuovo accesso. Se
+la copia non è riuscita o è incompleta, riapri il browser dalla pagina Collegamento («Usa il browser» o «Pagina
+iniziale») e premi di nuovo «Ho finito» sulla tua pagina iniziale: dopo «Ho finito» il browser torna al motore, quindi
+premerlo una seconda volta senza riaprirlo non copia nulla. Su Windows
+chiudere la finestra del browser non copia: serve «Ho finito». Con `pagine`, il predefinito, e con Instagram per ora
+anche con `richieste`, «Ho finito» non copia nulla e guarda solo se il cookie di sessione esiste.
+
«Annulla» torna alle impostazioni senza collegarti.
## La password: due verità diverse
@@ -42,8 +55,8 @@ premi «Ho finito» nella finestra di Febe.
(vedi [Sicurezza e riservatezza](Sicurezza-e-riservatezza)).
- **Su Windows** la scrivi direttamente nella pagina di Instagram: Febe non la riceve e non la salva.
-In tutti e due i casi resta solo la sessione del browser, nella cartella dei dati: **chi ha la cartella dei dati, o
-una sua copia, ha la sessione di Instagram.**
+In tutti e due i casi resta solo la sessione del browser, nella cartella dei dati (con la raccolta «richieste» anche la
+sua copia cifrata): **chi ha la cartella dei dati, o una sua copia, ha la sessione di Instagram.**
## Dopo il collegamento
@@ -84,7 +97,11 @@ scheda chiusa o ricaricata):
## Scollegarsi
-**«Scollega…»** chiede conferma, ferma il motore e cancella il profilo del browser, con la sessione. Per chiudere la
+**«Scollega…»** chiede conferma, ferma il motore e cancella il profilo del browser, con la sessione, e la copia della
+sessione salvata per le richieste, se c'è (in Docker la chiave `chiave.bin` resta, per la copia del prossimo accesso). Se
+il file della copia non si cancella, Febe lo dice e non lo usa più finché resta acceso; al prossimo avvio con la raccolta
+`richieste` lo rileggerebbe, quindi riprova «Scollega», o cancella a mano la cartella `sessione` nella cartella dei dati
+prima di riavviare. Per chiudere la
sessione anche dal lato di Instagram, prima esci dal sito usando tu il browser (menu del profilo, «Esci»), poi torna in
Collegamento e scollega.
diff --git a/docs/guida/Problemi-comuni.md b/docs/guida/Problemi-comuni.md
index d09d198..3507fee 100644
--- a/docs/guida/Problemi-comuni.md
+++ b/docs/guida/Problemi-comuni.md
@@ -20,6 +20,9 @@ dati.
| Il browser rifiuta l'interfaccia con un errore 400 sul nome | `FEBE_HOST` è impostata e il nome con cui apri l'interfaccia non è nell'elenco: aggiungilo |
| «Password sbagliata» anche con quella giusta, poi «bloccato» | Dopo 5 errori da uno stesso indirizzo (20 in tutto) l'accesso si blocca per 15 minuti: aspetta, poi riprova |
| Su Windows: Febe dice che manca WebView2 | Installa il runtime WebView2 dal collegamento che Febe mostra |
+| «La chiave della sessione salvata non è valida» | `FEBE_CHIAVE_SESSIONE` è impostata ma non è una chiave di 32 byte: correggila con 32 byte in base64 (`openssl rand -base64 32`) o toglila (Febe userà `/dati/sessione/chiave.bin`), poi riavvia. Motore e browser restano spenti fino ad allora |
+| «La chiave della sessione salvata non si legge» | Con la raccolta «richieste», `/dati/sessione/chiave.bin` non è una chiave di Febe o non si legge: cancellalo (la sessione salvata non si leggerà più: basta rifare l'accesso) oppure imposta `FEBE_CHIAVE_SESSIONE`, poi riavvia |
+| «Valore non valido per FEBE_RACCOLTA» (o `--raccolta`) | I valori sono `pagine` o `richieste`: correggi o togli la variabile |
## Collegamento
@@ -29,6 +32,8 @@ dati.
| La vista remota dice «Nessuna immagine dal browser» | La vista è aperta ma la pagina non arriva. Febe riavvia da solo l'invio delle immagini quando si fermano; premi «Riprova». Se resta così, guarda il registro (categoria «vista»: avvii, riavvii e silenzi) e riferisci il caso |
| Il browser è bianco, o la barra dice «Il browser è a riposo su una pagina vuota» | È la pagina vuota su cui Febe lascia il browser quando non lo usa: premi «Pagina iniziale» (la home di Instagram se sei collegato, altrimenti la pagina di accesso) |
| «Ho finito» dice che l'accesso non è riuscito | Nella pagina deve comparire la tua pagina iniziale di Instagram, non il modulo di accesso: completa l'accesso, poi di nuovo «Ho finito» |
+| «La sessione per le richieste non è stata copiata» | Solo con la raccolta «richieste». Il messaggio dice perché: se il browser non era su una pagina del sito o era sulla pagina di accesso o di verifica, apri la tua pagina iniziale e premi di nuovo «Ho finito»; se nel frattempo il browser era tornato al motore, rifai l'accesso dalla pagina Collegamento. La sessione salvata di prima resta com'era |
+| «Sessione copiata…, ma non ancora scritta su disco» | Il disco ha rifiutato la scrittura (spazio, permessi di `/dati/sessione`): Febe usa la copia in memoria e riprova alla prossima scrittura. Controlla lo spazio e i permessi; il registro dice il tipo d'errore |
| Dopo un riavvio Febe chiede di nuovo l'accesso | Non dovrebbe: la sessione è nel profilo del browser in `/dati/browser`. Controlla che `/dati` sia un volume persistente e non sia stato cancellato; riferisci il caso (è la voce S3 di [Ipotesi da verificare](Ipotesi-da-verificare)) |
## Il motore non scarica nulla
diff --git a/docs/guida/Sicurezza-e-riservatezza.md b/docs/guida/Sicurezza-e-riservatezza.md
index ce0e07a..5bd361e 100644
--- a/docs/guida/Sicurezza-e-riservatezza.md
+++ b/docs/guida/Sicurezza-e-riservatezza.md
@@ -14,6 +14,24 @@ copia altrove.
poi scollega Febe e ricollegalo.
- I cookie non si copiano da una macchina all'altra: ogni Febe fa il suo accesso.
+### La sessione salvata (raccolta «richieste»)
+
+Con la raccolta «richieste» (`FEBE_RACCOLTA`, `--raccolta`) «Ho finito» copia la sessione del browser in
+`sessione/sessione.json`, nella cartella dei dati, per le richieste dirette di Febe. Con Instagram, per ora, non
+succede: la copia si accende solo quando ci sono richieste configurate.
+
+- Il file è **cifrato**. Su Windows con la protezione dei dati di Windows (DPAPI) per il tuo utente: lo apre solo il tuo
+ utente su quel computer. In Docker con AES-256 e una chiave che sta in `FEBE_CHIAVE_SESSIONE`, se la imposti, o nel
+ file `/dati/sessione/chiave.bin`, creato da Febe e leggibile solo dal proprietario. **Con la chiave dentro `/dati`,
+ chi ha `/dati` ha anche la sessione**: se vuoi che una copia di `/dati` da sola non basti, metti la chiave in
+ `FEBE_CHIAVE_SESSIONE` (`openssl rand -base64 32`) e tienila fuori dai backup di `/dati`.
+- Non va nel database, nelle copie giornaliere, nel rapporto di diagnostica né nell'interfaccia. Febe non la esporta e
+ non accetta sessioni incollate da fuori. Nei registri ci sono solo conteggi e nomi, mai valori.
+- Se cambi la chiave, o il file si rovina, Febe la tratta come assente e lo scrive nel registro: basta rifare
+ l'accesso. «Scollega» la cancella.
+- Febe toglie `FEBE_PASSWORD` e `FEBE_CHIAVE_SESSIONE` dall'ambiente dei programmi che avvia (il browser, Xvfb,
+ ffmpeg): il browser esegue il codice del sito, e non deve poterle leggere.
+
## Docker: l'interfaccia non va esposta su Internet
- **Non esporre mai l'interfaccia Docker su Internet** senza una VPN (per esempio WireGuard o Tailscale) o un proxy con
diff --git a/docs/guida/Sviluppo.md b/docs/guida/Sviluppo.md
index 95f0131..9dd2176 100644
--- a/docs/guida/Sviluppo.md
+++ b/docs/guida/Sviluppo.md
@@ -152,7 +152,11 @@ FEBE_PASSWORD=prova dotnet run --project src/Febe.Server -- \
`--sito-di-prova` accetta solo indirizzi di questo computer; `--accesso-di-prova` apre il sito una volta all'avvio,
così il suo cookie di sessione esiste come dopo un accesso; `--prima-sessione N` fa partire la prima sessione dopo N
-secondi. Come root servono `--senza-sandbox` e, se Chromium non è nel `PATH`, `FEBE_CHROMIUM`. Per provare gli avvisi:
+secondi. Con `--raccolta richieste` (o `FEBE_RACCOLTA=richieste`) le ricette che il catalogo del sito di prova
+configura vanno con il client del sito e la sessione salvata, copiata dopo l'accesso automatico o a «Ho finito»; senza,
+tutto va con il browser come prima (dettagli in `tools/Febe.SitoDiProva/LEGGIMI.md`). Con Instagram `richieste` non
+cambia nulla finché non c'è un'operazione configurata. Come root servono `--senza-sandbox` e, se Chromium non è nel
+`PATH`, `FEBE_CHROMIUM`. Per provare gli avvisi:
imposta Telegram in Impostazioni ▸ Notifiche e chiedi al sito una verifica con `/_controllo/modo?valore=verifica`.
## La sonda
diff --git a/docs/stato.md b/docs/stato.md
index 8f9b9bb..5b77c90 100644
--- a/docs/stato.md
+++ b/docs/stato.md
@@ -1,12 +1,51 @@
# Stato
Filo fra le sessioni (specifica §15): che cosa è fatto, che cosa è in corso, che cosa è rimandato e perché.
-Aggiornato il 17 novembre 2026, versione 0.1.2 in `main` (il tag `v0.1.2` non è stato creato). **Le attività stanno
+Aggiornato il 17 novembre 2026 (tappa S4 di #36), versione 0.1.2 in `main` (il tag `v0.1.2` non è stato creato). **Le attività stanno
su Gitea**: issue, etichette e traguardi di https://gitea.encke-hake.ts.net/Alby96/Febe. Questo file resta il resoconto
fra le sessioni; ciò che è da fare si legge nelle issue aperte.
## In breve
+**17 novembre 2026: la sessione salvata cifrata, copiata a «Ho finito»** (#36, tappa S4, ramo
+`funzione/sessione-salvata`, unito in `main` con verifica verde).
+
+- **Interruttore**: opzione «raccolta» `pagine` (predefinita) o `richieste`; Docker `--raccolta` o `FEBE_RACCOLTA`,
+ Windows `--raccolta`. Solo con `richieste` **e** almeno un'operazione configurata la composizione costruisce sessione
+ salvata, client del sito per il motore e copia a «Ho finito». **Con Instagram non cambia nulla** (le dieci operazioni
+ restano non configurate: mancano ancora `__spin_*`, `__req`, `__s`, `__dyn`, `__csr` e altri); con `pagine` nemmeno
+ il sito di prova cambia strada. Il registro dice la strada presa, anche con `pagine`.
+- **Sessione salvata** `Dati/sessione/sessione.json` (`FileSiteSession`, Core): cookie con dominio, percorso,
+ solo-host, `Secure`, `HttpOnly` e scadenza, mandati solo dove il browser li manderebbe (RFC 6265); cifrata con DPAPI
+ su Windows e AES-256-GCM in Docker (chiave da `FEBE_CHIAVE_SESSIONE` o da `chiave.bin`, creata intera o per niente);
+ scrittura atomica, un solo semaforo, scrittura rifiutata tenuta in memoria e riprovata, file illeggibile = nessuna
+ sessione. Fuori da database, copie giornaliere, diagnostica e interfaccia. `FEBE_PASSWORD` e `FEBE_CHIAVE_SESSIONE`
+ non passano a Chromium, Xvfb, ffmpeg, ffprobe.
+- **Copia** (`SessionCapture`, Browser): `Page.getFrameTree`, `Network.getCookies` e una sola `Runtime.evaluate` in
+ sola lettura con i moduli della sezione `page` di `richieste..json`; solo da una pagina del sito che non sia
+ accesso o verifica, solo finché dura il permesso di guida di Alberto, anche dopo l'accesso automatico del sito di
+ prova. Valori nuovi della pagina: `rev`, `hs`, `hsi`, `dpr`, `ccg`, `comet_req`, `entry_nonce`. Una copia con valori
+ mancanti sostituisce comunque quella salvata; il messaggio conta solo ciò che le operazioni configurate mandano e
+ dice che quelle richieste si fermano come disconnessione. «Scollega» cancella la sessione salvata (anche con
+ `pagine`), `chiave.bin` resta.
+- **Sito di prova**: cookie `csrftoken` e `percorso_api` (`Path=/api/`), registro di moduli suo (`__d`/`require`, nomi
+ `GettoniProva`, `UtenteProva`, `VersioneProva`, `ConnessioneProva`, `AvvioProva`), controllo dei campi nuovi.
+- Revisione dei difetti trovati dopo l'implementazione (11 punti, tutti corretti): il messaggio «restano al browser»
+ falso, il consiglio «Riprova più tardi con «Ho finito»» che non poteva funzionare, `chiave.bin` corto lasciato da una
+ scrittura fallita, la tabella di `decisioni.md`, «Febe non lo usa più» detto di un file che al prossimo avvio
+ tornerebbe in uso, la riga di registro con `pagine`, prove mancanti (scrittura fallita al rinomina, «Scollega» con
+ `pagine`, ambiente di ffmpeg e ffprobe), questo resoconto.
+- Controlli: `dotnet build -warnaserror` pulito; `dotnet test tests/Febe.Tests` 1332 superate, 87 saltate (Chromium,
+ solo nella CI); `tests/Febe.Tests.Windows` 20 su 20 (DPAPI provato solo qui; una volta
+ `WebView2CollectionTests.ARealSessionOfTheCompositionRunsOnWebView2AndTheFilesArriveInTheLibrary` è fallita e poi è
+ passata da sola e nel giro completo).
+- **Non verificato**: la copia con Chromium vero (`SessionCaptureIntegrationTests`, solo nella CI); niente su
+ Instagram (regola 1).
+- **Domande per Alberto** (anche su #36): H21, `require()` dei moduli nella pagina viva di Instagram è innocuo? H22, i
+ moduli dei `doc_id` e dei valori sono caricati sulla pagina di «Ho finito»? Copiare anche alla chiusura della
+ finestra su Windows o alla fine del permesso di guida? Quanto restano validi i valori della pagina (`fb_dtsg`,
+ `lsd`, `rev`) dopo la copia? Una copia incompleta deve sostituire una completa (oggi sì)?
+
**17 novembre 2026: le ricette fatte di richieste** (#36, tappa S3).
- Otto ricette hanno ora una strada per richieste accanto a quella con il browser: Controllo del profilo, Storico,
diff --git a/docs/windows.md b/docs/windows.md
index a850571..086373c 100644
--- a/docs/windows.md
+++ b/docs/windows.md
@@ -75,7 +75,9 @@ Windows (ipotesi S3, da confermare: vedi sotto).
«Portalo in primo piano» (Collegamento).
- **Mentre la usi il motore resta fermo.** Quando hai finito, chiudila (la X o «Ho finito» nel Collegamento): torna
fuori vista e il motore può ripartire. Dopo una verifica, «Riprendi» si accende solo dopo che hai usato il browser.
-- «Scollega» (Collegamento) chiede conferma, ferma il motore, chiude il browser e cancella `Dati\browser` con la sessione.
+ Con `--raccolta richieste` solo «Ho finito» copia la sessione per le richieste: chiudere con la X non la copia.
+- «Scollega» (Collegamento) chiede conferma, ferma il motore, cancella la sessione salvata per le richieste
+ (`Dati\sessione\sessione.json`, se c'è), chiude il browser e cancella `Dati\browser` con la sessione.
Per chiudere la sessione anche dal lato di Instagram, prima esci dal sito usando tu il browser.
## Un account, un motore
@@ -153,6 +155,7 @@ disinstallato.
| `--sito-di-prova http://127.0.0.1:8481` | Sviluppo e prove: il browser lavora sul sito di prova locale invece che su Instagram |
| `--accesso-di-prova` | Solo con `--sito-di-prova`: apre il sito una volta, come dopo un accesso |
| `--prima-sessione ` | La prima sessione dopo questi secondi invece che dopo 2–10 minuti |
+| `--raccolta pagine\|richieste` | Come le ricette leggono il sito (specifica §6.0, #36): `pagine`, il predefinito, con il browser come sempre; `richieste` con il client del sito e la sessione salvata, copiata a «Ho finito» e cifrata con DPAPI per il tuo utente di Windows. Vale solo se il catalogo del sito ha operazioni configurate: con Instagram, per ora, non cambia nulla |
## Sicurezza dell'interfaccia
diff --git a/src/Febe.App/BrowserConnectionService.cs b/src/Febe.App/BrowserConnectionService.cs
index 5b51947..5bee24e 100644
--- a/src/Febe.App/BrowserConnectionService.cs
+++ b/src/Febe.App/BrowserConnectionService.cs
@@ -1,6 +1,7 @@
using System.Globalization;
using Febe.Browser.Cdp;
using Febe.Browser.Hosting;
+using Febe.Browser.Session;
using Febe.Core.Abstractions;
using Febe.Core.Collection;
using Febe.Core.Domain;
@@ -62,6 +63,8 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
private readonly string _loginUrl;
private readonly string _homeUrl;
private readonly SessionCookieOptions _cookie;
+ private readonly ISessionCopier? _copier;
+ private readonly Func? _forgetSavedSession;
private readonly SemaphoreSlim _commands = new(1, 1);
private readonly Lock _gate = new();
private EngineHost? _engine;
@@ -80,7 +83,14 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
/// The page «Accedi a Instagram» opens.
/// The site's home, the start page once connected.
/// The session cookie looked for (its name only).
- public BrowserConnectionService(IFebeBrowser browser, IFebeStorage storage, BrowserUseTracker tracker, IClock clock, FebeLog log, string loginUrl, string homeUrl, SessionCookieOptions cookie)
+ ///
+ /// The copy of the session into the saved session at «Ho finito» (issue #36, S4); null when the composition keeps no
+ /// saved session (option «raccolta» on «pagine», or no configured operation): «Ho finito» then reads names only.
+ ///
+ ///
+ /// What «Scollega» does to the saved session (deletes it, memory and file); null when there is none to delete.
+ ///
+ public BrowserConnectionService(IFebeBrowser browser, IFebeStorage storage, BrowserUseTracker tracker, IClock clock, FebeLog log, string loginUrl, string homeUrl, SessionCookieOptions cookie, ISessionCopier? copier = null, Func? forgetSavedSession = null)
{
_browser = browser ?? throw new ArgumentNullException(nameof(browser));
_storage = storage ?? throw new ArgumentNullException(nameof(storage));
@@ -90,6 +100,8 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
_loginUrl = loginUrl ?? throw new ArgumentNullException(nameof(loginUrl));
_homeUrl = homeUrl ?? throw new ArgumentNullException(nameof(homeUrl));
_cookie = cookie ?? throw new ArgumentNullException(nameof(cookie));
+ _copier = copier;
+ _forgetSavedSession = forgetSavedSession;
}
///
@@ -316,6 +328,9 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
var connected = await CheckAsync(force: true, mayReport: false, ct).ConfigureAwait(false) == true;
_tracker.MarkUsed(_clock.Now);
var first = connected && await MarkConnectedAsync(ct).ConfigureAwait(false);
+
+ // The copy for the site client (S4): while the page still holds the session and is still Alberto's.
+ var copy = connected && _copier is not null ? await CopySessionAsync(ct).ConfigureAwait(false) : null;
await RestIfAlbertosAsync().ConfigureAwait(false);
await HideQuietlyAsync().ConfigureAwait(false);
ReleaseLease();
@@ -339,6 +354,11 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
message = "Collegato a Instagram. Febe riprende da solo alla prossima sessione.";
}
+ if (copy is not null)
+ {
+ message += " " + CopyMessage(copy);
+ }
+
_log.Info("collegamento", connected ? "«Ho finito»: sessione presente nel browser." : "«Ho finito»: sessione assente nel browser.");
return new FinishResult(connected, message);
}
@@ -385,6 +405,9 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
// Windows: the browser window goes out of view and WebView2 closes before its folder is deleted.
await HideQuietlyAsync().ConfigureAwait(false);
Exception? failure = null;
+
+ // The saved session first (S4): no request of the site client may use it any more, whatever the profile does.
+ var savedSessionFailure = await ForgetSavedSessionAsync().ConfigureAwait(false);
try
{
await _browser.RestartWithEmptyProfileAsync(ct).ConfigureAwait(false);
@@ -412,12 +435,23 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
await engine.StartAsync(CancellationToken.None).ConfigureAwait(false);
}
+ if (savedSessionFailure is not null)
+ {
+ // Never the path or the message of the file system: the kind of error only.
+ _log.Warn("collegamento", $"«Scollega»: la sessione salvata non si è potuta cancellare dal disco ({savedSessionFailure.GetType().Name}): Febe non la usa più finché resta acceso, ma il file resta e al prossimo avvio con «richieste» la rileggerebbe.");
+ }
+
if (failure is not null)
{
_log.Warn("collegamento", "«Scollega»: il profilo del browser non si è potuto cancellare del tutto.", failure);
throw new BadRequestException("«Scollega» non è riuscito del tutto: " + failure.Message);
}
+ if (savedSessionFailure is not null)
+ {
+ throw new BadRequestException("«Scollega» non è riuscito del tutto: la sessione salvata per le richieste non si è potuta cancellare dal disco. Febe non la usa più finché resta acceso, ma al prossimo avvio con la raccolta «richieste» la rileggerebbe: riprova «Scollega» e, se resta, cancella a mano la cartella «sessione» nella cartella dei dati prima di riavviare Febe.");
+ }
+
_log.Info("collegamento", "«Scollega»: motore fermo, profilo del browser cancellato, browser ripartito vuoto.");
}
finally
@@ -698,6 +732,102 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
: $"Alberto usa il browser: {what} non aperta (errore di rete del browser).");
}
+ ///
+ /// The copy at «Ho finito» (issue #36, S4, §6.0): only while Alberto's own lease («Accedi», «Usa il browser») still
+ /// holds — after it ended the page is the engine's, and nothing is read from it (rule 7). A hold of the driving gate
+ /// keeps the lease from ending by itself meanwhile, and the page turn keeps a step of the profile search off the
+ /// page; a lease that ended all the same before the copy is saved throws the copy away.
+ ///
+ private async Task CopySessionAsync(CancellationToken ct)
+ {
+ IDisposable? lease;
+ lock (_gate)
+ {
+ lease = _lease;
+ }
+
+ if (lease is null || !_browser.UserIsDriving)
+ {
+ _log.Info("collegamento", "«Ho finito»: sessione non copiata, il browser era già tornato al motore.");
+ return new SessionCopyOutcome(SessionCopyStatus.Discarded, null, 0, 0, 0);
+ }
+
+ var hold = _browser.UserDriving.Begin();
+ try
+ {
+ using var turn = await TakePageAsync(ct).ConfigureAwait(false);
+ if (_engine is not null && turn is null)
+ {
+ _log.Info("collegamento", "«Ho finito»: sessione non copiata, la pagina era occupata dalla ricerca dei profili.");
+ return new SessionCopyOutcome(SessionCopyStatus.Refused, CaptureRefusal.BrowserError, 0, 0, 0);
+ }
+
+ bool StillAlbertos()
+ {
+ lock (_gate)
+ {
+ return ReferenceEquals(_lease, lease);
+ }
+ }
+
+ return await _copier!.CopyAsync(StillAlbertos, ct).ConfigureAwait(false);
+ }
+ finally
+ {
+ hold.Dispose();
+ }
+ }
+
+ ///
+ /// The clause of the «Ho finito» message about the copy, in Italian (counts only). It says what the code does: a
+ /// value a configured operation needs and the page did not give stops that request as a disconnection (§6.0), never
+ /// a way back to the browser; and after a refusal a new «Ho finito» needs the browser opened again, because
+ /// «Ho finito» always ends the lease.
+ ///
+ internal static string CopyMessage(SessionCopyOutcome copy)
+ {
+ ArgumentNullException.ThrowIfNull(copy);
+ const string Again = "Riapri il browser dalla pagina Collegamento («Usa il browser» o «Pagina iniziale») e premi di nuovo «Ho finito» sulla tua pagina iniziale.";
+ var missing = copy.MissingValues + copy.MissingDocIds;
+ var missingClause = missing == 0
+ ? string.Empty
+ : string.Create(
+ CultureInfo.InvariantCulture,
+ $" Alla pagina però mancavano {missing} valori che servono alle richieste: la copia ha comunque sostituito quella salvata prima, e le richieste che li usano non partono. Alla prima Febe si ferma come disconnessione e chiede un nuovo accesso. {Again}");
+ return copy.Status switch
+ {
+ SessionCopyStatus.Saved => "Sessione copiata per le richieste di Febe." + missingClause,
+ SessionCopyStatus.SavedInMemoryOnly =>
+ "Sessione copiata per le richieste di Febe, ma non ancora scritta su disco: Febe riprova alla prossima scrittura." + missingClause,
+ SessionCopyStatus.Discarded =>
+ "La sessione per le richieste non è stata copiata: nel frattempo il browser era tornato al motore. Rifai l'accesso dalla pagina Collegamento e premi «Ho finito» sulla tua pagina iniziale.",
+ _ when copy.Refusal is CaptureRefusal.NotOnSite or CaptureRefusal.CheckpointPage =>
+ $"La sessione per le richieste non è stata copiata: {BrowserSessionCopier.Reason(copy.Refusal.Value)}. La sessione salvata resta com'era. {Again}",
+ _ =>
+ $"La sessione per le richieste non è stata copiata: {BrowserSessionCopier.Reason(copy.Refusal ?? CaptureRefusal.BrowserError)}. La sessione salvata resta com'era. {Again}",
+ };
+ }
+
+ /// «Scollega» deletes the saved session (memory first, then the file); returns the error of the disk, if any.
+ private async Task ForgetSavedSessionAsync()
+ {
+ if (_forgetSavedSession is null)
+ {
+ return null;
+ }
+
+ try
+ {
+ // Not cancellable: «Scollega» must not stop halfway because the page that asked it went away.
+ await _forgetSavedSession(CancellationToken.None).ConfigureAwait(false);
+ return null;
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ return ex;
+ }
+ }
+
/// The empty rest page (or no document at all): never what Alberto should be shown.
private static bool IsRest(string? url) => url is "" or CdpPageExtensions.RestUrl;
diff --git a/src/Febe.App/CollectionRoute.cs b/src/Febe.App/CollectionRoute.cs
new file mode 100644
index 0000000..9125c1e
--- /dev/null
+++ b/src/Febe.App/CollectionRoute.cs
@@ -0,0 +1,52 @@
+namespace Febe.App;
+
+///
+/// How the engine's recipes reach the site (issue #36, S4): by the pages of the browser, as always, or by the site
+/// client's requests with the session saved at «Ho finito». is the default and changes nothing;
+/// takes effect only when richieste.<sito>.json has at least one configured operation
+/// (Instagram has none in S4, so with Instagram it changes nothing either). Option «raccolta»: --raccolta and
+/// FEBE_RACCOLTA in Docker, --raccolta on Windows.
+///
+public enum CollectionRoute
+{
+ /// «pagine»: every recipe with the browser; no saved session, no site client.
+ Pages,
+
+ /// «richieste»: the saved session and the site client for the configured operations.
+ Requests,
+}
+
+/// Italian names of , for the command line, the environment and the log.
+public static class CollectionRouteNames
+{
+ /// The option on the command line of both shells.
+ public const string Option = "--raccolta";
+
+ /// The environment variable of the Docker container.
+ public const string EnvironmentVariable = "FEBE_RACCOLTA";
+
+ /// The Italian name: «pagine» or «richieste».
+ public static string Name(CollectionRoute route) => route == CollectionRoute.Requests ? "richieste" : "pagine";
+
+ /// Reads «pagine» or «richieste» (any case, spaces around ignored).
+ public static bool TryParse(string? text, out CollectionRoute route)
+ {
+ switch (text?.Trim().ToLowerInvariant())
+ {
+ case "pagine":
+ route = CollectionRoute.Pages;
+ return true;
+ case "richieste":
+ route = CollectionRoute.Requests;
+ return true;
+ default:
+ route = CollectionRoute.Pages;
+ return false;
+ }
+ }
+
+ /// The Italian problem for a wrong value after (the option or the variable).
+ public static string Problem(string source, string? text) => text is null
+ ? $"Dopo {source} serve pagine o richieste."
+ : $"Valore non valido per {source} («{text}»): pagine oppure richieste.";
+}
diff --git a/src/Febe.App/FebeApp.cs b/src/Febe.App/FebeApp.cs
index bce97f0..81034e2 100644
--- a/src/Febe.App/FebeApp.cs
+++ b/src/Febe.App/FebeApp.cs
@@ -1,15 +1,19 @@
using System.Globalization;
+using System.Security.Cryptography;
using Febe.Browser.Recipes;
+using Febe.Browser.Session;
using Febe.Core.Abstractions;
using Febe.Core.Alerts;
using Febe.Core.Collection;
using Febe.Core.Collection.Diagnostics;
using Febe.Core.Collection.Downloads;
+using Febe.Core.Collection.Requests;
using Febe.Core.Collection.Search;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Core.Import;
using Febe.Core.Library;
+using Febe.Core.Security;
using Febe.Core.Storage;
using Febe.Data;
using Febe.Web;
@@ -46,6 +50,8 @@ public sealed class FebeApp : IAsyncDisposable
private readonly TaskCompletionSource _running = new(TaskCreationOptions.RunContinuationsAsynchronously);
private TelegramClient? _telegram;
private string? _temporaryFolder;
+ private RequestCatalog? _requestCatalog;
+ private ISessionCopier? _copier;
private int _disposed;
private FebeApp(FebeAppOptions options, IFebePlatform platform, FebeLog log, IClock clock, IReadOnlyList problems)
@@ -83,6 +89,15 @@ public sealed class FebeApp : IAsyncDisposable
public BrowserConnectionService? Connection { get; private set; }
+ ///
+ /// The saved session of the site client (issue #36, S4, §6.0, §13.2): built only with the option «raccolta» on
+ /// «richieste» and a catalog with configured operations; null otherwise (always with Instagram in S4).
+ ///
+ public ISavedSiteSession? SavedSession { get; private set; }
+
+ /// The site client the recipes use (same conditions as ); null when every recipe goes by the browser.
+ public HttpSiteRequester? SiteRequester { get; private set; }
+
public EngineHost? Engine { get; private set; }
public CollectionPipeline? Pipeline { get; private set; }
@@ -249,7 +264,18 @@ public sealed class FebeApp : IAsyncDisposable
var context = new FebePlatformContext(o, data, Database, Clock, Log, Tracker, ct => Connection?.OpenStartPageAsync(ct) ?? Task.CompletedTask);
var browser = await _platform.CreateBrowserAsync(context, ct).ConfigureAwait(false);
Browser = browser;
- var connection = new BrowserConnectionService(browser, Database, Tracker, Clock, Log, o.LoginUrl, HomeUrl(o.Site.BaseUrl), o.Site.SessionCookie);
+ PrepareSavedSession(context, browser);
+ var savedSession = SavedSession;
+ var sessionFile = data.SessionFile;
+ Func forget = savedSession is not null
+ ? savedSession.DeleteAsync
+ : _ =>
+ {
+ // Without a saved session in this start («pagine»): a file an earlier start with «richieste» left goes too.
+ OwnerOnlyFiles.DeleteWithLeftovers(sessionFile);
+ return Task.CompletedTask;
+ };
+ var connection = new BrowserConnectionService(browser, Database, Tracker, Clock, Log, o.LoginUrl, HomeUrl(o.Site.BaseUrl), o.Site.SessionCookie, _copier, forget);
Connection = connection;
var engineOptions = o.FirstSessionDelay is { } delay
? EngineOptions.Default with { StartupDelayMin = delay, StartupDelayMax = delay }
@@ -436,7 +462,9 @@ public sealed class FebeApp : IAsyncDisposable
SearchOptions = search.Options,
SearchPhotos = search.Photos,
- // Requests: S4 (#36). Until then every recipe goes by the browser.
+ // Requests (#36, S4): only with «raccolta» on «richieste» and configured operations; otherwise every
+ // recipe goes by the browser, as before.
+ Requests = CreateSiteRequests(),
},
ct).ConfigureAwait(false);
runner.Target = Pipeline.Runner;
@@ -465,7 +493,7 @@ public sealed class FebeApp : IAsyncDisposable
// With the test site's automatic login the first look reports nothing: the session it may not find yet is
// the one the login below opens (issue #52), not a disconnection.
await Connection!.RefreshAsync(ct, mayReport: !o.TestSiteAutoLogin).ConfigureAwait(false);
- if (o.TestSiteAutoLogin && Connection.IsConnected != true)
+ if (o.TestSiteAutoLogin && (Connection.IsConnected != true || (SavedSession is not null && SavedSession.Read() is null)))
{
await TestSiteLoginAsync(ct).ConfigureAwait(false);
}
@@ -497,7 +525,7 @@ public sealed class FebeApp : IAsyncDisposable
{
try
{
- var configuration = CollectionConfiguration.Describe(_options.Site.Name, pipeline.Vocabulary, pipeline.SiteMap);
+ var configuration = CollectionConfiguration.Describe(_options.Site.Name, pipeline.Vocabulary, pipeline.SiteMap, SiteRequester is not null ? _requestCatalog : null);
foreach (var line in configuration.Lines)
{
Log.Info("raccolta", line);
@@ -520,19 +548,150 @@ public sealed class FebeApp : IAsyncDisposable
}
}
+ ///
+ /// The gate of S4 (issue #36, decision of 17 November 2026): the saved session, its copy at «Ho finito» and the site
+ /// client exist only with the option «raccolta» on «richieste» AND a catalog of the site with at least one
+ /// configured operation. With «pagine» (the default) nothing is built, and one line of the log says so (§6.0: the
+ /// log says which route Febe took); with Instagram (no operation configured in S4) nothing is built either: no cookie
+ /// value is read, no module of the page.
+ ///
+ private void PrepareSavedSession(FebePlatformContext context, IFebeBrowser browser)
+ {
+ var o = _options;
+ if (o.Collection != CollectionRoute.Requests)
+ {
+ Log.Info("raccolta", "Raccolta «pagine»: tutte le ricette con il browser (nessuna sessione salvata, nessun client del sito).");
+ return;
+ }
+
+ var catalog = LoadRequestCatalog(context.Data);
+ if (catalog is null || !catalog.Configured.Any())
+ {
+ Log.Info("raccolta", $"Raccolta «richieste»: nessuna operazione configurata in richieste.{o.Site.Name}.json, tutte le ricette restano al browser (nessuna sessione salvata, nessun client del sito).");
+ return;
+ }
+
+ try
+ {
+ var protector = _platform.CreateSessionProtector(context);
+ var saved = new FileSiteSession(context.Data.SessionFile, protector, message => Log.Info("sessione", message));
+ var rules = LoadSignalRules(context.Data);
+ _copier = new BrowserSessionCopier(browser.Cdp, SessionCapturePlan.For(o.Site, catalog, rules), saved, Clock, message => Log.Info("sessione", message));
+ _requestCatalog = catalog;
+ SavedSession = saved;
+ Log.Info("raccolta", $"Raccolta «richieste»: {catalog.Configured.Count().ToString(CultureInfo.InvariantCulture)} operazioni configurate in {Path.GetFileName(catalog.Source)}; la sessione si copia a «Ho finito».");
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or CryptographicException or PlatformNotSupportedException)
+ {
+ // Never a reason not to collect: the browser does every recipe, as with «pagine». The kind of error only.
+ Log.Error("raccolta", $"Raccolta «richieste» non attivata: la cifratura della sessione salvata non è pronta ({ex.GetType().Name}). Tutte le ricette restano al browser.");
+ }
+ }
+
+ /// The catalog of the site: the copy in the Data folder, or the embedded file when there is none or it is not valid.
+ private RequestCatalog? LoadRequestCatalog(DataFolderLayout data)
+ {
+ var name = $"richieste.{_options.Site.Name}.json";
+ try
+ {
+ return RequestCatalog.LoadOrEmbedded(Path.Combine(data.Root, name), name);
+ }
+ catch (InvalidDataException ex)
+ {
+ Log.Warn("raccolta", $"{name} nella cartella dei dati non è valido: uso quello di Febe. {ex.Message}");
+ }
+
+ try
+ {
+ return RequestCatalog.LoadEmbedded(name);
+ }
+ catch (Exception ex) when (ex is InvalidDataException or FileNotFoundException)
+ {
+ Log.Warn("raccolta", $"Nessun catalogo delle richieste per il sito «{_options.Site.Name}».");
+ return null;
+ }
+ }
+
+ /// The stop rules of the site as the pipeline loads them: their login and verification paths are pages where no copy is made.
+ private SignalRules? LoadSignalRules(DataFolderLayout data)
+ {
+ var file = Path.Combine(data.Root, _options.Site.SignalsFile);
+ try
+ {
+ return File.Exists(file) ? SignalRules.Load(file) : SignalRules.LoadEmbedded(_options.Site.SignalsFile);
+ }
+ catch (InvalidDataException)
+ {
+ return SignalRules.LoadEmbedded(_options.Site.SignalsFile);
+ }
+ }
+
+ ///
+ /// The site client of the recipes, over the saved session (issue #36, S4): only when
+ /// built one. Instagram's options for Instagram, the test site's for the test site; any other site gets none.
+ ///
+ private SiteRequestOptions? CreateSiteRequests()
+ {
+ if (SavedSession is not { } session || _requestCatalog is not { } catalog)
+ {
+ return null;
+ }
+
+ var o = _options;
+ HttpSiteRequesterOptions? options = catalog.Site switch
+ {
+ "instagram" => HttpSiteRequesterOptions.Instagram(),
+ "prova" => HttpSiteRequesterOptions.TestSite(new Uri(o.Site.BaseUrl.TrimEnd('/') + "/"), o.Site.SessionCookie.CookieName),
+ _ => null,
+ };
+ if (options is null)
+ {
+ Log.Warn("raccolta", $"Client del sito non costruito: il sito «{catalog.Site}» non ha opzioni del client. Tutte le ricette restano al browser.");
+ return null;
+ }
+
+ try
+ {
+ var requester = new HttpSiteRequester(catalog, session, options, Clock, line => Log.Info("client", line));
+ DisposeOnStop(requester);
+ SiteRequester = requester;
+ return new SiteRequestOptions(requester, catalog);
+ }
+ catch (Exception ex) when (ex is InvalidOperationException or ArgumentException)
+ {
+ // The messages of the client name a variable or an option, never a value of the session.
+ Log.Warn("raccolta", "Client del sito non costruito: " + ex.Message + " Tutte le ricette restano al browser.");
+ return null;
+ }
+ }
+
/// The site's home page as the browser writes it (with its final slash), for «Pagina iniziale».
private static string HomeUrl(string baseUrl) =>
Uri.TryCreate(baseUrl, UriKind.Absolute, out var home) ? home.AbsoluteUri : baseUrl;
///
/// Development with the test site only (--accesso-di-prova): what Alberto does by hand on Instagram — open
- /// the site once, so that its session cookie exists — then back to the rest page.
+ /// the site once, so that its session cookie exists, and with a saved session copy it as «Ho finito» would (S4) —
+ /// then back to the rest page. Before the engine starts, under a hold of the driving gate as Alberto's own login.
///
private async Task TestSiteLoginAsync(CancellationToken ct)
{
var browser = Browser!;
- await Febe.Browser.Cdp.CdpPageExtensions.NavigateAsync(browser.Cdp, _options.LoginUrl, ct).ConfigureAwait(false);
- await Febe.Browser.Cdp.CdpPageExtensions.WaitForLoadAsync(browser.Cdp, Clock, TimeSpan.FromSeconds(15), ct).ConfigureAwait(false);
+ var hold = _copier is null ? null : browser.UserDriving.Begin();
+ try
+ {
+ await Febe.Browser.Cdp.CdpPageExtensions.NavigateAsync(browser.Cdp, _options.LoginUrl, ct).ConfigureAwait(false);
+ await Febe.Browser.Cdp.CdpPageExtensions.WaitForLoadAsync(browser.Cdp, Clock, TimeSpan.FromSeconds(15), ct).ConfigureAwait(false);
+ if (_copier is not null)
+ {
+ await _copier.CopyAsync(() => true, ct).ConfigureAwait(false);
+ }
+ }
+ finally
+ {
+ hold?.Dispose();
+ }
+
await browser.RestAsync(ct).ConfigureAwait(false);
await Connection!.RefreshAsync(ct).ConfigureAwait(false);
Log.Info("collegamento", "Sito di prova: accesso automatico fatto.");
diff --git a/src/Febe.App/IFebePlatform.cs b/src/Febe.App/IFebePlatform.cs
index ad52f06..0b43683 100644
--- a/src/Febe.App/IFebePlatform.cs
+++ b/src/Febe.App/IFebePlatform.cs
@@ -2,6 +2,7 @@ using Febe.Browser.Recipes;
using Febe.Core.Abstractions;
using Febe.Core.Alerts;
using Febe.Core.Library;
+using Febe.Core.Security;
using Febe.Core.Storage;
using Febe.Web;
using Febe.Web.Connection;
@@ -34,6 +35,17 @@ public interface IFebePlatform
/// The browser of this shell. Called once, after the database is open and before the engine exists.
Task CreateBrowserAsync(FebePlatformContext context, CancellationToken ct);
+ ///
+ /// How this shell encrypts the saved session (issue #36, S4, spec §13.2): DPAPI for the current user on Windows,
+ /// AES-256-GCM in Docker with the key of FEBE_CHIAVE_SESSIONE or Dati/sessione/chiave.bin. Called at
+ /// most once, after the database is open, and only when the composition keeps a saved session
+ /// ( is ). Says in the log where the
+ /// key comes from, never the key.
+ ///
+ /// The key file is there but is not a key of Febe.
+ /// The key file could not be made or read.
+ ISessionProtector CreateSessionProtector(FebePlatformContext context);
+
///
/// Services of this shell for a normal start, registered before the web layer (whose fallbacks use TryAdd):
/// native shell (its notifications are the Windows channel of the alerts), browser window, remote view, change of
@@ -103,6 +115,13 @@ public sealed record FebeAppOptions
/// Development: the first session comes after this delay instead of 2–10 minutes.
public TimeSpan? FirstSessionDelay { get; init; }
+ ///
+ /// Option «raccolta» (issue #36, S4): by default, as before S4.
+ /// builds the saved session and the site client only when the site's catalog
+ /// has configured operations.
+ ///
+ public CollectionRoute Collection { get; init; } = CollectionRoute.Pages;
+
/// Warnings found while reading the configuration, for the log.
public IReadOnlyList Warnings { get; init; } = [];
}
diff --git a/src/Febe.App/SessionCopier.cs b/src/Febe.App/SessionCopier.cs
new file mode 100644
index 0000000..0a9bc85
--- /dev/null
+++ b/src/Febe.App/SessionCopier.cs
@@ -0,0 +1,149 @@
+using System.Globalization;
+using Febe.Browser.Session;
+using Febe.Core.Abstractions;
+using Febe.Core.Collection.Requests;
+
+namespace Febe.App;
+
+/// How a copy of the browser's session ended (counts and names only).
+public enum SessionCopyStatus
+{
+ /// Copied and written to the saved session.
+ Saved,
+
+ /// Copied; it counts at once, but the disk refused it (tried again with the next write).
+ SavedInMemoryOnly,
+
+ /// Not copied: says why.
+ Refused,
+
+ /// Copied, then thrown away: meanwhile the page was no longer Alberto's (rule 7).
+ Discarded,
+}
+
+/// What a copy did, for the message of «Ho finito» and the tests. Never a value.
+/// How it ended.
+/// Why nothing was copied (with ).
+/// Cookies copied.
+/// Values of the page it did not find that a configured operation sends.
+/// doc_id of configured operations it did not find.
+public sealed record SessionCopyOutcome(SessionCopyStatus Status, CaptureRefusal? Refusal, int Cookies, int MissingValues, int MissingDocIds)
+{
+ /// True when the copy now is the saved session.
+ public bool Saved => Status is SessionCopyStatus.Saved or SessionCopyStatus.SavedInMemoryOnly;
+}
+
+///
+/// Copies the session of Febe's browser into the saved session (issue #36, S4, spec §6.0): at «Ho finito», and after the
+/// automatic login of the test site. A new copy replaces the saved one (§6.0 «un nuovo accesso ricopia tutto e
+/// sostituisce»), also when some value of the page is missing: the requests that send it then do not leave and stop
+/// the engine as a disconnection until a new copy has it (never a way back to the pages). A refused copy leaves the
+/// saved session as it is.
+///
+public interface ISessionCopier
+{
+ ///
+ /// Copies the session the page holds now. The caller holds the page (Alberto's lease, the page turn).
+ ///
+ /// Asked after reading, before saving: false throws the copy away (the page stopped being Alberto's).
+ /// Cancels the copy; nothing is saved then.
+ Task CopyAsync(Func mayKeep, CancellationToken ct);
+}
+
+///
+/// The copy over the browser's page () into a , bounded by
+/// . Logs one line with counts and names, never a value (rule 10).
+///
+public sealed class BrowserSessionCopier : ISessionCopier
+{
+ private readonly ICdpSession _cdp;
+ private readonly SessionCapturePlan _plan;
+ private readonly ISavedSiteSession _store;
+ private readonly IClock _clock;
+ private readonly Action _log;
+
+ /// The page of Febe's browser.
+ /// What to read (from the catalog of the site).
+ /// The saved session the copy replaces.
+ /// The composition's clock (when the copy was made).
+ /// Receives the Italian log line (counts and names only).
+ public BrowserSessionCopier(ICdpSession cdp, SessionCapturePlan plan, ISavedSiteSession store, IClock clock, Action log)
+ {
+ _cdp = cdp ?? throw new ArgumentNullException(nameof(cdp));
+ _plan = plan ?? throw new ArgumentNullException(nameof(plan));
+ _store = store ?? throw new ArgumentNullException(nameof(store));
+ _clock = clock ?? throw new ArgumentNullException(nameof(clock));
+ _log = log ?? throw new ArgumentNullException(nameof(log));
+ }
+
+ ///
+ /// How long the reading may last before it counts as a browser error: «Ho finito» holds the commands of the
+ /// connection meanwhile, so a browser that hangs must not hold them for ever (real time).
+ ///
+ public TimeSpan Timeout { get; set; } = TimeSpan.FromSeconds(10);
+
+ public async Task CopyAsync(Func mayKeep, CancellationToken ct)
+ {
+ ArgumentNullException.ThrowIfNull(mayKeep);
+ SessionCaptureResult result;
+ using (var limit = CancellationTokenSource.CreateLinkedTokenSource(ct))
+ {
+ limit.CancelAfter(Timeout);
+ try
+ {
+ result = await SessionCapture.CaptureAsync(_cdp, _plan, _clock, limit.Token).ConfigureAwait(false);
+ }
+ catch (OperationCanceledException) when (!ct.IsCancellationRequested)
+ {
+ _log("Sessione non copiata: il browser non ha risposto in tempo.");
+ return new SessionCopyOutcome(SessionCopyStatus.Refused, CaptureRefusal.BrowserError, 0, 0, 0);
+ }
+ }
+
+ if (result.Values is not { } values)
+ {
+ var refusal = result.Refusal ?? CaptureRefusal.BrowserError;
+ _log($"Sessione non copiata: {Reason(refusal)}. La sessione salvata resta com'era.");
+ return new SessionCopyOutcome(SessionCopyStatus.Refused, refusal, 0, 0, 0);
+ }
+
+ var counts = string.Create(
+ CultureInfo.InvariantCulture,
+ $"{result.Cookies} cookie ({result.DroppedCookies} scartati), {result.ExpectedValues - result.MissingValues.Count} valori della pagina su {result.ExpectedValues}, {result.ExpectedDocIds - result.MissingDocIds.Count} doc_id su {result.ExpectedDocIds}");
+ if (!mayKeep())
+ {
+ _log($"Sessione letta ma non salvata: nel frattempo il browser è tornato al motore ({counts}).");
+ return new SessionCopyOutcome(SessionCopyStatus.Discarded, null, result.Cookies, result.MissingValues.Count, result.MissingDocIds.Count);
+ }
+
+ // Not cancelled from here: the copy was made, and a half-written replacement is never left. It replaces the
+ // saved session also when a value is missing (§6.0): keeping an older copy could keep another login's cookies.
+ var onDisk = await _store.ReplaceAsync(values, CancellationToken.None).ConfigureAwait(false);
+
+ // Missing counts only what a configured operation sends: that request will not leave (a disconnection, §6.0).
+ var neededValues = result.MissingValues.Where(_plan.NeededValues.Contains).ToList();
+ var neededDocIds = result.MissingDocIds.Where(_plan.NeededDocIds.Contains).ToList();
+ var needed = neededValues.Concat(neededDocIds).ToList();
+ var unused = result.MissingValues.Concat(result.MissingDocIds).Except(needed, StringComparer.Ordinal).ToList();
+ _log($"Sessione copiata: {counts}"
+ + (needed.Count == 0 ? string.Empty : "; mancano " + string.Join(", ", needed) + ", che servono alle operazioni configurate")
+ + (unused.Count == 0 ? string.Empty : "; mancano anche " + string.Join(", ", unused) + ", che nessuna operazione configurata usa")
+ + (onDisk ? string.Empty : "; non ancora scritta su disco")
+ + ".");
+ return new SessionCopyOutcome(
+ onDisk ? SessionCopyStatus.Saved : SessionCopyStatus.SavedInMemoryOnly,
+ null,
+ result.Cookies,
+ neededValues.Count,
+ neededDocIds.Count);
+ }
+
+ /// Why a copy was refused, in Italian.
+ public static string Reason(CaptureRefusal refusal) => refusal switch
+ {
+ CaptureRefusal.NotOnSite => "il browser non era su una pagina del sito",
+ CaptureRefusal.CheckpointPage => "il browser era sulla pagina di accesso o di verifica",
+ CaptureRefusal.NoUserAgent => "il browser non ha dato il suo user agent",
+ _ => "il browser non ha risposto",
+ };
+}
diff --git a/src/Febe.Browser/Cdp/CdpCommandPolicy.cs b/src/Febe.Browser/Cdp/CdpCommandPolicy.cs
index 2565107..452bcfc 100644
--- a/src/Febe.Browser/Cdp/CdpCommandPolicy.cs
+++ b/src/Febe.Browser/Cdp/CdpCommandPolicy.cs
@@ -31,7 +31,8 @@ public static class CdpCommandPolicy
"Page.screencastFrameAck",
"Page.stopScreencast",
"Page.captureScreenshot",
- // Check the session: existence of the session cookie only.
+ // Check the session: existence of the session cookie only. Copy the session (§6.1 «Copiare la sessione»,
+ // issue #36, S4): the values too, once at «Ho finito» and only with a saved session (Session/SessionCapture).
"Network.getCookies");
/// Commands explicitly forbidden by spec §2 rule 2 and §6.1, refused with a specific message.
diff --git a/src/Febe.Browser/Hosting/ChromiumProcessHost.cs b/src/Febe.Browser/Hosting/ChromiumProcessHost.cs
index dea72f0..6796882 100644
--- a/src/Febe.Browser/Hosting/ChromiumProcessHost.cs
+++ b/src/Febe.Browser/Hosting/ChromiumProcessHost.cs
@@ -2,6 +2,7 @@ using System.Diagnostics;
using Febe.Browser.Cdp;
using Febe.Browser.Diagnostics;
using Febe.Core.Abstractions;
+using Febe.Core.Security;
namespace Febe.Browser.Hosting;
@@ -199,7 +200,11 @@ public sealed class ChromiumProcessHost : IBrowserHost
/// Same as . A stopped host cannot be started again: create a new one.
public ValueTask DisposeAsync() => new(StopAsync());
- private ProcessStartInfo BuildStartInfo(string executable, IReadOnlyList arguments, BrowserOptions options)
+ ///
+ /// The start of Chromium (or Edge): its arguments, the display, the variables of ,
+ /// and never Febe's secrets (), whatever the parent or the options hold.
+ ///
+ internal ProcessStartInfo BuildStartInfo(string executable, IReadOnlyList arguments, BrowserOptions options)
{
var info = new ProcessStartInfo(executable);
foreach (var argument in arguments)
@@ -224,7 +229,7 @@ public sealed class ChromiumProcessHost : IBrowserHost
}
}
- return info;
+ return info.WithoutSecrets();
}
private async Task WaitReadyAndConnectAsync(Process process, CancellationToken ct)
diff --git a/src/Febe.Browser/Hosting/HostingHelpers.cs b/src/Febe.Browser/Hosting/HostingHelpers.cs
index ef96806..e04327b 100644
--- a/src/Febe.Browser/Hosting/HostingHelpers.cs
+++ b/src/Febe.Browser/Hosting/HostingHelpers.cs
@@ -98,7 +98,8 @@ public sealed class UserDrivingGate
///
/// Tells whether the session cookie exists (spec §6.1, §7.6) through Network.getCookies.
-/// Only the cookie names are looked at: values are never read, kept or logged.
+/// Only the cookie names are looked at: values are never read, kept or logged here. The values are read only by the
+/// copy of the session at «Ho finito» (§6.1 «Copiare la sessione», Febe.Browser.Session.SessionCapture).
///
public static class SessionCookieProbe
{
diff --git a/src/Febe.Browser/Hosting/XvfbProcess.cs b/src/Febe.Browser/Hosting/XvfbProcess.cs
index 060c612..2723c06 100644
--- a/src/Febe.Browser/Hosting/XvfbProcess.cs
+++ b/src/Febe.Browser/Hosting/XvfbProcess.cs
@@ -2,6 +2,7 @@ using System.Diagnostics;
using System.Globalization;
using Febe.Browser.Diagnostics;
using Febe.Core.Abstractions;
+using Febe.Core.Security;
namespace Febe.Browser.Hosting;
@@ -98,7 +99,8 @@ public sealed class XvfbProcess : IAsyncDisposable
return null;
}
- private ProcessStartInfo BuildStartInfo(string exe)
+ /// The start of Xvfb, without Febe's secrets in its environment ().
+ internal ProcessStartInfo BuildStartInfo(string exe)
{
var info = new ProcessStartInfo(exe);
info.ArgumentList.Add(Display);
@@ -108,7 +110,7 @@ public sealed class XvfbProcess : IAsyncDisposable
info.ArgumentList.Add("-nolisten");
info.ArgumentList.Add("tcp");
info.ArgumentList.Add("-noreset");
- return info;
+ return info.WithoutSecrets();
}
private async Task WaitForSocketAsync(Process process, IClock clock, CancellationToken ct)
diff --git a/src/Febe.Browser/Recipes/CollectionPipeline.cs b/src/Febe.Browser/Recipes/CollectionPipeline.cs
index cc20791..64cb58a 100644
--- a/src/Febe.Browser/Recipes/CollectionPipeline.cs
+++ b/src/Febe.Browser/Recipes/CollectionPipeline.cs
@@ -108,7 +108,8 @@ public sealed record CollectionPipelineOptions
///
/// The site client and its catalog (issue #36, S3): the recipes whose roles are all configured go by requests.
- /// Null: every recipe goes by the browser. Production leaves it unset until S4.
+ /// Null: every recipe goes by the browser. Since S4 production sets it only with the option «raccolta» on
+ /// «richieste» and a catalog with configured operations (never with Instagram while none is configured).
///
public SiteRequestOptions? Requests { get; init; }
}
diff --git a/src/Febe.Browser/Session/SessionCapture.cs b/src/Febe.Browser/Session/SessionCapture.cs
new file mode 100644
index 0000000..d4822dd
--- /dev/null
+++ b/src/Febe.Browser/Session/SessionCapture.cs
@@ -0,0 +1,464 @@
+using System.Globalization;
+using System.Text;
+using System.Text.Json;
+using System.Text.Json.Nodes;
+using System.Text.RegularExpressions;
+using Febe.Browser.Cdp;
+using Febe.Browser.Recipes;
+using Febe.Core.Abstractions;
+using Febe.Core.Collection;
+using Febe.Core.Collection.Requests;
+
+namespace Febe.Browser.Session;
+
+/// One value of the page the copy reads: the session field, and the module and property that hold it.
+/// The session field ().
+/// The module of the page's require.
+/// The property of the module; null for a module whose export is the value (a doc_id).
+public sealed record PageRead(string Field, string Module, string? Property);
+
+///
+/// What the copy at «Ho finito» reads from the browser (issue #36, S4, spec §6.0, §6.1 «Copiare la sessione»): the
+/// cookies of the site for its root and for every path of the catalog, the user agent, and only the modules the
+/// page section of richieste.<sito>.json names (checked identifiers). Holds names only.
+///
+public sealed class SessionCapturePlan
+{
+ private SessionCapturePlan(Uri site, HostClassifier hosts, IReadOnlyList cookieUrls, IReadOnlyList values, IReadOnlyList docIds, IReadOnlyList refusedPaths, IReadOnlySet neededValues, IReadOnlySet neededDocIds)
+ {
+ Site = site;
+ Hosts = hosts;
+ CookieUrls = cookieUrls;
+ Values = values;
+ DocIds = docIds;
+ RefusedPaths = refusedPaths;
+ NeededValues = neededValues;
+ NeededDocIds = neededDocIds;
+ }
+
+ /// The root of the site (https://www.instagram.com/, http://127.0.0.1:port/).
+ public Uri Site { get; }
+
+ /// The hosts of the site: the page must be on one of them.
+ public HostClassifier Hosts { get; }
+
+ ///
+ /// The addresses Network.getCookies is asked for: the root and, for each path of the catalog, the path up to
+ /// its first value (/api/dati/profilo/{nome} → /api/dati/profilo/), so a cookie limited to a path of the
+ /// site client is copied with it.
+ ///
+ public IReadOnlyList CookieUrls { get; }
+
+ /// The values of the page, in the order of the catalog's page section.
+ public IReadOnlyList Values { get; }
+
+ /// The doc_id of every GraphQL operation of the catalog (configured or not): is the operation.
+ public IReadOnlyList DocIds { get; }
+
+ /// Paths of the site where no copy is made: the login and verification pages of the stop rules (§7.6).
+ public IReadOnlyList RefusedPaths { get; }
+
+ ///
+ /// The values of the page a configured operation sends (session:<field>): only these, when missing, stop
+ /// a request of the site client (a disconnection, §6.0); the others are read but no request waits for them.
+ ///
+ public IReadOnlySet NeededValues { get; }
+
+ /// The configured GraphQL operations that send their doc_id from the saved session.
+ public IReadOnlySet NeededDocIds { get; }
+
+ /// The plan of from its catalog and its stop rules.
+ /// The site of the composition.
+ /// Its richieste.<sito>.json; without a page section only cookies and user agent are read.
+ /// Its stop rules: every path rule for the site is a page where no copy is made. Null: none.
+ public static SessionCapturePlan For(CollectionSite site, RequestCatalog catalog, SignalRules? rules)
+ {
+ ArgumentNullException.ThrowIfNull(site);
+ ArgumentNullException.ThrowIfNull(catalog);
+ var root = new Uri(site.BaseUrl.TrimEnd('/') + "/", UriKind.Absolute);
+ var urls = new List { root };
+ foreach (var operation in catalog.Operations)
+ {
+ var cut = operation.Path.IndexOf('{', StringComparison.Ordinal);
+ var prefix = cut < 0 ? operation.Path : operation.Path[..cut];
+ if (prefix.StartsWith('/') && Uri.TryCreate(root, prefix, out var address) && !urls.Contains(address))
+ {
+ urls.Add(address);
+ }
+ }
+
+ var values = new List();
+ var docIds = new List();
+ if (catalog.Page is { } page)
+ {
+ foreach (var field in page.Order)
+ {
+ var source = page.Values[field];
+ values.Add(new PageRead(field, source.Module, source.Property));
+ }
+
+ foreach (var operation in catalog.Operations.Where(o => o.Kind == OperationKind.GraphQl))
+ {
+ if (page.DocIdModuleFor(operation.Name) is { } module)
+ {
+ docIds.Add(new PageRead(operation.Name, module, null));
+ }
+ }
+ }
+
+ // What the configured operations actually send from the saved session: a missing value no configured operation
+ // uses stops nothing, and «Ho finito» does not count it as missing.
+ var neededValues = new HashSet(StringComparer.Ordinal);
+ var neededDocIds = new HashSet(StringComparer.Ordinal);
+ foreach (var operation in catalog.Configured)
+ {
+ foreach (var source in operation.Headers.Values.Concat(operation.Body.Values).Where(v => v.Kind == ValueSourceKind.Session))
+ {
+ if (source.Argument == "doc_id")
+ {
+ neededDocIds.Add(operation.Name);
+ }
+ else if (catalog.Page?.Values.ContainsKey(source.Argument!) == true)
+ {
+ neededValues.Add(source.Argument!);
+ }
+ }
+ }
+
+ var refused = rules?.Rules
+ .Where(r => r.Path is not null && r.HostKinds.Contains(HostKind.Site))
+ .Select(r => r.Path!)
+ .ToList() ?? [];
+ return new SessionCapturePlan(root, site.Hosts, urls, values, docIds, refused, neededValues, neededDocIds);
+ }
+
+ /// Counts only.
+ public override string ToString() => string.Create(
+ CultureInfo.InvariantCulture,
+ $"Copia della sessione: {CookieUrls.Count} indirizzi per i cookie, {Values.Count} valori della pagina, {DocIds.Count} doc_id.");
+}
+
+/// Why a copy was not made.
+public enum CaptureRefusal
+{
+ /// The page is not on the site (the rest page, another host).
+ NotOnSite,
+
+ /// The page is a login or verification page of the site (a path of the stop rules).
+ CheckpointPage,
+
+ /// The browser gave no user agent.
+ NoUserAgent,
+
+ /// The browser did not answer, or refused (restarting, closed, too slow).
+ BrowserError,
+}
+
+///
+/// What a copy found. Its text and its members hold counts and names only; the values are in ,
+/// whose text shows counts too (rule 10).
+///
+public sealed class SessionCaptureResult
+{
+ internal SessionCaptureResult(SiteSessionValues? values, CaptureRefusal? refusal, int droppedCookies, IReadOnlyList missingValues, IReadOnlyList missingDocIds, int expectedValues, int expectedDocIds)
+ {
+ Values = values;
+ Refusal = refusal;
+ DroppedCookies = droppedCookies;
+ MissingValues = missingValues;
+ MissingDocIds = missingDocIds;
+ ExpectedValues = expectedValues;
+ ExpectedDocIds = expectedDocIds;
+ }
+
+ /// The copied session; null when the copy was refused.
+ public SiteSessionValues? Values { get; }
+
+ /// Why nothing was copied; null when is there.
+ public CaptureRefusal? Refusal { get; }
+
+ /// How many cookies were copied.
+ public int Cookies => Values?.Cookies.Count ?? 0;
+
+ /// Cookies of the site left out: partitioned, or with a name or value a browser would not send back.
+ public int DroppedCookies { get; }
+
+ /// The session fields the page did not give (left absent, never guessed: rule 9).
+ public IReadOnlyList MissingValues { get; }
+
+ /// The GraphQL operations whose doc_id the page did not give.
+ public IReadOnlyList MissingDocIds { get; }
+
+ /// How many values of the page the plan asked for.
+ public int ExpectedValues { get; }
+
+ /// How many doc_id the plan asked for.
+ public int ExpectedDocIds { get; }
+
+ internal static SessionCaptureResult Refused(CaptureRefusal refusal) => new(null, refusal, 0, [], [], 0, 0);
+
+ /// Counts and names only.
+ public override string ToString() => Refusal is { } refusal
+ ? $"Copia della sessione rifiutata: {refusal}."
+ : string.Create(
+ CultureInfo.InvariantCulture,
+ $"Copia della sessione: {Cookies} cookie ({DroppedCookies} scartati), {ExpectedValues - MissingValues.Count} valori della pagina su {ExpectedValues}, {ExpectedDocIds - MissingDocIds.Count} doc_id su {ExpectedDocIds}.");
+}
+
+///
+/// The copy of the browser's session into a saved session (issue #36, S4, spec §6.0, §6.1 «Copiare la sessione»): only
+/// Page.getFrameTree (where the page is), Network.getCookies with the values for the site's addresses,
+/// and ONE read-only Runtime.evaluate that reads navigator.userAgent and the modules of the plan. Nothing
+/// is navigated, nothing is written into the browser, nothing is logged here: the caller logs counts and names.
+///
+///
+/// A value the page does not give is left out, never invented (rule 9): a missing module, a property that is not a
+/// string or a number, a value too long or with control or non-ASCII characters. Cookies are kept as the browser has
+/// them (name, value, domain, path, host-only, secure, HTTP-only, expiry); a partitioned cookie, or one a browser would
+/// not send back, is left out and counted.
+///
+public static class SessionCapture
+{
+ /// The longest page value kept.
+ public const int MaxValueLength = 4096;
+
+ ///
+ /// Copies the session the page holds now.
+ ///
+ /// was cancelled.
+ public static async Task CaptureAsync(ICdpSession cdp, SessionCapturePlan plan, IClock clock, CancellationToken ct)
+ {
+ ArgumentNullException.ThrowIfNull(cdp);
+ ArgumentNullException.ThrowIfNull(plan);
+ ArgumentNullException.ThrowIfNull(clock);
+ try
+ {
+ // (a) Only on a page of the site, not on its login or verification page. The address is never logged.
+ var url = await cdp.GetMainFrameUrlAsync(ct).ConfigureAwait(false);
+ if (!Uri.TryCreate(url, UriKind.Absolute, out var page) || plan.Hosts.Classify(page) != HostKind.Site)
+ {
+ return SessionCaptureResult.Refused(CaptureRefusal.NotOnSite);
+ }
+
+ var path = string.IsNullOrEmpty(page.AbsolutePath) ? "/" : page.AbsolutePath;
+ if (plan.RefusedPaths.Any(rule => IsMatch(rule, path)))
+ {
+ return SessionCaptureResult.Refused(CaptureRefusal.CheckpointPage);
+ }
+
+ // (b) The cookies of the site, with their values.
+ var urls = new JsonArray();
+ foreach (var address in plan.CookieUrls)
+ {
+ urls.Add(address.AbsoluteUri);
+ }
+
+ var answer = await cdp.SendAsync("Network.getCookies", new JsonObject { ["urls"] = urls }, ct).ConfigureAwait(false);
+ var (cookies, dropped) = ReadCookies(answer, plan);
+
+ // (c) One read-only evaluation: the user agent and the modules of the plan.
+ var read = await cdp.EvaluateAsync(SessionCaptureScript.Build(plan), ct).ConfigureAwait(false);
+ var userAgent = read.ValueKind == JsonValueKind.Object && read.TryGetProperty("ua", out var ua) ? Accept(ua) : null;
+ if (userAgent is null)
+ {
+ return SessionCaptureResult.Refused(CaptureRefusal.NoUserAgent);
+ }
+
+ var fields = Collect(read, "values", plan.Values, out var missingValues);
+ var docIds = Collect(read, "docIds", plan.DocIds, out var missingDocIds);
+
+ // (d) The values present; the absent stay absent.
+ var values = new SiteSessionValues(cookies, userAgent, fields, docIds, clock.Now);
+ return new SessionCaptureResult(values, null, dropped, missingValues, missingDocIds, plan.Values.Count, plan.DocIds.Count);
+ }
+ catch (OperationCanceledException) when (ct.IsCancellationRequested)
+ {
+ throw;
+ }
+ catch (Exception ex) when (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException
+ or TimeoutException or CdpEvaluationException or CdpCommandNotAllowedException or OperationCanceledException
+ or KeyNotFoundException or InvalidOperationException)
+ {
+ // Never the text of the browser or the page: it may hold what the page holds.
+ return SessionCaptureResult.Refused(CaptureRefusal.BrowserError);
+ }
+ }
+
+ private static bool IsMatch(Regex rule, string path)
+ {
+ try
+ {
+ return rule.IsMatch(path);
+ }
+ catch (RegexMatchTimeoutException)
+ {
+ // An expression too slow on this address: as if it matched, no copy.
+ return true;
+ }
+ }
+
+ /// The cookies of for a host of the site, and how many were left out.
+ private static (List Cookies, int Dropped) ReadCookies(JsonElement answer, SessionCapturePlan plan)
+ {
+ var kept = new List();
+ var dropped = 0;
+ if (answer.ValueKind != JsonValueKind.Object || !answer.TryGetProperty("cookies", out var list) || list.ValueKind != JsonValueKind.Array)
+ {
+ return (kept, dropped);
+ }
+
+ var hosts = plan.CookieUrls.Select(SiteCookies.HostOf).Distinct(StringComparer.Ordinal).ToList();
+ foreach (var item in list.EnumerateArray())
+ {
+ if (item.ValueKind != JsonValueKind.Object)
+ {
+ continue;
+ }
+
+ var name = Text(item, "name");
+ var value = Text(item, "value");
+ var rawDomain = Text(item, "domain");
+ if (rawDomain is null)
+ {
+ dropped++;
+ continue;
+ }
+
+ var hostOnly = !rawDomain.StartsWith('.');
+ var domain = SiteCookies.NormalizeDomain(rawDomain);
+
+ // Another host's cookie (the browser answers by address, so this is only a second guard): not the site's.
+ if (domain is null || !hosts.Any(h => SiteCookies.DomainMatches(h, domain, hostOnly)))
+ {
+ continue;
+ }
+
+ // A partitioned cookie belongs to the page that embeds the site, not to the site: never sent by the client.
+ if (item.TryGetProperty("partitionKey", out var partition) && partition.ValueKind is not (JsonValueKind.Null or JsonValueKind.Undefined))
+ {
+ dropped++;
+ continue;
+ }
+
+ if (name is null || value is null || !SiteCookies.IsPlainName(name) || !SiteCookies.IsSendableValue(value))
+ {
+ dropped++;
+ continue;
+ }
+
+ var cookiePath = Text(item, "path") ?? "/";
+ var secure = Flag(item, "secure");
+ var httpOnly = Flag(item, "httpOnly");
+ DateTimeOffset? expires = null;
+ if (!Flag(item, "session") && item.TryGetProperty("expires", out var e) && e.ValueKind == JsonValueKind.Number && e.TryGetDouble(out var seconds) && seconds > 0)
+ {
+ expires = seconds >= DateTimeOffset.MaxValue.ToUnixTimeSeconds()
+ ? DateTimeOffset.MaxValue
+ : DateTimeOffset.FromUnixTimeMilliseconds((long)(seconds * 1000));
+ }
+
+ try
+ {
+ kept.Add(new SiteCookie(name, value, domain, cookiePath, hostOnly, secure, httpOnly, expires));
+ }
+ catch (ArgumentException)
+ {
+ // A path or domain a browser would not keep: left out (the message would name the cookie only).
+ dropped++;
+ }
+ }
+
+ return (kept, dropped);
+ }
+
+ /// The values of the plan asked for and the page gave; the names of the others.
+ private static Dictionary Collect(JsonElement read, string section, IReadOnlyList asked, out IReadOnlyList missing)
+ {
+ var found = new Dictionary(StringComparer.Ordinal);
+ var absent = new List();
+ var hasSection = read.TryGetProperty(section, out var given) && given.ValueKind == JsonValueKind.Object;
+ foreach (var entry in asked)
+ {
+ if (hasSection && given.TryGetProperty(entry.Field, out var value) && Accept(value) is { } text)
+ {
+ found[entry.Field] = text;
+ }
+ else
+ {
+ absent.Add(entry.Field);
+ }
+ }
+
+ missing = absent;
+ return found;
+ }
+
+ /// A string of at most printable ASCII characters, or null.
+ private static string? Accept(JsonElement value)
+ {
+ if (value.ValueKind != JsonValueKind.String)
+ {
+ return null;
+ }
+
+ var text = value.GetString();
+ return text is { Length: > 0 and <= MaxValueLength } && text.All(c => c is >= ' ' and <= '~') ? text : null;
+ }
+
+ private static string? Text(JsonElement item, string name) =>
+ item.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String ? value.GetString() : null;
+
+ private static bool Flag(JsonElement item, string name) =>
+ item.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.True;
+}
+
+///
+/// The one expression of the copy (§6.1: Runtime.evaluate read-only): written only from the identifiers of the
+/// plan, each embedded as a JSON string, so a catalog file cannot put code in it; it passes
+/// . Every module is read in its own try: an unknown module, or one the page
+/// refuses, is a missing value and never an error that leaves the expression.
+///
+public static class SessionCaptureScript
+{
+ /// The expression for .
+ public static string Build(SessionCapturePlan plan)
+ {
+ ArgumentNullException.ThrowIfNull(plan);
+ var text = new StringBuilder();
+ text.Append("(() => {\n");
+ text.Append(" const out = { ua: null, values: {}, docIds: {} };\n");
+ text.Append(" try { out.ua = String(navigator.userAgent); } catch (e) { out.ua = null; }\n");
+ text.Append(" const has = typeof require === 'function';\n");
+ text.Append(" const read = (m, p) => {\n");
+ text.Append(" if (!has) { return null; }\n");
+ text.Append(" try {\n");
+ text.Append(" const x = require(m);\n");
+ text.Append(" const v = p === null ? x : (x === null || x === undefined ? undefined : x[p]);\n");
+ text.Append(" return typeof v === 'string' || typeof v === 'number' ? String(v) : null;\n");
+ text.Append(" } catch (e) { return null; }\n");
+ text.Append(" };\n");
+ Append(text, "values", plan.Values);
+ Append(text, "docIds", plan.DocIds);
+ text.Append(" return out;\n");
+ text.Append("})()");
+ return text.ToString();
+ }
+
+ /// A JavaScript string literal (JSON) for .
+ private static string Quote(string name) => JsonValue.Create(name).ToJsonString();
+
+ private static void Append(StringBuilder text, string section, IReadOnlyList reads)
+ {
+ foreach (var read in reads)
+ {
+ // Checked identifiers, embedded as JSON strings all the same: never code.
+ if (!PageSources.IsIdentifier(read.Module) || (read.Property is not null && !PageSources.IsIdentifier(read.Property)))
+ {
+ throw new ArgumentException("Un nome della sezione «page» non è un identificatore.", nameof(reads));
+ }
+
+ var property = read.Property is null ? "null" : Quote(read.Property);
+ text.Append(CultureInfo.InvariantCulture, $" {{ const v = read({Quote(read.Module)}, {property}); if (v !== null) {{ out.{section}[{Quote(read.Field)}] = v; }} }}\n");
+ }
+ }
+}
diff --git a/src/Febe.Core/Collection/Requests/FileSiteSession.cs b/src/Febe.Core/Collection/Requests/FileSiteSession.cs
new file mode 100644
index 0000000..2d1a6bd
--- /dev/null
+++ b/src/Febe.Core/Collection/Requests/FileSiteSession.cs
@@ -0,0 +1,258 @@
+using System.Globalization;
+using System.Security.Cryptography;
+using Febe.Core.Security;
+
+namespace Febe.Core.Collection.Requests;
+
+///
+/// The saved session on disk (issue #36, S4, spec §6.0, §13.2): Dati/sessione/sessione.json, encrypted by an
+/// (DPAPI on Windows, AES-256-GCM in Docker), owner-only, replaced at once. Only the
+/// copy from the browser and the site client touch it; it is not in the database, so never in the daily copies, and
+/// the diagnostic report never reads it.
+///
+///
+///
+/// - Loaded once, when built: no file is no session; a file that cannot be read (another key or user, damaged,
+/// another format) is no session too, logged as such and left as it is, until a new copy replaces it.
+/// - One gate for , and ; an update
+/// checks the session and its capture again once it holds the gate, so a late answer never brings back a session
+/// «Scollega» deleted, nor touches one a new login replaced.
+/// - The memory counts first: the site already rotated its cookies, so a write the disk refuses keeps the new
+/// values in memory, logs one line with the kind of error, and is tried again with the next write.
+/// - Logs say counts and kinds only, never a value, a cookie name or a path (rule 10).
+///
+///
+public sealed class FileSiteSession : ISavedSiteSession
+{
+ private readonly ISessionProtector _protector;
+ private readonly Action _log;
+ private readonly Lock _snapshotGate = new();
+
+ // Never disposed: no wait handle is ever asked of it.
+ private readonly SemaphoreSlim _writes = new(1, 1);
+ private SiteSessionValues? _values;
+ private SavedSessionState _state;
+ private bool _unsaved;
+ private int _failedWrites;
+
+ /// The file (DataFolderLayout.SessionFile); its folder is made owner-only when first written.
+ /// The encryption of the platform.
+ /// Receives the Italian log lines (counts and kinds only); null discards them.
+ public FileSiteSession(string file, ISessionProtector protector, Action? log = null)
+ {
+ ArgumentException.ThrowIfNullOrWhiteSpace(file);
+ FilePath = Path.GetFullPath(file);
+ _protector = protector ?? throw new ArgumentNullException(nameof(protector));
+ _log = log ?? (_ => { });
+ Load();
+ }
+
+ /// The file of the session.
+ public string FilePath { get; }
+
+ public SavedSessionState State
+ {
+ get
+ {
+ lock (_snapshotGate)
+ {
+ return _state;
+ }
+ }
+ }
+
+ /// True while the values in memory are newer than the file (a write the disk refused).
+ public bool Unsaved
+ {
+ get
+ {
+ lock (_snapshotGate)
+ {
+ return _unsaved;
+ }
+ }
+ }
+
+ public SiteSessionValues? Read()
+ {
+ lock (_snapshotGate)
+ {
+ return _values;
+ }
+ }
+
+ public async Task ReplaceAsync(SiteSessionValues values, CancellationToken ct)
+ {
+ ArgumentNullException.ThrowIfNull(values);
+ await _writes.WaitAsync(ct).ConfigureAwait(false);
+ try
+ {
+ Swap(values, unsaved: true);
+ var saved = Persist(values);
+ if (saved)
+ {
+ _log(string.Create(CultureInfo.InvariantCulture, $"Sessione salvata scritta: {values.Cookies.Count} cookie, {values.Fields.Count} valori della pagina, {values.DocIds.Count} doc_id ({_protector.Scheme})."));
+ }
+
+ return saved;
+ }
+ finally
+ {
+ _writes.Release();
+ }
+ }
+
+ public async Task UpdateAsync(SiteSessionUpdate update, CancellationToken ct)
+ {
+ ArgumentNullException.ThrowIfNull(update);
+ ct.ThrowIfCancellationRequested();
+ if (update.IsEmpty)
+ {
+ return;
+ }
+
+ // Never cancelled once asked: the site already sent the renewal (HttpSiteRequester passes None anyway).
+ await _writes.WaitAsync(CancellationToken.None).ConfigureAwait(false);
+ try
+ {
+ // Checked again under the gate: «Scollega» or a new login may have come while this one waited.
+ var current = Read();
+ if (current is null || (update.Capture is { } capture && capture != current.Capture))
+ {
+ return;
+ }
+
+ var next = current.With(update);
+ Swap(next, unsaved: true);
+ Persist(next);
+ }
+ finally
+ {
+ _writes.Release();
+ }
+ }
+
+ public async Task DeleteAsync(CancellationToken ct)
+ {
+ // Not cancellable: «Scollega» must not stop halfway because the page that asked it went away.
+ await _writes.WaitAsync(CancellationToken.None).ConfigureAwait(false);
+ try
+ {
+ // Memory first: from here no update finds a session to renew.
+ lock (_snapshotGate)
+ {
+ _values = null;
+ _state = SavedSessionState.None;
+ _unsaved = false;
+ }
+
+ OwnerOnlyFiles.DeleteWithLeftovers(FilePath);
+ _log("Sessione salvata cancellata.");
+ }
+ finally
+ {
+ _writes.Release();
+ }
+ }
+
+ /// Counts only.
+ public override string ToString() => State switch
+ {
+ SavedSessionState.Present => Read()?.ToString() ?? "Nessuna sessione salvata.",
+ SavedSessionState.Unreadable => "Sessione salvata illeggibile.",
+ _ => "Nessuna sessione salvata.",
+ };
+
+ private void Load()
+ {
+ byte[]? blob = null;
+ byte[]? plain = null;
+ try
+ {
+ if (!File.Exists(FilePath))
+ {
+ _state = SavedSessionState.None;
+ return;
+ }
+
+ blob = File.ReadAllBytes(FilePath);
+ plain = _protector.Unprotect(blob);
+ _values = SavedSessionFile.Deserialize(plain);
+ _state = SavedSessionState.Present;
+ _log(string.Create(CultureInfo.InvariantCulture, $"Sessione salvata letta: {_values.Cookies.Count} cookie, {_values.Fields.Count} valori della pagina, {_values.DocIds.Count} doc_id ({_protector.Scheme})."));
+ }
+ catch (Exception ex) when (ex is SessionUnreadableException or InvalidDataException or CryptographicException)
+ {
+ _values = null;
+ _state = SavedSessionState.Unreadable;
+ _log("Sessione salvata illeggibile (cifratura o formato): serve un nuovo accesso. Il file resta com'è finché un nuovo accesso non lo sostituisce.");
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ _values = null;
+ _state = SavedSessionState.Unreadable;
+ _log($"Sessione salvata non letta ({ex.GetType().Name}): serve un nuovo accesso.");
+ }
+ finally
+ {
+ if (plain is not null)
+ {
+ CryptographicOperations.ZeroMemory(plain);
+ }
+ }
+ }
+
+ private void Swap(SiteSessionValues values, bool unsaved)
+ {
+ lock (_snapshotGate)
+ {
+ _values = values;
+ _state = SavedSessionState.Present;
+ _unsaved = unsaved;
+ }
+ }
+
+ /// Writes (always the newest, under the gate); false when the disk refused it.
+ private bool Persist(SiteSessionValues values)
+ {
+ byte[]? plain = null;
+ try
+ {
+ plain = SavedSessionFile.Serialize(values);
+ var blob = _protector.Protect(plain);
+ OwnerOnlyFiles.EnsureFolder(Path.GetDirectoryName(FilePath)!);
+ OwnerOnlyFiles.WriteAtomic(FilePath, blob);
+ lock (_snapshotGate)
+ {
+ if (ReferenceEquals(_values, values))
+ {
+ _unsaved = false;
+ }
+ }
+
+ if (Interlocked.Exchange(ref _failedWrites, 0) > 0)
+ {
+ _log("Sessione salvata scritta di nuovo: il disco ora accetta le scritture.");
+ }
+
+ return true;
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or CryptographicException)
+ {
+ // One line per run of failures: the kind of error only, never the path or a value.
+ if (Interlocked.Increment(ref _failedWrites) == 1)
+ {
+ _log($"Sessione salvata non scritta ({ex.GetType().Name}): resta in memoria e si riprova alla prossima scrittura.");
+ }
+
+ return false;
+ }
+ finally
+ {
+ if (plain is not null)
+ {
+ CryptographicOperations.ZeroMemory(plain);
+ }
+ }
+ }
+}
diff --git a/src/Febe.Core/Collection/Requests/HttpSiteRequester.cs b/src/Febe.Core/Collection/Requests/HttpSiteRequester.cs
index 23b7304..de24e8a 100644
--- a/src/Febe.Core/Collection/Requests/HttpSiteRequester.cs
+++ b/src/Febe.Core/Collection/Requests/HttpSiteRequester.cs
@@ -127,7 +127,9 @@ public sealed class SiteSessionMissingException : SiteRequestRefusedException
/// - Only to : https only for Instagram, http only for a loopback
/// test site; every address it builds is checked again before it leaves.
/// - No redirect is followed (AllowAutoRedirect = false): a 3xx comes back as an answer, a signal (§7.6).
-/// - Cookies are written by hand, as one Cookie header (UseCookies = false), in the session's order.
+/// - Cookies are written by hand, as one Cookie header (UseCookies = false): only those whose domain
+/// and path match the request and, when secure, only over https (RFC 6265 §5.4), longer paths first, then the session's
+/// order; a renewal from Set-Cookie keeps or sets domain and path as a browser does.
/// - HTTP/2 with fallback to HTTP/1.1 (), never HTTP/3;
/// gzip, deflate and brotli (the HTTP stack adds Accept-Encoding: gzip, deflate, br to say so: with
/// Host and Content-Length the only headers not in the catalog, besides the Cookie line; no
@@ -284,12 +286,15 @@ public sealed class HttpSiteRequester : ISiteRequester, IDisposable
{
var values = _session.Read()
?? throw new SiteSessionMissingException($"Richiesta «{operation.Name}» non inviata: non c'è una sessione salvata.", missing: null);
- if (values.CookieAt(_options.SessionCookie, _clock.Now) is null)
+ var address = Address(operation, request);
+
+ // The session cookie the browser would send to this address: one limited to another path or host is not it.
+ if (values.CookieFor(_options.SessionCookie, address, _clock.Now) is null)
{
throw new SiteSessionMissingException($"Richiesta «{operation.Name}» non inviata: la sessione salvata non ha il cookie di sessione, o è scaduto.", _options.SessionCookie);
}
- using var message = Build(operation, request, values);
+ using var message = Build(operation, request, address, values);
return await ExchangeAsync(operation, message, values.Capture, ct).ConfigureAwait(false);
}
finally
@@ -338,7 +343,7 @@ public sealed class HttpSiteRequester : ISiteRequester, IDisposable
{
// What the site renewed counts as soon as the headers are here, as for a browser: the site may already have
// dropped the old values, whatever happens to the body or to the caller next. Never cancelled.
- var update = SessionUpdate(response, capture, out var set, out var deleted);
+ var update = SessionUpdate(response, message.RequestUri!, capture, out var set, out var deleted);
if (!update.IsEmpty)
{
await _session.UpdateAsync(update, CancellationToken.None).ConfigureAwait(false);
@@ -405,15 +410,9 @@ public sealed class HttpSiteRequester : ISiteRequester, IDisposable
? cancelled
: new OperationCanceledException("Client del sito chiuso: la richiesta in corso è stata interrotta.", _closing.Token);
- private HttpRequestMessage Build(SiteOperation operation, SiteRequest request, SiteSessionValues values)
+ /// The address of : the site and the catalog path, checked to stay on the site.
+ private Uri Address(SiteOperation operation, SiteRequest request)
{
- // The catalog refuses a configured operation without it; checked again: no request leaves without the
- // browser's user agent (rule 4), and the HTTP stack would add none.
- if (!operation.Headers.TryGetValue("user-agent", out var agent) || agent != new ValueSource(ValueSourceKind.Session, "user_agent"))
- {
- throw new SiteRequestRefusedException($"Richiesta «{operation.Name}» non inviata: il modello non manda l'user agent del browser («user-agent»: «session:user_agent»).");
- }
-
var address = new Uri(_site, PathAndQuery(operation, request));
// Built from the site and a catalog path the catalog checked: checked again, so nothing leaves for another host.
@@ -422,6 +421,18 @@ public sealed class HttpSiteRequester : ISiteRequester, IDisposable
throw new SiteRequestRefusedException($"Richiesta «{operation.Name}» non inviata: l'indirizzo non è del sito.");
}
+ return address;
+ }
+
+ private HttpRequestMessage Build(SiteOperation operation, SiteRequest request, Uri address, SiteSessionValues values)
+ {
+ // The catalog refuses a configured operation without it; checked again: no request leaves without the
+ // browser's user agent (rule 4), and the HTTP stack would add none.
+ if (!operation.Headers.TryGetValue("user-agent", out var agent) || agent != new ValueSource(ValueSourceKind.Session, "user_agent"))
+ {
+ throw new SiteRequestRefusedException($"Richiesta «{operation.Name}» non inviata: il modello non manda l'user agent del browser («user-agent»: «session:user_agent»).");
+ }
+
var message = new HttpRequestMessage(new HttpMethod(operation.Method), address)
{
Version = HttpVersion.Version20,
@@ -444,7 +455,7 @@ public sealed class HttpSiteRequester : ISiteRequester, IDisposable
continue;
}
- var value = Resolve(operation, name, source, values, variables: null, now);
+ var value = Resolve(operation, name, source, values, address, variables: null, now);
if (name == "content-type")
{
contentType = value;
@@ -457,7 +468,8 @@ public sealed class HttpSiteRequester : ISiteRequester, IDisposable
}
}
- var cookies = string.Join("; ", values.CookiesAt(now).Select(c => $"{c.Key}={c.Value}"));
+ // Only the cookies whose domain and path match this address, longer paths first (RFC 6265 §5.4).
+ var cookies = string.Join("; ", values.CookiesFor(address, now).Select(c => $"{c.Name}={c.Value}"));
message.Headers.TryAddWithoutValidation("cookie", cookies);
if (operation.Kind == OperationKind.GraphQl)
@@ -466,7 +478,7 @@ public sealed class HttpSiteRequester : ISiteRequester, IDisposable
var form = new StringBuilder();
foreach (var field in operation.BodyOrder)
{
- var value = Resolve(operation, field, operation.Body[field], values, variables, now);
+ var value = Resolve(operation, field, operation.Body[field], values, address, variables, now);
if (form.Length > 0)
{
form.Append('&');
@@ -530,12 +542,14 @@ public sealed class HttpSiteRequester : ISiteRequester, IDisposable
return path + query;
}
- private static string Resolve(SiteOperation operation, string name, ValueSource source, SiteSessionValues values, string? variables, DateTimeOffset now)
+ private static string Resolve(SiteOperation operation, string name, ValueSource source, SiteSessionValues values, Uri address, string? variables, DateTimeOffset now)
{
var value = source.Kind switch
{
ValueSourceKind.Constant => source.Argument,
- ValueSourceKind.Cookie => values.CookieAt(source.Argument!, now),
+
+ // The cookie the browser would send with this request (x-csrftoken is the csrftoken of this path).
+ ValueSourceKind.Cookie => values.CookieFor(source.Argument!, address, now),
ValueSourceKind.Session => values.Field(source.Argument!, operation.Name),
ValueSourceKind.Operation => operation.Name,
ValueSourceKind.Variables => variables,
@@ -693,75 +707,67 @@ public sealed class HttpSiteRequester : ISiteRequester, IDisposable
return text.ToString();
}
- private SiteSessionUpdate SessionUpdate(HttpResponseMessage response, long capture, out List set, out List deleted)
+ ///
+ /// What the answer renews in the session, read as a browser reads it: each Set-Cookie line against the
+ /// request address (its domain and path, or host-only on the site and the default path), in order, the last line of
+ /// a cookie winning; and the names of the cookies set and deleted, for the answer.
+ ///
+ private SiteSessionUpdate SessionUpdate(HttpResponseMessage response, Uri request, long capture, out List set, out List deleted)
{
- set = [];
- deleted = [];
-
// In the order of the Set-Cookie lines: a cookie new to the session goes after the others in that order.
- var renewed = new List>();
- var expires = new Dictionary(StringComparer.Ordinal);
+ var renewed = new List();
+ var removed = new List();
if (response.Headers.TryGetValues("set-cookie", out var lines))
{
var now = _clock.Now;
foreach (var line in lines)
{
- if (SiteCookies.Parse(line, _site.IdnHost, now) is not { } cookie)
+ if (SiteCookies.Parse(line, request, now) is not { } parsed)
{
continue;
}
- var index = renewed.FindIndex(c => c.Key == cookie.Name);
- if (cookie.Deletes)
+ var key = parsed.Cookie.Key;
+ var index = renewed.FindIndex(c => c.Key == key);
+ if (parsed.Deletes)
{
if (index >= 0)
{
renewed.RemoveAt(index);
}
- expires.Remove(cookie.Name);
- set.Remove(cookie.Name);
- if (!deleted.Contains(cookie.Name))
+ if (!removed.Contains(key))
{
- deleted.Add(cookie.Name);
+ removed.Add(key);
}
}
else
{
if (index >= 0)
{
- renewed[index] = new(cookie.Name, cookie.Value);
+ renewed[index] = parsed.Cookie;
}
else
{
- renewed.Add(new(cookie.Name, cookie.Value));
+ renewed.Add(parsed.Cookie);
}
- if (cookie.Expires is { } until)
- {
- expires[cookie.Name] = until;
- }
- else
- {
- expires.Remove(cookie.Name);
- }
-
- deleted.Remove(cookie.Name);
- if (!set.Contains(cookie.Name))
- {
- set.Add(cookie.Name);
- }
+ removed.Remove(key);
}
}
}
+ var setNames = renewed.Select(c => c.Name).Distinct(StringComparer.Ordinal).ToList();
+ set = setNames;
+ deleted = [.. removed.Select(k => k.Name).Distinct(StringComparer.Ordinal).Where(n => !setNames.Contains(n, StringComparer.Ordinal))];
+
string? claim = null;
if (response.Headers.TryGetValues("x-ig-set-www-claim", out var claims))
{
claim = claims.LastOrDefault(c => !string.IsNullOrWhiteSpace(c))?.Trim();
}
- return new SiteSessionUpdate(renewed, deleted, claim, expires, capture);
+ return new SiteSessionUpdate(renewed, removed, claim, capture);
}
private TimeSpan? RetryAfter(RetryConditionHeaderValue? header)
diff --git a/src/Febe.Core/Collection/Requests/ISiteSession.cs b/src/Febe.Core/Collection/Requests/ISiteSession.cs
index 435f50a..4ab7af2 100644
--- a/src/Febe.Core/Collection/Requests/ISiteSession.cs
+++ b/src/Febe.Core/Collection/Requests/ISiteSession.cs
@@ -5,9 +5,10 @@ namespace Febe.Core.Collection.Requests;
///
/// The saved session the site client reads its values from and writes the site's renewals to (issue #36, spec §6.0,
-/// §13.2): the cookies of the site with their values, the user agent of the browser as it is, the tokens and
-/// identifiers the page holds, the doc_id of each catalog operation and the x-ig-www-claim. Tappa S4 adds
-/// the encrypted file of Dati/sessione; serves the tests and the test site.
+/// §13.2): the cookies of the site with their values, domains and paths, the user agent of the browser as it is, the
+/// tokens and identifiers the page holds, the doc_id of each catalog operation and the x-ig-www-claim.
+/// keeps it in the encrypted file of Dati/sessione (tappa S4);
+/// serves the tests and the simulation.
///
///
/// Only the site client and the copy from the browser («Ho finito», S4) touch it. Its values never reach a log, a
@@ -22,19 +23,55 @@ public interface ISiteSession
/// Applies what the site sent with one answer (renewed or deleted cookies, a new claim) in one write, so a stored
/// session never holds half an answer. Does nothing when there is no saved session, and nothing when
/// names another capture than the stored one: the late answer of a session
- /// a new login replaced never touches the new one (§6.0: «un nuovo accesso ricopia tutto e sostituisce»).
+ /// a new login replaced never touches the new one (§6.0: «un nuovo accesso ricopia tutto e sostituisce»). Never
+ /// throws because of the disk: a store that cannot write keeps the renewal in memory and tries again later.
///
Task UpdateAsync(SiteSessionUpdate update, CancellationToken ct);
}
+/// Whether a saved session is there (never what it holds).
+public enum SavedSessionState
+{
+ /// No saved session: never copied, or deleted by «Scollega».
+ None,
+
+ /// A saved session is there.
+ Present,
+
+ /// A file is there but cannot be read (another key, damaged, another format): counts as no session.
+ Unreadable,
+}
+
+///
+/// The saved session a new copy from the browser replaces and «Scollega» deletes (issue #36, S4, §6.0, §13.2).
+///
+public interface ISavedSiteSession : ISiteSession
+{
+ /// Whether a session is there; counts as none.
+ SavedSessionState State { get; }
+
+ ///
+ /// Replaces the whole session with a new copy (a new login: «un nuovo accesso ricopia tutto e sostituisce»). The new
+ /// values count at once, also when the disk refuses them; true when they are also on disk.
+ ///
+ Task ReplaceAsync(SiteSessionValues values, CancellationToken ct);
+
+ ///
+ /// Deletes the session («Scollega»): first in memory, so no later renewal can bring it back, then on disk.
+ ///
+ /// The file could not be deleted (the session is already gone from memory).
+ /// The file could not be deleted.
+ Task DeleteAsync(CancellationToken ct);
+}
+
///
/// A snapshot of the saved session. Its text () shows counts only, never a name of the account,
/// a value of a cookie or of a token.
///
///
-/// Cookies are the ones the browser would send to the site's address (S4 copies them with Network.getCookies
-/// for that address, so domain and path are already resolved by the browser), each with its expiry when it has one: an
-/// expired cookie is not sent, an expired session cookie is a missing session (§7.6, Disconnessione).
+/// Cookies keep domain, path, secure and expiry as the browser had them (S4 copies them with Network.getCookies):
+/// the site client sends a cookie only to an address it matches (); an expired cookie is
+/// not sent, an expired session cookie is a missing session (§7.6, Disconnessione).
///
public sealed class SiteSessionValues
{
@@ -43,59 +80,57 @@ public sealed class SiteSessionValues
private static long s_captures;
- /// Cookies of the site, by name, in the order the browser had them, values as they are.
- /// The user agent of Febe's browser, copied as it is (rule 4).
- ///
- /// Values of the page by the names of other than user_agent and
- /// doc_id: lsd, fb_dtsg, app_id, claim, account_id.
+ ///
+ /// Cookies of the site, in the order the browser had them (its order stands for the creation order, RFC 6265 §5.4);
+ /// a second cookie with the same replaces the first in its place.
///
+ /// The user agent of Febe's browser, copied as it is (rule 4).
+ /// Values of the page by the names of (and claim).
/// The doc_id of each GraphQL operation of the catalog, by operation name.
- /// When cookies expire, by name; a cookie not listed lasts as long as the session.
- /// A cookie name that is not a plain name, or a field that is not a session field.
+ /// When the browser's session was copied; null when not known.
+ /// A field that is not a session field (the message names the field, never a value).
public SiteSessionValues(
- IEnumerable> cookies,
+ IEnumerable cookies,
string userAgent,
IReadOnlyDictionary? fields = null,
IReadOnlyDictionary? docIds = null,
- IReadOnlyDictionary? expires = null)
- : this(cookies, userAgent, fields, docIds, expires, Interlocked.Increment(ref s_captures))
+ DateTimeOffset? copiedAt = null)
+ : this(cookies, userAgent, fields, docIds, copiedAt, Interlocked.Increment(ref s_captures))
{
}
private SiteSessionValues(
- IEnumerable> cookies,
+ IEnumerable cookies,
string userAgent,
IReadOnlyDictionary? fields,
IReadOnlyDictionary? docIds,
- IReadOnlyDictionary? expires,
+ DateTimeOffset? copiedAt,
long capture)
{
ArgumentNullException.ThrowIfNull(cookies);
ArgumentNullException.ThrowIfNull(userAgent);
- var list = new List>();
- foreach (var (name, value) in cookies)
+ var list = new List();
+ foreach (var cookie in cookies)
{
- if (!SiteCookies.IsPlainName(name))
- {
- throw new ArgumentException("Un nome di cookie della sessione non è un nome semplice.", nameof(cookies));
- }
-
- var index = list.FindIndex(c => c.Key == name);
+ ArgumentNullException.ThrowIfNull(cookie, nameof(cookies));
+ var index = list.FindIndex(c => c.Key == cookie.Key);
if (index >= 0)
{
- list[index] = new(name, value ?? string.Empty);
+ list[index] = cookie;
}
else
{
- list.Add(new(name, value ?? string.Empty));
+ list.Add(cookie);
}
}
foreach (var name in (fields ?? new Dictionary()).Keys)
{
- if (!ValueSource.SessionFields.Contains(name) || name is "user_agent" or "doc_id")
+ if (!StoredFields.Contains(name))
{
- throw new ArgumentException($"«{name}» non è un valore della sessione (ammessi: lsd, fb_dtsg, app_id, claim, account_id).", nameof(fields));
+ throw new ArgumentException(
+ $"«{name}» non è un valore della sessione (ammessi: {string.Join(", ", StoredFields.Order(StringComparer.Ordinal))}).",
+ nameof(fields));
}
}
@@ -103,55 +138,65 @@ public sealed class SiteSessionValues
UserAgent = userAgent;
Fields = (fields ?? new Dictionary()).ToFrozenDictionary(StringComparer.Ordinal);
DocIds = (docIds ?? new Dictionary()).ToFrozenDictionary(StringComparer.Ordinal);
- Expires = (expires ?? new Dictionary())
- .Where(e => list.Exists(c => c.Key == e.Key))
- .ToFrozenDictionary(StringComparer.Ordinal);
+ CopiedAt = copiedAt;
Capture = capture;
}
+ ///
+ /// The session fields read from the page (the page section of the catalog says where): every name of
+ /// but user_agent (the browser's), doc_id (by operation) and
+ /// claim (set by the site).
+ ///
+ public static IReadOnlySet PageFields { get; } = ValueSource.SessionFields
+ .Where(f => f is not ("user_agent" or "doc_id" or "claim")).ToFrozenSet(StringComparer.Ordinal);
+
+ /// The names may hold: and claim.
+ public static IReadOnlySet StoredFields { get; } = PageFields.Append("claim").ToFrozenSet(StringComparer.Ordinal);
+
///
/// Which capture from the browser these values come from: the same through every renewal (),
- /// another for a new login. Says nothing of the account.
+ /// another for a new login or a new start. Says nothing of the account.
///
public long Capture { get; }
- /// Cookies of the site, by name, in order (never logged).
- public IReadOnlyList> Cookies { get; }
-
- /// When cookies expire, by name; a cookie not listed lasts as long as the session.
- public IReadOnlyDictionary Expires { get; }
+ /// Cookies of the site, in order (values never logged).
+ public IReadOnlyList Cookies { get; }
/// The user agent of Febe's browser, as it is.
public string UserAgent { get; }
- /// Values of the page (lsd, fb_dtsg, app_id, claim, account_id).
+ /// Values of the page () and the claim.
public IReadOnlyDictionary Fields { get; }
/// The doc_id of each GraphQL operation, by operation name.
public IReadOnlyDictionary DocIds { get; }
- /// The value of the cookie , or null.
- public string? Cookie(string name)
+ /// When the browser's session was copied; null when not known.
+ public DateTimeOffset? CopiedAt { get; }
+
+ /// The value of the first stored cookie named , whatever its domain and path, or null (tests and checks).
+ public string? Cookie(string name) => Cookies.FirstOrDefault(c => c.Name == name)?.Value;
+
+ ///
+ /// The value of the cookie a browser would send to at
+ /// (the matching one with the longest path, RFC 6265 §5.4), or null when none matches,
+ /// it is empty or it expired.
+ ///
+ public string? CookieFor(string name, Uri address, DateTimeOffset now) =>
+ CookiesFor(address, now).FirstOrDefault(c => c.Name == name)?.Value;
+
+ ///
+ /// The cookies a browser would send to at , in the order of the
+ /// Cookie line (RFC 6265 §5.4): longer paths first, then the stored order. No empty and no expired one.
+ ///
+ public IReadOnlyList CookiesFor(Uri address, DateTimeOffset now)
{
- foreach (var (key, value) in Cookies)
- {
- if (key == name)
- {
- return value;
- }
- }
+ ArgumentNullException.ThrowIfNull(address);
- return null;
+ // OrderByDescending is stable: cookies with paths of the same length keep the stored order.
+ return [.. Cookies.Where(c => c.Matches(address, now)).OrderByDescending(c => c.Path.Length)];
}
- /// The value of the cookie the browser would still send at : null when missing, empty or expired.
- public string? CookieAt(string name, DateTimeOffset now) =>
- Cookie(name) is { Length: > 0 } value && !IsExpired(name, now) ? value : null;
-
- /// The cookies the browser would still send at , in order: no empty and no expired one.
- public IEnumerable> CookiesAt(DateTimeOffset now) =>
- Cookies.Where(c => c.Value.Length > 0 && !IsExpired(c.Key, now));
-
///
/// The value of a session field of the catalog () for
/// : user_agent, the doc_id of the operation, or a value of the page. Null
@@ -166,32 +211,24 @@ public sealed class SiteSessionValues
_ => Fields.TryGetValue(name, out var value) && value.Length > 0 ? value : null,
};
- /// These values with applied (same ).
+ ///
+ /// These values with applied (same ): deleted cookies go, a renewed
+ /// cookie keeps its place (the browser keeps the creation time of a cookie it overwrites), a new one goes at the end.
+ ///
public SiteSessionValues With(SiteSessionUpdate update)
{
ArgumentNullException.ThrowIfNull(update);
- var cookies = Cookies.Where(c => !update.CookiesDeleted.Contains(c.Key, StringComparer.Ordinal)).ToList();
- var expires = Expires.Where(e => !update.CookiesDeleted.Contains(e.Key, StringComparer.Ordinal)).ToDictionary(StringComparer.Ordinal);
- foreach (var (name, value) in update.CookiesSet)
+ var cookies = Cookies.Where(c => !update.CookiesDeleted.Contains(c.Key)).ToList();
+ foreach (var cookie in update.CookiesSet)
{
- var index = cookies.FindIndex(c => c.Key == name);
+ var index = cookies.FindIndex(c => c.Key == cookie.Key);
if (index >= 0)
{
- // Renewed in place: the browser keeps the creation time of a cookie it overwrites, so its place.
- cookies[index] = new(name, value);
+ cookies[index] = cookie;
}
else
{
- cookies.Add(new(name, value));
- }
-
- if (update.Expires.TryGetValue(name, out var until))
- {
- expires[name] = until;
- }
- else
- {
- expires.Remove(name);
+ cookies.Add(cookie);
}
}
@@ -201,11 +238,9 @@ public sealed class SiteSessionValues
fields["claim"] = claim;
}
- return new SiteSessionValues(cookies, UserAgent, fields, DocIds, expires, Capture);
+ return new SiteSessionValues(cookies, UserAgent, fields, DocIds, CopiedAt, Capture);
}
- private bool IsExpired(string name, DateTimeOffset now) => Expires.TryGetValue(name, out var until) && until <= now;
-
/// Counts only.
public override string ToString() => string.Create(
CultureInfo.InvariantCulture,
@@ -213,55 +248,50 @@ public sealed class SiteSessionValues
}
///
-/// What the site sent with one answer for the saved session: cookies it renewed (with their values), cookies it
-/// deleted (names), a new x-ig-www-claim. Its text shows counts only.
+/// What the site sent with one answer for the saved session: cookies it set or renewed (with their values, domains and
+/// paths), cookies it deleted (their keys), a new x-ig-www-claim. Its text shows counts only.
///
public sealed class SiteSessionUpdate
{
- /// Cookies set or renewed, in the order of the Set-Cookie lines (a name twice: the last value, the first place).
- /// Names of the cookies deleted.
+ /// Cookies set or renewed, in the order of the Set-Cookie lines (the same key twice: the last value, the first place).
+ /// Keys of the cookies deleted.
/// The new claim, or null.
- /// When the cookies set expire, by name; one not listed lasts as long as the session.
/// The the request was sent with; null applies to any.
public SiteSessionUpdate(
- IEnumerable>? cookiesSet = null,
- IEnumerable? cookiesDeleted = null,
+ IEnumerable? cookiesSet = null,
+ IEnumerable? cookiesDeleted = null,
string? claim = null,
- IReadOnlyDictionary? expires = null,
long? capture = null)
{
- var set = new List>();
- foreach (var (name, value) in cookiesSet ?? [])
+ var set = new List();
+ foreach (var cookie in cookiesSet ?? [])
{
- var index = set.FindIndex(c => c.Key == name);
+ ArgumentNullException.ThrowIfNull(cookie, nameof(cookiesSet));
+ var index = set.FindIndex(c => c.Key == cookie.Key);
if (index >= 0)
{
- set[index] = new(name, value);
+ set[index] = cookie;
}
else
{
- set.Add(new(name, value));
+ set.Add(cookie);
}
}
CookiesSet = set;
- CookiesDeleted = [.. (cookiesDeleted ?? []).Distinct(StringComparer.Ordinal)];
+ CookiesDeleted = [.. (cookiesDeleted ?? []).Distinct()];
Claim = string.IsNullOrEmpty(claim) ? null : claim;
- Expires = (expires ?? new Dictionary()).ToFrozenDictionary(StringComparer.Ordinal);
Capture = capture;
}
/// Cookies set or renewed, with their values, in the order the site set them (never logged).
- public IReadOnlyList> CookiesSet { get; }
-
- /// When the cookies set expire, by name.
- public IReadOnlyDictionary Expires { get; }
+ public IReadOnlyList CookiesSet { get; }
/// The capture the request was sent with: the update applies only to that one (null: to any).
public long? Capture { get; }
- /// Names of the cookies the site deleted.
- public IReadOnlyList CookiesDeleted { get; }
+ /// Keys of the cookies the site deleted.
+ public IReadOnlyList CookiesDeleted { get; }
/// The new claim (x-ig-set-www-claim), or null.
public string? Claim { get; }
@@ -276,10 +306,10 @@ public sealed class SiteSessionUpdate
}
///
-/// The saved session in memory (issue #36, S2): for the tests, the simulation and the test site, until tappa S4 adds the
-/// encrypted file. Thread-safe; every update replaces the snapshot at once.
+/// The saved session in memory (issue #36, S2): for the tests and the simulation; Febe keeps it in
+/// . Thread-safe; every update replaces the snapshot at once.
///
-public sealed class InMemorySiteSession : ISiteSession
+public sealed class InMemorySiteSession : ISavedSiteSession
{
private readonly Lock _gate = new();
private SiteSessionValues? _values;
@@ -291,6 +321,8 @@ public sealed class InMemorySiteSession : ISiteSession
/// How many non-empty updates were applied.
public int Updates => Volatile.Read(ref _updates);
+ public SavedSessionState State => Read() is null ? SavedSessionState.None : SavedSessionState.Present;
+
public SiteSessionValues? Read()
{
lock (_gate)
@@ -308,6 +340,19 @@ public sealed class InMemorySiteSession : ISiteSession
}
}
+ public Task ReplaceAsync(SiteSessionValues values, CancellationToken ct)
+ {
+ ArgumentNullException.ThrowIfNull(values);
+ Replace(values);
+ return Task.FromResult(true);
+ }
+
+ public Task DeleteAsync(CancellationToken ct)
+ {
+ Replace(null);
+ return Task.CompletedTask;
+ }
+
public Task UpdateAsync(SiteSessionUpdate update, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(update);
@@ -335,75 +380,3 @@ public sealed class InMemorySiteSession : ISiteSession
/// Counts only.
public override string ToString() => Read()?.ToString() ?? "Nessuna sessione salvata.";
}
-
-/// Cookie names and the Set-Cookie lines of the site, read the way a browser reads them (RFC 6265).
-public static class SiteCookies
-{
- /// True for a plain cookie name: no separator, space, quote or control character.
- public static bool IsPlainName(string? name) =>
- !string.IsNullOrEmpty(name) && name.Length <= 256
- && !name.Any(c => c is '=' or ';' or ',' or '"' or '\\' || char.IsWhiteSpace(c) || char.IsControl(c) || c > '\x7e');
-
- ///
- /// One Set-Cookie line: its name, its value as the browser keeps it (RFC 6265 §5.2: double quotes are part
- /// of the value), whether it deletes the cookie (an empty value or "", a Max-Age of zero or less, an
- /// Expires not after ), and when it expires (null: with the session). Null for a line
- /// that is not a cookie, or one for another domain than (a browser would refuse it).
- ///
- public static (string Name, string Value, bool Deletes, DateTimeOffset? Expires)? Parse(string line, string host, DateTimeOffset now)
- {
- ArgumentNullException.ThrowIfNull(line);
- ArgumentNullException.ThrowIfNull(host);
- var parts = line.Split(';');
- var pair = parts[0];
- var equals = pair.IndexOf('=', StringComparison.Ordinal);
- if (equals <= 0)
- {
- return null;
- }
-
- var name = pair[..equals].Trim();
- var value = pair[(equals + 1)..].Trim();
- if (!IsPlainName(name))
- {
- return null;
- }
-
- var empty = value.Length == 0 || value == "\"\"";
- DateTimeOffset? byAge = null;
- DateTimeOffset? byDate = null;
- foreach (var attribute in parts.Skip(1))
- {
- var cut = attribute.IndexOf('=', StringComparison.Ordinal);
- var key = (cut < 0 ? attribute : attribute[..cut]).Trim();
- var argument = cut < 0 ? string.Empty : attribute[(cut + 1)..].Trim();
- if (key.Equals("max-age", StringComparison.OrdinalIgnoreCase)
- && long.TryParse(argument, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var seconds))
- {
- // The last Max-Age counts (RFC 6265 §5.3: attributes are read in order).
- byAge = seconds <= 0 ? DateTimeOffset.MinValue
- : seconds >= (DateTimeOffset.MaxValue - now).TotalSeconds ? DateTimeOffset.MaxValue
- : now.AddSeconds(seconds);
- }
- else if (key.Equals("expires", StringComparison.OrdinalIgnoreCase)
- && DateTimeOffset.TryParse(argument, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AllowWhiteSpaces, out var expires))
- {
- byDate = expires;
- }
- else if (key.Equals("domain", StringComparison.OrdinalIgnoreCase) && argument.Length > 0)
- {
- var domain = argument.TrimStart('.');
- if (!host.Equals(domain, StringComparison.OrdinalIgnoreCase)
- && !host.EndsWith("." + domain, StringComparison.OrdinalIgnoreCase))
- {
- return null;
- }
- }
- }
-
- // Max-Age wins over Expires (RFC 6265 §5.3 step 3).
- var until = byAge ?? byDate;
- var deletes = empty || until <= now;
- return (name, value, deletes, deletes ? null : until);
- }
-}
diff --git a/src/Febe.Core/Collection/Requests/RequestCatalog.cs b/src/Febe.Core/Collection/Requests/RequestCatalog.cs
index 763eeea..bd3ff7a 100644
--- a/src/Febe.Core/Collection/Requests/RequestCatalog.cs
+++ b/src/Febe.Core/Collection/Requests/RequestCatalog.cs
@@ -39,8 +39,9 @@ public enum ValueSourceKind
Computed,
///
- /// Not settled yet: the request shapes show the name but not where its value comes from (a value of the page, of
- /// the browser, or a name the probe removed). The site client cannot send it until it is settled (tappa S4).
+ /// Not settled yet: the request shapes show the name but not where its value comes from (a value the page computes
+ /// while it runs, a header of the browser, or a name the probe removed). The site client cannot send it, and an
+ /// operation that has one cannot be configured, until it is settled.
///
Pending,
}
@@ -50,12 +51,23 @@ public enum ValueSourceKind
/// The constant, the cookie name or the session field; null for the other kinds.
public sealed record ValueSource(ValueSourceKind Kind, string? Argument)
{
- /// The session fields a header or field may take (§6.0, what «Ho finito» copies).
+ ///
+ /// The session fields a header or field may take (§6.0, what «Ho finito» copies): the browser's user_agent,
+ /// the claim the site sets, the doc_id of the operation, and the values of the page, which the
+ /// page section of the catalog says where to read (): lsd, fb_dtsg,
+ /// app_id, account_id, and since S4 rev (__rev), hs (__hs), hsi
+ /// (__hsi), dpr, ccg (__ccg), comet_req (__comet_req) and
+ /// entry_nonce (x-fb-entry-nonce).
+ ///
public static IReadOnlySet SessionFields { get; } = new[]
{
"user_agent", "lsd", "fb_dtsg", "app_id", "claim", "account_id", "doc_id",
+ "rev", "hs", "hsi", "dpr", "ccg", "comet_req", "entry_nonce",
}.ToFrozenSet(StringComparer.Ordinal);
+ /// The session fields that need no page entry: the browser's user agent and the claim the site sets (H13).
+ public static IReadOnlySet FieldsWithoutPage { get; } = new[] { "user_agent", "claim" }.ToFrozenSet(StringComparer.Ordinal);
+
/// The text form of the catalog file: constant:…, cookie:…, session:…, operation, variables, computed, pending.
public override string ToString() => Kind switch
{
@@ -153,11 +165,125 @@ public static class RequestRoles
role is RequestRole.PostsNext or RequestRole.TaggedNext or RequestRole.ReelsNext or RequestRole.HighlightNext or RequestRole.FollowingNext;
}
+/// Where the page keeps one value of the session: a module of its require and a property of it.
+/// The module name (an identifier: letters, digits, «_», «$»).
+/// The property of the module that holds the value (an identifier).
+public sealed record PageValueSource(string Module, string Property)
+{
+ /// The form of the file: Module.property.
+ public override string ToString() => $"{Module}.{Property}";
+}
+
+///
+/// The page section of richieste.<sito>.json (issue #36, S4, §6.0): where the page of the site keeps
+/// the values «Ho finito» copies into the saved session. The copy reads only these modules and properties, through one
+/// read-only evaluation generated from them; so every name is an identifier, checked at load, and an edited file
+/// cannot put code in it.
+///
+///
+/// docIdModule names the module of each GraphQL operation's doc_id, with {operation} for the name
+/// of the operation (on Instagram {operation}_instagramRelayOperation, whose export is the doc_id). Each entry
+/// of values names a session field of and its
+/// Module.property. A configured operation that sends a session: value with no source here is refused at
+/// load (rule 9: a value whose place in the page is not known is not guessed).
+///
+public sealed partial class PageSources
+{
+ /// The placeholder of .
+ public const string OperationPlaceholder = "{operation}";
+
+ internal PageSources(string? docIdModule, IReadOnlyDictionary values, IReadOnlyList order)
+ {
+ DocIdModule = docIdModule;
+ Values = values;
+ Order = order;
+ }
+
+ /// The module name of a doc_id, with ; null when the page gives none.
+ public string? DocIdModule { get; }
+
+ /// Where each page value of the session is, by session field.
+ public IReadOnlyDictionary Values { get; }
+
+ /// The fields of in the order of the file.
+ public IReadOnlyList Order { get; }
+
+ /// The module that holds the doc_id of , or null when there is none or the result is not an identifier.
+ public string? DocIdModuleFor(string operation)
+ {
+ ArgumentNullException.ThrowIfNull(operation);
+ if (DocIdModule is null)
+ {
+ return null;
+ }
+
+ var module = DocIdModule.Replace(OperationPlaceholder, operation, StringComparison.Ordinal);
+ return IsIdentifier(module) ? module : null;
+ }
+
+ /// True for a name the copy may write in its expression: ^[A-Za-z_$][A-Za-z0-9_$]*$, at most 128 characters.
+ public static bool IsIdentifier(string? name) => name is not null && Identifier().IsMatch(name);
+
+ /// Names and counts only.
+ public override string ToString() => string.Create(
+ CultureInfo.InvariantCulture,
+ $"Sezione page: {Values.Count} valori{(DocIdModule is null ? string.Empty : ", doc_id da " + DocIdModule)}.");
+
+ /// Reads the section; every name checked.
+ internal static PageSources? Parse(PageDto? dto, string where)
+ {
+ if (dto is null)
+ {
+ return null;
+ }
+
+ where = $"{where}, sezione «page»";
+ string? docIdModule = null;
+ if (dto.DocIdModule is not null)
+ {
+ docIdModule = dto.DocIdModule.Trim();
+ var at = docIdModule.IndexOf(OperationPlaceholder, StringComparison.Ordinal);
+ if (at < 0 || docIdModule.IndexOf(OperationPlaceholder, at + 1, StringComparison.Ordinal) >= 0
+ || !IsIdentifier(docIdModule.Replace(OperationPlaceholder, "x", StringComparison.Ordinal)))
+ {
+ throw new InvalidDataException($"{where}: «docIdModule» è un nome di modulo con «{OperationPlaceholder}» una volta sola e altrimenti solo lettere, cifre, «_» e «$».");
+ }
+ }
+
+ var values = new Dictionary(StringComparer.Ordinal);
+ var order = new List();
+ foreach (var (field, text) in dto.Values ?? new Dictionary())
+ {
+ if (!SiteSessionValues.PageFields.Contains(field))
+ {
+ throw new InvalidDataException(
+ $"{where}: «{field}» non è un valore della pagina (ammessi: {string.Join(", ", SiteSessionValues.PageFields.Order(StringComparer.Ordinal))}; user_agent, claim e doc_id non stanno qui).");
+ }
+
+ var dot = text?.IndexOf('.', StringComparison.Ordinal) ?? -1;
+ var module = dot > 0 ? text![..dot] : null;
+ var property = dot > 0 ? text![(dot + 1)..] : null;
+ if (!IsIdentifier(module) || !IsIdentifier(property))
+ {
+ throw new InvalidDataException($"{where}: il valore «{field}» si scrive «Modulo.proprietà», con nomi fatti solo di lettere, cifre, «_» e «$».");
+ }
+
+ values[field] = new PageValueSource(module!, property!);
+ order.Add(field);
+ }
+
+ return new PageSources(docIdModule, values.ToFrozenDictionary(StringComparer.Ordinal), order);
+ }
+
+ [GeneratedRegex(@"^[A-Za-z_$][A-Za-z0-9_$]{0,127}$", RegexOptions.CultureInvariant)]
+ private static partial Regex Identifier();
+}
+
///
/// One operation of richieste.<sito>.json: what the site client may ask (issue #36, spec §6.0). Written from
/// the real request shapes of febe-sonda richieste (§14.5) and documented by a cleaned sample of its answer
/// (rule 9). It holds no value of a session: the doc_id of a GraphQL query, the tokens and the account are read
-/// from the page at login (tappa S4) and named here only by their source.
+/// from the page at login (tappa S4, the page section) and named here only by their source.
///
public sealed partial class SiteOperation
{
@@ -433,9 +559,10 @@ public sealed partial class RequestCatalog
private readonly FrozenDictionary _byName;
private readonly FrozenDictionary _byRole;
- private RequestCatalog(string site, IReadOnlyList operations, string? source)
+ private RequestCatalog(string site, IReadOnlyList operations, PageSources? page, string? source)
{
Site = site;
+ Page = page;
Operations = operations;
Source = source ?? $"richieste.{site}.json";
_byName = operations.ToFrozenDictionary(o => o.Name, StringComparer.Ordinal);
@@ -448,6 +575,9 @@ public sealed partial class RequestCatalog
/// Every operation, in the order of the file.
public IReadOnlyList Operations { get; }
+ /// Where the page keeps the session values «Ho finito» copies (the page section); null when the file has none.
+ public PageSources? Page { get; }
+
/// Where it came from (file path or embedded name), for messages.
public string Source { get; }
@@ -506,13 +636,14 @@ public sealed partial class RequestCatalog
throw new InvalidDataException($"{name}: manca l'elenco «operations».");
}
+ var page = PageSources.Parse(file.Page, name);
var operations = new List(file.Operations.Count);
var names = new HashSet(StringComparer.Ordinal);
var roleHolders = new Dictionary();
for (var i = 0; i < file.Operations.Count; i++)
{
var dto = file.Operations[i] ?? throw new InvalidDataException($"{name}, operazione {(i + 1).ToString(CultureInfo.InvariantCulture)}: voce vuota.");
- var operation = ToOperation(dto, $"{name}, operazione {(i + 1).ToString(CultureInfo.InvariantCulture)}");
+ var operation = ToOperation(dto, $"{name}, operazione {(i + 1).ToString(CultureInfo.InvariantCulture)}", page);
if (!names.Add(operation.Name))
{
throw new InvalidDataException($"{name}: l'operazione «{operation.Name}» compare due volte.");
@@ -529,7 +660,7 @@ public sealed partial class RequestCatalog
operations.Add(operation);
}
- return new RequestCatalog(file.Site.Trim(), operations, source);
+ return new RequestCatalog(file.Site.Trim(), operations, page, source);
}
/// Why the code refuses an operation with this name, whatever the file says; null when it does not.
@@ -606,7 +737,7 @@ public sealed partial class RequestCatalog
return null;
}
- private static SiteOperation ToOperation(OperationDto dto, string where)
+ private static SiteOperation ToOperation(OperationDto dto, string where, PageSources? page)
{
if (string.IsNullOrWhiteSpace(dto.Name))
{
@@ -806,6 +937,19 @@ public sealed partial class RequestCatalog
{
throw new InvalidDataException($"{where}: un'operazione configurata dice il campione della risposta («sample») e i campi attesi («rootFields»).");
}
+
+ // A value of the session the copy at «Ho finito» does not know where to read would be missing, or guessed
+ // (rule 9): the page section names a module for every one, a doc_id module for a GraphQL query.
+ foreach (var field in headers.Values.Concat(body.Values).Where(v => v.Kind == ValueSourceKind.Session).Select(v => v.Argument!).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal))
+ {
+ var known = field == "doc_id"
+ ? page?.DocIdModuleFor(name) is not null
+ : ValueSource.FieldsWithoutPage.Contains(field) || page?.Values.ContainsKey(field) == true;
+ if (!known)
+ {
+ throw new InvalidDataException($"{where}: il valore session:{field} non ha un modulo nella sezione «page»: non può essere configurata finché non si sa dove la pagina lo tiene (regola 9).");
+ }
+ }
}
else if (reason is null)
{
@@ -1030,9 +1174,20 @@ internal sealed class CatalogFile
public string? Note { get; set; }
+ public PageDto? Page { get; set; }
+
public List? Operations { get; set; }
}
+internal sealed class PageDto
+{
+ public string? DocIdModule { get; set; }
+
+ public Dictionary? Values { get; set; }
+
+ public string? Note { get; set; }
+}
+
internal sealed class OperationDto
{
public string? Name { get; set; }
diff --git a/src/Febe.Core/Collection/Requests/SavedSessionFile.cs b/src/Febe.Core/Collection/Requests/SavedSessionFile.cs
new file mode 100644
index 0000000..1354fc8
--- /dev/null
+++ b/src/Febe.Core/Collection/Requests/SavedSessionFile.cs
@@ -0,0 +1,124 @@
+using System.Security.Cryptography;
+using System.Text.Json;
+
+namespace Febe.Core.Collection.Requests;
+
+///
+/// The plain form of the saved session before it is encrypted (issue #36, S4, §13.2): UTF-8 JSON with English keys,
+/// {"format":1,"copiedAt":…,"userAgent":…,"cookies":[{name,value,domain,hostOnly,path,secure,httpOnly,expires}],"fields":{…},"docIds":{…}}.
+/// The capture id is not kept: values read back count as a new capture, so a late answer of the process before can
+/// never touch them.
+///
+internal static class SavedSessionFile
+{
+ /// The format version.
+ public const int Format = 1;
+
+ /// The JSON of ; the caller zeroes it once encrypted.
+ public static byte[] Serialize(SiteSessionValues values)
+ {
+ ArgumentNullException.ThrowIfNull(values);
+ using var buffer = new MemoryStream();
+ using (var writer = new Utf8JsonWriter(buffer))
+ {
+ writer.WriteStartObject();
+ writer.WriteNumber("format", Format);
+ if (values.CopiedAt is { } copiedAt)
+ {
+ writer.WriteString("copiedAt", copiedAt);
+ }
+
+ writer.WriteString("userAgent", values.UserAgent);
+ writer.WriteStartArray("cookies");
+ foreach (var cookie in values.Cookies)
+ {
+ writer.WriteStartObject();
+ writer.WriteString("name", cookie.Name);
+ writer.WriteString("value", cookie.Value);
+ writer.WriteString("domain", cookie.Domain);
+ writer.WriteBoolean("hostOnly", cookie.HostOnly);
+ writer.WriteString("path", cookie.Path);
+ writer.WriteBoolean("secure", cookie.Secure);
+ writer.WriteBoolean("httpOnly", cookie.HttpOnly);
+ if (cookie.Expires is { } expires)
+ {
+ writer.WriteString("expires", expires);
+ }
+
+ writer.WriteEndObject();
+ }
+
+ writer.WriteEndArray();
+ WriteMap(writer, "fields", values.Fields);
+ WriteMap(writer, "docIds", values.DocIds);
+ writer.WriteEndObject();
+ }
+
+ var bytes = buffer.ToArray();
+ CryptographicOperations.ZeroMemory(buffer.GetBuffer());
+ return bytes;
+ }
+
+ /// The values of , as a new capture.
+ /// Not the format of Febe, or a cookie or field it would refuse; the message names no value.
+ public static SiteSessionValues Deserialize(ReadOnlySpan json)
+ {
+ try
+ {
+ using var document = JsonDocument.Parse(json.ToArray(), new JsonDocumentOptions { MaxDepth = 8 });
+ var root = document.RootElement;
+ if (root.ValueKind != JsonValueKind.Object || !root.TryGetProperty("format", out var format) || format.GetInt32() != Format)
+ {
+ throw new InvalidDataException("Sessione salvata in un formato che Febe non conosce.");
+ }
+
+ var cookies = new List();
+ foreach (var item in root.GetProperty("cookies").EnumerateArray())
+ {
+ cookies.Add(new SiteCookie(
+ item.GetProperty("name").GetString()!,
+ item.GetProperty("value").GetString()!,
+ item.GetProperty("domain").GetString()!,
+ item.GetProperty("path").GetString()!,
+ item.GetProperty("hostOnly").GetBoolean(),
+ item.GetProperty("secure").GetBoolean(),
+ item.GetProperty("httpOnly").GetBoolean(),
+ item.TryGetProperty("expires", out var expires) ? expires.GetDateTimeOffset() : null));
+ }
+
+ return new SiteSessionValues(
+ cookies,
+ root.GetProperty("userAgent").GetString()!,
+ ReadMap(root.GetProperty("fields")),
+ ReadMap(root.GetProperty("docIds")),
+ root.TryGetProperty("copiedAt", out var copiedAt) ? copiedAt.GetDateTimeOffset() : null);
+ }
+ catch (Exception ex) when (ex is JsonException or KeyNotFoundException or InvalidOperationException or FormatException or ArgumentException)
+ {
+ // The texts of these exceptions may quote the file: none is passed on.
+ throw new InvalidDataException("Sessione salvata non leggibile: il contenuto non è quello che Febe scrive.");
+ }
+ }
+
+ private static void WriteMap(Utf8JsonWriter writer, string name, IReadOnlyDictionary map)
+ {
+ writer.WriteStartObject(name);
+ foreach (var (key, value) in map.OrderBy(p => p.Key, StringComparer.Ordinal))
+ {
+ writer.WriteString(key, value);
+ }
+
+ writer.WriteEndObject();
+ }
+
+ private static Dictionary ReadMap(JsonElement element)
+ {
+ var map = new Dictionary(StringComparer.Ordinal);
+ foreach (var property in element.EnumerateObject())
+ {
+ map[property.Name] = property.Value.GetString() ?? throw new InvalidDataException("Valore vuoto.");
+ }
+
+ return map;
+ }
+}
diff --git a/src/Febe.Core/Collection/Requests/SiteCookie.cs b/src/Febe.Core/Collection/Requests/SiteCookie.cs
new file mode 100644
index 0000000..d1871c9
--- /dev/null
+++ b/src/Febe.Core/Collection/Requests/SiteCookie.cs
@@ -0,0 +1,346 @@
+using System.Globalization;
+using System.Net;
+
+namespace Febe.Core.Collection.Requests;
+
+///
+/// One cookie of the saved session as the browser keeps it (issue #36, S4, RFC 6265 §5.3): name, value, domain and
+/// path, whether it is host-only, secure or HTTP-only, and when it expires. The site client sends it only to an address
+/// whose host and path match and, when it is secure, only over https ().
+///
+///
+/// A class, not a record: its text () names the cookie, its domain and path, never the value
+/// (rule 10). Its identity is name, domain, path and host-only (), as Chromium keeps it: a host-only
+/// cookie of www.instagram.com and a cookie with Domain=www.instagram.com are two cookies.
+///
+public sealed class SiteCookie
+{
+ /// A plain cookie name ().
+ /// The value as the browser keeps it, quotes included ().
+ /// The host (host-only) or the domain it is sent to; stored lower-case without the leading dot.
+ /// The path it is sent under; starts with «/».
+ /// True when it goes only to the host , not to its subdomains.
+ /// True when it goes only over https.
+ /// True when the page cannot read it (kept for the record; the client sends it the same).
+ /// When it expires; null: it lasts as long as the session.
+ /// A name, value, domain or path a browser would not keep; the message names no value.
+ public SiteCookie(string name, string value, string domain, string path = "/", bool hostOnly = true, bool secure = false, bool httpOnly = false, DateTimeOffset? expires = null)
+ {
+ if (!SiteCookies.IsPlainName(name))
+ {
+ throw new ArgumentException("Un nome di cookie della sessione non è un nome semplice.", nameof(name));
+ }
+
+ ArgumentNullException.ThrowIfNull(value);
+ if (!SiteCookies.IsSendableValue(value))
+ {
+ throw new ArgumentException($"Il valore del cookie «{name}» ha caratteri che un browser non manda.", nameof(value));
+ }
+
+ var normalized = SiteCookies.NormalizeDomain(domain)
+ ?? throw new ArgumentException($"Il dominio del cookie «{name}» non è un nome di host.", nameof(domain));
+ if (!SiteCookies.IsCookiePath(path))
+ {
+ throw new ArgumentException($"Il percorso del cookie «{name}» non comincia con «/» o ha caratteri non ammessi.", nameof(path));
+ }
+
+ Name = name;
+ Value = value;
+ Domain = normalized;
+ Path = path;
+ HostOnly = hostOnly;
+ Secure = secure;
+ HttpOnly = httpOnly;
+ Expires = expires;
+ }
+
+ /// The name.
+ public string Name { get; }
+
+ /// The value, as the browser keeps it (never logged).
+ public string Value { get; }
+
+ /// The host (host-only) or the domain, lower-case, without the leading dot.
+ public string Domain { get; }
+
+ /// The path, starting with «/».
+ public string Path { get; }
+
+ /// True when it goes only to the host .
+ public bool HostOnly { get; }
+
+ /// True when it goes only over https.
+ public bool Secure { get; }
+
+ /// True when the page cannot read it.
+ public bool HttpOnly { get; }
+
+ /// When it expires; null: with the session.
+ public DateTimeOffset? Expires { get; }
+
+ /// Its identity in the store: a cookie with the same key replaces it.
+ public SiteCookieKey Key => new(Name, Domain, Path, HostOnly);
+
+ /// A host-only cookie for (tests and the test site).
+ public static SiteCookie ForHost(string name, string value, string host, string path = "/", bool secure = false, DateTimeOffset? expires = null) =>
+ new(name, value, host, path, hostOnly: true, secure: secure, expires: expires);
+
+ /// True when it has expired at .
+ public bool IsExpired(DateTimeOffset now) => Expires is { } until && until <= now;
+
+ ///
+ /// True when a browser would send it with a request to at : the
+ /// host domain-matches (host-only: the same host), the path path-matches (RFC 6265 §5.1.3, §5.1.4), a secure
+ /// cookie only over https, not expired and not empty.
+ ///
+ public bool Matches(Uri address, DateTimeOffset now)
+ {
+ ArgumentNullException.ThrowIfNull(address);
+ if (!address.IsAbsoluteUri || Value.Length == 0 || IsExpired(now))
+ {
+ return false;
+ }
+
+ if (Secure && address.Scheme != Uri.UriSchemeHttps)
+ {
+ return false;
+ }
+
+ return SiteCookies.DomainMatches(SiteCookies.HostOf(address), Domain, HostOnly)
+ && SiteCookies.PathMatches(address.AbsolutePath, Path);
+ }
+
+ /// The same cookie with another value and expiry (a renewal keeps everything else).
+ internal SiteCookie WithValue(string value, DateTimeOffset? expires) =>
+ new(Name, value, Domain, Path, HostOnly, Secure, HttpOnly, expires);
+
+ /// Name, domain and path: never the value.
+ public override string ToString() => string.Create(
+ CultureInfo.InvariantCulture,
+ $"Cookie «{Name}» ({(HostOnly ? string.Empty : ".")}{Domain}{Path}{(Secure ? ", sicuro" : string.Empty)})");
+}
+
+/// The identity of a cookie in the store (RFC 6265 §5.3 step 11, plus host-only as Chromium keeps it). Holds no value.
+/// The name.
+/// The domain, lower-case, without the leading dot.
+/// The path.
+/// True for a host-only cookie.
+public readonly record struct SiteCookieKey(string Name, string Domain, string Path, bool HostOnly);
+
+///
+/// One Set-Cookie line read as a browser reads it: the cookie it sets (domain and path resolved against the
+/// request), or the key of the cookie it deletes. Its text shows the name only.
+///
+public sealed class SetCookieLine
+{
+ internal SetCookieLine(SiteCookie cookie, bool deletes)
+ {
+ Cookie = cookie;
+ Deletes = deletes;
+ }
+
+ /// The cookie as the line sets it (for a deletion only its counts; no expiry).
+ public SiteCookie Cookie { get; }
+
+ /// True when the line deletes the cookie (empty value, Max-Age of zero or less, an Expires not later than now).
+ public bool Deletes { get; }
+
+ /// Name and what the line does, never the value.
+ public override string ToString() => $"Set-Cookie «{Cookie.Name}»{(Deletes ? " (cancella)" : string.Empty)}";
+}
+
+/// Cookie names and the Set-Cookie lines of the site, read the way a browser reads them (RFC 6265).
+public static class SiteCookies
+{
+ /// True for a plain cookie name: no separator, space, quote or control character.
+ public static bool IsPlainName(string? name) =>
+ !string.IsNullOrEmpty(name) && name.Length <= 256
+ && !name.Any(c => c is '=' or ';' or ',' or '"' or '\\' || char.IsWhiteSpace(c) || char.IsControl(c) || c > '\x7e');
+
+ ///
+ /// True for a value a browser sends back as it is: ASCII, no control character and no «;» (the separator of the
+ /// Cookie line). Quotes and backslashes stay part of the value (RFC 6265 §5.2).
+ ///
+ public static bool IsSendableValue(string? value) =>
+ value is not null && value.Length <= 4096 && !value.Any(c => c is ';' || c < ' ' || c > '\x7e');
+
+ /// The domain as the store keeps it (lower-case, no leading dot), or null when it is not a host name or address.
+ public static string? NormalizeDomain(string? domain)
+ {
+ if (string.IsNullOrWhiteSpace(domain))
+ {
+ return null;
+ }
+
+ var trimmed = domain.Trim().TrimStart('.').ToLowerInvariant();
+ if (trimmed.StartsWith('[') && trimmed.EndsWith(']'))
+ {
+ trimmed = trimmed[1..^1];
+ }
+
+ return trimmed.Length is > 0 and <= 253 && trimmed.All(c => char.IsAsciiLetterOrDigit(c) || c is '.' or '-' or '_' or ':')
+ ? trimmed
+ : null;
+ }
+
+ /// True for a cookie path: starts with «/», no control character and no «;».
+ public static bool IsCookiePath(string? path) =>
+ !string.IsNullOrEmpty(path) && path[0] == '/' && path.Length <= 1024 && !path.Any(c => c is ';' || c < ' ' || c == '\x7f');
+
+ /// The host of as cookies compare it: lower-case, IPv6 without brackets.
+ public static string HostOf(Uri address)
+ {
+ ArgumentNullException.ThrowIfNull(address);
+ return address.IdnHost.Trim('[', ']').ToLowerInvariant();
+ }
+
+ ///
+ /// RFC 6265 §5.1.3: a host-only cookie goes to its host only; a domain cookie to the domain and its subdomains, never
+ /// by suffix to an IP address.
+ ///
+ public static bool DomainMatches(string host, string domain, bool hostOnly)
+ {
+ ArgumentNullException.ThrowIfNull(host);
+ ArgumentNullException.ThrowIfNull(domain);
+ if (host.Equals(domain, StringComparison.OrdinalIgnoreCase))
+ {
+ return true;
+ }
+
+ return !hostOnly
+ && !IPAddress.TryParse(host, out _)
+ && host.EndsWith("." + domain, StringComparison.OrdinalIgnoreCase);
+ }
+
+ /// RFC 6265 §5.1.4: the request path is the cookie path, or starts with it at a «/».
+ public static bool PathMatches(string requestPath, string cookiePath)
+ {
+ ArgumentNullException.ThrowIfNull(requestPath);
+ ArgumentNullException.ThrowIfNull(cookiePath);
+ var path = requestPath.Length == 0 ? "/" : requestPath;
+ if (path == cookiePath)
+ {
+ return true;
+ }
+
+ return path.StartsWith(cookiePath, StringComparison.Ordinal)
+ && (cookiePath.EndsWith('/') || path[cookiePath.Length] == '/');
+ }
+
+ /// RFC 6265 §5.1.4: the path a cookie without a Path takes from the request (up to the last «/», excluded).
+ public static string DefaultPath(Uri address)
+ {
+ ArgumentNullException.ThrowIfNull(address);
+ var path = address.AbsolutePath;
+ if (path.Length == 0 || path[0] != '/')
+ {
+ return "/";
+ }
+
+ var last = path.LastIndexOf('/');
+ return last <= 0 ? "/" : path[..last];
+ }
+
+ ///
+ /// One Set-Cookie line of an answer to : name, value as the browser keeps it
+ /// (RFC 6265 §5.2: double quotes are part of the value), domain (the Domain attribute, or host-only on the
+ /// request host), path (the Path attribute when it starts with «/», otherwise the default path of the request),
+ /// Secure, HttpOnly, and when it expires; whether it deletes the cookie (an empty value or "", a
+ /// Max-Age of zero or less, an Expires not after ). Null for a line that is not a
+ /// cookie, one for a domain the request host does not domain-match (a browser would refuse it), or a value a
+ /// browser would not send back.
+ ///
+ public static SetCookieLine? Parse(string line, Uri request, DateTimeOffset now)
+ {
+ ArgumentNullException.ThrowIfNull(line);
+ ArgumentNullException.ThrowIfNull(request);
+ var host = HostOf(request);
+ var parts = line.Split(';');
+ var pair = parts[0];
+ var equals = pair.IndexOf('=', StringComparison.Ordinal);
+ if (equals <= 0)
+ {
+ return null;
+ }
+
+ var name = pair[..equals].Trim();
+ var value = pair[(equals + 1)..].Trim();
+ if (!IsPlainName(name) || !IsSendableValue(value))
+ {
+ return null;
+ }
+
+ var empty = value.Length == 0 || value == "\"\"";
+ DateTimeOffset? byAge = null;
+ DateTimeOffset? byDate = null;
+ string? domain = null;
+ string? path = null;
+ var secure = false;
+ var httpOnly = false;
+ foreach (var attribute in parts.Skip(1))
+ {
+ var cut = attribute.IndexOf('=', StringComparison.Ordinal);
+ var key = (cut < 0 ? attribute : attribute[..cut]).Trim();
+ var argument = cut < 0 ? string.Empty : attribute[(cut + 1)..].Trim();
+ if (key.Equals("max-age", StringComparison.OrdinalIgnoreCase)
+ && long.TryParse(argument, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var seconds))
+ {
+ // The last Max-Age counts (RFC 6265 §5.3: attributes are read in order).
+ byAge = seconds <= 0 ? DateTimeOffset.MinValue
+ : seconds >= (DateTimeOffset.MaxValue - now).TotalSeconds ? DateTimeOffset.MaxValue
+ : now.AddSeconds(seconds);
+ }
+ else if (key.Equals("expires", StringComparison.OrdinalIgnoreCase)
+ && DateTimeOffset.TryParse(argument, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AllowWhiteSpaces, out var expires))
+ {
+ byDate = expires;
+ }
+ else if (key.Equals("domain", StringComparison.OrdinalIgnoreCase))
+ {
+ // RFC 6265 §5.2.3: an empty Domain is ignored; the last one counts.
+ if (argument.Length > 0)
+ {
+ domain = NormalizeDomain(argument) ?? string.Empty;
+ }
+ }
+ else if (key.Equals("path", StringComparison.OrdinalIgnoreCase))
+ {
+ // §5.2.4: a Path that does not start with «/» is the default path.
+ path = argument.StartsWith('/') ? argument : null;
+ }
+ else if (key.Equals("secure", StringComparison.OrdinalIgnoreCase))
+ {
+ secure = true;
+ }
+ else if (key.Equals("httponly", StringComparison.OrdinalIgnoreCase))
+ {
+ httpOnly = true;
+ }
+ }
+
+ var hostOnly = domain is null;
+ if (domain is not null)
+ {
+ // A Domain the host does not domain-match, or an IP address set as a wider domain, a browser refuses; a
+ // single label other than the host (Domain=com) is a public suffix and refused too.
+ if (domain.Length == 0
+ || !DomainMatches(host, domain, hostOnly: false)
+ || (!domain.Contains('.', StringComparison.Ordinal) && domain != host))
+ {
+ return null;
+ }
+ }
+
+ path ??= DefaultPath(request);
+ if (!IsCookiePath(path))
+ {
+ return null;
+ }
+
+ // Max-Age wins over Expires (RFC 6265 §5.3 step 3).
+ var until = byAge ?? byDate;
+ var deletes = empty || until <= now;
+ var cookie = new SiteCookie(name, value, domain ?? host, path, hostOnly, secure, httpOnly, deletes ? null : until);
+ return new SetCookieLine(cookie, deletes);
+ }
+}
diff --git a/src/Febe.Core/Config/richieste.instagram.json b/src/Febe.Core/Config/richieste.instagram.json
index caa119e..5c9ebd1 100644
--- a/src/Febe.Core/Config/richieste.instagram.json
+++ b/src/Febe.Core/Config/richieste.instagram.json
@@ -1,6 +1,23 @@
{
"site": "instagram",
- "note": "Operazioni che il client del sito può chiedere a Instagram (issue #36, specifica §6.0). Scritte il 16 novembre 2026 dalle forme reali delle richieste ricavate con «febe-sonda richieste» dai file HAR del 12 novembre (con e senza scorrimento) e del 16 novembre, fuori dal repository e senza valori; le risposte sono documentate dai campioni ripuliti di tests/Febe.Tests/campioni/instagram (regola 9). Solo letture: il codice rifiuta ogni «Mutation», la telemetria, la navigazione della pagina e le famiglie di chat, messaggi, presenza e promozioni, anche se una copia modificata le elencasse. Nessun doc_id qui: si legge dai moduli della pagina all'accesso (tappa S4). Fonti dei valori: constant (dalle forme), cookie:csrftoken, session:… (copiato a «Ho finito»: user_agent, lsd, fb_dtsg, app_id, claim, account_id, doc_id), operation, variables, computed, pending (nome noto, fonte ancora da stabilire: tappa S4). Le forme scrivono i vero/falso del JSON come true/false, ma non distinguono un numero da un testo di cifre: i numeri delle variabili (count 12, first 3) sono scritti come numeri, da confermare. «(nome tolto)» e «(valore tolto)» sono ciò che la sonda non mostra: un'operazione che li ha nelle variabili resta non configurata. L'elenco dei seguiti manca: nessuna forma con la risposta.",
+ "note": "Operazioni che il client del sito può chiedere a Instagram (issue #36, specifica §6.0). Scritte il 16 novembre 2026 dalle forme reali delle richieste ricavate con «febe-sonda richieste» dai file HAR del 12 novembre (con e senza scorrimento) e del 16 novembre, fuori dal repository e senza valori; le risposte sono documentate dai campioni ripuliti di tests/Febe.Tests/campioni/instagram (regola 9). Solo letture: il codice rifiuta ogni «Mutation», la telemetria, la navigazione della pagina e le famiglie di chat, messaggi, presenza e promozioni, anche se una copia modificata le elencasse. Nessun doc_id né altro valore qui: la sezione «page» dice in quale modulo della pagina si trova ciascuno, e «Ho finito» li copia nella sessione salvata (tappa S4). I posti della sezione «page» vengono dal codice pubblico della pagina del HAR, solo forme e nomi: __rev da SiteData.client_revision, __hs da SiteData.haste_session, __hsi da SiteData.hsi, dpr da SiteData.pr, __comet_req da SiteData.comet_env, __ccg da WebConnectionClassServerGuess.connectionClass, x-fb-entry-nonce da BootloaderConfig.nonce, i doc_id dal modulo «_instagramRelayOperation»; dpr e __comet_req erano costanti (1 e 7) e ora si leggono dalla pagina. Fonti dei valori: constant (dalle forme), cookie:csrftoken, session:… (copiato a «Ho finito»: user_agent, claim, doc_id e i valori della sezione «page»: lsd, fb_dtsg, app_id, account_id, rev, hs, hsi, dpr, ccg, comet_req, entry_nonce), operation, variables, computed, pending (nome noto, fonte da stabilire: valori che la pagina calcola mentre gira come __req, __s, __dyn, __csr, __hblp, __hsdp, __sjsp, __crn, __d e __spin_r/__spin_b/__spin_t, le intestazioni del browser come referer, priority e sec-ch-ua, e i nomi tolti dalla sonda). Un'operazione configurata con un valore session:… senza posto nella sezione «page» è rifiutata. Le forme scrivono i vero/falso del JSON come true/false, ma non distinguono un numero da un testo di cifre: i numeri delle variabili (count 12, first 3) sono scritti come numeri, da confermare. «(nome tolto)» e «(valore tolto)» sono ciò che la sonda non mostra: un'operazione che li ha nelle variabili resta non configurata. L'elenco dei seguiti manca: nessuna forma con la risposta.",
+ "page": {
+ "note": "Dove la pagina tiene i valori della sessione: «Modulo.proprietà» del require della pagina; docIdModule con {operation} per il nome dell'operazione. Solo nomi, nessun valore.",
+ "docIdModule": "{operation}_instagramRelayOperation",
+ "values": {
+ "lsd": "LSD.token",
+ "fb_dtsg": "DTSGInitialData.token",
+ "account_id": "CurrentUserInitialData.USER_ID",
+ "app_id": "CurrentUserInitialData.APP_ID",
+ "rev": "SiteData.client_revision",
+ "hs": "SiteData.haste_session",
+ "hsi": "SiteData.hsi",
+ "dpr": "SiteData.pr",
+ "comet_req": "SiteData.comet_env",
+ "ccg": "WebConnectionClassServerGuess.connectionClass",
+ "entry_nonce": "BootloaderConfig.nonce"
+ }
+ },
"operations": [
{
"name": "PolarisSearchBoxRefetchableQuery",
@@ -26,7 +43,7 @@
"user-agent": "session:user_agent",
"x-asbd-id": "constant:359341",
"x-csrftoken": "cookie:csrftoken",
- "x-fb-entry-nonce": "pending",
+ "x-fb-entry-nonce": "session:entry_nonce",
"x-fb-friendly-name": "operation",
"x-fb-lsd": "session:lsd",
"x-ig-app-id": "session:app_id",
@@ -35,18 +52,18 @@
"body": {
"(nome tolto)": "pending",
"__a": "constant:1",
- "__ccg": "pending",
- "__comet_req": "constant:7",
+ "__ccg": "session:ccg",
+ "__comet_req": "session:comet_req",
"__crn": "pending",
"__csr": "pending",
"__d": "pending",
"__dyn": "pending",
"__hblp": "pending",
- "__hs": "pending",
+ "__hs": "session:hs",
"__hsdp": "pending",
- "__hsi": "pending",
+ "__hsi": "session:hsi",
"__req": "pending",
- "__rev": "pending",
+ "__rev": "session:rev",
"__s": "pending",
"__sjsp": "pending",
"__spin_b": "pending",
@@ -55,7 +72,7 @@
"__user": "session:account_id",
"av": "session:account_id",
"doc_id": "session:doc_id",
- "dpr": "constant:1",
+ "dpr": "session:dpr",
"fb_api_caller_class": "constant:RelayModern",
"fb_api_req_friendly_name": "operation",
"fb_dtsg": "session:fb_dtsg",
@@ -108,7 +125,7 @@
"user-agent": "session:user_agent",
"x-asbd-id": "constant:359341",
"x-csrftoken": "cookie:csrftoken",
- "x-fb-entry-nonce": "pending",
+ "x-fb-entry-nonce": "session:entry_nonce",
"x-fb-friendly-name": "operation",
"x-fb-lsd": "session:lsd",
"x-ig-app-id": "session:app_id",
@@ -117,18 +134,18 @@
"body": {
"(nome tolto)": "pending",
"__a": "constant:1",
- "__ccg": "pending",
- "__comet_req": "constant:7",
+ "__ccg": "session:ccg",
+ "__comet_req": "session:comet_req",
"__crn": "pending",
"__csr": "pending",
"__d": "pending",
"__dyn": "pending",
"__hblp": "pending",
- "__hs": "pending",
+ "__hs": "session:hs",
"__hsdp": "pending",
- "__hsi": "pending",
+ "__hsi": "session:hsi",
"__req": "pending",
- "__rev": "pending",
+ "__rev": "session:rev",
"__s": "pending",
"__sjsp": "pending",
"__spin_b": "pending",
@@ -137,7 +154,7 @@
"__user": "session:account_id",
"av": "session:account_id",
"doc_id": "session:doc_id",
- "dpr": "constant:1",
+ "dpr": "session:dpr",
"fb_api_caller_class": "constant:RelayModern",
"fb_api_req_friendly_name": "operation",
"fb_dtsg": "session:fb_dtsg",
@@ -186,7 +203,7 @@
"user-agent": "session:user_agent",
"x-asbd-id": "constant:359341",
"x-csrftoken": "cookie:csrftoken",
- "x-fb-entry-nonce": "pending",
+ "x-fb-entry-nonce": "session:entry_nonce",
"x-fb-friendly-name": "operation",
"x-fb-lsd": "session:lsd",
"x-ig-app-id": "session:app_id",
@@ -195,18 +212,18 @@
"body": {
"(nome tolto)": "pending",
"__a": "constant:1",
- "__ccg": "pending",
- "__comet_req": "constant:7",
+ "__ccg": "session:ccg",
+ "__comet_req": "session:comet_req",
"__crn": "pending",
"__csr": "pending",
"__d": "pending",
"__dyn": "pending",
"__hblp": "pending",
- "__hs": "pending",
+ "__hs": "session:hs",
"__hsdp": "pending",
- "__hsi": "pending",
+ "__hsi": "session:hsi",
"__req": "pending",
- "__rev": "pending",
+ "__rev": "session:rev",
"__s": "pending",
"__sjsp": "pending",
"__spin_b": "pending",
@@ -215,7 +232,7 @@
"__user": "session:account_id",
"av": "session:account_id",
"doc_id": "session:doc_id",
- "dpr": "constant:1",
+ "dpr": "session:dpr",
"fb_api_caller_class": "constant:RelayModern",
"fb_api_req_friendly_name": "operation",
"fb_dtsg": "session:fb_dtsg",
@@ -253,7 +270,7 @@
"category": "storico",
"roles": ["reels"],
"configured": false,
- "reason": "le variabili sono note, ma intestazioni e campi della pagina e del browser (come __dyn, __csr, referer, sec-ch-ua e quello con il nome tolto dalla sonda) hanno ancora la fonte «pending»: finché non si sa da dove vengono i valori la richiesta non si scrive (regola 9, tappa S4)",
+ "reason": "le variabili sono note, ma intestazioni e campi della pagina e del browser (come __dyn, __csr, referer, sec-ch-ua e quello con il nome tolto dalla sonda) hanno ancora la fonte «pending»: finché non si sa da dove vengono i valori la richiesta non si scrive (regola 9)",
"headers": {
"(nome tolto)": "pending",
"accept": "constant:*/*",
@@ -270,7 +287,7 @@
"user-agent": "session:user_agent",
"x-asbd-id": "constant:359341",
"x-csrftoken": "cookie:csrftoken",
- "x-fb-entry-nonce": "pending",
+ "x-fb-entry-nonce": "session:entry_nonce",
"x-fb-friendly-name": "operation",
"x-fb-lsd": "session:lsd",
"x-ig-app-id": "session:app_id",
@@ -279,18 +296,18 @@
"body": {
"(nome tolto)": "pending",
"__a": "constant:1",
- "__ccg": "pending",
- "__comet_req": "constant:7",
+ "__ccg": "session:ccg",
+ "__comet_req": "session:comet_req",
"__crn": "pending",
"__csr": "pending",
"__d": "pending",
"__dyn": "pending",
"__hblp": "pending",
- "__hs": "pending",
+ "__hs": "session:hs",
"__hsdp": "pending",
- "__hsi": "pending",
+ "__hsi": "session:hsi",
"__req": "pending",
- "__rev": "pending",
+ "__rev": "session:rev",
"__s": "pending",
"__sjsp": "pending",
"__spin_b": "pending",
@@ -299,7 +316,7 @@
"__user": "session:account_id",
"av": "session:account_id",
"doc_id": "session:doc_id",
- "dpr": "constant:1",
+ "dpr": "session:dpr",
"fb_api_caller_class": "constant:RelayModern",
"fb_api_req_friendly_name": "operation",
"fb_dtsg": "session:fb_dtsg",
@@ -332,7 +349,7 @@
"category": "storico",
"roles": ["tagged"],
"configured": false,
- "reason": "le variabili sono note, ma intestazioni e campi della pagina e del browser (come __dyn, __csr, referer, sec-ch-ua e quello con il nome tolto dalla sonda) hanno ancora la fonte «pending»: finché non si sa da dove vengono i valori la richiesta non si scrive (regola 9, tappa S4)",
+ "reason": "le variabili sono note, ma intestazioni e campi della pagina e del browser (come __dyn, __csr, referer, sec-ch-ua e quello con il nome tolto dalla sonda) hanno ancora la fonte «pending»: finché non si sa da dove vengono i valori la richiesta non si scrive (regola 9)",
"headers": {
"(nome tolto)": "pending",
"accept": "constant:*/*",
@@ -349,7 +366,7 @@
"user-agent": "session:user_agent",
"x-asbd-id": "constant:359341",
"x-csrftoken": "cookie:csrftoken",
- "x-fb-entry-nonce": "pending",
+ "x-fb-entry-nonce": "session:entry_nonce",
"x-fb-friendly-name": "operation",
"x-fb-lsd": "session:lsd",
"x-ig-app-id": "session:app_id",
@@ -358,18 +375,18 @@
"body": {
"(nome tolto)": "pending",
"__a": "constant:1",
- "__ccg": "pending",
- "__comet_req": "constant:7",
+ "__ccg": "session:ccg",
+ "__comet_req": "session:comet_req",
"__crn": "pending",
"__csr": "pending",
"__d": "pending",
"__dyn": "pending",
"__hblp": "pending",
- "__hs": "pending",
+ "__hs": "session:hs",
"__hsdp": "pending",
- "__hsi": "pending",
+ "__hsi": "session:hsi",
"__req": "pending",
- "__rev": "pending",
+ "__rev": "session:rev",
"__s": "pending",
"__sjsp": "pending",
"__spin_b": "pending",
@@ -378,7 +395,7 @@
"__user": "session:account_id",
"av": "session:account_id",
"doc_id": "session:doc_id",
- "dpr": "constant:1",
+ "dpr": "session:dpr",
"fb_api_caller_class": "constant:RelayModern",
"fb_api_req_friendly_name": "operation",
"fb_dtsg": "session:fb_dtsg",
@@ -408,7 +425,7 @@
"category": "profilo",
"roles": ["highlights"],
"configured": false,
- "reason": "le variabili sono note, ma intestazioni e campi della pagina e del browser (come __dyn, __csr, referer, sec-ch-ua e quello con il nome tolto dalla sonda) hanno ancora la fonte «pending»: finché non si sa da dove vengono i valori la richiesta non si scrive (regola 9, tappa S4)",
+ "reason": "le variabili sono note, ma intestazioni e campi della pagina e del browser (come __dyn, __csr, referer, sec-ch-ua e quello con il nome tolto dalla sonda) hanno ancora la fonte «pending»: finché non si sa da dove vengono i valori la richiesta non si scrive (regola 9)",
"headers": {
"(nome tolto)": "pending",
"accept": "constant:*/*",
@@ -425,7 +442,7 @@
"user-agent": "session:user_agent",
"x-asbd-id": "constant:359341",
"x-csrftoken": "cookie:csrftoken",
- "x-fb-entry-nonce": "pending",
+ "x-fb-entry-nonce": "session:entry_nonce",
"x-fb-friendly-name": "operation",
"x-fb-lsd": "session:lsd",
"x-ig-app-id": "session:app_id",
@@ -434,18 +451,18 @@
"body": {
"(nome tolto)": "pending",
"__a": "constant:1",
- "__ccg": "pending",
- "__comet_req": "constant:7",
+ "__ccg": "session:ccg",
+ "__comet_req": "session:comet_req",
"__crn": "pending",
"__csr": "pending",
"__d": "pending",
"__dyn": "pending",
"__hblp": "pending",
- "__hs": "pending",
+ "__hs": "session:hs",
"__hsdp": "pending",
- "__hsi": "pending",
+ "__hsi": "session:hsi",
"__req": "pending",
- "__rev": "pending",
+ "__rev": "session:rev",
"__s": "pending",
"__sjsp": "pending",
"__spin_b": "pending",
@@ -454,7 +471,7 @@
"__user": "session:account_id",
"av": "session:account_id",
"doc_id": "session:doc_id",
- "dpr": "constant:1",
+ "dpr": "session:dpr",
"fb_api_caller_class": "constant:RelayModern",
"fb_api_req_friendly_name": "operation",
"fb_dtsg": "session:fb_dtsg",
@@ -498,7 +515,7 @@
"user-agent": "session:user_agent",
"x-asbd-id": "constant:359341",
"x-csrftoken": "cookie:csrftoken",
- "x-fb-entry-nonce": "pending",
+ "x-fb-entry-nonce": "session:entry_nonce",
"x-fb-friendly-name": "operation",
"x-fb-lsd": "session:lsd",
"x-ig-app-id": "session:app_id",
@@ -507,18 +524,18 @@
"body": {
"(nome tolto)": "pending",
"__a": "constant:1",
- "__ccg": "pending",
- "__comet_req": "constant:7",
+ "__ccg": "session:ccg",
+ "__comet_req": "session:comet_req",
"__crn": "pending",
"__csr": "pending",
"__d": "pending",
"__dyn": "pending",
"__hblp": "pending",
- "__hs": "pending",
+ "__hs": "session:hs",
"__hsdp": "pending",
- "__hsi": "pending",
+ "__hsi": "session:hsi",
"__req": "pending",
- "__rev": "pending",
+ "__rev": "session:rev",
"__s": "pending",
"__sjsp": "pending",
"__spin_b": "pending",
@@ -527,7 +544,7 @@
"__user": "session:account_id",
"av": "session:account_id",
"doc_id": "session:doc_id",
- "dpr": "constant:1",
+ "dpr": "session:dpr",
"fb_api_analytics_tags": "pending",
"fb_api_caller_class": "constant:RelayModern",
"fb_api_req_friendly_name": "operation",
@@ -577,7 +594,7 @@
"x-asbd-id": "constant:359341",
"x-bloks-version-id": "constant:e9f7142825abe6e3e169776ae34e2fc4aeb2fa7ccdf139d43730b2f13505e200",
"x-csrftoken": "cookie:csrftoken",
- "x-fb-entry-nonce": "pending",
+ "x-fb-entry-nonce": "session:entry_nonce",
"x-fb-friendly-name": "operation",
"x-fb-lsd": "session:lsd",
"x-ig-app-id": "session:app_id",
@@ -587,18 +604,18 @@
"body": {
"(nome tolto)": "pending",
"__a": "constant:1",
- "__ccg": "pending",
- "__comet_req": "constant:7",
+ "__ccg": "session:ccg",
+ "__comet_req": "session:comet_req",
"__crn": "pending",
"__csr": "pending",
"__d": "pending",
"__dyn": "pending",
"__hblp": "pending",
- "__hs": "pending",
+ "__hs": "session:hs",
"__hsdp": "pending",
- "__hsi": "pending",
+ "__hsi": "session:hsi",
"__req": "pending",
- "__rev": "pending",
+ "__rev": "session:rev",
"__s": "pending",
"__sjsp": "pending",
"__spin_b": "pending",
@@ -607,7 +624,7 @@
"__user": "session:account_id",
"av": "session:account_id",
"doc_id": "session:doc_id",
- "dpr": "constant:1",
+ "dpr": "session:dpr",
"fb_api_caller_class": "constant:RelayModern",
"fb_api_req_friendly_name": "operation",
"fb_dtsg": "session:fb_dtsg",
@@ -658,7 +675,7 @@
"x-asbd-id": "constant:359341",
"x-bloks-version-id": "constant:e9f7142825abe6e3e169776ae34e2fc4aeb2fa7ccdf139d43730b2f13505e200",
"x-csrftoken": "cookie:csrftoken",
- "x-fb-entry-nonce": "pending",
+ "x-fb-entry-nonce": "session:entry_nonce",
"x-fb-friendly-name": "operation",
"x-fb-lsd": "session:lsd",
"x-ig-app-id": "session:app_id",
@@ -668,18 +685,18 @@
"body": {
"(nome tolto)": "pending",
"__a": "constant:1",
- "__ccg": "pending",
- "__comet_req": "constant:7",
+ "__ccg": "session:ccg",
+ "__comet_req": "session:comet_req",
"__crn": "pending",
"__csr": "pending",
"__d": "pending",
"__dyn": "pending",
"__hblp": "pending",
- "__hs": "pending",
+ "__hs": "session:hs",
"__hsdp": "pending",
- "__hsi": "pending",
+ "__hsi": "session:hsi",
"__req": "pending",
- "__rev": "pending",
+ "__rev": "session:rev",
"__s": "pending",
"__sjsp": "pending",
"__spin_b": "pending",
@@ -688,7 +705,7 @@
"__user": "session:account_id",
"av": "session:account_id",
"doc_id": "session:doc_id",
- "dpr": "constant:1",
+ "dpr": "session:dpr",
"fb_api_analytics_tags": "pending",
"fb_api_caller_class": "constant:RelayModern",
"fb_api_req_friendly_name": "operation",
@@ -726,7 +743,7 @@
"category": "post",
"roles": ["post"],
"configured": false,
- "reason": "il percorso è noto, ma intestazioni della pagina e del browser (come referer, sec-ch-ua e quella con il nome tolto dalla sonda) hanno ancora la fonte «pending»: finché non si sa da dove vengono i valori la richiesta non si scrive (regola 9, tappa S4)",
+ "reason": "il percorso è noto, ma intestazioni della pagina e del browser (come referer, sec-ch-ua e quella con il nome tolto dalla sonda) hanno ancora la fonte «pending»: finché non si sa da dove vengono i valori la richiesta non si scrive (regola 9)",
"headers": {
"(nome tolto)": "pending",
"accept": "constant:*/*",
diff --git a/src/Febe.Core/Config/richieste.prova.json b/src/Febe.Core/Config/richieste.prova.json
index 14c0f3f..40ba8df 100644
--- a/src/Febe.Core/Config/richieste.prova.json
+++ b/src/Febe.Core/Config/richieste.prova.json
@@ -1,6 +1,23 @@
{
"site": "prova",
- "note": "Operazioni che il client del sito chiede al sito di prova locale (tools/Febe.SitoDiProva, specifica §14.2) dalla tappa S2 di #36: le stesse risposte JSON che la pagina chiede a /dati/, servite sotto /api/ dove il sito controlla ciò che controlla un sito vero (cookie sessione_prova, x-csrftoken uguale al cookie csrftoken, x-app-id e le altre intestazioni e i campi del modello), documentate dai campioni ripuliti di tests/Febe.Tests/campioni/prova. Le pagine continuano a chiedere /dati/, che non controlla nulla. ProvaProfiloQuery è una richiesta GraphQL (POST /api/graphql con doc_id, nome dell'operazione e variabili) che risponde con il JSON di /dati/profilo/{nome}. Le regole di rifiuto sono le stesse di Instagram (nel codice). La scrittura /dati/ricerche-recenti (POST) non c'è e non può esserci: un indirizzo semplice si legge solo con GET.",
+ "note": "Operazioni che il client del sito chiede al sito di prova locale (tools/Febe.SitoDiProva, specifica §14.2) dalla tappa S2 di #36: le stesse risposte JSON che la pagina chiede a /dati/, servite sotto /api/ dove il sito controlla ciò che controlla un sito vero (cookie sessione_prova, x-csrftoken uguale al cookie csrftoken, x-app-id e le altre intestazioni e i campi del modello), documentate dai campioni ripuliti di tests/Febe.Tests/campioni/prova. Le pagine continuano a chiedere /dati/, che non controlla nulla. ProvaProfiloQuery è una richiesta GraphQL (POST /api/graphql con doc_id, nome dell'operazione e variabili) che risponde con il JSON di /dati/profilo/{nome}. Le regole di rifiuto sono le stesse di Instagram (nel codice). La scrittura /dati/ricerche-recenti (POST) non c'è e non può esserci: un indirizzo semplice si legge solo con GET. La sezione «page» dice dove le pagine del sito di prova tengono i valori della sessione, con nomi di moduli suoi, mai quelli di Instagram: GettoniProva (lsd, dtsg), UtenteProva (id, applicazione), VersioneProva (revisione, hs, hsi, dpr, comet), ConnessioneProva (classe), AvvioProva (nonce) e un modulo «_operazioneProva» per ogni doc_id (ProvaProfiloQuery_operazioneProva); i valori sono le costanti di TestSite (tools/Febe.SitoDiProva/DirectApi.cs).",
+ "page": {
+ "note": "Moduli del registro require/__d delle pagine del sito di prova (tools/Febe.SitoDiProva): stessi nomi qui e là.",
+ "docIdModule": "{operation}_operazioneProva",
+ "values": {
+ "lsd": "GettoniProva.lsd",
+ "fb_dtsg": "GettoniProva.dtsg",
+ "account_id": "UtenteProva.id",
+ "app_id": "UtenteProva.applicazione",
+ "rev": "VersioneProva.revisione",
+ "hs": "VersioneProva.hs",
+ "hsi": "VersioneProva.hsi",
+ "dpr": "VersioneProva.dpr",
+ "comet_req": "VersioneProva.comet",
+ "ccg": "ConnessioneProva.classe",
+ "entry_nonce": "AvvioProva.nonce"
+ }
+ },
"operations": [
{
"name": "inizio",
@@ -75,12 +92,19 @@
"user-agent": "session:user_agent",
"x-app-id": "session:app_id",
"x-csrftoken": "cookie:csrftoken",
+ "x-fb-entry-nonce": "session:entry_nonce",
"x-fb-friendly-name": "operation",
"x-ig-www-claim": "session:claim"
},
"body": {
"av": "session:account_id",
"__a": "constant:1",
+ "__ccg": "session:ccg",
+ "__comet_req": "session:comet_req",
+ "__hs": "session:hs",
+ "__hsi": "session:hsi",
+ "__rev": "session:rev",
+ "dpr": "session:dpr",
"fb_dtsg": "session:fb_dtsg",
"lsd": "session:lsd",
"fb_api_req_friendly_name": "operation",
@@ -97,7 +121,7 @@
"profilo"
],
"sample": "000002-profilo-pubblico",
- "note": "Una richiesta GraphQL del sito di prova: le stesse forme di Instagram (form con doc_id, fb_api_req_friendly_name e variables; x-csrftoken, x-fb-friendly-name, x-ig-www-claim), la risposta di /dati/profilo/{nome}. Il sito controlla doc_id, nome, gettoni e i tipi delle variabili (primi è il numero 12, raccolte un vero/falso)."
+ "note": "Una richiesta GraphQL del sito di prova: le stesse forme di Instagram (form con doc_id, fb_api_req_friendly_name e variables; x-csrftoken, x-fb-friendly-name, x-ig-www-claim), la risposta di /dati/profilo/{nome}. Il sito controlla doc_id, nome, gettoni e i tipi delle variabili (primi è il numero 12, raccolte un vero/falso). I campi di versione (__rev, __hs, __hsi, __ccg, dpr, __comet_req) e x-fb-entry-nonce vengono dalla sessione salvata, come su Instagram."
},
{
"name": "profilo-altri",
diff --git a/src/Febe.Core/Import/VideoMetadataProbe.cs b/src/Febe.Core/Import/VideoMetadataProbe.cs
index eef40f1..2a8bfce 100644
--- a/src/Febe.Core/Import/VideoMetadataProbe.cs
+++ b/src/Febe.Core/Import/VideoMetadataProbe.cs
@@ -1,6 +1,7 @@
using System.Diagnostics;
using System.Globalization;
using System.Text.Json;
+using Febe.Core.Security;
namespace Febe.Core.Import;
@@ -58,9 +59,12 @@ public sealed class FfprobeVideoMetadataProbe : IVideoMetadataProbe
return null;
}
- public async Task ProbeAsync(string path, CancellationToken ct = default)
+ ///
+ /// The start of ffprobe for : its arguments, and the environment of Febe without
+ /// FEBE_PASSWORD and FEBE_CHIAVE_SESSIONE, removed last (spec §13.2).
+ ///
+ internal ProcessStartInfo BuildStartInfo(string path)
{
- ArgumentException.ThrowIfNullOrWhiteSpace(path);
var start = new ProcessStartInfo(Executable)
{
RedirectStandardOutput = true,
@@ -78,7 +82,13 @@ public sealed class FfprobeVideoMetadataProbe : IVideoMetadataProbe
start.ArgumentList.Add(argument);
}
- using var process = new Process { StartInfo = start };
+ return start.WithoutSecrets();
+ }
+
+ public async Task ProbeAsync(string path, CancellationToken ct = default)
+ {
+ ArgumentException.ThrowIfNullOrWhiteSpace(path);
+ using var process = new Process { StartInfo = BuildStartInfo(path) };
try
{
if (!process.Start())
diff --git a/src/Febe.Core/Library/LibraryLayout.cs b/src/Febe.Core/Library/LibraryLayout.cs
index 5eb2e3d..7747791 100644
--- a/src/Febe.Core/Library/LibraryLayout.cs
+++ b/src/Febe.Core/Library/LibraryLayout.cs
@@ -133,4 +133,16 @@ public sealed record DataFolderLayout
/// Dati/segnali.json.
public string SignalsFile => Path.Combine(Root, "segnali.json");
+
+ ///
+ /// Dati/sessione: the saved session of the site client, encrypted, owner-only (issue #36, §13.2). Not in the
+ /// database, so never in the daily copies; never read by the diagnostic report.
+ ///
+ public string Session => Path.Combine(Root, "sessione");
+
+ /// Dati/sessione/sessione.json: the encrypted saved session.
+ public string SessionFile => Path.Combine(Session, "sessione.json");
+
+ /// Dati/sessione/chiave.bin: the AES key in Docker when FEBE_CHIAVE_SESSIONE is not set.
+ public string SessionKeyFile => Path.Combine(Session, "chiave.bin");
}
diff --git a/src/Febe.Core/Library/VideoFrameExtractor.cs b/src/Febe.Core/Library/VideoFrameExtractor.cs
index 8f78ee6..a4ed64f 100644
--- a/src/Febe.Core/Library/VideoFrameExtractor.cs
+++ b/src/Febe.Core/Library/VideoFrameExtractor.cs
@@ -1,4 +1,5 @@
using System.Diagnostics;
+using Febe.Core.Security;
namespace Febe.Core.Library;
@@ -63,7 +64,12 @@ public sealed class VideoFrameExtractor
return null;
}
- private async Task RunAsync(string videoPath, string seek, CancellationToken ct)
+ ///
+ /// The start of ffmpeg for one frame of at seconds: its
+ /// arguments, and the environment of Febe without FEBE_PASSWORD and FEBE_CHIAVE_SESSIONE, removed last
+ /// (spec §13.2).
+ ///
+ internal ProcessStartInfo BuildStartInfo(string videoPath, string seek)
{
var start = new ProcessStartInfo(Executable)
{
@@ -78,7 +84,12 @@ public sealed class VideoFrameExtractor
start.ArgumentList.Add(argument);
}
- using var process = new Process { StartInfo = start };
+ return start.WithoutSecrets();
+ }
+
+ private async Task RunAsync(string videoPath, string seek, CancellationToken ct)
+ {
+ using var process = new Process { StartInfo = BuildStartInfo(videoPath, seek) };
try
{
if (!process.Start())
diff --git a/src/Febe.Core/Security/AesGcmSessionProtector.cs b/src/Febe.Core/Security/AesGcmSessionProtector.cs
new file mode 100644
index 0000000..693e9c6
--- /dev/null
+++ b/src/Febe.Core/Security/AesGcmSessionProtector.cs
@@ -0,0 +1,73 @@
+using System.Security.Cryptography;
+
+namespace Febe.Core.Security;
+
+///
+/// AES-256-GCM for the saved session in Docker (issue #36, S4, spec §13.2), from the base library
+/// (System.Security.Cryptography, §3): header (6 bytes) | nonce (12, fresh for every write) | tag (16) |
+/// ciphertext; the header is the associated data, so a changed header is a damaged file.
+///
+public sealed class AesGcmSessionProtector : ISessionProtector
+{
+ private const int NonceLength = 12;
+ private const int TagLength = 16;
+
+ private readonly byte[] _key;
+
+ /// Exactly 32 bytes (); copied, never logged.
+ /// A key that is not 32 bytes (the message names the length only).
+ public AesGcmSessionProtector(ReadOnlySpan key)
+ {
+ if (key.Length != SessionKey.Length)
+ {
+ throw new ArgumentException($"La chiave della sessione salvata è di {SessionKey.Length} byte.", nameof(key));
+ }
+
+ _key = key.ToArray();
+ }
+
+ public string Scheme => "aes-gcm";
+
+ public byte[] Protect(ReadOnlySpan plain)
+ {
+ var header = SessionBlob.Header(SessionBlob.AesGcm);
+ var blob = new byte[SessionBlob.HeaderLength + NonceLength + TagLength + plain.Length];
+ header.CopyTo(blob, 0);
+ var nonce = blob.AsSpan(SessionBlob.HeaderLength, NonceLength);
+ RandomNumberGenerator.Fill(nonce);
+ var tag = blob.AsSpan(SessionBlob.HeaderLength + NonceLength, TagLength);
+ var cipher = blob.AsSpan(SessionBlob.HeaderLength + NonceLength + TagLength);
+ using var aes = new AesGcm(_key, TagLength);
+ aes.Encrypt(nonce, plain, cipher, tag, header);
+ return blob;
+ }
+
+ public byte[] Unprotect(ReadOnlySpan blob)
+ {
+ if (!SessionBlob.HasHeader(blob, SessionBlob.AesGcm) || blob.Length < SessionBlob.HeaderLength + NonceLength + TagLength)
+ {
+ throw new SessionUnreadableException();
+ }
+
+ var header = blob[..SessionBlob.HeaderLength];
+ var nonce = blob.Slice(SessionBlob.HeaderLength, NonceLength);
+ var tag = blob.Slice(SessionBlob.HeaderLength + NonceLength, TagLength);
+ var cipher = blob[(SessionBlob.HeaderLength + NonceLength + TagLength)..];
+ var plain = new byte[cipher.Length];
+ try
+ {
+ using var aes = new AesGcm(_key, TagLength);
+ aes.Decrypt(nonce, cipher, tag, plain, header);
+ return plain;
+ }
+ catch (CryptographicException)
+ {
+ // Another key or a changed byte: nothing of the inner text is passed on.
+ CryptographicOperations.ZeroMemory(plain);
+ throw new SessionUnreadableException();
+ }
+ }
+
+ /// The scheme only, never the key.
+ public override string ToString() => "Cifratura della sessione: AES-256-GCM.";
+}
diff --git a/src/Febe.Core/Security/ChildProcessEnvironment.cs b/src/Febe.Core/Security/ChildProcessEnvironment.cs
new file mode 100644
index 0000000..cb2b501
--- /dev/null
+++ b/src/Febe.Core/Security/ChildProcessEnvironment.cs
@@ -0,0 +1,42 @@
+using System.Diagnostics;
+
+namespace Febe.Core.Security;
+
+///
+/// What a process Febe starts (Chromium, Edge, Xvfb, ffmpeg, ffprobe, Explorer) must not inherit from Febe (issue #36,
+/// S4, rule 10): the interface password and the key of the saved session. A child process copies the environment of its
+/// parent; Chromium runs the site's code, so a secret in its environment is a secret one step from the site.
+///
+public static class ChildProcessEnvironment
+{
+ /// The interface password of Docker (spec §11).
+ public const string PasswordVariable = "FEBE_PASSWORD";
+
+ /// The variables taken out of every child process's environment.
+ public static IReadOnlyList SecretVariables { get; } = [PasswordVariable, SessionKey.EnvironmentVariable];
+
+ ///
+ /// Removes from 's environment. Call it last, after anything
+ /// else that sets variables. Only for UseShellExecute = false (with the shell, .NET passes no environment).
+ ///
+ public static ProcessStartInfo WithoutSecrets(this ProcessStartInfo info)
+ {
+ ArgumentNullException.ThrowIfNull(info);
+ RemoveSecrets(info.Environment);
+ return info;
+ }
+
+ /// Removes from (whatever the case of the name).
+ public static void RemoveSecrets(IDictionary environment)
+ {
+ ArgumentNullException.ThrowIfNull(environment);
+ foreach (var name in environment.Keys.Where(IsSecret).ToList())
+ {
+ environment.Remove(name);
+ }
+ }
+
+ /// True for a name of , in any case (Windows names ignore it).
+ public static bool IsSecret(string name) =>
+ SecretVariables.Any(secret => string.Equals(secret, name, StringComparison.OrdinalIgnoreCase));
+}
diff --git a/src/Febe.Core/Security/ISessionProtector.cs b/src/Febe.Core/Security/ISessionProtector.cs
new file mode 100644
index 0000000..20009d9
--- /dev/null
+++ b/src/Febe.Core/Security/ISessionProtector.cs
@@ -0,0 +1,70 @@
+namespace Febe.Core.Security;
+
+///
+/// Encrypts the saved session before it touches the disk (issue #36, S4, spec §13.2): DPAPI for the current user on
+/// Windows (in Febe.Desktop, the only project with ProtectedData and no package), AES-256-GCM with a key of its
+/// own in Docker (). The text it protects never reaches a log or an exception.
+///
+public interface ISessionProtector
+{
+ /// The scheme, for the log: dpapi or aes-gcm.
+ string Scheme { get; }
+
+ /// The encrypted form of , starting with 's header.
+ byte[] Protect(ReadOnlySpan plain);
+
+ /// The plain text of .
+ /// Another key or user, a damaged file, another scheme or format.
+ byte[] Unprotect(ReadOnlySpan blob);
+}
+
+///
+/// The header every protected session starts with: FEBS, the format version, the scheme. It says only what the
+/// file is, never what it holds; the AES scheme authenticates it.
+///
+public static class SessionBlob
+{
+ /// The scheme byte of DPAPI.
+ public const byte Dpapi = 1;
+
+ /// The scheme byte of AES-256-GCM.
+ public const byte AesGcm = 2;
+
+ /// The format version.
+ public const byte Version = 1;
+
+ /// The length of the header.
+ public const int HeaderLength = 6;
+
+ /// The header for .
+ public static byte[] Header(byte scheme) => [(byte)'F', (byte)'E', (byte)'B', (byte)'S', Version, scheme];
+
+ /// True when starts with the header of .
+ public static bool HasHeader(ReadOnlySpan blob, byte scheme) =>
+ blob.Length >= HeaderLength && blob[..HeaderLength].SequenceEqual(Header(scheme));
+}
+
+///
+/// The saved session cannot be read: another key or user, a damaged file, another format. Its message is fixed and
+/// carries no inner text: Febe treats it as no session and asks for a new login.
+///
+public sealed class SessionUnreadableException : Exception
+{
+ /// The fixed message.
+ public const string Text = "La sessione salvata non si legge (cifratura o formato): serve un nuovo accesso.";
+
+ public SessionUnreadableException()
+ : base(Text)
+ {
+ }
+
+ public SessionUnreadableException(string message)
+ : base(message)
+ {
+ }
+
+ public SessionUnreadableException(string message, Exception innerException)
+ : base(message, innerException)
+ {
+ }
+}
diff --git a/src/Febe.Core/Security/OwnerOnlyFiles.cs b/src/Febe.Core/Security/OwnerOnlyFiles.cs
new file mode 100644
index 0000000..cd068bc
--- /dev/null
+++ b/src/Febe.Core/Security/OwnerOnlyFiles.cs
@@ -0,0 +1,179 @@
+namespace Febe.Core.Security;
+
+///
+/// Files only their owner reads (issue #36, S4, spec §13.2): the folder Dati/sessione at 0700 and its files at
+/// 0600 on Unix, set when they are created (no window with wider rights); a file replaced at once (a part file in the
+/// same folder, then a rename over the old one), never half written. On Windows the modes do not apply: the Data folder
+/// is under the user's profile and DPAPI ties the session to the user.
+///
+public static class OwnerOnlyFiles
+{
+ /// The suffix of a file still being written.
+ public const string PartSuffix = ".part";
+
+ /// Read and write for the owner only.
+ public const UnixFileMode OwnerFile = UnixFileMode.UserRead | UnixFileMode.UserWrite;
+
+ /// Read, write and enter for the owner only.
+ public const UnixFileMode OwnerFolder = UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute;
+
+ private const UnixFileMode Others =
+ UnixFileMode.GroupRead | UnixFileMode.GroupWrite | UnixFileMode.GroupExecute
+ | UnixFileMode.OtherRead | UnixFileMode.OtherWrite | UnixFileMode.OtherExecute;
+
+ /// Creates owner-only (0700 on Unix); an existing one with wider rights is narrowed.
+ public static void EnsureFolder(string folder)
+ {
+ ArgumentException.ThrowIfNullOrWhiteSpace(folder);
+ if (OperatingSystem.IsWindows())
+ {
+ Directory.CreateDirectory(folder);
+ return;
+ }
+
+ if (!Directory.Exists(folder))
+ {
+ Directory.CreateDirectory(folder, OwnerFolder);
+ }
+ else if ((File.GetUnixFileMode(folder) & Others) != 0)
+ {
+ File.SetUnixFileMode(folder, OwnerFolder);
+ }
+ }
+
+ ///
+ /// Narrows to 0600 when group or others have any right on it (Unix only); true when it did.
+ ///
+ public static bool Tighten(string file)
+ {
+ ArgumentException.ThrowIfNullOrWhiteSpace(file);
+ if (OperatingSystem.IsWindows() || !File.Exists(file) || (File.GetUnixFileMode(file) & Others) == 0)
+ {
+ return false;
+ }
+
+ File.SetUnixFileMode(file, OwnerFile);
+ return true;
+ }
+
+ /// Writes the bytes of a new file into its stream (a seam for the tests of a disk that refuses the write).
+ internal delegate void BytesWriter(Stream stream, ReadOnlySpan bytes);
+
+ ///
+ /// Writes as a new owner-only file, whole or not at all: a part file in the same folder,
+ /// written through to the disk, then renamed to without replacing. Never replaces a file
+ /// that is there, and a failed write never leaves a short file at (nor a part file).
+ ///
+ /// The file is already there, or the disk refused it.
+ public static void CreateNew(string path, ReadOnlySpan bytes) => CreateNew(path, bytes, static (stream, data) => stream.Write(data));
+
+ ///
+ /// The new file.
+ /// Its content.
+ /// How the bytes go into the part file.
+ internal static void CreateNew(string path, ReadOnlySpan bytes, BytesWriter write)
+ {
+ ArgumentException.ThrowIfNullOrWhiteSpace(path);
+ ArgumentNullException.ThrowIfNull(write);
+ if (File.Exists(path))
+ {
+ throw new IOException($"{Path.GetFileName(path)} c'è già: Febe non lo sostituisce.");
+ }
+
+ var part = path + "." + Guid.NewGuid().ToString("N")[..8] + PartSuffix;
+ try
+ {
+ using (var stream = new FileStream(part, Options(FileMode.CreateNew, FileOptions.WriteThrough)))
+ {
+ write(stream, bytes);
+ stream.Flush(flushToDisk: true);
+ }
+
+ // Without replacing: a file made meanwhile by someone else stays, and this one throws IOException.
+ File.Move(part, path, overwrite: false);
+ }
+ finally
+ {
+ TryDelete(part);
+ }
+ }
+
+ ///
+ /// Replaces with at once: a part file in the same folder, owner-only
+ /// from its creation, written through to the disk, then renamed over the old file. A failure leaves the old file and
+ /// no part file.
+ ///
+ /// The disk refused the write or the rename.
+ /// The folder or the file is not writable.
+ public static void WriteAtomic(string path, ReadOnlySpan bytes)
+ {
+ ArgumentException.ThrowIfNullOrWhiteSpace(path);
+ var part = path + "." + Guid.NewGuid().ToString("N")[..8] + PartSuffix;
+ try
+ {
+ using (var stream = new FileStream(part, Options(FileMode.CreateNew, FileOptions.WriteThrough)))
+ {
+ stream.Write(bytes);
+ stream.Flush(flushToDisk: true);
+ }
+
+ File.Move(part, path, overwrite: true);
+ }
+ finally
+ {
+ TryDelete(part);
+ }
+ }
+
+ ///
+ /// Deletes and the part files a broken write may have left next to it. A file that is not
+ /// there is no error.
+ ///
+ /// The file could not be deleted.
+ /// The file could not be deleted.
+ public static void DeleteWithLeftovers(string path)
+ {
+ ArgumentException.ThrowIfNullOrWhiteSpace(path);
+ var folder = Path.GetDirectoryName(Path.GetFullPath(path))!;
+ if (!Directory.Exists(folder))
+ {
+ // No folder, no file: on Windows File.Delete would throw DirectoryNotFoundException.
+ return;
+ }
+
+ foreach (var part in Directory.EnumerateFiles(folder, Path.GetFileName(path) + ".*" + PartSuffix))
+ {
+ File.Delete(part);
+ }
+
+ File.Delete(path);
+ }
+
+ private static FileStreamOptions Options(FileMode mode, FileOptions options = FileOptions.None)
+ {
+ var result = new FileStreamOptions { Mode = mode, Access = FileAccess.Write, Share = FileShare.None, Options = options };
+ if (!OperatingSystem.IsWindows())
+ {
+ result.UnixCreateMode = OwnerFile;
+ }
+
+ return result;
+ }
+
+ private static void TryDelete(string path)
+ {
+ try
+ {
+ if (File.Exists(path))
+ {
+ File.Delete(path);
+ }
+ }
+ catch (IOException)
+ {
+ }
+ catch (UnauthorizedAccessException)
+ {
+ }
+ }
+}
diff --git a/src/Febe.Core/Security/SessionKey.cs b/src/Febe.Core/Security/SessionKey.cs
new file mode 100644
index 0000000..cd307f5
--- /dev/null
+++ b/src/Febe.Core/Security/SessionKey.cs
@@ -0,0 +1,165 @@
+using System.Globalization;
+using System.Security.Cryptography;
+
+namespace Febe.Core.Security;
+
+///
+/// The key of the saved session in Docker (issue #36, S4, spec §13.2): from FEBE_CHIAVE_SESSIONE (32 bytes in
+/// base64, or 64 hexadecimal digits), otherwise Dati/sessione/chiave.bin, made once with
+/// (not IRandomSource, which is for the timing of the engine), owner-only,
+/// never replaced. No text of this class ever holds the key or a part of it.
+///
+public static class SessionKey
+{
+ /// The length of the key: AES-256.
+ public const int Length = 32;
+
+ /// The environment variable that holds the key outside the Data folder.
+ public const string EnvironmentVariable = "FEBE_CHIAVE_SESSIONE";
+
+ ///
+ /// Reads a key written as text: base64 of exactly 32 bytes or 64 hexadecimal digits, spaces around it ignored.
+ /// The problem names the format only, never the value.
+ ///
+ public static bool TryParse(string? text, out byte[]? key, out string? problem)
+ {
+ key = null;
+ var trimmed = text?.Trim() ?? string.Empty;
+ if (trimmed.Length == 0)
+ {
+ problem = $"{EnvironmentVariable} è vuota.";
+ return false;
+ }
+
+ if (trimmed.Length == 2 * Length && trimmed.All(char.IsAsciiHexDigit))
+ {
+ key = Convert.FromHexString(trimmed);
+ problem = null;
+ return true;
+ }
+
+ var buffer = new byte[trimmed.Length];
+ if (Convert.TryFromBase64String(trimmed, buffer, out var written) && written == Length)
+ {
+ key = buffer[..Length];
+ CryptographicOperations.ZeroMemory(buffer);
+ problem = null;
+ return true;
+ }
+
+ CryptographicOperations.ZeroMemory(buffer);
+ problem = string.Create(
+ CultureInfo.InvariantCulture,
+ $"{EnvironmentVariable} deve essere una chiave di {Length} byte in base64 (per esempio quella di «openssl rand -base64 32») o di {2 * Length} cifre esadecimali.");
+ return false;
+ }
+
+ ///
+ /// What is wrong with , or null when it is a key of Febe or is not there (it will be made).
+ /// The text names the file and the length, never the content.
+ ///
+ public static string? CheckFile(string keyFile)
+ {
+ ArgumentException.ThrowIfNullOrWhiteSpace(keyFile);
+ try
+ {
+ if (!File.Exists(keyFile))
+ {
+ return null;
+ }
+
+ var length = new FileInfo(keyFile).Length;
+ return length == Length
+ ? null
+ : string.Create(CultureInfo.InvariantCulture, $"{Path.GetFileName(keyFile)} non è una chiave di Febe ({length} byte invece di {Length}): cancellalo e rifai l'accesso.");
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ return $"{Path.GetFileName(keyFile)} non si legge: controlla i permessi della cartella dei dati.";
+ }
+ }
+
+ ///
+ /// The key in , made when it is not there: 32 random bytes, a new owner-only file in an
+ /// owner-only folder, never replacing one that is there. A file with wider rights on Unix is narrowed to 0600 and
+ /// says so.
+ ///
+ /// The file is there but is not a key of Febe (32 bytes).
+ /// The disk refused to make or read the file.
+ public static byte[] LoadOrCreate(string keyFile, Action? warn = null) =>
+ LoadOrCreate(keyFile, warn, static (stream, bytes) => stream.Write(bytes));
+
+ ///
+ /// The key file.
+ /// Says when the rights of the file were narrowed.
+ /// How the bytes of a new key go to the disk (a seam for a disk that refuses the write).
+ internal static byte[] LoadOrCreate(string keyFile, Action? warn, OwnerOnlyFiles.BytesWriter write)
+ {
+ ArgumentException.ThrowIfNullOrWhiteSpace(keyFile);
+ var full = Path.GetFullPath(keyFile);
+ OwnerOnlyFiles.EnsureFolder(Path.GetDirectoryName(full)!);
+ if (!File.Exists(full))
+ {
+ var fresh = RandomNumberGenerator.GetBytes(Length);
+ try
+ {
+ // Whole or not at all: a write the disk refuses (full, I/O error) leaves no short chiave.bin behind,
+ // so the next start tries again instead of stopping at a file that is not a key.
+ OwnerOnlyFiles.CreateNew(full, fresh, write);
+ return fresh;
+ }
+ catch (IOException) when (File.Exists(full))
+ {
+ // Made by someone else in the meantime (only a whole file is ever renamed there): that one is the key.
+ CryptographicOperations.ZeroMemory(fresh);
+ }
+ catch
+ {
+ CryptographicOperations.ZeroMemory(fresh);
+ throw;
+ }
+ }
+
+ if (CheckFile(full) is { } problem)
+ {
+ throw new InvalidDataException(problem);
+ }
+
+ if (OwnerOnlyFiles.Tighten(full))
+ {
+ warn?.Invoke($"{Path.GetFileName(full)} era leggibile da altri utenti: ora lo legge solo il proprietario.");
+ }
+
+ return File.ReadAllBytes(full);
+ }
+
+ ///
+ /// The key of the saved session: (the value of )
+ /// when it is set, otherwise (). says
+ /// where the key comes from, never the key; with the variable set, an old chiave.bin is named as unused.
+ ///
+ /// The variable is set but is not a key, or the file is not a key of Febe.
+ public static byte[] Resolve(string? environmentValue, string keyFile, Action? log = null)
+ {
+ ArgumentException.ThrowIfNullOrWhiteSpace(keyFile);
+ if (!string.IsNullOrWhiteSpace(environmentValue))
+ {
+ if (!TryParse(environmentValue, out var key, out var problem))
+ {
+ throw new InvalidDataException(problem);
+ }
+
+ log?.Invoke($"Sessione salvata: chiave da {EnvironmentVariable}.");
+ if (File.Exists(keyFile))
+ {
+ log?.Invoke($"Sessione salvata: {Path.GetFileName(keyFile)} non si usa, la chiave viene da {EnvironmentVariable}.");
+ }
+
+ return key!;
+ }
+
+ var stored = LoadOrCreate(keyFile, log);
+ log?.Invoke($"Sessione salvata: chiave da Dati/sessione/{Path.GetFileName(keyFile)} (solo il proprietario la legge).");
+ return stored;
+ }
+}
diff --git a/src/Febe.Desktop.Core/DesktopOptions.cs b/src/Febe.Desktop.Core/DesktopOptions.cs
index 7d0c1cd..58ac818 100644
--- a/src/Febe.Desktop.Core/DesktopOptions.cs
+++ b/src/Febe.Desktop.Core/DesktopOptions.cs
@@ -104,6 +104,12 @@ public sealed record DesktopOptions
/// Development: the first session after this delay instead of 2–10 minutes.
public TimeSpan? FirstSessionDelay { get; init; }
+ ///
+ /// --raccolta pagine|richieste (issue #36, S4): by the pages (default, as before S4) or by requests with the
+ /// saved session, only for the operations the site's catalog configures.
+ ///
+ public CollectionRoute Collection { get; init; } = CollectionRoute.Pages;
+
/// The fixed DevTools port of Edge (fallback «edge» only), on 127.0.0.1.
public int EdgeDebugPort { get; init; } = 9222;
@@ -135,6 +141,7 @@ public sealed record DesktopOptions
TestSite = TestSite,
TestSiteAutoLogin = TestSiteAutoLogin,
FirstSessionDelay = FirstSessionDelay,
+ Collection = Collection,
};
private static Uri DefaultCdn(Uri site) => new UriBuilder(site) { Host = "127.0.0.2", Port = site.Port + 1, Path = "/" }.Uri;
@@ -145,7 +152,8 @@ public static class DesktopCommandLine
{
public const string Usage =
"Uso: Febe.exe [--nascosto] [--dati cartella] [--libreria cartella] [--browser finestra|composizione|edge] [--sviluppo]\n"
- + " [--sito-di-prova http://127.0.0.1:8481 [--cdn-di-prova http://127.0.0.2:8482] [--accesso-di-prova]] [--prima-sessione secondi]";
+ + " [--sito-di-prova http://127.0.0.1:8481 [--cdn-di-prova http://127.0.0.2:8482] [--accesso-di-prova]] [--prima-sessione secondi]\n"
+ + " [--raccolta pagine|richieste]";
public static bool TryParse(string[] args, out DesktopOptions options, out string problem)
{
@@ -222,6 +230,19 @@ public static class DesktopCommandLine
case "--accesso-di-prova":
options = options with { TestSiteAutoLogin = true };
break;
+ case CollectionRouteNames.Option:
+ {
+ var text = Next();
+ if (!CollectionRouteNames.TryParse(text, out var route))
+ {
+ problem = CollectionRouteNames.Problem(CollectionRouteNames.Option, text);
+ return false;
+ }
+
+ options = options with { Collection = route };
+ break;
+ }
+
case "--prima-sessione":
{
var text = Next();
diff --git a/src/Febe.Desktop.Core/DesktopPlatform.cs b/src/Febe.Desktop.Core/DesktopPlatform.cs
index 7147b55..cd9472c 100644
--- a/src/Febe.Desktop.Core/DesktopPlatform.cs
+++ b/src/Febe.Desktop.Core/DesktopPlatform.cs
@@ -4,6 +4,7 @@ using Febe.Browser.Cdp;
using Febe.Browser.Hosting;
using Febe.Core.Abstractions;
using Febe.Core.Library;
+using Febe.Core.Security;
using Febe.Web;
using Febe.Web.Api;
using Febe.Web.Connection;
@@ -54,6 +55,12 @@ public interface IDesktopShell
/// debugging port. False when Windows refused (the process then lives on its own, as before).
///
bool EndWithFebe(System.Diagnostics.Process process);
+
+ ///
+ /// How the saved session is encrypted on Windows (issue #36, S4, spec §13.2): DPAPI for the current user, from the
+ /// desktop framework of .NET (no package). Tests on Linux pass AES-256-GCM with a key made at run time.
+ ///
+ ISessionProtector SessionProtector { get; }
}
///
@@ -147,6 +154,15 @@ public sealed class DesktopPlatform : IFebePlatform
context);
}
+ /// DPAPI for the current Windows user (the shell's): no key file, nothing in the Data folder but the session.
+ public ISessionProtector CreateSessionProtector(FebePlatformContext context)
+ {
+ ArgumentNullException.ThrowIfNull(context);
+ var protector = _shell.SessionProtector;
+ context.Log.Info("sessione", $"Sessione salvata: cifrata con {protector.Scheme} (solo questo utente di Windows la legge).");
+ return protector;
+ }
+
public void RegisterServices(IServiceCollection services, FebeApp app)
{
ArgumentNullException.ThrowIfNull(services);
diff --git a/src/Febe.Desktop/DesktopShell.cs b/src/Febe.Desktop/DesktopShell.cs
index 7891c07..03c1ebb 100644
--- a/src/Febe.Desktop/DesktopShell.cs
+++ b/src/Febe.Desktop/DesktopShell.cs
@@ -5,7 +5,9 @@ using System.Windows.Threading;
using Febe.App;
using Febe.Desktop.Browser;
using Febe.Desktop.Core;
+using Febe.Core.Security;
using Febe.Desktop.Native;
+using Febe.Desktop.Security;
using Febe.Web.Native;
using Microsoft.Web.WebView2.Core;
using Microsoft.Win32;
@@ -17,6 +19,8 @@ internal sealed class DesktopShell(Dispatcher ui, ImageSource? icon, INativeShel
{
public INativeShell Native { get; } = native;
+ public ISessionProtector SessionProtector { get; } = new DpapiSessionProtector();
+
public string? WebView2Version()
{
try
diff --git a/src/Febe.Desktop/Security/DpapiSessionProtector.cs b/src/Febe.Desktop/Security/DpapiSessionProtector.cs
new file mode 100644
index 0000000..0b3c2dc
--- /dev/null
+++ b/src/Febe.Desktop/Security/DpapiSessionProtector.cs
@@ -0,0 +1,62 @@
+using System.Security.Cryptography;
+using System.Text;
+using Febe.Core.Security;
+
+namespace Febe.Desktop.Security;
+
+///
+/// DPAPI for the saved session on Windows (issue #36, S4, spec §13.2): for the current
+/// user, from the desktop framework of .NET (no package, decisioni.md). The blob is the shared header (scheme
+/// ) followed by what DPAPI gives; the header is also part of the entropy, so a blob with
+/// a changed header does not open. Another Windows user, another computer or a damaged byte is
+/// , never the inner text.
+///
+internal sealed class DpapiSessionProtector : ISessionProtector
+{
+ /// The fixed entropy of Febe's blobs: not a secret, it keeps other programs' DPAPI blobs apart.
+ private static readonly byte[] Entropy = Encoding.UTF8.GetBytes("Febe sessione salvata v1");
+
+ public string Scheme => "dpapi";
+
+ public byte[] Protect(ReadOnlySpan plain)
+ {
+ var header = SessionBlob.Header(SessionBlob.Dpapi);
+ var copy = plain.ToArray();
+ try
+ {
+ var sealedBytes = ProtectedData.Protect(copy, EntropyFor(header), DataProtectionScope.CurrentUser);
+ var blob = new byte[header.Length + sealedBytes.Length];
+ header.CopyTo(blob, 0);
+ sealedBytes.CopyTo(blob, header.Length);
+ return blob;
+ }
+ finally
+ {
+ CryptographicOperations.ZeroMemory(copy);
+ }
+ }
+
+ public byte[] Unprotect(ReadOnlySpan blob)
+ {
+ if (!SessionBlob.HasHeader(blob, SessionBlob.Dpapi) || blob.Length == SessionBlob.HeaderLength)
+ {
+ throw new SessionUnreadableException();
+ }
+
+ var header = blob[..SessionBlob.HeaderLength].ToArray();
+ try
+ {
+ return ProtectedData.Unprotect(blob[SessionBlob.HeaderLength..].ToArray(), EntropyFor(header), DataProtectionScope.CurrentUser);
+ }
+ catch (CryptographicException)
+ {
+ // Another user or computer, or a changed byte: nothing of the inner text is passed on.
+ throw new SessionUnreadableException();
+ }
+ }
+
+ /// The scheme only.
+ public override string ToString() => "Cifratura della sessione: DPAPI dell'utente di Windows.";
+
+ private static byte[] EntropyFor(byte[] header) => [.. Entropy, .. header];
+}
diff --git a/src/Febe.Server/DockerPlatform.cs b/src/Febe.Server/DockerPlatform.cs
index 5f4a81f..06da93e 100644
--- a/src/Febe.Server/DockerPlatform.cs
+++ b/src/Febe.Server/DockerPlatform.cs
@@ -1,5 +1,6 @@
using Febe.App;
using Febe.Core.Library;
+using Febe.Core.Security;
using Febe.Web;
using Febe.Web.Connection;
using Microsoft.Extensions.DependencyInjection;
@@ -49,6 +50,39 @@ internal sealed class DockerPlatform(ServerOptions options) : IFebePlatform
context.Log));
}
+ ///
+ /// AES-256-GCM (spec §13.2): the key of FEBE_CHIAVE_SESSIONE when it is set (already checked at start-up),
+ /// otherwise Dati/sessione/chiave.bin, made once owner-only. The same on Windows while developing with
+ /// Febe.Server (no Unix modes there). The log says where the key comes from, never the key.
+ ///
+ public ISessionProtector CreateSessionProtector(FebePlatformContext context)
+ {
+ ArgumentNullException.ThrowIfNull(context);
+ var keyFile = context.Data.SessionKeyFile;
+ if (Options.SessionKey is { } fromEnvironment)
+ {
+ context.Log.Info("sessione", $"Sessione salvata: chiave da {SessionKey.EnvironmentVariable}.");
+ if (File.Exists(keyFile))
+ {
+ context.Log.Warn("sessione", $"Sessione salvata: Dati/sessione/{Path.GetFileName(keyFile)} non si usa, la chiave viene da {SessionKey.EnvironmentVariable}.");
+ }
+
+ return new AesGcmSessionProtector(fromEnvironment);
+ }
+
+ var stored = SessionKey.LoadOrCreate(keyFile, message => context.Log.Warn("sessione", message));
+ try
+ {
+ context.Log.Info("sessione", $"Sessione salvata: chiave da Dati/sessione/{Path.GetFileName(keyFile)} (solo il proprietario la legge).");
+ return new AesGcmSessionProtector(stored);
+ }
+ finally
+ {
+ // The protector keeps its own copy.
+ System.Security.Cryptography.CryptographicOperations.ZeroMemory(stored);
+ }
+ }
+
public void RegisterServices(IServiceCollection services, FebeApp app)
{
ArgumentNullException.ThrowIfNull(services);
diff --git a/src/Febe.Server/ServerCommand.cs b/src/Febe.Server/ServerCommand.cs
index 9930c58..94fdc98 100644
--- a/src/Febe.Server/ServerCommand.cs
+++ b/src/Febe.Server/ServerCommand.cs
@@ -13,7 +13,9 @@ internal static class ServerCommand
"Uso: febe [--dati /dati] [--libreria /libreria] [--importa /importa] [--porta 8480] [--ascolta 0.0.0.0]\n"
+ " [--porta-debug 9222] [--display :99] [--chromium percorso] [--senza-sandbox]\n"
+ " [--sito-di-prova http://127.0.0.1:8481 [--cdn-di-prova http://127.0.0.2:8482] [--accesso-di-prova]] [--prima-sessione secondi]\n"
- + "Variabili: FEBE_PASSWORD (obbligatoria), FEBE_PORTA, TZ, LANG, FEBE_HOST, FEBE_PROXY_FIDATO, FEBE_SENZA_SANDBOX, FEBE_CHROMIUM.\n"
+ + " [--raccolta pagine|richieste]\n"
+ + "Variabili: FEBE_PASSWORD (obbligatoria), FEBE_PORTA, TZ, LANG, FEBE_HOST, FEBE_PROXY_FIDATO, FEBE_SENZA_SANDBOX, FEBE_CHROMIUM,\n"
+ + " FEBE_RACCOLTA, FEBE_CHIAVE_SESSIONE.\n"
+ "Altri comandi: --demo, --simula 30g --profilo prudente, --controllo-salute.";
public static async Task RunAsync(string[] args, TextWriter output, TextWriter error)
diff --git a/src/Febe.Server/ServerOptions.cs b/src/Febe.Server/ServerOptions.cs
index 6e40921..0f57a94 100644
--- a/src/Febe.Server/ServerOptions.cs
+++ b/src/Febe.Server/ServerOptions.cs
@@ -3,14 +3,16 @@ using System.Net;
using Febe.App;
using Febe.Browser.Hosting;
using Febe.Browser.Recipes;
+using Febe.Core.Security;
using Febe.Web;
namespace Febe.Server;
///
/// Configuration of the real server (spec §11): environment variables of the container, plus a few command-line
-/// options for development (other folders, the local test site, a short first-session delay). The password comes only
-/// from the environment, never from the command line (which other users of the machine can read).
+/// options for development (other folders, the local test site, a short first-session delay). The password and the key
+/// of the saved session come only from the environment, never from the command line (which other users of the machine
+/// can read), and never appear in , in or in a problem.
///
internal sealed record ServerOptions
{
@@ -25,6 +27,22 @@ internal sealed record ServerOptions
/// FEBE_PASSWORD: the interface password. Mandatory; never logged or shown.
public string? Password { get; init; }
+ ///
+ /// FEBE_CHIAVE_SESSIONE, decoded (issue #36, S4, spec §13.2): the 32-byte AES key of the saved session, kept out of
+ /// the Data folder. Null when the variable is not set (the key is then Dati/sessione/chiave.bin) or is not a
+ /// key (). Never logged or shown.
+ ///
+ public byte[]? SessionKey { get; init; }
+
+ /// What is wrong with FEBE_CHIAVE_SESSIONE (its format only, never its value); null when it is right or unset.
+ public string? SessionKeyProblem { get; init; }
+
+ ///
+ /// Option «raccolta» (--raccolta, FEBE_RACCOLTA; the command line wins): by the pages (default) or by requests
+ /// (issue #36, S4).
+ ///
+ public CollectionRoute Collection { get; init; } = CollectionRoute.Pages;
+
/// Where Kestrel listens: every address in Docker (the port is published), 127.0.0.1 with --ascolta.
public IPAddress ListenAddress { get; init; } = IPAddress.Any;
@@ -115,6 +133,7 @@ internal sealed record ServerOptions
TestSite = TestSite,
TestSiteAutoLogin = TestSiteAutoLogin,
FirstSessionDelay = FirstSessionDelay,
+ Collection = Collection,
Warnings = Warnings,
};
@@ -188,9 +207,28 @@ internal sealed record ServerOptions
return false;
}
+ var collection = CollectionRoute.Pages;
+ if (Env(CollectionRouteNames.EnvironmentVariable) is { } collectionText && !CollectionRouteNames.TryParse(collectionText, out collection))
+ {
+ problem = CollectionRouteNames.Problem(CollectionRouteNames.EnvironmentVariable, collectionText);
+ return false;
+ }
+
+ // Raw, like the password: the value never reaches a warning, a problem or the log.
+ byte[]? sessionKey = null;
+ string? sessionKeyProblem = null;
+ if (environment(Core.Security.SessionKey.EnvironmentVariable) is { Length: > 0 } keyText
+ && !Core.Security.SessionKey.TryParse(keyText, out sessionKey, out sessionKeyProblem))
+ {
+ sessionKey = null;
+ }
+
options = options with
{
- Password = environment("FEBE_PASSWORD") is { Length: > 0 } password ? password : null,
+ Password = environment(ChildProcessEnvironment.PasswordVariable) is { Length: > 0 } password ? password : null,
+ SessionKey = sessionKey,
+ SessionKeyProblem = sessionKeyProblem,
+ Collection = collection,
Port = port,
ZoneId = zoneId,
Zone = zone,
@@ -286,6 +324,19 @@ internal sealed record ServerOptions
case "--accesso-di-prova":
options = options with { TestSiteAutoLogin = true };
break;
+ case CollectionRouteNames.Option:
+ {
+ var text = Next();
+ if (!CollectionRouteNames.TryParse(text, out var route))
+ {
+ problem = CollectionRouteNames.Problem(CollectionRouteNames.Option, text);
+ return false;
+ }
+
+ options = options with { Collection = route };
+ break;
+ }
+
case "--prima-sessione":
{
var text = Next();
@@ -339,6 +390,19 @@ internal sealed record ServerOptions
return true;
}
+ ///
+ /// What the options are, for a debugger or an exception: the secrets only as «impostata» or «assente», never their
+ /// value (the generated text of a record would print them).
+ ///
+ public override string ToString()
+ {
+ var password = string.IsNullOrEmpty(Password) ? "assente" : "impostata";
+ var key = SessionKey is not null ? "impostata" : SessionKeyProblem is not null ? "non valida" : "assente";
+ return string.Create(
+ CultureInfo.InvariantCulture,
+ $"ServerOptions {{ Dati = {DataFolder}, Libreria = {LibraryFolder}, Porta = {Port}, Sito = {Site.Name}, Raccolta = {CollectionRouteNames.Name(Collection)}, {ChildProcessEnvironment.PasswordVariable} = {password}, {Core.Security.SessionKey.EnvironmentVariable} = {key} }}");
+ }
+
/// The time zone named by TZ, or null when unknown.
public static TimeZoneInfo? FindZone(string id) =>
TimeZoneInfo.TryFindSystemTimeZoneById(id, out var zone) ? zone : null;
diff --git a/src/Febe.Server/StartupChecks.cs b/src/Febe.Server/StartupChecks.cs
index 8c3f183..8fdccf5 100644
--- a/src/Febe.Server/StartupChecks.cs
+++ b/src/Febe.Server/StartupChecks.cs
@@ -1,12 +1,14 @@
using Febe.App;
using Febe.Core.Library;
+using Febe.Core.Security;
using Febe.Web.Connection;
namespace Febe.Server;
///
-/// The checks made before anything starts (spec §8.2, §11): the interface password and the Data folder. With a problem
-/// the engine and the browser do not start, and the interface shows only the page that explains it.
+/// The checks made before anything starts (spec §8.2, §11): the interface password, the Data folder and the key of the
+/// saved session (issue #36, S4). With a problem the engine and the browser do not start, and the interface shows only
+/// the page that explains it. No text ever holds the password or the key.
///
internal static class StartupChecks
{
@@ -16,6 +18,12 @@ internal static class StartupChecks
public const string DataOnNetwork = DataFolderProblems.DataOnNetwork;
+ /// FEBE_CHIAVE_SESSIONE is set but is not a key of 32 bytes.
+ public const string SessionKeyInvalid = "chiave-sessione-non-valida";
+
+ /// Dati/sessione/chiave.bin is there but is not a key of Febe (or cannot be read).
+ public const string SessionKeyFileInvalid = "chiave-sessione-file";
+
/// Every problem found, in the order the error page shows them.
public static IReadOnlyList Run(ServerOptions options, DataFolderCheck? check = null)
{
@@ -36,6 +44,28 @@ internal static class StartupChecks
problems.Add(data);
}
+ // A key set by hand that is wrong is always said, whatever the «raccolta»: left silent, it would surprise later.
+ if (options.SessionKeyProblem is { } keyProblem)
+ {
+ problems.Add(new ConfigurationProblem(
+ SessionKeyInvalid,
+ "La chiave della sessione salvata non è valida",
+ keyProblem + " Febe non ha avviato né il motore né il browser, per non cifrare la sessione con una chiave sbagliata.",
+ $"Correggi {SessionKey.EnvironmentVariable} (nel modello di Unraid o in compose.yml) con 32 byte in base64, per esempio il risultato di «openssl rand -base64 32», oppure toglila: Febe userà Dati/sessione/chiave.bin. Poi riavvia il contenitore."));
+ }
+
+ // chiave.bin is read only by the requests route, and only when the variable does not give the key.
+ if (options.Collection == CollectionRoute.Requests && options.SessionKey is null && options.SessionKeyProblem is null
+ && SessionKey.CheckFile(new DataFolderLayout(options.DataFolder).SessionKeyFile) is { } fileProblem)
+ {
+ problems.Add(new ConfigurationProblem(
+ SessionKeyFileInvalid,
+ "La chiave della sessione salvata non si legge",
+ fileProblem + " Febe non ha avviato né il motore né il browser.",
+ "Cancella Dati/sessione/chiave.bin (la sessione salvata non si leggerà più: basta rifare l'accesso), oppure imposta "
+ + $"{SessionKey.EnvironmentVariable}, poi riavvia il contenitore."));
+ }
+
return problems;
}
}
diff --git a/src/Febe.Web/wwwroot/testi/it.json b/src/Febe.Web/wwwroot/testi/it.json
index 8fbace2..d69c491 100644
--- a/src/Febe.Web/wwwroot/testi/it.json
+++ b/src/Febe.Web/wwwroot/testi/it.json
@@ -726,7 +726,7 @@
"usaBrowserTesto": "Per controllare qualcosa a mano. Mentre usi il browser il motore resta fermo.",
"scollega": "Scollega…",
"scollegaTitolo": "Scollegare Febe da Instagram?",
- "scollegaTesto": "Febe ferma il motore e cancella il profilo del suo browser, con la sessione. Per chiudere la sessione anche dal lato di Instagram, prima esci dal sito usando tu il browser (menu del profilo, «Esci»), poi torna qui.",
+ "scollegaTesto": "Febe ferma il motore e cancella il profilo del suo browser, con la sessione, e la copia della sessione salvata per le richieste, se c'è. Per chiudere la sessione anche dal lato di Instagram, prima esci dal sito usando tu il browser (menu del profilo, «Esci»), poi torna qui.",
"scollegaConferma": "Scollega e cancella la sessione",
"usaPrima": "Usa prima il browser",
"scollegato": "Febe è scollegato da Instagram.",
diff --git a/tests/Febe.Tests.Windows/DpapiSessionProtectorTests.cs b/tests/Febe.Tests.Windows/DpapiSessionProtectorTests.cs
new file mode 100644
index 0000000..f4208ad
--- /dev/null
+++ b/tests/Febe.Tests.Windows/DpapiSessionProtectorTests.cs
@@ -0,0 +1,65 @@
+using System.Text;
+using Febe.Core.Security;
+using Febe.Desktop.Security;
+
+namespace Febe.Tests.Windows;
+
+///
+/// The saved session on Windows (issue #36, S4, spec §13.2): DPAPI for the current user, from the desktop framework of
+/// .NET with no package. No WebView2 needed. A blob that does not open is ,
+/// whose text holds nothing of the session.
+///
+[TestClass]
+public sealed class DpapiSessionProtectorTests
+{
+ private const string Secret = "valore-di-prova-della-sessione";
+
+ private static readonly byte[] Plain = Encoding.UTF8.GetBytes("{\"cookies\":[{\"name\":\"sessione_prova\",\"value\":\"" + Secret + "\"}]}");
+
+ [TestMethod]
+ public void ARoundTripForTheCurrentUserGivesTheSameBytes()
+ {
+ var protector = new DpapiSessionProtector();
+ Assert.AreEqual("dpapi", protector.Scheme);
+ var blob = protector.Protect(Plain);
+ Assert.IsTrue(SessionBlob.HasHeader(blob, SessionBlob.Dpapi), "the shared header with the DPAPI scheme");
+ CollectionAssert.AreEqual(Plain, protector.Unprotect(blob));
+ CollectionAssert.AreEqual(Plain, new DpapiSessionProtector().Unprotect(blob), "another instance of the same user");
+ CollectionAssert.AreNotEqual(blob, protector.Protect(Plain), "DPAPI salts every blob");
+ }
+
+ [TestMethod]
+ public void TheBlobHoldsNoValueInClear()
+ {
+ var blob = new DpapiSessionProtector().Protect(Plain);
+ foreach (var form in new[] { Encoding.UTF8.GetBytes(Secret), Encoding.Unicode.GetBytes(Secret), Encoding.ASCII.GetBytes(Convert.ToBase64String(Encoding.UTF8.GetBytes(Secret))) })
+ {
+ Assert.AreEqual(-1, blob.AsSpan().IndexOf(form), "a form of the value is in the blob");
+ }
+ }
+
+ [TestMethod]
+ public void ATamperedBlobOrAnotherSchemeIsUnreadableAndTheMessageHasNoValue()
+ {
+ var protector = new DpapiSessionProtector();
+ var blob = protector.Protect(Plain);
+
+ var changedByte = blob.ToArray();
+ changedByte[^5] ^= 0x40;
+ var changedHeader = blob.ToArray();
+ changedHeader[4] = 9;
+ var aesHeader = blob.ToArray();
+ aesHeader[5] = SessionBlob.AesGcm;
+ var headerOnly = SessionBlob.Header(SessionBlob.Dpapi);
+
+ foreach (var wrong in new[] { changedByte, changedHeader, aesHeader, headerOnly, [], Encoding.UTF8.GetBytes(Secret) })
+ {
+ var error = Assert.ThrowsExactly(() => protector.Unprotect(wrong));
+ Assert.AreEqual(SessionUnreadableException.Text, error.Message);
+ Assert.IsNull(error.InnerException, "nothing of DPAPI's own text is passed on");
+ Assert.DoesNotContain(Secret, error.ToString());
+ }
+
+ Assert.DoesNotContain(Secret, protector.ToString());
+ }
+}
diff --git a/tests/Febe.Tests/Browser/SessionCaptureTests.cs b/tests/Febe.Tests/Browser/SessionCaptureTests.cs
new file mode 100644
index 0000000..1ccb8c7
--- /dev/null
+++ b/tests/Febe.Tests/Browser/SessionCaptureTests.cs
@@ -0,0 +1,410 @@
+using System.Text.Json;
+using System.Text.Json.Nodes;
+using Febe.App;
+using Febe.Browser.Cdp;
+using Febe.Browser.Recipes;
+using Febe.Browser.Session;
+using Febe.Core.Abstractions;
+using Febe.Core.Collection;
+using Febe.Core.Collection.Requests;
+using Febe.Tests.Browser.TestSupport;
+
+namespace Febe.Tests.Browser;
+
+///
+/// The copy of the browser's session at «Ho finito» (issue #36, S4, spec §6.0, §6.1 «Copiare la sessione»), against a
+/// fake page: only Page.getFrameTree, Network.getCookies and one read-only Runtime.evaluate; the
+/// cookies with their domains and paths, the modules the catalog names and nothing else, a missing value left out and
+/// never guessed (rule 9), and no value in any text (rule 10). Never Instagram, never a browser.
+///
+[TestClass]
+public sealed class SessionCaptureTests
+{
+ private const string SiteHost = "127.0.0.1:8481";
+ private const string UserAgent = "Mozilla/5.0 (X11; Linux x86_64) Agente di prova";
+
+ private static readonly CollectionSite Site = CollectionSite.TestSite(SiteHost, "127.0.0.2:8482");
+ private static readonly SessionCapturePlan Plan = SessionCapturePlan.For(Site, RequestCatalog.LoadTestSite(), SignalRules.LoadTestSite());
+
+ /// The secrets of the fake page: none may appear in a text, a message or a log line.
+ private static readonly string[] Secrets = ["valore-sessione-segreto", "valore-csrf-segreto", "valore-api-segreto", "lsd-segreto", "nonce-segreto", "9000000000000009"];
+
+ [TestMethod]
+ public async Task TheCopySendsOnlyGetCookiesAndOneEvaluateThatPassesTheGuard()
+ {
+ var cdp = Page($"http://{SiteHost}/profilo/marta.prova/");
+ var result = await SessionCapture.CaptureAsync(cdp, Plan, new VirtualClock(), CancellationToken.None);
+
+ Assert.IsNotNull(result.Values, result.ToString());
+ CollectionAssert.AreEqual(new[] { "Page.getFrameTree", "Network.getCookies", "Runtime.evaluate" }, cdp.Sent.Select(c => c.Method).ToArray());
+ Assert.IsTrue(cdp.Sent.All(c => CdpCommandPolicy.IsAllowed(c.Method)), "only commands of §6.1");
+ var evaluation = cdp.Sent.Single(c => c.Method == "Runtime.evaluate").Parameters!;
+ ReadOnlyScriptGuard.EnsureReadOnly(evaluation["expression"]!.GetValue());
+ Assert.IsTrue(evaluation["returnByValue"]!.GetValue());
+ Assert.IsFalse(evaluation["awaitPromise"]!.GetValue(), "nothing asynchronous in the page");
+ }
+
+ [TestMethod]
+ public void GetCookiesAsksTheSiteRootAndEveryCatalogPathPrefix()
+ {
+ var urls = Plan.CookieUrls.Select(u => u.AbsoluteUri).ToList();
+ Assert.AreEqual($"http://{SiteHost}/", urls[0], "the root first");
+ CollectionAssert.Contains(urls, $"http://{SiteHost}/api/graphql");
+ Assert.IsTrue(urls.All(u => u.StartsWith($"http://{SiteHost}/", StringComparison.Ordinal)), "only the site");
+ Assert.IsFalse(urls.Any(u => u.Contains('{', StringComparison.Ordinal) || u.Contains("%7B", StringComparison.OrdinalIgnoreCase)), "a path is cut before its first value");
+ Assert.IsTrue(urls.Any(u => u.StartsWith($"http://{SiteHost}/api/dati/", StringComparison.Ordinal)), "the addresses of the plain operations too");
+ Assert.AreEqual(urls.Count, urls.Distinct().Count());
+ }
+
+ [TestMethod]
+ public async Task CookiesKeepValueDomainPathSecureAndExpiryAndOthersAreLeftOut()
+ {
+ var expiry = new DateTimeOffset(2027, 1, 1, 0, 0, 0, TimeSpan.Zero);
+ var cdp = Page($"http://{SiteHost}/", cookies: new JsonArray(
+ Cookie("sessione_prova", "valore-sessione-segreto", "127.0.0.1", expires: expiry.ToUnixTimeSeconds()),
+ Cookie("csrftoken", "valore-csrf-segreto", "127.0.0.1"),
+ Cookie("percorso_api", "valore-api-segreto", "127.0.0.1", "/api/", secure: true),
+ Cookie("altrove", "valore", "esempio.invalid"),
+ Cookie("diviso", "valore", "127.0.0.1", partitioned: true),
+ Cookie("strano", "valore;con-separatore", "127.0.0.1"),
+ Cookie("accentato", "caffè", "127.0.0.1")));
+
+ var result = await SessionCapture.CaptureAsync(cdp, Plan, new VirtualClock(), CancellationToken.None);
+ var values = result.Values!;
+ CollectionAssert.AreEqual(new[] { "sessione_prova", "csrftoken", "percorso_api" }, values.Cookies.Select(c => c.Name).ToArray(), "another host's cookie is not the site's");
+ Assert.AreEqual(3, result.DroppedCookies, "partitioned, «;» and non-ASCII values are left out and counted");
+
+ var session = values.Cookies[0];
+ Assert.AreEqual("valore-sessione-segreto", session.Value);
+ Assert.AreEqual("127.0.0.1", session.Domain);
+ Assert.IsTrue(session.HostOnly);
+ Assert.AreEqual("/", session.Path);
+ Assert.IsTrue(session.HttpOnly);
+ Assert.AreEqual(expiry, session.Expires);
+ Assert.IsNull(values.Cookies[1].Expires, "a session cookie has no expiry");
+
+ var api = values.Cookies[2];
+ Assert.AreEqual("/api/", api.Path, "a cookie limited to a path keeps it");
+ Assert.IsTrue(api.Secure);
+ Assert.IsNull(values.CookieFor("percorso_api", new Uri($"http://{SiteHost}/"), new VirtualClock().Now), "never sent outside its path");
+ }
+
+ [TestMethod]
+ public async Task ADomainCookieOfInstagramIsKeptAsADomainCookie()
+ {
+ var plan = SessionCapturePlan.For(CollectionSite.Instagram, RequestCatalog.LoadInstagram(), SignalRules.LoadDefault());
+ var cdp = Page("https://www.instagram.com/", cookies: new JsonArray(
+ Cookie("sessionid", "valore-sessione-segreto", ".instagram.com", secure: true),
+ Cookie("altro", "valore", ".example.invalid")));
+
+ var result = await SessionCapture.CaptureAsync(cdp, plan, new VirtualClock(), CancellationToken.None);
+ var cookie = result.Values!.Cookies.Single();
+ Assert.AreEqual("instagram.com", cookie.Domain);
+ Assert.IsFalse(cookie.HostOnly, "a leading dot is a domain cookie");
+ Assert.IsTrue(cookie.Secure);
+ }
+
+ [TestMethod]
+ public async Task TheUserAgentIsNavigatorUserAgentAsItIsAndThePageValuesComeFromTheCatalogModulesOnly()
+ {
+ var cdp = Page($"http://{SiteHost}/");
+ var result = await SessionCapture.CaptureAsync(cdp, Plan, new VirtualClock(), CancellationToken.None);
+ var values = result.Values!;
+ Assert.AreEqual(UserAgent, values.UserAgent);
+ Assert.AreEqual("lsd-segreto", values.Fields["lsd"]);
+ Assert.AreEqual("1", values.Fields["dpr"], "a number of the page as text");
+ Assert.AreEqual("9000000000000009", values.DocIds["ProvaProfiloQuery"]);
+ Assert.IsFalse(values.Fields.ContainsKey("estraneo"), "a value the plan did not ask is ignored");
+ Assert.IsFalse(values.DocIds.ContainsKey("AltraQuery"));
+
+ // The expression names exactly the modules of the catalog's page section, and the GraphQL operations of the catalog.
+ var expression = SessionCaptureScript.Build(Plan);
+ var catalog = RequestCatalog.LoadTestSite();
+ foreach (var source in catalog.Page!.Values.Values)
+ {
+ StringAssert.Contains(expression, $"read(\"{source.Module}\", \"{source.Property}\")");
+ }
+
+ StringAssert.Contains(expression, "read(\"ProvaProfiloQuery_operazioneProva\", null)");
+ Assert.AreEqual(catalog.Page.Values.Count + 1, CountOf(expression, "const v = read("), "one read per value and doc_id, nothing else");
+ }
+
+ [TestMethod]
+ public void TheExpressionPassesTheGuardForBothShippedCatalogs()
+ {
+ foreach (var (site, catalog, rules) in new[]
+ {
+ (Site, RequestCatalog.LoadTestSite(), SignalRules.LoadTestSite()),
+ (CollectionSite.Instagram, RequestCatalog.LoadInstagram(), SignalRules.LoadDefault()),
+ })
+ {
+ var expression = SessionCaptureScript.Build(SessionCapturePlan.For(site, catalog, rules));
+ Assert.IsTrue(ReadOnlyScriptGuard.IsReadOnly(expression), site.Name);
+ Assert.DoesNotContain("document.cookie", expression);
+ Assert.DoesNotContain("Storage", expression);
+ }
+ }
+
+ [TestMethod]
+ public async Task AMissingModuleOrANonStringOrAControlCharacterValueIsMissingNotGuessed()
+ {
+ var page = PageValues();
+ var values = (JsonObject)page["values"]!;
+ values.Remove("hsi");
+ values["hs"] = new JsonObject { ["oggetto"] = true };
+ values["rev"] = "con\naccapo";
+ values["ccg"] = new string('x', SessionCapture.MaxValueLength + 1);
+ ((JsonObject)page["docIds"]!).Remove("ProvaProfiloQuery");
+ var cdp = Page($"http://{SiteHost}/", page: page);
+
+ var result = await SessionCapture.CaptureAsync(cdp, Plan, new VirtualClock(), CancellationToken.None);
+ CollectionAssert.AreEquivalent(new[] { "hsi", "hs", "rev", "ccg" }, result.MissingValues.ToArray());
+ CollectionAssert.AreEqual(new[] { "ProvaProfiloQuery" }, result.MissingDocIds.ToArray());
+ foreach (var name in result.MissingValues)
+ {
+ Assert.IsFalse(result.Values!.Fields.ContainsKey(name), name);
+ }
+
+ Assert.IsEmpty(result.Values!.DocIds);
+ Assert.AreEqual("lsd-segreto", result.Values.Fields["lsd"], "the others are copied");
+ }
+
+ [TestMethod]
+ public async Task NotOnTheSiteOrOnItsLoginOrVerificationPageNothingIsRead()
+ {
+ foreach (var (url, refusal) in new[]
+ {
+ ("about:blank", CaptureRefusal.NotOnSite),
+ ("http://127.0.0.2:8482/file.jpg", CaptureRefusal.NotOnSite),
+ ("https://altro.example.invalid/", CaptureRefusal.NotOnSite),
+ ($"http://{SiteHost}/verifica?motivo=prova", CaptureRefusal.CheckpointPage),
+ ($"http://{SiteHost}/accesso/", CaptureRefusal.CheckpointPage),
+ ($"http://{SiteHost}/sessione-scaduta", CaptureRefusal.CheckpointPage),
+ })
+ {
+ var cdp = Page(url);
+ var result = await SessionCapture.CaptureAsync(cdp, Plan, new VirtualClock(), CancellationToken.None);
+ Assert.IsNull(result.Values, url);
+ Assert.AreEqual(refusal, result.Refusal, url);
+ CollectionAssert.AreEqual(new[] { "Page.getFrameTree" }, cdp.Sent.Select(c => c.Method).ToArray(), url);
+ }
+ }
+
+ [TestMethod]
+ public async Task ABrowserErrorOrNoUserAgentRefusesWithoutThePageText()
+ {
+ var failing = Page($"http://{SiteHost}/");
+ failing.Responder = (method, parameters) => method switch
+ {
+ "Page.getFrameTree" => Frame($"http://{SiteHost}/"),
+ "Runtime.evaluate" => new JsonObject { ["exceptionDetails"] = new JsonObject { ["text"] = "lsd-segreto è nella pagina" } },
+ _ => Cookies(),
+ };
+ var error = await SessionCapture.CaptureAsync(failing, Plan, new VirtualClock(), CancellationToken.None);
+ Assert.AreEqual(CaptureRefusal.BrowserError, error.Refusal);
+ AssertNoSecret(error.ToString());
+
+ var page = PageValues();
+ page["ua"] = null;
+ var noAgent = await SessionCapture.CaptureAsync(Page($"http://{SiteHost}/", page: page), Plan, new VirtualClock(), CancellationToken.None);
+ Assert.AreEqual(CaptureRefusal.NoUserAgent, noAgent.Refusal);
+
+ var thrower = new ThrowingCdp();
+ var gone = await SessionCapture.CaptureAsync(thrower, Plan, new VirtualClock(), CancellationToken.None);
+ Assert.AreEqual(CaptureRefusal.BrowserError, gone.Refusal);
+ }
+
+ [TestMethod]
+ public async Task TheCopierSavesReplacesOrThrowsAwayAndItsLogAndTextsHoldNoValue()
+ {
+ var log = new List();
+ var store = new InMemorySiteSession(null);
+ var copier = new BrowserSessionCopier(Page($"http://{SiteHost}/"), Plan, store, new VirtualClock(), log.Add);
+
+ var first = await copier.CopyAsync(() => true, CancellationToken.None);
+ Assert.AreEqual(SessionCopyStatus.Saved, first.Status);
+ var saved = store.Read()!;
+ Assert.AreEqual("valore-sessione-segreto", saved.Cookie("sessione_prova"));
+
+ // A second copy replaces the session with a new capture; one the page stopped being Alberto's meanwhile is thrown away.
+ var second = await copier.CopyAsync(() => true, CancellationToken.None);
+ Assert.AreEqual(SessionCopyStatus.Saved, second.Status);
+ Assert.AreNotEqual(saved.Capture, store.Read()!.Capture, "a new login replaces the session (§6.0)");
+ var kept = store.Read();
+ var late = await copier.CopyAsync(() => false, CancellationToken.None);
+ Assert.AreEqual(SessionCopyStatus.Discarded, late.Status);
+ Assert.AreSame(kept, store.Read(), "a copy thrown away touches nothing");
+
+ // Not on the site: refused, the saved session stays.
+ var away = new BrowserSessionCopier(Page("about:blank"), Plan, store, new VirtualClock(), log.Add);
+ Assert.AreEqual(CaptureRefusal.NotOnSite, (await away.CopyAsync(() => true, CancellationToken.None)).Refusal);
+ Assert.AreSame(kept, store.Read());
+
+ Assert.HasCount(4, log);
+ foreach (var text in log.Append(saved.ToString()).Append(first.ToString()).Append(Plan.ToString()).Append(saved.Cookies[0].ToString()))
+ {
+ AssertNoSecret(text);
+ }
+
+ StringAssert.Contains(log[0], "Sessione copiata: 3 cookie");
+ }
+
+ [TestMethod]
+ public async Task TheCopierCountsAsMissingOnlyWhatAConfiguredOperationSends()
+ {
+ // The test site's catalog with its GraphQL query not configured: only the plain operations remain, which send
+ // app_id and the user agent; rev, hsi and the query's doc_id are read but no configured request waits for them.
+ var file = JsonNode.Parse(SiteMap.ReadEmbeddedText("richieste.prova.json"))!.AsObject();
+ var query = file["operations"]!.AsArray().Select(o => o!.AsObject()).Single(o => o["name"]!.GetValue() == "ProvaProfiloQuery");
+ query["configured"] = false;
+ query["reason"] = "Non configurata per la prova.";
+ var plan = SessionCapturePlan.For(Site, RequestCatalog.Parse(file.ToJsonString(), "richieste.prova.json (prova)"), SignalRules.LoadTestSite());
+ CollectionAssert.AreEquivalent(new[] { "app_id" }, plan.NeededValues.ToArray());
+ Assert.IsEmpty(plan.NeededDocIds);
+ CollectionAssert.Contains(Plan.NeededDocIds.ToArray(), "ProvaProfiloQuery", "configured in the shipped test catalog");
+
+ var page = PageValues();
+ ((JsonObject)page["values"]!).Remove("hsi");
+ ((JsonObject)page["values"]!).Remove("rev");
+ ((JsonObject)page["docIds"]!).Remove("ProvaProfiloQuery");
+ var log = new List();
+ var unused = await new BrowserSessionCopier(Page($"http://{SiteHost}/", page: page), plan, new InMemorySiteSession(null), new VirtualClock(), log.Add)
+ .CopyAsync(() => true, CancellationToken.None);
+ Assert.AreEqual(SessionCopyStatus.Saved, unused.Status);
+ Assert.AreEqual(0, unused.MissingValues + unused.MissingDocIds, "nothing a configured request sends is missing");
+ StringAssert.Contains(log[^1], "che nessuna operazione configurata usa");
+
+ ((JsonObject)page["values"]!).Remove("app_id");
+ var needed = await new BrowserSessionCopier(Page($"http://{SiteHost}/", page: page), plan, new InMemorySiteSession(null), new VirtualClock(), log.Add)
+ .CopyAsync(() => true, CancellationToken.None);
+ Assert.AreEqual(1, needed.MissingValues);
+ Assert.AreEqual(0, needed.MissingDocIds);
+ StringAssert.Contains(log[^1], "mancano app_id, che servono alle operazioni configurate");
+
+ // With the shipped catalog the query is configured: its doc_id counts.
+ var shipped = await new BrowserSessionCopier(Page($"http://{SiteHost}/", page: page), Plan, new InMemorySiteSession(null), new VirtualClock(), log.Add)
+ .CopyAsync(() => true, CancellationToken.None);
+ Assert.AreEqual(3, shipped.MissingValues, "app_id, hsi and rev");
+ Assert.AreEqual(1, shipped.MissingDocIds);
+ AssertNoSecret(string.Join("\n", log));
+ }
+
+ [TestMethod]
+ [Timeout(20_000, CooperativeCancellation = true)]
+ public async Task ABrowserThatDoesNotAnswerIsABrowserErrorAfterTheTimeout()
+ {
+ var store = new InMemorySiteSession(null);
+ var copier = new BrowserSessionCopier(new HangingCdp(), Plan, store, new VirtualClock(), _ => { }) { Timeout = TimeSpan.FromMilliseconds(200) };
+ var outcome = await copier.CopyAsync(() => true, CancellationToken.None);
+ Assert.AreEqual(SessionCopyStatus.Refused, outcome.Status);
+ Assert.AreEqual(CaptureRefusal.BrowserError, outcome.Refusal);
+ Assert.IsNull(store.Read());
+ }
+
+ private static int CountOf(string text, string part)
+ {
+ var count = 0;
+ for (var at = text.IndexOf(part, StringComparison.Ordinal); at >= 0; at = text.IndexOf(part, at + part.Length, StringComparison.Ordinal))
+ {
+ count++;
+ }
+
+ return count;
+ }
+
+ private static void AssertNoSecret(string text)
+ {
+ foreach (var secret in Secrets)
+ {
+ Assert.DoesNotContain(secret, text);
+ }
+ }
+
+ /// A page at that answers the three commands of the copy.
+ private static FakeCdpSession Page(string url, JsonArray? cookies = null, JsonObject? page = null)
+ {
+ var cdp = new FakeCdpSession(new VirtualClock());
+ cdp.Responder = (method, _) => method switch
+ {
+ "Page.getFrameTree" => Frame(url),
+ "Network.getCookies" => cookies is null ? Cookies() : new JsonObject { ["cookies"] = JsonNode.Parse(cookies.ToJsonString()) },
+ "Runtime.evaluate" => new JsonObject { ["result"] = new JsonObject { ["type"] = "object", ["value"] = JsonNode.Parse((page ?? PageValues()).ToJsonString()) } },
+ _ => null,
+ };
+ return cdp;
+ }
+
+ private static JsonObject Frame(string url) =>
+ new() { ["frameTree"] = new JsonObject { ["frame"] = new JsonObject { ["id"] = "F1", ["url"] = url } } };
+
+ private static JsonObject Cookies() => new()
+ {
+ ["cookies"] = new JsonArray(
+ Cookie("sessione_prova", "valore-sessione-segreto", "127.0.0.1"),
+ Cookie("csrftoken", "valore-csrf-segreto", "127.0.0.1"),
+ Cookie("percorso_api", "valore-api-segreto", "127.0.0.1", "/api/")),
+ };
+
+ private static JsonObject Cookie(string name, string value, string domain, string path = "/", bool secure = false, long? expires = null, bool partitioned = false)
+ {
+ var cookie = new JsonObject
+ {
+ ["name"] = name,
+ ["value"] = value,
+ ["domain"] = domain,
+ ["path"] = path,
+ ["expires"] = expires ?? -1,
+ ["session"] = expires is null,
+ ["secure"] = secure,
+ ["httpOnly"] = true,
+ };
+ if (partitioned)
+ {
+ cookie["partitionKey"] = new JsonObject { ["topLevelSite"] = "http://esempio.invalid", ["hasCrossSiteAncestor"] = false };
+ }
+
+ return cookie;
+ }
+
+ private static JsonObject PageValues() => new()
+ {
+ ["ua"] = UserAgent,
+ ["values"] = new JsonObject
+ {
+ ["lsd"] = "lsd-segreto",
+ ["fb_dtsg"] = "dtsg-di-prova",
+ ["account_id"] = "1234",
+ ["app_id"] = "applicazione",
+ ["rev"] = "revisione",
+ ["hs"] = "hs",
+ ["hsi"] = "hsi",
+ ["dpr"] = "1",
+ ["comet_req"] = "7",
+ ["ccg"] = "BUONA",
+ ["entry_nonce"] = "nonce-segreto",
+ ["estraneo"] = "non chiesto",
+ },
+ ["docIds"] = new JsonObject { ["ProvaProfiloQuery"] = "9000000000000009", ["AltraQuery"] = "1" },
+ };
+
+ /// A browser that went away: every command fails.
+ private sealed class ThrowingCdp : ICdpSession
+ {
+ public Task SendAsync(string method, object? parameters = null, CancellationToken ct = default) =>
+ throw new CdpDisconnectedException();
+
+ public IDisposable On(string eventName, Action handler) => throw new NotSupportedException();
+ }
+
+ /// A browser that never answers until cancelled.
+ private sealed class HangingCdp : ICdpSession
+ {
+ public async Task SendAsync(string method, object? parameters = null, CancellationToken ct = default)
+ {
+ await Task.Delay(Timeout.Infinite, ct);
+ return default;
+ }
+
+ public IDisposable On(string eventName, Action handler) => throw new NotSupportedException();
+ }
+}
diff --git a/tests/Febe.Tests/Collection/FileSiteSessionTests.cs b/tests/Febe.Tests/Collection/FileSiteSessionTests.cs
new file mode 100644
index 0000000..040e4f8
--- /dev/null
+++ b/tests/Febe.Tests/Collection/FileSiteSessionTests.cs
@@ -0,0 +1,393 @@
+using System.Collections.Concurrent;
+using System.Security.Cryptography;
+using System.Text;
+using Febe.Core.Collection.Requests;
+using Febe.Core.Library;
+using Febe.Core.Security;
+using Febe.Tests.Support;
+
+namespace Febe.Tests.Collection;
+
+///
+/// The saved session on disk (issue #36, S4, spec §6.0, §13.2): Dati/sessione/sessione.json encrypted, owner-only,
+/// replaced at once; read back by a new start as a new capture; renewals serialised and kept in memory when the disk
+/// refuses them; «Scollega» deletes it for good; a file that cannot be read is no session, never a crash; no value in
+/// clear on disk, in a text or in a log line.
+///
+[TestClass]
+public sealed class FileSiteSessionTests
+{
+ private static readonly DateTimeOffset Now = new(2026, 11, 17, 10, 0, 0, TimeSpan.Zero);
+ private static readonly Uri Graph = new("https://www.instagram.com/api/graphql");
+
+ private static readonly string[] Secrets =
+ [
+ "segreto-sessione-1", "segreto-csrf-2", "segreto-percorso-3", "segreto-lsd-4", "segreto-dtsg-5", "segreto-rev-6",
+ "segreto-nonce-7", "segreto-docid-8", "segreto-agente-9", "segreto-claim-10",
+ ];
+
+ [TestMethod]
+ public async Task WhatIsWrittenIsReadBackByANewInstance()
+ {
+ using var folder = new TempFolder("sessione");
+ var layout = new DataFolderLayout(folder.Path);
+ var protector = Protector();
+ var store = new FileSiteSession(layout.SessionFile, protector);
+ Assert.AreEqual(SavedSessionState.None, store.State);
+ Assert.IsNull(store.Read());
+
+ var values = Values();
+ Assert.IsTrue(await store.ReplaceAsync(values, CancellationToken.None));
+ Assert.AreSame(values, store.Read());
+ Assert.AreEqual(SavedSessionState.Present, store.State);
+ Assert.IsFalse(store.Unsaved);
+ Assert.AreEqual(Path.Combine(folder.Path, "sessione", "sessione.json"), store.FilePath, "Dati/sessione/sessione.json.");
+
+ var restored = new FileSiteSession(layout.SessionFile, protector).Read();
+ Assert.IsNotNull(restored);
+ Assert.AreEqual(SavedSessionState.Present, new FileSiteSession(layout.SessionFile, protector).State);
+ CollectionAssert.AreEqual(
+ values.Cookies.Select(Describe).ToArray(),
+ restored.Cookies.Select(Describe).ToArray(),
+ "Name, value, domain, host-only, path, secure, HTTP-only and expiry, in order.");
+ Assert.AreEqual(values.UserAgent, restored.UserAgent);
+ CollectionAssert.AreEquivalent(values.Fields.ToArray(), restored.Fields.ToArray());
+ CollectionAssert.AreEquivalent(values.DocIds.ToArray(), restored.DocIds.ToArray());
+ Assert.AreEqual(values.CopiedAt, restored.CopiedAt);
+ Assert.AreEqual("segreto-percorso-3", restored.CookieFor("ds_user_id", Graph, Now), "The path cookie still goes to /api/.");
+ Assert.IsNull(restored.CookieFor("ds_user_id", new Uri("https://www.instagram.com/marta/"), Now));
+ }
+
+ [TestMethod]
+ public async Task AValueReadBackIsANewCaptureSoALateRenewalOfTheOldProcessTouchesNothing()
+ {
+ using var folder = new TempFolder("sessione");
+ var file = Path.Combine(folder.Path, "sessione", "sessione.json");
+ var protector = Protector();
+ var before = new FileSiteSession(file, protector);
+ var values = Values();
+ await before.ReplaceAsync(values, CancellationToken.None);
+
+ var after = new FileSiteSession(file, protector);
+ var restored = after.Read()!;
+ Assert.AreNotEqual(values.Capture, restored.Capture, "A new start is a new capture.");
+ Assert.AreNotEqual(restored.Capture, new SiteSessionValues([], "agente").Capture, "And later captures never reuse its id.");
+
+ await after.UpdateAsync(new SiteSessionUpdate([Cookie("sessionid", "vecchia-risposta")], capture: values.Capture), CancellationToken.None);
+ Assert.AreEqual("segreto-sessione-1", after.Read()!.Cookie("sessionid"));
+ Assert.AreEqual("segreto-sessione-1", new FileSiteSession(file, protector).Read()!.Cookie("sessionid"), "Nor the file.");
+ }
+
+ [TestMethod]
+ public async Task TheFileHoldsNoValueInClear()
+ {
+ using var folder = new TempFolder("sessione");
+ var file = Path.Combine(folder.Path, "sessione.json");
+ var store = new FileSiteSession(file, Protector());
+ await store.ReplaceAsync(Values(), CancellationToken.None);
+
+ var bytes = File.ReadAllBytes(file);
+ Assert.AreEqual("FEBS", Encoding.ASCII.GetString(bytes, 0, 4));
+ foreach (var secret in Secrets.Append("sessionid").Append("instagram"))
+ {
+ foreach (var form in new[] { Encoding.UTF8.GetBytes(secret), Encoding.Unicode.GetBytes(secret), Encoding.ASCII.GetBytes(Convert.ToBase64String(Encoding.UTF8.GetBytes(secret))) })
+ {
+ Assert.AreEqual(-1, bytes.AsSpan().IndexOf(form), $"«{secret}» is on disk in clear.");
+ }
+ }
+ }
+
+ [TestMethod]
+ public async Task AFailedWriteKeepsTheRenewedCookiesInMemoryAndIsTriedAgainLater()
+ {
+ using var folder = new TempFolder("sessione");
+ var file = Path.Combine(folder.Path, "sessione.json");
+ var protector = new FlakyProtector(Protector());
+ var log = new ConcurrentQueue();
+ var store = new FileSiteSession(file, protector, log.Enqueue);
+ await store.ReplaceAsync(Values(), CancellationToken.None);
+ var capture = store.Read()!.Capture;
+
+ // The site rotated csrftoken: the disk refuses, the memory keeps the new value (the old one no longer works).
+ protector.Fail = true;
+ await store.UpdateAsync(new SiteSessionUpdate([Csrf("segreto-rinnovo-11")], capture: capture), CancellationToken.None);
+ await store.UpdateAsync(new SiteSessionUpdate([Csrf("segreto-rinnovo-12")], capture: capture), CancellationToken.None);
+ Assert.AreEqual("segreto-rinnovo-12", store.Read()!.Cookie("csrftoken"));
+ Assert.IsTrue(store.Unsaved);
+ Assert.AreEqual("segreto-csrf-2", new FileSiteSession(file, Protector(protector)).Read()!.Cookie("csrftoken"), "The file is the old one, whole.");
+ Assert.AreEqual(1, log.Count(l => l.Contains("non scritta", StringComparison.Ordinal)), "One line for a run of failures:\n" + string.Join("\n", log));
+ Assert.IsFalse(Directory.GetFiles(folder.Path).Any(f => f.EndsWith(OwnerOnlyFiles.PartSuffix, StringComparison.Ordinal)));
+
+ // A failed copy at «Ho finito» still replaces the session in memory, and says it is not on disk.
+ Assert.IsFalse(await store.ReplaceAsync(Values(csrf: "segreto-nuovo-accesso-13"), CancellationToken.None));
+ Assert.AreEqual("segreto-nuovo-accesso-13", store.Read()!.Cookie("csrftoken"));
+ capture = store.Read()!.Capture;
+
+ protector.Fail = false;
+ await store.UpdateAsync(new SiteSessionUpdate([Cookie("mid", "segreto-mid-14")], capture: capture), CancellationToken.None);
+ Assert.IsFalse(store.Unsaved);
+ var reread = new FileSiteSession(file, Protector(protector)).Read()!;
+ Assert.AreEqual("segreto-nuovo-accesso-13", reread.Cookie("csrftoken"), "The next write carries everything kept in memory.");
+ Assert.AreEqual("segreto-mid-14", reread.Cookie("mid"));
+ Assert.IsTrue(log.Any(l => l.Contains("di nuovo", StringComparison.Ordinal)));
+ AssertNoSecret(log);
+ }
+
+ [TestMethod]
+ public async Task AWriteTheDiskRefusesAfterEncryptionLeavesNoPartFileKeepsTheMemoryAndTheNextWriteSucceeds()
+ {
+ using var folder = new TempFolder("sessione");
+ var file = Path.Combine(folder.Path, "sessione.json");
+ var protector = Protector();
+ var log = new ConcurrentQueue();
+ var store = new FileSiteSession(file, protector, log.Enqueue);
+
+ // Something the rename cannot replace stands where the session goes: the part file is written, the move fails.
+ Directory.CreateDirectory(file);
+ Assert.IsFalse(await store.ReplaceAsync(Values(), CancellationToken.None));
+ Assert.IsTrue(store.Unsaved);
+ Assert.AreEqual("segreto-csrf-2", store.Read()!.Cookie("csrftoken"), "Kept in memory.");
+ Assert.IsEmpty(Directory.GetFiles(folder.Path, "*" + OwnerOnlyFiles.PartSuffix), "A failed write leaves no part file.");
+ Assert.AreEqual(1, log.Count(l => l.Contains("non scritta", StringComparison.Ordinal)), string.Join("\n", log));
+
+ // The obstacle goes: the next write carries what memory kept.
+ Directory.Delete(file);
+ var capture = store.Read()!.Capture;
+ await store.UpdateAsync(new SiteSessionUpdate([Cookie("mid", "segreto-mid-14")], capture: capture), CancellationToken.None);
+ Assert.IsFalse(store.Unsaved);
+ var reread = new FileSiteSession(file, protector).Read()!;
+ Assert.AreEqual("segreto-csrf-2", reread.Cookie("csrftoken"));
+ Assert.AreEqual("segreto-mid-14", reread.Cookie("mid"));
+
+ if (OperatingSystem.IsWindows())
+ {
+ // On Windows a file held open without sharing cannot be replaced: the old file stays whole.
+ var before = File.ReadAllBytes(file);
+ using (new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.None))
+ {
+ await store.UpdateAsync(new SiteSessionUpdate([Cookie("mid", "segreto-mid-15")], capture: capture), CancellationToken.None);
+ }
+
+ Assert.IsTrue(store.Unsaved);
+ CollectionAssert.AreEqual(before, File.ReadAllBytes(file), "The old file is intact.");
+ Assert.IsEmpty(Directory.GetFiles(folder.Path, "*" + OwnerOnlyFiles.PartSuffix));
+ }
+
+ AssertNoSecret(log);
+ }
+
+ [TestMethod]
+ public async Task ConcurrentUpdatesAreSerializedAndNoneIsLost()
+ {
+ using var folder = new TempFolder("sessione");
+ var file = Path.Combine(folder.Path, "sessione.json");
+ var protector = Protector();
+ var store = new FileSiteSession(file, protector);
+ await store.ReplaceAsync(Values(), CancellationToken.None);
+ var capture = store.Read()!.Capture;
+
+ await Task.WhenAll(Enumerable.Range(0, 40).Select(i => Task.Run(() =>
+ store.UpdateAsync(new SiteSessionUpdate([Cookie("c" + i.ToString(System.Globalization.CultureInfo.InvariantCulture), "v")], capture: capture), CancellationToken.None))));
+
+ Assert.AreEqual(Values().Cookies.Count + 40, store.Read()!.Cookies.Count);
+ Assert.AreEqual(Values().Cookies.Count + 40, new FileSiteSession(file, protector).Read()!.Cookies.Count, "The last write holds every update.");
+ }
+
+ [TestMethod]
+ public async Task DeleteRemovesTheFileAndItsLeftoversAndNoLateUpdateBringsItBack()
+ {
+ using var folder = new TempFolder("sessione");
+ var file = Path.Combine(folder.Path, "sessione.json");
+ var protector = new FlakyProtector(Protector());
+ var log = new List();
+ var store = new FileSiteSession(file, protector, log.Add);
+ await store.ReplaceAsync(Values(), CancellationToken.None);
+ var capture = store.Read()!.Capture;
+ File.WriteAllText(file + ".1234abcd" + OwnerOnlyFiles.PartSuffix, "resto");
+
+ // An update waits behind a write that is in progress; «Scollega» comes; whatever the order they get the gate
+ // in, no session is left.
+ using var hold = new ManualResetEventSlim(false);
+ protector.Hold = hold;
+ var replacing = Task.Run(() => store.ReplaceAsync(store.Read()!, CancellationToken.None));
+ Assert.IsTrue(protector.Entered.Wait(TimeSpan.FromSeconds(30)));
+ var updating = store.UpdateAsync(new SiteSessionUpdate([Cookie("tardivo", "x")], capture: capture), CancellationToken.None);
+ var deleting = store.DeleteAsync(CancellationToken.None);
+ hold.Set();
+ await Task.WhenAll(replacing, updating, deleting);
+ await store.UpdateAsync(new SiteSessionUpdate([Cookie("tardivo", "y")], capture: capture), CancellationToken.None);
+
+ Assert.IsNull(store.Read());
+ Assert.AreEqual(SavedSessionState.None, store.State);
+ Assert.IsFalse(File.Exists(file));
+ Assert.AreEqual(0, Directory.GetFiles(folder.Path).Length, "No part file left either.");
+ Assert.IsNull(new FileSiteSession(file, protector).Read());
+ Assert.IsTrue(log.Any(l => l.Contains("cancellata", StringComparison.Ordinal)));
+
+ await store.DeleteAsync(CancellationToken.None);
+ }
+
+ [TestMethod]
+ public async Task AnUnreadableFileIsNoSessionAndIsLeftAsItIs()
+ {
+ using var folder = new TempFolder("sessione");
+ var file = Path.Combine(folder.Path, "sessione.json");
+ var protector = Protector();
+ await new FileSiteSession(file, protector).ReplaceAsync(Values(), CancellationToken.None);
+ var written = File.ReadAllBytes(file);
+
+ // Another key (a new FEBE_CHIAVE_SESSIONE, another user for DPAPI), a damaged file, another format.
+ var cases = new (string File, ISessionProtector Protector, byte[] Bytes)[]
+ {
+ (file, Protector(), written),
+ (Path.Combine(folder.Path, "rovinato.json"), protector, [.. written.Take(written.Length - 3)]),
+ (Path.Combine(folder.Path, "testo.json"), protector, Encoding.UTF8.GetBytes("""{"format":1,"cookies":[]}""")),
+ (Path.Combine(folder.Path, "formato.json"), protector, protector.Protect(Encoding.UTF8.GetBytes("""{"format":9,"segreto":"segreto-formato-15"}"""))),
+ (Path.Combine(folder.Path, "cookie.json"), protector, protector.Protect(Encoding.UTF8.GetBytes("""{"format":1,"userAgent":"a","cookies":[{"name":"a=b","value":"segreto-cookie-16","domain":"x","hostOnly":true,"path":"/","secure":false,"httpOnly":false}],"fields":{},"docIds":{}}"""))),
+ };
+ foreach (var (path, reader, bytes) in cases)
+ {
+ if (path != file)
+ {
+ File.WriteAllBytes(path, bytes);
+ }
+
+ var log = new List();
+ var store = new FileSiteSession(path, reader, log.Add);
+ Assert.IsNull(store.Read(), path);
+ Assert.AreEqual(SavedSessionState.Unreadable, store.State, path);
+ CollectionAssert.AreEqual(bytes, File.ReadAllBytes(path), "Left as it is.");
+ Assert.AreEqual(1, log.Count);
+ StringAssert.Contains(log[0], "illeggibile");
+ Assert.IsFalse(log[0].Contains("segreto", StringComparison.Ordinal) || log[0].Contains(path, StringComparison.Ordinal), log[0]);
+ Assert.AreEqual("Sessione salvata illeggibile.", store.ToString());
+
+ // A renewal finds no session; a new login replaces the file.
+ await store.UpdateAsync(new SiteSessionUpdate([Cookie("x", "y")]), CancellationToken.None);
+ Assert.IsNull(store.Read());
+ Assert.IsTrue(await store.ReplaceAsync(Values(), CancellationToken.None));
+ Assert.AreEqual(SavedSessionState.Present, new FileSiteSession(path, reader).State);
+ }
+ }
+
+ [TestMethod]
+ public async Task TheFolderAndTheFileAreOwnerOnlyOnUnix()
+ {
+ using var folder = new TempFolder("sessione");
+ var layout = new DataFolderLayout(folder.Path);
+ await new FileSiteSession(layout.SessionFile, Protector()).ReplaceAsync(Values(), CancellationToken.None);
+
+ Assert.IsTrue(File.Exists(layout.SessionFile));
+ Assert.AreEqual(layout.Session, Path.GetDirectoryName(layout.SessionFile));
+ Assert.AreEqual(layout.Session, Path.GetDirectoryName(layout.SessionKeyFile));
+ if (!OperatingSystem.IsWindows())
+ {
+ Assert.AreEqual(OwnerOnlyFiles.OwnerFile, File.GetUnixFileMode(layout.SessionFile));
+ Assert.AreEqual(OwnerOnlyFiles.OwnerFolder, File.GetUnixFileMode(layout.Session));
+ }
+
+ // The daily copies and the diagnostic report live elsewhere and never look in Dati/sessione.
+ Assert.IsFalse(layout.Session.StartsWith(layout.Backups, StringComparison.Ordinal));
+ Assert.IsFalse(layout.Session.StartsWith(layout.Diagnostics, StringComparison.Ordinal));
+ }
+
+ [TestMethod]
+ public async Task TheTextAndTheLogLinesShowCountsOnly()
+ {
+ using var folder = new TempFolder("sessione");
+ var file = Path.Combine(folder.Path, "sessione.json");
+ var log = new List();
+ var protector = Protector();
+ var store = new FileSiteSession(file, protector, log.Add);
+ Assert.AreEqual("Nessuna sessione salvata.", store.ToString());
+ await store.ReplaceAsync(Values(), CancellationToken.None);
+ await store.UpdateAsync(new SiteSessionUpdate([Csrf("segreto-rinnovo-17")], claim: "segreto-claim-18"), CancellationToken.None);
+ _ = new FileSiteSession(file, protector, log.Add);
+ await store.DeleteAsync(CancellationToken.None);
+
+ var texts = log.Append(store.ToString()).Append(protector.ToString()).ToList();
+ AssertNoSecret(texts);
+ foreach (var text in texts)
+ {
+ Assert.IsFalse(text.Contains("csrftoken", StringComparison.Ordinal) || text.Contains(folder.Path, StringComparison.Ordinal), text);
+ }
+
+ Assert.IsTrue(log.Any(l => l.Contains("Sessione salvata scritta: 4 cookie", StringComparison.Ordinal)), string.Join("\n", log));
+ Assert.IsTrue(log.Any(l => l.Contains("Sessione salvata letta", StringComparison.Ordinal)));
+ }
+
+ /// A session with a cookie of each kind, every page value and a doc_id; values from .
+ private static SiteSessionValues Values(string csrf = "segreto-csrf-2") => new(
+ [
+ new SiteCookie("sessionid", "segreto-sessione-1", ".instagram.com", "/", hostOnly: false, secure: true, httpOnly: true, expires: Now.AddDays(365)),
+ Csrf(csrf),
+ SiteCookie.ForHost("ds_user_id", "segreto-percorso-3", "www.instagram.com", "/api/", secure: true),
+ SiteCookie.ForHost("rur", "\"CLN\\054segreto\"", "www.instagram.com"),
+ ],
+ "Mozilla/5.0 segreto-agente-9",
+ new Dictionary
+ {
+ ["lsd"] = "segreto-lsd-4", ["fb_dtsg"] = "segreto-dtsg-5", ["rev"] = "segreto-rev-6", ["entry_nonce"] = "segreto-nonce-7",
+ ["claim"] = "segreto-claim-10", ["dpr"] = "2",
+ },
+ new Dictionary { ["PolarisProfilePostsQuery"] = "segreto-docid-8" },
+ Now);
+
+ /// The csrftoken of Instagram as the browser keeps it (Domain=.instagram.com, secure): a renewal has the same key.
+ private static SiteCookie Csrf(string value) =>
+ new("csrftoken", value, ".instagram.com", "/", hostOnly: false, secure: true, expires: Now.AddDays(30));
+
+ private static SiteCookie Cookie(string name, string value) => SiteCookie.ForHost(name, value, "www.instagram.com");
+
+ private static string Describe(SiteCookie c) => $"{c.Name}|{c.Value}|{c.Domain}|{c.HostOnly}|{c.Path}|{c.Secure}|{c.HttpOnly}|{c.Expires:O}";
+
+ private static readonly ConcurrentDictionary Keys = new();
+
+ /// A protector with a key made now (never a key in the repository).
+ private static AesGcmSessionProtector Protector()
+ {
+ var key = RandomNumberGenerator.GetBytes(SessionKey.Length);
+ var protector = new AesGcmSessionProtector(key);
+ Keys[protector] = key;
+ return protector;
+ }
+
+ /// Another protector with the same key as 's.
+ private static AesGcmSessionProtector Protector(FlakyProtector flaky) => new(Keys[flaky.Inner]);
+
+ private static void AssertNoSecret(IEnumerable texts)
+ {
+ foreach (var text in texts)
+ {
+ Assert.IsFalse(text.Contains("segreto", StringComparison.Ordinal), text);
+ }
+ }
+
+ /// A protector that can refuse to write (as a full or read-only disk would) or hold a write halfway.
+ private sealed class FlakyProtector(AesGcmSessionProtector inner) : ISessionProtector
+ {
+ public AesGcmSessionProtector Inner => inner;
+
+ public bool Fail { get; set; }
+
+ public ManualResetEventSlim? Hold { get; set; }
+
+ public ManualResetEventSlim Entered { get; } = new(false);
+
+ public string Scheme => inner.Scheme;
+
+ public byte[] Protect(ReadOnlySpan plain)
+ {
+ if (Hold is { } hold)
+ {
+ Hold = null;
+ Entered.Set();
+ hold.Wait(TimeSpan.FromSeconds(30));
+ }
+
+ return Fail ? throw new IOException("Disco pieno.") : inner.Protect(plain);
+ }
+
+ public byte[] Unprotect(ReadOnlySpan blob) => inner.Unprotect(blob);
+ }
+}
diff --git a/tests/Febe.Tests/Collection/HttpSiteRequesterShapeTests.cs b/tests/Febe.Tests/Collection/HttpSiteRequesterShapeTests.cs
index 9a56fce..b99f8b0 100644
--- a/tests/Febe.Tests/Collection/HttpSiteRequesterShapeTests.cs
+++ b/tests/Febe.Tests/Collection/HttpSiteRequesterShapeTests.cs
@@ -58,17 +58,19 @@ public sealed class HttpSiteRequesterShapeTests
Assert.AreEqual("POST /api/graphql HTTP/1.1", request.Line);
CollectionAssert.AreEquivalent(
- new[] { "host", "accept", "content-length", "content-type", "user-agent", "x-app-id", "x-csrftoken", "x-fb-friendly-name", "x-ig-www-claim", "cookie", "accept-encoding" },
+ new[] { "host", "accept", "content-length", "content-type", "user-agent", "x-app-id", "x-csrftoken", "x-fb-entry-nonce", "x-fb-friendly-name", "x-ig-www-claim", "cookie", "accept-encoding" },
request.Headers.Select(h => h.Name).ToArray());
+ Assert.AreEqual(TestSite.EntryNonce, request.Header("x-fb-entry-nonce"), "From the session (the page's BootloaderConfig.nonce on Instagram).");
Assert.AreEqual("application/x-www-form-urlencoded", request.Header("content-type"), "As the catalog writes it, no charset added.");
Assert.AreEqual(TestSite.ProfileQuery, request.Header("x-fb-friendly-name"));
Assert.AreEqual("0", request.Header("x-ig-www-claim"));
Assert.AreEqual(
- "av=17841400000000077&__a=1&fb_dtsg=dtsg-di-prova&lsd=lsd-di-prova&fb_api_req_friendly_name=ProvaProfiloQuery"
+ "av=17841400000000077&__a=1&__ccg=BUONA&__comet_req=7&__hs=hs-di-prova&__hsi=hsi-di-prova&__rev=revisione-di-prova&dpr=1"
+ + "&fb_dtsg=dtsg-di-prova&lsd=lsd-di-prova&fb_api_req_friendly_name=ProvaProfiloQuery"
+ "&variables=%7B%22username%22%3A%22marta.prova%22%2C%22scheda%22%3A%22post%22%2C%22primi%22%3A12%2C%22raccolte%22%3Atrue%7D"
+ "&doc_id=8000000000000001",
request.Body,
- "Fields in the order of the file; the variables as JSON.stringify writes them: 12 a number, true a boolean.");
+ "Fields in the order of the file, the version fields from the session; the variables as JSON.stringify writes them: 12 a number, true a boolean.");
Assert.AreEqual(Encoding.UTF8.GetByteCount(request.Body).ToString(System.Globalization.CultureInfo.InvariantCulture), request.Header("content-length"));
}
@@ -238,7 +240,7 @@ public sealed class HttpSiteRequesterShapeTests
using var listener = new OneShotListener("""{"profilo":{}}""");
// «rur» expired a minute ago: not in the cookie line.
- var session = new InMemorySiteSession(new SiteSessionValues(values.Cookies, values.UserAgent, values.Fields, values.DocIds, new Dictionary { ["rur"] = clock.Now.AddMinutes(-1) }));
+ var session = new InMemorySiteSession(new SiteSessionValues(Expiring(values, "rur", clock.Now.AddMinutes(-1)), values.UserAgent, values.Fields, values.DocIds));
using (var requester = new HttpSiteRequester(RequestCatalog.LoadTestSite(), session, HttpSiteRequesterOptions.TestSite(new Uri($"http://127.0.0.1:{listener.Port}/")), clock))
{
await requester.SendAsync(Profile(), Permit.Grant(ActionKind.ProfileOpen, null), CancellationToken.None);
@@ -246,7 +248,7 @@ public sealed class HttpSiteRequesterShapeTests
}
// The session cookie expired: nothing leaves, a Disconnessione.
- var expired = new InMemorySiteSession(new SiteSessionValues(values.Cookies, values.UserAgent, values.Fields, values.DocIds, new Dictionary { [TestSite.SessionCookie] = clock.Now }));
+ var expired = new InMemorySiteSession(new SiteSessionValues(Expiring(values, TestSite.SessionCookie, clock.Now), values.UserAgent, values.Fields, values.DocIds));
using var late = new HttpSiteRequester(RequestCatalog.LoadTestSite(), expired, HttpSiteRequesterOptions.TestSite(new Uri($"http://127.0.0.1:{listener.Port}/")), clock);
var refused = await Assert.ThrowsExactlyAsync(() => late.SendAsync(Profile(), Permit.Grant(ActionKind.ProfileOpen, null), CancellationToken.None));
Assert.AreEqual(TestSite.SessionCookie, refused.Missing);
@@ -290,8 +292,110 @@ public sealed class HttpSiteRequesterShapeTests
Assert.IsFalse(refusal.Contains("segreto", StringComparison.Ordinal) || refusal.Contains("proxy.example", StringComparison.Ordinal), "Never the value.");
}
+ [TestMethod]
+ public async Task TheCookieLineCarriesOnlyCookiesWhoseDomainAndPathMatchLongerPathsFirst()
+ {
+ using var listener = new OneShotListener("""{"profilo":{}}""");
+ var values = Session();
+ var cookies = values.Cookies.Concat(
+ [
+ SiteCookie.ForHost("percorso_api", "p", "127.0.0.1", "/api/"),
+ SiteCookie.ForHost("dati_lunghi", "d", "127.0.0.1", "/api/dati/"),
+ SiteCookie.ForHost("altrove", "a", "127.0.0.1", "/accesso/"),
+ SiteCookie.ForHost("quasi", "q", "127.0.0.1", "/ap"),
+ SiteCookie.ForHost("estraneo", "e", "altro.example"),
+ SiteCookie.ForHost("sicuro", "s", "127.0.0.1", secure: true),
+ ]);
+ using var requester = new HttpSiteRequester(RequestCatalog.LoadTestSite(), new InMemorySiteSession(new SiteSessionValues(cookies, values.UserAgent, values.Fields, values.DocIds)), HttpSiteRequesterOptions.TestSite(new Uri($"http://127.0.0.1:{listener.Port}/")), new VirtualClock());
+
+ await requester.SendAsync(Profile(), Permit.Grant(ActionKind.ProfileOpen, null), CancellationToken.None);
+
+ Assert.AreEqual(
+ "dati_lunghi=d; percorso_api=p; csrftoken=csrf-1; sessione_prova=attiva; rur=\"FRC\\05412\"",
+ (await listener.Request).Header("cookie"),
+ "Longer paths first, then the session's order; no other path, host, a «/ap» that is not a segment, nor a secure cookie over http.");
+ }
+
+ [TestMethod]
+ public async Task TheCsrfHeaderTakesTheCookieThatMatchesTheRequestPath()
+ {
+ using var listener = new OneShotListener("""{"profilo":{}}""");
+ var values = Session();
+ var cookies = values.Cookies.Append(SiteCookie.ForHost("csrftoken", "csrf-api", "127.0.0.1", "/api/"));
+ using var requester = new HttpSiteRequester(RequestCatalog.LoadTestSite(), new InMemorySiteSession(new SiteSessionValues(cookies, values.UserAgent, values.Fields, values.DocIds)), HttpSiteRequesterOptions.TestSite(new Uri($"http://127.0.0.1:{listener.Port}/")), new VirtualClock());
+
+ await requester.SendAsync(Profile(), Permit.Grant(ActionKind.ProfileOpen, null), CancellationToken.None);
+
+ var request = await listener.Request;
+ Assert.AreEqual("csrf-api", request.Header("x-csrftoken"), "The csrftoken the browser would send first to /api/.");
+ StringAssert.StartsWith(request.Header("cookie"), "csrftoken=csrf-api; csrftoken=csrf-1;");
+ }
+
+ [TestMethod]
+ public async Task ASessionCookieOfAnotherPathOrHostIsAMissingSession()
+ {
+ using var listener = new OneShotListener("""{"profilo":{}}""");
+ var values = Session();
+ foreach (var misplaced in new[]
+ {
+ SiteCookie.ForHost(TestSite.SessionCookie, SiteControl.InitialSession, "127.0.0.1", "/accesso/"),
+ SiteCookie.ForHost(TestSite.SessionCookie, SiteControl.InitialSession, "127.0.0.2"),
+ SiteCookie.ForHost(TestSite.SessionCookie, SiteControl.InitialSession, "127.0.0.1", secure: true),
+ })
+ {
+ var cookies = values.Cookies.Where(c => c.Name != TestSite.SessionCookie).Append(misplaced);
+ using var requester = new HttpSiteRequester(RequestCatalog.LoadTestSite(), new InMemorySiteSession(new SiteSessionValues(cookies, values.UserAgent, values.Fields, values.DocIds)), HttpSiteRequesterOptions.TestSite(new Uri($"http://127.0.0.1:{listener.Port}/")), new VirtualClock());
+ var refused = await Assert.ThrowsExactlyAsync(() => requester.SendAsync(Profile(), Permit.Grant(ActionKind.ProfileOpen, null), CancellationToken.None));
+ Assert.AreEqual(TestSite.SessionCookie, refused.Missing, misplaced.ToString());
+ }
+
+ Assert.AreEqual(0, listener.Connections, "Nothing left.");
+ }
+
+ [TestMethod]
+ [DataRow("rev", "__rev")]
+ [DataRow("hs", "__hs")]
+ [DataRow("hsi", "__hsi")]
+ [DataRow("dpr", "dpr")]
+ [DataRow("ccg", "__ccg")]
+ [DataRow("comet_req", "__comet_req")]
+ [DataRow("entry_nonce", "x-fb-entry-nonce")]
+ public async Task AVersionFieldTheSessionLacksStopsTheQueryBeforeItLeaves(string field, string missing)
+ {
+ using var listener = new OneShotListener("""{"profilo":{}}""");
+ var values = Session();
+ var fields = values.Fields.Where(f => f.Key != field).ToDictionary();
+ using var requester = new HttpSiteRequester(RequestCatalog.LoadTestSite(), new InMemorySiteSession(new SiteSessionValues(values.Cookies, values.UserAgent, fields, values.DocIds)), HttpSiteRequesterOptions.TestSite(new Uri($"http://127.0.0.1:{listener.Port}/")), new VirtualClock());
+
+ var refused = await Assert.ThrowsExactlyAsync(() => requester.SendAsync(SiteRequest.For(TestSite.ProfileQuery, (CaseValues.Username, "marta.prova")), Permit.Grant(ActionKind.ProfileOpen, null), CancellationToken.None));
+
+ Assert.AreEqual(missing, refused.Missing, "Never guessed (rule 9).");
+ Assert.AreEqual(0, listener.Connections);
+ }
+
+ [TestMethod]
+ public async Task ARenewalKeepsThePathAndDomainItWasSetWith()
+ {
+ using var listener = new OneShotListener("""{"profilo":{}}""", extraHeaders: "Set-Cookie: percorso_api=nuovo; Path=/api/\r\nSet-Cookie: senza_percorso=x\r\nSet-Cookie: csrftoken=csrf-2; Path=/\r\n");
+ var session = new InMemorySiteSession(Session());
+ using var requester = new HttpSiteRequester(RequestCatalog.LoadTestSite(), session, HttpSiteRequesterOptions.TestSite(new Uri($"http://127.0.0.1:{listener.Port}/")), new VirtualClock());
+
+ await requester.SendAsync(Profile(), Permit.Grant(ActionKind.ProfileOpen, null), CancellationToken.None);
+
+ var cookies = session.Read()!.Cookies;
+ CollectionAssert.AreEqual(
+ new[] { "csrftoken 127.0.0.1 / csrf-2", "sessione_prova 127.0.0.1 / attiva", "rur 127.0.0.1 / \"FRC\\05412\"", "percorso_api 127.0.0.1 /api/ nuovo", "senza_percorso 127.0.0.1 /api/dati/profilo x" },
+ cookies.Select(c => $"{c.Name} {c.Domain} {c.Path} {c.Value}").ToArray(),
+ "csrftoken renewed in place; the new ones host-only on the site, at their Path or at the default path of the request.");
+ Assert.IsTrue(cookies.All(c => c.HostOnly));
+ }
+
private static SiteRequest Profile() => SiteRequest.For("profilo", (CaseValues.Username, "marta.prova"));
+ /// The cookies of with expiring at .
+ private static IEnumerable Expiring(SiteSessionValues values, string name, DateTimeOffset at) =>
+ values.Cookies.Select(c => c.Name == name ? new SiteCookie(c.Name, c.Value, c.Domain, c.Path, c.HostOnly, c.Secure, c.HttpOnly, at) : c);
+
private static async Task WaitUntilAsync(Func condition)
{
using var limit = new CancellationTokenSource(TimeSpan.FromSeconds(30));
@@ -305,9 +409,13 @@ public sealed class HttpSiteRequesterShapeTests
new(RequestCatalog.LoadTestSite(), new InMemorySiteSession(Session()), HttpSiteRequesterOptions.TestSite(new Uri($"http://127.0.0.1:{port}/")), new VirtualClock());
private static SiteSessionValues Session() => new(
- [new("csrftoken", "csrf-1"), new(TestSite.SessionCookie, SiteControl.InitialSession), new("rur", "\"FRC\\05412\"")],
+ [
+ SiteCookie.ForHost("csrftoken", "csrf-1", "127.0.0.1"),
+ SiteCookie.ForHost(TestSite.SessionCookie, SiteControl.InitialSession, "127.0.0.1"),
+ SiteCookie.ForHost("rur", "\"FRC\\05412\"", "127.0.0.1"),
+ ],
UserAgent,
- new Dictionary { ["app_id"] = TestSite.AppId, ["lsd"] = TestSite.Lsd, ["fb_dtsg"] = TestSite.Dtsg, ["claim"] = "0", ["account_id"] = "17841400000000077" },
+ HttpSiteRequesterTests.PageValues(),
TestSite.DocIds);
/// The head and body of one HTTP/1.1 request, as they arrived.
diff --git a/tests/Febe.Tests/Collection/HttpSiteRequesterTests.cs b/tests/Febe.Tests/Collection/HttpSiteRequesterTests.cs
index b01556c..1e448b5 100644
--- a/tests/Febe.Tests/Collection/HttpSiteRequesterTests.cs
+++ b/tests/Febe.Tests/Collection/HttpSiteRequesterTests.cs
@@ -452,6 +452,7 @@ public sealed class HttpSiteRequesterTests
var secrets = new List
{
Csrf, OtherCookie, SiteControl.InitialSession, "rinnovata-1", "claim-prova-1", TestSite.AppId, TestSite.Lsd, TestSite.Dtsg, AccountId,
+ TestSite.Revision, TestSite.HasteSession, TestSite.HasteSessionId, TestSite.ConnectionClass, TestSite.EntryNonce,
TestSite.DocIds[TestSite.ProfileQuery], UserAgent, "Mozilla", "marta.prova", "luca.prova", "c12", "127.0.0.1", "scheda", "primi", "accesso", "next",
};
secrets.AddRange(cases.Values.SelectMany(c => c.Values.Values));
@@ -464,7 +465,7 @@ public sealed class HttpSiteRequesterTests
}
}
- private static Dictionary Values, string PagePath)> Cases(TestSite site)
+ internal static Dictionary Values, string PagePath)> Cases(TestSite site)
{
string code;
string highlight;
@@ -524,7 +525,7 @@ public sealed class HttpSiteRequesterTests
private static SiteRequest Profile() => SiteRequest.For("profilo", (CaseValues.Username, "marta.prova"));
- private static SiteRequest Graph() => SiteRequest.For(TestSite.ProfileQuery, (CaseValues.Username, "marta.prova"));
+ internal static SiteRequest Graph() => SiteRequest.For(TestSite.ProfileQuery, (CaseValues.Username, "marta.prova"));
private static SiteOperation Operation(string name) => Catalog.Operations.Single(o => o.Name == name);
@@ -542,25 +543,39 @@ public sealed class HttpSiteRequesterTests
/// The saved session of a test: the cookies, tokens and doc_id the pages of the test site hand out.
internal static SiteSessionValues Values(string? session = SiteControl.InitialSession, string? csrf = Csrf, string appId = TestSite.AppId, bool docIds = true)
{
- var cookies = new List>();
+ // Host-only cookies of the test site's host, path «/», as its pages set them.
+ var cookies = new List();
if (csrf is not null)
{
- cookies.Add(new(TestSite.CsrfCookie, csrf));
+ cookies.Add(SiteCookie.ForHost(TestSite.CsrfCookie, csrf, "127.0.0.1"));
}
if (session is not null)
{
- cookies.Add(new(TestSite.SessionCookie, session));
+ cookies.Add(SiteCookie.ForHost(TestSite.SessionCookie, session, "127.0.0.1"));
}
- cookies.Add(new("altro", OtherCookie));
- return new SiteSessionValues(
- cookies,
- UserAgent,
- new Dictionary { ["app_id"] = appId, ["lsd"] = TestSite.Lsd, ["fb_dtsg"] = TestSite.Dtsg, ["claim"] = "0", ["account_id"] = AccountId },
- docIds ? TestSite.DocIds : null);
+ cookies.Add(SiteCookie.ForHost("altro", OtherCookie, "127.0.0.1"));
+ return new SiteSessionValues(cookies, UserAgent, PageValues(appId), docIds ? TestSite.DocIds : null);
}
+ /// The values the pages of the test site hold (the «page» section of richieste.prova.json), and the claim.
+ internal static Dictionary PageValues(string appId = TestSite.AppId) => new()
+ {
+ ["app_id"] = appId,
+ ["lsd"] = TestSite.Lsd,
+ ["fb_dtsg"] = TestSite.Dtsg,
+ ["claim"] = "0",
+ ["account_id"] = AccountId,
+ ["rev"] = TestSite.Revision,
+ ["hs"] = TestSite.HasteSession,
+ ["hsi"] = TestSite.HasteSessionId,
+ ["dpr"] = TestSite.Dpr,
+ ["comet_req"] = TestSite.CometReq,
+ ["ccg"] = TestSite.ConnectionClass,
+ ["entry_nonce"] = TestSite.EntryNonce,
+ };
+
/// A site client for the test site with its session, clock and log.
private sealed class Bed : IDisposable
{
diff --git a/tests/Febe.Tests/Collection/RequestCatalogTests.cs b/tests/Febe.Tests/Collection/RequestCatalogTests.cs
index 194256d..99e082c 100644
--- a/tests/Febe.Tests/Collection/RequestCatalogTests.cs
+++ b/tests/Febe.Tests/Collection/RequestCatalogTests.cs
@@ -4,6 +4,7 @@ using System.Text.RegularExpressions;
using Febe.Core.Abstractions;
using Febe.Core.Collection;
using Febe.Core.Collection.Requests;
+using Febe.Tests.Collection.Support;
namespace Febe.Tests.Collection;
@@ -36,7 +37,8 @@ public sealed partial class RequestCatalogTests
// Only what the shapes tell whole is configured: a variable whose name the probe removed, a value it does not
// show, or a header or field whose source is still pending leaves the operation not configured (rule 9). Every
- // Instagram operation has such headers and fields until tappa S4; for four of them only those are missing.
+ // Instagram operation still has such headers and fields after S4 (values the page computes as it runs, headers of
+ // the browser, removed names); for four of them only those are missing.
Assert.AreEqual(0, instagram.Configured.Count());
CollectionAssert.AreEquivalent(
new[] { "PolarisProfileReelsTabContentQuery", "PolarisProfileTaggedTabContentQuery", "PolarisProfileStoryHighlightsTrayContentQuery", "media-info" },
@@ -326,6 +328,166 @@ public sealed partial class RequestCatalogTests
}
}
+ [TestMethod]
+ public void ThePageSectionSaysWhereThePageKeepsEachSessionValue()
+ {
+ var instagram = RequestCatalog.LoadInstagram().Page;
+ Assert.IsNotNull(instagram);
+ Assert.AreEqual("PolarisProfilePostsQuery_instagramRelayOperation", instagram.DocIdModuleFor("PolarisProfilePostsQuery"));
+ Assert.AreEqual(new PageValueSource("LSD", "token"), instagram.Values["lsd"]);
+ Assert.AreEqual(new PageValueSource("DTSGInitialData", "token"), instagram.Values["fb_dtsg"]);
+ Assert.AreEqual(new PageValueSource("CurrentUserInitialData", "USER_ID"), instagram.Values["account_id"]);
+ Assert.AreEqual(new PageValueSource("CurrentUserInitialData", "APP_ID"), instagram.Values["app_id"]);
+ Assert.AreEqual(new PageValueSource("SiteData", "client_revision"), instagram.Values["rev"]);
+ Assert.AreEqual(new PageValueSource("SiteData", "haste_session"), instagram.Values["hs"]);
+ Assert.AreEqual(new PageValueSource("SiteData", "hsi"), instagram.Values["hsi"]);
+ Assert.AreEqual(new PageValueSource("SiteData", "pr"), instagram.Values["dpr"]);
+ Assert.AreEqual(new PageValueSource("SiteData", "comet_env"), instagram.Values["comet_req"]);
+ Assert.AreEqual(new PageValueSource("WebConnectionClassServerGuess", "connectionClass"), instagram.Values["ccg"]);
+ Assert.AreEqual(new PageValueSource("BootloaderConfig", "nonce"), instagram.Values["entry_nonce"]);
+ CollectionAssert.AreEquivalent(SiteSessionValues.PageFields.ToArray(), instagram.Values.Keys.ToArray(), "A place for every page value.");
+
+ // The test site has its own module names, never Instagram's.
+ var prova = RequestCatalog.LoadTestSite().Page;
+ Assert.IsNotNull(prova);
+ Assert.AreEqual("ProvaProfiloQuery_operazioneProva", prova.DocIdModuleFor("ProvaProfiloQuery"));
+ CollectionAssert.AreEquivalent(SiteSessionValues.PageFields.ToArray(), prova.Values.Keys.ToArray());
+ var instagramModules = instagram.Values.Values.Select(v => v.Module).ToHashSet(StringComparer.OrdinalIgnoreCase);
+ Assert.IsFalse(prova.Values.Values.Any(v => instagramModules.Contains(v.Module)));
+ Assert.IsFalse(prova.DocIdModule!.Contains("instagram", StringComparison.OrdinalIgnoreCase));
+ Assert.IsTrue(prova.Values.Values.All(v => PageSources.IsIdentifier(v.Module) && PageSources.IsIdentifier(v.Property)));
+ }
+
+ [TestMethod]
+ public void TheInstagramVersionFieldsComeFromTheSessionAndAllTenOperationsStayNotConfigured()
+ {
+ var catalog = RequestCatalog.LoadInstagram();
+ Assert.AreEqual(0, catalog.Configured.Count(), "S4 configures no Instagram operation.");
+ var session = new Dictionary
+ {
+ ["__rev"] = "rev", ["__hs"] = "hs", ["__hsi"] = "hsi", ["__ccg"] = "ccg", ["__comet_req"] = "comet_req", ["dpr"] = "dpr",
+ };
+ foreach (var operation in catalog.Operations.Where(o => o.Kind == OperationKind.GraphQl))
+ {
+ foreach (var (field, source) in session)
+ {
+ Assert.AreEqual(new ValueSource(ValueSourceKind.Session, source), operation.Body[field], $"{operation.Name} {field}");
+ }
+
+ Assert.AreEqual(new ValueSource(ValueSourceKind.Session, "entry_nonce"), operation.Headers["x-fb-entry-nonce"], operation.Name);
+ Assert.AreEqual(new ValueSource(ValueSourceKind.Constant, "359341"), operation.Headers["x-asbd-id"], "The BDHeaderConfig property is not established.");
+ foreach (var spin in new[] { "__spin_r", "__spin_b", "__spin_t" })
+ {
+ Assert.AreEqual(ValueSourceKind.Pending, operation.Body[spin].Kind, $"{operation.Name} {spin}: who adds it to the request is not shown.");
+ }
+ }
+ }
+
+ [TestMethod]
+ public void EveryPendingLeftIsARuntimeValueABrowserHeaderOrARemovedName()
+ {
+ // A closed list: what the page computes while it runs (__req, __s, __dyn, __csr, __hblp, __hsdp, __sjsp, __crn,
+ // __d, __spin_*, x-web-session-id), headers of the browser (referer, priority, sec-ch-ua*, x-ig-max-touch-points)
+ // and the names the probe removed. Nothing else may stay pending without a decision.
+ var allowed = new HashSet(StringComparer.Ordinal)
+ {
+ "__req", "__s", "__dyn", "__csr", "__hblp", "__hsdp", "__sjsp", "__crn", "__d", "__spin_r", "__spin_b", "__spin_t",
+ "x-web-session-id", "referer", "priority", "sec-ch-ua", "sec-ch-ua-mobile", "sec-ch-ua-platform", "x-ig-max-touch-points",
+ "fb_api_analytics_tags", "qpl_active_flow_ids", RequestCatalog.RemovedName,
+ };
+ var pending = RequestCatalog.LoadInstagram().Operations.SelectMany(o => o.PendingValues).Distinct(StringComparer.Ordinal).ToList();
+ CollectionAssert.AreEqual(Array.Empty(), pending.Where(p => !allowed.Contains(p)).ToArray());
+ Assert.IsFalse(pending.Contains("__rev") || pending.Contains("x-fb-entry-nonce"), "Settled in S4.");
+ Assert.AreEqual(0, RequestCatalog.LoadTestSite().Operations.Sum(o => o.PendingValues.Count));
+ }
+
+ [TestMethod]
+ [DataRow("""{"password": "Utente.password"}""", "password")]
+ [DataRow("""{"user_agent": "Navigatore.agente"}""", "user_agent")]
+ [DataRow("""{"claim": "Pagina.claim"}""", "claim")]
+ [DataRow("""{"doc_id": "Pagina.doc"}""", "doc_id")]
+ [DataRow("""{"lsd": "LSD.token;alert(1)"}""", "Modulo.proprietà")]
+ [DataRow("""{"lsd": "LSD"}""", "Modulo.proprietà")]
+ [DataRow("""{"lsd": "LSD.token.altro"}""", "Modulo.proprietà")]
+ [DataRow("""{"lsd": "1LSD.token"}""", "Modulo.proprietà")]
+ [DataRow("""{"lsd": "LSD.to-ken"}""", "Modulo.proprietà")]
+ [DataRow("""{"lsd": "require('x').y"}""", "Modulo.proprietà")]
+ [DataRow("""{"lsd": ".token"}""", "Modulo.proprietà")]
+ public void ThePageSectionRefusesUnknownFieldsAndNamesThatAreNotIdentifiers(string values, string expected)
+ {
+ var file = JsonNode.Parse(SiteMap.ReadEmbeddedText("richieste.prova.json"))!.AsObject();
+ file["page"]!["values"] = JsonNode.Parse(values);
+ var refused = Refuse(file.ToJsonString());
+ StringAssert.Contains(refused, "page");
+ StringAssert.Contains(refused, expected);
+ }
+
+ [TestMethod]
+ [DataRow("Modulo_relay")]
+ [DataRow("{operation}_{operation}")]
+ [DataRow("{operation}-relay")]
+ [DataRow("{operation}.relay")]
+ [DataRow("{operazione}_relay")]
+ public void TheDocIdModuleHasTheOperationOnceAndIsOtherwiseAnIdentifier(string module)
+ {
+ var file = JsonNode.Parse(SiteMap.ReadEmbeddedText("richieste.prova.json"))!.AsObject();
+ file["page"]!["docIdModule"] = module;
+ StringAssert.Contains(Refuse(file.ToJsonString()), "docIdModule");
+ }
+
+ [TestMethod]
+ public void AConfiguredOperationWhoseSessionValueHasNoPlaceInThePageIsRefused()
+ {
+ // No module for lsd: the configured GraphQL query that sends it is refused, naming the value.
+ var file = JsonNode.Parse(SiteMap.ReadEmbeddedText("richieste.prova.json"))!.AsObject();
+ file["page"]!["values"]!.AsObject().Remove("lsd");
+ var refused = Refuse(file.ToJsonString());
+ StringAssert.Contains(refused, "session:lsd");
+ StringAssert.Contains(refused, "ProvaProfiloQuery");
+ StringAssert.Contains(refused, "regola 9");
+
+ // No doc_id module: every configured GraphQL query is refused.
+ file = JsonNode.Parse(SiteMap.ReadEmbeddedText("richieste.prova.json"))!.AsObject();
+ file["page"]!.AsObject().Remove("docIdModule");
+ StringAssert.Contains(Refuse(file.ToJsonString()), "session:doc_id");
+
+ // No page section at all: x-app-id (session:app_id) of the plain addresses has no place either.
+ file = JsonNode.Parse(SiteMap.ReadEmbeddedText("richieste.prova.json"))!.AsObject();
+ file.Remove("page");
+ StringAssert.Contains(Refuse(file.ToJsonString()), "session:");
+
+ // The user agent and the claim need no place in the page; an operation that is not configured waits anyway.
+ Assert.IsNotNull(RequestCatalog.Parse(Alone(Rest("post2", "/dati/post/{code}")), "richieste.prova.json"));
+ var waiting = Rest("post3", "/dati/post/{code}");
+ waiting["headers"] = new JsonObject { ["user-agent"] = "session:user_agent", ["x-app-id"] = "session:app_id" };
+ waiting["configured"] = false;
+ waiting["reason"] = "in attesa";
+ Assert.IsNotNull(RequestCatalog.Parse(Alone(waiting), "richieste.prova.json"));
+
+ // Instagram's page section names every value its operations use, so settling the pending ones would be enough.
+ Assert.AreEqual(4, SettledCatalog.Instagram().Configured.Count());
+ }
+
+ [TestMethod]
+ public void TheNewSessionFieldsAreAcceptedAndUnknownOnesStillRefused()
+ {
+ foreach (var field in new[] { "rev", "hs", "hsi", "dpr", "ccg", "comet_req", "entry_nonce" })
+ {
+ var operation = Rest("post2", "/dati/post/{code}");
+ operation["headers"] = new JsonObject { ["user-agent"] = "session:user_agent", ["x-prova"] = "session:" + field };
+ operation["configured"] = false;
+ operation["reason"] = "prova";
+ Assert.AreEqual(new ValueSource(ValueSourceKind.Session, field), Get(RequestCatalog.Parse(Alone(operation), "richieste.prova.json"), "post2").Headers["x-prova"]);
+ }
+
+ foreach (var field in new[] { "password", "spin_r", "cookie", "sessionid" })
+ {
+ var operation = Rest("post2", "/dati/post/{code}");
+ operation["headers"] = new JsonObject { ["x-prova"] = "session:" + field };
+ StringAssert.Contains(Refuse(Alone(operation)), "fonte");
+ }
+ }
+
private static SiteOperation Get(RequestCatalog catalog, string name) =>
catalog.TryGet(name, out var operation) ? operation : throw new AssertFailedException($"«{name}» non è nel catalogo.");
diff --git a/tests/Febe.Tests/Collection/SessionCaptureIntegrationTests.cs b/tests/Febe.Tests/Collection/SessionCaptureIntegrationTests.cs
new file mode 100644
index 0000000..401d5af
--- /dev/null
+++ b/tests/Febe.Tests/Collection/SessionCaptureIntegrationTests.cs
@@ -0,0 +1,137 @@
+using System.Security.Cryptography;
+using System.Text.Json;
+using System.Text.Json.Nodes;
+using Febe.Browser.Cdp;
+using Febe.Browser.Recipes;
+using Febe.Browser.Session;
+using Febe.Core.Abstractions;
+using Febe.Core.Collection;
+using Febe.Core.Collection.Requests;
+using Febe.Core.Security;
+using Febe.SitoDiProva;
+using Febe.Tests.Collection.Support;
+using Febe.Tests.Support;
+using VirtualClock = Febe.Tests.Browser.TestSupport.VirtualClock;
+
+namespace Febe.Tests.Collection;
+
+///
+/// The copy at «Ho finito» with a real Chromium on the local test site (issue #36, S4, spec §6.0, §14.2), never
+/// Instagram: the cookies the pages set (the one limited to /api/ with its path), the user agent and the modules
+/// of the page are copied into an encrypted saved session, and the site client then gets an answer to every configured
+/// operation of richieste.prova.json with it. The copy writes nothing into the browser. Runs where Chromium and
+/// Xvfb are (the CI).
+///
+[TestClass]
+[TestCategory(SyntheticSite.Category)]
+[DoNotParallelize]
+public sealed class SessionCaptureIntegrationTests
+{
+ private static SharedChromium? s_chromium;
+ private static string? s_unavailable;
+
+ public TestContext TestContext { get; set; } = null!;
+
+ [ClassInitialize]
+ public static async Task StartAsync(TestContext context)
+ {
+ s_unavailable = SharedChromium.UnavailableReason();
+ if (s_unavailable is null)
+ {
+ s_chromium = await SharedChromium.StartAsync();
+ }
+ }
+
+ [ClassCleanup]
+ public static async Task StopAsync()
+ {
+ if (s_chromium is not null)
+ {
+ await s_chromium.DisposeAsync();
+ s_chromium = null;
+ }
+ }
+
+ [TestMethod]
+ [Timeout(180_000, CooperativeCancellation = true)]
+ public async Task ALoginOnTheTestSiteCopiedAtHoFinitoServesTheSiteClient()
+ {
+ if (s_unavailable is not null)
+ {
+ Assert.Inconclusive(s_unavailable);
+ }
+
+ var ct = TestContext.CancellationToken;
+ await using var site = await SyntheticSite.StartAsync();
+ var cdp = s_chromium!.Cdp;
+
+ // Alberto's login on the test site: a visit opens the session.
+ var navigation = await cdp.NavigateAsync(site.Url("/benvenuto"), ct);
+ Assert.IsTrue(navigation.Succeeded, navigation.ErrorText);
+ Assert.IsTrue(await cdp.WaitForLoadAsync(new SystemClock(), TimeSpan.FromSeconds(60), ct), "La pagina non ha finito di caricare.");
+
+ var plan = SessionCapturePlan.For(CollectionSite.TestSite(site.SiteHost, site.CdnHost), RequestCatalog.LoadTestSite(), SignalRules.LoadTestSite());
+ var before = await CookiesAsync(cdp, plan, ct);
+ var result = await SessionCapture.CaptureAsync(cdp, plan, new VirtualClock(), ct);
+ var after = await CookiesAsync(cdp, plan, ct);
+
+ Assert.IsNotNull(result.Values, result.ToString());
+ Assert.IsEmpty(result.MissingValues, string.Join(", ", result.MissingValues));
+ Assert.IsEmpty(result.MissingDocIds, string.Join(", ", result.MissingDocIds));
+ Assert.AreEqual(0, result.DroppedCookies);
+ Assert.AreEqual(before, after, "the copy writes no cookie into the browser");
+ Assert.IsFalse((await cdp.EvaluateAsync("navigator.webdriver === true", ct)).GetBoolean(), "the browser as it is");
+
+ var values = result.Values;
+ Assert.AreEqual((await cdp.EvaluateAsync("navigator.userAgent", ct)).GetString(), values.UserAgent);
+ CollectionAssert.IsSubsetOf(new[] { TestSite.SessionCookie, TestSite.CsrfCookie, TestSite.ApiPathCookie }, values.Cookies.Select(c => c.Name).ToArray());
+ var apiCookie = values.Cookies.Single(c => c.Name == TestSite.ApiPathCookie);
+ Assert.AreEqual(TestSite.ApiPath, apiCookie.Path, "the cookie limited to /api/ keeps its path");
+ Assert.AreEqual("127.0.0.1", apiCookie.Domain);
+ Assert.IsTrue(apiCookie.HostOnly);
+ Assert.AreEqual(TestSite.Lsd, values.Fields["lsd"]);
+ Assert.AreEqual(TestSite.Dpr, values.Fields["dpr"], "a number of the page as text");
+ Assert.AreEqual(TestSite.DocIds[TestSite.ProfileQuery], values.DocIds[TestSite.ProfileQuery]);
+ lock (site.World.Gate)
+ {
+ Assert.AreEqual(site.World.Viewer.Id, values.Fields["account_id"]);
+ }
+
+ // Into the encrypted file, read back by a new store as at the next start, then the site client.
+ using var temp = new TempFolder("sessione-copiata");
+ var protector = new AesGcmSessionProtector(RandomNumberGenerator.GetBytes(SessionKey.Length));
+ var file = temp.Combine("sessione", "sessione.json");
+ Assert.IsTrue(await new FileSiteSession(file, protector).ReplaceAsync(values, ct));
+ var restored = new FileSiteSession(file, protector);
+ Assert.AreEqual(SavedSessionState.Present, restored.State);
+
+ var catalog = RequestCatalog.LoadTestSite();
+ using var requester = new HttpSiteRequester(catalog, restored, HttpSiteRequesterOptions.TestSite(new Uri(site.SiteUrl + "/")), new VirtualClock());
+ var cases = HttpSiteRequesterTests.Cases(site);
+ foreach (var operation in catalog.Configured)
+ {
+ var answer = await requester.SendAsync(new SiteRequest(operation.Name, cases[operation.Name].Values), Permit.Grant(operation.Category, null), ct);
+ Assert.AreEqual(200, answer.Status, operation.Name);
+ Assert.IsTrue(answer.RootFieldsPresent, operation.Name);
+ }
+
+ Assert.AreEqual(catalog.Configured.Count(), site.Control.DirectRequests.Count);
+ }
+
+ /// The cookies of the site in the browser (names, values, paths), to compare before and after the copy.
+ private static async Task CookiesAsync(ICdpSession cdp, SessionCapturePlan plan, CancellationToken ct)
+ {
+ var urls = new JsonArray();
+ foreach (var url in plan.CookieUrls)
+ {
+ urls.Add(url.AbsoluteUri);
+ }
+
+ var answer = await cdp.SendAsync("Network.getCookies", new JsonObject { ["urls"] = urls }, ct);
+ return string.Join(
+ "; ",
+ answer.GetProperty("cookies").EnumerateArray()
+ .Select(c => $"{c.GetProperty("name").GetString()}={c.GetProperty("value").GetString()}@{c.GetProperty("domain").GetString()}{c.GetProperty("path").GetString()}")
+ .Order(StringComparer.Ordinal));
+ }
+}
diff --git a/tests/Febe.Tests/Collection/SessionProtectorTests.cs b/tests/Febe.Tests/Collection/SessionProtectorTests.cs
new file mode 100644
index 0000000..62d8765
--- /dev/null
+++ b/tests/Febe.Tests/Collection/SessionProtectorTests.cs
@@ -0,0 +1,221 @@
+using System.Security.Cryptography;
+using System.Text;
+using Febe.Core.Security;
+using Febe.Tests.Support;
+
+namespace Febe.Tests.Collection;
+
+///
+/// The encryption of the saved session in Docker (issue #36, S4, spec §13.2): AES-256-GCM with a fresh nonce per write,
+/// the key from FEBE_CHIAVE_SESSIONE or from chiave.bin made once, owner-only, never replaced; files replaced at once.
+/// Keys are made at run time (no key in the repository, gitleaks); no text ever holds a key or a plain value.
+///
+[TestClass]
+public sealed class SessionProtectorTests
+{
+ private static readonly byte[] Plain = Encoding.UTF8.GetBytes("""{"cookies":[{"name":"sessionid","value":"valore-in-chiaro-1"}]}""");
+
+ [TestMethod]
+ public void ARoundTripGivesTheSameBytesAndEveryWriteHasAFreshNonce()
+ {
+ var protector = new AesGcmSessionProtector(RandomNumberGenerator.GetBytes(SessionKey.Length));
+ var first = protector.Protect(Plain);
+ var second = protector.Protect(Plain);
+
+ CollectionAssert.AreEqual(Plain, protector.Unprotect(first));
+ CollectionAssert.AreEqual(Plain, protector.Unprotect(second));
+ Assert.IsTrue(SessionBlob.HasHeader(first, SessionBlob.AesGcm), "FEBS, version, scheme.");
+ Assert.AreEqual("FEBS", Encoding.ASCII.GetString(first, 0, 4));
+ Assert.AreEqual(SessionBlob.HeaderLength + 12 + 16 + Plain.Length, first.Length);
+ CollectionAssert.AreNotEqual(first, second, "A fresh nonce for every write.");
+ Assert.AreEqual(-1, IndexOf(first, Encoding.UTF8.GetBytes("valore-in-chiaro-1")), "Nothing in clear.");
+ Assert.AreEqual("aes-gcm", protector.Scheme);
+ }
+
+ [TestMethod]
+ public void ATamperedByteAnotherKeyOrAnotherSchemeIsUnreadableAndTheMessageHasNoValue()
+ {
+ var key = RandomNumberGenerator.GetBytes(SessionKey.Length);
+ var protector = new AesGcmSessionProtector(key);
+ var blob = protector.Protect(Plain);
+
+ foreach (var index in new[] { 5, SessionBlob.HeaderLength + 1, SessionBlob.HeaderLength + 13, blob.Length - 1 })
+ {
+ var tampered = (byte[])blob.Clone();
+ tampered[index] ^= 0x01;
+ var refused = Assert.ThrowsExactly(() => protector.Unprotect(tampered));
+ Assert.AreEqual(SessionUnreadableException.Text, refused.Message);
+ Assert.IsNull(refused.InnerException, "No inner text is passed on.");
+ }
+
+ var other = new AesGcmSessionProtector(RandomNumberGenerator.GetBytes(SessionKey.Length));
+ Assert.ThrowsExactly(() => other.Unprotect(blob));
+ Assert.ThrowsExactly(() => protector.Unprotect(blob.AsSpan(0, 10)));
+ Assert.ThrowsExactly(() => protector.Unprotect(Plain), "Not a blob of Febe.");
+ var dpapiHeader = (byte[])blob.Clone();
+ dpapiHeader[5] = SessionBlob.Dpapi;
+ Assert.ThrowsExactly(() => protector.Unprotect(dpapiHeader));
+
+ Assert.ThrowsExactly(() => new AesGcmSessionProtector(new byte[16]));
+ Assert.IsFalse(protector.ToString().Contains(Convert.ToBase64String(key), StringComparison.Ordinal));
+ }
+
+ [TestMethod]
+ public void TheKeyIsBase64Of32BytesOr64HexAndAWrongValueIsRefusedWithoutEchoingIt()
+ {
+ var key = RandomNumberGenerator.GetBytes(SessionKey.Length);
+ Assert.IsTrue(SessionKey.TryParse(Convert.ToBase64String(key), out var fromBase64, out var none));
+ CollectionAssert.AreEqual(key, fromBase64);
+ Assert.IsNull(none);
+ Assert.IsTrue(SessionKey.TryParse(" " + Convert.ToHexString(key).ToLowerInvariant() + "\n", out var fromHex, out _));
+ CollectionAssert.AreEqual(key, fromHex);
+
+ foreach (var wrong in new[] { "chiave-troppo-corta", Convert.ToBase64String(new byte[16]), Convert.ToBase64String(new byte[33]), new string('z', 64), " " })
+ {
+ Assert.IsFalse(SessionKey.TryParse(wrong, out var parsed, out var problem), wrong);
+ Assert.IsNull(parsed);
+ Assert.IsNotNull(problem);
+ StringAssert.Contains(problem, SessionKey.EnvironmentVariable);
+ if (wrong.Trim().Length > 0)
+ {
+ Assert.IsFalse(problem.Contains(wrong.Trim(), StringComparison.Ordinal), "Never the value.");
+ }
+ }
+
+ Assert.IsFalse(SessionKey.TryParse(null, out _, out _));
+ }
+
+ [TestMethod]
+ public void ChiaveBinIsCreatedOnceOwnerOnlyAndNeverReplaced()
+ {
+ using var folder = new TempFolder("sessione-chiave");
+ var file = folder.Combine("sessione", "chiave.bin");
+
+ var first = SessionKey.LoadOrCreate(file);
+ var again = SessionKey.LoadOrCreate(file);
+
+ Assert.AreEqual(SessionKey.Length, first.Length);
+ CollectionAssert.AreEqual(first, again, "Made once, then read.");
+ CollectionAssert.AreEqual(first, File.ReadAllBytes(file));
+ if (!OperatingSystem.IsWindows())
+ {
+ Assert.AreEqual(OwnerOnlyFiles.OwnerFile, File.GetUnixFileMode(file), "0600 from its creation.");
+ Assert.AreEqual(OwnerOnlyFiles.OwnerFolder, File.GetUnixFileMode(folder.Combine("sessione")), "0700.");
+ }
+
+ Assert.ThrowsExactly(() => OwnerOnlyFiles.CreateNew(file, new byte[SessionKey.Length]), "Never replaced.");
+ CollectionAssert.AreEqual(first, File.ReadAllBytes(file));
+ }
+
+ [TestMethod]
+ public void AKeyWriteTheDiskRefusesLeavesNoChiaveBinSoTheNextStartMakesOne()
+ {
+ using var folder = new TempFolder("sessione-chiave");
+ var file = folder.Combine("sessione", "chiave.bin");
+
+ // The disk fills up after the first bytes: the error comes out, and nothing short is left as «the key».
+ Assert.ThrowsExactly(() => SessionKey.LoadOrCreate(file, null, static (stream, bytes) =>
+ {
+ stream.Write(bytes[..4]);
+ throw new IOException("Spazio esaurito sul disco (prova).");
+ }));
+ Assert.IsFalse(File.Exists(file), "No short chiave.bin behind.");
+ Assert.IsEmpty(Directory.GetFiles(folder.Combine("sessione")), "Nor a part file.");
+ Assert.IsNull(SessionKey.CheckFile(file), "The next start is not stopped by a key problem.");
+
+ var key = SessionKey.LoadOrCreate(file);
+ Assert.AreEqual(SessionKey.Length, key.Length);
+ CollectionAssert.AreEqual(key, File.ReadAllBytes(file));
+ Assert.IsEmpty(Directory.GetFiles(folder.Combine("sessione"), "*" + OwnerOnlyFiles.PartSuffix));
+ }
+
+ [TestMethod]
+ public void AChiaveBinOfTheWrongLengthIsAProblemNotARegeneration()
+ {
+ using var folder = new TempFolder("sessione-chiave");
+ var file = folder.Combine("chiave.bin");
+ File.WriteAllBytes(file, Encoding.ASCII.GetBytes("non-una-chiave"));
+
+ var problem = SessionKey.CheckFile(file);
+ Assert.IsNotNull(problem);
+ StringAssert.Contains(problem, "chiave.bin");
+ Assert.IsFalse(problem.Contains("non-una-chiave", StringComparison.Ordinal));
+ var refused = Assert.ThrowsExactly(() => SessionKey.LoadOrCreate(file));
+ Assert.IsFalse(refused.Message.Contains("non-una-chiave", StringComparison.Ordinal));
+ CollectionAssert.AreEqual(Encoding.ASCII.GetBytes("non-una-chiave"), File.ReadAllBytes(file), "Left as it is, never made again.");
+ Assert.IsNull(SessionKey.CheckFile(folder.Combine("manca.bin")), "A missing file will be made.");
+ }
+
+ [TestMethod]
+ public void LooserModesAreNarrowedToTheOwnerOnUnix()
+ {
+ using var folder = new TempFolder("sessione-chiave");
+ var file = folder.Combine("chiave.bin");
+ File.WriteAllBytes(file, RandomNumberGenerator.GetBytes(SessionKey.Length));
+ var warnings = new List();
+ if (OperatingSystem.IsWindows())
+ {
+ Assert.IsFalse(OwnerOnlyFiles.Tighten(file), "No Unix modes on Windows.");
+ Assert.AreEqual(SessionKey.Length, SessionKey.LoadOrCreate(file, warnings.Add).Length);
+ Assert.AreEqual(0, warnings.Count);
+ return;
+ }
+
+ File.SetUnixFileMode(file, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.GroupRead | UnixFileMode.OtherRead);
+ Assert.AreEqual(SessionKey.Length, SessionKey.LoadOrCreate(file, warnings.Add).Length);
+ Assert.AreEqual(OwnerOnlyFiles.OwnerFile, File.GetUnixFileMode(file));
+ Assert.AreEqual(1, warnings.Count);
+ StringAssert.Contains(warnings[0], "solo il proprietario");
+ }
+
+ [TestMethod]
+ public void TheEnvironmentKeyWinsAndAnUnusedChiaveBinIsNamedNeverRead()
+ {
+ using var folder = new TempFolder("sessione-chiave");
+ var file = folder.Combine("chiave.bin");
+ var key = RandomNumberGenerator.GetBytes(SessionKey.Length);
+ var text = Convert.ToBase64String(key);
+ var log = new List();
+
+ CollectionAssert.AreEqual(key, SessionKey.Resolve(text, file, log.Add));
+ Assert.IsFalse(File.Exists(file), "With the variable, no chiave.bin is made.");
+
+ var stored = SessionKey.Resolve(null, file, log.Add);
+ Assert.IsTrue(File.Exists(file));
+ CollectionAssert.AreEqual(stored, SessionKey.Resolve(" ", file, log.Add), "An empty variable is no variable.");
+ CollectionAssert.AreEqual(key, SessionKey.Resolve(text, file, log.Add));
+ Assert.IsTrue(log.Any(l => l.Contains("non si usa", StringComparison.Ordinal)), string.Join("\n", log));
+
+ var refused = Assert.ThrowsExactly(() => SessionKey.Resolve("chiave-sbagliata", file, log.Add));
+ Assert.IsFalse(refused.Message.Contains("chiave-sbagliata", StringComparison.Ordinal));
+ foreach (var line in log)
+ {
+ Assert.IsFalse(line.Contains(text, StringComparison.Ordinal) || line.Contains(Convert.ToBase64String(stored), StringComparison.Ordinal), line);
+ }
+ }
+
+ [TestMethod]
+ public void AnAtomicWriteReplacesTheFileAndLeavesNoPartFile()
+ {
+ using var folder = new TempFolder("sessione-file");
+ var file = folder.Combine("sessione.json");
+ OwnerOnlyFiles.WriteAtomic(file, "uno"u8);
+ OwnerOnlyFiles.WriteAtomic(file, "due"u8);
+
+ Assert.AreEqual("due", File.ReadAllText(file));
+ CollectionAssert.AreEqual(new[] { "sessione.json" }, Directory.GetFiles(folder.Path).Select(Path.GetFileName).ToArray());
+ if (!OperatingSystem.IsWindows())
+ {
+ Assert.AreEqual(OwnerOnlyFiles.OwnerFile, File.GetUnixFileMode(file));
+ }
+
+ // A broken write left a part file: deleting the session takes it too.
+ File.WriteAllText(file + ".abcdef12" + OwnerOnlyFiles.PartSuffix, "resto");
+ File.WriteAllText(folder.Combine("altro.txt"), "non è della sessione");
+ OwnerOnlyFiles.DeleteWithLeftovers(file);
+ CollectionAssert.AreEqual(new[] { "altro.txt" }, Directory.GetFiles(folder.Path).Select(Path.GetFileName).ToArray());
+ OwnerOnlyFiles.DeleteWithLeftovers(file);
+ }
+
+ private static int IndexOf(byte[] haystack, byte[] needle) => haystack.AsSpan().IndexOf(needle);
+}
diff --git a/tests/Febe.Tests/Collection/SiteAnswerSignalsTests.cs b/tests/Febe.Tests/Collection/SiteAnswerSignalsTests.cs
index 0bf6f0e..34f1be8 100644
--- a/tests/Febe.Tests/Collection/SiteAnswerSignalsTests.cs
+++ b/tests/Febe.Tests/Collection/SiteAnswerSignalsTests.cs
@@ -143,11 +143,15 @@ public sealed class SiteAnswerSignalsTests
private static byte[] Bytes(string text) => Encoding.UTF8.GetBytes(text);
}
-/// The saved session of the site client (issue #36, S2): cookies read as a browser reads them, updates in one write, no value in its text.
+///
+/// The saved session of the site client (issue #36, S2 and S4): cookies read and sent as a browser reads and sends
+/// them, with their domain and path (RFC 6265), updates in one write, no value in any text.
+///
[TestClass]
public sealed class SiteSessionTests
{
private static readonly DateTimeOffset Now = new(2026, 11, 16, 10, 0, 0, TimeSpan.Zero);
+ private static readonly Uri Graph = new("https://www.instagram.com/api/graphql");
[TestMethod]
[DataRow("sessionid=abc; Path=/; HttpOnly", "abc", false)]
@@ -163,66 +167,161 @@ public sealed class SiteSessionTests
[DataRow("sessionid=abc; Domain=instagram.com", "abc", false)]
public void ACookieLineIsReadAsABrowserReadsIt(string line, string value, bool deletes)
{
- var cookie = SiteCookies.Parse(line, "www.instagram.com", Now);
+ var cookie = SiteCookies.Parse(line, Graph, Now);
Assert.IsNotNull(cookie);
- Assert.AreEqual("sessionid", cookie.Value.Name);
- Assert.AreEqual(value, cookie.Value.Value);
- Assert.AreEqual(deletes, cookie.Value.Deletes);
+ Assert.AreEqual("sessionid", cookie.Cookie.Name);
+ Assert.AreEqual(value, cookie.Cookie.Value);
+ Assert.AreEqual(deletes, cookie.Deletes);
+ }
+
+ [TestMethod]
+ [DataRow("a=b", "www.instagram.com", true, "/api", false)]
+ [DataRow("a=b; Path=/api/", "www.instagram.com", true, "/api/", false)]
+ [DataRow("a=b; Path=relativo", "www.instagram.com", true, "/api", false)]
+ [DataRow("a=b; Path=/; Domain=.instagram.com", "instagram.com", false, "/", false)]
+ [DataRow("a=b; Domain=WWW.Instagram.com; Path=/", "www.instagram.com", false, "/", false)]
+ [DataRow("a=b; Path=/; Secure; HttpOnly", "www.instagram.com", true, "/", true)]
+ public void ACookieLineKeepsItsDomainAndPathAsABrowserReadsThem(string line, string domain, bool hostOnly, string path, bool secure)
+ {
+ // No Domain: host-only on the request host; no Path (or one not starting with «/»): the default path of the
+ // request, «/api» for «/api/graphql» (RFC 6265 §5.1.4).
+ var cookie = SiteCookies.Parse(line, Graph, Now)!.Cookie;
+ Assert.AreEqual(domain, cookie.Domain);
+ Assert.AreEqual(hostOnly, cookie.HostOnly);
+ Assert.AreEqual(path, cookie.Path);
+ Assert.AreEqual(secure, cookie.Secure);
+ }
+
+ [TestMethod]
+ public void TheDefaultPathIsTheRequestPathUpToItsLastSlash()
+ {
+ Assert.AreEqual("/", SiteCookies.DefaultPath(new Uri("https://www.instagram.com/")));
+ Assert.AreEqual("/", SiteCookies.DefaultPath(new Uri("https://www.instagram.com/marta")));
+ Assert.AreEqual("/api", SiteCookies.DefaultPath(new Uri("https://www.instagram.com/api/graphql")));
+ Assert.AreEqual("/api/v1/media/1/info", SiteCookies.DefaultPath(new Uri("https://www.instagram.com/api/v1/media/1/info/")));
+ }
+
+ [TestMethod]
+ public void ACookieGoesOnlyWhereItsDomainPathAndSchemeMatch()
+ {
+ var host = SiteCookie.ForHost("a", "1", "www.instagram.com");
+ var wide = new SiteCookie("b", "2", ".instagram.com", hostOnly: false);
+ var api = SiteCookie.ForHost("c", "3", "www.instagram.com", "/api");
+ var secure = SiteCookie.ForHost("d", "4", "127.0.0.1", secure: true);
+
+ Assert.IsTrue(host.Matches(Graph, Now));
+ Assert.IsFalse(host.Matches(new Uri("https://help.instagram.com/"), Now), "Host-only: not a subdomain.");
+ Assert.IsTrue(wide.Matches(new Uri("https://help.instagram.com/"), Now));
+ Assert.IsTrue(wide.Matches(new Uri("https://instagram.com/"), Now));
+ Assert.IsFalse(wide.Matches(new Uri("https://evilinstagram.com/"), Now), "A suffix only at a dot.");
+ Assert.IsTrue(api.Matches(Graph, Now));
+ Assert.IsTrue(api.Matches(new Uri("https://www.instagram.com/api"), Now));
+ Assert.IsFalse(api.Matches(new Uri("https://www.instagram.com/apix/graphql"), Now), "A path prefix only at a «/».");
+ Assert.IsFalse(api.Matches(new Uri("https://www.instagram.com/"), Now));
+ Assert.IsFalse(secure.Matches(new Uri("http://127.0.0.1:8481/api/dati"), Now), "Secure: only over https.");
+ Assert.IsTrue(secure.Matches(new Uri("https://127.0.0.1:8481/api/dati"), Now));
+ Assert.IsFalse(new SiteCookie("e", "5", "0.0.1", hostOnly: false).Matches(new Uri("http://127.0.0.1/"), Now), "Never a suffix of an IP address.");
+ Assert.IsFalse(SiteCookie.ForHost("f", string.Empty, "www.instagram.com").Matches(Graph, Now), "An empty cookie is not sent.");
+ Assert.IsFalse(SiteCookie.ForHost("g", "7", "www.instagram.com", expires: Now).Matches(Graph, Now), "Expired.");
+ }
+
+ [TestMethod]
+ public void TheCookiesOfARequestComeLongerPathsFirstThenInTheStoredOrder()
+ {
+ var values = new SiteSessionValues(
+ [
+ SiteCookie.ForHost("csrftoken", "radice", "www.instagram.com"),
+ SiteCookie.ForHost("zeta", "z", "www.instagram.com"),
+ SiteCookie.ForHost("csrftoken", "api", "www.instagram.com", "/api/"),
+ new SiteCookie("mid", "m", "instagram.com", hostOnly: false),
+ SiteCookie.ForHost("altrove", "x", "www.instagram.com", "/accounts/"),
+ SiteCookie.ForHost("estraneo", "x", "www.facebook.com"),
+ ],
+ "agente");
+
+ CollectionAssert.AreEqual(
+ new[] { "csrftoken=api", "csrftoken=radice", "zeta=z", "mid=m" },
+ values.CookiesFor(Graph, Now).Select(c => $"{c.Name}={c.Value}").ToArray());
+ Assert.AreEqual("api", values.CookieFor("csrftoken", Graph, Now), "The one with the longest path, as x-csrftoken takes it.");
+ Assert.AreEqual("radice", values.CookieFor("csrftoken", new Uri("https://www.instagram.com/marta/"), Now));
+ Assert.IsNull(values.CookieFor("altrove", Graph, Now));
}
[TestMethod]
public void AQuotedValueIsKeptAsTheBrowserKeepsItAndTheExpiryIsRead()
{
// RFC 6265 §5.2: the quotes are part of the value; sent back without them the cookie would not be the browser's.
- var rur = SiteCookies.Parse("rur=\"CLN\\05412\\0541795\"; Domain=.instagram.com; Path=/; Max-Age=3600", "www.instagram.com", Now)!.Value;
+ var rur = SiteCookies.Parse("rur=\"CLN\\05412\\0541795\"; Domain=.instagram.com; Path=/; Max-Age=3600", Graph, Now)!.Cookie;
Assert.AreEqual("\"CLN\\05412\\0541795\"", rur.Value);
Assert.AreEqual(Now.AddHours(1), rur.Expires, "Max-Age from now.");
- Assert.AreEqual(new DateTimeOffset(2027, 11, 16, 10, 0, 0, TimeSpan.Zero), SiteCookies.Parse("a=b; expires=Tue, 16 Nov 2027 10:00:00 GMT", "www.instagram.com", Now)!.Value.Expires);
- Assert.IsNull(SiteCookies.Parse("a=b; Path=/", "www.instagram.com", Now)!.Value.Expires, "No expiry: it lasts as the session.");
- Assert.IsNull(SiteCookies.Parse("a=b; Max-Age=0", "www.instagram.com", Now)!.Value.Expires, "A deletion has no expiry.");
+ Assert.AreEqual(new DateTimeOffset(2027, 11, 16, 10, 0, 0, TimeSpan.Zero), SiteCookies.Parse("a=b; expires=Tue, 16 Nov 2027 10:00:00 GMT", Graph, Now)!.Cookie.Expires);
+ Assert.IsNull(SiteCookies.Parse("a=b; Path=/", Graph, Now)!.Cookie.Expires, "No expiry: it lasts as the session.");
+ Assert.IsNull(SiteCookies.Parse("a=b; Max-Age=0", Graph, Now)!.Cookie.Expires, "A deletion has no expiry.");
}
[TestMethod]
public async Task NewCookiesKeepTheOrderOfTheSiteAndExpiredOnesAreNotSent()
{
var session = new InMemorySiteSession(new SiteSessionValues(
- [new("csrftoken", "c1"), new("sessionid", "s1"), new("vecchio", "v1")],
- "agente",
- expires: new Dictionary { ["vecchio"] = Now.AddMinutes(1) }));
+ [Cookie("csrftoken", "c1"), Cookie("sessionid", "s1"), Cookie("vecchio", "v1", Now.AddMinutes(1))],
+ "agente"));
var capture = session.Read()!.Capture;
// Ten names, in an order no hash keeps by chance.
var names = new[] { "ig_nrcb", "ps_l", "zz", "aa", "mid", "datr", "ps_n", "wd", "b1", "a9" };
await session.UpdateAsync(
- new SiteSessionUpdate(names.Select(n => new KeyValuePair(n, "x-" + n)), expires: new Dictionary { ["wd"] = Now.AddDays(7) }, capture: capture),
+ new SiteSessionUpdate(names.Select(n => Cookie(n, "x-" + n, n == "wd" ? Now.AddDays(7) : null)), capture: capture),
CancellationToken.None);
var values = session.Read()!;
- CollectionAssert.AreEqual(new[] { "csrftoken", "sessionid", "vecchio" }.Concat(names).ToArray(), values.Cookies.Select(c => c.Key).ToArray());
+ CollectionAssert.AreEqual(new[] { "csrftoken", "sessionid", "vecchio" }.Concat(names).ToArray(), values.Cookies.Select(c => c.Name).ToArray());
Assert.AreEqual(capture, values.Capture, "A renewal keeps the capture.");
- Assert.AreEqual(Now.AddDays(7), values.Expires["wd"]);
+ Assert.AreEqual(Now.AddDays(7), values.Cookies.Single(c => c.Name == "wd").Expires);
- Assert.AreEqual("v1", values.CookieAt("vecchio", Now));
- Assert.IsNull(values.CookieAt("vecchio", Now.AddMinutes(1)), "Expired: the browser would not send it.");
- Assert.IsFalse(values.CookiesAt(Now.AddMinutes(2)).Any(c => c.Key == "vecchio"));
- Assert.IsNull(values.CookieAt("wd", Now.AddDays(8)));
- Assert.AreEqual("s1", values.CookieAt("sessionid", Now.AddYears(5)), "No expiry: as long as the session.");
+ Assert.AreEqual("v1", values.CookieFor("vecchio", Graph, Now));
+ Assert.IsNull(values.CookieFor("vecchio", Graph, Now.AddMinutes(1)), "Expired: the browser would not send it.");
+ Assert.IsFalse(values.CookiesFor(Graph, Now.AddMinutes(2)).Any(c => c.Name == "vecchio"));
+ Assert.IsNull(values.CookieFor("wd", Graph, Now.AddDays(8)));
+ Assert.AreEqual("s1", values.CookieFor("sessionid", Graph, Now.AddYears(5)), "No expiry: as long as the session.");
// Renewed without an expiry: the old expiry goes.
- await session.UpdateAsync(new SiteSessionUpdate([new("wd", "x2")], capture: capture), CancellationToken.None);
- Assert.IsFalse(session.Read()!.Expires.ContainsKey("wd"));
+ await session.UpdateAsync(new SiteSessionUpdate([Cookie("wd", "x2")], capture: capture), CancellationToken.None);
+ Assert.IsNull(session.Read()!.Cookies.Single(c => c.Name == "wd").Expires);
+ }
+
+ [TestMethod]
+ public async Task TheSameNameOnTwoPathsIsTwoCookiesAndADeletionTouchesOnlyItsKey()
+ {
+ var session = new InMemorySiteSession(new SiteSessionValues(
+ [
+ Cookie("csrftoken", "radice"),
+ SiteCookie.ForHost("csrftoken", "api", "www.instagram.com", "/api/"),
+ new SiteCookie("csrftoken", "dominio", "instagram.com", hostOnly: false),
+ ],
+ "agente"));
+ Assert.AreEqual(3, session.Read()!.Cookies.Count, "Name, domain, path and host-only make the key.");
+
+ // The site renews the one at «/api/» and deletes the host-only one at «/»: the domain cookie stays as it was.
+ var renewal = SiteCookies.Parse("csrftoken=nuovo; Path=/api/", Graph, Now)!;
+ var deletion = SiteCookies.Parse("csrftoken=; Path=/; Max-Age=0", Graph, Now)!;
+ Assert.IsTrue(deletion.Deletes);
+ await session.UpdateAsync(new SiteSessionUpdate([renewal.Cookie], [deletion.Cookie.Key]), CancellationToken.None);
+
+ var cookies = session.Read()!.Cookies;
+ CollectionAssert.AreEqual(new[] { "/api/ nuovo", "/ dominio" }, cookies.Select(c => $"{c.Path} {c.Value}").ToArray(), "Renewed in place, the deleted one gone.");
+ Assert.IsFalse(cookies[1].HostOnly);
}
[TestMethod]
public async Task TheLateAnswerOfAReplacedSessionChangesNothing()
{
- var session = new InMemorySiteSession(new SiteSessionValues([new("sessionid", "vecchia")], "agente"));
+ var session = new InMemorySiteSession(new SiteSessionValues([Cookie("sessionid", "vecchia")], "agente"));
var old = session.Read()!.Capture;
- session.Replace(new SiteSessionValues([new("sessionid", "nuova")], "agente"));
+ session.Replace(new SiteSessionValues([Cookie("sessionid", "nuova")], "agente"));
Assert.AreNotEqual(old, session.Read()!.Capture, "A new login is a new capture.");
- await session.UpdateAsync(new SiteSessionUpdate(cookiesDeleted: ["sessionid"], claim: "vecchio", capture: old), CancellationToken.None);
+ await session.UpdateAsync(new SiteSessionUpdate(cookiesDeleted: [Cookie("sessionid", string.Empty).Key], claim: "vecchio", capture: old), CancellationToken.None);
Assert.AreEqual("nuova", session.Read()!.Cookie("sessionid"));
Assert.AreEqual(SiteSessionValues.InitialClaim, session.Read()!.Field("claim", "Op"), "No claim yet: the page's «0».");
Assert.AreEqual(0, session.Updates);
@@ -231,44 +330,91 @@ public sealed class SiteSessionTests
[TestMethod]
[DataRow("sessionid=abc; Domain=facebook.com")]
[DataRow("sessionid=abc; Domain=evilinstagram.com")]
+ [DataRow("sessionid=abc; Domain=com")]
+ [DataRow("sessionid=abc; Domain=help.instagram.com")]
+ [DataRow("sessionid=a\u0001b")]
+ [DataRow("sessionid=caffè")]
[DataRow("senza-uguale")]
[DataRow("=abc")]
[DataRow("nome con spazio=abc")]
public void ACookieOfAnotherDomainOrNotACookieIsIgnored(string line) =>
- Assert.IsNull(SiteCookies.Parse(line, "www.instagram.com", Now));
+ Assert.IsNull(SiteCookies.Parse(line, Graph, Now));
+
+ [TestMethod]
+ public void ACookieThatABrowserWouldNotKeepIsRefusedWithoutItsValue()
+ {
+ foreach (var make in new Func[]
+ {
+ () => SiteCookie.ForHost("a=b", "segreto", "www.instagram.com"),
+ () => SiteCookie.ForHost("a", "segreto;altro", "www.instagram.com"),
+ () => SiteCookie.ForHost("a", "segreto\r\nx: y", "www.instagram.com"),
+ () => SiteCookie.ForHost("a", "segreto", "www.instagram.com", "senza-barra"),
+ () => SiteCookie.ForHost("a", "segreto", "host con spazi"),
+ })
+ {
+ var refused = Assert.ThrowsExactly(() => make());
+ Assert.IsFalse(refused.Message.Contains("segreto", StringComparison.Ordinal), refused.Message);
+ }
+ }
[TestMethod]
public async Task AnUpdateIsAppliedAtOnceAndTheTextShowsNoValue()
{
var session = new InMemorySiteSession(new SiteSessionValues(
- [new("csrftoken", "segreto-1"), new("sessionid", "segreto-2"), new("rur", "segreto-3")],
+ [Cookie("csrftoken", "segreto-1"), Cookie("sessionid", "segreto-2"), Cookie("rur", "segreto-3")],
"Mozilla/5.0 segreto-agente",
- new Dictionary { ["claim"] = "0", ["lsd"] = "segreto-4" },
+ new Dictionary { ["claim"] = "0", ["lsd"] = "segreto-4", ["rev"] = "segreto-11", ["entry_nonce"] = "segreto-12" },
new Dictionary { ["Op"] = "segreto-5" }));
- await session.UpdateAsync(new SiteSessionUpdate(new Dictionary { ["csrftoken"] = "segreto-6", ["nuovo"] = "segreto-7" }, ["rur"], "segreto-8"), CancellationToken.None);
+ var update = new SiteSessionUpdate([Cookie("csrftoken", "segreto-6"), Cookie("nuovo", "segreto-7")], [Cookie("rur", string.Empty).Key], "segreto-8");
+ await session.UpdateAsync(update, CancellationToken.None);
await session.UpdateAsync(new SiteSessionUpdate(), CancellationToken.None);
var values = session.Read()!;
- CollectionAssert.AreEqual(new[] { "csrftoken", "sessionid", "nuovo" }, values.Cookies.Select(c => c.Key).ToArray(), "Renewed in place, new at the end, deleted gone.");
+ CollectionAssert.AreEqual(new[] { "csrftoken", "sessionid", "nuovo" }, values.Cookies.Select(c => c.Name).ToArray(), "Renewed in place, new at the end, deleted gone.");
Assert.AreEqual("segreto-6", values.Cookie("csrftoken"));
Assert.AreEqual("segreto-8", values.Field("claim", "Op"));
Assert.AreEqual("segreto-5", values.Field("doc_id", "Op"));
+ Assert.AreEqual("segreto-11", values.Field("rev", "Op"));
Assert.IsNull(values.Field("doc_id", "Altra"));
Assert.AreEqual("Mozilla/5.0 segreto-agente", values.Field("user_agent", "Op"));
Assert.AreEqual(1, session.Updates, "An empty update writes nothing.");
- foreach (var text in new[] { session.ToString(), values.ToString(), new SiteSessionUpdate(new Dictionary { ["a"] = "segreto-9" }, ["b"], "segreto-10").ToString() })
+ var texts = new List { session.ToString(), values.ToString(), update.ToString(), $"{values}", $"{update}" };
+ texts.AddRange(values.Cookies.Select(c => c.ToString()));
+ texts.AddRange(update.CookiesDeleted.Select(k => k.ToString()));
+ texts.Add(SiteCookies.Parse("csrftoken=segreto-9; Path=/", Graph, Now)!.ToString());
+ foreach (var text in texts)
{
Assert.IsFalse(text.Contains("segreto", StringComparison.Ordinal), text);
- Assert.IsFalse(text.Contains("csrftoken", StringComparison.Ordinal), text);
}
- Assert.ThrowsExactly(() => new SiteSessionValues([new("a=b", "c")], "agente"));
+ foreach (var text in new[] { session.ToString(), values.ToString(), update.ToString() })
+ {
+ Assert.IsFalse(text.Contains("csrftoken", StringComparison.Ordinal), "The session's text has counts only: " + text);
+ }
+
Assert.ThrowsExactly(() => new SiteSessionValues([], "agente", new Dictionary { ["password"] = "x" }));
+ Assert.ThrowsExactly(() => new SiteSessionValues([], "agente", new Dictionary { ["user_agent"] = "x" }), "The user agent is not a page value.");
var empty = new InMemorySiteSession(null);
await empty.UpdateAsync(new SiteSessionUpdate(claim: "x"), CancellationToken.None);
Assert.IsNull(empty.Read(), "No session: an update creates none.");
}
+
+ [TestMethod]
+ public void TheNewPageFieldsAreSessionFieldsAndTheVocabularyIsClosed()
+ {
+ foreach (var field in new[] { "rev", "hs", "hsi", "dpr", "ccg", "comet_req", "entry_nonce", "lsd", "fb_dtsg", "app_id", "account_id" })
+ {
+ Assert.IsTrue(SiteSessionValues.PageFields.Contains(field), field);
+ Assert.IsTrue(ValueSource.SessionFields.Contains(field), field);
+ }
+
+ CollectionAssert.AreEquivalent(new[] { "user_agent", "claim", "doc_id" }, ValueSource.SessionFields.Except(SiteSessionValues.PageFields).ToArray());
+ Assert.IsFalse(ValueSource.SessionFields.Contains("spin_r"), "__spin_* stay pending: who adds them to the request is not shown.");
+ }
+
+ private static SiteCookie Cookie(string name, string value, DateTimeOffset? expires = null) =>
+ SiteCookie.ForHost(name, value, "www.instagram.com", expires: expires);
}
diff --git a/tests/Febe.Tests/Collection/Support/SettledCatalog.cs b/tests/Febe.Tests/Collection/Support/SettledCatalog.cs
index 75deedf..92bbb19 100644
--- a/tests/Febe.Tests/Collection/Support/SettledCatalog.cs
+++ b/tests/Febe.Tests/Collection/Support/SettledCatalog.cs
@@ -5,13 +5,14 @@ using Febe.Core.Collection.Requests;
namespace Febe.Tests.Collection.Support;
///
-/// The shipped Instagram catalog as tappa S4 will leave it for some operations: their headers and fields with a
-/// «pending» source dropped and the operation configured. Only for the tests of the site client contract, which need
-/// an Instagram operation the guard lets through; the shipped file keeps them not configured (rule 9).
+/// The shipped Instagram catalog as it would be once the «pending» sources are settled for some operations: their
+/// headers and fields with a «pending» source dropped and the operation configured (the «page» section already names a
+/// place for every session value they use). Only for the tests of the site client contract, which need an Instagram
+/// operation the guard lets through; the shipped file keeps them not configured (rule 9).
///
public static class SettledCatalog
{
- /// The operations whose variables the shapes show whole (only the headers and fields wait for S4).
+ /// The operations whose variables the shapes show whole (only headers and fields still «pending» wait).
public static IReadOnlyList KnownVariables { get; } =
[
"PolarisProfileReelsTabContentQuery", "PolarisProfileTaggedTabContentQuery",
diff --git a/tests/Febe.Tests/Collection/TestSiteSessionTests.cs b/tests/Febe.Tests/Collection/TestSiteSessionTests.cs
new file mode 100644
index 0000000..a10b626
--- /dev/null
+++ b/tests/Febe.Tests/Collection/TestSiteSessionTests.cs
@@ -0,0 +1,121 @@
+using Febe.Core.Abstractions;
+using Febe.Core.Collection;
+using Febe.Core.Collection.Requests;
+using Febe.SitoDiProva;
+using Febe.Tests.Support;
+using VirtualClock = Febe.Tests.Browser.TestSupport.VirtualClock;
+
+namespace Febe.Tests.Collection;
+
+///
+/// What the test site gives its pages for the copy at «Ho finito» (issue #36, S4, spec §14.2): the cookies a real site
+/// sets (the session, csrftoken, one limited to /api/), a module registry of its own whose names are the
+/// page section of richieste.prova.json (never Instagram's), and a /api/graphql that refuses a
+/// wrong or missing value of the page as it refuses a wrong token. No browser.
+///
+[TestClass]
+[TestCategory(SyntheticSite.Category)]
+public sealed class TestSiteSessionTests
+{
+ public TestContext TestContext { get; set; } = null!;
+
+ [TestMethod]
+ public async Task AVisitSetsTheSessionCsrftokenAndTheApiPathCookie()
+ {
+ await using var site = await SyntheticSite.StartAsync();
+ using var client = new HttpClient(new SocketsHttpHandler { UseProxy = false, UseCookies = false, AllowAutoRedirect = false });
+ using var response = await client.GetAsync(new Uri(site.Url("/")), TestContext.CancellationToken);
+ var lines = response.Headers.GetValues("Set-Cookie").ToList();
+
+ string Line(string name) => lines.Single(l => l.StartsWith(name + "=", StringComparison.Ordinal));
+ StringAssert.Contains(Line(TestSite.SessionCookie), "path=/;");
+ StringAssert.Contains(Line(TestSite.SessionCookie).ToLowerInvariant(), "httponly");
+ var csrf = Line(TestSite.CsrfCookie);
+ StringAssert.Contains(csrf, "path=/;");
+ Assert.DoesNotContain("httponly", csrf.ToLowerInvariant(), "the page reads it to send it back in x-csrftoken");
+ StringAssert.Contains(Line(TestSite.ApiPathCookie), "path=/api/");
+
+ // A second visit with the session and the token keeps them: no new cookie.
+ var session = Line(TestSite.SessionCookie).Split(';')[0];
+ var token = csrf.Split(';')[0];
+ using var again = new HttpRequestMessage(HttpMethod.Get, new Uri(site.Url("/")));
+ again.Headers.TryAddWithoutValidation("Cookie", $"{session}; {token}");
+ using var second = await client.SendAsync(again, TestContext.CancellationToken);
+ Assert.IsFalse(second.Headers.Contains("Set-Cookie"));
+ }
+
+ [TestMethod]
+ public async Task ThePageModulesAreThoseOfTheCatalogsPageSectionWithTheValuesTheSiteChecks()
+ {
+ var catalog = RequestCatalog.LoadTestSite();
+ var page = catalog.Page!;
+ var modules = TestSite.PageModules("1234");
+ var expected = HttpSiteRequesterTests.PageValues();
+ foreach (var field in page.Order)
+ {
+ var source = page.Values[field];
+ Assert.IsTrue(modules.TryGetValue(source.Module, out var module), $"{field}: module {source.Module}");
+ Assert.IsTrue(module.TryGetValue(source.Property, out var value), $"{field}: {source}");
+ Assert.AreEqual(field == "account_id" ? "1234" : expected[field], value, field);
+ }
+
+ foreach (var operation in catalog.Operations.Where(o => o.Kind == OperationKind.GraphQl))
+ {
+ var module = page.DocIdModuleFor(operation.Name)!;
+ Assert.AreEqual(operation.Name + TestSite.DocIdModuleSuffix, module);
+ Assert.AreEqual(TestSite.DocIds[operation.Name], modules[module][string.Empty]);
+ }
+
+ // Never Instagram's names in the test site.
+ foreach (var name in modules.Keys)
+ {
+ Assert.DoesNotContain("instagram", name.ToLowerInvariant());
+ Assert.IsFalse(RequestCatalog.LoadInstagram().Page!.Values.Values.Any(s => s.Module == name), name);
+ }
+
+ // Every page of the site carries the registry first in its head.
+ await using var site = await SyntheticSite.StartAsync();
+ using var client = new HttpClient(new SocketsHttpHandler { UseProxy = false, UseCookies = false, AllowAutoRedirect = false });
+ foreach (var path in new[] { "/", "/benvenuto", "/profilo/marta.prova/" })
+ {
+ var html = await client.GetStringAsync(new Uri(site.Url(path)), TestContext.CancellationToken);
+ StringAssert.Contains(html, "");
+ return text.ToString();
+ }
+
+ /// Puts first in the head of .
+ internal static string InsertAfterHead(string html, string script)
+ {
+ var at = html.IndexOf("", StringComparison.Ordinal);
+ return at < 0 ? html : html.Insert(at + "".Length, script);
+ }
+
+ private static IEnumerable<(string Name, JsonNode Module)> Modules(string accountId)
+ {
+ yield return ("GettoniProva", new JsonObject { ["lsd"] = Lsd, ["dtsg"] = Dtsg });
+ yield return ("UtenteProva", new JsonObject { ["id"] = accountId, ["applicazione"] = AppId });
+ yield return ("VersioneProva", new JsonObject
+ {
+ ["revisione"] = Revision,
+ ["hs"] = HasteSession,
+ ["hsi"] = HasteSessionId,
+
+ // Numbers in the page, as a real page keeps them: the copy turns them into text.
+ ["dpr"] = int.Parse(Dpr, CultureInfo.InvariantCulture),
+ ["comet"] = int.Parse(CometReq, CultureInfo.InvariantCulture),
+ });
+ yield return ("ConnessioneProva", new JsonObject { ["classe"] = ConnectionClass });
+ yield return ("AvvioProva", new JsonObject { ["nonce"] = EntryNonce });
+ foreach (var (operation, docId) in DocIds.OrderBy(d => d.Key, StringComparer.Ordinal))
+ {
+ yield return (operation + DocIdModuleSuffix, JsonValue.Create(docId));
+ }
+ }
+
+ private static string Text(JsonNode? node) => node is JsonValue value && value.TryGetValue(out var number)
+ ? number.ToString(CultureInfo.InvariantCulture)
+ : node?.GetValue() ?? string.Empty;
+}
diff --git a/tools/Febe.SitoDiProva/SiteControl.cs b/tools/Febe.SitoDiProva/SiteControl.cs
index 41298c4..0ec604a 100644
--- a/tools/Febe.SitoDiProva/SiteControl.cs
+++ b/tools/Febe.SitoDiProva/SiteControl.cs
@@ -74,6 +74,7 @@ public sealed class SiteControl
private int _renewals;
private int _logins;
private int _claims;
+ private int _csrfTokens;
private StopMode _mode = StopMode.Normal;
private int _armAfter;
@@ -203,6 +204,9 @@ public sealed class SiteControl
}
}
+ /// A new value of the cookie csrftoken, as a visit without one gets.
+ internal string NextCsrf() => "csrf-prova-" + Interlocked.Increment(ref _csrfTokens).ToString(System.Globalization.CultureInfo.InvariantCulture);
+
/// A new claim value.
internal string NextClaim() => "claim-prova-" + Interlocked.Increment(ref _claims).ToString(System.Globalization.CultureInfo.InvariantCulture);
diff --git a/tools/Febe.SitoDiProva/TestSite.cs b/tools/Febe.SitoDiProva/TestSite.cs
index 354b7a4..de11c57 100644
--- a/tools/Febe.SitoDiProva/TestSite.cs
+++ b/tools/Febe.SitoDiProva/TestSite.cs
@@ -207,13 +207,23 @@ public sealed partial class TestSite : IAsyncDisposable
return;
}
- if (!Control.IsSession(context.Request.Cookies[SessionCookie]))
+ var opened = !Control.IsSession(context.Request.Cookies[SessionCookie]);
+ if (opened)
{
// No cookie, or one the site ended (a session that expired, a reset): the visit is a new login, with a new
// value that the site client accepts too once copied.
context.Response.Cookies.Append(SessionCookie, Control.OpenSession(), new CookieOptions { Path = "/", MaxAge = TimeSpan.FromDays(1), SameSite = SameSiteMode.Lax, HttpOnly = true });
}
+ if (opened || string.IsNullOrEmpty(context.Request.Cookies[CsrfCookie]))
+ {
+ // What a real site gives its pages besides the session (issue #36, S4): the token the page reads and sends
+ // back in x-csrftoken, and a cookie only for the addresses under /api/, which the copy at «Ho finito» must
+ // keep with its path.
+ context.Response.Cookies.Append(CsrfCookie, Control.NextCsrf(), new CookieOptions { Path = "/", MaxAge = TimeSpan.FromDays(1), SameSite = SameSiteMode.Lax });
+ context.Response.Cookies.Append(ApiPathCookie, ApiPathCookieValue, new CookieOptions { Path = ApiPath, MaxAge = TimeSpan.FromDays(1), SameSite = SameSiteMode.Lax, HttpOnly = true });
+ }
+
var segments = path.Split('/', StringSplitOptions.RemoveEmptyEntries).Select(Uri.UnescapeDataString).ToArray();
string html;
var status = 200;
@@ -265,6 +275,15 @@ public sealed partial class TestSite : IAsyncDisposable
html = html.Replace("