Sessione salvata: copia alla chiusura della finestra e alla fine della guida, «Serve «Ho finito»», scelta per la copia incompleta e stato in Collegamento (#36, S4b)

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 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-18 11:41:35 +01:00
1 parent 9958745e53
commit 883ea4683c
41 files changed
+1349 -101

No files matched your search

+5
View File
@@ -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 |
+32 -8
View File
@@ -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
+2
View File
@@ -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)) |
+7 -4
View File
@@ -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,
+246 -2
View File
@@ -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».
/// </para>
/// <para>
/// 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 (<see cref="CopyOnWindowClosedAsync"/>) 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
/// <see cref="ConnectionState.SessionCopyMissing"/> («Serve «Ho finito»») and the engine waits.
/// </para>
/// </remarks>
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;
/// <param name="browser">The browser of Febe.</param>
/// <param name="storage">The database (first connection, «Scollega»).</param>
@@ -119,6 +129,24 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
}
}
/// <summary>
/// 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).
/// </summary>
public bool SessionCopyMissing => _copier is not null && _copier.SavedState != SavedSessionState.Present;
/// <summary>
/// Whether the engine may collect (<see cref="EngineRuntime.IsConnected"/>): the session cookie is in the browser
/// and, with a saved session, a readable copy of it is there too.
/// </summary>
public bool IsReadyToCollect => IsConnected == true && !SessionCopyMissing;
/// <summary>
/// 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.
/// </summary>
public TimeSpan LetGoWait { get; set; } = TimeSpan.FromSeconds(30);
/// <summary>
/// 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));
}
/// <summary>
/// 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 <see cref="LetGoWait"/>. Never throws for the
/// browser; logs counts only.
/// </summary>
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
}
}
/// <summary>
/// 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
/// (<paramref name="poll"/>) 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.
/// </summary>
private async Task<bool> 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();
}
}
/// <summary>
/// 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).
/// </summary>
private async Task CopyOnLetGoAsync(string what, Func<bool> 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.");
}
}
/// <summary>What a copy without «Ho finito» did, for the log (counts only).</summary>
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",
};
}
/// <summary>The saved session for the interface, in counts and names; null without a saved session in this start.</summary>
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.
}
}
/// <summary>The first connection ever starts the gradual start (spec §7.2). True when it was the first.</summary>
private async Task<bool> 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}",
_ =>
+20 -5
View File
@@ -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)
{
+6 -1
View File
@@ -72,7 +72,12 @@ public interface IFebePlatform
/// the login page otherwise, once the engine's session ended and with the page's turn
/// (<c>BrowserConnectionService.OpenStartPageAsync</c>). Null: the button does nothing.
/// </param>
public sealed record FebePlatformContext(FebeAppOptions Options, DataFolderLayout Data, IFebeStorage Storage, IClock Clock, FebeLog Log, BrowserUseTracker Tracker, Func<CancellationToken, Task>? OpenStartPage = null);
/// <param name="CopyOnWindowClosed">
/// 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 (<c>BrowserConnectionService.CopyOnWindowClosedAsync</c>). The
/// window holds the driving gate until the task ends. Null: nothing.
/// </param>
public sealed record FebePlatformContext(FebeAppOptions Options, DataFolderLayout Data, IFebeStorage Storage, IClock Clock, FebeLog Log, BrowserUseTracker Tracker, Func<CancellationToken, Task>? OpenStartPage = null, Func<CancellationToken, Task>? CopyOnWindowClosed = null);
/// <summary>Options of the shared composition, filled by each shell from its own configuration.</summary>
public sealed record FebeAppOptions
+140 -9
View File
@@ -19,6 +19,12 @@ public enum SessionCopyStatus
/// <summary>Copied, then thrown away: meanwhile the page was no longer Alberto's (rule 7).</summary>
Discarded,
/// <summary>
/// Copied but not saved: a value the requests need was missing, the saved copy has them all, and Alberto chose
/// «Tieni la copia completa» (<see cref="IncompleteCopyChoice.KeepComplete"/>). The saved session stays as it was.
/// </summary>
KeptComplete,
}
/// <summary>What a copy did, for the message of «Ho finito» and the tests. Never a value.</summary>
@@ -34,11 +40,42 @@ public sealed record SessionCopyOutcome(SessionCopyStatus Status, CaptureRefusal
}
/// <summary>
/// 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.
/// </summary>
/// <param name="State">Whether a saved session is there and can be read.</param>
/// <param name="CopiedAt">When the browser's session was copied; null without a session or when not known.</param>
/// <param name="Cookies">How many cookies it holds.</param>
/// <param name="ValuesPresent">Values of the page it holds, of <paramref name="ValuesExpected"/>.</param>
/// <param name="ValuesExpected">Values of the page the copy reads.</param>
/// <param name="MissingValues">Names of the values of the page it lacks.</param>
/// <param name="DocIdsPresent">doc_id it holds, of <paramref name="DocIdsExpected"/>.</param>
/// <param name="DocIdsExpected">doc_id the copy reads.</param>
/// <param name="MissingDocIds">Operations whose doc_id it lacks.</param>
/// <param name="NeededMissing">How many of the missing values and doc_id a configured operation sends.</param>
public sealed record SavedSessionReport(
SavedSessionState State,
DateTimeOffset? CopiedAt,
int Cookies,
int ValuesPresent,
int ValuesExpected,
IReadOnlyList<string> MissingValues,
int DocIdsPresent,
int DocIdsExpected,
IReadOnlyList<string> MissingDocIds,
int NeededMissing)
{
/// <summary>True when a readable session is there and nothing a configured operation sends is missing.</summary>
public bool Complete => State == SavedSessionState.Present && NeededMissing == 0;
}
/// <summary>
/// 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.
/// </summary>
public interface ISessionCopier
{
@@ -48,6 +85,12 @@ public interface ISessionCopier
/// <param name="mayKeep">Asked after reading, before saving: false throws the copy away (the page stopped being Alberto's).</param>
/// <param name="ct">Cancels the copy; nothing is saved then.</param>
Task<SessionCopyOutcome> CopyAsync(Func<bool> mayKeep, CancellationToken ct);
/// <summary>Whether a saved session is there and can be read (cheap: «Collegato» and the engine ask it often).</summary>
SavedSessionState SavedState { get; }
/// <summary>The saved session now, in counts and names (the Collegamento page, «Collegato»).</summary>
SavedSessionReport Report();
}
/// <summary>
@@ -76,6 +119,12 @@ public sealed class BrowserSessionCopier : ISessionCopier
_log = log ?? throw new ArgumentNullException(nameof(log));
}
/// <summary>
/// What an incomplete copy does, asked at every copy (the setting of the Collegamento page,
/// <see cref="SessionCopySettings"/>); by default it replaces the saved session, as before.
/// </summary>
public Func<CancellationToken, Task<IncompleteCopyChoice>> IncompleteCopy { get; init; } = _ => Task.FromResult(IncompleteCopyChoice.Replace);
/// <summary>
/// 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<string>();
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<string>();
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);
}
/// <summary>Why a copy was refused, in Italian.</summary>
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",
};
/// <summary>True when <paramref name="saved"/> holds every value and doc_id a configured operation sends.</summary>
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;
}
}
@@ -57,12 +57,14 @@ public sealed record ValueSource(ValueSourceKind Kind, string? Argument)
/// <c>page</c> section of the catalog says where to read (<see cref="PageSources"/>): <c>lsd</c>, <c>fb_dtsg</c>,
/// <c>app_id</c>, <c>account_id</c>, and since S4 <c>rev</c> (<c>__rev</c>), <c>hs</c> (<c>__hs</c>), <c>hsi</c>
/// (<c>__hsi</c>), <c>dpr</c>, <c>ccg</c> (<c>__ccg</c>), <c>comet_req</c> (<c>__comet_req</c>) and
/// <c>entry_nonce</c> (<c>x-fb-entry-nonce</c>).
/// <c>entry_nonce</c> (<c>x-fb-entry-nonce</c>), and since S4b <c>spin_r</c>, <c>spin_b</c> and <c>spin_t</c>
/// (<c>__spin_r</c>, <c>__spin_b</c>, <c>__spin_t</c>: a snapshot of the page at «Ho finito», decision of 18 November
/// 2026).
/// </summary>
public static IReadOnlySet<string> 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);
/// <summary>The session fields that need no <c>page</c> entry: the browser's user agent and the claim the site sets (H13).</summary>
@@ -0,0 +1,65 @@
using Febe.Core.Storage;
namespace Febe.Core.Collection.Requests;
/// <summary>What a copy of the browser's session does when some value the requests need is missing (issue #36, S4b).</summary>
public enum IncompleteCopyChoice
{
/// <summary>
/// «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).
/// </summary>
Replace,
/// <summary>
/// «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.
/// </summary>
KeepComplete,
}
/// <summary>
/// The settings of the copy of the session (issue #36, S4b; decision of Alberto of 18 November 2026, answer 9), in the
/// <c>setting</c> table like the other settings. Read at every copy: a change holds from the next copy, no restart.
/// </summary>
/// <param name="IncompleteCopy">What an incomplete copy does.</param>
public sealed record SessionCopySettings(IncompleteCopyChoice IncompleteCopy)
{
/// <summary>The key of <see cref="IncompleteCopy"/>: <c>sostituisci</c> or <c>tieni-completa</c>.</summary>
public const string IncompleteCopyKey = "sessione.copia-incompleta";
/// <summary>The text of <see cref="IncompleteCopyChoice.Replace"/> in the table and in the API.</summary>
public const string ReplaceText = "sostituisci";
/// <summary>The text of <see cref="IncompleteCopyChoice.KeepComplete"/> in the table and in the API.</summary>
public const string KeepCompleteText = "tieni-completa";
/// <summary>The settings of a database that never stored them: an incomplete copy replaces the saved one.</summary>
public static SessionCopySettings Default { get; } = new(IncompleteCopyChoice.Replace);
/// <summary>The text of <paramref name="choice"/>.</summary>
public static string ToText(IncompleteCopyChoice choice) => choice == IncompleteCopyChoice.KeepComplete ? KeepCompleteText : ReplaceText;
/// <summary>The choice of <paramref name="text"/>; null for any other text.</summary>
public static IncompleteCopyChoice? Parse(string? text) => text switch
{
ReplaceText => IncompleteCopyChoice.Replace,
KeepCompleteText => IncompleteCopyChoice.KeepComplete,
_ => null,
};
/// <summary>The stored settings; an unknown or missing value is the default.</summary>
public static async Task<SessionCopySettings> 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;
}
/// <summary>Stores these settings.</summary>
public Task SaveAsync(ISettingsStore settings, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(settings);
return settings.SetAsync(IncompleteCopyKey, ToText(IncompleteCopy), ct);
}
}
+32 -29
View File
@@ -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 «<operazione>_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 «<operazione>_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",
+8 -2
View File
@@ -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",
+10 -1
View File
@@ -12,6 +12,7 @@ public sealed class EngineRuntime
private readonly Lock _gate = new();
private readonly Func<bool> _userIsDriving;
private readonly Func<bool>? _isConnected;
private readonly Func<bool>? _sessionCopyMissing;
private CautionProfile _profile = CautionProfile.Prudent;
private DateTimeOffset? _rampStart;
private SessionContext? _session;
@@ -23,10 +24,15 @@ public sealed class EngineRuntime
/// <param name="userIsDriving">True while Alberto uses the browser (<see cref="IBrowserHost.UserIsDriving"/>).</param>
/// <param name="isConnected">Whether the Instagram session exists in the browser; null when unknown.</param>
public EngineRuntime(Func<bool>? userIsDriving = null, Func<bool>? isConnected = null)
/// <param name="sessionCopyMissing">
/// True when the browser holds the session but the saved session of the raccolta «richieste» is missing (issue #36,
/// S4b): <paramref name="isConnected"/> is then false and the monitor says «Serve «Ho finito»». Null: never.
/// </param>
public EngineRuntime(Func<bool>? userIsDriving = null, Func<bool>? isConnected = null, Func<bool>? sessionCopyMissing = null)
{
_userIsDriving = userIsDriving ?? (() => false);
_isConnected = isConnected;
_sessionCopyMissing = sessionCopyMissing;
}
/// <summary>The effective caution profile (settings applied).</summary>
@@ -56,6 +62,9 @@ public sealed class EngineRuntime
/// <summary>Whether the browser holds an Instagram session; null when the host does not say.</summary>
public bool? IsConnected => _isConnected?.Invoke();
/// <summary>True when the browser holds the session but the copy for the requests is missing (S4b).</summary>
public bool SessionCopyMissing => _sessionCopyMissing?.Invoke() == true;
/// <summary>The session in progress, if any. The Governor refuses every site action without one.</summary>
public SessionContext? CurrentSession
{
+4 -2
View File
@@ -85,6 +85,7 @@ public sealed class EngineServices
/// <param name="userIsDriving">True while Alberto uses the browser.</param>
/// <param name="isConnected">Whether the browser holds an Instagram session; null when unknown.</param>
/// <param name="ct">Cancellation.</param>
/// <param name="sessionCopyMissing">True when the session is in the browser but its saved copy is missing (S4b).</param>
public static async Task<EngineServices> CreateAsync(
IFebeStorage storage,
IClock clock,
@@ -92,14 +93,15 @@ public sealed class EngineServices
EngineOptions? options = null,
Func<bool>? userIsDriving = null,
Func<bool>? isConnected = null,
CancellationToken ct = default)
CancellationToken ct = default,
Func<bool>? 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);
+2
View File
@@ -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:
+1 -1
View File
@@ -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);
}
+37 -3
View File
@@ -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.
/// </param>
internal sealed record WebView2HostOptions(BrowserHosting Hosting, string AdditionalBrowserArguments, ImageSource? Icon, Action MarkUsed, Func<CancellationToken, Task>? OpenStartPage = null);
/// <param name="CopyOnClose">
/// 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.
/// </param>
internal sealed record WebView2HostOptions(BrowserHosting Hosting, string AdditionalBrowserArguments, ImageSource? Icon, Action MarkUsed, Func<CancellationToken, Task>? OpenStartPage = null, Func<CancellationToken, Task>? CopyOnClose = null);
/// <summary>What the host does when a process of WebView2 fails (issue #52).</summary>
internal enum ProcessFailureResponse
@@ -554,12 +558,42 @@ internal sealed class WebView2Host : IBrowserHost
TakeLease();
}
/// <summary>Alberto closed the window (or left it minimised too long): done, out of view.</summary>
/// <summary>
/// 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).
/// </summary>
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<CancellationToken, Task> 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<CoreWebView2> action, Func<CoreWebView2, bool> allowed)
+38 -1
View File
@@ -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<ConnectionSettingsDto> 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));
}
/// <summary>The saved session in counts and names; null without one.</summary>
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",
};
}
+8 -2
View File
@@ -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"
+1
View File
@@ -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))]
+27 -2
View File
@@ -5,8 +5,33 @@ namespace Febe.Web.Api;
// ---------------------------------------------------------------- connection (PROTOCOLLO.md)
/// <summary><c>GET /api/connection</c>. <see cref="State"/>: notConnected, connected, verificationRequired, browserUnavailable.</summary>
public sealed record ConnectionStatusDto(string State, string? Username, string? DisplayName, bool UserIsDriving, string? CurrentUrl);
/// <summary>
/// <c>GET /api/connection</c>. <see cref="State"/>: notConnected, connected, copyMissing, verificationRequired,
/// browserUnavailable. <see cref="SavedSession"/> only with the raccolta «richieste».
/// </summary>
public sealed record ConnectionStatusDto(string State, string? Username, string? DisplayName, bool UserIsDriving, string? CurrentUrl, SavedSessionDto? SavedSession = null);
/// <summary>
/// The saved session in counts and names (issue #36, S4b): <see cref="State"/> present, none or unreadable;
/// <see cref="CopiedAt"/> Unix milliseconds. Never a value.
/// </summary>
public sealed record SavedSessionDto(
string State,
long? CopiedAt,
int Cookies,
int ValuesPresent,
int ValuesExpected,
IReadOnlyList<string> MissingValues,
int DocIdsPresent,
int DocIdsExpected,
IReadOnlyList<string> MissingDocIds,
int NeededMissing);
/// <summary>
/// <c>GET/PUT /api/connection/settings</c>: what an incomplete copy of the session does, <c>sostituisci</c> (the
/// default) or <c>tieni-completa</c>.
/// </summary>
public sealed record ConnectionSettingsDto(string IncompleteCopy);
/// <summary><c>POST /api/connection/begin</c>.</summary>
public sealed record BeginDrivingRequest(bool OpenLogin);
+45 -1
View File
@@ -14,6 +14,48 @@ public enum ConnectionState
/// <summary>The browser is not available (starting, crashed, demo without browser).</summary>
BrowserUnavailable,
/// <summary>
/// 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.
/// </summary>
SessionCopyMissing,
}
/// <summary>
/// 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).
/// </summary>
/// <param name="State"><see cref="Present"/>, <see cref="None"/> or <see cref="Unreadable"/>.</param>
/// <param name="CopiedAt">When the copy was made; null when there is none or it is not known.</param>
/// <param name="Cookies">How many cookies it holds.</param>
/// <param name="ValuesPresent">Values of the page it holds.</param>
/// <param name="ValuesExpected">Values of the page the copy reads.</param>
/// <param name="MissingValues">Names of the values it lacks.</param>
/// <param name="DocIdsPresent">doc_id it holds.</param>
/// <param name="DocIdsExpected">doc_id the copy reads.</param>
/// <param name="MissingDocIds">Operations whose doc_id it lacks.</param>
/// <param name="NeededMissing">How many of those a configured operation sends (its requests do not leave).</param>
public sealed record SavedSessionStatus(
string State,
DateTimeOffset? CopiedAt,
int Cookies,
int ValuesPresent,
int ValuesExpected,
IReadOnlyList<string> MissingValues,
int DocIdsPresent,
int DocIdsExpected,
IReadOnlyList<string> MissingDocIds,
int NeededMissing)
{
/// <summary>A readable saved session.</summary>
public const string Present = "present";
/// <summary>No saved session.</summary>
public const string None = "none";
/// <summary>A file that cannot be read: counts as none.</summary>
public const string Unreadable = "unreadable";
}
/// <summary>What the interface knows about the link to Instagram.</summary>
@@ -22,12 +64,14 @@ public enum ConnectionState
/// <param name="DisplayName">Display name, when known.</param>
/// <param name="UserIsDriving">True while Alberto is using the browser (login page, remote view, browser window): the engine is still.</param>
/// <param name="CurrentUrl">Address shown in the remote view's address bar, without query string.</param>
/// <param name="SavedSession">The saved session (raccolta «richieste»); null when this start keeps none.</param>
public sealed record ConnectionStatus(
ConnectionState State,
string? Username,
string? DisplayName,
bool UserIsDriving,
string? CurrentUrl);
string? CurrentUrl,
SavedSessionStatus? SavedSession = null);
/// <summary>Result of «Ho finito» on the Collegamento page.</summary>
/// <param name="Connected">True when the session cookie now exists.</param>
+10 -1
View File
@@ -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).
+9
View File
@@ -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}
+1 -1
View File
@@ -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')),
+67 -7
View File
@@ -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'),
+23
View File
@@ -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": [
{
@@ -58,7 +58,9 @@ internal sealed class DesktopBed : IAsyncDisposable
/// <param name="name">Prefix of the temporary folder.</param>
/// <param name="autoLogin"><c>--accesso-di-prova</c>: the composition opens the test site once at start-up.</param>
public static async Task<DesktopBed> StartAsync(string name, bool autoLogin, CancellationToken ct)
/// <param name="ct">Cancels the start.</param>
/// <param name="extra">More options of Febe.exe (<c>--raccolta richieste</c>).</param>
public static async Task<DesktopBed> 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);
@@ -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);
}
}
@@ -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<string>();
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" },
@@ -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":{}}""");
@@ -452,7 +452,7 @@ public sealed class HttpSiteRequesterTests
var secrets = new List<string>
{
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,
};
/// <summary>A site client for the test site with its session, clock and log.</summary>
@@ -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<string>(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<string>(), 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 };
@@ -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)
{
@@ -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) =>
@@ -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);
}
@@ -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]
@@ -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;
/// <summary>
/// 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.
/// </summary>
[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<DesktopTestBed> 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);
}
/// <summary>«Accedi» or «Usa il browser», the site's home with the session, «Ho finito». Returns the message.</summary>
private static async Task<string> 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()!;
}
}
@@ -196,6 +196,33 @@ internal sealed class FakeBrowser : IFebeBrowser
return Task.CompletedTask;
}
/// <summary>
/// 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.
/// </summary>
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();
}
}
/// <summary>The next «Scollega» finds a file held by another process (Windows) and cannot delete the profile.</summary>
public bool ProfileLocked { get; set; }
@@ -244,6 +271,9 @@ internal sealed class FakeCdp : ICdpSession
/// </summary>
public JsonObject? PageCapture { get; set; } = DefaultPageCapture();
/// <summary>Called when the copy's evaluation is asked, before it answers (what the test wants to look at then).</summary>
public Action? OnCapture { get; set; }
/// <summary>How many times the copy's evaluation (the one that reads <c>navigator.userAgent</c>) was asked.</summary>
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();
+11 -1
View File
@@ -53,6 +53,15 @@ public sealed partial class TestSite
/// <summary>The nonce of the page load (session:entry_nonce, header <c>x-fb-entry-nonce</c>; AvvioProva.nonce).</summary>
public const string EntryNonce = "nonce-di-prova";
/// <summary>The revision of the page load (session:spin_r, field <c>__spin_r</c>; GiroProva.revisione, a number in the page).</summary>
public const string SpinRevision = "1001";
/// <summary>The branch of the page load (session:spin_b, field <c>__spin_b</c>; GiroProva.ramo).</summary>
public const string SpinBranch = "ramo-di-prova";
/// <summary>The time of the page load (session:spin_t, field <c>__spin_t</c>; GiroProva.tempo, a number in the page).</summary>
public const string SpinTime = "1700000000";
/// <summary>A cookie of the pages limited to the addresses under <see cref="ApiPath"/> (Path=/api/): the copy keeps it with its path.</summary>
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);
}
+6
View File
@@ -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));