Instagram: Febe legge le risposte vere (campioni dal HAR del 21/10)
verifica / controlli (push) Successful in 2m10s
verifica / prove (push) Successful in 26m16s
verifica / installatore (push) Successful in 5m39s
verifica / immagine (push) Successful in 28m39s

Febe non estraeva nulla da Instagram per due motivi. Instagram manda i
dati di storie e raccolte (GraphQL) come text/javascript, e la cattura
leggeva solo le risposte dichiarate JSON: le scartava tutte. E i file di
Instagram (lettori, bersagli) erano scheletri, quindi le ricette si
rifiutavano di girare.

Alberto ha mandato un HAR del suo browser e una guida. La guida descrive
richieste costruite a mano, vietate dalle regole 2-4, e un formato che
nel HAR non compare: non si usa. Dal HAR si è letta solo la forma; le
risposte utili sono diventate campioni grezzi fuori dal repository,
ripuliti e verificati con febe-sonda (tests/Febe.Tests/campioni/instagram).

Che cosa cambia:
- la cattura legge le risposte text/javascript chieste dalla pagina (mai
  gli script) e ogni blocco JSON incorporato nel documento della pagina,
  e avvisa quando un corpo atteso non arriverà;
- le risposte che non parlano di contenuti (promozioni, «storia vista»)
  si ignorano invece di valere come formato non riconosciuto;
- lettori.instagram.json è confermato, con sole chiavi presenti nei
  campioni; identificativi delle raccolte nella forma dell'indirizzo;
- bersagli.instagram.json ha le pagine viste nel traffico vero; i
  bersagli restano vuoti (H11): storie, raccolte, Taggati e Reel
  aspettano lo script tools/bersagli/raccogli-bersagli.js;
- le ricette del profilo reggono dati in risposte diverse e prendono la
  paginazione solo dalla risposta che porta i loro post; l'elenco dei
  seguiti scarta i profili suggeriti; «Tu» si riconosce anche dal solo
  identificativo dell'account collegato;
- il visualizzatore delle raccolte conta i contenuti (l'indirizzo non
  cambia), chiede il permesso prima di ogni contenuto e si chiude sempre;
- una ricetta che la configurazione non lascia girare è «Da configurare»:
  non è un guasto, non si sospende, non si pianifica; le sospensioni
  dovute ai file vecchi si azzerano una volta al cambio dei file;
- la barra laterale dice «Collegato» dal cookie di sessione; i «Post
  singolo» per gli indirizzi scaduti non vengono più annullati;
- febe-sonda da-har; la ripulitura tiene latest_reel_media e mette un
  riempitivo neutro sotto le chiavi simili a segreti (gitleaks).

Prove su Windows: 783 superate, 76 saltate (Chromium e Xvfb, nella CI).
Nulla è stato provato contro Instagram. Dettagli e decisioni in
docs/stato.md e docs/decisioni.md (righe del 25 ottobre).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-10-25 14:22:16 +01:00
1 parent b3a7c31e5a
commit 31bbbf8bb7
69 files changed
+9184 -453

No files matched your search

