Sessione salvata cifrata, copiata a «Ho finito» (#36, S4)
Il client del sito ha bisogno della sessione del browser di Febe: ora la copia c'è, cifrata e dietro un interruttore, senza cambiare nulla di predefinito. - Opzione «raccolta» (pagine predefinita, richieste): solo con «richieste» e almeno un'operazione configurata si costruiscono sessione salvata, client del sito e copia. Con Instagram nulla cambia: le dieci operazioni restano non configurate (mancano __spin_*, __req, __s, __dyn, __csr e altri). - Cookie con dominio, percorso, solo-host, Secure, HttpOnly e scadenza, mandati solo dove il browser li manderebbe (RFC 6265). - Sezione «page» del catalogo: dove la pagina tiene ogni valore; nuovi campi rev, hs, hsi, dpr, ccg, comet_req, entry_nonce. Il caricatore rifiuta un'operazione configurata con un valore di sessione senza fonte nella pagina. - Dati/sessione/sessione.json: DPAPI su Windows, AES-256-GCM in Docker (chiave da FEBE_CHIAVE_SESSIONE o chiave.bin), scrittura atomica, file illeggibile = nessuna sessione. «Scollega» la cancella; chiave.bin resta. - Copia a «Ho finito» con Network.getCookies e una sola Runtime.evaluate in sola lettura, solo da una pagina del sito e finché dura il permesso di guida. - FEBE_PASSWORD e FEBE_CHIAVE_SESSIONE non passano a Chromium, Xvfb, ffmpeg. - Sito di prova: csrftoken, cookie limitato a /api/, registro di moduli suo. - Revisione su tre lenti: 11 punti confermati, tutti corretti. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
3046b2da47
commit
c87768766c
69 files changed
+5936
-415
No files matched your search
@@ -0,0 +1,59 @@
|
||||
using Febe.App;
|
||||
using Febe.Core.Library;
|
||||
using Febe.Desktop.Core;
|
||||
using Febe.Tests.Desktop.Support;
|
||||
using Febe.Tests.Support;
|
||||
using Febe.Web.Engine;
|
||||
|
||||
namespace Febe.Tests.Desktop;
|
||||
|
||||
/// <summary>
|
||||
/// Issue #36, S4, spec §12 and §13.2, on the Windows side without Windows: the option «raccolta» of Febe.exe (pages by
|
||||
/// default) and the protector of the saved session, which comes from the Windows-only shell (DPAPI there, a fake here).
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class DesktopSessionOptionsTests
|
||||
{
|
||||
[TestMethod]
|
||||
public void TheCommandLineReadsRaccoltaAndPagesIsTheDefault()
|
||||
{
|
||||
var folders = new DesktopFolders("a", "b");
|
||||
Assert.IsTrue(DesktopCommandLine.TryParse([], out var plain, out var problem), problem);
|
||||
Assert.AreEqual(CollectionRoute.Pages, plain.Collection, "nothing changes by default");
|
||||
Assert.AreEqual(CollectionRoute.Pages, plain.AppOptions("c", folders).Collection);
|
||||
|
||||
Assert.IsTrue(DesktopCommandLine.TryParse(["--sito-di-prova", "http://127.0.0.1:8481", "--raccolta", "RICHIESTE"], out var requests, out problem), problem);
|
||||
Assert.AreEqual(CollectionRoute.Requests, requests.Collection);
|
||||
Assert.AreEqual(CollectionRoute.Requests, requests.AppOptions("c", folders).Collection);
|
||||
|
||||
Assert.IsFalse(DesktopCommandLine.TryParse(["--raccolta", "browser"], out _, out problem));
|
||||
StringAssert.Contains(problem, "pagine oppure richieste");
|
||||
Assert.IsFalse(DesktopCommandLine.TryParse(["--raccolta"], out _, out problem));
|
||||
StringAssert.Contains(problem, "Dopo --raccolta");
|
||||
StringAssert.Contains(DesktopCommandLine.Usage, "--raccolta pagine|richieste");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheProtectorIsTheShellsAndTheLogNamesOnlyItsScheme()
|
||||
{
|
||||
using var temp = new TempFolder("desktop-sessione");
|
||||
using var console = new StringWriter();
|
||||
var clock = new ManualClock(new DateTimeOffset(2026, 11, 17, 10, 0, 0, TimeSpan.Zero));
|
||||
using var log = new FebeLog(null, console, clock);
|
||||
var shell = new FakeDesktopShell();
|
||||
var platform = new DesktopPlatform(new DesktopOptions(), shell, new MemoryLocationStore(), dataFolderFixed: true);
|
||||
var data = new DataFolderLayout(temp.Combine("dati"));
|
||||
var context = new FebePlatformContext(
|
||||
new FebeAppOptions { DataFolder = data.Root, LibraryFolder = temp.Combine("libreria") },
|
||||
data,
|
||||
null!,
|
||||
clock,
|
||||
log,
|
||||
new BrowserUseTracker());
|
||||
|
||||
var protector = platform.CreateSessionProtector(context);
|
||||
Assert.AreSame(shell.SessionProtector, protector);
|
||||
StringAssert.Contains(console.ToString(), "Sessione salvata: cifrata con " + protector.Scheme);
|
||||
Assert.IsFalse(Directory.Exists(data.Session), "no key file on Windows: DPAPI needs none");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,313 @@
|
||||
using System.Net;
|
||||
using Febe.App;
|
||||
using Febe.Core.Collection.Requests;
|
||||
using Febe.Tests.Desktop.Support;
|
||||
using Febe.Tests.Support;
|
||||
|
||||
namespace Febe.Tests.Desktop;
|
||||
|
||||
/// <summary>
|
||||
/// The saved session in the shared composition (issue #36, S4, spec §6.0, §13.2, rule 7), with a fake browser: it
|
||||
/// exists only with «raccolta» on «richieste» and configured operations (never with Instagram in S4, never by
|
||||
/// default), «Ho finito» copies it only while Alberto's lease holds and only from a page of the site, «Annulla» copies
|
||||
/// nothing, «Scollega» deletes it, and the test site's automatic login copies it too. Never Instagram.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class SavedSessionConnectionTests
|
||||
{
|
||||
private const string Site = "http://127.0.0.1:8481";
|
||||
|
||||
public TestContext TestContext { get; set; } = null!;
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(90_000, CooperativeCancellation = true)]
|
||||
public async Task TheGateBuildsNothingWithInstagramNorByDefaultAndTheClientWithTheTestSiteAndRichieste()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
|
||||
// Instagram with «richieste»: no operation is configured in S4, so nothing is built and nothing is read.
|
||||
await using (var bed = await DesktopTestBed.StartAsync(["--raccolta", "richieste"]))
|
||||
{
|
||||
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
|
||||
Assert.IsNull(bed.App.SavedSession);
|
||||
Assert.IsNull(bed.App.SiteRequester);
|
||||
var finish = await LoginAsync(bed);
|
||||
Assert.DoesNotContain("Sessione copiata", finish);
|
||||
Assert.AreEqual(0, bed.Browser!.FakeCdp.CaptureReads, "no module of Instagram's page is read");
|
||||
Assert.IsFalse(Directory.Exists(bed.App.Data!.Session), "nothing in Dati/sessione");
|
||||
}
|
||||
|
||||
// The test site by default («pagine»): the browser path, as before S4.
|
||||
await using (var bed = await DesktopTestBed.StartAsync(["--sito-di-prova", Site]))
|
||||
{
|
||||
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
|
||||
Assert.AreEqual(CollectionRoute.Pages, bed.App.Options.Collection);
|
||||
Assert.IsNull(bed.App.SavedSession);
|
||||
Assert.IsNull(bed.App.SiteRequester);
|
||||
await LoginAsync(bed);
|
||||
Assert.AreEqual(0, bed.Browser!.FakeCdp.CaptureReads);
|
||||
Assert.IsFalse(Directory.Exists(bed.App.Data!.Session));
|
||||
}
|
||||
|
||||
// The test site with «richieste»: the saved session, its copy and the site client.
|
||||
await using (var bed = await DesktopTestBed.StartAsync(["--sito-di-prova", Site, "--raccolta", "richieste"]))
|
||||
{
|
||||
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
|
||||
Assert.IsNotNull(bed.App.SavedSession);
|
||||
Assert.IsNotNull(bed.App.SiteRequester);
|
||||
Assert.AreEqual(SavedSessionState.None, bed.App.SavedSession.State);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(90_000, CooperativeCancellation = true)]
|
||||
public async Task HoFinitoSavesTheSessionAnnullaDoesNotAndScollegaDeletesIt()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await StartAsync();
|
||||
var app = bed.App;
|
||||
var browser = bed.Browser!;
|
||||
|
||||
// «Annulla» after a login: nothing copied.
|
||||
await BeginAsync(bed);
|
||||
browser.FakeCdp.LoggedIn = true;
|
||||
using (var cancel = await bed.SendAsync(HttpMethod.Post, "/api/connection/cancel"))
|
||||
{
|
||||
Assert.AreEqual(HttpStatusCode.NoContent, cancel.StatusCode);
|
||||
}
|
||||
|
||||
Assert.AreEqual(0, browser.FakeCdp.CaptureReads);
|
||||
Assert.IsNull(app.SavedSession!.Read());
|
||||
|
||||
// «Ho finito» on a page of the site: copied, encrypted on disk, before the page goes to rest.
|
||||
var message = await LoginAsync(bed);
|
||||
StringAssert.Contains(message, "Sessione copiata per le richieste di Febe.");
|
||||
Assert.AreEqual(1, browser.FakeCdp.CaptureReads);
|
||||
var saved = app.SavedSession.Read()!;
|
||||
Assert.AreEqual("sessione-di-prova", saved.Cookie("sessione_prova"));
|
||||
Assert.AreEqual("/api/", saved.Cookies.Single(c => c.Name == "percorso_api").Path);
|
||||
Assert.IsNull(saved.Cookie("sessionid"), "another site's cookie is not copied");
|
||||
Assert.AreEqual(Febe.SitoDiProva.TestSite.EntryNonce, saved.Fields["entry_nonce"]);
|
||||
Assert.AreEqual("about:blank", browser.FakeCdp.Url, "then the page rests, as before");
|
||||
var file = app.Data!.SessionFile;
|
||||
Assert.IsTrue(File.Exists(file));
|
||||
var bytes = File.ReadAllBytes(file);
|
||||
CollectionAssert.AreEqual("FEBS"u8.ToArray(), bytes[..4], "the header of an encrypted session");
|
||||
Assert.AreEqual(-1, System.Text.Encoding.ASCII.GetString(bytes).IndexOf("sessione-di-prova", StringComparison.Ordinal), "no value in clear");
|
||||
Assert.IsFalse(browser.UserIsDriving, "«Ho finito» ends the lease after the copy");
|
||||
|
||||
// «Scollega»: the saved session goes with the profile, from memory and from disk.
|
||||
using (var disconnect = await bed.SendAsync(HttpMethod.Post, "/api/connection/disconnect"))
|
||||
{
|
||||
Assert.AreEqual(HttpStatusCode.NoContent, disconnect.StatusCode);
|
||||
}
|
||||
|
||||
Assert.IsNull(app.SavedSession.Read());
|
||||
Assert.IsFalse(File.Exists(file));
|
||||
Assert.AreEqual(1, browser.EmptiedProfiles);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(60_000, CooperativeCancellation = true)]
|
||||
public async Task ALateHoFinitoAfterTheLeaseEndedDoesNotCopy()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await StartAsync();
|
||||
var browser = bed.Browser!;
|
||||
bed.App.Connection!.DrivingGrace = TimeSpan.FromMilliseconds(300);
|
||||
|
||||
await BeginAsync(bed);
|
||||
browser.FakeCdp.LoggedIn = true;
|
||||
|
||||
// He closes the window without «Ho finito»: the lease ends by itself, 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 + "/");
|
||||
|
||||
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());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(60_000, CooperativeCancellation = true)]
|
||||
public async Task HoFinitoOnAPageThatIsNotTheSiteKeepsTheOldSessionAndSaysSo()
|
||||
{
|
||||
await using var bed = await StartAsync();
|
||||
var browser = bed.Browser!;
|
||||
await LoginAsync(bed);
|
||||
var first = bed.App.SavedSession!.Read()!;
|
||||
|
||||
// «Usa il browser», then «Ho finito» from another site's page.
|
||||
await BeginAsync(bed, openLogin: false);
|
||||
browser.FakeCdp.Navigated("https://altro.example.invalid/pagina");
|
||||
var finish = await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish");
|
||||
var message = finish.GetProperty("message").GetString()!;
|
||||
StringAssert.Contains(message, "non era su una pagina del sito");
|
||||
StringAssert.Contains(message, "premi di nuovo «Ho finito»");
|
||||
Assert.AreSame(first, bed.App.SavedSession.Read(), "a refused copy leaves the saved session as it was");
|
||||
|
||||
// And from the site's page again: a new copy replaces it.
|
||||
await BeginAsync(bed, openLogin: false);
|
||||
browser.FakeCdp.Navigated(Site + "/");
|
||||
await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish");
|
||||
Assert.AreNotEqual(first.Capture, bed.App.SavedSession.Read()!.Capture);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(60_000, CooperativeCancellation = true)]
|
||||
public async Task AFailedDeleteOfTheSavedSessionMakesScollegaReportAPartialFailure()
|
||||
{
|
||||
await using var bed = await StartAsync();
|
||||
await LoginAsync(bed);
|
||||
var file = bed.App.Data!.SessionFile;
|
||||
|
||||
// Something the file system will not delete as a file stands where the session is.
|
||||
File.Delete(file);
|
||||
Directory.CreateDirectory(file);
|
||||
using (var disconnect = await bed.SendAsync(HttpMethod.Post, "/api/connection/disconnect"))
|
||||
{
|
||||
Assert.AreEqual(HttpStatusCode.BadRequest, disconnect.StatusCode);
|
||||
var text = await disconnect.Content.ReadAsStringAsync();
|
||||
StringAssert.Contains(text, "sessione salvata");
|
||||
}
|
||||
|
||||
Assert.IsNull(bed.App.SavedSession!.Read(), "not used any more, whatever the disk did");
|
||||
Assert.AreEqual(1, bed.Browser!.EmptiedProfiles, "the profile is deleted all the same");
|
||||
Directory.Delete(file);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(60_000, CooperativeCancellation = true)]
|
||||
public async Task WithPagineScollegaStillDeletesASessionLeftByARichiesteStartButKeepsTheKey()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await DesktopTestBed.StartAsync(["--sito-di-prova", Site]);
|
||||
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
|
||||
Assert.IsNull(bed.App.SavedSession, "«pagine»: no saved session in this start");
|
||||
StringAssert.Contains(ReadLog(bed), "Raccolta «pagine»", "the log says which route Febe took (§6.0)");
|
||||
|
||||
// What an earlier start with «richieste» left: the encrypted session, a broken write, the key.
|
||||
var data = bed.App.Data!;
|
||||
Directory.CreateDirectory(data.Session);
|
||||
File.WriteAllText(data.SessionFile, "copia-di-prova");
|
||||
var part = data.SessionFile + ".1234abcd" + Febe.Core.Security.OwnerOnlyFiles.PartSuffix;
|
||||
File.WriteAllText(part, "resto");
|
||||
var key = new byte[Febe.Core.Security.SessionKey.Length];
|
||||
File.WriteAllBytes(data.SessionKeyFile, key);
|
||||
|
||||
using (var disconnect = await bed.SendAsync(HttpMethod.Post, "/api/connection/disconnect"))
|
||||
{
|
||||
Assert.AreEqual(HttpStatusCode.NoContent, disconnect.StatusCode);
|
||||
}
|
||||
|
||||
Assert.IsFalse(File.Exists(data.SessionFile), "a session of the disconnected account never comes back at the next «richieste» start");
|
||||
Assert.IsFalse(File.Exists(part));
|
||||
Assert.IsTrue(File.Exists(data.SessionKeyFile), "chiave.bin stays, for the copy of the next login");
|
||||
Assert.AreEqual(1, bed.Browser!.EmptiedProfiles);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(60_000, CooperativeCancellation = true)]
|
||||
public async Task HoFinitoOnAPageMissingAValueTheRequestsNeedSaysTheyStopAsADisconnection()
|
||||
{
|
||||
await using var bed = await StartAsync();
|
||||
var browser = bed.Browser!;
|
||||
|
||||
// The page lacks one module (the nonce of AvvioProva) and the doc_id module.
|
||||
var page = FakeCdp.DefaultPageCapture();
|
||||
((System.Text.Json.Nodes.JsonObject)page["values"]!).Remove("entry_nonce");
|
||||
((System.Text.Json.Nodes.JsonObject)page["docIds"]!).Remove(Febe.SitoDiProva.TestSite.ProfileQuery);
|
||||
browser.FakeCdp.PageCapture = page;
|
||||
|
||||
var message = await LoginAsync(bed);
|
||||
StringAssert.Contains(message, "mancavano 2 valori");
|
||||
StringAssert.Contains(message, "non partono");
|
||||
StringAssert.Contains(message, "disconnessione");
|
||||
StringAssert.Contains(message, "«Usa il browser»");
|
||||
Assert.DoesNotContain("restano al browser", message, "nothing sends those requests back to the browser");
|
||||
var saved = bed.App.SavedSession!.Read()!;
|
||||
Assert.IsFalse(saved.Fields.ContainsKey("entry_nonce"), "missing, never guessed");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void EveryCopyMessageSaysWhatTheCodeDoesNext()
|
||||
{
|
||||
static string For(SessionCopyStatus status, Febe.Browser.Session.CaptureRefusal? refusal = null, int missing = 0, int docIds = 0) =>
|
||||
BrowserConnectionService.CopyMessage(new SessionCopyOutcome(status, refusal, 3, missing, docIds));
|
||||
|
||||
Assert.AreEqual("Sessione copiata per le richieste di Febe.", For(SessionCopyStatus.Saved));
|
||||
foreach (var partial in new[] { For(SessionCopyStatus.Saved, missing: 1, docIds: 1), For(SessionCopyStatus.SavedInMemoryOnly, missing: 2) })
|
||||
{
|
||||
StringAssert.Contains(partial, "mancavano 2 valori");
|
||||
StringAssert.Contains(partial, "ha comunque sostituito quella salvata");
|
||||
StringAssert.Contains(partial, "si ferma come disconnessione");
|
||||
Assert.DoesNotContain("restano al browser", partial);
|
||||
}
|
||||
|
||||
// «Ho finito» always ends the lease: after a refusal the advice is to open the browser again, never «Ho finito» alone.
|
||||
foreach (var refusal in Enum.GetValues<Febe.Browser.Session.CaptureRefusal>())
|
||||
{
|
||||
var refused = For(SessionCopyStatus.Refused, refusal);
|
||||
StringAssert.Contains(refused, "Riapri il browser dalla pagina Collegamento");
|
||||
StringAssert.Contains(refused, "resta com'era");
|
||||
Assert.DoesNotContain("Riprova più tardi con «Ho finito»", refused);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(60_000, CooperativeCancellation = true)]
|
||||
public async Task TheTestSitesAutomaticLoginCopiesTheSessionWhenTheGateIsOn()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
var shell = new FakeDesktopShell { OnCreated = b => b.FakeCdp.LogsInOnVisit = Site };
|
||||
await using var bed = await DesktopTestBed.StartAsync(["--sito-di-prova", Site, "--accesso-di-prova", "--raccolta", "richieste"], shell);
|
||||
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
|
||||
Assert.IsTrue(bed.App.Connection!.IsConnected);
|
||||
Assert.AreEqual(Febe.SitoDiProva.TestSite.Lsd, bed.App.SavedSession!.Read()!.Fields["lsd"]);
|
||||
Assert.IsTrue(File.Exists(bed.App.Data!.SessionFile));
|
||||
Assert.AreEqual("about:blank", bed.Browser!.FakeCdp.Url, "back to rest after the copy");
|
||||
Assert.IsFalse(bed.Browser.UserIsDriving);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The log files of this start, read while Febe still writes them.</summary>
|
||||
private static string ReadLog(DesktopTestBed bed)
|
||||
{
|
||||
var folder = bed.App.Log.Folder;
|
||||
Assert.IsNotNull(folder, "the log has a folder");
|
||||
var text = new System.Text.StringBuilder();
|
||||
foreach (var file in Directory.GetFiles(folder))
|
||||
{
|
||||
using var stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
|
||||
using var reader = new StreamReader(stream);
|
||||
text.Append(reader.ReadToEnd());
|
||||
}
|
||||
|
||||
return text.ToString();
|
||||
}
|
||||
|
||||
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», Alberto logs in on the site's page, «Ho finito». Returns the message.</summary>
|
||||
private static async Task<string> LoginAsync(DesktopTestBed bed)
|
||||
{
|
||||
await BeginAsync(bed);
|
||||
bed.Browser!.FakeCdp.LoggedIn = true;
|
||||
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()!;
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,12 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using Febe.App;
|
||||
using Febe.Browser.Cdp;
|
||||
using Febe.Browser.Hosting;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Security;
|
||||
using Febe.Desktop.Core;
|
||||
using Febe.Web.Native;
|
||||
|
||||
@@ -31,6 +33,11 @@ internal sealed class FakeDesktopShell : IDesktopShell
|
||||
/// <summary>Called with each browser as it is created, before Febe uses it (to set up the fake page).</summary>
|
||||
public Action<FakeBrowser>? OnCreated { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// DPAPI exists only on Windows: here AES-256-GCM, with a key made at run time (never a literal key in the tests).
|
||||
/// </summary>
|
||||
public ISessionProtector SessionProtector { get; } = new AesGcmSessionProtector(RandomNumberGenerator.GetBytes(SessionKey.Length));
|
||||
|
||||
public string? WebView2Version() => RuntimeVersion;
|
||||
|
||||
public IFebeBrowser CreateWebView2Browser(WebView2BrowserSettings settings, FebePlatformContext context)
|
||||
@@ -226,9 +233,44 @@ internal sealed class FakeCdp : ICdpSession
|
||||
{
|
||||
private readonly Lock _gate = new();
|
||||
private readonly Dictionary<string, List<Action<JsonElement>>> _handlers = new(StringComparer.Ordinal);
|
||||
private int _captureReads;
|
||||
private int _cookieReads;
|
||||
|
||||
public bool LoggedIn { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// What the copy of the session (issue #36, S4) reads from this page with its one evaluation (the user agent, the
|
||||
/// values and doc_id of the modules); null: the page answers nothing to it. Low-entropy test values only.
|
||||
/// </summary>
|
||||
public JsonObject? PageCapture { get; set; } = DefaultPageCapture();
|
||||
|
||||
/// <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);
|
||||
|
||||
/// <summary>How many times <c>Network.getCookies</c> was asked.</summary>
|
||||
public int CookieReads => Volatile.Read(ref _cookieReads);
|
||||
|
||||
/// <summary>The values of the test site's page, as the copy would find them.</summary>
|
||||
public static JsonObject DefaultPageCapture() => new()
|
||||
{
|
||||
["ua"] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Finestra di prova",
|
||||
["values"] = new JsonObject
|
||||
{
|
||||
["lsd"] = Febe.SitoDiProva.TestSite.Lsd,
|
||||
["fb_dtsg"] = Febe.SitoDiProva.TestSite.Dtsg,
|
||||
["app_id"] = Febe.SitoDiProva.TestSite.AppId,
|
||||
["account_id"] = "1234",
|
||||
["rev"] = Febe.SitoDiProva.TestSite.Revision,
|
||||
["hs"] = Febe.SitoDiProva.TestSite.HasteSession,
|
||||
["hsi"] = Febe.SitoDiProva.TestSite.HasteSessionId,
|
||||
["dpr"] = Febe.SitoDiProva.TestSite.Dpr,
|
||||
["comet_req"] = Febe.SitoDiProva.TestSite.CometReq,
|
||||
["ccg"] = Febe.SitoDiProva.TestSite.ConnectionClass,
|
||||
["entry_nonce"] = Febe.SitoDiProva.TestSite.EntryNonce,
|
||||
},
|
||||
["docIds"] = new JsonObject { [Febe.SitoDiProva.TestSite.ProfileQuery] = Febe.SitoDiProva.TestSite.DocIds[Febe.SitoDiProva.TestSite.ProfileQuery] },
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Like the test site, which sets its session cookie on any visit: a navigation to an address starting with this
|
||||
/// logs in, and the page reports itself loaded. Null: only the test logs in.
|
||||
@@ -257,8 +299,9 @@ internal sealed class FakeCdp : ICdpSession
|
||||
{
|
||||
"Page.getFrameTree" => new JsonObject { ["frameTree"] = new JsonObject { ["frame"] = new JsonObject { ["id"] = "F1", ["url"] = Url } } },
|
||||
"Page.navigate" => Navigate(parameters),
|
||||
// The session cookie of Instagram, and the test site's one.
|
||||
"Network.getCookies" => new JsonObject { ["cookies"] = LoggedIn ? new JsonArray(new JsonObject { ["name"] = "sessionid" }, new JsonObject { ["name"] = "sessione_prova" }) : new JsonArray() },
|
||||
// The session cookie of Instagram, and the test site's ones (with the values and places the copy keeps).
|
||||
"Network.getCookies" => Cookies(),
|
||||
"Runtime.evaluate" when IsCapture(parameters) => Capture(),
|
||||
"Runtime.evaluate" when LogsInOnVisit is not null => new JsonObject { ["result"] = new JsonObject { ["type"] = "string", ["value"] = "complete" } },
|
||||
_ => new JsonObject(),
|
||||
};
|
||||
@@ -286,6 +329,48 @@ internal sealed class FakeCdp : ICdpSession
|
||||
});
|
||||
}
|
||||
|
||||
private static bool IsCapture(object? parameters) =>
|
||||
(parameters as JsonObject)?["expression"]?.GetValue<string>() is { } expression
|
||||
&& expression.Contains("navigator.userAgent", StringComparison.Ordinal);
|
||||
|
||||
private JsonObject Cookies()
|
||||
{
|
||||
Interlocked.Increment(ref _cookieReads);
|
||||
if (!LoggedIn)
|
||||
{
|
||||
return new JsonObject { ["cookies"] = new JsonArray() };
|
||||
}
|
||||
|
||||
static JsonObject Cookie(string name, string value, string domain, string path = "/") => new()
|
||||
{
|
||||
["name"] = name,
|
||||
["value"] = value,
|
||||
["domain"] = domain,
|
||||
["path"] = path,
|
||||
["expires"] = -1,
|
||||
["session"] = true,
|
||||
["secure"] = false,
|
||||
["httpOnly"] = true,
|
||||
};
|
||||
|
||||
return new JsonObject
|
||||
{
|
||||
["cookies"] = new JsonArray(
|
||||
Cookie("sessionid", "sessione-di-prova", ".instagram.com"),
|
||||
Cookie("sessione_prova", "sessione-di-prova", "127.0.0.1"),
|
||||
Cookie("csrftoken", "csrf-di-prova", "127.0.0.1"),
|
||||
Cookie("percorso_api", "solo-sotto-api", "127.0.0.1", "/api/")),
|
||||
};
|
||||
}
|
||||
|
||||
private JsonObject Capture()
|
||||
{
|
||||
Interlocked.Increment(ref _captureReads);
|
||||
return PageCapture is { } page
|
||||
? new JsonObject { ["result"] = new JsonObject { ["type"] = "object", ["value"] = JsonNode.Parse(page.ToJsonString()) } }
|
||||
: new JsonObject();
|
||||
}
|
||||
|
||||
private JsonObject Navigate(object? parameters)
|
||||
{
|
||||
var url = (parameters as JsonObject)?["url"]?.GetValue<string>();
|
||||
|
||||
Reference in new issue
Block a user