Sessione salvata cifrata, copiata a «Ho finito» (#36, S4)
Il client del sito ha bisogno della sessione del browser di Febe: ora la copia c'è, cifrata e dietro un interruttore, senza cambiare nulla di predefinito. - Opzione «raccolta» (pagine predefinita, richieste): solo con «richieste» e almeno un'operazione configurata si costruiscono sessione salvata, client del sito e copia. Con Instagram nulla cambia: le dieci operazioni restano non configurate (mancano __spin_*, __req, __s, __dyn, __csr e altri). - Cookie con dominio, percorso, solo-host, Secure, HttpOnly e scadenza, mandati solo dove il browser li manderebbe (RFC 6265). - Sezione «page» del catalogo: dove la pagina tiene ogni valore; nuovi campi rev, hs, hsi, dpr, ccg, comet_req, entry_nonce. Il caricatore rifiuta un'operazione configurata con un valore di sessione senza fonte nella pagina. - Dati/sessione/sessione.json: DPAPI su Windows, AES-256-GCM in Docker (chiave da FEBE_CHIAVE_SESSIONE o chiave.bin), scrittura atomica, file illeggibile = nessuna sessione. «Scollega» la cancella; chiave.bin resta. - Copia a «Ho finito» con Network.getCookies e una sola Runtime.evaluate in sola lettura, solo da una pagina del sito e finché dura il permesso di guida. - FEBE_PASSWORD e FEBE_CHIAVE_SESSIONE non passano a Chromium, Xvfb, ffmpeg. - Sito di prova: csrftoken, cookie limitato a /api/, registro di moduli suo. - Revisione su tre lenti: 11 punti confermati, tutti corretti. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
3046b2da47
commit
c87768766c
69 files changed
+5936
-415
No files matched your search
@@ -32,6 +32,36 @@ public sealed partial class TestSite
|
||||
/// <summary>The token <c>fb_dtsg</c> the pages of the site would hold (session:fb_dtsg).</summary>
|
||||
public const string Dtsg = "dtsg-di-prova";
|
||||
|
||||
/// <summary>The revision of the pages (session:rev, field <c>__rev</c>; module VersioneProva.revisione of richieste.prova.json).</summary>
|
||||
public const string Revision = "revisione-di-prova";
|
||||
|
||||
/// <summary>The haste session of the pages (session:hs, field <c>__hs</c>; VersioneProva.hs).</summary>
|
||||
public const string HasteSession = "hs-di-prova";
|
||||
|
||||
/// <summary>The id of the page load (session:hsi, field <c>__hsi</c>; VersioneProva.hsi).</summary>
|
||||
public const string HasteSessionId = "hsi-di-prova";
|
||||
|
||||
/// <summary>The pixel ratio the pages send (session:dpr, field <c>dpr</c>; VersioneProva.dpr).</summary>
|
||||
public const string Dpr = "1";
|
||||
|
||||
/// <summary>The comet environment the pages send (session:comet_req, field <c>__comet_req</c>; VersioneProva.comet).</summary>
|
||||
public const string CometReq = "7";
|
||||
|
||||
/// <summary>The connection class the pages send (session:ccg, field <c>__ccg</c>; ConnessioneProva.classe).</summary>
|
||||
public const string ConnectionClass = "BUONA";
|
||||
|
||||
/// <summary>The nonce of the page load (session:entry_nonce, header <c>x-fb-entry-nonce</c>; AvvioProva.nonce).</summary>
|
||||
public const string EntryNonce = "nonce-di-prova";
|
||||
|
||||
/// <summary>A cookie of the pages limited to the addresses under <see cref="ApiPath"/> (Path=/api/): the copy keeps it with its path.</summary>
|
||||
public const string ApiPathCookie = "percorso_api";
|
||||
|
||||
/// <summary>The value of <see cref="ApiPathCookie"/>.</summary>
|
||||
public const string ApiPathCookieValue = "solo-sotto-api";
|
||||
|
||||
/// <summary>The path of <see cref="ApiPathCookie"/>.</summary>
|
||||
public const string ApiPath = "/api/";
|
||||
|
||||
/// <summary>The GraphQL query of the site: a profile page, with the JSON of <c>/dati/profilo/{nome}</c>.</summary>
|
||||
public const string ProfileQuery = "ProvaProfiloQuery";
|
||||
|
||||
@@ -225,6 +255,14 @@ public sealed partial class TestSite
|
||||
return ("campi", null);
|
||||
}
|
||||
|
||||
// The values of the page the saved session copies (S4): a missing or different one gets the same generic 400.
|
||||
if (form["__rev"].ToString() != Revision || form["__hs"].ToString() != HasteSession || form["__hsi"].ToString() != HasteSessionId
|
||||
|| form["__ccg"].ToString() != ConnectionClass || form["dpr"].ToString() != Dpr || form["__comet_req"].ToString() != CometReq
|
||||
|| request.Headers["x-fb-entry-nonce"].ToString() != EntryNonce)
|
||||
{
|
||||
return ("campi", null);
|
||||
}
|
||||
|
||||
JsonObject variables;
|
||||
try
|
||||
{
|
||||
|
||||
@@ -111,7 +111,7 @@ che non controlla nulla: per il browser non cambia niente.
|
||||
| Richiesta | Risposta |
|
||||
|---|---|
|
||||
| `GET /api/dati/...` | lo stesso indirizzo e la stessa risposta di `/dati/...` (tabella sopra) |
|
||||
| `POST /api/graphql` | la richiesta GraphQL `ProvaProfiloQuery`: modulo `application/x-www-form-urlencoded` con `doc_id`, `fb_api_req_friendly_name`, `variables`, `lsd`, `fb_dtsg`, `__a=1`, `av`; risponde con il JSON di `/dati/profilo/{nome}?scheda=...` |
|
||||
| `POST /api/graphql` | la richiesta GraphQL `ProvaProfiloQuery`: modulo `application/x-www-form-urlencoded` con `doc_id`, `fb_api_req_friendly_name`, `variables`, `lsd`, `fb_dtsg`, `__a=1`, `av`, `__rev`, `__hs`, `__hsi`, `__ccg`, `dpr`, `__comet_req` e l'intestazione `x-fb-entry-nonce`; risponde con il JSON di `/dati/profilo/{nome}?scheda=...` |
|
||||
| un'altra richiesta sotto `/api/` | 404; un `POST` di un indirizzo semplice o un `GET` di `/api/graphql`: 405 (il client non scrive mai) |
|
||||
|
||||
Su `/api/` il sito controlla quello che controlla un sito vero, nell'ordine:
|
||||
@@ -124,14 +124,40 @@ Su `/api/` il sito controlla quello che controlla un sito vero, nell'ordine:
|
||||
3. `user-agent` non vuoto, `accept` presente, `x-app-id` uguale a `prova-applicazione-1`;
|
||||
4. per `/api/graphql`: `content-type`, il `doc_id` della query (`ProvaProfiloQuery` = `8000000000000001`) con lo stesso
|
||||
nome in `fb_api_req_friendly_name` e in `x-fb-friendly-name`, `lsd` = `lsd-di-prova`, `fb_dtsg` = `dtsg-di-prova`,
|
||||
`x-ig-www-claim` presente (il client manda `0`, come la pagina, finché il sito non ne dà uno), e le variabili con i
|
||||
loro tipi: `{"username": testo, "scheda": "post"|"reel"|"taggati", "primi": 12 (numero), "raccolte": vero/falso}`.
|
||||
`x-ig-www-claim` presente (il client manda `0`, come la pagina, finché il sito non ne dà uno), i valori della pagina
|
||||
(`__rev`, `__hs`, `__hsi`, `__ccg`, `dpr`, `__comet_req`, `x-fb-entry-nonce`) e le variabili con i loro tipi:
|
||||
`{"username": testo, "scheda": "post"|"reel"|"taggati", "primi": 12 (numero), "raccolte": vero/falso}`.
|
||||
|
||||
I valori sono costanti di `TestSite` (`AppId`, `Lsd`, `Dtsg`, `DocIds`, `CsrfCookie`). Le pagine del sito **non danno
|
||||
ancora** nessuno di questi valori: né il cookie `csrftoken`, né `app_id`, `lsd`, `fb_dtsg`, il `doc_id` della query o un
|
||||
claim. Per ora li mettono le prove nella sessione salvata (`InMemorySiteSession`); perché una sessione copiata dal
|
||||
browser di prova passi i controlli, la tappa S4 deve farli esporre alle pagine (un cookie e i moduli, come su
|
||||
Instagram). Le risposte a una richiesta che non passa i controlli sono **generiche e marcate H16**: non si sa ancora
|
||||
I valori sono costanti di `TestSite` (`AppId`, `Lsd`, `Dtsg`, `Revision`, `HasteSession`, `HasteSessionId`,
|
||||
`ConnectionClass`, `Dpr`, `CometReq`, `EntryNonce`, `DocIds`, `CsrfCookie`). Dalla tappa S4 di #36 le pagine li danno
|
||||
come li darebbe un sito vero, così la copia a «Ho finito» li trova nel browser di prova:
|
||||
|
||||
- una visita che apre la sessione, o che arriva senza `csrftoken`, riceve il cookie `csrftoken` (`csrf-prova-1`,
|
||||
`csrf-prova-2`…, leggibile dalla pagina) e il cookie `percorso_api` limitato a `Path=/api/` (il sito non lo
|
||||
controlla: serve a provare che la copia tiene il percorso di un cookie);
|
||||
- ogni pagina (non la verifica né la sessione scaduta) ha in testa un registro di moduli suo, `__d(nome, [], fabbrica)`
|
||||
e `require(nome)` (un nome sconosciuto è un errore), con i moduli della sezione `page` di `richieste.prova.json`:
|
||||
`GettoniProva` (`lsd`, `dtsg`), `UtenteProva` (`id`: l'account di Alberto del mondo, `applicazione`),
|
||||
`VersioneProva` (`revisione`, `hs`, `hsi`, `dpr` e `comet` come numeri), `ConnessioneProva` (`classe`),
|
||||
`AvvioProva` (`nonce`) e `ProvaProfiloQuery_operazioneProva`, che esporta il `doc_id`. Nomi del sito di prova, mai
|
||||
quelli di Instagram (`TestSite.PageModules`).
|
||||
|
||||
Le prove che non passano dal browser mettono gli stessi valori nella sessione salvata (`InMemorySiteSession`).
|
||||
|
||||
Per far girare Febe per richieste contro il sito di prova serve la raccolta `richieste` (il predefinito `pagine` non
|
||||
copia nulla e va con il browser, come prima):
|
||||
|
||||
```sh
|
||||
FEBE_PASSWORD=prova dotnet run --project src/Febe.Server -- \
|
||||
--dati /tmp/febe/dati --libreria /tmp/febe/libreria --importa /tmp/febe/importa --ascolta 127.0.0.1 \
|
||||
--sito-di-prova http://127.0.0.1:8481 --accesso-di-prova --raccolta richieste --prima-sessione 5
|
||||
```
|
||||
|
||||
Con `--accesso-di-prova` la copia si fa subito dopo l'accesso automatico; senza, a «Ho finito» dalla pagina
|
||||
Collegamento. La sessione copiata sta in `Dati/sessione/sessione.json`, cifrata (specifica §13.2). Il registro dice
|
||||
quanti cookie e quanti valori della pagina ha copiato, mai i valori.
|
||||
|
||||
Le risposte a una richiesta che non passa i controlli sono **generiche e marcate H16**: non si sa ancora
|
||||
che cosa risponde Instagram a una sessione scaduta, a un gettone sbagliato o a una richiesta malformata.
|
||||
|
||||
| Controllo non passato | Risposta (H16, generica) |
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using System.Text.Json.Nodes;
|
||||
|
||||
namespace Febe.SitoDiProva;
|
||||
|
||||
/// <summary>
|
||||
/// The modules of the pages (issue #36, S4): a tiny registry of its own (<c>__d</c> to declare a module,
|
||||
/// <c>require</c> to read it, an error for an unknown name) with the values a real site's page holds and the copy at
|
||||
/// «Ho finito» reads — tokens, account, version fields, the doc_id of each GraphQL query. The names are the test
|
||||
/// site's own (the <c>page</c> section of <c>richieste.prova.json</c>), never Instagram's; the values are the
|
||||
/// constants the site checks in <c>/api/</c>.
|
||||
/// </summary>
|
||||
public sealed partial class TestSite
|
||||
{
|
||||
/// <summary>The suffix of the module that exports the doc_id of a GraphQL query: <c>ProvaProfiloQuery_operazioneProva</c>.</summary>
|
||||
public const string DocIdModuleSuffix = "_operazioneProva";
|
||||
|
||||
/// <summary>
|
||||
/// What the pages declare, by module and property, as text (numbers as the page would turn them into text); the
|
||||
/// doc_id modules export the value itself (property <c>""</c>).
|
||||
/// </summary>
|
||||
/// <param name="accountId">The id of the account the pages show as connected (<see cref="World.Viewer"/>).</param>
|
||||
public static IReadOnlyDictionary<string, IReadOnlyDictionary<string, string>> PageModules(string accountId)
|
||||
{
|
||||
var modules = new Dictionary<string, IReadOnlyDictionary<string, string>>(StringComparer.Ordinal);
|
||||
foreach (var (name, module) in Modules(accountId))
|
||||
{
|
||||
modules[name] = module is JsonObject properties
|
||||
? properties.ToDictionary(p => p.Key, p => Text(p.Value), StringComparer.Ordinal)
|
||||
: new Dictionary<string, string>(StringComparer.Ordinal) { [string.Empty] = Text(module) };
|
||||
}
|
||||
|
||||
return modules;
|
||||
}
|
||||
|
||||
/// <summary>The inline script of the registry, for the head of every page but the verification and session-ended ones.</summary>
|
||||
internal static string ModuleRegistryScript(string accountId)
|
||||
{
|
||||
var text = new StringBuilder();
|
||||
text.Append("<script>(function () {\n");
|
||||
text.Append(" var declared = {}, made = {};\n");
|
||||
text.Append(" var own = function (o, k) { return Object.prototype.hasOwnProperty.call(o, k); };\n");
|
||||
text.Append(" window.__d = function (name, deps, factory) { declared[name] = factory; };\n");
|
||||
text.Append(" window.require = function (name) {\n");
|
||||
text.Append(" if (own(made, name)) { return made[name].exports; }\n");
|
||||
text.Append(" if (!own(declared, name)) { throw new Error('Modulo sconosciuto: ' + name); }\n");
|
||||
text.Append(" var module = { exports: {} };\n");
|
||||
text.Append(" made[name] = module;\n");
|
||||
text.Append(" declared[name](module);\n");
|
||||
text.Append(" return module.exports;\n");
|
||||
text.Append(" };\n");
|
||||
foreach (var (name, module) in Modules(accountId))
|
||||
{
|
||||
// JSON text in a script: the serializer escapes «<», so no value can close the element.
|
||||
text.Append(CultureInfo.InvariantCulture, $" __d({JsonValue.Create(name).ToJsonString()}, [], function (module) {{ module.exports = {module!.ToJsonString()}; }});\n");
|
||||
}
|
||||
|
||||
text.Append("})();</script>");
|
||||
return text.ToString();
|
||||
}
|
||||
|
||||
/// <summary>Puts <paramref name="script"/> first in the head of <paramref name="html"/>.</summary>
|
||||
internal static string InsertAfterHead(string html, string script)
|
||||
{
|
||||
var at = html.IndexOf("<head>", StringComparison.Ordinal);
|
||||
return at < 0 ? html : html.Insert(at + "<head>".Length, script);
|
||||
}
|
||||
|
||||
private static IEnumerable<(string Name, JsonNode Module)> Modules(string accountId)
|
||||
{
|
||||
yield return ("GettoniProva", new JsonObject { ["lsd"] = Lsd, ["dtsg"] = Dtsg });
|
||||
yield return ("UtenteProva", new JsonObject { ["id"] = accountId, ["applicazione"] = AppId });
|
||||
yield return ("VersioneProva", new JsonObject
|
||||
{
|
||||
["revisione"] = Revision,
|
||||
["hs"] = HasteSession,
|
||||
["hsi"] = HasteSessionId,
|
||||
|
||||
// Numbers in the page, as a real page keeps them: the copy turns them into text.
|
||||
["dpr"] = int.Parse(Dpr, CultureInfo.InvariantCulture),
|
||||
["comet"] = int.Parse(CometReq, CultureInfo.InvariantCulture),
|
||||
});
|
||||
yield return ("ConnessioneProva", new JsonObject { ["classe"] = ConnectionClass });
|
||||
yield return ("AvvioProva", new JsonObject { ["nonce"] = EntryNonce });
|
||||
foreach (var (operation, docId) in DocIds.OrderBy(d => d.Key, StringComparer.Ordinal))
|
||||
{
|
||||
yield return (operation + DocIdModuleSuffix, JsonValue.Create(docId));
|
||||
}
|
||||
}
|
||||
|
||||
private static string Text(JsonNode? node) => node is JsonValue value && value.TryGetValue<int>(out var number)
|
||||
? number.ToString(CultureInfo.InvariantCulture)
|
||||
: node?.GetValue<string>() ?? string.Empty;
|
||||
}
|
||||
@@ -74,6 +74,7 @@ public sealed class SiteControl
|
||||
private int _renewals;
|
||||
private int _logins;
|
||||
private int _claims;
|
||||
private int _csrfTokens;
|
||||
private StopMode _mode = StopMode.Normal;
|
||||
private int _armAfter;
|
||||
|
||||
@@ -203,6 +204,9 @@ public sealed class SiteControl
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A new value of the cookie <c>csrftoken</c>, as a visit without one gets.</summary>
|
||||
internal string NextCsrf() => "csrf-prova-" + Interlocked.Increment(ref _csrfTokens).ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
|
||||
/// <summary>A new claim value.</summary>
|
||||
internal string NextClaim() => "claim-prova-" + Interlocked.Increment(ref _claims).ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
|
||||
|
||||
@@ -207,13 +207,23 @@ public sealed partial class TestSite : IAsyncDisposable
|
||||
return;
|
||||
}
|
||||
|
||||
if (!Control.IsSession(context.Request.Cookies[SessionCookie]))
|
||||
var opened = !Control.IsSession(context.Request.Cookies[SessionCookie]);
|
||||
if (opened)
|
||||
{
|
||||
// No cookie, or one the site ended (a session that expired, a reset): the visit is a new login, with a new
|
||||
// value that the site client accepts too once copied.
|
||||
context.Response.Cookies.Append(SessionCookie, Control.OpenSession(), new CookieOptions { Path = "/", MaxAge = TimeSpan.FromDays(1), SameSite = SameSiteMode.Lax, HttpOnly = true });
|
||||
}
|
||||
|
||||
if (opened || string.IsNullOrEmpty(context.Request.Cookies[CsrfCookie]))
|
||||
{
|
||||
// What a real site gives its pages besides the session (issue #36, S4): the token the page reads and sends
|
||||
// back in x-csrftoken, and a cookie only for the addresses under /api/, which the copy at «Ho finito» must
|
||||
// keep with its path.
|
||||
context.Response.Cookies.Append(CsrfCookie, Control.NextCsrf(), new CookieOptions { Path = "/", MaxAge = TimeSpan.FromDays(1), SameSite = SameSiteMode.Lax });
|
||||
context.Response.Cookies.Append(ApiPathCookie, ApiPathCookieValue, new CookieOptions { Path = ApiPath, MaxAge = TimeSpan.FromDays(1), SameSite = SameSiteMode.Lax, HttpOnly = true });
|
||||
}
|
||||
|
||||
var segments = path.Split('/', StringSplitOptions.RemoveEmptyEntries).Select(Uri.UnescapeDataString).ToArray();
|
||||
string html;
|
||||
var status = 200;
|
||||
@@ -265,6 +275,15 @@ public sealed partial class TestSite : IAsyncDisposable
|
||||
html = html.Replace("<body ", "<body data-memoria-ricerca=\"si\" ", StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
// The modules of the page (issue #36, S4): what the copy at «Ho finito» reads, by the names of richieste.prova.json.
|
||||
string registry;
|
||||
lock (World.Gate)
|
||||
{
|
||||
registry = ModuleRegistryScript(World.Viewer.Id);
|
||||
}
|
||||
|
||||
html = InsertAfterHead(html, registry);
|
||||
|
||||
await HtmlAsync(context, status, html).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user