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

+365
View File
@@ -0,0 +1,365 @@
using System.Globalization;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using Febe.Core.Abstractions;
using Febe.Core.Collection;
namespace Febe.Sonda;
/// <summary>What a HAR conversion did: counts only, never a value.</summary>
/// <param name="Entries">Entries of the HAR.</param>
/// <param name="DataResponses">Site answers written because their body is data (<see cref="DataResponses.IsData"/>).</param>
/// <param name="Documents">Page documents that embed JSON: each of their blocks is written as a sample of its own.</param>
/// <param name="DocumentBlocks">Samples written from page documents: one per JSON block they embed, the way Febe's capture
/// hands the blocks to the readers.</param>
/// <param name="OtherHosts">Left out: not an answer of the site (CDN, other sites).</param>
/// <param name="NotData">Left out: files, images, scripts, styles, or a type or status that is not data.</param>
/// <param name="WithoutBody">Left out: the HAR does not hold the body.</param>
/// <param name="NotJson">Left out: a body that is not valid JSON (for example one that starts with <c>for (;;);</c>).</param>
/// <param name="DocumentsWithoutData">Left out: page documents that embed no JSON.</param>
public sealed record HarImportReport(int Entries, int DataResponses, int Documents, int DocumentBlocks, int OtherHosts, int NotData, int WithoutBody, int NotJson, int DocumentsWithoutData)
{
public int Written => DataResponses + DocumentBlocks;
}
/// <summary>
/// Converts a HAR exported from the browser's DevTools (Chrome, Edge) into the probe's RAW format (spec §14.5), so that
/// <c>ripulisci</c> and <c>verifica</c> work on it as on a recording of the probe: flat files <c>NNNNNN-&lt;kind&gt;.json</c>,
/// each <c>{"descrittore":{indirizzo, host, stato, tipo, risorsa, quando}, "corpo": &lt;body&gt;}</c>.
/// </summary>
/// <remarks>
/// It keeps what Febe's own capture keeps (<c>ResponseTap</c>), in the same pieces: site answers whose body is data, and
/// the JSON blocks embedded in page documents, one sample per block with the document's descriptor
/// (<see cref="DataResponses.EmbeddedJsonBlocks"/>). Everything else is left out. Headers, cookies, query strings and
/// request bodies are never copied: the address keeps scheme, host and path only, and of the request body only the
/// GraphQL operation name is read, to name the file, when it has the shape of a name in the site's code (never a path:
/// paths contain user names).
/// The output is still RAW (bodies hold other people's data): it must stay outside any repository.
/// </remarks>
public static partial class HarImporter
{
/// <summary>Request parameter that names the GraphQL operation of a POST (a fixed name in the site's code).</summary>
public const string OperationParameter = "fb_api_req_friendly_name";
private static readonly JsonDocumentOptions BodyOptions = new() { MaxDepth = 256 };
/// <summary>Converts <paramref name="harPath"/> into the new, empty folder <paramref name="rawFolder"/>.</summary>
/// <exception cref="InvalidOperationException">A folder is inside a git repository, or the output folder is not empty.</exception>
/// <exception cref="InvalidDataException">The file is not a HAR.</exception>
public static HarImportReport Import(string harPath, string rawFolder, HostClassifier? hosts = null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(harPath);
ArgumentException.ThrowIfNullOrWhiteSpace(rawFolder);
hosts ??= HostClassifier.Instagram;
var har = Path.GetFullPath(harPath);
if (!File.Exists(har))
{
throw new FileNotFoundException($"Il file HAR non esiste: {har}", har);
}
// The HAR holds cookies and other people's data, and so does the output: neither belongs in a repository.
RepositoryGuard.EnsureOutside(Path.GetDirectoryName(har)!);
var folder = Path.GetFullPath(rawFolder);
RepositoryGuard.EnsureOutside(folder);
if (Directory.Exists(folder) && Directory.EnumerateFileSystemEntries(folder).Any())
{
throw new InvalidOperationException($"La cartella «{folder}» non è vuota: indica una cartella nuova, solo per questa conversione.");
}
JsonDocument document;
try
{
using var stream = File.OpenRead(har);
document = JsonDocument.Parse(stream);
}
catch (JsonException ex)
{
throw new InvalidDataException($"{Path.GetFileName(har)}: non è un file HAR valido (riga {ex.LineNumber + 1}).", ex);
}
using (document)
{
if (document.RootElement.ValueKind != JsonValueKind.Object
|| !document.RootElement.TryGetProperty("log", out var log) || log.ValueKind != JsonValueKind.Object
|| !log.TryGetProperty("entries", out var entries) || entries.ValueKind != JsonValueKind.Array)
{
throw new InvalidDataException($"{Path.GetFileName(har)}: non è un file HAR (manca «log.entries»).");
}
Directory.CreateDirectory(folder);
File.WriteAllText(
Path.Combine(folder, "LEGGIMI.txt"),
"Campioni GREZZI convertiti da un file HAR con «febe-sonda da-har»: contengono dati personali di Alberto e di altre persone.\n"
+ "Non vanno nel repository e non si inviano: si ripuliscono con «febe-sonda ripulisci», si controllano con «febe-sonda verifica»\n"
+ "e si cancellano, insieme al file HAR, quando lettori e mappa sono scritti (specifica §14.5).\n");
int count = 0, written = 0, data = 0, documents = 0, blocks = 0, otherHosts = 0, notData = 0, withoutBody = 0, notJson = 0, documentsWithoutData = 0;
foreach (var entry in entries.EnumerateArray())
{
count++;
var outcome = ConvertEntry(entry, hosts, out var sample);
if (sample is not null)
{
// One block at a time: each is written and disposed before the next one is parsed.
var bodies = 0;
foreach (var body in sample.Bodies)
{
using (body)
{
written++;
Write(Path.Combine(folder, $"{written.ToString("000000", CultureInfo.InvariantCulture)}-{sample.Kind}.json"), sample, body);
}
bodies++;
}
if (outcome == EntryOutcome.Document)
{
blocks += bodies;
outcome = bodies > 0 ? EntryOutcome.Document : EntryOutcome.DocumentWithoutData;
}
}
switch (outcome)
{
case EntryOutcome.Data:
data++;
break;
case EntryOutcome.Document:
documents++;
break;
case EntryOutcome.OtherHost:
otherHosts++;
break;
case EntryOutcome.WithoutBody:
withoutBody++;
break;
case EntryOutcome.NotJson:
notJson++;
break;
case EntryOutcome.DocumentWithoutData:
documentsWithoutData++;
break;
default:
notData++;
break;
}
}
return new HarImportReport(count, data, documents, blocks, otherHosts, notData, withoutBody, notJson, documentsWithoutData);
}
}
/// <summary>
/// The name of the GraphQL operation of a request, when it is one: a word of the site's code (letters and digits,
/// ending in Query, Mutation or Subscription, no run of three digits), the same for everyone. Otherwise null.
/// </summary>
public static string? OperationName(string? value)
{
var name = value?.Trim();
return name is not null && OperationShape().IsMatch(name) && !DigitRun().IsMatch(name) ? name : null;
}
private static EntryOutcome ConvertEntry(JsonElement entry, HostClassifier hosts, out RawSample? sample)
{
sample = null;
if (entry.ValueKind != JsonValueKind.Object
|| !entry.TryGetProperty("request", out var request) || request.ValueKind != JsonValueKind.Object
|| !entry.TryGetProperty("response", out var response) || response.ValueKind != JsonValueKind.Object)
{
return EntryOutcome.NotData;
}
// Chrome's resource types, written as the browser's protocol names them (what ResponseTap sees).
var resource = Text(entry, "_resourceType")?.ToLowerInvariant() switch
{
"xhr" => "XHR",
"fetch" => "Fetch",
"document" => "Document",
_ => null,
};
if (resource is null)
{
return EntryOutcome.NotData;
}
var url = Text(request, "url");
var host = hosts.Classify(url);
if (host != HostKind.Site)
{
return EntryOutcome.OtherHost;
}
var status = response.TryGetProperty("status", out var s) && s.TryGetInt32(out var code) ? code : 0;
var content = response.TryGetProperty("content", out var c) && c.ValueKind == JsonValueKind.Object ? c : default;
var mime = (content.ValueKind == JsonValueKind.Object ? Text(content, "mimeType") : null)?.Split(';')[0].Trim().ToLowerInvariant() ?? string.Empty;
var isData = DataResponses.IsData(mime, resource) && status is >= 200 and < 600 && status != 204;
var isDocument = !isData && resource == "Document" && status is >= 200 and < 300 && DataResponses.IsPageDocument(mime, isMainFrameDocument: true);
if (!isData && !isDocument)
{
return EntryOutcome.NotData;
}
var bytes = Body(content);
if (bytes is null)
{
return EntryOutcome.WithoutBody;
}
var address = UrlSanitizer.Sanitize(url).Url;
var at = When(Text(entry, "startedDateTime"));
if (isDocument)
{
// Only the JSON the page embeds, one block per sample, as Febe's capture hands it to the readers: parsed
// while the samples are written (a document without any becomes DocumentWithoutData there).
sample = new RawSample("documento", address, host, status, mime, resource, at, DataResponses.EmbeddedJsonBlocks(Encoding.UTF8.GetString(bytes)));
return EntryOutcome.Document;
}
JsonDocument body;
try
{
body = JsonDocument.Parse(bytes, BodyOptions);
}
catch (JsonException)
{
return EntryOutcome.NotJson;
}
var kind = resource == "Document" ? "documento" : OperationName(Operation(request)) ?? "risposta";
sample = new RawSample(kind, address, host, status, mime, resource, at, [body]);
return EntryOutcome.Data;
}
/// <summary>The value of <see cref="OperationParameter"/> in a form-encoded request body; nothing else is read.</summary>
private static string? Operation(JsonElement request)
{
if (!request.TryGetProperty("postData", out var post) || post.ValueKind != JsonValueKind.Object)
{
return null;
}
if (post.TryGetProperty("params", out var parameters) && parameters.ValueKind == JsonValueKind.Array)
{
foreach (var parameter in parameters.EnumerateArray())
{
if (parameter.ValueKind == JsonValueKind.Object && Text(parameter, "name") == OperationParameter)
{
return Unescape(Text(parameter, "value"));
}
}
return null;
}
if ((Text(post, "mimeType") ?? string.Empty).Contains("x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase) && Text(post, "text") is { } text)
{
foreach (var pair in text.Split('&'))
{
var equals = pair.IndexOf('=', StringComparison.Ordinal);
if (equals > 0 && Unescape(pair[..equals]) == OperationParameter)
{
return Unescape(pair[(equals + 1)..]);
}
}
}
return null;
}
private static string? Unescape(string? value)
{
if (value is null)
{
return null;
}
try
{
return Uri.UnescapeDataString(value.Replace('+', ' '));
}
catch (UriFormatException)
{
return null;
}
}
private static byte[]? Body(JsonElement content)
{
if (content.ValueKind != JsonValueKind.Object || Text(content, "text") is not { Length: > 0 } text)
{
return null;
}
if (!string.Equals(Text(content, "encoding"), "base64", StringComparison.OrdinalIgnoreCase))
{
return Encoding.UTF8.GetBytes(text);
}
try
{
return Convert.FromBase64String(text);
}
catch (FormatException)
{
return null;
}
}
private static string? When(string? value) =>
DateTimeOffset.TryParse(value, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var at)
? at.UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture)
: null;
private static string? Text(JsonElement element, string property) =>
element.TryGetProperty(property, out var value) && value.ValueKind == JsonValueKind.String ? value.GetString() : null;
/// <summary>The same descriptor the probe writes (<see cref="ProbeRecorder"/>), then the body as it arrived.</summary>
private static void Write(string path, RawSample sample, JsonDocument body)
{
using var stream = new FileStream(path, FileMode.CreateNew, FileAccess.Write);
using var writer = new Utf8JsonWriter(stream, new JsonWriterOptions { MaxDepth = 300 });
writer.WriteStartObject();
writer.WriteStartObject("descrittore");
writer.WriteString("indirizzo", sample.Url);
writer.WriteString("host", sample.Host switch { HostKind.Site => "sito", HostKind.Cdn => "cdn", _ => "altro" });
writer.WriteNumber("stato", sample.Status);
writer.WriteString("tipo", sample.MimeType);
writer.WriteString("risorsa", sample.ResourceType);
if (sample.At is { } at)
{
writer.WriteString("quando", at);
}
else
{
writer.WriteNull("quando");
}
writer.WriteEndObject();
writer.WritePropertyName("corpo");
body.RootElement.WriteTo(writer);
writer.WriteEndObject();
}
// A GraphQL operation name: an identifier of the site's code (e.g. a «...PageQuery»), never free text.
[GeneratedRegex("^[A-Za-z][A-Za-z0-9_]{1,96}(Query|Mutation|Subscription)$", RegexOptions.CultureInvariant)]
private static partial Regex OperationShape();
[GeneratedRegex("[0-9]{3}", RegexOptions.CultureInvariant)]
private static partial Regex DigitRun();
private enum EntryOutcome
{
Data,
Document,
OtherHost,
NotData,
WithoutBody,
NotJson,
DocumentWithoutData,
}
/// <summary>What is written of one entry: its descriptor, and its body (a data answer) or the JSON blocks it embeds (a page document).</summary>
private sealed record RawSample(string Kind, string Url, HostKind Host, int Status, string MimeType, string ResourceType, string? At, IEnumerable<JsonDocument> Bodies);
}
+40
View File
@@ -10,9 +10,11 @@ using Febe.Sonda;
// [--sito <host> --cdn <host>] (solo per provarla sul sito di prova)
// febe-sonda ripulisci --da <grezzi> --a <ripuliti> [--ammessi <ripulitura.json>] [--sito <host> --cdn <host>]
// febe-sonda verifica --grezzi <grezzi> --ripuliti <ripuliti> [--ammessi <ripulitura.json>]
// febe-sonda da-har --har <file .har> --a <cartella nuova fuori dal repository> [--sito <host> --cdn <host>]
return args.Length == 0 ? Usage() : args[0] switch
{
"registra" => await RecordAsync(args[1..]),
"da-har" => FromHar(args[1..]),
"ripulisci" => Sanitize(args[1..]),
"verifica" => Verify(args[1..]),
_ => Usage(),
@@ -25,7 +27,11 @@ static int Usage()
febe-sonda registra --cartella <cartella fuori dal repository> [--display :0 | --xvfb] [--porta 9333] [--chromium <file>] [--no-sandbox]
febe-sonda ripulisci --da <campioni grezzi> --a <campioni ripuliti> [--ammessi <ripulitura.json>]
febe-sonda verifica --grezzi <campioni grezzi> --ripuliti <campioni ripuliti> [--ammessi <ripulitura.json>]
febe-sonda da-har --har <file .har esportato dal browser> --a <cartella nuova fuori dal repository>
La sonda è passiva: apre il browser e registra ciò che la pagina riceve mentre navighi tu. Non compie gesti.
«da-har» converte nello stesso formato grezzo un file HAR esportato dagli strumenti per sviluppatori del browser:
tiene le sole risposte di dati del sito e i dati incorporati nelle pagine; mai intestazioni, cookie, parametri
degli indirizzi o corpi delle richieste. Poi si usano «ripulisci» e «verifica» come per la sonda.
""");
return 2;
}
@@ -109,6 +115,40 @@ static async Task<int> RecordAsync(string[] args)
}
}
static int FromHar(string[] args)
{
var har = Option(args, "--har");
var to = Option(args, "--a");
if (string.IsNullOrWhiteSpace(har) || string.IsNullOrWhiteSpace(to))
{
Console.Error.WriteLine("Indicare --har <file .har> e --a <cartella nuova fuori dal repository>.");
return 2;
}
HarImportReport report;
try
{
report = HarImporter.Import(har, to, Hosts(args));
}
catch (Exception ex) when (ex is InvalidOperationException or InvalidDataException or FileNotFoundException)
{
Console.Error.WriteLine(ex.Message);
return 3;
}
// Counts only: what the answers contain stays on this machine.
Console.WriteLine($"Lette {report.Entries} voci del file HAR; scritti {report.Written} campioni grezzi: {report.DataResponses} risposte di dati del sito, {report.DocumentBlocks} blocchi di dati incorporati in {report.Documents} pagine.");
Console.WriteLine($"Lasciate fuori: {report.OtherHosts} di altri indirizzi (CDN, altri siti), {report.NotData} che non sono dati (file, immagini, script...), {report.WithoutBody} senza corpo, {report.NotJson} non JSON, {report.DocumentsWithoutData} pagine senza dati incorporati.");
if (report.Written == 0 && report.WithoutBody > 0)
{
Console.WriteLine("Il file HAR non contiene i corpi delle risposte: esportalo di nuovo dal pannello Rete con le risposte incluse.");
}
Console.WriteLine($"Campioni grezzi in: {Path.GetFullPath(to)}");
Console.WriteLine("Ora: febe-sonda ripulisci --da <cartella> --a <copia ripulita>, poi febe-sonda verifica.");
return report.Written > 0 ? 0 : 1;
}
static int Sanitize(string[] args)
{
var from = Option(args, "--da");
+16 -2
View File
@@ -21,7 +21,7 @@ public sealed record SanitizeReport(int Files, int Lines, int ReplacedStrings, i
/// sensitive run of any raw sample (it is drawn again). Fake letters are consonants only, so they cannot spell the
/// words of a caption. The browser profile folder of the probe is never read.
/// </remarks>
public sealed class SampleSanitizer
public sealed partial class SampleSanitizer
{
/// <summary>The probe's browser profile: holds the session, never part of the samples.</summary>
public const string BrowserProfileFolder = "profilo-browser";
@@ -188,12 +188,26 @@ public sealed class SampleSanitizer
}
_strings++;
return JsonValue.Create(Fake(text, "s"));
return JsonValue.Create(LooksLikeSecretKey(key) ? Filler(text) : Fake(text, "s"));
default:
return JsonValue.Create(element);
}
}
/// <summary>
/// True for the keys under which a site keeps tokens and keys of its own (Instagram: «organic_tracking_token»,
/// «rank_token», «client_cache_key»). Their fakes would look like real secrets to a secret scanner (gitleaks in the
/// CI): they get a neutral filler of the same shape instead.
/// </summary>
internal static bool LooksLikeSecretKey(string? key) => key is not null && SecretKey().IsMatch(key);
/// <summary>Letters become «x», digits «7», symbols «·»: the shape stays, nothing of the value and no entropy.</summary>
private static string Filler(string text) =>
new([.. text.Select(c => char.IsLetter(c) ? 'x' : char.IsDigit(c) ? '7' : char.IsSurrogate(c) || char.IsSymbol(c) ? '·' : c)]);
[System.Text.RegularExpressions.GeneratedRegex("token|secret|passw|credential|cookie|csrf|session|signature|auth|key", System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.CultureInvariant)]
private static partial System.Text.RegularExpressions.Regex SecretKey();
private string FakeKey(string key)
{
_keys++;
+2 -2
View File
@@ -18,8 +18,8 @@
"keys": ["type", "*_type", "status", "tipo", "stato", "risorsa", "host", "role", "tag", "evento"]
},
"date": {
"note": "Date: si tengono i numeri e i testi che hanno la forma di una data. taken_at è uno degli indizi di §6.4.",
"keys": ["taken_at", "*_at", "pubblicato", "scade", "ultima_storia", "quando"]
"note": "Date: si tengono i numeri e i testi che hanno la forma di una data. taken_at è uno degli indizi di §6.4; latest_reel_media è la data dell'ultima storia di un profilo (campioni del 21/10/2026).",
"keys": ["taken_at", "*_at", "latest_reel_media", "pubblicato", "scade", "ultima_storia", "quando"]
}
}
}
+33
View File
@@ -0,0 +1,33 @@
# Raccolta dei bersagli dal browser di tutti i giorni
`raccogli-bersagli.js` serve a compilare i **bersagli** di `src/Febe.Core/Config/bersagli.instagram.json` (ipotesi
H11): l'anello delle storie, la zona «avanti» e la X del visualizzatore, le schede del profilo, le raccolte in evidenza.
Si usa come spiegato in `docs/prove-dal-vivo.md`, parte **A bis**.
## Come si usa
1. Nel browser con cui navighi di solito, già entrato nel sito, apri gli strumenti per sviluppatori (F12) e la scheda
**Console**.
2. Incolla tutto il contenuto di `raccogli-bersagli.js` e premi Invio. Compare «Febe: raccolta dei bersagli attiva».
Se la pagina si ricarica del tutto, la raccolta si perde: incollalo di nuovo.
3. Naviga e clicca come al solito. A ogni clic la Console scrive «Febe: clic N registrato».
4. Alla fine scrivi `febeBersagli()` nella Console: copia negli appunti i clic registrati (se la copia non riesce, li
scrive nella Console e li copi da lì).
## Che cosa fa e che cosa non fa
- **Sola lettura.** Aggiunge un solo ascoltatore dei clic, che non blocca e non cambia il clic, e legge attributi.
Non modifica la pagina, non manda nulla a nessuno, non legge cookie né le memorie del browser. I dati restano nella
memoria della scheda finché non chiami `febeBersagli()`.
- Per ogni clic registra la forma dell'indirizzo prima e circa 1,5 secondi dopo, e del comando cliccato (il più vicino
fra collegamento, pulsante, elemento con un ruolo o con `tabindex`): elemento, ruolo, `aria-label`, `alt`, `title`, il
testo (solo per pulsanti, collegamenti, schede e simili), il **nome accessibile calcolato come lo calcola Febe**
(`src/Febe.Browser/Targets/TargetResolver.cs`), se il nome viene da un'icona `svg` con `aria-label`, la forma del
collegamento, e quanti elementi visibili hanno lo stesso ruolo e lo stesso nome (con la posizione di quello cliccato).
- La voce `perLaMappa` è già nella forma dei campi `role`, `name`, `href` e `index` della mappa.
- **Nomi.** Negli indirizzi restano solo le parole fisse (`stories`, `highlights`, `p`, `reel`, `reels`, `tagged`,
`following`, `followers`, `explore`); ogni altro pezzo diventa `<x>`. Nei testi registrati, i nomi visti negli
indirizzi e ogni `@parola` diventano `NOME`. I nomi scritti per esteso (per esempio «Mario Rossi») **non** si
riconoscono: prima di inviare il testo, sostituisci a mano con `NOME` ogni nome di persona rimasto.
- Un nome utente che è anche una parola dell'interfaccia può far diventare `NOME` anche quella parola: va bene così,
meglio un nome di comando in meno che un nome di persona in più.
+258
View File
@@ -0,0 +1,258 @@
// Febe: targets from the everyday browser (docs/prove-dal-vivo.md, part «A bis»; hypothesis H11).
//
// Paste it in the Console of the browser's DevTools, with the site open and already logged in, then browse by hand.
// For every click it records the shape of the address before and about 1.5 s after, and the attributes of the clicked
// command that Febe's target map uses (src/Febe.Core/Config/bersagli.<sito>.json): role, accessible name computed as
// src/Febe.Browser/Targets/TargetResolver.cs computes it, link shape. At the end, febeBersagli() copies the records.
//
// READ-ONLY with respect to the page: one capturing click listener that never blocks or changes the click, and
// attribute reads. It never changes the DOM, never sends anything anywhere, never reads cookies or the browser's
// storage. Records stay in this tab's memory; reloading the page drops them (paste it again after a reload).
// Address segments that are not fixed words become «<x>»; user names seen in the addresses and @words become «NOME».
(() => {
'use strict';
if (typeof globalThis.febeBersagli === 'function') {
console.log('Febe: la raccolta dei bersagli è già attiva. febeBersagli() copia ciò che è stato registrato.');
return;
}
const FIXED = new Set(['stories', 'highlights', 'p', 'reel', 'reels', 'tagged', 'following', 'followers', 'explore']);
const MAX_TEXT = 80;
const records = [];
const names = new Set();
// Same as TargetResolver.cs: collapsed whitespace.
const clean = (s) => (s || '').replace(/\s+/g, ' ').trim();
// The shape of a path: fixed words stay, every other segment becomes «<x>». The segments that are not fixed words
// are kept aside (in memory only) to mask them in the recorded texts.
const shapeOf = (path) => {
if (typeof path !== 'string') return null;
return path.split('/').map((segment) => {
if (segment === '' || FIXED.has(segment.toLowerCase())) return segment;
let decoded = segment;
try { decoded = decodeURIComponent(segment); } catch { /* keep it as it is */ }
if (decoded.length >= 2) names.add(decoded.toLowerCase());
return '<x>';
}).join('/');
};
// Same as TargetResolver.cs roleOf: explicit role first, then the implicit role of the tag.
const roleOf = (el) => {
const explicit = clean(el.getAttribute('role')).split(' ')[0];
if (explicit) return explicit.toLowerCase();
const tag = el.tagName.toLowerCase();
const type = (el.getAttribute('type') || '').toLowerCase();
switch (tag) {
case 'a': case 'area': return el.hasAttribute('href') ? 'link' : '';
case 'button': return 'button';
case 'input':
if (['button', 'submit', 'reset', 'image'].includes(type)) return 'button';
if (type === 'checkbox') return 'checkbox';
if (type === 'radio') return 'radio';
if (type === 'search') return 'searchbox';
if (['', 'text', 'email', 'tel', 'url', 'password'].includes(type)) return 'textbox';
return '';
case 'textarea': return 'textbox';
case 'select': return 'combobox';
case 'img': return el.getAttribute('alt') === '' ? 'presentation' : 'img';
case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6': return 'heading';
case 'nav': return 'navigation';
case 'main': return 'main';
case 'dialog': return 'dialog';
case 'article': return 'article';
case 'ul': case 'ol': return 'list';
case 'li': return 'listitem';
case 'section': return (el.hasAttribute('aria-label') || el.hasAttribute('aria-labelledby')) ? 'region' : '';
default: return '';
}
};
// Same as TargetResolver.cs textOf: a child's aria-label stands for its subtree, aria-hidden children are skipped.
const textOf = (node, depth) => {
if (depth > 25) return '';
let out = '';
for (const child of node.childNodes) {
if (child.nodeType === 3) { out += child.nodeValue + ' '; continue; }
if (child.nodeType !== 1) continue;
if (child.getAttribute('aria-hidden') === 'true') continue;
const label = clean(child.getAttribute('aria-label'));
if (label) { out += label + ' '; continue; }
const tag = child.tagName.toLowerCase();
if (tag === 'img') { out += (child.getAttribute('alt') || '') + ' '; continue; }
if (tag === 'script' || tag === 'style' || tag === 'template') continue;
out += textOf(child, depth + 1) + ' ';
}
return out;
};
// Roles named from their content (TargetResolver.cs fromContent): only these get their text recorded.
const fromContent = new Set(['button', 'link', 'tab', 'menuitem', 'heading', 'cell', 'gridcell', 'option',
'checkbox', 'radio', 'switch', 'listitem', 'treeitem', 'columnheader', 'rowheader', 'tooltip']);
// Same as TargetResolver.cs nameOf: the accessible name the «name» field of the map is matched against.
const nameOf = (el, role) => {
const ids = clean(el.getAttribute('aria-labelledby'));
if (ids) {
const joined = clean(ids.split(' ').map((id) => document.getElementById(id)).filter(Boolean).map((e) => e.textContent).join(' '));
if (joined) return joined;
}
const aria = clean(el.getAttribute('aria-label'));
if (aria) return aria;
const tag = el.tagName.toLowerCase();
const type = (el.getAttribute('type') || '').toLowerCase();
if (tag === 'img' || (tag === 'input' && type === 'image')) {
const alt = clean(el.getAttribute('alt'));
if (alt) return alt;
}
if (tag === 'input' && ['button', 'submit', 'reset'].includes(type)) {
const label = clean(el.getAttribute('value'));
if (label) return label;
}
if (fromContent.has(role)) {
const text = clean(textOf(el, 0));
if (text) return text;
}
return clean(el.getAttribute('title') || el.getAttribute('placeholder'));
};
const visible = (el) => {
const r = el.getBoundingClientRect();
if (!(r.width > 0 && r.height > 0)) return false;
return typeof el.checkVisibility === 'function' ? el.checkVisibility({ opacityProperty: true, visibilityProperty: true }) : true;
};
// Like ProbeRecorder.cs: the path of a link and whether it stays on the site, never the host of another site.
const linkOf = (el) => {
const href = el.getAttribute('href');
if (!href) return null;
try {
const u = new URL(href, document.baseURI);
return { sito: u.origin === location.origin, path: shapeOf(u.pathname) };
} catch { return null; }
};
const escapeRegex = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
// User names seen in any recorded address, and every @word, become «NOME»; texts are cut to 80 characters.
const mask = (text) => {
if (text === null || text === undefined) return null;
let out = clean(String(text)).replace(/@[\p{L}\p{N}._]+/gu, 'NOME');
for (const name of names) {
out = out.replace(new RegExp('(^|[^\\p{L}\\p{N}_])' + escapeRegex(name) + '(?![\\p{L}\\p{N}_])', 'giu'), '$1NOME');
}
return out.length > MAX_TEXT ? out.slice(0, MAX_TEXT) : out;
};
const describe = (el, inner) => {
const role = roleOf(el);
const name = nameOf(el, role);
const svg = el.querySelector('svg[aria-label]');
const svgLabel = svg ? clean(svg.getAttribute('aria-label')) : '';
let same = null;
let position = null;
if (role) {
// How many visible elements share role and name, and which one this is: the «index» field of the map.
same = 0;
for (const other of document.querySelectorAll('*')) {
if (roleOf(other) !== role || nameOf(other, role) !== name || !visible(other)) continue;
if (other === el) position = same;
same++;
}
}
return {
tag: el.tagName.toLowerCase(),
interno: inner && inner !== el && inner.tagName ? inner.tagName.toLowerCase() : null,
roleAttributo: el.getAttribute('role'),
ruolo: role,
ariaLabel: el.getAttribute('aria-label'),
alt: el.getAttribute('alt'),
titolo: el.getAttribute('title'),
testo: fromContent.has(role) ? clean(el.textContent) : null,
nome: name,
svg: svgLabel || null,
nomeDaSvg: !!svgLabel && !clean(el.getAttribute('aria-label')) && name === clean(textOf(el, 0)) && name.includes(svgLabel),
collegamento: linkOf(el),
tabindex: el.getAttribute('tabindex'),
uguali: same,
posizione: position,
};
};
const onClick = (event) => {
try {
const inner = event.target && event.target.nodeType === 1 ? event.target : null;
const el = inner && inner.closest ? inner.closest('a[href], button, [role], [tabindex]') : null;
const record = {
n: records.length + 1,
ora: new Date().toTimeString().slice(0, 8),
prima: shapeOf(location.pathname),
dopo: null,
elemento: el ? describe(el, inner) : null,
};
records.push(record);
setTimeout(() => {
try { record.dopo = shapeOf(location.pathname); } catch { /* the record stays without it */ }
}, 1500);
console.log(`Febe: clic ${record.n} registrato${el ? '' : ' (nessun comando sotto il puntatore)'}.`);
} catch {
// Never disturb the page: a click that cannot be described is just not recorded.
}
};
document.addEventListener('click', onClick, { capture: true, passive: true });
// The records, masked, ready for bersagli.<sito>.json: «<x>» becomes «*» (one segment), «NOME» becomes «.+».
const output = () => records.map((r) => {
const e = r.elemento;
if (!e) return { n: r.n, ora: r.ora, prima: r.prima, dopo: r.dopo, elemento: null };
const element = {
...e,
roleAttributo: mask(e.roleAttributo),
ariaLabel: mask(e.ariaLabel),
alt: mask(e.alt),
titolo: mask(e.titolo),
testo: mask(e.testo),
nome: mask(e.nome),
svg: mask(e.svg),
};
const name = element.nome ? '^' + escapeRegex(element.nome).replace(/NOME/g, '.+') + '$' : '';
return {
n: r.n,
ora: r.ora,
prima: r.prima,
dopo: r.dopo,
elemento: element,
perLaMappa: {
role: e.ruolo,
name,
href: e.collegamento && e.collegamento.sito ? e.collegamento.path.replace(/<x>/g, '*') : '',
index: e.posizione,
},
};
});
// copy() is a utility of the DevTools Console, there while the Console runs a command: kept from the paste too.
const copier = typeof copy === 'function' ? copy : null;
globalThis.febeBersagli = () => {
const text = JSON.stringify(output(), null, 2);
let copied = true;
if (typeof copy === 'function') {
copy(text);
} else if (copier) {
copier(text);
} else {
copied = false;
}
if (copied) {
console.log(`Febe: copiati negli appunti ${records.length} clic registrati. Incollali in un file di testo e controlla che non resti nessun nome.`);
} else {
console.log(text);
console.log(`Febe: ${records.length} clic registrati, scritti qui sopra: copiali da qui.`);
}
return records.length;
};
console.log('Febe: raccolta dei bersagli attiva (sola lettura). Naviga come al solito; alla fine scrivi febeBersagli().');
})();