Niente più browser nel bot: la sessione di Bidoo si incolla da Chrome (#36)
I cookie di accesso di Bidoo (__stattrb, PHPSESSID) sono HttpOnly: nessuno script o copia della pagina li vede, quindi non esiste un modo più semplice degli strumenti per sviluppatori. Lì Chrome ha già «Copia come cURL», che porta cookie e User-Agent in un colpo. Per questo, come deciso da Alberto, il browser del bot se ne va. - Session/SessionPaste riconosce da solo cURL (bash e cmd, -b o -H cookie, -A o -H user-agent), «Copia come PowerShell», intestazioni della richiesta (anche nome e valore su righe diverse), la riga Cookie, righe della tabella dei cookie e il solo valore di __stattrb; rifiuta un testo senza il cookie di accesso. Lo User-Agent del testo vale più di quello del campo. - La pagina Browser diventa «Accesso a Bidoo» (#/accesso, #/browser ci porta): riquadro da incollare, istruzioni per Chrome, stato della sessione. - Via AssistedLogin, i comandi login.* e i messaggi login.frame/login.state; via chromium e fonts-liberation dall'immagine, e prova-immagine.sh controlla che Chromium non ci sia. All'avvio il bot cancella /config/browser, il profilo della 1.x con una copia dei cookie. - Il client CDP e l'avvio di Chromium passano in tools/Mimante.Schermate, che usa Chrome o Edge del PC. - ADR 0017 (supera la 0003; la 0010 resta per la base Debian), README, architettura, guida, docker.md, stato e CHANGELOG aggiornati. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
f92b8d08f0
commit
88c16568fb
38 files changed
+632
-838
No files matched your search
@@ -0,0 +1,178 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Net.WebSockets;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
|
||||
namespace Mimante.Schermate.Cdp;
|
||||
|
||||
/// <summary>Un errore restituito da Chromium a un comando CDP.</summary>
|
||||
public sealed class CdpException(string method, string message) : Exception($"{method}: {message}");
|
||||
|
||||
/// <summary>Il canale verso Chromium: in produzione un WebSocket, nei test una coda in memoria.</summary>
|
||||
public interface ICdpTransport : IAsyncDisposable
|
||||
{
|
||||
Task SendAsync(string json, CancellationToken ct);
|
||||
|
||||
/// <summary>Il prossimo messaggio intero; null quando il canale si chiude.</summary>
|
||||
Task<string?> ReceiveAsync(CancellationToken ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Client del Chrome DevTools Protocol scritto a mano, per le schermate: JSON-RPC su
|
||||
/// WebSocket, <c>id</c> incrementale, mappa delle risposte in attesa, eventi con
|
||||
/// <c>sessionId</c> (sessioni piatte, <c>Target.attachToTarget</c> con <c>flatten: true</c>).
|
||||
/// Niente Playwright: servono una decina di comandi.
|
||||
/// </summary>
|
||||
public sealed class CdpClient : IAsyncDisposable
|
||||
{
|
||||
private readonly ICdpTransport _transport;
|
||||
private readonly ConcurrentDictionary<int, (string Method, TaskCompletionSource<JsonElement> Tcs)> _pending = new();
|
||||
private readonly CancellationTokenSource _cts = new();
|
||||
private readonly Task _reader;
|
||||
private int _nextId;
|
||||
|
||||
/// <summary>Un evento: metodo, parametri, sessione (null = browser).</summary>
|
||||
public event Action<string, JsonElement, string?>? Event;
|
||||
|
||||
/// <summary>Il canale si è chiuso (Chromium uscito).</summary>
|
||||
public event Action? Closed;
|
||||
|
||||
public CdpClient(ICdpTransport transport)
|
||||
{
|
||||
_transport = transport;
|
||||
_reader = Task.Run(() => ReadLoopAsync(_cts.Token));
|
||||
}
|
||||
|
||||
public static async Task<CdpClient> ConnectAsync(Uri endpoint, CancellationToken ct)
|
||||
{
|
||||
var ws = new ClientWebSocket();
|
||||
ws.Options.KeepAliveInterval = TimeSpan.FromSeconds(20);
|
||||
await ws.ConnectAsync(endpoint, ct).ConfigureAwait(false);
|
||||
return new CdpClient(new WebSocketCdpTransport(ws));
|
||||
}
|
||||
|
||||
public bool IsClosed { get; private set; }
|
||||
|
||||
/// <summary>Un comando; la risposta è il campo <c>result</c>. Un <c>error</c> diventa <see cref="CdpException"/>.</summary>
|
||||
public async Task<JsonElement> SendAsync(string method, object? parameters = null, string? sessionId = null,
|
||||
CancellationToken ct = default, TimeSpan? timeout = null)
|
||||
{
|
||||
if (IsClosed) throw new CdpException(method, "browser chiuso");
|
||||
var id = Interlocked.Increment(ref _nextId);
|
||||
var tcs = new TaskCompletionSource<JsonElement>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
_pending[id] = (method, tcs);
|
||||
|
||||
var message = new JsonObject { ["id"] = id, ["method"] = method };
|
||||
if (parameters != null) message["params"] = JsonSerializer.SerializeToNode(parameters);
|
||||
if (sessionId != null) message["sessionId"] = sessionId;
|
||||
|
||||
try
|
||||
{
|
||||
await _transport.SendAsync(message.ToJsonString(), ct).ConfigureAwait(false);
|
||||
return await tcs.Task.WaitAsync(timeout ?? TimeSpan.FromSeconds(15), ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (TimeoutException)
|
||||
{
|
||||
throw new CdpException(method, "nessuna risposta dal browser");
|
||||
}
|
||||
finally
|
||||
{
|
||||
_pending.TryRemove(id, out _);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Un comando di cui non interessa la risposta (conferme dei frame, input).</summary>
|
||||
public void Post(string method, object? parameters = null, string? sessionId = null) =>
|
||||
_ = SendAsync(method, parameters, sessionId).ContinueWith(t => _ = t.Exception, TaskScheduler.Default);
|
||||
|
||||
private async Task ReadLoopAsync(CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
while (!ct.IsCancellationRequested)
|
||||
{
|
||||
var text = await _transport.ReceiveAsync(ct).ConfigureAwait(false);
|
||||
if (text == null) break;
|
||||
Handle(text);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) { }
|
||||
catch (WebSocketException) { }
|
||||
finally
|
||||
{
|
||||
IsClosed = true;
|
||||
foreach (var (_, p) in _pending) p.Tcs.TrySetException(new CdpException(p.Method, "browser chiuso"));
|
||||
_pending.Clear();
|
||||
Closed?.Invoke();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Smista un messaggio in arrivo: risposta a un comando o evento.</summary>
|
||||
internal void Handle(string text)
|
||||
{
|
||||
using var doc = JsonDocument.Parse(text);
|
||||
var root = doc.RootElement;
|
||||
if (root.TryGetProperty("id", out var idEl) && idEl.TryGetInt32(out var id))
|
||||
{
|
||||
if (!_pending.TryGetValue(id, out var p)) return;
|
||||
if (root.TryGetProperty("error", out var err))
|
||||
p.Tcs.TrySetException(new CdpException(p.Method, err.TryGetProperty("message", out var msg) ? msg.GetString() ?? "errore" : "errore"));
|
||||
else
|
||||
p.Tcs.TrySetResult(root.TryGetProperty("result", out var result) ? result.Clone() : default);
|
||||
return;
|
||||
}
|
||||
|
||||
if (root.TryGetProperty("method", out var method))
|
||||
{
|
||||
var session = root.TryGetProperty("sessionId", out var s) ? s.GetString() : null;
|
||||
var parameters = root.TryGetProperty("params", out var pr) ? pr.Clone() : default;
|
||||
try { Event?.Invoke(method.GetString() ?? "", parameters, session); }
|
||||
catch { /* un gestore rotto non chiude il canale */ }
|
||||
}
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
await _cts.CancelAsync().ConfigureAwait(false);
|
||||
await _transport.DisposeAsync().ConfigureAwait(false);
|
||||
try { await _reader.WaitAsync(TimeSpan.FromSeconds(2)).ConfigureAwait(false); } catch { }
|
||||
_cts.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Il WebSocket di Chromium (<c>ws://127.0.0.1:porta/devtools/browser/…</c>).</summary>
|
||||
internal sealed class WebSocketCdpTransport(ClientWebSocket ws) : ICdpTransport
|
||||
{
|
||||
private readonly SemaphoreSlim _sendGate = new(1, 1);
|
||||
|
||||
public async Task SendAsync(string json, CancellationToken ct)
|
||||
{
|
||||
await _sendGate.WaitAsync(ct).ConfigureAwait(false);
|
||||
try { await ws.SendAsync(Encoding.UTF8.GetBytes(json), WebSocketMessageType.Text, true, ct).ConfigureAwait(false); }
|
||||
finally { _sendGate.Release(); }
|
||||
}
|
||||
|
||||
public async Task<string?> ReceiveAsync(CancellationToken ct)
|
||||
{
|
||||
var buffer = new byte[64 * 1024];
|
||||
using var ms = new MemoryStream();
|
||||
while (true)
|
||||
{
|
||||
var r = await ws.ReceiveAsync(buffer, ct).ConfigureAwait(false);
|
||||
if (r.MessageType == WebSocketMessageType.Close) return null;
|
||||
ms.Write(buffer, 0, r.Count);
|
||||
if (r.EndOfMessage) return Encoding.UTF8.GetString(ms.GetBuffer(), 0, (int)ms.Length);
|
||||
}
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
if (ws.State == WebSocketState.Open)
|
||||
{
|
||||
try { await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "fine", CancellationToken.None).WaitAsync(TimeSpan.FromSeconds(2)).ConfigureAwait(false); }
|
||||
catch { }
|
||||
}
|
||||
ws.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
|
||||
namespace Mimante.Schermate.Cdp;
|
||||
|
||||
/// <summary>
|
||||
/// Chromium senza finestra per le schermate. Il bot non ha più un browser (ADR 0017): Chrome, Edge o
|
||||
/// Chromium sono quelli del PC o del lavoro della CI. L'indirizzo del protocollo si legge da
|
||||
/// <c>DevToolsActivePort</c> (porta scelta dal browser: nessun conflitto).
|
||||
/// </summary>
|
||||
public sealed class ChromiumProcess : IAsyncDisposable
|
||||
{
|
||||
private readonly Process _process;
|
||||
|
||||
public Uri Endpoint { get; }
|
||||
|
||||
private ChromiumProcess(Process process, Uri endpoint)
|
||||
{
|
||||
_process = process;
|
||||
Endpoint = endpoint;
|
||||
}
|
||||
|
||||
public bool HasExited => _process.HasExited;
|
||||
|
||||
/// <summary>Dove cercare il browser: su Linux il pacchetto della distribuzione, su Windows Chrome o Edge.</summary>
|
||||
public static IEnumerable<string> Candidates()
|
||||
{
|
||||
yield return "/usr/bin/chromium";
|
||||
yield return "/usr/bin/chromium-browser";
|
||||
yield return "/usr/bin/google-chrome";
|
||||
yield return "/usr/bin/google-chrome-stable";
|
||||
if (OperatingSystem.IsWindows())
|
||||
{
|
||||
foreach (var root in new[] { Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86),
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) })
|
||||
{
|
||||
if (string.IsNullOrEmpty(root)) continue;
|
||||
yield return Path.Combine(root, "Google", "Chrome", "Application", "chrome.exe");
|
||||
yield return Path.Combine(root, "Chromium", "Application", "chrome.exe");
|
||||
yield return Path.Combine(root, "Microsoft", "Edge", "Application", "msedge.exe");
|
||||
}
|
||||
}
|
||||
if (OperatingSystem.IsMacOS()) yield return "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";
|
||||
}
|
||||
|
||||
public static string? FindExecutable() => Candidates().FirstOrDefault(File.Exists);
|
||||
|
||||
public static IReadOnlyList<string> Arguments(string profileDir) => new[]
|
||||
{
|
||||
"--headless=new", "--remote-debugging-port=0", $"--user-data-dir={profileDir}", "--no-sandbox", "--disable-gpu",
|
||||
"--window-size=1280,900", "--lang=it-IT", "--no-first-run", "--no-default-browser-check", "--disable-dev-shm-usage",
|
||||
"--disable-background-networking", "--disable-sync", "--mute-audio", "about:blank"
|
||||
};
|
||||
|
||||
public static async Task<ChromiumProcess> StartAsync(string profileDir, CancellationToken ct)
|
||||
{
|
||||
var exe = FindExecutable() ?? throw new InvalidOperationException("Chrome, Edge o Chromium non trovato su questo computer");
|
||||
Directory.CreateDirectory(profileDir);
|
||||
var portFile = Path.Combine(profileDir, "DevToolsActivePort");
|
||||
try { if (File.Exists(portFile)) File.Delete(portFile); } catch (IOException) { }
|
||||
// Un blocco lasciato da un Chromium ucciso impedisce di riaprire il profilo.
|
||||
foreach (var lockName in new[] { "SingletonLock", "SingletonSocket", "SingletonCookie" })
|
||||
{
|
||||
try { var p = Path.Combine(profileDir, lockName); if (File.Exists(p) || Directory.Exists(p)) File.Delete(p); } catch { }
|
||||
}
|
||||
|
||||
var psi = new ProcessStartInfo(exe)
|
||||
{
|
||||
UseShellExecute = false,
|
||||
RedirectStandardError = true,
|
||||
RedirectStandardOutput = true,
|
||||
CreateNoWindow = true
|
||||
};
|
||||
foreach (var a in Arguments(profileDir)) psi.ArgumentList.Add(a);
|
||||
|
||||
var process = Process.Start(psi) ?? throw new InvalidOperationException("Chromium non si è avviato");
|
||||
process.ErrorDataReceived += (_, _) => { };
|
||||
process.OutputDataReceived += (_, _) => { };
|
||||
process.BeginErrorReadLine();
|
||||
process.BeginOutputReadLine();
|
||||
|
||||
var deadline = DateTime.UtcNow.AddSeconds(20);
|
||||
while (DateTime.UtcNow < deadline)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
if (process.HasExited) throw new InvalidOperationException($"Chromium si è chiuso subito (codice {process.ExitCode})");
|
||||
if (TryReadPort(portFile) is { } endpoint) return new ChromiumProcess(process, endpoint);
|
||||
await Task.Delay(100, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
try { process.Kill(entireProcessTree: true); } catch { }
|
||||
throw new InvalidOperationException("Chromium non ha aperto il protocollo di controllo in 20 secondi");
|
||||
}
|
||||
|
||||
/// <summary>Riga 1 la porta, riga 2 il percorso del WebSocket del browser.</summary>
|
||||
internal static Uri? TryReadPort(string file)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!File.Exists(file)) return null;
|
||||
var lines = File.ReadAllLines(file);
|
||||
if (lines.Length < 2 || !int.TryParse(lines[0].Trim(), NumberStyles.None, CultureInfo.InvariantCulture, out var port) || port <= 0) return null;
|
||||
return new Uri($"ws://127.0.0.1:{port}{lines[1].Trim()}");
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!_process.HasExited)
|
||||
{
|
||||
await _process.WaitForExitAsync(new CancellationTokenSource(TimeSpan.FromSeconds(3)).Token).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) { }
|
||||
try { if (!_process.HasExited) _process.Kill(entireProcessTree: true); } catch { }
|
||||
_process.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<!--
|
||||
Schermate del README e controllo dell'interfaccia: pilota Chromium con il client CDP del
|
||||
bot (nessun pacchetto in più), fotografa ogni pagina e segnala gli errori JavaScript.
|
||||
Schermate del README e controllo dell'interfaccia: pilota Chrome, Edge o Chromium del PC con
|
||||
un client CDP scritto qui (Cdp/, nessun pacchetto in più), fotografa ogni pagina e segnala gli
|
||||
errori JavaScript. Il bot non ha più un browser (ADR 0017): il client vive solo qui.
|
||||
-->
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
using System.Text.Json;
|
||||
using Mimante.Session.Cdp;
|
||||
using Mimante.Schermate.Cdp;
|
||||
|
||||
// Uso: dotnet run --project tools/Mimante.Schermate -- <indirizzo> <password dell'interfaccia> <cartella>
|
||||
// Esempio: dotnet run --project tools/Mimante.Schermate -- http://localhost:8080 dev docs/schermate
|
||||
@@ -146,23 +146,8 @@ else
|
||||
await Shot("14-aste-puntate", "#/aste", "document.querySelector('.panel .tabs button[data-tab=puntate]')?.click()", 500);
|
||||
await Eval("document.querySelector('.panel .tabs button[data-tab=auto]')?.click()");
|
||||
await Shot("02-apprendimento", "#/apprendimento", null, 3500);
|
||||
await Shot("03-browser", "#/browser");
|
||||
if (args.Contains("--accesso-assistito"))
|
||||
{
|
||||
// Apre il browser del bot (Chromium dentro il bot) e aspetta il primo fotogramma.
|
||||
await Eval("document.querySelector('.browser .idle button')?.click()");
|
||||
var frame = false;
|
||||
for (var i = 0; i < 40 && !frame; i++)
|
||||
{
|
||||
await Task.Delay(500, ct);
|
||||
frame = (await Eval("!document.querySelector('.browser canvas').hidden")).ValueKind == JsonValueKind.True;
|
||||
}
|
||||
await Task.Delay(2500, ct);
|
||||
await Shot("03-browser", "#/browser", null, 200);
|
||||
Console.WriteLine(frame ? "Browser del bot: fotogrammi ricevuti" : "Browser del bot: nessun fotogramma");
|
||||
if (!frame) errors.Add("accesso assistito: nessun fotogramma dal browser del bot");
|
||||
await Eval("document.querySelector('.browser .url button[title^=\"Chiudi\"]')?.click()");
|
||||
}
|
||||
// La pagina d'accesso con un testo incollato a mano (non si invia): mostra il riquadro pieno.
|
||||
await Shot("03-accesso", "#/accesso", "document.querySelector('textarea.paste').value = \"curl 'https://it.bidoo.com/' -b '__stattrb=…; PHPSESSID=…' -H 'user-agent: …'\"", 500);
|
||||
if (args.Contains("--messaggio"))
|
||||
{
|
||||
// Il messaggio a schermo per un'informazione importante: senza token Telegram il
|
||||
|
||||
Reference in new issue
Block a user