+182 -78
View File
@@ -19,8 +19,17 @@ public sealed record ResponseTapOptions
/// <summary>How long to wait for one body before giving up on it (one stuck request must not block the others).</summary>
public TimeSpan BodyTimeout { get; init; } = TimeSpan.FromSeconds(15);
/// <summary>Decides from the declared MIME type whether a body is worth parsing as JSON.</summary>
public Func<string, bool> IsJsonMimeType { get; init; } = static mime => mime.Contains("json", StringComparison.OrdinalIgnoreCase);
/// <summary>
/// Decides from the declared MIME type and the resource type whether a body is worth parsing as JSON
/// (<see cref="DataResponses.IsData"/>: JSON, and JavaScript the page fetched itself).
/// </summary>
public Func<string, string?, bool> IsDataResponse { get; init; } = DataResponses.IsData;
/// <summary>
/// Whether the main document of a site page is read too, for the JSON blocks it embeds
/// (<see cref="DataResponses.EmbeddedJsonBlocks"/>).
/// </summary>
public bool ReadPageDocuments { get; init; } = true;
/// <summary>Per-resource buffer of the browser (<c>Network.enable</c> maxResourceBufferSize).</summary>
public int BrowserResourceBufferBytes { get; init; } = 32 * 1024 * 1024;
@@ -37,22 +46,26 @@ public sealed record ResponseTapStats(long Responses, long JsonBodies, long Body
/// and the metadata of every response and main-frame navigation to <see cref="IResponseObserver"/>s.
/// </summary>
/// <remarks>
/// It does not filter by address: readers recognise data by its shape (spec §6.4). Bodies stay in memory for the
/// time of the reading, are never written to disk and never logged. Event handlers only queue work; bodies are
/// fetched and parsed on a background worker, one at a time.
/// It does not filter by address: readers recognise data by its shape (spec §6.4). A body is read when the browser
/// declares it as JSON, or as JavaScript fetched by the page (Instagram's GraphQL answers), and the main document of a
/// site page is read for the JSON blocks it embeds, each handed to consumers as an answer of its own with the
/// document's descriptor. Bodies stay in memory for the time of the reading, are never written to disk and never
/// logged. Event handlers only queue work; bodies are fetched and parsed on a background worker, one at a time.
/// </remarks>
public sealed class ResponseTap : IAsyncDisposable
{
private static readonly JsonDocumentOptions BodyOptions = new() { MaxDepth = 256 };
private readonly ICdpSession _cdp;
private readonly HostClassifier _hosts;
private readonly IClock _clock;
private readonly IBrowserLog _log;
private readonly ResponseTapOptions _options;
private readonly ConcurrentDictionary<string, ResponseDescriptor> _inFlight = new(StringComparer.Ordinal);
private readonly ConcurrentDictionary<string, PendingBody> _inFlight = new(StringComparer.Ordinal);
private readonly Lock _gate = new();
private readonly List<IResponseConsumer> _consumers = [];
private readonly List<IResponseObserver> _observers = [];
private readonly Channel<ResponseDescriptor> _queue = Channel.CreateUnbounded<ResponseDescriptor>(new UnboundedChannelOptions { SingleReader = true });
private readonly Channel<PendingBody> _queue = Channel.CreateUnbounded<PendingBody>(new UnboundedChannelOptions { SingleReader = true });
private readonly CancellationTokenSource _lifetime = new();
private readonly List<IDisposable> _subscriptions = [];
private Task? _worker;
@@ -181,7 +194,14 @@ public sealed class ResponseTap : IAsyncDisposable
private void OnReconnected(object? sender, EventArgs e)
{
_inFlight.Clear();
foreach (var key in _inFlight.Keys)
{
if (_inFlight.TryRemove(key, out _))
{
NotifyDropped(key);
}
}
_ = Task.Run(async () =>
{
try
@@ -240,16 +260,21 @@ public sealed class ResponseTap : IAsyncDisposable
}
}
if (_options.IsJsonMimeType(mime) && status is >= 200 and < 600 && status != 204)
if (_options.IsDataResponse(mime, type) && status is >= 200 and < 600 && status != 204)
{
_inFlight[requestId] = descriptor;
_inFlight[requestId] = new PendingBody(descriptor, IsPageDocument: false);
}
else if (_options.ReadPageDocuments && descriptor.HostKind == HostKind.Site && status is >= 200 and < 300
&& DataResponses.IsPageDocument(mime, isMainDocument))
{
_inFlight[requestId] = new PendingBody(descriptor, IsPageDocument: true);
}
}
private void OnLoadingFinished(JsonElement p)
{
if (!p.TryGetProperty("requestId", out var idElement) || idElement.GetString() is not { } requestId
|| !_inFlight.TryRemove(requestId, out var descriptor))
|| !_inFlight.TryRemove(requestId, out var pending))
{
return;
}
@@ -258,17 +283,19 @@ public sealed class ResponseTap : IAsyncDisposable
if (length > _options.MaxBodyBytes)
{
Interlocked.Increment(ref _skipped);
NotifyDropped(requestId);
return;
}
_queue.Writer.TryWrite(descriptor);
_queue.Writer.TryWrite(pending);
}
private void OnLoadingFailed(JsonElement p)
{
if (p.TryGetProperty("requestId", out var idElement) && idElement.GetString() is { } requestId)
if (p.TryGetProperty("requestId", out var idElement) && idElement.GetString() is { } requestId
&& _inFlight.TryRemove(requestId, out _))
{
_inFlight.TryRemove(requestId, out _);
NotifyDropped(requestId);
}
}
@@ -284,8 +311,16 @@ public sealed class ResponseTap : IAsyncDisposable
_mainFrameId = frame.TryGetProperty("id", out var id) ? id.GetString() : _mainFrameId;
// Requests of the previous document that never finished (e.g. a body the page did not read: Chromium then
// sends no loadingFinished) will not finish any more: forget them.
_inFlight.Clear();
// sends no loadingFinished) will not finish any more: forget them. The new document itself is kept: the frame
// commits it before its body has finished loading (its request id is the frame's loader id).
var loader = frame.TryGetProperty("loaderId", out var l) ? l.GetString() : null;
foreach (var key in _inFlight.Keys)
{
if (key != loader && _inFlight.TryRemove(key, out _))
{
NotifyDropped(key);
}
}
Publish(frame.TryGetProperty("url", out var u) ? u.GetString() : null, sameDocument: false);
}
@@ -325,64 +360,128 @@ public sealed class ResponseTap : IAsyncDisposable
private async Task WorkAsync(CancellationToken ct)
{
await foreach (var descriptor in _queue.Reader.ReadAllAsync(ct).ConfigureAwait(false))
try
{
IResponseConsumer[] consumers;
lock (_gate)
await foreach (var pending in _queue.Reader.ReadAllAsync(ct).ConfigureAwait(false))
{
consumers = [.. _consumers];
try
{
await HandleAsync(pending, ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException || !ct.IsCancellationRequested)
{
// One unexpected body must not stop the capture of the following ones. Only the type: the message
// of a parsing error may quote the body.
_log.Warn($"Cattura: errore imprevisto nella lettura di una risposta ({ex.GetType().Name}).");
NotifyDropped(pending.Descriptor.RequestId);
}
}
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
}
}
if (consumers.Length == 0)
/// <summary>Fetches one body and hands it to the consumers; tells the observers once when nothing reached them.</summary>
private async Task HandleAsync(PendingBody pending, CancellationToken ct)
{
var descriptor = pending.Descriptor;
IResponseConsumer[] consumers;
lock (_gate)
{
consumers = [.. _consumers];
}
if (consumers.Length == 0)
{
NotifyDropped(descriptor.RequestId);
return;
}
byte[]? bytes;
try
{
bytes = await FetchBodyAsync(descriptor.RequestId, ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is CdpCommandException or CdpDisconnectedException or BrowserUnavailableException or TimeoutException)
{
// The body may already be evicted from the browser's buffer, or the page navigated away.
Interlocked.Increment(ref _bodyErrors);
_log.Debug($"Cattura: corpo non disponibile ({ex.GetType().Name}).");
NotifyDropped(descriptor.RequestId);
return;
}
var delivered = bytes is null ? 0
: pending.IsPageDocument ? await ConsumeDocumentAsync(descriptor, bytes, consumers, ct).ConfigureAwait(false)
: await ConsumeBodyAsync(descriptor, bytes, consumers, ct).ConfigureAwait(false);
if (delivered == 0)
{
NotifyDropped(descriptor.RequestId);
}
}
/// <summary>The body of a data response, as one answer. Returns how many answers reached the consumers (0 or 1).</summary>
private async Task<int> ConsumeBodyAsync(ResponseDescriptor descriptor, byte[] bytes, IResponseConsumer[] consumers, CancellationToken ct)
{
JsonDocument document;
try
{
document = JsonDocument.Parse(bytes, BodyOptions);
}
catch (JsonException)
{
// Not JSON after all (e.g. Instagram's «for (;;);» answers of /ajax/, which carry no contents): skipped.
Interlocked.Increment(ref _parseErrors);
return 0;
}
using (document)
{
await DeliverAsync(descriptor, document, consumers, ct).ConfigureAwait(false);
return 1;
}
}
/// <summary>
/// The JSON blocks a page document embeds, each handed to the consumers as an answer of its own with the document's
/// descriptor, so that a pagination stays with the block that carries it
/// (<see cref="DataResponses.EmbeddedJsonBlocks"/>). One block at a time: each is disposed before the next is parsed.
/// Returns how many blocks reached the consumers; a document without any is not data, and not a parse error.
/// </summary>
private async Task<int> ConsumeDocumentAsync(ResponseDescriptor descriptor, byte[] bytes, IResponseConsumer[] consumers, CancellationToken ct)
{
var delivered = 0;
foreach (var block in DataResponses.EmbeddedJsonBlocks(Encoding.UTF8.GetString(bytes)))
{
using (block)
{
continue;
delivered++;
await DeliverAsync(descriptor, block, consumers, ct).ConfigureAwait(false);
}
}
JsonDocument? document;
return delivered;
}
private async Task DeliverAsync(ResponseDescriptor descriptor, JsonDocument body, IResponseConsumer[] consumers, CancellationToken ct)
{
Interlocked.Increment(ref _jsonBodies);
foreach (var consumer in consumers)
{
try
{
document = await FetchBodyAsync(descriptor.RequestId, ct).ConfigureAwait(false);
await consumer.ConsumeAsync(descriptor, body, ct).ConfigureAwait(false);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
catch (Exception ex) when (ex is not OperationCanceledException || !ct.IsCancellationRequested)
{
return;
}
catch (Exception ex) when (ex is CdpCommandException or CdpDisconnectedException or BrowserUnavailableException or TimeoutException)
{
// The body may already be evicted from the browser's buffer, or the page navigated away.
Interlocked.Increment(ref _bodyErrors);
_log.Debug($"Cattura: corpo non disponibile ({ex.GetType().Name}).");
continue;
}
if (document is null)
{
continue;
}
using (document)
{
Interlocked.Increment(ref _jsonBodies);
foreach (var consumer in consumers)
{
try
{
await consumer.ConsumeAsync(descriptor, document, ct).ConfigureAwait(false);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
return;
}
catch (Exception ex)
{
_log.Warn($"Cattura: errore in un lettore ({consumer.GetType().Name}).", ex);
}
}
_log.Warn($"Cattura: errore in un lettore ({consumer.GetType().Name}).", ex);
}
}
}
private async Task<JsonDocument?> FetchBodyAsync(string requestId, CancellationToken ct)
/// <summary>The decoded bytes of a body, or null when the browser gives none or it cannot be decoded.</summary>
private async Task<byte[]?> FetchBodyAsync(string requestId, CancellationToken ct)
{
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
timeout.CancelAfter(_options.BodyTimeout);
@@ -402,34 +501,39 @@ public sealed class ResponseTap : IAsyncDisposable
}
var encoded = result.TryGetProperty("base64Encoded", out var b) && b.ValueKind == JsonValueKind.True;
byte[] bytes;
if (encoded)
if (!encoded)
{
if (!body.TryGetBytesFromBase64(out var decoded))
{
Interlocked.Increment(ref _parseErrors);
return null;
}
bytes = decoded;
}
else
{
bytes = Encoding.UTF8.GetBytes(body.GetString() ?? string.Empty);
return Encoding.UTF8.GetBytes(body.GetString() ?? string.Empty);
}
try
if (!body.TryGetBytesFromBase64(out var decoded))
{
return JsonDocument.Parse(bytes, new JsonDocumentOptions { MaxDepth = 256 });
}
catch (JsonException)
{
// Declared as JSON but it is not (or has a prefix): readers will be told by the probe in M0.
Interlocked.Increment(ref _parseErrors);
return null;
}
return decoded;
}
/// <summary>Tells the observers that a body they may be waiting for will not come.</summary>
private void NotifyDropped(string requestId)
{
foreach (var observer in SnapshotObservers())
{
try
{
observer.OnBodyDropped(requestId);
}
catch (Exception ex)
{
_log.Warn("Cattura: errore in un osservatore delle risposte.", ex);
}
}
}
/// <summary>A body to fetch once its loading has finished.</summary>
private sealed record PendingBody(ResponseDescriptor Descriptor, bool IsPageDocument);
private IResponseObserver[] SnapshotObservers()
{
lock (_gate)