Raccolta (M0/M2): sito di prova completo, lettori per forma, ricette su browser vero, coda degli scaricamenti, sonda con ripulitura e verifica; documenti delle ipotesi e delle prove dal vivo

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
Claude committed 2026-10-13 17:32:35 +00:00
1 parent e2c987873b
commit 4fc5a6c0d4
74 files changed
+12689 -13

No files matched your search

+4
View File
@@ -10,6 +10,10 @@
<ProjectReference Include="..\..\src\Febe.Core\Febe.Core.csproj" />
<ProjectReference Include="..\..\src\Febe.Browser\Febe.Browser.csproj" />
</ItemGroup>
<ItemGroup>
<!-- Elenco di ciò che la ripulitura lascia com'è: incorporato, sostituibile con l'opzione «ammessi». -->
<EmbeddedResource Include="ripulitura.json" LogicalName="Febe.Sonda.ripulitura.json" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="Febe.Tests" />
</ItemGroup>
+272
View File
@@ -0,0 +1,272 @@
using System.Globalization;
using System.Text.Json;
using System.Text.Json.Nodes;
using Febe.Browser.Capture;
using Febe.Browser.Cdp;
using Febe.Core.Abstractions;
using Febe.Core.Collection;
namespace Febe.Sonda;
/// <summary>Refuses sample folders inside a git repository (spec §14.5: raw samples stay outside the repository).</summary>
public static class RepositoryGuard
{
/// <summary>The repository that contains <paramref name="folder"/> (its root), or null.</summary>
public static string? FindRepository(string folder)
{
var current = new DirectoryInfo(Path.GetFullPath(folder));
while (current is not null)
{
var marker = Path.Combine(current.FullName, ".git");
if (Directory.Exists(marker) || File.Exists(marker))
{
return current.FullName;
}
current = current.Parent;
}
return null;
}
/// <exception cref="InvalidOperationException">The folder is inside a repository.</exception>
public static void EnsureOutside(string folder)
{
if (FindRepository(folder) is { } repository)
{
throw new InvalidOperationException(
$"La cartella «{Path.GetFullPath(folder)}» sta dentro un repository git ({repository}): i campioni grezzi contengono dati di altre persone e devono stare fuori dal repository (specifica §14.5). Scegli un'altra cartella.");
}
}
}
/// <summary>Counters of a recording.</summary>
public sealed record ProbeStats(int Responses, int Navigations, int Interactions);
/// <summary>
/// The passive probe of M0 (spec §14.5): while Alberto browses by hand, it stores every JSON response the page receives
/// (sanitized descriptor + body) and, for the elements he hovers and focuses, the attributes useful to the target map
/// (role, accessible name, aria-label, link shape), read with a read-only <c>Runtime.evaluate</c> polled every few
/// hundred milliseconds. It never navigates and never performs a gesture: no <c>Input.*</c> command is ever sent.
/// </summary>
/// <remarks>Raw files: <c>risposte/NNNNNN.json</c>, <c>navigazioni.jsonl</c>, <c>interazioni.jsonl</c>.</remarks>
public sealed class ProbeRecorder : IResponseConsumer, IResponseObserver, IAsyncDisposable
{
/// <summary>Read-only description of the hovered and focused interactive elements.</summary>
internal const string InteractionScript = """
(() => {
const clean = (s) => (s || '').replace(/\s+/g, ' ').trim().slice(0, 160);
const interactive = (el) => el && el.closest ? el.closest('a[href], button, [role], input, textarea, select, summary, [tabindex]') : null;
const shape = (href) => {
try {
const u = new URL(href, document.baseURI);
return { host: u.host, path: u.pathname };
} catch { return null; }
};
const describe = (el) => {
if (!el || el === document.body || el === document.documentElement) return null;
const link = el.getAttribute('href');
return {
tag: el.tagName.toLowerCase(),
role: clean(el.getAttribute('role')),
ariaLabel: clean(el.getAttribute('aria-label')),
name: clean(el.getAttribute('aria-label') || el.getAttribute('alt') || el.getAttribute('title') || el.textContent),
href: link ? shape(link) : null,
type: clean(el.getAttribute('type')),
};
};
const hovered = document.querySelectorAll(':hover');
return {
path: location.pathname,
hover: describe(interactive(hovered.length ? hovered[hovered.length - 1] : null)),
focus: describe(interactive(document.activeElement)),
};
})()
""";
private readonly ICdpSession _cdp;
private readonly HostClassifier _hosts;
private readonly IClock _clock;
private readonly string _folder;
private readonly TimeSpan _pollEvery;
private readonly SemaphoreSlim _write = new(1, 1);
private readonly CancellationTokenSource _stop = new();
private ResponseTap? _tap;
private Task? _poller;
private int _responses;
private int _navigations;
private int _interactions;
private string? _lastHover;
private string? _lastFocus;
public ProbeRecorder(ICdpSession cdp, HostClassifier hosts, string folder, IClock? clock = null, TimeSpan? pollEvery = null)
{
_cdp = cdp ?? throw new ArgumentNullException(nameof(cdp));
_hosts = hosts ?? throw new ArgumentNullException(nameof(hosts));
_folder = Path.GetFullPath(folder);
_clock = clock ?? new SystemClock();
_pollEvery = pollEvery ?? TimeSpan.FromMilliseconds(400);
}
public string Folder => _folder;
public ProbeStats Stats => new(Volatile.Read(ref _responses), Volatile.Read(ref _navigations), Volatile.Read(ref _interactions));
public async Task StartAsync(CancellationToken ct = default)
{
RepositoryGuard.EnsureOutside(_folder);
Directory.CreateDirectory(Path.Combine(_folder, "risposte"));
await File.WriteAllTextAsync(
Path.Combine(_folder, "LEGGIMI.txt"),
"Campioni GREZZI della sonda di Febe: 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 alla fine di M0 (specifica §14.5).\n",
ct).ConfigureAwait(false);
_tap = new ResponseTap(_cdp, _hosts, _clock);
_tap.AddConsumer(this);
_tap.AddObserver(this);
await _tap.StartAsync(ct).ConfigureAwait(false);
_poller = Task.Run(() => PollAsync(_stop.Token), CancellationToken.None);
}
public async Task StopAsync()
{
await _stop.CancelAsync().ConfigureAwait(false);
if (_poller is not null)
{
try
{
await _poller.ConfigureAwait(false);
}
catch (OperationCanceledException)
{
}
}
if (_tap is not null)
{
await _tap.DisposeAsync().ConfigureAwait(false);
_tap = null;
}
}
public async ValueTask DisposeAsync()
{
await StopAsync().ConfigureAwait(false);
_stop.Dispose();
_write.Dispose();
}
async ValueTask IResponseConsumer.ConsumeAsync(ResponseDescriptor response, JsonDocument body, CancellationToken ct)
{
var number = Interlocked.Increment(ref _responses);
var sample = new JsonObject
{
["descrittore"] = new JsonObject
{
["indirizzo"] = response.Url,
["host"] = response.HostKind switch { HostKind.Site => "sito", HostKind.Cdn => "cdn", _ => "altro" },
["stato"] = response.Status,
["tipo"] = response.MimeType,
["risorsa"] = response.ResourceType,
["quando"] = response.At.UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture),
},
["corpo"] = JsonNode.Parse(body.RootElement.GetRawText()),
};
var file = Path.Combine(_folder, "risposte", number.ToString("000000", CultureInfo.InvariantCulture) + ".json");
await File.WriteAllTextAsync(file, sample.ToJsonString(), ct).ConfigureAwait(false);
}
void IResponseObserver.OnResponse(ResponseDescriptor response)
{
}
void IResponseObserver.OnNavigation(NavigationDescriptor navigation)
{
Interlocked.Increment(ref _navigations);
var line = new JsonObject
{
["quando"] = navigation.At.UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture),
["indirizzo"] = navigation.Url,
["host"] = navigation.HostKind switch { HostKind.Site => "sito", HostKind.Cdn => "cdn", _ => "altro" },
["stesso_documento"] = navigation.SameDocument,
};
_ = AppendLineAsync("navigazioni.jsonl", line);
}
private async Task PollAsync(CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
try
{
var state = await _cdp.EvaluateAsync(InteractionScript, ct).ConfigureAwait(false);
if (state.ValueKind == JsonValueKind.Object)
{
_lastHover = await RecordAsync(state, "hover", "sopra", _lastHover).ConfigureAwait(false);
_lastFocus = await RecordAsync(state, "focus", "fuoco", _lastFocus).ConfigureAwait(false);
}
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
return;
}
catch (Exception ex) when (ex is CdpCommandException or CdpEvaluationException or CdpDisconnectedException or BrowserUnavailableException or TimeoutException)
{
// Page changing or browser restarting: try again at the next tick.
}
await _clock.Delay(_pollEvery, ct).ConfigureAwait(false);
}
}
/// <summary>Writes a line when the described element changed; returns the new «last seen» value.</summary>
private async Task<string?> RecordAsync(JsonElement state, string property, string kind, string? last)
{
if (!state.TryGetProperty(property, out var element) || element.ValueKind != JsonValueKind.Object)
{
return null;
}
var raw = element.GetRawText();
if (raw == last)
{
return last;
}
Interlocked.Increment(ref _interactions);
var node = JsonNode.Parse(raw)!.AsObject();
if (node["href"] is JsonObject href && href["host"]?.GetValue<string>() is { } linkHost)
{
// Only whether the link stays on the site: the host of an external link may say something about a person.
href["host"] = _hosts.Classify($"https://{linkHost}/") switch { HostKind.Site => "sito", HostKind.Cdn => "cdn", _ => "altro" };
}
var line = new JsonObject
{
["quando"] = _clock.Now.UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture),
["evento"] = kind,
["percorso"] = state.TryGetProperty("path", out var path) ? path.GetString() : null,
["elemento"] = node,
};
await AppendLineAsync("interazioni.jsonl", line).ConfigureAwait(false);
return raw;
}
private async Task AppendLineAsync(string name, JsonObject line)
{
await _write.WaitAsync().ConfigureAwait(false);
try
{
await File.AppendAllTextAsync(Path.Combine(_folder, name), line.ToJsonString() + "\n").ConfigureAwait(false);
}
catch (ObjectDisposedException)
{
}
finally
{
_write.Release();
}
}
}
+171 -2
View File
@@ -1,2 +1,171 @@
// Passive probe (spec §14.5). Filled in by milestone M0.
Console.WriteLine("febe-sonda");
using System.Globalization;
using Febe.Browser.Diagnostics;
using Febe.Browser.Hosting;
using Febe.Core.Abstractions;
using Febe.Core.Collection;
using Febe.Sonda;
// Passive probe of M0 (spec §14.5).
// febe-sonda registra --cartella <fuori dal repository> [--display :0 | --xvfb] [--porta 9333] [--chromium <file>] [--no-sandbox]
// [--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>]
return args.Length == 0 ? Usage() : args[0] switch
{
"registra" => await RecordAsync(args[1..]),
"ripulisci" => Sanitize(args[1..]),
"verifica" => Verify(args[1..]),
_ => Usage(),
};
static int Usage()
{
Console.Error.WriteLine("""
Uso:
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>]
La sonda è passiva: apre il browser e registra ciò che la pagina riceve mentre navighi tu. Non compie gesti.
""");
return 2;
}
static async Task<int> RecordAsync(string[] args)
{
var folder = Option(args, "--cartella");
if (string.IsNullOrWhiteSpace(folder))
{
Console.Error.WriteLine("Indicare --cartella <cartella fuori dal repository>.");
return 2;
}
try
{
RepositoryGuard.EnsureOutside(folder);
}
catch (InvalidOperationException ex)
{
Console.Error.WriteLine(ex.Message);
return 3;
}
var log = new DelegateBrowserLog((level, message, _) =>
{
if (level >= BrowserLogLevel.Warning)
{
Console.Error.WriteLine(message);
}
});
XvfbProcess? xvfb = null;
var display = Option(args, "--display");
if (args.Contains("--xvfb"))
{
display = XvfbProcess.FindFreeDisplay() ?? throw new InvalidOperationException("Nessun display libero per Xvfb.");
xvfb = new XvfbProcess(display, 1280, 900, log: log);
await xvfb.StartAsync(CancellationToken.None);
Console.WriteLine($"Xvfb avviato su {display}: il browser non è visibile da qui (serve la vista remota di Febe o un display vero con --display).");
}
var hosts = Hosts(args);
var profile = Path.Combine(Path.GetFullPath(folder), SampleSanitizer.BrowserProfileFolder);
var host = new ChromiumProcessHost(new ChromiumLaunchOptions { NoSandbox = args.Contains("--no-sandbox") }, log: log);
try
{
await host.StartAsync(
new BrowserOptions(profile, 1280, 900, int.TryParse(Option(args, "--porta"), NumberStyles.Integer, CultureInfo.InvariantCulture, out var port) ? port : 9333, Option(args, "--chromium"), display),
CancellationToken.None);
await using var recorder = new ProbeRecorder(host.Cdp, hosts, folder);
await recorder.StartAsync();
Console.WriteLine($"""
Sonda in ascolto. Campioni grezzi in: {recorder.Folder}
Accedi e naviga a mano nella finestra del browser seguendo docs/prove-dal-vivo.md.
La sonda non compie gesti e non apre pagine da sola. Premi Invio (o Ctrl+C) per terminare.
""");
var stop = new TaskCompletionSource();
Console.CancelKeyPress += (_, e) =>
{
e.Cancel = true;
stop.TrySetResult();
};
_ = Task.Run(() =>
{
Console.ReadLine();
stop.TrySetResult();
});
await stop.Task;
await recorder.StopAsync();
var stats = recorder.Stats;
Console.WriteLine($"Registrate {stats.Responses} risposte, {stats.Navigations} navigazioni, {stats.Interactions} interazioni.");
Console.WriteLine("Ora: febe-sonda ripulisci --da <cartella> --a <copia ripulita>, poi febe-sonda verifica.");
return 0;
}
finally
{
await host.DisposeAsync();
if (xvfb is not null)
{
await xvfb.DisposeAsync();
}
}
}
static int Sanitize(string[] args)
{
var from = Option(args, "--da");
var to = Option(args, "--a");
if (string.IsNullOrWhiteSpace(from) || string.IsNullOrWhiteSpace(to))
{
Console.Error.WriteLine("Indicare --da <campioni grezzi> e --a <campioni ripuliti>.");
return 2;
}
var allowlist = Option(args, "--ammessi") is { } path ? SanitizerAllowlist.Load(path) : SanitizerAllowlist.Default;
var report = new SampleSanitizer(allowlist, Hosts(args)).SanitizeFolder(from, to);
Console.WriteLine($"Ripuliti {report.Files} file ({report.Lines} righe): {report.ReplacedStrings} testi, {report.ReplacedNumbers} numeri, {report.ReplacedKeys} chiavi, {report.Addresses} indirizzi sostituiti.");
var verify = SampleVerifier.Verify(from, to, allowlist);
Console.WriteLine(verify.Passed ? "Verifica superata." : $"Verifica NON superata: {verify.Leaks.Count} frammenti sopravvissuti.");
return verify.Passed ? 0 : 1;
}
static int Verify(string[] args)
{
var raw = Option(args, "--grezzi");
var clean = Option(args, "--ripuliti");
if (string.IsNullOrWhiteSpace(raw) || string.IsNullOrWhiteSpace(clean))
{
Console.Error.WriteLine("Indicare --grezzi <campioni grezzi> e --ripuliti <campioni ripuliti>.");
return 2;
}
var allowlist = Option(args, "--ammessi") is { } path ? SanitizerAllowlist.Load(path) : SanitizerAllowlist.Default;
var report = SampleVerifier.Verify(raw, clean, allowlist);
Console.WriteLine($"Grezzi: {report.RawFiles} file; ripuliti: {report.CleanFiles}; frammenti controllati: {report.CheckedTokens}.");
foreach (var missing in report.MissingCleanFiles)
{
Console.WriteLine($"Manca la copia ripulita di {missing}.");
}
foreach (var leak in report.Leaks)
{
// Where, never what: the value itself stays on this machine.
Console.WriteLine($"Sopravvive un frammento di {leak.Length} {leak.Kind} in {leak.CleanFile}.");
}
Console.WriteLine(report.Passed ? "Verifica superata: nessun valore dei grezzi sopravvive fuori dall'elenco ammesso." : "Verifica NON superata.");
return report.Passed ? 0 : 1;
}
static HostClassifier Hosts(string[] args)
{
var site = Option(args, "--sito");
var cdn = Option(args, "--cdn");
return site is null && cdn is null
? HostClassifier.Instagram
: new HostClassifier((site ?? string.Empty).Split(',', StringSplitOptions.RemoveEmptyEntries), (cdn ?? string.Empty).Split(',', StringSplitOptions.RemoveEmptyEntries));
}
static string? Option(string[] args, string name)
{
var index = Array.IndexOf(args, name);
return index >= 0 && index + 1 < args.Length ? args[index + 1] : null;
}
+369
View File
@@ -0,0 +1,369 @@
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using Febe.Core.Collection;
namespace Febe.Sonda;
/// <summary>What a cleaning run did.</summary>
public sealed record SanitizeReport(int Files, int Lines, int ReplacedStrings, int ReplacedNumbers, int ReplacedKeys, int Addresses);
/// <summary>
/// Cleans raw probe samples by allowlist (spec §14.5): structure and keys stay; every string and every long number
/// becomes a fake value of the same shape (letters for letters, digits for digits, punctuation kept), except the short
/// list of fields that say nothing about a person (<see cref="SanitizerAllowlist"/>); keys that look like identifiers
/// are replaced too; addresses keep only «site or CDN» and the file extension.
/// </summary>
/// <remarks>
/// Equal values get equal fakes within a run (relations between responses survive), and a fake never contains a
/// 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
{
/// <summary>The probe's browser profile: holds the session, never part of the samples.</summary>
public const string BrowserProfileFolder = "profilo-browser";
private const string Consonants = "bcdfghjklmnpqrstvwxz";
/// <summary>
/// File extensions an address may keep. Only known file types: the last segment of a page address may be a user
/// name with a dot («nome.cognome»), and its «extension» would leak part of it.
/// </summary>
private static readonly HashSet<string> FileExtensions = new(StringComparer.Ordinal)
{
"jpg", "jpeg", "png", "webp", "heic", "heif", "gif", "avif", "mp4", "m4v", "mov", "webm", "m4a", "mp3", "aac",
"m3u8", "mpd", "ts", "json", "js", "css", "html", "htm", "txt", "xml", "svg", "ico", "woff", "woff2",
};
private readonly SanitizerAllowlist _allowlist;
private readonly HostClassifier _hosts;
private readonly byte[] _key;
private readonly Dictionary<string, string> _fakes = new(StringComparer.Ordinal);
private HashSet<string> _sensitive = new(StringComparer.Ordinal);
private int[] _lengths = [];
private int _strings;
private int _numbers;
private int _keys;
private int _addresses;
public SampleSanitizer(SanitizerAllowlist? allowlist = null, HostClassifier? hosts = null, byte[]? key = null)
{
_allowlist = allowlist ?? SanitizerAllowlist.Default;
_hosts = hosts ?? HostClassifier.Instagram;
_key = key ?? RandomNumberGenerator.GetBytes(32);
}
/// <summary>Raw sample files of a folder: *.json and *.jsonl, outside the browser profile.</summary>
public static IReadOnlyList<string> SampleFiles(string folder) =>
[.. Directory.EnumerateFiles(folder, "*.*", SearchOption.AllDirectories)
.Where(f => f.EndsWith(".json", StringComparison.OrdinalIgnoreCase) || f.EndsWith(".jsonl", StringComparison.OrdinalIgnoreCase))
.Where(f => !Path.GetRelativePath(folder, f).Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar).Contains(BrowserProfileFolder, StringComparer.Ordinal))
.Order(StringComparer.Ordinal)];
/// <summary>Cleans every sample of <paramref name="rawFolder"/> into <paramref name="cleanFolder"/>, same relative names.</summary>
public SanitizeReport SanitizeFolder(string rawFolder, string cleanFolder)
{
var raw = Path.GetFullPath(rawFolder);
var clean = Path.GetFullPath(cleanFolder);
if (!Directory.Exists(raw))
{
throw new DirectoryNotFoundException($"La cartella dei campioni grezzi non esiste: {raw}");
}
if (clean.StartsWith(raw + Path.DirectorySeparatorChar, StringComparison.Ordinal) || clean == raw)
{
throw new InvalidOperationException("La cartella dei campioni ripuliti non può stare dentro quella dei grezzi.");
}
var files = SampleFiles(raw);
var tokens = new SensitiveTokens(_allowlist);
var documents = new List<(string Relative, bool Lines, List<JsonNode?> Nodes)>();
foreach (var file in files)
{
var relative = Path.GetRelativePath(raw, file);
var isLines = file.EndsWith(".jsonl", StringComparison.OrdinalIgnoreCase);
var nodes = new List<JsonNode?>();
foreach (var text in isLines ? File.ReadLines(file).Where(l => !string.IsNullOrWhiteSpace(l)) : [File.ReadAllText(file)])
{
using var document = JsonDocument.Parse(text, new JsonDocumentOptions { MaxDepth = 256 });
tokens.Add(document.RootElement);
nodes.Add(JsonNode.Parse(text, documentOptions: new JsonDocumentOptions { MaxDepth = 256 }));
}
documents.Add((relative, isLines, nodes));
}
UseSensitive(tokens);
var lines = 0;
foreach (var (relative, isLines, nodes) in documents)
{
var target = Path.Combine(clean, relative);
Directory.CreateDirectory(Path.GetDirectoryName(target)!);
if (isLines)
{
File.WriteAllLines(target, nodes.Select(n => Sanitize(n)?.ToJsonString() ?? "null"));
lines += nodes.Count;
}
else
{
File.WriteAllText(target, Sanitize(nodes[0])?.ToJsonString(new JsonSerializerOptions { WriteIndented = true }) ?? "null");
}
}
return new SanitizeReport(documents.Count, lines, _strings, _numbers, _keys, _addresses);
}
/// <summary>Cleans one document (tests). Call <see cref="UseSensitive"/> first to avoid collisions with other samples.</summary>
public JsonNode? Sanitize(JsonNode? node, string? key = null)
{
switch (node)
{
case null:
return null;
case JsonObject obj:
var result = new JsonObject();
foreach (var (name, value) in obj)
{
var cleanName = SensitiveTokens.IsDataKey(name) ? FakeKey(name) : name;
result[cleanName] = Sanitize(value, name);
}
return result;
case JsonArray array:
var list = new JsonArray();
foreach (var item in array)
{
list.Add(Sanitize(item, key));
}
return list;
case JsonValue value:
return SanitizeValue(value, key);
default:
return null;
}
}
/// <summary>Sets the raw tokens that fakes must never contain.</summary>
public void UseSensitive(SensitiveTokens tokens)
{
_sensitive = [.. tokens.Effective];
_lengths = [.. tokens.Lengths.Order()];
}
private JsonNode? SanitizeValue(JsonValue value, string? key)
{
var element = value.GetValue<JsonElement>();
switch (element.ValueKind)
{
case JsonValueKind.True:
case JsonValueKind.False:
case JsonValueKind.Null:
return JsonValue.Create(element);
case JsonValueKind.Number:
var raw = element.GetRawText();
var digits = raw.Count(char.IsAsciiDigit);
var integral = !raw.Contains('.', StringComparison.Ordinal) && !raw.Contains('e', StringComparison.OrdinalIgnoreCase);
if (_allowlist.KeepsNumber(key) || (integral && digits < 5) || (!integral && digits < 6))
{
return JsonValue.Create(element);
}
_numbers++;
return JsonNode.Parse(FakeNumber(raw));
case JsonValueKind.String:
var text = element.GetString() ?? string.Empty;
if (text.Length == 0 || _allowlist.KeepsString(key, text))
{
return JsonValue.Create(text);
}
if (Uri.TryCreate(text, UriKind.Absolute, out var uri) && uri.Scheme is "http" or "https")
{
_addresses++;
return JsonValue.Create(FakeAddress(text, uri));
}
_strings++;
return JsonValue.Create(Fake(text, "s"));
default:
return JsonValue.Create(element);
}
}
private string FakeKey(string key)
{
_keys++;
return Fake(key, "k");
}
private string FakeNumber(string raw)
{
var fake = Fake(raw, "n");
// A JSON number must not start with 0 (except «0.x»): keep the first digit non-zero.
var first = -1;
for (var i = 0; i < fake.Length; i++)
{
if (char.IsAsciiDigit(fake[i]))
{
first = i;
break;
}
}
if (first >= 0 && fake[first] == '0' && raw[first] != '0')
{
fake = string.Concat(fake.AsSpan(0, first), "7", fake.AsSpan(first + 1));
}
return fake;
}
private string FakeAddress(string text, Uri uri)
{
if (_fakes.TryGetValue("u|" + text, out var known))
{
return known;
}
var host = _hosts.Classify(uri) switch
{
HostKind.Site => "sito",
HostKind.Cdn => "cdn",
_ => "altro",
};
var last = uri.AbsolutePath.Split('/').LastOrDefault() ?? string.Empty;
var dot = last.LastIndexOf('.');
var extension = dot > 0 && FileExtensions.Contains(last[(dot + 1)..].ToLowerInvariant()) ? last[dot..].ToLowerInvariant() : string.Empty;
var token = Fake(Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(text)))[..16], "u");
var fake = $"https://{host}.esempio/{token}{extension}";
_fakes["u|" + text] = fake;
return fake;
}
/// <summary>A fake with the shape of <paramref name="original"/>, the same for the same value in this run.</summary>
private string Fake(string original, string kind)
{
var cacheKey = kind + "|" + original;
if (_fakes.TryGetValue(cacheKey, out var known))
{
return known;
}
for (var salt = 0; ; salt++)
{
var candidate = Shape(original, kind, salt);
if ((candidate != original || !original.Any(char.IsLetterOrDigit)) && !ContainsSensitive(candidate))
{
_fakes[cacheKey] = candidate;
return candidate;
}
if (salt > 64)
{
// Practically unreachable; fall back to a neutral filler of the same length.
var filler = new string(original.Select(c => char.IsLetter(c) ? 'x' : char.IsDigit(c) ? '7' : c).ToArray());
_fakes[cacheKey] = filler;
return filler;
}
}
}
private string Shape(string original, string kind, int salt)
{
var stream = Bytes($"{kind}|{salt.ToString(CultureInfo.InvariantCulture)}|{original}", original.Length);
var sb = new StringBuilder(original.Length);
for (var i = 0; i < original.Length; i++)
{
var c = original[i];
var r = stream[i];
if (char.IsLetter(c))
{
var letter = Consonants[r % Consonants.Length];
sb.Append(char.IsUpper(c) ? char.ToUpperInvariant(letter) : letter);
}
else if (char.IsDigit(c))
{
sb.Append((char)('0' + (r % 10)));
}
else if (char.IsSurrogate(c) || char.IsSymbol(c))
{
sb.Append('·'); // emoji and symbols carry meaning in captions: replaced by a neutral dot
}
else
{
sb.Append(c);
}
}
return sb.ToString();
}
private byte[] Bytes(string seed, int length)
{
var result = new byte[Math.Max(length, 1)];
var block = 0;
var offset = 0;
while (offset < result.Length)
{
var hash = HMACSHA256.HashData(_key, Encoding.UTF8.GetBytes(seed + "#" + block.ToString(CultureInfo.InvariantCulture)));
var take = Math.Min(hash.Length, result.Length - offset);
Array.Copy(hash, 0, result, offset, take);
offset += take;
block++;
}
return result;
}
private bool ContainsSensitive(string candidate)
{
if (_sensitive.Count == 0)
{
return false;
}
foreach (var token in SensitiveTokensOf(candidate))
{
foreach (var length in _lengths)
{
if (length > token.Length)
{
break;
}
for (var i = 0; i + length <= token.Length; i++)
{
if (_sensitive.Contains(token.Substring(i, length)))
{
return true;
}
}
}
}
return false;
}
private static IEnumerable<string> SensitiveTokensOf(string text)
{
var start = -1;
for (var i = 0; i <= text.Length; i++)
{
var isPart = i < text.Length && char.IsLetterOrDigit(text[i]);
if (isPart && start < 0)
{
start = i;
}
else if (!isPart && start >= 0)
{
yield return text[start..i].ToLowerInvariant();
start = -1;
}
}
}
}
+110
View File
@@ -0,0 +1,110 @@
using System.Text;
using System.Text.Json;
namespace Febe.Sonda;
/// <summary>One leak found by the verification: where, never what (the value itself is not printed).</summary>
/// <param name="CleanFile">Cleaned file (relative path) where a raw piece survives.</param>
/// <param name="Length">Length of the surviving piece.</param>
/// <param name="Kind">«lettere» or «cifre».</param>
public sealed record SampleLeak(string CleanFile, int Length, string Kind);
/// <summary>Result of the verification of cleaned samples.</summary>
public sealed record VerifyReport(int RawFiles, int CleanFiles, int CheckedTokens, IReadOnlyList<SampleLeak> Leaks, IReadOnlyList<string> MissingCleanFiles)
{
public bool Passed => Leaks.Count == 0 && MissingCleanFiles.Count == 0 && CleanFiles > 0;
}
/// <summary>
/// The check of spec §14.5, run on Alberto's machine: fails if any run of four or more letters and digits (five for
/// numbers) of the raw samples survives in the cleaned ones, outside the allowlist. It prints where, never the value.
/// </summary>
public static class SampleVerifier
{
public static VerifyReport Verify(string rawFolder, string cleanFolder, SanitizerAllowlist? allowlist = null)
{
var raw = Path.GetFullPath(rawFolder);
var clean = Path.GetFullPath(cleanFolder);
var tokens = new SensitiveTokens(allowlist ?? SanitizerAllowlist.Default);
var rawFiles = SampleSanitizer.SampleFiles(raw);
foreach (var file in rawFiles)
{
foreach (var text in Documents(file))
{
using var document = JsonDocument.Parse(text, new JsonDocumentOptions { MaxDepth = 256 });
tokens.Add(document.RootElement);
}
}
var missing = rawFiles.Select(f => Path.GetRelativePath(raw, f)).Where(r => !File.Exists(Path.Combine(clean, r))).ToList();
var cleanFiles = Directory.Exists(clean) ? SampleSanitizer.SampleFiles(clean) : [];
var sensitive = tokens.Effective;
var leaks = new List<SampleLeak>();
foreach (var file in cleanFiles)
{
var atoms = new StringBuilder();
foreach (var text in Documents(file))
{
using var document = JsonDocument.Parse(text, new JsonDocumentOptions { MaxDepth = 256 });
Atoms(document.RootElement, atoms, 0);
}
var haystack = atoms.ToString().ToLowerInvariant();
foreach (var token in sensitive)
{
if (haystack.Contains(token, StringComparison.Ordinal))
{
leaks.Add(new SampleLeak(Path.GetRelativePath(clean, file), token.Length, token.Any(char.IsLetter) ? "lettere" : "cifre"));
}
}
}
return new VerifyReport(rawFiles.Count, cleanFiles.Count, sensitive.Count, leaks, missing);
}
private static IEnumerable<string> Documents(string file) =>
file.EndsWith(".jsonl", StringComparison.OrdinalIgnoreCase)
? File.ReadLines(file).Where(l => !string.IsNullOrWhiteSpace(l))
: [File.ReadAllText(file)];
/// <summary>
/// Every value and every data key of a cleaned document, separated so that tokens cannot span two of them.
/// Ordinary keys are structure, copied from the raw samples on purpose: they are not looked at.
/// </summary>
private static void Atoms(JsonElement element, StringBuilder sb, int depth)
{
if (depth > 256)
{
return;
}
switch (element.ValueKind)
{
case JsonValueKind.Object:
foreach (var property in element.EnumerateObject())
{
if (SensitiveTokens.IsDataKey(property.Name))
{
sb.Append(property.Name).Append('\u0001');
}
Atoms(property.Value, sb, depth + 1);
}
break;
case JsonValueKind.Array:
foreach (var item in element.EnumerateArray())
{
Atoms(item, sb, depth + 1);
}
break;
case JsonValueKind.String:
sb.Append(element.GetString()).Append('\u0001');
break;
case JsonValueKind.Number:
sb.Append(element.GetRawText()).Append('\u0001');
break;
}
}
}
+121
View File
@@ -0,0 +1,121 @@
using System.Globalization;
using System.Text.Json;
using System.Text.RegularExpressions;
namespace Febe.Sonda;
/// <summary>Kind of a field that says nothing about a person (spec §14.5).</summary>
public enum AllowedField
{
None,
Dimension,
Duration,
Count,
Code,
Date,
}
/// <summary>
/// The short list of fields the sanitizer keeps (<c>ripulitura.json</c>): dimensions, durations, counts, type codes and
/// dates. Everything else is replaced. Booleans and null are always kept: they cannot identify anyone.
/// </summary>
public sealed partial class SanitizerAllowlist
{
private readonly List<(Regex Pattern, AllowedField Field)> _rules;
public SanitizerAllowlist(IEnumerable<(string KeyPattern, AllowedField Field)> rules)
{
_rules = [.. rules.Select(r => (new Regex("^" + Regex.Escape(r.KeyPattern.Trim().ToLowerInvariant()).Replace("\\*", ".*", StringComparison.Ordinal) + "$", RegexOptions.CultureInvariant), r.Field))];
}
/// <summary>The shipped list (embedded <c>ripulitura.json</c>).</summary>
public static SanitizerAllowlist Default { get; } = Parse(ReadEmbedded());
public static SanitizerAllowlist Load(string path) => Parse(File.ReadAllText(path));
public static SanitizerAllowlist Parse(string json)
{
using var document = JsonDocument.Parse(json, new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true });
var rules = new List<(string, AllowedField)>();
if (!document.RootElement.TryGetProperty("categories", out var categories) || categories.ValueKind != JsonValueKind.Object)
{
throw new InvalidDataException("ripulitura.json: manca «categories».");
}
foreach (var category in categories.EnumerateObject())
{
var field = category.Name.ToLowerInvariant() switch
{
"dimension" => AllowedField.Dimension,
"duration" => AllowedField.Duration,
"count" => AllowedField.Count,
"code" => AllowedField.Code,
"date" => AllowedField.Date,
_ => throw new InvalidDataException($"ripulitura.json: categoria «{category.Name}» sconosciuta (ammesse: dimension, duration, count, code, date)."),
};
if (category.Value.TryGetProperty("keys", out var keys) && keys.ValueKind == JsonValueKind.Array)
{
foreach (var key in keys.EnumerateArray())
{
if (key.GetString() is { Length: > 0 } pattern)
{
rules.Add((pattern, field));
}
}
}
}
return new SanitizerAllowlist(rules);
}
public AllowedField FieldOf(string? key)
{
if (string.IsNullOrEmpty(key))
{
return AllowedField.None;
}
var lower = key.ToLowerInvariant();
foreach (var (pattern, field) in _rules)
{
if (pattern.IsMatch(lower))
{
return field;
}
}
return AllowedField.None;
}
/// <summary>True when a number under <paramref name="key"/> is kept as it is.</summary>
public bool KeepsNumber(string? key) => FieldOf(key) != AllowedField.None;
/// <summary>True when a string under <paramref name="key"/> is kept: short type codes, and dates under date keys.</summary>
public bool KeepsString(string? key, string value) => FieldOf(key) switch
{
AllowedField.Code => value.Length <= 40 && CodeShape().IsMatch(value) && !LongDigits().IsMatch(value),
AllowedField.Date => value.Length <= 40 && (DateShape().IsMatch(value)
|| (UnixShape().IsMatch(value) && long.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out _))),
_ => false,
};
private static string ReadEmbedded()
{
using var stream = typeof(SanitizerAllowlist).Assembly.GetManifestResourceStream("Febe.Sonda.ripulitura.json")
?? throw new FileNotFoundException("Risorsa incorporata mancante: ripulitura.json");
using var reader = new StreamReader(stream);
return reader.ReadToEnd();
}
[GeneratedRegex(@"^[A-Za-z][A-Za-z0-9_./+\- ]*$", RegexOptions.CultureInvariant)]
private static partial Regex CodeShape();
[GeneratedRegex(@"\d{3,}", RegexOptions.CultureInvariant)]
private static partial Regex LongDigits();
[GeneratedRegex(@"^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?)?$", RegexOptions.CultureInvariant)]
private static partial Regex DateShape();
[GeneratedRegex(@"^\d{9,13}$", RegexOptions.CultureInvariant)]
private static partial Regex UnixShape();
}
+129
View File
@@ -0,0 +1,129 @@
using System.Text.Json;
using Febe.Core.Collection.Readers;
namespace Febe.Sonda;
/// <summary>
/// The pieces of raw samples that must not survive the cleaning (spec §14.5): every run of four or more letters and
/// digits found in the values (strings, long numbers) and in the keys that look like identifiers, except the
/// structure (ordinary keys) and the values the allowlist keeps. Purely numeric runs count from five digits: shorter
/// numbers (dimensions, counts) identify nobody.
/// </summary>
public sealed class SensitiveTokens
{
/// <summary>Words of address structure that the cleaned samples write themselves.</summary>
private static readonly string[] AddressWords = ["http", "https", "www", "html", "json", "jpeg", "webp", "heic", "esempio"];
private readonly HashSet<string> _tokens = new(StringComparer.Ordinal);
private readonly HashSet<string> _excluded = new(StringComparer.Ordinal);
public SensitiveTokens(SanitizerAllowlist allowlist)
{
Allowlist = allowlist;
foreach (var word in AddressWords)
{
_excluded.Add(word);
}
}
public SanitizerAllowlist Allowlist { get; }
/// <summary>Tokens that must not appear in the cleaned samples (lower case).</summary>
public IReadOnlySet<string> Effective
{
get
{
var set = new HashSet<string>(_tokens, StringComparer.Ordinal);
set.ExceptWith(_excluded);
return set;
}
}
/// <summary>Lengths of the effective tokens, for window checks.</summary>
public IReadOnlySet<int> Lengths => Effective.Select(t => t.Length).ToHashSet();
public void Add(JsonElement root) => Walk(root, key: null, depth: 0);
/// <summary>Alphanumeric runs of <paramref name="text"/> that would be sensitive, lower case.</summary>
public static IEnumerable<string> Tokenize(string text)
{
var start = -1;
for (var i = 0; i <= text.Length; i++)
{
var isPart = i < text.Length && char.IsLetterOrDigit(text[i]);
if (isPart && start < 0)
{
start = i;
}
else if (!isPart && start >= 0)
{
var token = text[start..i];
start = -1;
var letters = token.Any(char.IsLetter);
if ((letters && token.Length >= 4) || (!letters && token.Length >= 5))
{
yield return token.ToLowerInvariant();
}
}
}
}
/// <summary>True when the key is data rather than structure (sanitizer replaces it).</summary>
public static bool IsDataKey(string key) =>
KeyStructure.LooksLikeIdentifier(key) || key.Any(c => !(char.IsAsciiLetterOrDigit(c) || c is '_' or '-'));
private void Walk(JsonElement element, string? key, int depth)
{
if (depth > 256)
{
return;
}
switch (element.ValueKind)
{
case JsonValueKind.Object:
foreach (var property in element.EnumerateObject())
{
var target = IsDataKey(property.Name) ? _tokens : _excluded;
foreach (var token in Tokenize(property.Name))
{
target.Add(token);
}
if (!IsDataKey(property.Name))
{
// A whole ordinary key is structure too (e.g. «ultima_storia»).
_excluded.Add(property.Name.ToLowerInvariant());
}
Walk(property.Value, property.Name, depth + 1);
}
break;
case JsonValueKind.Array:
foreach (var item in element.EnumerateArray())
{
Walk(item, key, depth + 1);
}
break;
case JsonValueKind.String:
var text = element.GetString() ?? string.Empty;
var kept = Allowlist.KeepsString(key, text);
foreach (var token in Tokenize(text))
{
(kept ? _excluded : _tokens).Add(token);
}
break;
case JsonValueKind.Number:
var raw = element.GetRawText();
foreach (var token in Tokenize(raw))
{
(Allowlist.KeepsNumber(key) ? _excluded : _tokens).Add(token);
}
break;
}
}
}
+25
View File
@@ -0,0 +1,25 @@
{
"note": "Elenco di ciò che la ripulitura dei campioni lascia com'è (specifica §14.5). Tutto il resto si sostituisce: ogni stringa e ogni numero lungo diventano un valore finto della stessa forma. Le chiavi si confrontano senza maiuscole; «*» vale per qualunque parte del nome. Si ammettono solo campi che non dicono nulla di una persona.",
"categories": {
"dimension": {
"note": "Dimensioni in pixel: si tengono i numeri.",
"keys": ["width", "height", "*_width", "*_height", "larghezza", "altezza"]
},
"duration": {
"note": "Durate: si tengono i numeri.",
"keys": ["duration", "*_duration", "durata"]
},
"count": {
"note": "Conteggi: si tengono i numeri.",
"keys": ["count", "*_count", "pubblicazioni", "parti_totali"]
},
"code": {
"note": "Codici di tipo e di stato: si tengono i numeri e i testi brevi fatti di lettere, senza cifre ripetute. «role», «tag» ed «evento» sono i ruoli e i tipi degli elementi registrati dalla sonda (link, button, tab...); «host» è già ridotto dalla sonda a sito, cdn o altro.",
"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"]
}
}
}