Files
Febe/src/Febe.Browser/Cdp/CdpCommandPolicy.cs
T
Alby96andClaude Opus 5.5 724c0752cf Vista remota: l'avvio dei fotogrammi si ritenta mentre la pagina cambia documento
Da ReadyToCommitNavigation al commit di una navigazione con un nuovo
RenderFrameHost (con RenderDocument: ogni navigazione, anche verso la
pagina di riposo) Chromium rifiuta Page.startScreencast con -32000
«Not attached to an active page». La vista aperta in quel momento
(insieme alla pagina di accesso, dopo un riposo del motore, durante una
sessione) finiva in «Il browser di Febe non risponde».

Ora ScreencastSession rimanda l'avvio solo su quella risposta, con pause
da 100 a 500 ms e per al più 5 s sull'orologio vero (IClock, iniettabile
nelle prove); ogni altro errore sale subito com'era. Nessun comando CDP
nuovo. Vale anche per il riavvio dei fotogrammi dopo un riavvio del browser.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 16:54:50 +02:00

140 lines
5.6 KiB
C#

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}).")
{
/// <summary>Chromium's generic «server error» code.</summary>
public const int ServerErrorCode = -32000;
/// <summary>
/// What Chromium answers to a browser-side page command (<c>Page.startScreencast</c>, <c>Page.captureScreenshot</c>)
/// while the page's current document is not «active»: from <c>ReadyToCommitNavigation</c> of a navigation that uses
/// a new RenderFrameHost until that navigation commits, DevTools already points at the new, still uncommitted frame
/// (content/browser/devtools/protocol/page_handler.cc, <c>AssureTopLevelActiveFrame</c>;
/// render_frame_devtools_agent_host.cc, <c>ReadyToCommitNavigation</c>). A new RenderFrameHost comes with a process
/// swap, a cross-site or back-forward-cache swap and, with RenderDocument (on by default in current Chromium), with
/// every navigation of the page to a new document — the rest page included.
/// </summary>
public const string InactivePageMessage = "Not attached to an active page";
public string Method { get; } = method;
public int Code { get; } = code;
public string BrowserMessage { get; } = browserMessage;
/// <summary>
/// The page is between two documents (see <see cref="InactivePageMessage"/>): the same command a moment later finds
/// the new document committed. A browser that is gone answers differently (closed connection, no answer).
/// </summary>
public bool IsInactivePage => Code == ServerErrorCode && string.Equals(BrowserMessage, InactivePageMessage, StringComparison.Ordinal);
}
/// <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)
{
}
}