Files
Febe/tests/Febe.Tests/Desktop/Support/FakeDesktopShell.cs
T
Alby96andClaude Opus 5.5 883ea4683c 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>
2026-11-18 11:41:35 +01:00

447 lines
15 KiB
C#

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;
namespace Febe.Tests.Desktop.Support;
/// <summary>The Windows-only part of the desktop, faked: what the platform asks of it is recorded.</summary>
internal sealed class FakeDesktopShell : IDesktopShell
{
public FakeNativeShell NativeShell { get; } = new();
public INativeShell Native => NativeShell;
/// <summary>The WebView2 runtime this «Windows» has (null: missing).</summary>
public string? RuntimeVersion { get; set; } = "141.0.3537.71";
/// <summary>Where «Edge» is (null: not installed).</summary>
public string? EdgePath { get; set; }
/// <summary>The browsers created, with the settings the platform gave them.</summary>
public ConcurrentQueue<(WebView2BrowserSettings Settings, FakeBrowser Browser)> Created { get; } = new();
public ConcurrentQueue<string> ProcessWindows { get; } = new();
/// <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)
{
var browser = new FakeBrowser(settings.ProfileDirectory, settings.Width, settings.Height, context);
OnCreated?.Invoke(browser);
Created.Enqueue((settings, browser));
return browser;
}
public string? FindEdge() => EdgePath;
public Task ShowProcessWindowAsync(int processId, CancellationToken ct)
{
ProcessWindows.Enqueue("mostra " + processId);
return Task.CompletedTask;
}
public Task HideProcessWindowAsync(int processId, CancellationToken ct)
{
ProcessWindows.Enqueue("nascondi " + processId);
return Task.CompletedTask;
}
/// <summary>The processes the platform asked to tie to Febe's life (Edge), by id.</summary>
public ConcurrentQueue<int> TiedToFebe { get; } = new();
/// <summary>What «Windows» answers when a process is tied to Febe.</summary>
public bool TieSucceeds { get; set; } = true;
public bool EndWithFebe(System.Diagnostics.Process process)
{
TiedToFebe.Enqueue(process.Id);
return TieSucceeds;
}
}
/// <summary>Folder picker, explorer, default browser, notifications (the Windows alerts) and autostart, faked.</summary>
internal sealed class FakeNativeShell : INativeShell
{
public bool CanPickFolder => true;
public bool CanShowInFolder => true;
public bool CanOpenUrl => true;
public bool CanNotify => true;
public bool SupportsAutostart => true;
public bool Autostart { get; private set; }
public string? FolderToPick { get; set; }
public ConcurrentQueue<string> Shown { get; } = new();
public ConcurrentQueue<Uri> Opened { get; } = new();
public ConcurrentQueue<(string Title, string Message)> Notified { get; } = new();
public Task<string?> PickFolderAsync(string title, string? initialFolder, CancellationToken ct) => Task.FromResult(FolderToPick);
public Task<bool> ShowInFolderAsync(string fullPath, CancellationToken ct)
{
Shown.Enqueue(fullPath);
return Task.FromResult(true);
}
public Task<bool> OpenUrlAsync(Uri address, CancellationToken ct)
{
Opened.Enqueue(address);
return Task.FromResult(true);
}
public Task NotifyAsync(string title, string message, CancellationToken ct)
{
Notified.Enqueue((title, message));
return Task.CompletedTask;
}
public Task<bool> GetAutostartAsync(CancellationToken ct) => Task.FromResult(Autostart);
public Task SetAutostartAsync(bool enabled, CancellationToken ct)
{
Autostart = enabled;
return Task.CompletedTask;
}
}
/// <summary>
/// The window «Browser di Febe», faked: a CDP session that answers like a browser on a blank page, a session cookie
/// that exists once «Alberto» has logged in, and a record of every time the window came to the front or went away.
/// </summary>
internal sealed class FakeBrowser : IFebeBrowser
{
private readonly FebePlatformContext _context;
private IDisposable? _lease;
public FakeBrowser(string profileDirectory, int width, int height, FebePlatformContext context)
{
ProfileDirectory = profileDirectory;
WindowWidth = width;
WindowHeight = height;
_context = context;
}
public FakeCdp FakeCdp { get; } = new();
public ICdpSession Cdp => FakeCdp;
public UserDrivingGate UserDriving { get; } = new();
public bool UserIsDriving => UserDriving.IsDriving;
public bool IsAvailable { get; private set; }
public string? LastError => null;
public string ProfileDirectory { get; }
public int WindowWidth { get; }
public int WindowHeight { get; }
public int Shown { get; private set; }
public int Hidden { get; private set; }
public int EmptiedProfiles { get; private set; }
public bool Disposed { get; private set; }
public Task RunAsync(CancellationToken ct)
{
Directory.CreateDirectory(ProfileDirectory);
IsAvailable = true;
return Task.CompletedTask;
}
public Task<NavigationResult> RestAsync(CancellationToken ct) => FakeCdp.NavigateAsync(CdpPageExtensions.RestUrl, ct);
/// <summary>Like the real window: in front, Alberto is driving.</summary>
public Task ShowToUserAsync(CancellationToken ct)
{
Shown++;
_lease ??= UserDriving.Begin();
_context.Tracker.MarkUsed(_context.Clock.Now);
return Task.CompletedTask;
}
public Task HideFromUserAsync(CancellationToken ct)
{
Hidden++;
_lease?.Dispose();
_lease = null;
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; }
public Task RestartWithEmptyProfileAsync(CancellationToken ct)
{
if (ProfileLocked)
{
throw new IOException("Il file Cookies è in uso da un altro processo.");
}
if (Directory.Exists(ProfileDirectory))
{
Directory.Delete(ProfileDirectory, recursive: true);
}
Directory.CreateDirectory(ProfileDirectory);
FakeCdp.LoggedIn = false;
EmptiedProfiles++;
return Task.CompletedTask;
}
public ValueTask DisposeAsync()
{
Disposed = true;
IsAvailable = false;
return ValueTask.CompletedTask;
}
}
/// <summary>
/// A CDP session answering like a page: frame tree, navigation (with its <c>Page.frameNavigated</c> event, as the
/// collection pipeline hears it), the session cookie (name only).
/// </summary>
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>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);
/// <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,
["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] },
};
/// <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.
/// </summary>
public string? LogsInOnVisit { get; set; }
public string Url { get; private set; } = "about:blank";
public ConcurrentQueue<string> Methods { get; } = new();
/// <summary>Every address a <c>Page.navigate</c> asked for, in order.</summary>
public ConcurrentQueue<string> Visited { get; } = new();
/// <summary>The main frame moved to <paramref name="url"/> by itself (a redirect of the site), not by a command.</summary>
public void Navigated(string url)
{
Url = url;
Raise("Page.frameNavigated", new JsonObject { ["frame"] = new JsonObject { ["id"] = "F1", ["url"] = url } });
}
public Task<JsonElement> SendAsync(string method, object? parameters = null, CancellationToken ct = default)
{
CdpCommandPolicy.EnsureAllowed(method);
Methods.Enqueue(method);
JsonNode result = method switch
{
"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 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(),
};
return Task.FromResult(JsonDocument.Parse(result.ToJsonString()).RootElement.Clone());
}
public IDisposable On(string eventName, Action<JsonElement> handler)
{
lock (_gate)
{
if (!_handlers.TryGetValue(eventName, out var list))
{
_handlers[eventName] = list = [];
}
list.Add(handler);
}
return new Removal(() =>
{
lock (_gate)
{
_handlers[eventName].Remove(handler);
}
});
}
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);
OnCapture?.Invoke();
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>();
if (url is not null)
{
Visited.Enqueue(url);
if (LogsInOnVisit is { } site && url.StartsWith(site, StringComparison.Ordinal))
{
LoggedIn = true;
}
Navigated(url);
}
return new JsonObject { ["frameId"] = "F1" };
}
private void Raise(string eventName, JsonObject parameters)
{
Action<JsonElement>[] handlers;
lock (_gate)
{
handlers = _handlers.TryGetValue(eventName, out var list) ? [.. list] : [];
}
var element = JsonDocument.Parse(parameters.ToJsonString()).RootElement.Clone();
foreach (var handler in handlers)
{
handler(element);
}
}
private sealed class Removal(Action remove) : IDisposable
{
private Action? _remove = remove;
public void Dispose() => Interlocked.Exchange(ref _remove, null)?.Invoke();
}
}