Strato browser (M0/M2): client CDP con elenco dei comandi ammessi, ChromiumProcessHost e Xvfb sorvegliati, gesti umani, mappa dei bersagli, cattura delle risposte, segnali di arresto, scaricamento dal browser, vista remota, distribuzioni del ritmo; prove unitarie e d'insieme con Chromium su Xvfb; esito locale di S5 e S6
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
44 files changed
+8396
No files matched your search
@@ -0,0 +1,431 @@
|
||||
using System.Buffers;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Net.WebSockets;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using Febe.Browser.Diagnostics;
|
||||
using Febe.Core.Abstractions;
|
||||
|
||||
namespace Febe.Browser.Cdp;
|
||||
|
||||
/// <summary>Options of <see cref="CdpClient"/>.</summary>
|
||||
/// <param name="CommandTimeout">How long to wait for the answer to a command before giving up.</param>
|
||||
public sealed record CdpClientOptions(TimeSpan? CommandTimeout = null)
|
||||
{
|
||||
public static CdpClientOptions Default { get; } = new();
|
||||
|
||||
internal TimeSpan EffectiveTimeout => CommandTimeout ?? TimeSpan.FromSeconds(60);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Chrome DevTools Protocol client over a WebSocket (spec §5, §6.1), written by hand on <see cref="ClientWebSocket"/>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <list type="bullet">
|
||||
/// <item>Only commands of <see cref="CdpCommandPolicy"/> are sent; <c>Runtime.evaluate</c> also passes <see cref="ReadOnlyScriptGuard"/>.</item>
|
||||
/// <item>The log receives command names only: never parameters, results or event payloads.</item>
|
||||
/// <item>Event handlers run on the receive loop: they must be quick and must never wait for a command
|
||||
/// (queue the work instead), or the loop stops.</item>
|
||||
/// <item>When the connection drops every pending command fails with <see cref="CdpDisconnectedException"/>;
|
||||
/// a new client is needed (see <see cref="ReconnectingCdpSession"/>). Disposal is idempotent.</item>
|
||||
/// </list>
|
||||
/// </remarks>
|
||||
public sealed class CdpClient : ICdpSession, IAsyncDisposable
|
||||
{
|
||||
private const int ReceiveChunk = 64 * 1024;
|
||||
private const int MaxRetainedBuffer = 4 * 1024 * 1024;
|
||||
|
||||
private static readonly JsonSerializerOptions ParameterOptions = new(JsonSerializerDefaults.Web)
|
||||
{
|
||||
DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull,
|
||||
};
|
||||
|
||||
private readonly WebSocket _socket;
|
||||
private readonly IBrowserLog _log;
|
||||
private readonly CdpClientOptions _options;
|
||||
private readonly ConcurrentDictionary<int, Pending> _pending = new();
|
||||
private readonly Dictionary<string, List<Action<JsonElement>>> _handlers = new(StringComparer.Ordinal);
|
||||
private readonly Lock _handlersGate = new();
|
||||
private readonly SemaphoreSlim _sendLock = new(1, 1);
|
||||
private readonly CancellationTokenSource _lifetime = new();
|
||||
private readonly Task _receiveLoop;
|
||||
private int _nextId;
|
||||
private int _disposed;
|
||||
private int _closed;
|
||||
private Exception? _closeReason;
|
||||
|
||||
internal CdpClient(WebSocket socket, IBrowserLog? log = null, CdpClientOptions? options = null)
|
||||
{
|
||||
_socket = socket ?? throw new ArgumentNullException(nameof(socket));
|
||||
_log = log ?? NullBrowserLog.Instance;
|
||||
_options = options ?? CdpClientOptions.Default;
|
||||
_receiveLoop = Task.Run(ReceiveLoopAsync);
|
||||
}
|
||||
|
||||
/// <summary>True until the connection closes or the client is disposed.</summary>
|
||||
public bool IsConnected => Volatile.Read(ref _closed) == 0;
|
||||
|
||||
/// <summary>Raised once when the connection closes (the argument is the cause, null for a normal close).</summary>
|
||||
public event EventHandler<Exception?>? Disconnected;
|
||||
|
||||
/// <summary>Connects to a DevTools WebSocket on the loopback interface (never through a proxy).</summary>
|
||||
public static async Task<CdpClient> ConnectAsync(Uri webSocketUrl, IBrowserLog? log = null, CdpClientOptions? options = null, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(webSocketUrl);
|
||||
CdpTargetDiscovery.EnsureLoopback(webSocketUrl);
|
||||
|
||||
var socket = new ClientWebSocket();
|
||||
socket.Options.Proxy = null;
|
||||
socket.Options.KeepAliveInterval = TimeSpan.FromSeconds(20);
|
||||
try
|
||||
{
|
||||
using var connectTimeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
connectTimeout.CancelAfter(TimeSpan.FromSeconds(10));
|
||||
await socket.ConnectAsync(webSocketUrl, connectTimeout.Token).ConfigureAwait(false);
|
||||
}
|
||||
catch
|
||||
{
|
||||
socket.Dispose();
|
||||
throw;
|
||||
}
|
||||
|
||||
(log ?? NullBrowserLog.Instance).Debug("CDP: collegamento aperto.");
|
||||
return new CdpClient(socket, log, options);
|
||||
}
|
||||
|
||||
public async Task<JsonElement> SendAsync(string method, object? parameters = null, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrEmpty(method);
|
||||
CdpCommandPolicy.EnsureAllowed(method);
|
||||
var node = CdpParameters.ToNode(parameters, ParameterOptions);
|
||||
if (method == "Runtime.evaluate")
|
||||
{
|
||||
ReadOnlyScriptGuard.EnsureReadOnly(CdpParameters.GetString(node, "expression"));
|
||||
}
|
||||
|
||||
ThrowIfClosed();
|
||||
|
||||
var id = Interlocked.Increment(ref _nextId);
|
||||
var pending = new Pending(method, new TaskCompletionSource<JsonElement>(TaskCreationOptions.RunContinuationsAsynchronously));
|
||||
_pending[id] = pending;
|
||||
try
|
||||
{
|
||||
var payload = Serialize(id, method, node);
|
||||
using (var lockWait = CancellationTokenSource.CreateLinkedTokenSource(ct, _lifetime.Token))
|
||||
{
|
||||
await _sendLock.WaitAsync(lockWait.Token).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
ThrowIfClosed();
|
||||
|
||||
// Never pass the caller's token to the socket: cancelling a send aborts the whole connection.
|
||||
await _socket.SendAsync(payload, WebSocketMessageType.Text, endOfMessage: true, _lifetime.Token).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_sendLock.Release();
|
||||
}
|
||||
|
||||
_log.Debug($"CDP → {method}");
|
||||
|
||||
using var wait = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
wait.CancelAfter(_options.EffectiveTimeout);
|
||||
try
|
||||
{
|
||||
return await pending.Completion.Task.WaitAsync(wait.Token).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
|
||||
{
|
||||
ThrowIfClosed();
|
||||
throw new TimeoutException($"Il browser non ha risposto al comando «{method}» entro {_options.EffectiveTimeout.TotalSeconds:0} s.");
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is WebSocketException or ObjectDisposedException || (ex is OperationCanceledException && _lifetime.IsCancellationRequested && !ct.IsCancellationRequested))
|
||||
{
|
||||
throw new CdpDisconnectedException("Il collegamento con il browser si è chiuso durante il comando.", ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_pending.TryRemove(id, out _);
|
||||
}
|
||||
}
|
||||
|
||||
public IDisposable On(string eventName, Action<JsonElement> handler)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrEmpty(eventName);
|
||||
ArgumentNullException.ThrowIfNull(handler);
|
||||
lock (_handlersGate)
|
||||
{
|
||||
if (!_handlers.TryGetValue(eventName, out var list))
|
||||
{
|
||||
list = [];
|
||||
_handlers[eventName] = list;
|
||||
}
|
||||
|
||||
list.Add(handler);
|
||||
}
|
||||
|
||||
return new Subscription(() =>
|
||||
{
|
||||
lock (_handlersGate)
|
||||
{
|
||||
if (_handlers.TryGetValue(eventName, out var list))
|
||||
{
|
||||
list.Remove(handler);
|
||||
if (list.Count == 0)
|
||||
{
|
||||
_handlers.Remove(eventName);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _disposed, 1) == 1)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (_socket.State == WebSocketState.Open)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var closeTimeout = new CancellationTokenSource(TimeSpan.FromSeconds(1));
|
||||
await _socket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, null, closeTimeout.Token).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is WebSocketException or OperationCanceledException or ObjectDisposedException)
|
||||
{
|
||||
// The browser may already be gone.
|
||||
}
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await _receiveLoop.WaitAsync(TimeSpan.FromSeconds(1)).ConfigureAwait(false);
|
||||
}
|
||||
catch (TimeoutException)
|
||||
{
|
||||
// Fall through: cancelling aborts the receive.
|
||||
}
|
||||
|
||||
await _lifetime.CancelAsync().ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
await _receiveLoop.ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is OperationCanceledException or WebSocketException)
|
||||
{
|
||||
}
|
||||
|
||||
MarkClosed(null);
|
||||
_socket.Dispose();
|
||||
|
||||
// _sendLock and _lifetime are deliberately not disposed: a concurrent SendAsync may still touch them,
|
||||
// and neither holds unmanaged resources (no wait handle, no timer).
|
||||
}
|
||||
|
||||
private async Task ReceiveLoopAsync()
|
||||
{
|
||||
var buffer = new ArrayBufferWriter<byte>(ReceiveChunk);
|
||||
Exception? failure = null;
|
||||
try
|
||||
{
|
||||
while (!_lifetime.IsCancellationRequested)
|
||||
{
|
||||
buffer.ResetWrittenCount();
|
||||
ValueWebSocketReceiveResult result;
|
||||
do
|
||||
{
|
||||
result = await _socket.ReceiveAsync(buffer.GetMemory(ReceiveChunk), _lifetime.Token).ConfigureAwait(false);
|
||||
if (result.MessageType == WebSocketMessageType.Close)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
buffer.Advance(result.Count);
|
||||
}
|
||||
while (!result.EndOfMessage);
|
||||
|
||||
Dispatch(buffer.WrittenSpan);
|
||||
|
||||
if (buffer.Capacity > MaxRetainedBuffer)
|
||||
{
|
||||
buffer = new ArrayBufferWriter<byte>(ReceiveChunk);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (_lifetime.IsCancellationRequested)
|
||||
{
|
||||
}
|
||||
catch (Exception ex) when (ex is WebSocketException or ObjectDisposedException or InvalidOperationException)
|
||||
{
|
||||
failure = ex;
|
||||
}
|
||||
finally
|
||||
{
|
||||
MarkClosed(failure);
|
||||
}
|
||||
}
|
||||
|
||||
private void Dispatch(ReadOnlySpan<byte> message)
|
||||
{
|
||||
JsonElement root;
|
||||
try
|
||||
{
|
||||
// ParseValue yields a self-contained element (no JsonDocument to dispose) and needs no serializer,
|
||||
// so it also works where reflection-based serialization is disabled (trimmed or AOT builds).
|
||||
var reader = new Utf8JsonReader(message);
|
||||
root = JsonElement.ParseValue(ref reader);
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
_log.Warn("CDP: messaggio non leggibile ricevuto dal browser.", ex);
|
||||
return;
|
||||
}
|
||||
|
||||
if (root.ValueKind != JsonValueKind.Object)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (root.TryGetProperty("id", out var idElement) && idElement.TryGetInt32(out var id))
|
||||
{
|
||||
if (!_pending.TryGetValue(id, out var pending))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (root.TryGetProperty("error", out var error))
|
||||
{
|
||||
var code = error.TryGetProperty("code", out var c) && c.TryGetInt32(out var ci) ? ci : 0;
|
||||
var text = error.TryGetProperty("message", out var m) ? m.GetString() ?? string.Empty : string.Empty;
|
||||
_log.Debug($"CDP ✗ {pending.Method} (codice {code})");
|
||||
pending.Completion.TrySetException(new CdpCommandException(pending.Method, code, text));
|
||||
}
|
||||
else
|
||||
{
|
||||
pending.Completion.TrySetResult(root.TryGetProperty("result", out var result) ? result : default);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (root.TryGetProperty("method", out var methodElement) && methodElement.GetString() is { } eventName)
|
||||
{
|
||||
Action<JsonElement>[] handlers;
|
||||
lock (_handlersGate)
|
||||
{
|
||||
if (!_handlers.TryGetValue(eventName, out var list) || list.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
handlers = [.. list];
|
||||
}
|
||||
|
||||
var parameters = root.TryGetProperty("params", out var p) ? p : default;
|
||||
foreach (var handler in handlers)
|
||||
{
|
||||
try
|
||||
{
|
||||
handler(parameters);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.Warn($"CDP: errore nel gestore dell'evento {eventName}.", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void MarkClosed(Exception? reason)
|
||||
{
|
||||
if (Interlocked.Exchange(ref _closed, 1) == 1)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_closeReason = reason;
|
||||
var disconnected = new CdpDisconnectedException("Il collegamento con il browser si è chiuso.", reason);
|
||||
foreach (var (_, pending) in _pending)
|
||||
{
|
||||
pending.Completion.TrySetException(disconnected);
|
||||
}
|
||||
|
||||
if (Volatile.Read(ref _disposed) == 0)
|
||||
{
|
||||
_log.Info("CDP: il browser ha chiuso il collegamento.");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
Disconnected?.Invoke(this, reason);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.Warn("CDP: errore nel gestore della disconnessione.", ex);
|
||||
}
|
||||
}
|
||||
|
||||
private void ThrowIfClosed()
|
||||
{
|
||||
if (Volatile.Read(ref _closed) == 1 || Volatile.Read(ref _disposed) == 1)
|
||||
{
|
||||
throw new CdpDisconnectedException("Il collegamento con il browser è chiuso.", _closeReason);
|
||||
}
|
||||
}
|
||||
|
||||
private static ReadOnlyMemory<byte> Serialize(int id, string method, JsonNode? parameters)
|
||||
{
|
||||
var output = new ArrayBufferWriter<byte>(256);
|
||||
using (var writer = new Utf8JsonWriter(output))
|
||||
{
|
||||
writer.WriteStartObject();
|
||||
writer.WriteNumber("id", id);
|
||||
writer.WriteString("method", method);
|
||||
if (parameters is not null)
|
||||
{
|
||||
writer.WritePropertyName("params");
|
||||
parameters.WriteTo(writer);
|
||||
}
|
||||
|
||||
writer.WriteEndObject();
|
||||
}
|
||||
|
||||
return output.WrittenMemory;
|
||||
}
|
||||
|
||||
private sealed record Pending(string Method, TaskCompletionSource<JsonElement> Completion);
|
||||
}
|
||||
|
||||
/// <summary>Disposable that runs an action once.</summary>
|
||||
internal sealed class Subscription(Action dispose) : IDisposable
|
||||
{
|
||||
private Action? _dispose = dispose;
|
||||
|
||||
public void Dispose() => Interlocked.Exchange(ref _dispose, null)?.Invoke();
|
||||
}
|
||||
|
||||
/// <summary>Converts command parameters (anonymous objects, dictionaries, JSON nodes or elements) to JSON.</summary>
|
||||
internal static class CdpParameters
|
||||
{
|
||||
public static JsonNode? ToNode(object? parameters, JsonSerializerOptions options) => parameters switch
|
||||
{
|
||||
null => null,
|
||||
JsonNode node => node,
|
||||
JsonElement { ValueKind: JsonValueKind.Undefined or JsonValueKind.Null } => null,
|
||||
JsonElement element => JsonNode.Parse(element.GetRawText()),
|
||||
_ when !JsonSerializer.IsReflectionEnabledByDefault => throw new NotSupportedException(
|
||||
"Senza serializzazione per riflessione i parametri CDP vanno passati come JsonObject."),
|
||||
_ => JsonSerializer.SerializeToNode(parameters, parameters.GetType(), options),
|
||||
};
|
||||
|
||||
public static string? GetString(JsonNode? node, string property) =>
|
||||
node is JsonObject obj && obj.TryGetPropertyValue(property, out var value) && value is JsonValue v && v.TryGetValue<string>(out var s)
|
||||
? s
|
||||
: null;
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
using System.Collections.Frozen;
|
||||
|
||||
namespace Febe.Browser.Cdp;
|
||||
|
||||
/// <summary>
|
||||
/// The CDP commands Febe may send (spec §6.1). Everything else is refused before it reaches the browser.
|
||||
/// Adding a command requires a line in docs/decisioni.md with the reason.
|
||||
/// </summary>
|
||||
public static class CdpCommandPolicy
|
||||
{
|
||||
/// <summary>The allowlist of spec §6.1, grouped by purpose.</summary>
|
||||
public static FrozenSet<string> Allowed { get; } = FrozenSet.Create(
|
||||
StringComparer.Ordinal,
|
||||
// Navigate and read the state (Runtime.evaluate read-only only, see ReadOnlyScriptGuard).
|
||||
"Page.enable",
|
||||
"Page.navigate",
|
||||
"Page.getFrameTree",
|
||||
"Runtime.evaluate",
|
||||
// Capture responses.
|
||||
"Network.enable",
|
||||
"Network.getResponseBody",
|
||||
// Gestures.
|
||||
"Input.dispatchMouseEvent",
|
||||
"Input.dispatchKeyEvent",
|
||||
// Download files.
|
||||
"Network.loadNetworkResource",
|
||||
"IO.read",
|
||||
"IO.close",
|
||||
// Remote view and preview.
|
||||
"Page.startScreencast",
|
||||
"Page.screencastFrameAck",
|
||||
"Page.stopScreencast",
|
||||
"Page.captureScreenshot",
|
||||
// Check the session: existence of the session cookie only.
|
||||
"Network.getCookies");
|
||||
|
||||
/// <summary>Commands explicitly forbidden by spec §2 rule 2 and §6.1, refused with a specific message.</summary>
|
||||
public static FrozenSet<string> ForbiddenCommands { get; } = FrozenSet.Create(
|
||||
StringComparer.Ordinal,
|
||||
"Network.setUserAgentOverride",
|
||||
"Network.setExtraHTTPHeaders",
|
||||
"Page.addScriptToEvaluateOnNewDocument");
|
||||
|
||||
/// <summary>Whole domains that are forbidden (spec §6.1).</summary>
|
||||
public static IReadOnlyList<string> ForbiddenDomains { get; } = ["Emulation", "Fetch"];
|
||||
|
||||
public static bool IsAllowed(string method) => method is not null && Allowed.Contains(method);
|
||||
|
||||
public static bool IsExplicitlyForbidden(string method)
|
||||
{
|
||||
if (string.IsNullOrEmpty(method))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (ForbiddenCommands.Contains(method))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
var dot = method.IndexOf('.', StringComparison.Ordinal);
|
||||
var domain = dot < 0 ? method : method[..dot];
|
||||
return ForbiddenDomains.Contains(domain, StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>Throws <see cref="CdpCommandNotAllowedException"/> unless <paramref name="method"/> is on the allowlist.</summary>
|
||||
public static void EnsureAllowed(string method)
|
||||
{
|
||||
if (IsExplicitlyForbidden(method))
|
||||
{
|
||||
throw new CdpCommandNotAllowedException(
|
||||
method,
|
||||
$"Il comando CDP «{method}» è vietato: altera ciò che il browser dichiara o le richieste che invia (specifica §2, regola 2; §6.1).");
|
||||
}
|
||||
|
||||
if (!IsAllowed(method))
|
||||
{
|
||||
throw new CdpCommandNotAllowedException(
|
||||
method,
|
||||
$"Il comando CDP «{method}» non è nell'elenco dei comandi ammessi (specifica §6.1). Ogni aggiunta va motivata in docs/decisioni.md.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A CDP command was refused by <see cref="CdpCommandPolicy"/> and never sent.</summary>
|
||||
public sealed class CdpCommandNotAllowedException(string method, string message) : InvalidOperationException(message)
|
||||
{
|
||||
public string Method { get; } = method;
|
||||
}
|
||||
|
||||
/// <summary>The browser answered a command with an error. The message never contains parameters.</summary>
|
||||
public sealed class CdpCommandException(string method, int code, string browserMessage)
|
||||
: Exception($"Il comando CDP «{method}» è fallito: {browserMessage} (codice {code}).")
|
||||
{
|
||||
public string Method { get; } = method;
|
||||
|
||||
public int Code { get; } = code;
|
||||
|
||||
public string BrowserMessage { get; } = browserMessage;
|
||||
}
|
||||
|
||||
/// <summary>The connection to the browser is closed (browser exited, crashed or is restarting).</summary>
|
||||
public sealed class CdpDisconnectedException : Exception
|
||||
{
|
||||
public CdpDisconnectedException()
|
||||
: base("Il collegamento con il browser è chiuso.")
|
||||
{
|
||||
}
|
||||
|
||||
public CdpDisconnectedException(string message)
|
||||
: base(message)
|
||||
{
|
||||
}
|
||||
|
||||
public CdpDisconnectedException(string message, Exception? inner)
|
||||
: base(message, inner)
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using Febe.Core.Abstractions;
|
||||
|
||||
namespace Febe.Browser.Cdp;
|
||||
|
||||
/// <summary>A read-only evaluation threw inside the page.</summary>
|
||||
public sealed class CdpEvaluationException(string message) : Exception(message);
|
||||
|
||||
/// <summary>Result of <c>Page.navigate</c>.</summary>
|
||||
/// <param name="FrameId">Frame that navigated.</param>
|
||||
/// <param name="ErrorText">Browser error (e.g. «net::ERR_CONNECTION_REFUSED»), null on success.</param>
|
||||
public sealed record NavigationResult(string FrameId, string? ErrorText)
|
||||
{
|
||||
public bool Succeeded => ErrorText is null;
|
||||
}
|
||||
|
||||
/// <summary>Page-level helpers built only on the commands of spec §6.1.</summary>
|
||||
public static class CdpPageExtensions
|
||||
{
|
||||
/// <summary>The «rest» page (spec §6.1): no site page stays open outside a session.</summary>
|
||||
public const string RestUrl = "about:blank";
|
||||
|
||||
/// <summary>
|
||||
/// Evaluates a read-only expression and returns its value (by value). The expression passes
|
||||
/// <see cref="ReadOnlyScriptGuard"/> in the client. Exceptions in the page become <see cref="CdpEvaluationException"/>.
|
||||
/// </summary>
|
||||
public static async Task<JsonElement> EvaluateAsync(this ICdpSession cdp, string expression, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(cdp);
|
||||
var result = await cdp.SendAsync(
|
||||
"Runtime.evaluate",
|
||||
new JsonObject
|
||||
{
|
||||
["expression"] = expression,
|
||||
["returnByValue"] = true,
|
||||
["awaitPromise"] = false,
|
||||
["silent"] = true,
|
||||
},
|
||||
ct).ConfigureAwait(false);
|
||||
|
||||
if (result.ValueKind == JsonValueKind.Object && result.TryGetProperty("exceptionDetails", out var details))
|
||||
{
|
||||
var text = details.TryGetProperty("exception", out var ex) && ex.TryGetProperty("description", out var d)
|
||||
? d.GetString()
|
||||
: details.TryGetProperty("text", out var t) ? t.GetString() : null;
|
||||
var firstLine = (text ?? "errore sconosciuto").Split('\n')[0];
|
||||
throw new CdpEvaluationException($"Lettura della pagina fallita: {(firstLine.Length > 200 ? firstLine[..200] : firstLine)}");
|
||||
}
|
||||
|
||||
return result.ValueKind == JsonValueKind.Object
|
||||
&& result.TryGetProperty("result", out var remote)
|
||||
&& remote.TryGetProperty("value", out var value)
|
||||
? value
|
||||
: default;
|
||||
}
|
||||
|
||||
/// <summary>Identifier of the main frame (needed by <c>Network.loadNetworkResource</c>).</summary>
|
||||
public static async Task<string> GetMainFrameIdAsync(this ICdpSession cdp, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(cdp);
|
||||
var tree = await cdp.SendAsync("Page.getFrameTree", null, ct).ConfigureAwait(false);
|
||||
return tree.GetProperty("frameTree").GetProperty("frame").GetProperty("id").GetString()
|
||||
?? throw new InvalidOperationException("Il browser non ha indicato il frame principale.");
|
||||
}
|
||||
|
||||
/// <summary>Address of the main frame (may contain data: never log it unsanitized).</summary>
|
||||
public static async Task<string> GetMainFrameUrlAsync(this ICdpSession cdp, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(cdp);
|
||||
var tree = await cdp.SendAsync("Page.getFrameTree", null, ct).ConfigureAwait(false);
|
||||
return tree.GetProperty("frameTree").GetProperty("frame").GetProperty("url").GetString() ?? string.Empty;
|
||||
}
|
||||
|
||||
/// <summary><c>Page.navigate</c>. Returns when the navigation commits (not when the page has finished loading).</summary>
|
||||
public static async Task<NavigationResult> NavigateAsync(this ICdpSession cdp, string url, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(cdp);
|
||||
ArgumentException.ThrowIfNullOrEmpty(url);
|
||||
var result = await cdp.SendAsync("Page.navigate", new JsonObject { ["url"] = url }, ct).ConfigureAwait(false);
|
||||
var frameId = result.TryGetProperty("frameId", out var f) ? f.GetString() ?? string.Empty : string.Empty;
|
||||
var error = result.TryGetProperty("errorText", out var e) ? e.GetString() : null;
|
||||
return new NavigationResult(frameId, string.IsNullOrEmpty(error) ? null : error);
|
||||
}
|
||||
|
||||
/// <summary>Puts the browser at rest on the blank page (spec §6.1, §7.2).</summary>
|
||||
public static Task<NavigationResult> RestAsync(this ICdpSession cdp, CancellationToken ct = default) =>
|
||||
cdp.NavigateAsync(RestUrl, ct);
|
||||
|
||||
/// <summary>
|
||||
/// Waits until <c>document.readyState</c> is «complete» (read-only polling), up to <paramref name="timeout"/>.
|
||||
/// Returns false on timeout. Uses <paramref name="clock"/> for the pauses between polls.
|
||||
/// </summary>
|
||||
public static async Task<bool> WaitForLoadAsync(this ICdpSession cdp, IClock clock, TimeSpan timeout, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(clock);
|
||||
var deadline = clock.Now + timeout;
|
||||
while (true)
|
||||
{
|
||||
try
|
||||
{
|
||||
var state = await cdp.EvaluateAsync("document.readyState", ct).ConfigureAwait(false);
|
||||
if (state.ValueKind == JsonValueKind.String && state.GetString() == "complete")
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
catch (CdpCommandException)
|
||||
{
|
||||
// The context may be swapped during a navigation: poll again.
|
||||
}
|
||||
|
||||
if (clock.Now >= deadline)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
await clock.Delay(TimeSpan.FromMilliseconds(100), ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Febe.Browser.Cdp;
|
||||
|
||||
/// <summary>A DevTools target listed by <c>/json/list</c>. The address may hold data: never log it.</summary>
|
||||
public sealed record CdpTarget(string Id, string Type, string Url, Uri WebSocketDebuggerUrl);
|
||||
|
||||
/// <summary>
|
||||
/// Finds the page target through the DevTools HTTP endpoint on <c>http://127.0.0.1:<port></c> (spec §6.1).
|
||||
/// Only the loopback interface is ever contacted, never through a proxy.
|
||||
/// </summary>
|
||||
public static class CdpTargetDiscovery
|
||||
{
|
||||
private static readonly HttpClient Http = new(new SocketsHttpHandler
|
||||
{
|
||||
UseProxy = false,
|
||||
ConnectTimeout = TimeSpan.FromSeconds(2),
|
||||
AllowAutoRedirect = false,
|
||||
})
|
||||
{
|
||||
Timeout = TimeSpan.FromSeconds(5),
|
||||
};
|
||||
|
||||
/// <summary>Base address of the DevTools HTTP endpoint for <paramref name="port"/>.</summary>
|
||||
public static Uri EndpointFor(int port)
|
||||
{
|
||||
ValidatePort(port);
|
||||
return new Uri($"http://127.0.0.1:{port.ToString(System.Globalization.CultureInfo.InvariantCulture)}/");
|
||||
}
|
||||
|
||||
/// <summary>True when the DevTools endpoint answers <c>/json/version</c>.</summary>
|
||||
public static async Task<bool> IsAvailableAsync(int port, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var response = await Http.GetAsync(new Uri(EndpointFor(port), "json/version"), ct).ConfigureAwait(false);
|
||||
return response.StatusCode == HttpStatusCode.OK;
|
||||
}
|
||||
catch (HttpRequestException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
catch (TaskCanceledException) when (!ct.IsCancellationRequested)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Browser version string from <c>/json/version</c> (e.g. «Chrome/141.0.7390.37»), or null.</summary>
|
||||
public static async Task<string?> GetBrowserVersionAsync(int port, CancellationToken ct)
|
||||
{
|
||||
var version = await Http.GetFromJsonAsync(new Uri(EndpointFor(port), "json/version"), CdpDiscoveryJsonContext.Default.VersionDto, ct).ConfigureAwait(false);
|
||||
return version?.Browser;
|
||||
}
|
||||
|
||||
public static async Task<IReadOnlyList<CdpTarget>> ListAsync(int port, CancellationToken ct)
|
||||
{
|
||||
var items = await Http.GetFromJsonAsync(new Uri(EndpointFor(port), "json/list"), CdpDiscoveryJsonContext.Default.ListTargetDto, ct).ConfigureAwait(false);
|
||||
var targets = new List<CdpTarget>();
|
||||
foreach (var item in items ?? [])
|
||||
{
|
||||
if (string.IsNullOrEmpty(item.Id) || string.IsNullOrEmpty(item.WebSocketDebuggerUrl)
|
||||
|| !Uri.TryCreate(item.WebSocketDebuggerUrl, UriKind.Absolute, out var ws))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
EnsureLoopback(ws, port);
|
||||
targets.Add(new CdpTarget(item.Id, item.Type ?? string.Empty, item.Url ?? string.Empty, ws));
|
||||
}
|
||||
|
||||
return targets;
|
||||
}
|
||||
|
||||
/// <summary>The first target of type «page», or null when the browser has none.</summary>
|
||||
public static async Task<CdpTarget?> FindPageAsync(int port, CancellationToken ct)
|
||||
{
|
||||
var targets = await ListAsync(port, ct).ConfigureAwait(false);
|
||||
return targets.FirstOrDefault(t => t.Type == "page");
|
||||
}
|
||||
|
||||
/// <summary>Refuses any DevTools address that is not on the loopback interface (and, when given, on the expected port).</summary>
|
||||
public static void EnsureLoopback(Uri address, int? expectedPort = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(address);
|
||||
var host = address.IdnHost.Trim('[', ']');
|
||||
var loopback = host.Equals("localhost", StringComparison.OrdinalIgnoreCase)
|
||||
|| (IPAddress.TryParse(host, out var ip) && IPAddress.IsLoopback(ip));
|
||||
if (!loopback || address.Scheme is not ("ws" or "http"))
|
||||
{
|
||||
throw new InvalidOperationException("Il protocollo DevTools si usa solo su 127.0.0.1 (specifica §6.1).");
|
||||
}
|
||||
|
||||
if (expectedPort is { } port && address.Port != port)
|
||||
{
|
||||
throw new InvalidOperationException("Il browser ha indicato una porta DevTools diversa da quella fissata.");
|
||||
}
|
||||
}
|
||||
|
||||
internal static void ValidatePort(int port)
|
||||
{
|
||||
if (port is < 1024 or > 65535)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(port), port, "La porta di debug deve essere fissa, fra 1024 e 65535 (mai 0).");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class TargetDto
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
|
||||
public string? Type { get; set; }
|
||||
|
||||
public string? Url { get; set; }
|
||||
|
||||
public string? WebSocketDebuggerUrl { get; set; }
|
||||
}
|
||||
|
||||
internal sealed class VersionDto
|
||||
{
|
||||
public string? Browser { get; set; }
|
||||
}
|
||||
|
||||
[JsonSourceGenerationOptions(PropertyNameCaseInsensitive = true)]
|
||||
[JsonSerializable(typeof(List<TargetDto>), TypeInfoPropertyName = "ListTargetDto")]
|
||||
[JsonSerializable(typeof(VersionDto))]
|
||||
internal sealed partial class CdpDiscoveryJsonContext : JsonSerializerContext;
|
||||
@@ -0,0 +1,48 @@
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Febe.Browser.Cdp;
|
||||
|
||||
/// <summary>
|
||||
/// Defense in depth for <c>Runtime.evaluate</c>, which spec §6.1 allows only read-only (element positions,
|
||||
/// address, presence of dialogs). Expressions that click, scroll, focus, fire events, change the DOM or storage,
|
||||
/// navigate, override properties or build requests by hand are refused before they reach the browser.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A deny-list cannot prove an expression harmless: it catches mistakes in Febe's own scripts, which are the only
|
||||
/// expressions ever evaluated. Gestures go through <c>Input.*</c> only.
|
||||
/// </remarks>
|
||||
public static partial class ReadOnlyScriptGuard
|
||||
{
|
||||
public static void EnsureReadOnly(string? expression)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(expression))
|
||||
{
|
||||
throw new CdpCommandNotAllowedException("Runtime.evaluate", "Runtime.evaluate senza espressione.");
|
||||
}
|
||||
|
||||
var match = Forbidden().Match(expression);
|
||||
if (match.Success)
|
||||
{
|
||||
throw new CdpCommandNotAllowedException(
|
||||
"Runtime.evaluate",
|
||||
$"Runtime.evaluate si usa solo in sola lettura (specifica §6.1): l'espressione contiene «{match.Value.Trim()}».");
|
||||
}
|
||||
}
|
||||
|
||||
public static bool IsReadOnly(string? expression) =>
|
||||
!string.IsNullOrWhiteSpace(expression) && !Forbidden().IsMatch(expression);
|
||||
|
||||
// Gestures and focus; DOM and attribute changes; navigation and history; property overrides;
|
||||
// hand-built requests; storage and cookies; synthetic events; assignments to DOM state.
|
||||
[GeneratedRegex(
|
||||
@"\.\s*(click|focus|blur|submit|requestSubmit|reset|remove|append|prepend|scroll|scrollTo|scrollBy|scrollIntoView|scrollIntoViewIfNeeded|dispatchEvent|setAttribute|setAttributeNS|removeAttribute|toggleAttribute|appendChild|removeChild|replaceChild|replaceWith|insertBefore|insertAdjacentHTML|insertAdjacentElement|insertAdjacentText|showModal|setSelectionRange|pushState|replaceState|assign|reload|defineProperty|defineProperties|__defineGetter__|__defineSetter__|setItem|removeItem|execCommand)\s*\("
|
||||
+ @"|\b(fetch|XMLHttpRequest|sendBeacon|WebSocket|EventSource|importScripts|import)\s*\("
|
||||
+ @"|\bnew\s+(XMLHttpRequest|WebSocket|EventSource|Worker|SharedWorker|\w*Event)\b"
|
||||
+ @"|\b(document\.cookie|localStorage|sessionStorage|indexedDB|cookieStore)\b"
|
||||
+ @"|\.\s*(innerHTML|outerHTML|textContent|innerText|outerText|value|checked|selected|scrollTop|scrollLeft|src|href|cookie|title|hash|search|pathname)\s*(=(?!=)|\+=)"
|
||||
+ @"|\b(location|window\.location|document\.location)\s*=(?!=)"
|
||||
+ @"|\bnavigator\s*\.\s*\w+\s*=(?!=)"
|
||||
+ @"|\b(window\.open|document\.write|document\.writeln|document\.open)\s*\(",
|
||||
RegexOptions.CultureInvariant)]
|
||||
private static partial Regex Forbidden();
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
using System.Text.Json;
|
||||
using Febe.Core.Abstractions;
|
||||
|
||||
namespace Febe.Browser.Cdp;
|
||||
|
||||
/// <summary>Notifies components that the CDP connection was replaced (browser restarted).</summary>
|
||||
public interface ICdpConnectionEvents
|
||||
{
|
||||
/// <summary>
|
||||
/// Raised after a new connection replaced a lost one. Domain state (<c>Network.enable</c>, a screencast)
|
||||
/// is lost with the old connection: components re-enable what they need. Not raised for the first connection.
|
||||
/// </summary>
|
||||
event EventHandler? Reconnected;
|
||||
}
|
||||
|
||||
/// <summary>Raised by <see cref="ReconnectingCdpSession"/> while no browser connection is available.</summary>
|
||||
public sealed class BrowserUnavailableException()
|
||||
: InvalidOperationException("Il browser non è disponibile in questo momento (avvio o riavvio in corso).");
|
||||
|
||||
/// <summary>
|
||||
/// A stable <see cref="ICdpSession"/> on top of a sequence of <see cref="CdpClient"/>s: subscriptions survive
|
||||
/// browser restarts, and commands fail fast with <see cref="BrowserUnavailableException"/> while detached.
|
||||
/// </summary>
|
||||
public sealed class ReconnectingCdpSession : ICdpSession, ICdpConnectionEvents
|
||||
{
|
||||
private readonly Lock _gate = new();
|
||||
private readonly List<Registration> _registrations = [];
|
||||
private CdpClient? _client;
|
||||
private bool _everAttached;
|
||||
|
||||
public event EventHandler? Reconnected;
|
||||
|
||||
public bool IsAttached
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return _client is { IsConnected: true };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Uses <paramref name="client"/> from now on. The caller keeps ownership (and disposes it).</summary>
|
||||
public void Attach(CdpClient client)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(client);
|
||||
bool reconnect;
|
||||
lock (_gate)
|
||||
{
|
||||
DetachLocked();
|
||||
_client = client;
|
||||
foreach (var registration in _registrations)
|
||||
{
|
||||
registration.Inner = client.On(registration.EventName, registration.Handler);
|
||||
}
|
||||
|
||||
reconnect = _everAttached;
|
||||
_everAttached = true;
|
||||
}
|
||||
|
||||
if (reconnect)
|
||||
{
|
||||
Reconnected?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Stops using the current client (it is not disposed here).</summary>
|
||||
public void Detach()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
DetachLocked();
|
||||
}
|
||||
}
|
||||
|
||||
public Task<JsonElement> SendAsync(string method, object? parameters = null, CancellationToken ct = default)
|
||||
{
|
||||
// Policy first, so a forbidden command is reported as such even while the browser is down.
|
||||
CdpCommandPolicy.EnsureAllowed(method);
|
||||
CdpClient? client;
|
||||
lock (_gate)
|
||||
{
|
||||
client = _client;
|
||||
}
|
||||
|
||||
return client is null ? Task.FromException<JsonElement>(new BrowserUnavailableException()) : client.SendAsync(method, parameters, ct);
|
||||
}
|
||||
|
||||
public IDisposable On(string eventName, Action<JsonElement> handler)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrEmpty(eventName);
|
||||
ArgumentNullException.ThrowIfNull(handler);
|
||||
var registration = new Registration(eventName, handler);
|
||||
lock (_gate)
|
||||
{
|
||||
_registrations.Add(registration);
|
||||
registration.Inner = _client?.On(eventName, handler);
|
||||
}
|
||||
|
||||
return new Subscription(() =>
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_registrations.Remove(registration);
|
||||
registration.Inner?.Dispose();
|
||||
registration.Inner = null;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void DetachLocked()
|
||||
{
|
||||
foreach (var registration in _registrations)
|
||||
{
|
||||
registration.Inner?.Dispose();
|
||||
registration.Inner = null;
|
||||
}
|
||||
|
||||
_client = null;
|
||||
}
|
||||
|
||||
private sealed class Registration(string eventName, Action<JsonElement> handler)
|
||||
{
|
||||
public string EventName { get; } = eventName;
|
||||
|
||||
public Action<JsonElement> Handler { get; } = handler;
|
||||
|
||||
public IDisposable? Inner { get; set; }
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user