From 883ea4683cd9d9cd716f294c1abb9dbe6863aa7a Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Wed, 18 Nov 2026 11:41:35 +0100 Subject: [PATCH] =?UTF-8?q?Sessione=20salvata:=20copia=20alla=20chiusura?= =?UTF-8?q?=20della=20finestra=20e=20alla=20fine=20della=20guida,=20=C2=AB?= =?UTF-8?q?Serve=20=C2=ABHo=20finito=C2=BB=C2=BB,=20scelta=20per=20la=20co?= =?UTF-8?q?pia=20incompleta=20e=20stato=20in=20Collegamento=20(#36,=20S4b)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Risposte 1, 5, 6, 9 e 10 di Alberto a S4. I valori __spin_r, __spin_b e __spin_t si copiano dalla pagina come gli altri (su Instagram da SiteData, ipotesi H23, operazioni ancora non configurate; nel sito di prova dal modulo GiroProva). La sessione si copia anche quando si chiude la finestra del browser su Windows e quando il permesso di guida finisce, sempre prima che la pagina torni al motore e con le garanzie di «Ho finito». Con «richieste» «Collegato» vuole una sessione salvata leggibile, altrimenti lo stato è «Serve «Ho finito»» e il motore aspetta. Nuova impostazione sessione.copia-incompleta (sostituisci, predefinita, o tieni-completa) e riquadro della sessione salvata nella pagina Collegamento, con soli conteggi e nomi. Co-Authored-By: Claude Opus 5.5 --- docs/decisioni.md | 5 + docs/guida/Primo-collegamento.md | 40 ++- docs/guida/Problemi-comuni.md | 2 + docs/guida/Sicurezza-e-riservatezza.md | 11 +- src/Febe.App/BrowserConnectionService.cs | 248 +++++++++++++++- src/Febe.App/FebeApp.cs | 25 +- src/Febe.App/IFebePlatform.cs | 7 +- src/Febe.App/SessionCopier.cs | 149 +++++++++- .../Collection/Requests/RequestCatalog.cs | 6 +- .../Requests/SessionCopySettings.cs | 65 +++++ src/Febe.Core/Config/richieste.instagram.json | 61 ++-- src/Febe.Core/Config/richieste.prova.json | 10 +- src/Febe.Core/Engine/EngineRuntime.cs | 11 +- src/Febe.Core/Engine/EngineServices.cs | 6 +- src/Febe.Core/Engine/Monitor.cs | 2 + src/Febe.Desktop/Browser/WebView2Browser.cs | 2 +- src/Febe.Desktop/Browser/WebView2Host.cs | 40 ++- src/Febe.Web/Api/ConnectionApi.cs | 39 ++- src/Febe.Web/Api/EngineApi.cs | 10 +- src/Febe.Web/Api/FebeJsonContext.cs | 1 + src/Febe.Web/Api/Part2Dtos.cs | 29 +- src/Febe.Web/Connection/IConnectionService.cs | 46 ++- src/Febe.Web/Connection/PROTOCOLLO.md | 11 +- src/Febe.Web/wwwroot/css/febe.css | 9 + src/Febe.Web/wwwroot/js/core/shell.js | 2 +- src/Febe.Web/wwwroot/js/pages/connection.js | 74 ++++- src/Febe.Web/wwwroot/testi/it.json | 23 ++ .../Febe.Tests.Windows/Support/DesktopBed.cs | 6 +- .../WebView2ConnectionTests.cs | 39 +++ .../Febe.Tests/Browser/SessionCaptureTests.cs | 98 +++++++ .../Collection/HttpSiteRequesterShapeTests.cs | 6 +- .../Collection/HttpSiteRequesterTests.cs | 5 +- .../Collection/RequestCatalogTests.cs | 17 +- .../SessionCaptureIntegrationTests.cs | 3 + .../Collection/SiteAnswerSignalsTests.cs | 4 +- .../Collection/TestSiteSessionTests.cs | 2 +- .../Desktop/SavedSessionConnectionTests.cs | 12 +- .../Desktop/SessionCopyOnLetGoTests.cs | 272 ++++++++++++++++++ .../Desktop/Support/FakeDesktopShell.cs | 34 +++ tools/Febe.SitoDiProva/DirectApi.cs | 12 +- tools/Febe.SitoDiProva/PageModules.cs | 6 + 41 files changed, 1349 insertions(+), 101 deletions(-) create mode 100644 src/Febe.Core/Collection/Requests/SessionCopySettings.cs create mode 100644 tests/Febe.Tests/Desktop/SessionCopyOnLetGoTests.cs diff --git a/docs/decisioni.md b/docs/decisioni.md index bd24b83..82296f5 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -420,3 +420,8 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15). | 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» | +| 2026-11-18 | Nuovi valori della sessione `spin_r`, `spin_b`, `spin_t` (`__spin_r`, `__spin_b`, `__spin_t`), copiati dalla pagina a «Ho finito» come gli altri: su Instagram dalle chiavi omonime di `SiteData` (`SiteData.__spin_r` …), nel sito di prova dal modulo suo `GiroProva` (`revisione` e `tempo` numeri, `ramo` testo), che il sito controlla nella richiesta GraphQL. Nelle dieci operazioni di Instagram le tre fonti passano da `pending` a `session:spin_*`, ma restano tutte non configurate | Risposta 1 di Alberto (#36, S4): un'istantanea della pagina; i valori che cambiano mentre la pagina gira (`__req`, `__s`, `__dyn`, `__csr` …) restano al browser. Che `SiteData` tenga quelle chiavi viene dalla forma del codice pubblico della pagina già usata in S4; chi le mette nella richiesta resta da vedere dal vivo (H23), e finché `__req`, `__s`, `__dyn`, `__csr` non hanno fonte nessuna operazione si configura comunque | +| 2026-11-18 | La sessione si copia anche alla chiusura della finestra «Browser di Febe» su Windows (anche ridotta a icona troppo a lungo) e quando il permesso di guida di «Accedi» / «Usa il browser» finisce da solo, sempre prima che la pagina torni al motore: la finestra tiene una presa del permesso di guida finché la copia non è finita (`WebView2HostOptions.CopyOnClose`, `FebePlatformContext.CopyOnWindowClosed`), la fine del permesso copia prima di rilasciarlo; in tutti e due i casi i comandi del collegamento, la presa del permesso e il turno della pagina come a «Ho finito», solo con il cookie di sessione nel browser, solo da una pagina del sito che non sia di accesso o di verifica. Nessun messaggio, una riga di registro con soli conteggi; la fine del permesso non copia di nuovo se la finestra ha appena copiato (un segno di guida entro un giro di controllo dalla copia è la presa della finestra) | Risposta 5 di Alberto. Sotto le stesse garanzie di «Ho finito» per la regola 7: la pagina non è mai letta quando è del motore. In Docker c'è solo la fine del permesso (la vista remota non ha una finestra da chiudere); la chiusura della finestra ha un limite di 30 s (`LetGoWait`) perché non trattenga il motore se un altro comando del collegamento è in corso | +| 2026-11-18 | Con la raccolta «richieste» e una sessione salvata nella composizione, «Collegato» vuole anche una sessione salvata leggibile: senza, lo stato è `SessionCopyMissing` (`copyMissing`, «Serve «Ho finito»»), `EngineRuntime.IsConnected` è falso e il motore aspetta con il titolo «Serve «Ho finito»»; la pagina Collegamento apre la pagina iniziale (non l'accesso) e spiega che cosa fare. Con «pagine» non cambia nulla | Risposta 6 di Alberto. Senza copia le ricette per richieste si fermerebbero alla prima come disconnessione: meglio aspettare e dirlo. La strada di «Pagina iniziale» resta quella del cookie | +| 2026-11-18 | Impostazione `sessione.copia-incompleta` (`SessionCopySettings`, tabella `setting`): `sostituisci` (predefinita) o `tieni-completa`. Con `tieni-completa` una copia a cui manca un valore o un `doc_id` che un'operazione configurata manda non sostituisce una copia salvata che li ha tutti, e «Ho finito» lo dice; altrimenti sostituisce come in S4. Letta a ogni copia (nessun riavvio), `GET`/`PUT /api/connection/settings`, scelta nel riquadro della pagina Collegamento | Risposta 9 di Alberto: un'opzione, con il comportamento di S4 come predefinito perché una copia più vecchia potrebbe avere i cookie di un altro accesso; il messaggio consiglia «Sostituisci comunque» dopo un nuovo accesso o un cambio di account | +| 2026-11-18 | La pagina Collegamento mostra la sessione salvata (riquadro «Sessione salvata per le richieste»): data della copia, valori della pagina e `doc_id` presenti su quelli letti, numero di cookie, nomi di quelli mancanti e quanti servono alle operazioni configurate; `GET /api/connection` li porta in `savedSession` (solo conteggi e nomi, mai valori; `null` con «pagine»). La data si scrive nel fuso del browser | Risposta 10 di Alberto. I nomi dei campi e delle operazioni non sono valori (regola 10); il rapporto (`ISessionCopier.Report`) li calcola dalla sessione in memoria, senza leggere il file | diff --git a/docs/guida/Primo-collegamento.md b/docs/guida/Primo-collegamento.md index c18ee78..dd184b7 100644 --- a/docs/guida/Primo-collegamento.md +++ b/docs/guida/Primo-collegamento.md @@ -37,13 +37,37 @@ fa anche una **copia della sessione** per le richieste dirette di Febe: i cookie 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. +mancava qualche valore che serve alle richieste. Le richieste che usano un 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. + +Febe copia la sessione anche quando lasci il browser **senza** «Ho finito», sempre prima di riprenderselo e solo da una +pagina del sito che non sia di accesso o di verifica: + +- **su Windows**, quando chiudi la finestra «Browser di Febe» (o la lasci ridotta a icona troppo a lungo); +- **in Docker e su Windows**, quando dopo «Accedi a Instagram» o «Usa il browser» non usi più il browser per 2 minuti + e la guida finisce da sola. + +In questi casi non compare nessun messaggio: il registro dice com'è andata (solo conteggi, mai valori), e la pagina +Collegamento mostra la copia. + +**«Collegato» con la raccolta «richieste».** Il cookie di sessione nel browser non basta: serve anche una copia +leggibile della sessione. Se manca (per esempio dopo «Annulla», o se il file non si legge più), lo stato è **«Serve «Ho +finito»»**, il motore aspetta e la pagina Collegamento apre la tua pagina iniziale nel browser: premi «Ho finito». + +**La sessione salvata nella pagina Collegamento.** Da collegato, il riquadro «Sessione salvata per le richieste» dice +quando è stata copiata, quanti valori della pagina e quanti `doc_id` ci sono su quelli che Febe legge, quanti cookie, e +il nome di quelli che mancano (mai i valori). Sotto c'è la scelta **«Se una copia nuova è incompleta»**: + +- **«Sostituisci comunque»** (il predefinito, consigliato): la copia nuova prende sempre il posto di quella salvata, + perché una copia più vecchia potrebbe avere i cookie di un altro accesso; +- **«Tieni la copia completa»**: se alla copia nuova manca qualcosa che le richieste usano e quella salvata ha tutto, + Febe tiene quella salvata e il messaggio di «Ho finito» lo dice. Se hai rifatto l'accesso o cambiato account, torna a + «Sostituisci comunque». + +La scelta vale dalla copia successiva, senza riavviare. Con `pagine`, il predefinito, e con Instagram per ora anche con +`richieste`, «Ho finito» non copia nulla, guarda solo se il cookie di sessione esiste e il riquadro non c'è. «Annulla» torna alle impostazioni senza collegarti. @@ -66,7 +90,7 @@ sua copia cifrata): **chi ha la cartella dei dati, o una sua copia, ha la sessio «Prudente»). - La prima sessione parte tra 2 e 10 minuti dopo l'avvio, e solo dentro la fascia oraria. - Lo stato del collegamento è sempre in fondo alla barra laterale: collegato, da collegare, verifica richiesta, sessione - chiusa. + chiusa e, con la raccolta «richieste», «Serve «Ho finito»». - Il tuo profilo compare tra gli account segnato «Tu», con «Post in cui è taggato» attivo: è così che si scaricano i post in cui sei taggato. Su Instagram i dati della pagina danno solo l'identificativo del tuo account: Febe ti riconosce quando compare anche il tuo profilo (per esempio la tua voce nella barra delle storie); fino ad allora la diff --git a/docs/guida/Problemi-comuni.md b/docs/guida/Problemi-comuni.md index 3507fee..07874d7 100644 --- a/docs/guida/Problemi-comuni.md +++ b/docs/guida/Problemi-comuni.md @@ -33,6 +33,8 @@ dati. | 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 | +| «Serve «Ho finito»» (barra laterale o pagina Collegamento) | Solo con la raccolta «richieste»: il browser ha la sessione, ma Febe non ha una copia leggibile per le richieste (dopo «Annulla», o con un file che non si legge più). Il motore aspetta: dalla pagina Collegamento apri la tua pagina iniziale nel browser e premi «Ho finito» | +| «Alla pagina mancavano … Febe tiene la copia completa salvata prima e non usa quella nuova» | Hai scelto «Tieni la copia completa» nella pagina Collegamento e alla pagina mancava un valore che le richieste usano. Se hai rifatto l'accesso o cambiato account, scegli «Sostituisci comunque» e premi di nuovo «Ho finito» | | «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)) | diff --git a/docs/guida/Sicurezza-e-riservatezza.md b/docs/guida/Sicurezza-e-riservatezza.md index 5bd361e..5016ac9 100644 --- a/docs/guida/Sicurezza-e-riservatezza.md +++ b/docs/guida/Sicurezza-e-riservatezza.md @@ -17,16 +17,19 @@ copia altrove. ### 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. +`sessione/sessione.json`, nella cartella dei dati, per le richieste dirette di Febe; la copia si fa anche quando chiudi +la finestra del browser su Windows e quando la guida del browser finisce da sola (vedi +[Primo collegamento](Primo-collegamento)). 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. +- Non va nel database, nelle copie giornaliere, nel rapporto di diagnostica né nell'interfaccia: la pagina Collegamento + ne mostra solo la data, i conteggi e i nomi dei valori che mancano. 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, diff --git a/src/Febe.App/BrowserConnectionService.cs b/src/Febe.App/BrowserConnectionService.cs index 5bee24e..3a56e4d 100644 --- a/src/Febe.App/BrowserConnectionService.cs +++ b/src/Febe.App/BrowserConnectionService.cs @@ -4,6 +4,7 @@ using Febe.Browser.Hosting; using Febe.Browser.Session; using Febe.Core.Abstractions; using Febe.Core.Collection; +using Febe.Core.Collection.Requests; using Febe.Core.Domain; using Febe.Core.Engine; using Febe.Core.Storage; @@ -40,6 +41,14 @@ namespace Febe.App; /// (spec §7.6): reported to the breaker as the recipes would, so that it is an incident with its alert and only /// «Riprendi» restarts the engine. Not when Alberto himself is at the browser, nor after his «Scollega». /// +/// +/// With a saved session (issue #36, S4b) the session is copied at «Ho finito», and also when Alberto lets go of the +/// browser without it: the window «Browser di Febe» closed on Windows () and the +/// lease of «Accedi» / «Usa il browser» ending by itself. Always before the page goes back to the engine, with the +/// same guarantees as «Ho finito» (the driving gate held, the page's turn), and only from a page of the site that is +/// not a login or verification page. «Collegato» then also needs a readable saved session: without one the state is +/// («Serve «Ho finito»») and the engine waits. +/// /// public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposable { @@ -74,6 +83,7 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa private bool? _connected; private bool? _disconnectedByUser; private DateTimeOffset _checkedAt = DateTimeOffset.MinValue; + private DateTimeOffset _lastCopyAt = DateTimeOffset.MinValue; /// The browser of Febe. /// The database (first connection, «Scollega»). @@ -119,6 +129,24 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa } } + /// + /// True when the composition keeps a saved session (raccolta «richieste») and there is no readable one: the cookie + /// alone is not «Collegato», the copy of «Ho finito» is missing (issue #36, S4b, answer 6). + /// + public bool SessionCopyMissing => _copier is not null && _copier.SavedState != SavedSessionState.Present; + + /// + /// Whether the engine may collect (): the session cookie is in the browser + /// and, with a saved session, a readable copy of it is there too. + /// + public bool IsReadyToCollect => IsConnected == true && !SessionCopyMissing; + + /// + /// How long a copy when Alberto closes the browser window waits, at most, for the commands of the connection and for + /// the copy itself (real time); then it gives up and the window gives the page back. Tests shorten it. + /// + public TimeSpan LetGoWait { get; set; } = TimeSpan.FromSeconds(30); + /// /// Where the browser goes when Alberto takes it from the rest page or presses «Pagina iniziale» (issue #52): the /// site's home when the session is there, the login page when it is not (or not known yet) and after a disconnection @@ -161,6 +189,11 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa var state = breaker is BreakerStatus.Challenge or BreakerStatus.Disconnected ? ConnectionState.VerificationRequired : await CheckAsync(force: false, mayReport: true, ct).ConfigureAwait(false) == true ? ConnectionState.Connected : ConnectionState.NotConnected; + var saved = _copier?.Report(); + if (state == ConnectionState.Connected && saved is not null && saved.State != SavedSessionState.Present) + { + state = ConnectionState.SessionCopyMissing; + } Account? mine = null; if (state != ConnectionState.NotConnected) @@ -168,7 +201,47 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa mine = await _storage.Accounts.GetMineAsync(ct).ConfigureAwait(false); } - return new ConnectionStatus(state, mine?.Username, mine?.DisplayName, driving, await CurrentUrlAsync(ct).ConfigureAwait(false)); + return new ConnectionStatus(state, mine?.Username, mine?.DisplayName, driving, await CurrentUrlAsync(ct).ConfigureAwait(false), ToStatus(saved)); + } + + /// + /// The window «Browser di Febe» was closed by Alberto without «Ho finito» (Windows, issue #36, S4b, answer 5): the + /// session is copied while the page is still his. The caller (the window) holds the driving gate until this returns, + /// so the page goes back to the engine only afterwards. Gives up after . Never throws for the + /// browser; logs counts only. + /// + public async Task CopyOnWindowClosedAsync(CancellationToken ct) + { + const string What = "Finestra del browser chiusa"; + if (_copier is null || !_browser.IsAvailable) + { + return; + } + + using var limit = CancellationTokenSource.CreateLinkedTokenSource(ct); + limit.CancelAfter(LetGoWait); + try + { + await _commands.WaitAsync(limit.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) when (limit.IsCancellationRequested) + { + _log.Info("collegamento", $"{What}: sessione non copiata, un altro comando del collegamento era ancora in corso."); + return; + } + catch (ObjectDisposedException) + { + return; // Febe is stopping + } + + try + { + await CopyOnLetGoAsync(What, () => _browser.UserIsDriving, limit.Token).ConfigureAwait(false); + } + finally + { + ReleaseCommands(); + } } public async Task BeginUserDrivingAsync(bool openLogin, CancellationToken ct) @@ -653,7 +726,18 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa lastSign = _lastDrivingSign; } - if (_clock.Now - lastSign >= grace && ReleaseLease(lease)) + if (_clock.Now - lastSign < grace) + { + continue; + } + + // Before the page goes back to the engine: the copy of the session (S4b, answer 5). + if (!await CopyBeforeLeaseEndsAsync(lease, lastSign, poll, ct).ConfigureAwait(false)) + { + continue; + } + + if (ReleaseLease(lease)) { _log.Info("collegamento", $"Nessuna vista del browser aperta da {ItalianText.Duration(grace)} senza «Ho finito» né «Annulla»: il motore può riprendere."); return; @@ -666,6 +750,163 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa } } + /// + /// The copy when the lease of «Accedi» / «Usa il browser» is about to end by itself (S4b, answer 5), while it still + /// holds. Not when a copy was already made since the last sign that Alberto used the browser (the window closed a + /// moment before): the window's own hold lasts a moment after its copy, so a sign within one look + /// () of the copy is that hold, not Alberto. False when the lease must not end now: a sign of + /// driving came while the copy waited for its turn. + /// + private async Task CopyBeforeLeaseEndsAsync(IDisposable lease, DateTimeOffset lastSign, TimeSpan poll, CancellationToken ct) + { + if (_copier is null) + { + return true; + } + + lock (_gate) + { + if (_lastCopyAt != DateTimeOffset.MinValue && _lastCopyAt >= lastSign - poll) + { + return true; + } + } + + // Cancelled when «Ho finito», «Annulla» or «Scollega» end the lease meanwhile: then they decide. + await _commands.WaitAsync(ct).ConfigureAwait(false); + try + { + bool StillAlbertos() + { + lock (_gate) + { + return ReferenceEquals(_lease, lease); + } + } + + if (!StillAlbertos()) + { + return true; + } + + if (_browser.UserDriving.Leases > 1) + { + // The remote view or the window came back while this waited: the lease goes on. + lock (_gate) + { + _lastDrivingSign = _clock.Now; + } + + return false; + } + + await CopyOnLetGoAsync("Fine della guida del browser", StillAlbertos, ct).ConfigureAwait(false); + return true; + } + finally + { + ReleaseCommands(); + } + } + + /// + /// The copy when Alberto lets go of the browser without «Ho finito»: only while the page is still his, only when the + /// browser holds the session, with the driving gate held and the page's turn, like «Ho finito». The copier refuses a + /// page off the site or a login or verification page. One log line with the outcome (counts only). + /// + private async Task CopyOnLetGoAsync(string what, Func stillAlbertos, CancellationToken ct) + { + try + { + if (!_browser.UserIsDriving) + { + _log.Info("collegamento", $"{what}: sessione non copiata, il browser era già tornato al motore."); + return; + } + + if (await CheckAsync(force: true, mayReport: false, ct).ConfigureAwait(false) != true) + { + _log.Info("collegamento", $"{what}: nessuna sessione nel browser, niente da copiare."); + return; + } + + 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", $"{what}: sessione non copiata, la pagina era occupata dalla ricerca dei profili."); + return; + } + + var outcome = await _copier!.CopyAsync(stillAlbertos, ct).ConfigureAwait(false); + lock (_gate) + { + _lastCopyAt = _clock.Now; + } + + _log.Info("collegamento", $"{what}: {LetGoSummary(outcome)}."); + } + finally + { + hold.Dispose(); + } + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) + { + _log.Info("collegamento", $"{what}: sessione non copiata, il browser non ha risposto in tempo."); + } + } + + /// What a copy without «Ho finito» did, for the log (counts only). + internal static string LetGoSummary(SessionCopyOutcome copy) + { + ArgumentNullException.ThrowIfNull(copy); + var missing = copy.MissingValues + copy.MissingDocIds; + var clause = missing == 0 ? string.Empty : string.Create(CultureInfo.InvariantCulture, $", ma mancano {missing} valori che servono alle richieste"); + return copy.Status switch + { + SessionCopyStatus.Saved => "sessione copiata" + clause, + SessionCopyStatus.SavedInMemoryOnly => "sessione copiata, non ancora scritta su disco" + clause, + SessionCopyStatus.KeptComplete => string.Create(CultureInfo.InvariantCulture, $"copia incompleta ({missing} valori mancanti), resta quella completa salvata prima"), + SessionCopyStatus.Discarded => "sessione letta ma non salvata, il browser era tornato al motore", + _ => $"sessione non copiata, {BrowserSessionCopier.Reason(copy.Refusal ?? CaptureRefusal.BrowserError)}; la sessione salvata resta com'era", + }; + } + + /// The saved session for the interface, in counts and names; null without a saved session in this start. + private static SavedSessionStatus? ToStatus(SavedSessionReport? report) => report is null + ? null + : new SavedSessionStatus( + report.State switch + { + SavedSessionState.Present => SavedSessionStatus.Present, + SavedSessionState.Unreadable => SavedSessionStatus.Unreadable, + _ => SavedSessionStatus.None, + }, + report.CopiedAt, + report.Cookies, + report.ValuesPresent, + report.ValuesExpected, + report.MissingValues, + report.DocIdsPresent, + report.DocIdsExpected, + report.MissingDocIds, + report.NeededMissing); + + private void ReleaseCommands() + { + try + { + _commands.Release(); + } + catch (ObjectDisposedException) + { + // Febe stopped while the copy ran. + } + } + /// The first connection ever starts the gradual start (spec §7.2). True when it was the first. private async Task MarkConnectedAsync(CancellationToken ct) { @@ -801,6 +1042,9 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa "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.", + SessionCopyStatus.KeptComplete => string.Create( + CultureInfo.InvariantCulture, + $"Alla pagina mancavano {missing} valori che servono alle richieste: come hai scelto nella pagina Collegamento («Tieni la copia completa»), Febe tiene la copia completa salvata prima e non usa quella nuova. Se nel frattempo hai rifatto l'accesso o cambiato account, scegli «Sostituisci comunque». {Again}"), _ 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}", _ => diff --git a/src/Febe.App/FebeApp.cs b/src/Febe.App/FebeApp.cs index 81034e2..502a112 100644 --- a/src/Febe.App/FebeApp.cs +++ b/src/Febe.App/FebeApp.cs @@ -261,7 +261,16 @@ public sealed class FebeApp : IAsyncDisposable // Browser, connection, engine. The engine loop starts only once the browser is up. // «Pagina iniziale» (issue #52) is the connection's, which exists only after the browser: looked up when pressed. - var context = new FebePlatformContext(o, data, Database, Clock, Log, Tracker, ct => Connection?.OpenStartPageAsync(ct) ?? Task.CompletedTask); + // The copy when Alberto closes the browser window (S4b) is the connection's too, looked up when it happens. + var context = new FebePlatformContext( + o, + data, + Database, + Clock, + Log, + Tracker, + ct => Connection?.OpenStartPageAsync(ct) ?? Task.CompletedTask, + ct => Connection?.CopyOnWindowClosedAsync(ct) ?? Task.CompletedTask); var browser = await _platform.CreateBrowserAsync(context, ct).ConfigureAwait(false); Browser = browser; PrepareSavedSession(context, browser); @@ -286,8 +295,9 @@ public sealed class FebeApp : IAsyncDisposable random, engineOptions, userIsDriving: () => browser.UserIsDriving, - isConnected: () => connection.IsConnected == true, - ct: ct).ConfigureAwait(false); + isConnected: () => connection.IsReadyToCollect, + ct: ct, + sessionCopyMissing: () => connection.IsConnected == true && connection.SessionCopyMissing).ConfigureAwait(false); // The diagnostic report (issue #39): one recorder for the engine, the pipeline and the interface. What the // capture sees goes to the session in progress, if any. var diagnostics = new CollectionDiagnostics(Clock, () => services.Runtime.CurrentSession?.SessionId, new DiagnosticLog(data.Diagnostics, Clock)); @@ -576,10 +586,15 @@ public sealed class FebeApp : IAsyncDisposable 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)); + var settings = context.Storage.Settings; + _copier = new BrowserSessionCopier(browser.Cdp, SessionCapturePlan.For(o.Site, catalog, rules), saved, Clock, message => Log.Info("sessione", message)) + { + // What an incomplete copy does (S4b): read at every copy, so a change on the Collegamento page holds at once. + IncompleteCopy = async token => (await SessionCopySettings.LoadAsync(settings, token).ConfigureAwait(false)).IncompleteCopy, + }; _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»."); + 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», alla chiusura della finestra del browser e alla fine della guida."); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or CryptographicException or PlatformNotSupportedException) { diff --git a/src/Febe.App/IFebePlatform.cs b/src/Febe.App/IFebePlatform.cs index 0b43683..11bbc58 100644 --- a/src/Febe.App/IFebePlatform.cs +++ b/src/Febe.App/IFebePlatform.cs @@ -72,7 +72,12 @@ public interface IFebePlatform /// the login page otherwise, once the engine's session ended and with the page's turn /// (BrowserConnectionService.OpenStartPageAsync). Null: the button does nothing. /// -public sealed record FebePlatformContext(FebeAppOptions Options, DataFolderLayout Data, IFebeStorage Storage, IClock Clock, FebeLog Log, BrowserUseTracker Tracker, Func? OpenStartPage = null); +/// +/// What closing the browser window does before the page goes back to the engine (issue #36, S4b): the connection copies +/// the session into the saved session, when there is one (BrowserConnectionService.CopyOnWindowClosedAsync). The +/// window holds the driving gate until the task ends. Null: nothing. +/// +public sealed record FebePlatformContext(FebeAppOptions Options, DataFolderLayout Data, IFebeStorage Storage, IClock Clock, FebeLog Log, BrowserUseTracker Tracker, Func? OpenStartPage = null, Func? CopyOnWindowClosed = null); /// Options of the shared composition, filled by each shell from its own configuration. public sealed record FebeAppOptions diff --git a/src/Febe.App/SessionCopier.cs b/src/Febe.App/SessionCopier.cs index 0a9bc85..467ff5a 100644 --- a/src/Febe.App/SessionCopier.cs +++ b/src/Febe.App/SessionCopier.cs @@ -19,6 +19,12 @@ public enum SessionCopyStatus /// Copied, then thrown away: meanwhile the page was no longer Alberto's (rule 7). Discarded, + + /// + /// Copied but not saved: a value the requests need was missing, the saved copy has them all, and Alberto chose + /// «Tieni la copia completa» (). The saved session stays as it was. + /// + KeptComplete, } /// What a copy did, for the message of «Ho finito» and the tests. Never a value. @@ -34,11 +40,42 @@ public sealed record SessionCopyOutcome(SessionCopyStatus Status, CaptureRefusal } /// -/// 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. +/// The saved session as the Collegamento page shows it (issue #36, S4b, answer 10): its state, when it was copied, how +/// many values of the page and doc_id it holds and the names of those it lacks. Counts and names only, never a value. +/// +/// Whether a saved session is there and can be read. +/// When the browser's session was copied; null without a session or when not known. +/// How many cookies it holds. +/// Values of the page it holds, of . +/// Values of the page the copy reads. +/// Names of the values of the page it lacks. +/// doc_id it holds, of . +/// doc_id the copy reads. +/// Operations whose doc_id it lacks. +/// How many of the missing values and doc_id a configured operation sends. +public sealed record SavedSessionReport( + SavedSessionState State, + DateTimeOffset? CopiedAt, + int Cookies, + int ValuesPresent, + int ValuesExpected, + IReadOnlyList MissingValues, + int DocIdsPresent, + int DocIdsExpected, + IReadOnlyList MissingDocIds, + int NeededMissing) +{ + /// True when a readable session is there and nothing a configured operation sends is missing. + public bool Complete => State == SavedSessionState.Present && NeededMissing == 0; +} + +/// +/// Copies the session of Febe's browser into the saved session (issue #36, S4, spec §6.0): at «Ho finito», after the +/// automatic login of the test site, and (S4b) when Alberto closes the browser window on Windows or his driving lease +/// ends by itself. 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 — unless Alberto chose «Tieni la copia completa» and the saved one is complete. +/// The requests that send a missing value 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 { @@ -48,6 +85,12 @@ public interface ISessionCopier /// 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); + + /// Whether a saved session is there and can be read (cheap: «Collegato» and the engine ask it often). + SavedSessionState SavedState { get; } + + /// The saved session now, in counts and names (the Collegamento page, «Collegato»). + SavedSessionReport Report(); } /// @@ -76,6 +119,12 @@ public sealed class BrowserSessionCopier : ISessionCopier _log = log ?? throw new ArgumentNullException(nameof(log)); } + /// + /// What an incomplete copy does, asked at every copy (the setting of the Collegamento page, + /// ); by default it replaces the saved session, as before. + /// + public Func> IncompleteCopy { get; init; } = _ => Task.FromResult(IncompleteCopyChoice.Replace); + /// /// 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). @@ -116,15 +165,24 @@ public sealed class BrowserSessionCopier : ISessionCopier 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(); + + // An incomplete copy replaces the saved one (§6.0: an older copy could keep another login's cookies), unless + // Alberto chose to keep a complete one (answer 9 of 18 November 2026) and the saved one is complete. + if (needed.Count > 0 + && IsComplete(_store.Read()) + && await IncompleteCopy(CancellationToken.None).ConfigureAwait(false) == IncompleteCopyChoice.KeepComplete) + { + _log($"Sessione letta ma non salvata: mancano {string.Join(", ", needed)}, che servono alle operazioni configurate; come scelto, resta la copia completa salvata prima ({counts})."); + return new SessionCopyOutcome(SessionCopyStatus.KeptComplete, null, result.Cookies, neededValues.Count, neededDocIds.Count); + } + + // Not cancelled from here: the copy was made, and a half-written replacement is never left. + var onDisk = await _store.ReplaceAsync(values, CancellationToken.None).ConfigureAwait(false); _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") @@ -138,6 +196,52 @@ public sealed class BrowserSessionCopier : ISessionCopier neededDocIds.Count); } + public SavedSessionState SavedState => _store.State; + + public SavedSessionReport Report() + { + var state = _store.State; + var values = state == SavedSessionState.Present ? _store.Read() : null; + if (values is null) + { + var none = state == SavedSessionState.Present ? SavedSessionState.None : state; + return new SavedSessionReport(none, null, 0, 0, _plan.Values.Count, [], 0, _plan.DocIds.Count, [], 0); + } + + var missingValues = new List(); + var needed = 0; + foreach (var read in _plan.Values) + { + if (!values.Fields.ContainsKey(read.Field)) + { + missingValues.Add(read.Field); + needed += _plan.NeededValues.Contains(read.Field) ? 1 : 0; + } + } + + var missingDocIds = new List(); + foreach (var read in _plan.DocIds) + { + if (!values.DocIds.ContainsKey(read.Field)) + { + missingDocIds.Add(read.Field); + needed += _plan.NeededDocIds.Contains(read.Field) ? 1 : 0; + } + } + + return new SavedSessionReport( + SavedSessionState.Present, + values.CopiedAt, + values.Cookies.Count, + _plan.Values.Count - missingValues.Count, + _plan.Values.Count, + missingValues, + _plan.DocIds.Count - missingDocIds.Count, + _plan.DocIds.Count, + missingDocIds, + needed); + } + /// Why a copy was refused, in Italian. public static string Reason(CaptureRefusal refusal) => refusal switch { @@ -146,4 +250,31 @@ public sealed class BrowserSessionCopier : ISessionCopier CaptureRefusal.NoUserAgent => "il browser non ha dato il suo user agent", _ => "il browser non ha risposto", }; + + /// True when holds every value and doc_id a configured operation sends. + private bool IsComplete(SiteSessionValues? saved) + { + if (saved is null) + { + return false; + } + + foreach (var field in _plan.NeededValues) + { + if (!saved.Fields.ContainsKey(field)) + { + return false; + } + } + + foreach (var operation in _plan.NeededDocIds) + { + if (!saved.DocIds.ContainsKey(operation)) + { + return false; + } + } + + return true; + } } diff --git a/src/Febe.Core/Collection/Requests/RequestCatalog.cs b/src/Febe.Core/Collection/Requests/RequestCatalog.cs index bd3ff7a..360d294 100644 --- a/src/Febe.Core/Collection/Requests/RequestCatalog.cs +++ b/src/Febe.Core/Collection/Requests/RequestCatalog.cs @@ -57,12 +57,14 @@ public sealed record ValueSource(ValueSourceKind Kind, string? Argument) /// 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). + /// entry_nonce (x-fb-entry-nonce), and since S4b spin_r, spin_b and spin_t + /// (__spin_r, __spin_b, __spin_t: a snapshot of the page at «Ho finito», decision of 18 November + /// 2026). /// 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", + "rev", "hs", "hsi", "dpr", "ccg", "comet_req", "entry_nonce", "spin_r", "spin_b", "spin_t", }.ToFrozenSet(StringComparer.Ordinal); /// The session fields that need no page entry: the browser's user agent and the claim the site sets (H13). diff --git a/src/Febe.Core/Collection/Requests/SessionCopySettings.cs b/src/Febe.Core/Collection/Requests/SessionCopySettings.cs new file mode 100644 index 0000000..8a7194b --- /dev/null +++ b/src/Febe.Core/Collection/Requests/SessionCopySettings.cs @@ -0,0 +1,65 @@ +using Febe.Core.Storage; + +namespace Febe.Core.Collection.Requests; + +/// What a copy of the browser's session does when some value the requests need is missing (issue #36, S4b). +public enum IncompleteCopyChoice +{ + /// + /// «Sostituisci comunque» (the default): the new copy replaces the saved one all the same, because keeping an older + /// copy could keep the cookies of another login (§6.0). + /// + Replace, + + /// + /// «Tieni la copia completa»: when the saved copy has every value the configured operations need and the new one + /// does not, the saved one stays and the message says so. + /// + KeepComplete, +} + +/// +/// The settings of the copy of the session (issue #36, S4b; decision of Alberto of 18 November 2026, answer 9), in the +/// setting table like the other settings. Read at every copy: a change holds from the next copy, no restart. +/// +/// What an incomplete copy does. +public sealed record SessionCopySettings(IncompleteCopyChoice IncompleteCopy) +{ + /// The key of : sostituisci or tieni-completa. + public const string IncompleteCopyKey = "sessione.copia-incompleta"; + + /// The text of in the table and in the API. + public const string ReplaceText = "sostituisci"; + + /// The text of in the table and in the API. + public const string KeepCompleteText = "tieni-completa"; + + /// The settings of a database that never stored them: an incomplete copy replaces the saved one. + public static SessionCopySettings Default { get; } = new(IncompleteCopyChoice.Replace); + + /// The text of . + public static string ToText(IncompleteCopyChoice choice) => choice == IncompleteCopyChoice.KeepComplete ? KeepCompleteText : ReplaceText; + + /// The choice of ; null for any other text. + public static IncompleteCopyChoice? Parse(string? text) => text switch + { + ReplaceText => IncompleteCopyChoice.Replace, + KeepCompleteText => IncompleteCopyChoice.KeepComplete, + _ => null, + }; + + /// The stored settings; an unknown or missing value is the default. + public static async Task LoadAsync(ISettingsStore settings, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(settings); + var text = await settings.GetAsync(IncompleteCopyKey, ct).ConfigureAwait(false); + return Parse(text) is { } choice ? new SessionCopySettings(choice) : Default; + } + + /// Stores these settings. + public Task SaveAsync(ISettingsStore settings, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(settings); + return settings.SetAsync(IncompleteCopyKey, ToText(IncompleteCopy), ct); + } +} diff --git a/src/Febe.Core/Config/richieste.instagram.json b/src/Febe.Core/Config/richieste.instagram.json index 5c9ebd1..dffb37f 100644 --- a/src/Febe.Core/Config/richieste.instagram.json +++ b/src/Febe.Core/Config/richieste.instagram.json @@ -1,6 +1,6 @@ { "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 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.", + "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, __spin_r, __spin_b e __spin_t dalle chiavi omonime di SiteData (decisione di Alberto del 18 novembre 2026: si copiano dalla pagina a «Ho finito», come gli altri; chi le aggiunge alla richiesta resta da vedere, H23), 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, spin_r, spin_b, spin_t), 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 e __d, 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", @@ -15,7 +15,10 @@ "dpr": "SiteData.pr", "comet_req": "SiteData.comet_env", "ccg": "WebConnectionClassServerGuess.connectionClass", - "entry_nonce": "BootloaderConfig.nonce" + "entry_nonce": "BootloaderConfig.nonce", + "spin_r": "SiteData.__spin_r", + "spin_b": "SiteData.__spin_b", + "spin_t": "SiteData.__spin_t" } }, "operations": [ @@ -66,9 +69,9 @@ "__rev": "session:rev", "__s": "pending", "__sjsp": "pending", - "__spin_b": "pending", - "__spin_r": "pending", - "__spin_t": "pending", + "__spin_b": "session:spin_b", + "__spin_r": "session:spin_r", + "__spin_t": "session:spin_t", "__user": "session:account_id", "av": "session:account_id", "doc_id": "session:doc_id", @@ -148,9 +151,9 @@ "__rev": "session:rev", "__s": "pending", "__sjsp": "pending", - "__spin_b": "pending", - "__spin_r": "pending", - "__spin_t": "pending", + "__spin_b": "session:spin_b", + "__spin_r": "session:spin_r", + "__spin_t": "session:spin_t", "__user": "session:account_id", "av": "session:account_id", "doc_id": "session:doc_id", @@ -226,9 +229,9 @@ "__rev": "session:rev", "__s": "pending", "__sjsp": "pending", - "__spin_b": "pending", - "__spin_r": "pending", - "__spin_t": "pending", + "__spin_b": "session:spin_b", + "__spin_r": "session:spin_r", + "__spin_t": "session:spin_t", "__user": "session:account_id", "av": "session:account_id", "doc_id": "session:doc_id", @@ -310,9 +313,9 @@ "__rev": "session:rev", "__s": "pending", "__sjsp": "pending", - "__spin_b": "pending", - "__spin_r": "pending", - "__spin_t": "pending", + "__spin_b": "session:spin_b", + "__spin_r": "session:spin_r", + "__spin_t": "session:spin_t", "__user": "session:account_id", "av": "session:account_id", "doc_id": "session:doc_id", @@ -389,9 +392,9 @@ "__rev": "session:rev", "__s": "pending", "__sjsp": "pending", - "__spin_b": "pending", - "__spin_r": "pending", - "__spin_t": "pending", + "__spin_b": "session:spin_b", + "__spin_r": "session:spin_r", + "__spin_t": "session:spin_t", "__user": "session:account_id", "av": "session:account_id", "doc_id": "session:doc_id", @@ -465,9 +468,9 @@ "__rev": "session:rev", "__s": "pending", "__sjsp": "pending", - "__spin_b": "pending", - "__spin_r": "pending", - "__spin_t": "pending", + "__spin_b": "session:spin_b", + "__spin_r": "session:spin_r", + "__spin_t": "session:spin_t", "__user": "session:account_id", "av": "session:account_id", "doc_id": "session:doc_id", @@ -538,9 +541,9 @@ "__rev": "session:rev", "__s": "pending", "__sjsp": "pending", - "__spin_b": "pending", - "__spin_r": "pending", - "__spin_t": "pending", + "__spin_b": "session:spin_b", + "__spin_r": "session:spin_r", + "__spin_t": "session:spin_t", "__user": "session:account_id", "av": "session:account_id", "doc_id": "session:doc_id", @@ -618,9 +621,9 @@ "__rev": "session:rev", "__s": "pending", "__sjsp": "pending", - "__spin_b": "pending", - "__spin_r": "pending", - "__spin_t": "pending", + "__spin_b": "session:spin_b", + "__spin_r": "session:spin_r", + "__spin_t": "session:spin_t", "__user": "session:account_id", "av": "session:account_id", "doc_id": "session:doc_id", @@ -699,9 +702,9 @@ "__rev": "session:rev", "__s": "pending", "__sjsp": "pending", - "__spin_b": "pending", - "__spin_r": "pending", - "__spin_t": "pending", + "__spin_b": "session:spin_b", + "__spin_r": "session:spin_r", + "__spin_t": "session:spin_t", "__user": "session:account_id", "av": "session:account_id", "doc_id": "session:doc_id", diff --git a/src/Febe.Core/Config/richieste.prova.json b/src/Febe.Core/Config/richieste.prova.json index 40ba8df..39744c1 100644 --- a/src/Febe.Core/Config/richieste.prova.json +++ b/src/Febe.Core/Config/richieste.prova.json @@ -15,7 +15,10 @@ "dpr": "VersioneProva.dpr", "comet_req": "VersioneProva.comet", "ccg": "ConnessioneProva.classe", - "entry_nonce": "AvvioProva.nonce" + "entry_nonce": "AvvioProva.nonce", + "spin_r": "GiroProva.revisione", + "spin_b": "GiroProva.ramo", + "spin_t": "GiroProva.tempo" } }, "operations": [ @@ -104,6 +107,9 @@ "__hs": "session:hs", "__hsi": "session:hsi", "__rev": "session:rev", + "__spin_r": "session:spin_r", + "__spin_b": "session:spin_b", + "__spin_t": "session:spin_t", "dpr": "session:dpr", "fb_dtsg": "session:fb_dtsg", "lsd": "session:lsd", @@ -121,7 +127,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). I campi di versione (__rev, __hs, __hsi, __ccg, dpr, __comet_req) e x-fb-entry-nonce vengono dalla sessione salvata, come su Instagram." + "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, __spin_r, __spin_b, __spin_t) e x-fb-entry-nonce vengono dalla sessione salvata, come su Instagram." }, { "name": "profilo-altri", diff --git a/src/Febe.Core/Engine/EngineRuntime.cs b/src/Febe.Core/Engine/EngineRuntime.cs index 4132c0d..074eab2 100644 --- a/src/Febe.Core/Engine/EngineRuntime.cs +++ b/src/Febe.Core/Engine/EngineRuntime.cs @@ -12,6 +12,7 @@ public sealed class EngineRuntime private readonly Lock _gate = new(); private readonly Func _userIsDriving; private readonly Func? _isConnected; + private readonly Func? _sessionCopyMissing; private CautionProfile _profile = CautionProfile.Prudent; private DateTimeOffset? _rampStart; private SessionContext? _session; @@ -23,10 +24,15 @@ public sealed class EngineRuntime /// True while Alberto uses the browser (). /// Whether the Instagram session exists in the browser; null when unknown. - public EngineRuntime(Func? userIsDriving = null, Func? isConnected = null) + /// + /// True when the browser holds the session but the saved session of the raccolta «richieste» is missing (issue #36, + /// S4b): is then false and the monitor says «Serve «Ho finito»». Null: never. + /// + public EngineRuntime(Func? userIsDriving = null, Func? isConnected = null, Func? sessionCopyMissing = null) { _userIsDriving = userIsDriving ?? (() => false); _isConnected = isConnected; + _sessionCopyMissing = sessionCopyMissing; } /// The effective caution profile (settings applied). @@ -56,6 +62,9 @@ public sealed class EngineRuntime /// Whether the browser holds an Instagram session; null when the host does not say. public bool? IsConnected => _isConnected?.Invoke(); + /// True when the browser holds the session but the copy for the requests is missing (S4b). + public bool SessionCopyMissing => _sessionCopyMissing?.Invoke() == true; + /// The session in progress, if any. The Governor refuses every site action without one. public SessionContext? CurrentSession { diff --git a/src/Febe.Core/Engine/EngineServices.cs b/src/Febe.Core/Engine/EngineServices.cs index 4ca22a2..009cd9c 100644 --- a/src/Febe.Core/Engine/EngineServices.cs +++ b/src/Febe.Core/Engine/EngineServices.cs @@ -85,6 +85,7 @@ public sealed class EngineServices /// True while Alberto uses the browser. /// Whether the browser holds an Instagram session; null when unknown. /// Cancellation. + /// True when the session is in the browser but its saved copy is missing (S4b). public static async Task CreateAsync( IFebeStorage storage, IClock clock, @@ -92,14 +93,15 @@ public sealed class EngineServices EngineOptions? options = null, Func? userIsDriving = null, Func? isConnected = null, - CancellationToken ct = default) + CancellationToken ct = default, + Func? sessionCopyMissing = null) { ArgumentNullException.ThrowIfNull(storage); ArgumentNullException.ThrowIfNull(clock); ArgumentNullException.ThrowIfNull(random); options ??= EngineOptions.Default; - var runtime = new EngineRuntime(userIsDriving, isConnected); + var runtime = new EngineRuntime(userIsDriving, isConnected, sessionCopyMissing); var settings = await EngineSettingsStore.LoadAsync(storage.Settings, ct).ConfigureAwait(false); runtime.Profile = settings.EffectiveProfile; runtime.IsPaused = await storage.Settings.GetBoolAsync(EngineSettingKeys.Paused, false, ct).ConfigureAwait(false); diff --git a/src/Febe.Core/Engine/Monitor.cs b/src/Febe.Core/Engine/Monitor.cs index 92c2d07..ba99900 100644 --- a/src/Febe.Core/Engine/Monitor.cs +++ b/src/Febe.Core/Engine/Monitor.cs @@ -184,6 +184,8 @@ public sealed class EngineMonitor : IEngineMonitor case EngineMode.Disconnected: return ("Scollegato", ["La sessione di Instagram non c'è più.", "Apri il browser, accedi di nuovo, poi premi «Riprendi». Febe non prova a rientrare da solo."], "Accedi di nuovo"); + case EngineMode.NotConnected when runtime.SessionCopyMissing: + return ("Serve «Ho finito»", ["Il browser è collegato, ma manca la copia della sessione per le richieste.", "Dalla pagina Collegamento apri il browser e premi «Ho finito» sulla tua pagina iniziale."], "Serve «Ho finito»"); case EngineMode.NotConnected: return ("Non collegato", ["Il browser di Febe non ha una sessione di Instagram.", "Collegalo dalla pagina Collegamento."], "Non collegato"); case EngineMode.UserDriving: diff --git a/src/Febe.Desktop/Browser/WebView2Browser.cs b/src/Febe.Desktop/Browser/WebView2Browser.cs index b8fb7d9..e10eeea 100644 --- a/src/Febe.Desktop/Browser/WebView2Browser.cs +++ b/src/Febe.Desktop/Browser/WebView2Browser.cs @@ -52,7 +52,7 @@ internal sealed class WebView2Browser : IFebeBrowser _options = new BrowserOptions(ProfileDirectory, settings.Width, settings.Height); Host = new WebView2Host( ui, - new WebView2HostOptions(settings.Hosting, settings.AdditionalBrowserArguments, icon, () => context.Tracker.MarkUsed(context.Clock.Now), context.OpenStartPage), + new WebView2HostOptions(settings.Hosting, settings.AdditionalBrowserArguments, icon, () => context.Tracker.MarkUsed(context.Clock.Now), context.OpenStartPage, context.CopyOnWindowClosed), context.Log); Host.BrowserProcessFailed += (_, _) => RequestRestart(null); } diff --git a/src/Febe.Desktop/Browser/WebView2Host.cs b/src/Febe.Desktop/Browser/WebView2Host.cs index 830ac43..d95b10f 100644 --- a/src/Febe.Desktop/Browser/WebView2Host.cs +++ b/src/Febe.Desktop/Browser/WebView2Host.cs @@ -23,7 +23,11 @@ namespace Febe.Desktop.Browser; /// What «Pagina iniziale» does (issue #52): the connection opens the site's home when connected, the login page otherwise, /// once the engine's session ended and with the page's turn. Null: the button does nothing. /// -internal sealed record WebView2HostOptions(BrowserHosting Hosting, string AdditionalBrowserArguments, ImageSource? Icon, Action MarkUsed, Func? OpenStartPage = null); +/// +/// What closing the window does before the page goes back to the engine (issue #36, S4b): the connection copies the +/// session, when it keeps a saved one. The window keeps the engine still until the task ends. Null: nothing. +/// +internal sealed record WebView2HostOptions(BrowserHosting Hosting, string AdditionalBrowserArguments, ImageSource? Icon, Action MarkUsed, Func? OpenStartPage = null, Func? CopyOnClose = null); /// What the host does when a process of WebView2 fails (issue #52). internal enum ProcessFailureResponse @@ -554,12 +558,42 @@ internal sealed class WebView2Host : IBrowserHost TakeLease(); } - /// Alberto closed the window (or left it minimised too long): done, out of view. + /// + /// Alberto closed the window (or left it minimised too long): done, out of view at once. With a saved session + /// (S4b) the session is copied first: a hold of the driving gate keeps the page his until the copy is over, and only + /// then does it go back to the engine (rule 7). + /// private void Done() { _window?.MoveOffScreen(); - ReleaseLease(); NotifyPositionChanged(); + if (_lease is null || _closing || _settings.CopyOnClose is not { } copy) + { + ReleaseLease(); + return; + } + + var hold = UserDriving.Begin(); + ReleaseLease(); + _ = CopyThenLetGoAsync(copy, hold); + } + + private async Task CopyThenLetGoAsync(Func copy, IDisposable hold) + { + try + { + await copy(CancellationToken.None).ConfigureAwait(true); + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + // The kind of error only: the page and the browser may hold what the session holds. + _log.Warn("browser", $"Copia della sessione alla chiusura della finestra non riuscita ({ex.GetType().Name})."); + } + finally + { + hold.Dispose(); + _settings.MarkUsed(); + } } private void UserNavigation(Action action, Func allowed) diff --git a/src/Febe.Web/Api/ConnectionApi.cs b/src/Febe.Web/Api/ConnectionApi.cs index 23f60e7..575d031 100644 --- a/src/Febe.Web/Api/ConnectionApi.cs +++ b/src/Febe.Web/Api/ConnectionApi.cs @@ -1,4 +1,6 @@ using Febe.Core.Abstractions; +using Febe.Core.Collection.Requests; +using Febe.Core.Storage; using Febe.Web.Connection; using Febe.Web.Engine; using Febe.Web.Native; @@ -57,19 +59,54 @@ public static class ConnectionApi await connection.DisconnectAsync(ct).ConfigureAwait(false); return Results.NoContent(); }); + + // What an incomplete copy of the session does (issue #36, S4b, answer 9): read at every copy, no restart. + endpoints.MapGet("/api/connection/settings", async (IFebeStorage storage, CancellationToken ct) => + ApiHttp.Json(await SettingsAsync(storage, ct).ConfigureAwait(false), FebeJsonContext.Default.ConnectionSettingsDto)); + + endpoints.MapPut("/api/connection/settings", async (HttpContext context, IFebeStorage storage, CancellationToken ct) => + { + var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.ConnectionSettingsDto).ConfigureAwait(false); + var choice = SessionCopySettings.Parse(body.IncompleteCopy) + ?? throw new BadRequestException($"Scelta sconosciuta per la copia incompleta: ammesse «{SessionCopySettings.ReplaceText}» e «{SessionCopySettings.KeepCompleteText}»."); + await new SessionCopySettings(choice).SaveAsync(storage.Settings, ct).ConfigureAwait(false); + return ApiHttp.Json(await SettingsAsync(storage, ct).ConfigureAwait(false), FebeJsonContext.Default.ConnectionSettingsDto); + }); + } + + private static async Task SettingsAsync(IFebeStorage storage, CancellationToken ct) + { + var settings = await SessionCopySettings.LoadAsync(storage.Settings, ct).ConfigureAwait(false); + return new ConnectionSettingsDto(SessionCopySettings.ToText(settings.IncompleteCopy)); } public static ConnectionStatusDto ToDto(ConnectionStatus status) { ArgumentNullException.ThrowIfNull(status); - return new ConnectionStatusDto(State(status.State), status.Username, status.DisplayName, status.UserIsDriving, status.CurrentUrl); + return new ConnectionStatusDto(State(status.State), status.Username, status.DisplayName, status.UserIsDriving, status.CurrentUrl, ToDto(status.SavedSession)); } + /// The saved session in counts and names; null without one. + public static SavedSessionDto? ToDto(SavedSessionStatus? saved) => saved is null + ? null + : new SavedSessionDto( + saved.State, + saved.CopiedAt?.ToUnixTimeMilliseconds(), + saved.Cookies, + saved.ValuesPresent, + saved.ValuesExpected, + saved.MissingValues, + saved.DocIdsPresent, + saved.DocIdsExpected, + saved.MissingDocIds, + saved.NeededMissing); + public static string State(ConnectionState state) => state switch { ConnectionState.NotConnected => "notConnected", ConnectionState.Connected => "connected", ConnectionState.VerificationRequired => "verificationRequired", + ConnectionState.SessionCopyMissing => "copyMissing", _ => "browserUnavailable", }; } diff --git a/src/Febe.Web/Api/EngineApi.cs b/src/Febe.Web/Api/EngineApi.cs index 465ad23..b5efbc1 100644 --- a/src/Febe.Web/Api/EngineApi.cs +++ b/src/Febe.Web/Api/EngineApi.cs @@ -98,10 +98,16 @@ public static class EngineApi var mine = await storage.Accounts.GetMineAsync(ct).ConfigureAwait(false); var state = snapshot.Mode switch { - EngineMode.NotConnected => "notConnected", + // The cookie is there but the copy for the requests is missing (S4b): «Serve «Ho finito»», with the account. + EngineMode.NotConnected => (await connection.GetStatusAsync(ct).ConfigureAwait(false)).State == ConnectionState.SessionCopyMissing ? "copyMissing" : "notConnected", EngineMode.StoppedForVerification => "verification", EngineMode.Disconnected => "disconnected", - EngineMode.Off => (await connection.GetStatusAsync(ct).ConfigureAwait(false)).State == ConnectionState.Connected ? "connected" : "notConnected", + EngineMode.Off => (await connection.GetStatusAsync(ct).ConfigureAwait(false)).State switch + { + ConnectionState.Connected => "connected", + ConnectionState.SessionCopyMissing => "copyMissing", + _ => "notConnected", + }, _ => "connected", }; var link = state == "notConnected" diff --git a/src/Febe.Web/Api/FebeJsonContext.cs b/src/Febe.Web/Api/FebeJsonContext.cs index 3035868..1edd824 100644 --- a/src/Febe.Web/Api/FebeJsonContext.cs +++ b/src/Febe.Web/Api/FebeJsonContext.cs @@ -48,6 +48,7 @@ namespace Febe.Web.Api; [JsonSerializable(typeof(LoginDto))] [JsonSerializable(typeof(Library.LibraryChange))] [JsonSerializable(typeof(ConnectionStatusDto))] +[JsonSerializable(typeof(ConnectionSettingsDto))] [JsonSerializable(typeof(BeginDrivingRequest))] [JsonSerializable(typeof(CancelDrivingRequest))] [JsonSerializable(typeof(FinishDto))] diff --git a/src/Febe.Web/Api/Part2Dtos.cs b/src/Febe.Web/Api/Part2Dtos.cs index 5b56b85..6bdc318 100644 --- a/src/Febe.Web/Api/Part2Dtos.cs +++ b/src/Febe.Web/Api/Part2Dtos.cs @@ -5,8 +5,33 @@ namespace Febe.Web.Api; // ---------------------------------------------------------------- connection (PROTOCOLLO.md) -/// GET /api/connection. : notConnected, connected, verificationRequired, browserUnavailable. -public sealed record ConnectionStatusDto(string State, string? Username, string? DisplayName, bool UserIsDriving, string? CurrentUrl); +/// +/// GET /api/connection. : notConnected, connected, copyMissing, verificationRequired, +/// browserUnavailable. only with the raccolta «richieste». +/// +public sealed record ConnectionStatusDto(string State, string? Username, string? DisplayName, bool UserIsDriving, string? CurrentUrl, SavedSessionDto? SavedSession = null); + +/// +/// The saved session in counts and names (issue #36, S4b): present, none or unreadable; +/// Unix milliseconds. Never a value. +/// +public sealed record SavedSessionDto( + string State, + long? CopiedAt, + int Cookies, + int ValuesPresent, + int ValuesExpected, + IReadOnlyList MissingValues, + int DocIdsPresent, + int DocIdsExpected, + IReadOnlyList MissingDocIds, + int NeededMissing); + +/// +/// GET/PUT /api/connection/settings: what an incomplete copy of the session does, sostituisci (the +/// default) or tieni-completa. +/// +public sealed record ConnectionSettingsDto(string IncompleteCopy); /// POST /api/connection/begin. public sealed record BeginDrivingRequest(bool OpenLogin); diff --git a/src/Febe.Web/Connection/IConnectionService.cs b/src/Febe.Web/Connection/IConnectionService.cs index 2f051c8..f91affb 100644 --- a/src/Febe.Web/Connection/IConnectionService.cs +++ b/src/Febe.Web/Connection/IConnectionService.cs @@ -14,6 +14,48 @@ public enum ConnectionState /// The browser is not available (starting, crashed, demo without browser). BrowserUnavailable, + + /// + /// The session cookie is in the browser, but the raccolta «richieste» has no readable saved session to send it with + /// (issue #36, S4b): «Serve «Ho finito»». The engine waits until a copy is made. + /// + SessionCopyMissing, +} + +/// +/// The saved session of the raccolta «richieste» as the Collegamento page shows it (issue #36, S4b): counts and names +/// only, never a value (rule 10). +/// +/// , or . +/// When the copy was made; null when there is none or it is not known. +/// How many cookies it holds. +/// Values of the page it holds. +/// Values of the page the copy reads. +/// Names of the values it lacks. +/// doc_id it holds. +/// doc_id the copy reads. +/// Operations whose doc_id it lacks. +/// How many of those a configured operation sends (its requests do not leave). +public sealed record SavedSessionStatus( + string State, + DateTimeOffset? CopiedAt, + int Cookies, + int ValuesPresent, + int ValuesExpected, + IReadOnlyList MissingValues, + int DocIdsPresent, + int DocIdsExpected, + IReadOnlyList MissingDocIds, + int NeededMissing) +{ + /// A readable saved session. + public const string Present = "present"; + + /// No saved session. + public const string None = "none"; + + /// A file that cannot be read: counts as none. + public const string Unreadable = "unreadable"; } /// What the interface knows about the link to Instagram. @@ -22,12 +64,14 @@ public enum ConnectionState /// Display name, when known. /// True while Alberto is using the browser (login page, remote view, browser window): the engine is still. /// Address shown in the remote view's address bar, without query string. +/// The saved session (raccolta «richieste»); null when this start keeps none. public sealed record ConnectionStatus( ConnectionState State, string? Username, string? DisplayName, bool UserIsDriving, - string? CurrentUrl); + string? CurrentUrl, + SavedSessionStatus? SavedSession = null); /// Result of «Ho finito» on the Collegamento page. /// True when the session cookie now exists. diff --git a/src/Febe.Web/Connection/PROTOCOLLO.md b/src/Febe.Web/Connection/PROTOCOLLO.md index b67224e..47a8520 100644 --- a/src/Febe.Web/Connection/PROTOCOLLO.md +++ b/src/Febe.Web/Connection/PROTOCOLLO.md @@ -7,11 +7,12 @@ Lo usano due parti scritte in parallelo: non cambiarlo senza aggiornare entrambe | Endpoint | Corpo e risposta | |---|---| -| `GET /api/connection` | `{ state: "notConnected"\|"connected"\|"verificationRequired"\|"browserUnavailable", username, displayName, userIsDriving, currentUrl }` | +| `GET /api/connection` | `{ state: "notConnected"\|"connected"\|"copyMissing"\|"verificationRequired"\|"browserUnavailable", username, displayName, userIsDriving, currentUrl, savedSession }` | | `POST /api/connection/begin` | `{ openLogin: bool }` → 204. Alberto usa il browser; con `openLogin` il browser carica la pagina di accesso vera; senza, se il browser è a riposo (`about:blank`) apre la pagina iniziale (sotto) | | `POST /api/connection/finish` | → `{ connected: bool, message }` («Ho finito») | | `POST /api/connection/cancel` | corpo facoltativo `{ pageLeft: bool }` → 204 («Annulla»; con `pageLeft` la pagina è stata lasciata, sotto) | | `POST /api/connection/disconnect` | → 204 («Scollega», dopo la conferma nell'interfaccia) | +| `GET /api/connection/settings`, `PUT /api/connection/settings` | `{ incompleteCopy: "sostituisci"\|"tieni-completa" }`: che cosa fa una copia della sessione incompleta (raccolta «richieste»); un altro valore → 400 | | `POST /api/browser/show` | corpo facoltativo `{ openLogin: bool }` → `{ message }`. Solo Windows: porta in primo piano la finestra «Browser di Febe»; come `begin` apre la pagina di accesso (`openLogin`) o, se era a riposo, la pagina iniziale | **Pagina iniziale** (issue #52): la home del sito se Febe è collegato e non scollegato da Instagram, altrimenti la @@ -27,6 +28,14 @@ di una disconnessione apre il browser con `openLogin: true` (in Docker la pagina In modalità dimostrativa la scena `scollegato` dà `notConnected`, la scena `fermo` dà `verificationRequired`. +**Raccolta «richieste»** (issue #36, S4b): `savedSession` è `null` senza sessione salvata in questo avvio («pagine», o +nessuna operazione configurata); altrimenti `{ state: "present"|"none"|"unreadable", copiedAt (ms Unix o null), cookies, +valuesPresent, valuesExpected, missingValues: [nomi], docIdsPresent, docIdsExpected, missingDocIds: [operazioni], +neededMissing }`: solo conteggi e nomi, mai valori. Con il cookie di sessione nel browser ma senza una sessione salvata +leggibile lo stato è `copyMissing` («Serve «Ho finito»»): il motore aspetta, e `/api/engine` dice `copyMissing` nel +collegamento. La sessione si copia a «Ho finito», alla chiusura della finestra del browser su Windows e quando il +permesso di guida finisce da solo, sempre prima che la pagina torni al motore. + L'interfaccia manda `cancel` con `{ "pageLeft": true }` anche quando Alberto lascia la pagina Browser, o la pagina Collegamento mentre accede, senza «Ho finito» né «Annulla»: un'altra pagina, la scheda chiusa o ricaricata (`fetch` con `keepalive`, che porta l'`Origin` dell'interfaccia). In Docker vale come «Annulla» (il browser torna a riposo). diff --git a/src/Febe.Web/wwwroot/css/febe.css b/src/Febe.Web/wwwroot/css/febe.css index 633fe34..7a5e494 100644 --- a/src/Febe.Web/wwwroot/css/febe.css +++ b/src/Febe.Web/wwwroot/css/febe.css @@ -802,6 +802,15 @@ input[type=range].cursore.lungo::-webkit-slider-thumb{border-color:var(--accento .collega-destra h2.sez{margin-bottom:12px} .collega-destra .avviso{font-size:13.5px;line-height:1.5;padding:13px 16px} .nota-password{background:var(--accento-tinta)} +.sessione-salvata{padding:14px 16px;font-size:13.5px;line-height:1.5} +.sessione-salvata p{margin:0 0 6px} +.sessione-salvata h2.sez{margin-bottom:8px} +.sessione-salvata h3.sez{font-size:13.5px;font-weight:650;margin:12px 0 8px} +.sessione-salvata .avviso{margin:4px 0 8px} +.sessione-salvata .scelte{display:flex;flex-direction:column;gap:10px} +.sessione-salvata .scelte .voce{align-items:flex-start} +.sessione-salvata .scelte .voce .tondo{margin-top:2px} +.sessione-salvata .scelte small{display:block;color:var(--testo-2);font-size:12.5px} .passi-collegamento{list-style:none;margin:0 0 8px;padding:0;display:flex;flex-direction:column;gap:18px} .passi-collegamento li{display:flex;gap:14px} .passi-collegamento .numero{width:24px;height:24px;border-radius:50%;flex:none;display:inline-flex;align-items:center;justify-content:center;background:var(--accento-tinta);color:var(--accento-scuro);font-weight:650;font-size:12.5px;margin-top:1px} diff --git a/src/Febe.Web/wwwroot/js/core/shell.js b/src/Febe.Web/wwwroot/js/core/shell.js index 003deef..354f002 100644 --- a/src/Febe.Web/wwwroot/js/core/shell.js +++ b/src/Febe.Web/wwwroot/js/core/shell.js @@ -63,7 +63,7 @@ function renderStatus(state) { const s = state.snapshot; const meter = s.profilesOpenedToday; const connection = state.connection; - const linkState = t(connection.state === 'verification' ? 'stato.verifica' : connection.state === 'disconnected' ? 'stato.scollegato' : 'stato.collegato'); + const linkState = t(connection.state === 'verification' ? 'stato.verifica' : connection.state === 'disconnected' ? 'stato.scollegato' : connection.state === 'copyMissing' ? 'stato.copiaMancante' : 'stato.collegato'); // The own account is known only after the first sweep (a verification can come before it): no «@null». const who = connection.state === 'notConnected' ? h('div.chi', h('span.av.segnaposto', icon('user', 's')), diff --git a/src/Febe.Web/wwwroot/js/pages/connection.js b/src/Febe.Web/wwwroot/js/pages/connection.js index 6f54b60..9f5433c 100644 --- a/src/Febe.Web/wwwroot/js/pages/connection.js +++ b/src/Febe.Web/wwwroot/js/pages/connection.js @@ -2,7 +2,9 @@ // the steps «Come collegarti», the note that the password goes only to Instagram (keys pass through the server without // being recorded), the risk note, Annulla and «Ho finito». Windows: the browser is the separate window «Browser di // Febe» and the large area says so, with «Portalo in primo piano». When connected: the account, «Usa il browser» and -// «Scollega» with its confirmation. While Alberto uses the browser the engine is still. +// «Scollega» with its confirmation. While Alberto uses the browser the engine is still. With the raccolta «richieste» +// (issue #36, S4b) the page also shows the saved session in counts and names (never values), the choice for an +// incomplete copy, and «Serve «Ho finito»» when the browser is connected but the copy is missing. import { api } from '../core/api.js'; import { caps } from '../core/context.js'; @@ -10,10 +12,10 @@ import { h, icon, fill } from '../core/dom.js'; import { engineState, refreshEngine } from '../core/engine.js'; import { navigate } from '../core/shell.js'; import { t } from '../core/text.js'; -import { avatar, confirmDialog, label, showError, toast } from '../core/ui.js'; +import { avatar, confirmDialog, label, radio, showError, toast } from '../core/ui.js'; import { remoteView } from './remote-view.js'; -const STATE_KIND = { notConnected: 'ambra', connected: 'verde', verificationRequired: 'rosso', browserUnavailable: '' }; +const STATE_KIND = { notConnected: 'ambra', connected: 'verde', copyMissing: 'ambra', verificationRequired: 'rosso', browserUnavailable: '' }; /** True while the engine waits for «Riprendi» (the stop strip of a verification or a disconnection). */ function waitsForResume(state) { @@ -120,6 +122,7 @@ export async function mountConnection(page) { fill(stateLabel, label(t(`impostazioni.collegamento.stati.${status.state}`), STATE_KIND[status.state] || '')); if (status.state === 'connected') drawConnected(); else if (status.state === 'browserUnavailable') drawUnavailable(); + else if (status.state === 'copyMissing') drawLogin({ copyMissing: true }); else drawLogin(); } @@ -145,15 +148,17 @@ export async function mountConnection(page) { }); // ------------------------------------------------------------------------------------------- login or verification - function drawLogin() { + function drawLogin({ copyMissing = false } = {}) { const verification = status.state === 'verificationRequired'; + // Connected but without the copy for the requests: the start page (the site's home), never the login page. + const login = !verification && !copyMissing; waitingResume = false; closeView(); - lease.begin(!verification); + lease.begin(login); if (windows) { fill(left, windowPanel()); } else { - view = remoteView(page, { url: status.currentUrl, login: !verification }); + view = remoteView(page, { url: status.currentUrl, login }); fill(left, view.element); } const steps = t(windows ? 'impostazioni.collegamento.passiWindows' : 'impostazioni.collegamento.passi'); @@ -161,6 +166,8 @@ export async function mountConnection(page) { fill(right, verification ? h('div.avviso.rosso', icon('octagon-alert', 's'), h('span', h('b', t('impostazioni.collegamento.verificaTitolo')), ' ', t('impostazioni.collegamento.verificaTesto'))) + : copyMissing + ? h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', h('b', t('impostazioni.collegamento.copiaMancanteTitolo')), ' ', t('impostazioni.collegamento.copiaMancanteTesto'))) : h('div', h('h2.sez', t('impostazioni.collegamento.come')), h('ol.passi-collegamento', (Array.isArray(steps) ? steps : []).map((s, i) => h('li', h('span.numero', String(i + 1)), h('div', h('b', s.titolo), h('p', s.testo)))))), @@ -168,6 +175,7 @@ export async function mountConnection(page) { h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', t('impostazioni.collegamento.rischio'))), // Windows: one engine per account (spec §5) said before the login too; Docker keeps mockup 10 as it is. windows ? h('div.avviso', icon('info', 's'), h('span', t('impostazioni.collegamento.unMotore'))) : null, + copyMissing ? savedSessionBox(status.savedSession, page) : null, message, h('div.molla'), h('div.bottoni-collegamento', @@ -235,7 +243,8 @@ export async function mountConnection(page) { fill(right, passwordNote(windows), h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', t('impostazioni.collegamento.rischio'))), - h('div.avviso', icon('info', 's'), h('span', t('impostazioni.collegamento.unMotore')))); + h('div.avviso', icon('info', 's'), h('span', t('impostazioni.collegamento.unMotore'))), + savedSessionBox(status.savedSession, page)); } async function useBrowser() { @@ -287,6 +296,57 @@ export async function mountConnection(page) { await draw(); } +/** + * The saved session of the raccolta «richieste» (issue #36, S4b): when it was copied, the values and doc_id present + * and the names of the missing ones — counts and names only, the server never sends a value — and the choice for an + * incomplete copy. Nothing without a saved session in this start («pagine»). + */ +export function savedSessionBox(saved, page) { + if (!saved) return null; + const k = (key, vars) => t(`impostazioni.collegamento.salvata.${key}`, vars); + const lines = []; + if (saved.state === 'present') { + if (saved.copiedAt) { + const when = new Date(saved.copiedAt).toLocaleString('it-IT', { dateStyle: 'medium', timeStyle: 'short' }); + lines.push(h('p', k('copiata', { quando: when }))); + } + lines.push(h('p.muto', [ + k('valori', { presenti: String(saved.valuesPresent), attesi: String(saved.valuesExpected) }), + k('docId', { presenti: String(saved.docIdsPresent), attesi: String(saved.docIdsExpected) }), + k('cookie', { n: String(saved.cookies) }), + ].join(' '))); + const missing = [...(saved.missingValues || []), ...(saved.missingDocIds || [])]; + if (missing.length) lines.push(h('p', k('mancano', { nomi: missing.join(', ') }))); + lines.push(saved.neededMissing + ? h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', k('servono', { n: String(saved.neededMissing) }))) + : h('p', k('completa'))); + } else { + lines.push(h('p', k(saved.state === 'unreadable' ? 'illeggibile' : 'nessuna'))); + } + + const choose = async (value) => { + try { + await api('/api/connection/settings', { method: 'PUT', body: { incompleteCopy: value } }); + toast(k('salvato')); + } catch (error) { + showError(error); + } + }; + const replace = radio({ name: 'copia-incompleta', value: 'sostituisci', checked: true, onchange: choose, labelNode: h('span', h('b', k('sostituisci')), h('small', k('sostituisciAiuto'))) }); + const keep = radio({ name: 'copia-incompleta', value: 'tieni-completa', onchange: choose, labelNode: h('span', h('b', k('tieni')), h('small', k('tieniAiuto'))) }); + api('/api/connection/settings', { signal: page && page.signal }).then((settings) => { + keep.input.checked = settings.incompleteCopy === 'tieni-completa'; + replace.input.checked = !keep.input.checked; + }).catch(() => {}); + + return h('div.pannello.sessione-salvata', + h('h2.sez', k('titolo')), + ...lines, + h('p.aiuto.piccolo', k('nota')), + h('h3.sez', k('incompleta')), + h('div.scelte', { role: 'radiogroup', 'aria-label': k('incompleta') }, replace, keep)); +} + /** «La password va solo a Instagram», with the true wording of each shell (spec §10.3). */ export function passwordNote(windows) { return h('div.avviso.nota-password', icon('shield-check', 's'), diff --git a/src/Febe.Web/wwwroot/testi/it.json b/src/Febe.Web/wwwroot/testi/it.json index d69c491..da4a5be 100644 --- a/src/Febe.Web/wwwroot/testi/it.json +++ b/src/Febe.Web/wwwroot/testi/it.json @@ -24,6 +24,7 @@ "nessunAccount": "Nessun account", "verifica": "Verifica richiesta", "scollegato": "Sessione chiusa", + "copiaMancante": "Serve «Ho finito»", "accountDaLeggere": "Nome non ancora noto", "nonDisponibile": "Stato del motore non disponibile" }, @@ -690,9 +691,31 @@ "stati": { "notConnected": "Non collegato", "connected": "Collegato", + "copyMissing": "Serve «Ho finito»", "verificationRequired": "Verifica richiesta", "browserUnavailable": "Browser non disponibile" }, + "copiaMancanteTitolo": "Manca la copia della sessione", + "copiaMancanteTesto": "Il browser è collegato, ma Febe non ha ancora una copia della sessione per le richieste (o non riesce a leggerla). Apri la tua pagina iniziale nel browser e premi «Ho finito»: fino ad allora il motore aspetta.", + "salvata": { + "titolo": "Sessione salvata per le richieste", + "copiata": "Copiata {quando}.", + "nessuna": "Nessuna copia: premi «Ho finito» sulla tua pagina iniziale.", + "illeggibile": "C'è un file, ma Febe non riesce a leggerlo (un'altra chiave o un file rovinato): conta come nessuna copia. Il prossimo «Ho finito» lo sostituisce.", + "valori": "Valori della pagina: {presenti} su {attesi}.", + "docId": "doc_id: {presenti} su {attesi}.", + "cookie": "Cookie: {n}.", + "mancano": "Mancano: {nomi}.", + "servono": "{n} di questi servono alle richieste configurate: quelle richieste non partono e, alla prima, Febe si ferma come disconnessione.", + "completa": "Nulla di ciò che le richieste configurate mandano manca.", + "nota": "Qui ci sono solo conteggi e nomi, mai i valori.", + "incompleta": "Se una copia nuova è incompleta", + "sostituisci": "Sostituisci comunque (consigliato)", + "sostituisciAiuto": "La copia nuova prende sempre il posto di quella salvata: una copia più vecchia potrebbe avere i cookie di un altro accesso.", + "tieni": "Tieni la copia completa", + "tieniAiuto": "Se alla copia nuova manca qualcosa che le richieste usano e quella salvata è completa, Febe tiene quella salvata e te lo dice.", + "salvato": "Scelta salvata: vale dalla prossima copia." + }, "come": "Come collegarti", "passi": [ { diff --git a/tests/Febe.Tests.Windows/Support/DesktopBed.cs b/tests/Febe.Tests.Windows/Support/DesktopBed.cs index 8a1e1af..290d1af 100644 --- a/tests/Febe.Tests.Windows/Support/DesktopBed.cs +++ b/tests/Febe.Tests.Windows/Support/DesktopBed.cs @@ -58,7 +58,9 @@ internal sealed class DesktopBed : IAsyncDisposable /// Prefix of the temporary folder. /// --accesso-di-prova: the composition opens the test site once at start-up. - public static async Task StartAsync(string name, bool autoLogin, CancellationToken ct) + /// Cancels the start. + /// More options of Febe.exe (--raccolta richieste). + public static async Task StartAsync(string name, bool autoLogin, CancellationToken ct, string[]? extra = null) { var site = await TestSite.StartAsync(new TestSiteOptions(), ct); var folder = new TestFolder(name); @@ -77,6 +79,8 @@ internal sealed class DesktopBed : IAsyncDisposable arguments.Add("--accesso-di-prova"); } + arguments.AddRange(extra ?? []); + if (!DesktopCommandLine.TryParse([.. arguments], out var options, out var problem)) { throw new ArgumentException(problem); diff --git a/tests/Febe.Tests.Windows/WebView2ConnectionTests.cs b/tests/Febe.Tests.Windows/WebView2ConnectionTests.cs index 8dd5722..0c00b69 100644 --- a/tests/Febe.Tests.Windows/WebView2ConnectionTests.cs +++ b/tests/Febe.Tests.Windows/WebView2ConnectionTests.cs @@ -1,3 +1,4 @@ +using Febe.Browser.Cdp; using Febe.Core.Storage; using Febe.Tests.Windows.Support; using Febe.Web.Connection; @@ -64,4 +65,42 @@ public sealed class WebView2ConnectionTests Assert.IsFalse(bed.Lines.Any("non parte"), bed.Lines.Text); Assert.IsFalse(bed.Lines.Any("ERRORE"), bed.Lines.Text); } + + [TestMethod] + [Timeout(240_000, CooperativeCancellation = true)] + public async Task WithRichiesteClosingTheWindowCopiesTheSessionBeforeThePageGoesBack() + { + // Issue #36, S4b (answer 5 of 18 November 2026): the window «Browser di Febe» closed with its X, without + // «Ho finito», copies the session from the site's page into the saved session, under Alberto's lease. + var ct = TestContext.CancellationToken; + await using var bed = await DesktopBed.StartAsync("finestra-copia", autoLogin: false, ct, ["--raccolta", "richieste"]); + var app = bed.App; + await app.Running.WaitAsync(TimeSpan.FromSeconds(120), ct); + var connection = app.Connection!; + var browser = bed.Browser; + var savedSession = app.SavedSession ?? throw new AssertFailedException("the test site's catalog has configured operations"); + var window = await bed.Ui.InvokeAsync(() => browser.Host.Window) ?? throw new AssertFailedException("nessuna finestra"); + + // «Accedi» (the welcome page starts the test site's session), then Alberto goes to the home of the site. + await connection.BeginUserDrivingAsync(openLogin: true, ct); + await browser.Cdp.NavigateAsync(bed.Site.Url("/"), ct); + await connection.RefreshAsync(ct); + Assert.AreEqual(ConnectionState.SessionCopyMissing, (await connection.GetStatusAsync(ct)).State, "the cookie alone is not «Collegato» with «richieste»"); + + await bed.Ui.InvokeAsync(() => + { + window.Close(); + return true; + }); + await bed.WaitUntilAsync(() => Task.FromResult(savedSession.Read() is not null), TimeSpan.FromSeconds(30), "la copia alla chiusura della finestra", ct); + var saved = savedSession.Read()!; + Assert.AreEqual(Febe.SitoDiProva.TestSite.SpinBranch, saved.Fields["spin_b"]); + Assert.AreEqual(Febe.SitoDiProva.TestSite.EntryNonce, saved.Fields["entry_nonce"]); + Assert.IsFalse(await bed.Ui.InvokeAsync(() => window.IsOnScreen)); + Assert.AreEqual(ConnectionState.Connected, (await connection.GetStatusAsync(ct)).State); + Assert.IsTrue(bed.Lines.Any("Finestra del browser chiusa: sessione copiata"), bed.Lines.Text); + Assert.IsFalse(bed.Lines.Any(Febe.SitoDiProva.TestSite.Lsd), "no value in the log"); + Assert.IsFalse(bed.Lines.Any("ERRORE"), bed.Lines.Text); + await connection.CancelAsync(ct); + } } diff --git a/tests/Febe.Tests/Browser/SessionCaptureTests.cs b/tests/Febe.Tests/Browser/SessionCaptureTests.cs index 1ccb8c7..7bcb2e2 100644 --- a/tests/Febe.Tests/Browser/SessionCaptureTests.cs +++ b/tests/Febe.Tests/Browser/SessionCaptureTests.cs @@ -289,6 +289,101 @@ public sealed class SessionCaptureTests AssertNoSecret(string.Join("\n", log)); } + [TestMethod] + public async Task KeepTheCompleteCopyKeepsTheSavedOneOnlyWhenItIsCompleteAndTheNewOneLacksWhatTheRequestsNeed() + { + // Answer 9 of 18 November 2026: «tieni la completa» is a choice; «sostituisci» stays the default. + var log = new List(); + var store = new InMemorySiteSession(null); + var choice = IncompleteCopyChoice.KeepComplete; + BrowserSessionCopier Copier(JsonObject page) => + new(Page($"http://{SiteHost}/", page: page), Plan, store, new VirtualClock(), log.Add) { IncompleteCopy = _ => Task.FromResult(choice) }; + var lacking = PageValues(); + ((JsonObject)lacking["values"]!).Remove("lsd"); + + // Nothing saved yet: the incomplete copy is saved all the same (there is no complete one to keep). + Assert.AreEqual(SessionCopyStatus.Saved, (await Copier(lacking).CopyAsync(() => true, CancellationToken.None)).Status); + var incomplete = store.Read()!; + + // An incomplete saved copy is not one to keep: the next incomplete copy replaces it. + Assert.AreEqual(SessionCopyStatus.Saved, (await Copier(lacking).CopyAsync(() => true, CancellationToken.None)).Status); + Assert.AreNotEqual(incomplete.Capture, store.Read()!.Capture); + + // A complete copy, then an incomplete one: the complete one stays, and the outcome says so. + Assert.AreEqual(SessionCopyStatus.Saved, (await Copier(PageValues()).CopyAsync(() => true, CancellationToken.None)).Status); + var complete = store.Read(); + var kept = await Copier(lacking).CopyAsync(() => true, CancellationToken.None); + Assert.AreEqual(SessionCopyStatus.KeptComplete, kept.Status); + Assert.IsFalse(kept.Saved); + Assert.AreEqual(1, kept.MissingValues); + Assert.AreSame(complete, store.Read(), "the saved session stays as it was"); + StringAssert.Contains(log[^1], "resta la copia completa salvata prima"); + StringAssert.Contains(log[^1], "mancano lsd"); + + // A complete new copy always replaces it. + Assert.AreEqual(SessionCopyStatus.Saved, (await Copier(PageValues()).CopyAsync(() => true, CancellationToken.None)).Status); + Assert.AreNotSame(complete, store.Read()); + complete = store.Read(); + + // With «sostituisci» the incomplete copy replaces the complete one, as in S4. + choice = IncompleteCopyChoice.Replace; + Assert.AreEqual(SessionCopyStatus.Saved, (await Copier(lacking).CopyAsync(() => true, CancellationToken.None)).Status); + Assert.AreNotSame(complete, store.Read()); + Assert.IsFalse(store.Read()!.Fields.ContainsKey("lsd"), "missing, never guessed"); + AssertNoSecret(string.Join("\n", log)); + } + + [TestMethod] + public async Task TheReportCountsAndNamesWhatTheSavedSessionHoldsAndNeverAValue() + { + var store = new InMemorySiteSession(null); + var clock = new VirtualClock(); + var page = PageValues(); + ((JsonObject)page["values"]!).Remove("hsi"); + ((JsonObject)page["docIds"]!).Remove("ProvaProfiloQuery"); + var copier = new BrowserSessionCopier(Page($"http://{SiteHost}/", page: page), Plan, store, clock, _ => { }); + + var none = copier.Report(); + Assert.AreEqual(SavedSessionState.None, none.State); + Assert.AreEqual(SavedSessionState.None, copier.SavedState); + Assert.IsFalse(none.Complete); + Assert.IsNull(none.CopiedAt); + Assert.AreEqual(Plan.Values.Count, none.ValuesExpected); + Assert.AreEqual(0, none.ValuesPresent); + + await copier.CopyAsync(() => true, CancellationToken.None); + var report = copier.Report(); + Assert.AreEqual(SavedSessionState.Present, report.State); + Assert.AreEqual(SavedSessionState.Present, copier.SavedState); + Assert.AreEqual(clock.Now, report.CopiedAt); + Assert.AreEqual(3, report.Cookies); + Assert.AreEqual(Plan.Values.Count - 1, report.ValuesPresent); + Assert.AreEqual(14, report.ValuesExpected, "the page values of the test catalog, spin_r, spin_b and spin_t among them"); + CollectionAssert.AreEqual(new[] { "hsi" }, report.MissingValues.ToArray()); + Assert.AreEqual(0, report.DocIdsPresent); + CollectionAssert.AreEqual(new[] { "ProvaProfiloQuery" }, report.MissingDocIds.ToArray()); + Assert.AreEqual(2, report.NeededMissing, "the configured GraphQL query sends both"); + Assert.IsFalse(report.Complete); + AssertNoSecret(report.ToString()); + AssertNoSecret(string.Join(",", report.MissingValues.Concat(report.MissingDocIds))); + } + + [TestMethod] + public async Task TheSpinValuesAreCopiedFromTheirModuleLikeTheOtherValuesOfThePage() + { + // Decision of 18 November 2026: __spin_r, __spin_b, __spin_t are a snapshot of the page at «Ho finito». + var store = new InMemorySiteSession(null); + await new BrowserSessionCopier(Page($"http://{SiteHost}/"), Plan, store, new VirtualClock(), _ => { }).CopyAsync(() => true, CancellationToken.None); + var saved = store.Read()!; + Assert.AreEqual("1001", saved.Fields["spin_r"]); + Assert.AreEqual("ramo", saved.Fields["spin_b"]); + Assert.AreEqual("1700000000", saved.Fields["spin_t"]); + var script = SessionCaptureScript.Build(Plan); + StringAssert.Contains(script, "read(\"GiroProva\", \"revisione\")"); + StringAssert.Contains(script, "read(\"GiroProva\", \"tempo\")"); + Assert.DoesNotContain("SiteData", script, "the test site's own module names, never Instagram's"); + } + [TestMethod] [Timeout(20_000, CooperativeCancellation = true)] public async Task ABrowserThatDoesNotAnswerIsABrowserErrorAfterTheTimeout() @@ -382,6 +477,9 @@ public sealed class SessionCaptureTests ["comet_req"] = "7", ["ccg"] = "BUONA", ["entry_nonce"] = "nonce-segreto", + ["spin_r"] = "1001", + ["spin_b"] = "ramo", + ["spin_t"] = "1700000000", ["estraneo"] = "non chiesto", }, ["docIds"] = new JsonObject { ["ProvaProfiloQuery"] = "9000000000000009", ["AltraQuery"] = "1" }, diff --git a/tests/Febe.Tests/Collection/HttpSiteRequesterShapeTests.cs b/tests/Febe.Tests/Collection/HttpSiteRequesterShapeTests.cs index b99f8b0..37f45d3 100644 --- a/tests/Febe.Tests/Collection/HttpSiteRequesterShapeTests.cs +++ b/tests/Febe.Tests/Collection/HttpSiteRequesterShapeTests.cs @@ -65,7 +65,8 @@ public sealed class HttpSiteRequesterShapeTests 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&__ccg=BUONA&__comet_req=7&__hs=hs-di-prova&__hsi=hsi-di-prova&__rev=revisione-di-prova&dpr=1" + "av=17841400000000077&__a=1&__ccg=BUONA&__comet_req=7&__hs=hs-di-prova&__hsi=hsi-di-prova&__rev=revisione-di-prova" + + "&__spin_r=1001&__spin_b=ramo-di-prova&__spin_t=1700000000&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", @@ -360,6 +361,9 @@ public sealed class HttpSiteRequesterShapeTests [DataRow("ccg", "__ccg")] [DataRow("comet_req", "__comet_req")] [DataRow("entry_nonce", "x-fb-entry-nonce")] + [DataRow("spin_r", "__spin_r")] + [DataRow("spin_b", "__spin_b")] + [DataRow("spin_t", "__spin_t")] public async Task AVersionFieldTheSessionLacksStopsTheQueryBeforeItLeaves(string field, string missing) { using var listener = new OneShotListener("""{"profilo":{}}"""); diff --git a/tests/Febe.Tests/Collection/HttpSiteRequesterTests.cs b/tests/Febe.Tests/Collection/HttpSiteRequesterTests.cs index 1e448b5..632d307 100644 --- a/tests/Febe.Tests/Collection/HttpSiteRequesterTests.cs +++ b/tests/Febe.Tests/Collection/HttpSiteRequesterTests.cs @@ -452,7 +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.Revision, TestSite.HasteSession, TestSite.HasteSessionId, TestSite.ConnectionClass, TestSite.EntryNonce, TestSite.SpinBranch, 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)); @@ -574,6 +574,9 @@ public sealed class HttpSiteRequesterTests ["comet_req"] = TestSite.CometReq, ["ccg"] = TestSite.ConnectionClass, ["entry_nonce"] = TestSite.EntryNonce, + ["spin_r"] = TestSite.SpinRevision, + ["spin_b"] = TestSite.SpinBranch, + ["spin_t"] = TestSite.SpinTime, }; /// A site client for the test site with its session, clock and log. diff --git a/tests/Febe.Tests/Collection/RequestCatalogTests.cs b/tests/Febe.Tests/Collection/RequestCatalogTests.cs index 99e082c..f30f09b 100644 --- a/tests/Febe.Tests/Collection/RequestCatalogTests.cs +++ b/tests/Febe.Tests/Collection/RequestCatalogTests.cs @@ -345,6 +345,9 @@ public sealed partial class RequestCatalogTests 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"]); + Assert.AreEqual(new PageValueSource("SiteData", "__spin_r"), instagram.Values["spin_r"]); + Assert.AreEqual(new PageValueSource("SiteData", "__spin_b"), instagram.Values["spin_b"]); + Assert.AreEqual(new PageValueSource("SiteData", "__spin_t"), instagram.Values["spin_t"]); 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. @@ -376,9 +379,10 @@ public sealed partial class RequestCatalogTests 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" }) + // A snapshot of the page at «Ho finito» (decision of 18 November 2026); the operations stay not configured anyway. + 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."); + Assert.AreEqual(new ValueSource(ValueSourceKind.Session, spin), operation.Body["__" + spin], $"{operation.Name} __{spin}"); } } } @@ -387,17 +391,18 @@ public sealed partial class RequestCatalogTests 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) + // __d, 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", + "__req", "__s", "__dyn", "__csr", "__hblp", "__hsdp", "__sjsp", "__crn", "__d", "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.IsFalse(pending.Contains("__spin_r") || pending.Contains("__spin_b") || pending.Contains("__spin_t"), "Settled in S4b."); Assert.AreEqual(0, RequestCatalog.LoadTestSite().Operations.Sum(o => o.PendingValues.Count)); } @@ -471,7 +476,7 @@ public sealed partial class RequestCatalogTests [TestMethod] public void TheNewSessionFieldsAreAcceptedAndUnknownOnesStillRefused() { - foreach (var field in new[] { "rev", "hs", "hsi", "dpr", "ccg", "comet_req", "entry_nonce" }) + foreach (var field in new[] { "rev", "hs", "hsi", "dpr", "ccg", "comet_req", "entry_nonce", "spin_r", "spin_b", "spin_t" }) { var operation = Rest("post2", "/dati/post/{code}"); operation["headers"] = new JsonObject { ["user-agent"] = "session:user_agent", ["x-prova"] = "session:" + field }; @@ -480,7 +485,7 @@ public sealed partial class RequestCatalogTests 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" }) + foreach (var field in new[] { "password", "spin", "cookie", "sessionid" }) { var operation = Rest("post2", "/dati/post/{code}"); operation["headers"] = new JsonObject { ["x-prova"] = "session:" + field }; diff --git a/tests/Febe.Tests/Collection/SessionCaptureIntegrationTests.cs b/tests/Febe.Tests/Collection/SessionCaptureIntegrationTests.cs index 401d5af..c7d0bb7 100644 --- a/tests/Febe.Tests/Collection/SessionCaptureIntegrationTests.cs +++ b/tests/Febe.Tests/Collection/SessionCaptureIntegrationTests.cs @@ -91,6 +91,9 @@ public sealed class SessionCaptureIntegrationTests 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.SpinRevision, values.Fields["spin_r"], "S4b: __spin_r from the page, a number as text"); + Assert.AreEqual(TestSite.SpinBranch, values.Fields["spin_b"]); + Assert.AreEqual(TestSite.SpinTime, values.Fields["spin_t"]); Assert.AreEqual(TestSite.DocIds[TestSite.ProfileQuery], values.DocIds[TestSite.ProfileQuery]); lock (site.World.Gate) { diff --git a/tests/Febe.Tests/Collection/SiteAnswerSignalsTests.cs b/tests/Febe.Tests/Collection/SiteAnswerSignalsTests.cs index 34f1be8..c5071e4 100644 --- a/tests/Febe.Tests/Collection/SiteAnswerSignalsTests.cs +++ b/tests/Febe.Tests/Collection/SiteAnswerSignalsTests.cs @@ -405,14 +405,14 @@ public sealed class SiteSessionTests [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" }) + foreach (var field in new[] { "rev", "hs", "hsi", "dpr", "ccg", "comet_req", "entry_nonce", "spin_r", "spin_b", "spin_t", "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."); + Assert.IsFalse(ValueSource.SessionFields.Contains("spin"), "The vocabulary is closed."); } private static SiteCookie Cookie(string name, string value, DateTimeOffset? expires = null) => diff --git a/tests/Febe.Tests/Collection/TestSiteSessionTests.cs b/tests/Febe.Tests/Collection/TestSiteSessionTests.cs index a10b626..c320bf8 100644 --- a/tests/Febe.Tests/Collection/TestSiteSessionTests.cs +++ b/tests/Febe.Tests/Collection/TestSiteSessionTests.cs @@ -111,7 +111,7 @@ public sealed class TestSiteSessionTests } Assert.AreEqual(200, await StatusWith("rev", TestSite.Revision), "the right values pass"); - foreach (var field in new[] { "rev", "hs", "hsi", "ccg", "dpr", "comet_req", "entry_nonce" }) + foreach (var field in new[] { "rev", "hs", "hsi", "ccg", "dpr", "comet_req", "entry_nonce", "spin_r", "spin_b", "spin_t" }) { Assert.AreEqual(400, await StatusWith(field, "altro-valore"), field); } diff --git a/tests/Febe.Tests/Desktop/SavedSessionConnectionTests.cs b/tests/Febe.Tests/Desktop/SavedSessionConnectionTests.cs index b5eaa5b..5269674 100644 --- a/tests/Febe.Tests/Desktop/SavedSessionConnectionTests.cs +++ b/tests/Febe.Tests/Desktop/SavedSessionConnectionTests.cs @@ -118,17 +118,21 @@ public sealed class SavedSessionConnectionTests await BeginAsync(bed); browser.FakeCdp.LoggedIn = true; + browser.FakeCdp.Navigated(Site + "/"); - // He closes the window without «Ho finito»: the lease ends by itself, the page is the engine's again. + // He puts the window away without «Ho finito»: the lease ends by itself, after the copy of S4b (its page is still + // his until then), and the page is the engine's again. await browser.HideFromUserAsync(ct); await DesktopTestBed.WaitUntilAsync(() => !browser.UserIsDriving, TimeSpan.FromSeconds(10), "la fine della guida"); - browser.FakeCdp.Navigated(Site + "/"); + Assert.AreEqual(1, browser.FakeCdp.CaptureReads, "copied once, before the lease ended"); + var copied = bed.App.SavedSession!.Read(); + Assert.IsNotNull(copied); var finish = await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish"); Assert.IsTrue(finish.GetProperty("connected").GetBoolean()); StringAssert.Contains(finish.GetProperty("message").GetString(), "non è stata copiata"); - Assert.AreEqual(0, browser.FakeCdp.CaptureReads, "nothing is read from a page that is not his"); - Assert.IsNull(bed.App.SavedSession!.Read()); + Assert.AreEqual(1, browser.FakeCdp.CaptureReads, "nothing is read from a page that is not his"); + Assert.AreSame(copied, bed.App.SavedSession.Read()); } [TestMethod] diff --git a/tests/Febe.Tests/Desktop/SessionCopyOnLetGoTests.cs b/tests/Febe.Tests/Desktop/SessionCopyOnLetGoTests.cs new file mode 100644 index 0000000..69fa82b --- /dev/null +++ b/tests/Febe.Tests/Desktop/SessionCopyOnLetGoTests.cs @@ -0,0 +1,272 @@ +using System.Net; +using Febe.App; +using Febe.Core.Collection.Requests; +using Febe.Tests.Desktop.Support; +using Febe.Web.Connection; + +namespace Febe.Tests.Desktop; + +/// +/// Stage S4b of issue #36 (answers of Alberto of 18 November 2026) in the shared composition, with a fake browser and +/// the test site's catalog: the session is copied also when Alberto closes the browser window and when his driving +/// lease ends by itself — only from a page of the site, before the page goes back to the engine (rule 7) —; with the +/// raccolta «richieste» «Collegato» needs a readable saved session («Serve «Ho finito»» otherwise, the engine waits); +/// an incomplete copy can keep the complete one; the Collegamento page gets counts and names, never values. Never +/// Instagram. +/// +[TestClass] +public sealed class SessionCopyOnLetGoTests +{ + private const string Site = "http://127.0.0.1:8481"; + + public TestContext TestContext { get; set; } = null!; + + [TestMethod] + [Timeout(60_000, CooperativeCancellation = true)] + public async Task ClosingTheWindowCopiesTheSessionBeforeThePageGoesBackToTheEngine() + { + var ct = TestContext.CancellationToken; + await using var bed = await StartAsync(); + var browser = bed.Browser!; + var connection = bed.App.Connection!; + + // «Apri il browser»: only the window holds the engine still (no lease of «Accedi»). + await connection.ShowBrowserAsync(openLogin: false, ct); + browser.FakeCdp.LoggedIn = true; + browser.FakeCdp.Navigated(Site + "/"); + bool? drivingWhileCopying = null; + bool? sessionWhileCopying = null; + browser.FakeCdp.OnCapture = () => + { + drivingWhileCopying = browser.UserIsDriving; + sessionWhileCopying = bed.App.Engine!.Services.Runtime.CurrentSession is not null; + }; + + await browser.CloseWindowAsync(ct); + + Assert.AreEqual(1, browser.FakeCdp.CaptureReads); + Assert.IsTrue(drivingWhileCopying, "the page is still Alberto's while it is read"); + Assert.IsFalse(sessionWhileCopying, "no engine session runs meanwhile"); + Assert.IsFalse(browser.UserIsDriving, "then it goes back to the engine"); + var saved = bed.App.SavedSession!.Read(); + Assert.IsNotNull(saved); + Assert.AreEqual(Febe.SitoDiProva.TestSite.SpinBranch, saved.Fields["spin_b"]); + Assert.AreEqual(ConnectionState.Connected, (await connection.GetStatusAsync(ct)).State); + } + + [TestMethod] + [Timeout(60_000, CooperativeCancellation = true)] + public async Task ClosingTheWindowOffTheSiteOrWithoutASessionCopiesNothing() + { + var ct = TestContext.CancellationToken; + await using var bed = await StartAsync(); + var browser = bed.Browser!; + var connection = bed.App.Connection!; + + // Another site's page: the copier refuses before reading the modules. + await connection.ShowBrowserAsync(openLogin: false, ct); + browser.FakeCdp.LoggedIn = true; + browser.FakeCdp.Navigated("https://altro.example.invalid/pagina"); + await browser.CloseWindowAsync(ct); + Assert.AreEqual(0, browser.FakeCdp.CaptureReads); + Assert.IsNull(bed.App.SavedSession!.Read()); + + // A page of the site without the session cookie: nothing to copy. + await connection.ShowBrowserAsync(openLogin: false, ct); + browser.FakeCdp.LoggedIn = false; + browser.FakeCdp.Navigated(Site + "/"); + await browser.CloseWindowAsync(ct); + Assert.AreEqual(0, browser.FakeCdp.CaptureReads); + Assert.IsNull(bed.App.SavedSession.Read()); + Assert.IsFalse(browser.UserIsDriving); + } + + [TestMethod] + [Timeout(60_000, CooperativeCancellation = true)] + public async Task TheEndOfTheLeaseCopiesOnceAndNotAgainAfterTheWindowCopied() + { + var ct = TestContext.CancellationToken; + await using var bed = await StartAsync(); + var browser = bed.Browser!; + var connection = bed.App.Connection!; + connection.DrivingGrace = TimeSpan.FromMilliseconds(400); + + // «Usa il browser», then the window is put away without «Ho finito»: the lease ends by itself after the copy. + await BeginAsync(bed, openLogin: false); + browser.FakeCdp.LoggedIn = true; + browser.FakeCdp.Navigated(Site + "/"); + await browser.HideFromUserAsync(ct); + await DesktopTestBed.WaitUntilAsync(() => !browser.UserIsDriving, TimeSpan.FromSeconds(10), "la fine della guida"); + Assert.AreEqual(1, browser.FakeCdp.CaptureReads, "copied when the lease ended"); + Assert.IsNotNull(bed.App.SavedSession!.Read()); + + // «Usa il browser» again, the window closed (a copy), then the lease ends: no second copy for the same use. + await BeginAsync(bed, openLogin: false); + browser.FakeCdp.Navigated(Site + "/profilo/marta.prova/"); + await browser.CloseWindowAsync(ct); + Assert.AreEqual(2, browser.FakeCdp.CaptureReads, "the window's copy"); + await DesktopTestBed.WaitUntilAsync(() => !browser.UserIsDriving, TimeSpan.FromSeconds(10), "la fine della guida dopo la finestra"); + Assert.AreEqual(2, browser.FakeCdp.CaptureReads, "the end of the lease does not copy again"); + + // On the site's login page (a path of its stop rules) the end of the lease copies nothing: the copier refuses it. + var before = bed.App.SavedSession.Read(); + await BeginAsync(bed, openLogin: false); + browser.FakeCdp.Navigated(Site + "/accesso/"); + await browser.HideFromUserAsync(ct); + await DesktopTestBed.WaitUntilAsync(() => !browser.UserIsDriving, TimeSpan.FromSeconds(10), "la fine della guida sulla pagina di accesso"); + Assert.AreSame(before, bed.App.SavedSession.Read()); + Assert.AreEqual(2, browser.FakeCdp.CaptureReads, "refused before the modules are read"); + } + + [TestMethod] + [Timeout(60_000, CooperativeCancellation = true)] + public async Task WithRichiesteCollegatoNeedsTheSavedSessionAndTheEngineWaitsForIt() + { + var ct = TestContext.CancellationToken; + await using var bed = await StartAsync(); + var browser = bed.Browser!; + var connection = bed.App.Connection!; + + // The session in the browser, but «Annulla» instead of «Ho finito»: no copy. + await BeginAsync(bed); + browser.FakeCdp.LoggedIn = true; + using (var cancel = await bed.SendAsync(HttpMethod.Post, "/api/connection/cancel")) + { + Assert.AreEqual(HttpStatusCode.NoContent, cancel.StatusCode); + } + + // As the background look would see it a moment later. + await connection.RefreshAsync(ct); + var status = await bed.JsonAsync(HttpMethod.Get, "/api/connection"); + Assert.AreEqual("copyMissing", status.GetProperty("state").GetString()); + var saved = status.GetProperty("savedSession"); + Assert.AreEqual("none", saved.GetProperty("state").GetString()); + Assert.IsTrue(connection.IsConnected); + Assert.IsTrue(connection.SessionCopyMissing); + Assert.IsFalse(connection.IsReadyToCollect, "the engine waits"); + Assert.IsFalse(bed.App.Engine!.Services.Runtime.IsConnected); + Assert.IsTrue(bed.App.Engine.Services.Runtime.SessionCopyMissing); + var engine = await bed.JsonAsync(HttpMethod.Get, "/api/engine"); + Assert.AreEqual("copyMissing", engine.GetProperty("connection").GetProperty("state").GetString()); + Assert.AreEqual("Serve «Ho finito»", engine.GetProperty("snapshot").GetProperty("headline").GetString()); + + // «Ho finito»: «Collegato», with counts and names of the copy and never a value. + await BeginAsync(bed, openLogin: false); + browser.FakeCdp.Navigated(Site + "/"); + await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish"); + using (var answer = await bed.SendAsync(HttpMethod.Get, "/api/connection")) + { + var text = await answer.Content.ReadAsStringAsync(ct); + foreach (var secret in new[] { Febe.SitoDiProva.TestSite.Lsd, Febe.SitoDiProva.TestSite.Dtsg, Febe.SitoDiProva.TestSite.EntryNonce, Febe.SitoDiProva.TestSite.SpinBranch, "sessione-di-prova", "csrf-di-prova", "Finestra di prova" }) + { + Assert.DoesNotContain(secret, text, "counts and names only"); + } + } + + status = await bed.JsonAsync(HttpMethod.Get, "/api/connection"); + Assert.AreEqual("connected", status.GetProperty("state").GetString()); + saved = status.GetProperty("savedSession"); + Assert.AreEqual("present", saved.GetProperty("state").GetString()); + Assert.IsTrue(saved.GetProperty("copiedAt").GetInt64() > 0); + Assert.AreEqual(saved.GetProperty("valuesExpected").GetInt32(), saved.GetProperty("valuesPresent").GetInt32()); + Assert.AreEqual(0, saved.GetProperty("missingValues").GetArrayLength()); + Assert.AreEqual(0, saved.GetProperty("neededMissing").GetInt32()); + Assert.IsTrue(connection.IsReadyToCollect); + } + + [TestMethod] + [Timeout(60_000, CooperativeCancellation = true)] + public async Task WithPagineCollegatoIsTheCookieAloneAndNoSavedSessionIsShown() + { + var ct = TestContext.CancellationToken; + await using var bed = await DesktopTestBed.StartAsync(["--sito-di-prova", Site]); + await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct); + await BeginAsync(bed); + bed.Browser!.FakeCdp.LoggedIn = true; + await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish"); + var status = await bed.JsonAsync(HttpMethod.Get, "/api/connection"); + Assert.AreEqual("connected", status.GetProperty("state").GetString()); + Assert.IsTrue(status.TryGetProperty("savedSession", out var saved) is false || saved.ValueKind == System.Text.Json.JsonValueKind.Null); + Assert.IsFalse(bed.App.Connection!.SessionCopyMissing); + Assert.AreEqual(0, bed.Browser.FakeCdp.CaptureReads); + } + + [TestMethod] + [Timeout(60_000, CooperativeCancellation = true)] + public async Task TheIncompleteCopySettingIsStoredAndHeldByTheNextHoFinito() + { + await using var bed = await StartAsync(); + var browser = bed.Browser!; + + // The default: «sostituisci»; an unknown choice is refused. + Assert.AreEqual(SessionCopySettings.ReplaceText, (await bed.JsonAsync(HttpMethod.Get, "/api/connection/settings")).GetProperty("incompleteCopy").GetString()); + using (var wrong = await bed.SendAsync(HttpMethod.Put, "/api/connection/settings", """{"incompleteCopy":"forse"}""")) + { + Assert.AreEqual(HttpStatusCode.BadRequest, wrong.StatusCode); + } + + var keep = await bed.JsonAsync(HttpMethod.Put, "/api/connection/settings", """{"incompleteCopy":"tieni-completa"}"""); + Assert.AreEqual(SessionCopySettings.KeepCompleteText, keep.GetProperty("incompleteCopy").GetString()); + Assert.AreEqual(SessionCopySettings.KeepCompleteText, await bed.App.Database.Settings.GetAsync(SessionCopySettings.IncompleteCopyKey)); + + // A complete copy, then one from a page without the nonce: the complete one stays and «Ho finito» says so. + await FinishOnSiteAsync(bed, openLogin: true); + var complete = bed.App.SavedSession!.Read()!; + var page = FakeCdp.DefaultPageCapture(); + ((System.Text.Json.Nodes.JsonObject)page["values"]!).Remove("entry_nonce"); + browser.FakeCdp.PageCapture = page; + var message = await FinishOnSiteAsync(bed, openLogin: false); + StringAssert.Contains(message, "Febe tiene la copia completa salvata prima"); + StringAssert.Contains(message, "«Sostituisci comunque»"); + Assert.AreSame(complete, bed.App.SavedSession.Read()); + + // «Sostituisci comunque»: the next incomplete copy replaces it, as in S4. + await bed.JsonAsync(HttpMethod.Put, "/api/connection/settings", """{"incompleteCopy":"sostituisci"}"""); + message = await FinishOnSiteAsync(bed, openLogin: false); + StringAssert.Contains(message, "ha comunque sostituito quella salvata"); + Assert.IsFalse(bed.App.SavedSession.Read()!.Fields.ContainsKey("entry_nonce")); + var status = await bed.JsonAsync(HttpMethod.Get, "/api/connection"); + Assert.AreEqual("connected", status.GetProperty("state").GetString(), "an incomplete copy is still a readable session"); + var saved = status.GetProperty("savedSession"); + Assert.AreEqual("entry_nonce", saved.GetProperty("missingValues")[0].GetString()); + Assert.AreEqual(1, saved.GetProperty("neededMissing").GetInt32()); + } + + [TestMethod] + public void TheMessagesOfTheNewOutcomesSayWhatHappened() + { + var kept = BrowserConnectionService.CopyMessage(new SessionCopyOutcome(SessionCopyStatus.KeptComplete, null, 3, 1, 0)); + StringAssert.Contains(kept, "mancavano 1 valori"); + StringAssert.Contains(kept, "tiene la copia completa salvata prima"); + StringAssert.Contains(kept, "Riapri il browser dalla pagina Collegamento"); + + Assert.AreEqual("sessione copiata", BrowserConnectionService.LetGoSummary(new SessionCopyOutcome(SessionCopyStatus.Saved, null, 3, 0, 0))); + StringAssert.Contains(BrowserConnectionService.LetGoSummary(new SessionCopyOutcome(SessionCopyStatus.Saved, null, 3, 2, 0)), "mancano 2 valori"); + StringAssert.Contains(BrowserConnectionService.LetGoSummary(new SessionCopyOutcome(SessionCopyStatus.KeptComplete, null, 3, 1, 0)), "resta quella completa"); + StringAssert.Contains(BrowserConnectionService.LetGoSummary(new SessionCopyOutcome(SessionCopyStatus.Refused, Febe.Browser.Session.CaptureRefusal.CheckpointPage, 0, 0, 0)), "pagina di accesso o di verifica"); + } + + private async Task StartAsync() + { + var bed = await DesktopTestBed.StartAsync(["--sito-di-prova", Site, "--raccolta", "richieste"]); + await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), TestContext.CancellationToken); + return bed; + } + + private static async Task BeginAsync(DesktopTestBed bed, bool openLogin = true) + { + using var begin = await bed.SendAsync(HttpMethod.Post, "/api/connection/begin", openLogin ? """{"openLogin":true}""" : """{"openLogin":false}"""); + Assert.AreEqual(HttpStatusCode.NoContent, begin.StatusCode); + } + + /// «Accedi» or «Usa il browser», the site's home with the session, «Ho finito». Returns the message. + private static async Task FinishOnSiteAsync(DesktopTestBed bed, bool openLogin) + { + await BeginAsync(bed, openLogin); + bed.Browser!.FakeCdp.LoggedIn = true; + bed.Browser.FakeCdp.Navigated(Site + "/"); + var finish = await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish"); + Assert.IsTrue(finish.GetProperty("connected").GetBoolean(), finish.GetProperty("message").GetString()); + return finish.GetProperty("message").GetString()!; + } +} diff --git a/tests/Febe.Tests/Desktop/Support/FakeDesktopShell.cs b/tests/Febe.Tests/Desktop/Support/FakeDesktopShell.cs index 181ec77..aab8520 100644 --- a/tests/Febe.Tests/Desktop/Support/FakeDesktopShell.cs +++ b/tests/Febe.Tests/Desktop/Support/FakeDesktopShell.cs @@ -196,6 +196,33 @@ internal sealed class FakeBrowser : IFebeBrowser return Task.CompletedTask; } + /// + /// Like Alberto closing the real window «Browser di Febe» (WebView2Host.Done, issue #36, S4b): out of view at once, + /// the copy of the session before the page goes back to the engine (a hold keeps it his meanwhile), then the lease ends. + /// + public async Task CloseWindowAsync(CancellationToken ct) + { + Hidden++; + if (_lease is null || _context.CopyOnWindowClosed is not { } copy) + { + _lease?.Dispose(); + _lease = null; + return; + } + + var hold = UserDriving.Begin(); + _lease.Dispose(); + _lease = null; + try + { + await copy(ct); + } + finally + { + hold.Dispose(); + } + } + /// The next «Scollega» finds a file held by another process (Windows) and cannot delete the profile. public bool ProfileLocked { get; set; } @@ -244,6 +271,9 @@ internal sealed class FakeCdp : ICdpSession /// public JsonObject? PageCapture { get; set; } = DefaultPageCapture(); + /// Called when the copy's evaluation is asked, before it answers (what the test wants to look at then). + public Action? OnCapture { get; set; } + /// How many times the copy's evaluation (the one that reads navigator.userAgent) was asked. public int CaptureReads => Volatile.Read(ref _captureReads); @@ -267,6 +297,9 @@ internal sealed class FakeCdp : ICdpSession ["comet_req"] = Febe.SitoDiProva.TestSite.CometReq, ["ccg"] = Febe.SitoDiProva.TestSite.ConnectionClass, ["entry_nonce"] = Febe.SitoDiProva.TestSite.EntryNonce, + ["spin_r"] = Febe.SitoDiProva.TestSite.SpinRevision, + ["spin_b"] = Febe.SitoDiProva.TestSite.SpinBranch, + ["spin_t"] = Febe.SitoDiProva.TestSite.SpinTime, }, ["docIds"] = new JsonObject { [Febe.SitoDiProva.TestSite.ProfileQuery] = Febe.SitoDiProva.TestSite.DocIds[Febe.SitoDiProva.TestSite.ProfileQuery] }, }; @@ -366,6 +399,7 @@ internal sealed class FakeCdp : ICdpSession private JsonObject Capture() { Interlocked.Increment(ref _captureReads); + OnCapture?.Invoke(); return PageCapture is { } page ? new JsonObject { ["result"] = new JsonObject { ["type"] = "object", ["value"] = JsonNode.Parse(page.ToJsonString()) } } : new JsonObject(); diff --git a/tools/Febe.SitoDiProva/DirectApi.cs b/tools/Febe.SitoDiProva/DirectApi.cs index d05cc26..827988b 100644 --- a/tools/Febe.SitoDiProva/DirectApi.cs +++ b/tools/Febe.SitoDiProva/DirectApi.cs @@ -53,6 +53,15 @@ public sealed partial class TestSite /// The nonce of the page load (session:entry_nonce, header x-fb-entry-nonce; AvvioProva.nonce). public const string EntryNonce = "nonce-di-prova"; + /// The revision of the page load (session:spin_r, field __spin_r; GiroProva.revisione, a number in the page). + public const string SpinRevision = "1001"; + + /// The branch of the page load (session:spin_b, field __spin_b; GiroProva.ramo). + public const string SpinBranch = "ramo-di-prova"; + + /// The time of the page load (session:spin_t, field __spin_t; GiroProva.tempo, a number in the page). + public const string SpinTime = "1700000000"; + /// A cookie of the pages limited to the addresses under (Path=/api/): the copy keeps it with its path. public const string ApiPathCookie = "percorso_api"; @@ -258,7 +267,8 @@ public sealed partial class TestSite // The values of the page the saved session copies (S4): a missing or different one gets the same generic 400. if (form["__rev"].ToString() != Revision || form["__hs"].ToString() != HasteSession || form["__hsi"].ToString() != HasteSessionId || form["__ccg"].ToString() != ConnectionClass || form["dpr"].ToString() != Dpr || form["__comet_req"].ToString() != CometReq - || request.Headers["x-fb-entry-nonce"].ToString() != EntryNonce) + || request.Headers["x-fb-entry-nonce"].ToString() != EntryNonce + || form["__spin_r"].ToString() != SpinRevision || form["__spin_b"].ToString() != SpinBranch || form["__spin_t"].ToString() != SpinTime) { return ("campi", null); } diff --git a/tools/Febe.SitoDiProva/PageModules.cs b/tools/Febe.SitoDiProva/PageModules.cs index cec0e95..834d390 100644 --- a/tools/Febe.SitoDiProva/PageModules.cs +++ b/tools/Febe.SitoDiProva/PageModules.cs @@ -83,6 +83,12 @@ public sealed partial class TestSite }); yield return ("ConnessioneProva", new JsonObject { ["classe"] = ConnectionClass }); yield return ("AvvioProva", new JsonObject { ["nonce"] = EntryNonce }); + yield return ("GiroProva", new JsonObject + { + ["revisione"] = int.Parse(SpinRevision, CultureInfo.InvariantCulture), + ["ramo"] = SpinBranch, + ["tempo"] = int.Parse(SpinTime, CultureInfo.InvariantCulture), + }); foreach (var (operation, docId) in DocIds.OrderBy(d => d.Key, StringComparer.Ordinal)) { yield return (operation + DocIdModuleSuffix, JsonValue.Create(docId));