using System.Text; using System.Text.Json; using System.Text.Json.Nodes; using System.Text.RegularExpressions; using Febe.Core.Abstractions; using Febe.Core.Collection; namespace Febe.Sonda; /// What an extraction of request shapes did: counts only, never a value. /// Entries of the HAR. /// Requests the page made to the site (XHR, Fetch) that were described. /// Distinct shapes written: same method, path pattern, operation and query identifier. /// Names (parameters, fields, keys) replaced because they could be data. public sealed record RequestShapesReport(int Entries, int SiteRequests, int Shapes, int RemovedNames); /// /// Describes the SHAPE of the requests Instagram's own page makes to the site (decision of 12 November 2026, issue #34: /// Febe has its page ask for the data the site's web application asks for, in the same form). From a HAR exported by /// Alberto it writes, for each distinct request: method, path with every segment that is not a known word of the site /// replaced by {numero} or {testo}, names of query parameters, headers and body fields with the kind of /// their value, the structure of the GraphQL variables, and values only from closed lists of values that are the same /// for everyone (application identifiers, operation names and identifiers, page sizes, true/false). /// /// /// Unlike the raw samples of , the output is meant to be sent: it must hold no personal data /// by construction. Values are never copied unless they are on a closed list. Names are copied only when they are on a /// closed list, or when they have the shape of a name of the site's code (no dot, no run of three digits) AND never /// occur anywhere in the HAR as a value: a user name, code or cursor that the page uses as a key (an object keyed by /// user, a form field without a value) also occurs as a value somewhere (an address, a response, a cookie) and is /// removed. A name removed by mistake costs only detail. The output is still written outside any repository, and /// Alberto reads it before sending it. /// public static partial class RequestShapes { /// Written in place of a header value that is not on a closed list. public const string Removed = "(valore tolto)"; /// Written in place of a name (parameter, field, key) that could be data. public const string RemovedName = "(nome tolto)"; /// The body field that describes a request body that is neither a form nor a JSON object. public const string WholeBody = "(corpo)"; /// /// Path segments kept as they are: words of the site's addresses, the same for everyone. Anything else (user names, /// identifiers, codes) becomes {numero} or {testo}. A missing word only costs detail, never privacy. /// private static readonly HashSet KnownSegments = new(StringComparer.Ordinal) { "api", "v1", "graphql", "graphql_www", "query", "ajax", "bulk-route-definitions", "navigation", "web", "users", "user", "web_profile_info", "usernameinfo", "info", "feed", "timeline", "reels_media", "reels_tray", "highlights", "highlights_tray", "friendships", "following", "followers", "show", "show_many", "search", "topsearch", "fbsearch", "web_search", "typeahead", "accounts_typeahead", "top_serp", "media", "comments", "usertags", "clips", "stories", "story", "tags", "sections", "discover", "explore", "chaining", "profile", "posts", "reels", "tagged", "saved", "qp", "batch_fetch_web", "logging_client_events", "direct_v2", "inbox", "has_new", "get_presence", "wwwgraphql", "ig", "bz", "web_info", "current_user", "user_info", "locations", "seen", "media_seen", "reel", "p", "accounts", "edit", "activity", "news", "inbox_v2", "notifications", "badge", "home", "graphql_query", }; /// Request headers whose value is the same for everyone and is kept; any other value is removed. private static readonly HashSet KnownHeaderValues = new(StringComparer.OrdinalIgnoreCase) { "accept", "content-type", "x-ig-app-id", "x-asbd-id", "x-requested-with", "x-instagram-ajax", "x-bloks-version-id", "sec-fetch-dest", "sec-fetch-mode", "sec-fetch-site", }; /// Header that names the operation: its value is kept only when it has the shape of an operation name. private const string FriendlyNameHeader = "x-fb-friendly-name"; /// Header that names the GraphQL root field: its value is kept only when it has the shape of one. private const string RootFieldHeader = "x-root-field-name"; /// Query or body fields whose value names the site's code and is kept when it has the shape of an identifier. private static readonly HashSet KnownValueFields = new(StringComparer.Ordinal) { HarImporter.OperationParameter, "fb_api_caller_class", "doc_id", "query_hash", "query_id", "server_timestamps", "__comet_req", "__a", "dpr", }; /// Fields whose value identifies the query: two requests that differ in them are different shapes. private static readonly string[] QueryIdentifiers = ["doc_id", "query_hash", "query_id"]; /// Fields that hold JSON: only its structure is written (keys and kinds of values). private static readonly HashSet JsonFields = new(StringComparer.Ordinal) { "variables", "params", "query_params" }; /// Names whose small numbers (at most three digits) are a page size or a switch and are kept as they are. private static readonly HashSet PageSizeNames = new(StringComparer.Ordinal) { "count", "first", "last", "limit", "page_size", "num_results", "__comet_req", "__a", "dpr", }; /// Names of the site's code always kept, even when the same word occurs as a value somewhere. private static readonly HashSet KnownNames = new(StringComparer.Ordinal) { "after", "before", "cursor", "max_id", "min_id", "id", "ids", "user_id", "target_user_id", "username", "query", "data", "include_reel", "reel_ids", "media_id", "shortcode", "search_surface", "context", "rank_token", }; private static readonly JsonDocumentOptions DeepDocuments = new() { MaxDepth = 256 }; /// Writes the shapes of the site requests in to the new file . /// A path is inside a git repository, or the output exists. /// The file is not a HAR. public static RequestShapesReport Extract(string harPath, string outputPath, HostClassifier? hosts = null) { ArgumentException.ThrowIfNullOrWhiteSpace(harPath); ArgumentException.ThrowIfNullOrWhiteSpace(outputPath); hosts ??= HostClassifier.Instagram; var har = Path.GetFullPath(harPath); if (!File.Exists(har)) { throw new FileNotFoundException($"Il file HAR non esiste: {har}", har); } RepositoryGuard.EnsureOutside(Path.GetDirectoryName(har)!); var output = Path.GetFullPath(outputPath); RepositoryGuard.EnsureOutside(Path.GetDirectoryName(output)!); if (Directory.Exists(output)) { throw new InvalidOperationException($"«{output}» è una cartella: indica un file nuovo, per esempio «{Path.Combine(output, "richieste.json")}»."); } if (File.Exists(output)) { throw new InvalidOperationException($"Il file «{output}» esiste già: indica un file nuovo."); } JsonDocument document; try { using var stream = File.OpenRead(har); document = JsonDocument.Parse(stream, DeepDocuments); } catch (JsonException ex) { throw new InvalidDataException($"{Path.GetFileName(har)}: non è un file HAR valido (riga {ex.LineNumber + 1}).", ex); } var shapes = new Dictionary(StringComparer.Ordinal); int count = 0, described = 0; Names names; 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»)."); } // First pass: every value the HAR holds, wherever it is. A name equal to one of them is never written. names = new Names(ValueCollector.Collect(entries)); foreach (var entry in entries.EnumerateArray()) { count++; if (Describe(entry, hosts, names) is not { } shape) { continue; } described++; if (shapes.TryGetValue(shape.Key, out var known)) { known.Merge(shape); } else { shapes[shape.Key] = shape; } } } var root = new JsonObject { ["nota"] = "Forma delle richieste che la pagina di Instagram fa al sito, ricavata con «febe-sonda richieste» da un file HAR. " + "Nessun valore personale: dei parametri, delle intestazioni e dei corpi restano i nomi e il tipo dei valori; i valori solo se " + "sono uguali per tutti (identificativo dell'applicazione, nomi e identificativi delle operazioni, grandezza delle pagine, vero/falso). " + "Un nome che altrove nel file HAR compare come valore diventa «(nome tolto)». Leggilo prima di inviarlo.", ["richieste"] = new JsonArray(shapes.Values .OrderBy(s => s.Path, StringComparer.Ordinal) .ThenBy(s => s.Key, StringComparer.Ordinal) .Select(s => (JsonNode)s.ToJson()) .ToArray()), }; Directory.CreateDirectory(Path.GetDirectoryName(output)!); using (var stream = new FileStream(output, FileMode.CreateNew, FileAccess.Write)) using (var writer = new StreamWriter(stream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false))) { writer.Write(root.ToJsonString(new JsonSerializerOptions { WriteIndented = true, Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping })); writer.Write('\n'); } return new RequestShapesReport(count, described, shapes.Count, names.Removed); } /// The path with each segment that is not a known word replaced by {numero} or {testo}. public static string PathPattern(string path) { ArgumentNullException.ThrowIfNull(path); var segments = path.Split('/'); for (var i = 0; i < segments.Length; i++) { var segment = segments[i]; if (segment.Length == 0 || KnownSegments.Contains(segment)) { continue; } segments[i] = Digits().IsMatch(segment) ? "{numero}" : "{testo}"; } return string.Join('/', segments); } /// /// The kind of the value of , never the value: «numero», «vuoto» or «testo». Kept as they are: /// true/false, and a small number (at most three digits) only for a page size or a switch. /// public static string ValueShape(string name, string? value) => value switch { null or "" => "vuoto", "true" or "false" => value, _ when SmallNumber().IsMatch(value) && PageSizeNames.Contains(name) => value, _ when Digits().IsMatch(value) => "numero", _ => "testo", }; /// /// Two descriptions of the same value seen in different requests, made one: the same value stays; two numbers are /// «numero», true and false are «sì/no», an empty value gives way to the other; anything else is «testo». /// public static string Generalize(string a, string b) { ArgumentNullException.ThrowIfNull(a); ArgumentNullException.ThrowIfNull(b); if (a == b) { return a; } return (Kind(a), Kind(b)) switch { ("vuoto", _) => b, (_, "vuoto") => a, ("numero", "numero") => "numero", ("sì/no", "sì/no") => "sì/no", _ => "testo", }; static string Kind(string value) => value switch { "vuoto" or "nulla" => "vuoto", "true" or "false" or "sì/no" => "sì/no", "numero" => "numero", _ when Digits().IsMatch(value) => "numero", _ => "testo", }; } private static Shape? Describe(JsonElement entry, HostClassifier hosts, Names names) { if (entry.ValueKind != JsonValueKind.Object || !entry.TryGetProperty("request", out var request) || request.ValueKind != JsonValueKind.Object) { return null; } var resource = Text(entry, "_resourceType")?.ToLowerInvariant() switch { "xhr" => "XHR", "fetch" => "Fetch", _ => null, }; var url = Text(request, "url"); if (resource is null || hosts.Classify(url) != HostKind.Site || !Uri.TryCreate(url, UriKind.Absolute, out var uri)) { return null; } var shape = new Shape((Text(request, "method") ?? "GET").ToUpperInvariant(), PathPattern(uri.AbsolutePath), resource); // Query string and body: the same rules for names and values, and a name repeated in one request is one entry. var raw = new Dictionary(StringComparer.Ordinal); foreach (var (name, value) in Pairs(uri.Query)) { raw.TryAdd(name, value); Put(shape.Parameters, names, name, value); } var fields = BodyFields(request, out var whole); foreach (var (name, value) in fields) { raw.TryAdd(name, value); Put(shape.Body, names, name, value); } if (whole is not null) { Add(shape.Body, WholeBody, JsonValue.Create(whole)!); } if (request.TryGetProperty("headers", out var headers) && headers.ValueKind == JsonValueKind.Array) { foreach (var header in headers.EnumerateArray()) { var name = header.ValueKind == JsonValueKind.Object ? Text(header, "name")?.ToLowerInvariant() : null; if (string.IsNullOrEmpty(name) || name.StartsWith(':')) { continue; } var value = Text(header, "value"); shape.Headers[names.Safe(name)] = name switch { FriendlyNameHeader => HarImporter.OperationName(value) ?? Removed, RootFieldHeader => RootField(value) ?? Removed, _ when KnownHeaderValues.Contains(name) && value is not null && SafeHeaderValue().IsMatch(value) => value, _ => Removed, }; } } shape.RootField = shape.Headers.TryGetValue(RootFieldHeader, out var field) ? RootField(field) : null; shape.Operation = HarImporter.OperationName(raw.GetValueOrDefault(HarImporter.OperationParameter)) ?? (shape.Headers.TryGetValue(FriendlyNameHeader, out var friendly) ? HarImporter.OperationName(friendly) : null) ?? shape.RootField; shape.QueryIdentifier = string.Join(' ', QueryIdentifiers .Select(id => raw.GetValueOrDefault(id) is { } value && SafeCodeValue().IsMatch(value) ? $"{id}={value}" : null) .OfType()); if (entry.TryGetProperty("response", out var response) && response.ValueKind == JsonValueKind.Object) { if (response.TryGetProperty("status", out var status) && status.ValueKind == JsonValueKind.Number && status.TryGetInt32(out var code)) { shape.Statuses.Add(code); } if (response.TryGetProperty("content", out var content) && content.ValueKind == JsonValueKind.Object && Text(content, "mimeType")?.Split(';')[0].Trim().ToLowerInvariant() is { Length: > 0 } mime && SafeHeaderValue().IsMatch(mime)) { shape.Types.Add(mime); } } return shape; } /// One field of the query string or of the body, described: name by , value by kind. private static void Put(SortedDictionary into, Names names, string name, string? value) { if (name.Length == 0) { // A pair without a name or without «=»: the text itself could be anything. Add(into, names.Remove(), JsonValue.Create("vuoto")!); return; } JsonNode node; if (JsonFields.Contains(name)) { node = Structure(value, names); } else if (name == HarImporter.OperationParameter) { node = JsonValue.Create(HarImporter.OperationName(value) ?? ValueShape(name, value))!; } else if (KnownValueFields.Contains(name) && value is not null && SafeCodeValue().IsMatch(value)) { node = JsonValue.Create(value)!; } else { node = JsonValue.Create(ValueShape(name, value))!; } Add(into, names.Safe(name), node); } private static void Add(SortedDictionary into, string name, JsonNode node) => into[name] = into.TryGetValue(name, out var known) ? MergeNodes(known, node) : node; /// The structure of a JSON text: names by , kinds of values, never a value. private static JsonNode Structure(string? text, Names names) { if (string.IsNullOrEmpty(text)) { return JsonValue.Create("vuoto")!; } try { return Structure(JsonNode.Parse(text, documentOptions: DeepDocuments), null, names); } catch (JsonException) { return JsonValue.Create("testo")!; } } private static JsonNode Structure(JsonNode? node, string? name, Names names) { switch (node) { case null: return JsonValue.Create("nulla")!; case JsonObject o: var members = new SortedDictionary(StringComparer.Ordinal); foreach (var (key, value) in o) { Add(members, names.Safe(key), Structure(value, key, names)); } return new JsonObject(members.Select(m => KeyValuePair.Create(m.Key, (JsonNode?)m.Value))); case JsonArray a: // Every element described, then made one: a list says what its elements look like, not how many. JsonNode? element = null; foreach (var item in a.Take(1000)) { var described = Structure(item, name, names); element = element is null ? described : MergeNodes(element, described); } return element is null ? new JsonArray() : new JsonArray(element); case JsonValue v when v.GetValueKind() is JsonValueKind.True or JsonValueKind.False: return JsonValue.Create(v.GetValueKind() == JsonValueKind.True ? "true" : "false")!; case JsonValue v when v.GetValueKind() == JsonValueKind.Number: return JsonValue.Create(ValueShape(name ?? string.Empty, v.ToJsonString()))!; case JsonValue v when v.GetValueKind() == JsonValueKind.String: // The text «true» is a text, not a switch. return JsonValue.Create(ValueShape(name ?? string.Empty, v.GetValue()) is "true" or "false" ? "testo" : ValueShape(name ?? string.Empty, v.GetValue()))!; default: return JsonValue.Create("testo")!; } } /// /// Two descriptions of the same field made one: objects by the union of their keys, lists by their elements, values /// by ; a structure (object or list) wins over a plain value. /// private static JsonNode MergeNodes(JsonNode a, JsonNode b) { switch (a, b) { case (JsonObject oa, JsonObject ob): var members = new SortedDictionary(StringComparer.Ordinal); foreach (var (key, value) in oa.Concat(ob)) { if (value is not null) { members[key] = members.TryGetValue(key, out var known) ? MergeNodes(known, value) : value.DeepClone(); } } return new JsonObject(members.Select(m => KeyValuePair.Create(m.Key, (JsonNode?)m.Value))); case (JsonArray la, JsonArray lb): return (la.Count, lb.Count) switch { (0, _) => lb.DeepClone(), (_, 0) => la.DeepClone(), _ => new JsonArray(MergeNodes(la[0]!, lb[0]!)), }; case (JsonValue va, JsonValue vb): return JsonValue.Create(Generalize(Leaf(va), Leaf(vb)))!; case (JsonValue, _): return b.DeepClone(); default: return a.DeepClone(); } static string Leaf(JsonValue value) => value.TryGetValue(out var text) ? text : value.ToJsonString(); } /// /// The fields of a request body: a form field by field, a JSON object member by member. Anything else is described /// whole in («json» or «testo»), and never split on «&» and «=»: words of a search would /// become names. /// private static List<(string Name, string? Value)> BodyFields(JsonElement request, out string? whole) { whole = null; var fields = new List<(string, string?)>(); if (!request.TryGetProperty("postData", out var post) || post.ValueKind != JsonValueKind.Object) { return fields; } var mime = Text(post, "mimeType") ?? string.Empty; var text = Text(post, "text"); if (mime.Contains("x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase)) { if (post.TryGetProperty("params", out var parameters) && parameters.ValueKind == JsonValueKind.Array && parameters.GetArrayLength() > 0) { foreach (var parameter in parameters.EnumerateArray()) { if (parameter.ValueKind == JsonValueKind.Object && Text(parameter, "name") is { } name) { fields.Add((Unescape(name) ?? string.Empty, Unescape(Text(parameter, "value")))); } } } else if (text is not null) { fields.AddRange(Pairs(text)); } return fields; } if (string.IsNullOrWhiteSpace(text)) { return fields; } // Not a form: JSON whatever the declared type (a fetch with a string body is «text/plain»), or else «testo». var trimmed = text.TrimStart(); if (trimmed.StartsWith('{') || trimmed.StartsWith('[')) { try { if (JsonNode.Parse(text, documentOptions: DeepDocuments) is JsonObject members) { foreach (var (name, value) in members) { fields.Add((name, value switch { null => null, JsonValue v when v.GetValueKind() == JsonValueKind.String => v.GetValue(), _ => value.ToJsonString(), })); } return fields; } whole = "json"; return fields; } catch (JsonException) { // Not JSON after all: described whole, below. } } whole = "testo"; return fields; } /// Name and value of each pair of a query string or a form; a pair without «=» has an empty name. private static IEnumerable<(string Name, string? Value)> Pairs(string query) { foreach (var pair in query.TrimStart('?').Split('&', StringSplitOptions.RemoveEmptyEntries)) { var equals = pair.IndexOf('=', StringComparison.Ordinal); yield return equals < 0 ? (string.Empty, null) : (Unescape(pair[..equals]) ?? string.Empty, Unescape(pair[(equals + 1)..])); } } private static string? RootField(string? value) { var name = value?.Trim(); return name is not null && RootFieldShape().IsMatch(name) && !DigitRun().IsMatch(name) ? name : null; } internal static string? Unescape(string? value) { if (value is null) { return null; } try { return Uri.UnescapeDataString(value.Replace('+', ' ')); } catch (UriFormatException) { return null; } } internal static string? Text(JsonElement element, string property) => element.TryGetProperty(property, out var value) && value.ValueKind == JsonValueKind.String ? value.GetString() : null; [GeneratedRegex("^[0-9]+$", RegexOptions.CultureInvariant)] private static partial Regex Digits(); [GeneratedRegex("^[0-9]{1,3}$", RegexOptions.CultureInvariant)] private static partial Regex SmallNumber(); [GeneratedRegex("[0-9]{3}", RegexOptions.CultureInvariant)] private static partial Regex DigitRun(); // A name in the site's code: letters, digits, «_», «-» (e.g. «x-ig-app-id», «max_id», «__a»). No dot: user names // have dots, names of the code do not. [GeneratedRegex("^[A-Za-z_][A-Za-z0-9_-]{0,63}$", RegexOptions.CultureInvariant)] private static partial Regex CodeName(); // A GraphQL root field, as in «x-root-field-name» (e.g. «xdt_api__v1__feed__user_timeline_graphql_connection»). [GeneratedRegex("^[a-z][a-z0-9_]{2,127}$", RegexOptions.CultureInvariant)] private static partial Regex RootFieldShape(); // A header value from the closed list: an identifier or a media type, never free text. [GeneratedRegex("^[A-Za-z0-9_.,;=*/+ -]{1,80}$", RegexOptions.CultureInvariant)] private static partial Regex SafeHeaderValue(); // A value of the closed list of fields: an identifier of the site's code (doc_id is a long number of the code, // query_hash a hexadecimal one, not of a person). [GeneratedRegex("^[A-Za-z0-9_]{1,96}$", RegexOptions.CultureInvariant)] private static partial Regex SafeCodeValue(); /// Decides which names are written: the closed lists, or the shape of a code name that is never a value. private sealed class Names(HashSet values) { public int Removed { get; private set; } public string Safe(string name) { if (KnownNames.Contains(name) || KnownValueFields.Contains(name) || JsonFields.Contains(name) || PageSizeNames.Contains(name) || KnownHeaderValues.Contains(name)) { return name; } return CodeName().IsMatch(name) && !DigitRun().IsMatch(name) && !values.Contains(name) ? name : Remove(); } public string Remove() { Removed++; return RemovedName; } } /// One distinct request: method, path pattern, operation and query identifier, with all its occurrences. private sealed class Shape(string method, string path, string resource) { public string Method { get; } = method; public string Path { get; } = path; public string Resource { get; } = resource; public string? Operation { get; set; } public string? RootField { get; set; } public string QueryIdentifier { get; set; } = string.Empty; public SortedDictionary Parameters { get; } = new(StringComparer.Ordinal); public SortedDictionary Headers { get; } = new(StringComparer.Ordinal); public SortedDictionary Body { get; } = new(StringComparer.Ordinal); public SortedSet Statuses { get; } = []; public SortedSet Types { get; } = new(StringComparer.Ordinal); public int Times { get; private set; } = 1; public string Key => $"{Method} {Path} {Operation} {RootField} {QueryIdentifier}"; public void Merge(Shape other) { Times++; foreach (var (name, value) in other.Parameters) { Add(Parameters, name, value); } foreach (var (name, value) in other.Body) { Add(Body, name, value); } foreach (var (name, value) in other.Headers) { Headers[name] = Headers.TryGetValue(name, out var known) && known != value ? RequestShapes.Removed : value; } Statuses.UnionWith(other.Statuses); Types.UnionWith(other.Types); } public JsonObject ToJson() => new() { ["metodo"] = Method, ["percorso"] = Path, ["operazione"] = Operation, ["campo_radice"] = RootField, ["risorsa"] = Resource, ["volte"] = Times, ["parametri"] = new JsonObject(Parameters.Select(p => KeyValuePair.Create(p.Key, (JsonNode?)p.Value.DeepClone()))), ["intestazioni"] = new JsonObject(Headers.Select(p => KeyValuePair.Create(p.Key, (JsonNode?)JsonValue.Create(p.Value)))), ["corpo"] = new JsonObject(Body.Select(p => KeyValuePair.Create(p.Key, (JsonNode?)p.Value.DeepClone()))), ["stati"] = new JsonArray(Statuses.Select(s => (JsonNode)JsonValue.Create(s)).ToArray()), ["tipi"] = new JsonArray(Types.Select(t => (JsonNode)JsonValue.Create(t)).ToArray()), }; } } /// /// Every value a HAR holds (addresses, cookies, header values, form values, strings of JSON requests and responses, /// data embedded in pages), to tell a name of the site's code from a piece of data used as a name. /// internal static class ValueCollector { private const int MaxBodyChars = 64 * 1024 * 1024; private const string ScriptGuard = "for (;;);"; private static readonly char[] HeaderSeparators = [';', ',', '=', ' ']; public static HashSet Collect(JsonElement entries) { var values = new HashSet(StringComparer.OrdinalIgnoreCase); foreach (var entry in entries.EnumerateArray()) { if (entry.ValueKind != JsonValueKind.Object) { continue; } if (entry.TryGetProperty("request", out var request) && request.ValueKind == JsonValueKind.Object) { Address(values, RequestShapes.Text(request, "url")); Headers(values, request); PairValues(values, request, "queryString"); PairValues(values, request, "cookies"); if (request.TryGetProperty("postData", out var post) && post.ValueKind == JsonValueKind.Object) { PairValues(values, post, "params"); if (RequestShapes.Text(post, "text") is { } text) { Body(values, text); } } } if (entry.TryGetProperty("response", out var response) && response.ValueKind == JsonValueKind.Object) { Headers(values, response); PairValues(values, response, "cookies"); Address(values, RequestShapes.Text(response, "redirectURL")); if (response.TryGetProperty("content", out var content) && content.ValueKind == JsonValueKind.Object && RequestShapes.Text(content, "text") is { Length: > 0 and <= MaxBodyChars } body) { if (RequestShapes.Text(content, "encoding") == "base64") { try { body = Encoding.UTF8.GetString(Convert.FromBase64String(body)); } catch (FormatException) { continue; } } if ((RequestShapes.Text(content, "mimeType") ?? string.Empty).Contains("html", StringComparison.OrdinalIgnoreCase)) { foreach (var block in DataResponses.EmbeddedJsonBlocks(body)) { using (block) { Element(values, block.RootElement); } } } else { Body(values, body); } } } } return values; } private static void Add(HashSet values, string? value) { var text = value?.Trim(); if (string.IsNullOrEmpty(text) || text.Length > 512) { return; } values.Add(text); if (text.StartsWith('@') && text.Length > 1) { values.Add(text[1..]); } } private static void Address(HashSet values, string? url) { if (string.IsNullOrEmpty(url) || !Uri.TryCreate(url, UriKind.Absolute, out var uri)) { return; } foreach (var segment in uri.AbsolutePath.Split('/', StringSplitOptions.RemoveEmptyEntries)) { Add(values, RequestShapes.Unescape(segment)); } Form(values, uri.Query); Form(values, uri.Fragment.TrimStart('#')); } /// The values of a query string or a form; a pair without «=» is all value. private static void Form(HashSet values, string text) { foreach (var pair in text.TrimStart('?').Split('&', StringSplitOptions.RemoveEmptyEntries)) { var equals = pair.IndexOf('=', StringComparison.Ordinal); var value = RequestShapes.Unescape(equals < 0 ? pair : pair[(equals + 1)..]); Add(values, value); if (value is not null) { Json(values, value); } } } private static void Headers(HashSet values, JsonElement message) { if (!message.TryGetProperty("headers", out var headers) || headers.ValueKind != JsonValueKind.Array) { return; } foreach (var header in headers.EnumerateArray()) { if (header.ValueKind == JsonValueKind.Object && RequestShapes.Text(header, "value") is { } value) { Add(values, value); foreach (var part in value.Split(HeaderSeparators, StringSplitOptions.RemoveEmptyEntries)) { Add(values, part); } Address(values, value); } } } private static void PairValues(HashSet values, JsonElement owner, string property) { if (!owner.TryGetProperty(property, out var pairs) || pairs.ValueKind != JsonValueKind.Array) { return; } foreach (var pair in pairs.EnumerateArray()) { if (pair.ValueKind == JsonValueKind.Object && RequestShapes.Unescape(RequestShapes.Text(pair, "value")) is { } value) { Add(values, value); Json(values, value); } } } /// A body: one or more JSON values (Instagram may send several in a row, after «for (;;);»), or a form, or text. private static void Body(HashSet values, string text) { var trimmed = text.TrimStart(); if (trimmed.StartsWith(ScriptGuard, StringComparison.Ordinal)) { trimmed = trimmed[ScriptGuard.Length..].TrimStart(); } if (!Json(values, trimmed)) { Form(values, trimmed); } } /// Every string value (not the names) of the JSON values in ; false if it is not JSON. private static bool Json(HashSet values, string text) { var trimmed = text.TrimStart(); if (!trimmed.StartsWith('{') && !trimmed.StartsWith('[')) { return false; } var reader = new Utf8JsonReader(Encoding.UTF8.GetBytes(trimmed), new JsonReaderOptions { AllowMultipleValues = true, CommentHandling = JsonCommentHandling.Skip, MaxDepth = 256 }); var any = false; try { while (reader.Read()) { any = true; if (reader.TokenType == JsonTokenType.String) { var value = reader.GetString(); Add(values, value); if (value is not null && value.Length is > 1 and < 65536) { // A JSON text inside a string (GraphQL variables): its values too. Json(values, value); } } } } catch (JsonException) { // The values read up to here are kept: a truncated body still names what it held. } return any; } private static void Element(HashSet values, JsonElement element) { switch (element.ValueKind) { case JsonValueKind.Object: foreach (var property in element.EnumerateObject()) { Element(values, property.Value); } break; case JsonValueKind.Array: foreach (var item in element.EnumerateArray()) { Element(values, item); } break; case JsonValueKind.String: Add(values, element.GetString()); break; } } }