Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,47 @@ Reads retry twice on a network error, a 5xx or a 429, half a second apart.
That is deliberately few: a start that waits half a minute on a server
that is down is worse than one that carries on.

## The firewall in front of the site

*Found 2026-09-28, running the first real sign-in against the test site.*

**SiteGround's firewall refuses the first TLS handshake that .NET's managed
HTTP handler makes in a process.** It answers with an HTML 403 page. Later
connections resume the TLS session and pass.

- This is deterministic: request 1 is refused, requests 2 and 3 get through.
- Windows' WinHTTP and Android's native handler are never refused.
- Link's notes describe the same host fingerprinting TLS.

Three things follow:

- **A 403 whose body is not JSON is the firewall, and it is retried.** It
is retried twice, for any request, including an exchange: the request
never reached WordPress, so no code was spent. A JSON 403 is the plugin
refusing and is never retried. This is integrity-sharp's rule for the
same host.
- **Every request asks for its connection to be closed.** Otherwise the
retry goes over the pooled connection the firewall just refused, and is
refused again. A new connection resumes the session. Freedom makes a
handful of requests per start, so keep-alive buys nothing worth that.
- **On Android, `UseFreedom` sends through `AndroidMessageHandler`**, the
platform's own stack, as Link does.

Every request also carries a `User-Agent`
(`Freedom.Client/0.1.0 (register; …)`, or the app's own name first under
`UseFreedom`). .NET sends none of its own, and an access log should say
whose traffic this is.

**The same proxy drops `If-None-Match`.** The right ETag sent back as a
header still got a 200, so the manifest request sends the ETag as
`?etag=` as well, and the plugin accepts either.

**The library's JSON is source-generated.** It therefore works where
reflection-based serialization is switched off: trimmed and AOT builds,
and .NET 10's file-based apps, where the first request used to throw.
`FreedomStateJson` gives stores one shared, generated way to write a
snapshot and credentials down.

## Only a refusal clears anything

**A refusal clears the store and the credentials**, and `ConfigChanged`
Expand Down
20 changes: 19 additions & 1 deletion TheBleedingDeacons.Freedom.Client.Maui/FreedomMauiExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Logging;
using Microsoft.Maui.ApplicationModel;
using Microsoft.Maui.Hosting;
using TheBleedingDeacons.Freedom.Client.Abstractions;

Expand Down Expand Up @@ -37,6 +38,13 @@ public static MauiAppBuilder UseFreedom(this MauiAppBuilder builder, FreedomOpti

var services = builder.Services;

// The app's own name and version first, then the library's: the
// traffic is the app's, and "which build is this?" is the first
// question asked of a misbehaving tablet.
options = options.UserAgent is null
? options with { UserAgent = $"{AppInfo.Current.Name.Replace(' ', '-')}/{AppInfo.Current.VersionString} ({FreedomApi.DefaultUserAgent(options.Application)})" }
: options;

services.TryAddSingleton(options);
services.TryAddSingleton<IFreedomStore>(_ => new SecureStorageFreedomStore(options.Application));
services.TryAddSingleton<IFreedomCredentialStore>(_ => new SecureStorageCredentialStore(options.Application));
Expand All @@ -48,8 +56,18 @@ public static MauiAppBuilder UseFreedom(this MauiAppBuilder builder, FreedomOpti
sp.GetRequiredService<IFreedomCredentialStore>(),
sp.GetRequiredService<IFreedomSignIn>(),
sp.GetRequiredService<IDeviceIdentity>(),
logger: sp.GetService<ILogger<FreedomClient>>()));
NativeHttpClient(),
sp.GetService<ILogger<FreedomClient>>()));

return builder;
}

/// <summary>
/// Android's own HTTP stack rather than .NET's managed one, as Link uses:
/// the edge firewall in front of the suite's sites fingerprints the TLS
/// handshake, and the platform stack is the one the system browser uses.
/// One client for the process — Freedom asks once per start.
/// </summary>
private static HttpClient NativeHttpClient() =>
new(new Xamarin.Android.Net.AndroidMessageHandler(), disposeHandler: true) { Timeout = TimeSpan.FromSeconds(20) };
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
// Copyright (c) The Bleeding Deacons. Licensed under the MIT license.

using System.Text.Json;
using Microsoft.Maui.Storage;
using TheBleedingDeacons.Freedom.Client.Abstractions;
using TheBleedingDeacons.Freedom.Client.Serialization;

namespace TheBleedingDeacons.Freedom.Client.Maui;

Expand All @@ -28,19 +28,17 @@ public sealed class SecureStorageCredentialStore(string application) : IFreedomC
{
try
{
var json = await SecureStorage.Default.GetAsync(_key).ConfigureAwait(false);

return string.IsNullOrEmpty(json) ? null : JsonSerializer.Deserialize<TabletCredentials>(json);
return FreedomStateJson.DeserializeCredentials(await SecureStorage.Default.GetAsync(_key).ConfigureAwait(false));
}
catch (Exception e) when (e is JsonException or InvalidOperationException or Java.Lang.Exception)
catch (Exception e) when (e is InvalidOperationException or Java.Lang.Exception)
{
return null;
}
}

/// <inheritdoc/>
public Task SaveAsync(TabletCredentials credentials, CancellationToken cancellationToken) =>
SecureStorage.Default.SetAsync(_key, JsonSerializer.Serialize(credentials));
SecureStorage.Default.SetAsync(_key, FreedomStateJson.Serialize(credentials));

/// <inheritdoc/>
public Task ClearAsync(CancellationToken cancellationToken)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
// Copyright (c) The Bleeding Deacons. Licensed under the MIT license.

using System.Text.Json;
using Microsoft.Maui.Storage;
using TheBleedingDeacons.Freedom.Client.Abstractions;
using TheBleedingDeacons.Freedom.Client.Serialization;
using TheBleedingDeacons.Freedom.Client.Stores;

namespace TheBleedingDeacons.Freedom.Client.Maui;
Expand Down Expand Up @@ -30,19 +30,9 @@ public async Task<FreedomSnapshot> LoadAsync(CancellationToken cancellationToken
{
try
{
var json = await SecureStorage.Default.GetAsync(_key).ConfigureAwait(false);
if (string.IsNullOrEmpty(json))
{
return FreedomSnapshot.Empty;
}

var stored = JsonSerializer.Deserialize<Stored>(json);

return stored is null
? FreedomSnapshot.Empty
: new FreedomSnapshot(stored.Values.ToDictionary(v => v.Key, StringComparer.Ordinal), stored.Etag, stored.VerifiedAt);
return FreedomStateJson.DeserializeSnapshot(await SecureStorage.Default.GetAsync(_key).ConfigureAwait(false));
}
catch (Exception e) when (e is JsonException or InvalidOperationException or Java.Lang.Exception)
catch (Exception e) when (e is InvalidOperationException or Java.Lang.Exception)
{
// Unreadable is treated as empty: the next sync fetches everything,
// which is the right answer to a store that has lost its contents.
Expand Down Expand Up @@ -88,7 +78,5 @@ public Task ClearAsync(CancellationToken cancellationToken)
}

private Task WriteAsync(FreedomSnapshot snapshot) =>
SecureStorage.Default.SetAsync(_key, JsonSerializer.Serialize(new Stored([.. snapshot.Values.Values], snapshot.Etag, snapshot.VerifiedAt)));

private sealed record Stored(List<FreedomValue> Values, string? Etag, DateTimeOffset? VerifiedAt);
SecureStorage.Default.SetAsync(_key, FreedomStateJson.Serialize(snapshot));
}
92 changes: 82 additions & 10 deletions TheBleedingDeacons.Freedom.Client/FreedomApi.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,13 @@
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using TheBleedingDeacons.Freedom.Client.Serialization;
using TheBleedingDeacons.Freedom.Models;

namespace TheBleedingDeacons.Freedom.Client;
Expand All @@ -25,24 +28,36 @@ namespace TheBleedingDeacons.Freedom.Client;
/// start that waits half a minute on a server that is down is worse than one
/// that carries on with what it has. Reads retry twice on a network error, a
/// 5xx or a 429; nothing that writes is retried.</para>
/// <para><b>A firewall's 403 is retried, a plugin's is not.</b> SiteGround's
/// firewall in front of aa-bristol.org fingerprints the TLS handshake, and
/// refuses the <i>first</i> full handshake .NET's managed handler makes in a
/// process with an HTML 403 page; later connections resume the session and
/// pass. Checked 2026-09-28, deterministically: request 1 403, requests 2 and 3
/// through. WinHTTP and Android's native handler are not refused at all. So a
/// 403 whose body is not JSON is the firewall, the request never reached
/// WordPress, and it is retried — even a write, since nothing was spent. A
/// JSON 403 is the plugin refusing and is never retried. integrity-sharp
/// arrived at the same rule for the same host.</para>
/// <para><b>Every request carries a <c>User-Agent</c></b>, since .NET sends none
/// of its own: the traffic is attributable in an access log, as Link's and
/// Fellowship's are. A client that already sets one is left alone.</para>
/// </remarks>
public sealed class FreedomApi : IDisposable
{
/// <summary>The wire's JSON: snake_case, as WordPress writes it.</summary>
internal static readonly JsonSerializerOptions Json = new()
{
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,
PropertyNameCaseInsensitive = true,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
};
internal static readonly JsonSerializerOptions Json = FreedomJsonContext.Default.Options;

private const int MaxReadRetries = 2;

/// <summary>Retries after a firewall's HTML 403, for any request.</summary>
private const int MaxFirewallRetries = 2;

private readonly Uri _root;
private readonly HttpClient _http;
private readonly bool _ownsHttp;
private readonly ILogger _logger;
private readonly TimeSpan _retryDelay;
private readonly string _userAgent;

/// <summary>
/// Initializes a new instance of the <see cref="FreedomApi"/> class.
Expand All @@ -52,7 +67,8 @@ public sealed class FreedomApi : IDisposable
/// <param name="logger">A logger. Values and tokens are never logged.</param>
/// <param name="allowInsecureBaseUrl">Allow plain http, for a local development site.</param>
/// <param name="retryDelay">The pause before a retry; half a second by default.</param>
public FreedomApi(Uri baseUrl, HttpClient? httpClient = null, ILogger? logger = null, bool allowInsecureBaseUrl = false, TimeSpan? retryDelay = null)
/// <param name="userAgent">The <c>User-Agent</c> to send; <see cref="DefaultUserAgent"/> when null.</param>
public FreedomApi(Uri baseUrl, HttpClient? httpClient = null, ILogger? logger = null, bool allowInsecureBaseUrl = false, TimeSpan? retryDelay = null, string? userAgent = null)
{
ArgumentNullException.ThrowIfNull(baseUrl);

Expand All @@ -66,6 +82,26 @@ public FreedomApi(Uri baseUrl, HttpClient? httpClient = null, ILogger? logger =
_ownsHttp = httpClient is null;
_logger = logger ?? NullLogger.Instance;
_retryDelay = retryDelay ?? TimeSpan.FromMilliseconds(500);
_userAgent = string.IsNullOrWhiteSpace(userAgent) ? DefaultUserAgent(null) : userAgent;
}

/// <summary>
/// The User-Agent sent when none is given:
/// <c>Freedom.Client/0.1.0 (register; Microsoft Windows 10.0.26200; +https://github.com/bleedingdeacons/freedom-sharp)</c>.
/// </summary>
public static string DefaultUserAgent(string? application)
{
var version = typeof(FreedomApi).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion ?? "0";
var plus = version.IndexOf('+', StringComparison.Ordinal);
if (plus >= 0)
{
// Source Link appends the commit; the version alone is what a log needs.
version = version[..plus];
}

var who = string.IsNullOrWhiteSpace(application) ? string.Empty : application + "; ";

return $"Freedom.Client/{version} ({who}{RuntimeInformation.OSDescription.Trim()}; +https://github.com/bleedingdeacons/freedom-sharp)";
}

/// <summary>Begin a browser sign-in.</summary>
Expand Down Expand Up @@ -124,7 +160,12 @@ public Task<ApiResponse<Manifest>> GetManifestAsync(string token, string? etag,
return SendAsync<Manifest>(
() =>
{
var request = new HttpRequestMessage(HttpMethod.Get, new Uri(_root, "config/manifest"));
// The ETag travels twice. If-None-Match is the standard way, and
// SiteGround's proxy does not pass it through to WordPress (checked
// 2026-09-28: the right ETag, sent back, still got a 200), so it
// goes in the query as well, which nothing in between touches.
var path = string.IsNullOrEmpty(etag) ? "config/manifest" : "config/manifest?etag=" + Uri.EscapeDataString(etag);
var request = new HttpRequestMessage(HttpMethod.Get, new Uri(_root, path));
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
if (!string.IsNullOrEmpty(etag))
{
Expand All @@ -142,13 +183,13 @@ public Task<ApiResponse<ValuesResponse>> GetValuesAsync(string token, IReadOnlyL
{
// A read, though it is a POST: the keys travel in the body rather than a
// query string that proxies log.
return SendAsync<ValuesResponse>(() => Post("config/values", new { keys }, token), retry: true, cancellationToken);
return SendAsync<ValuesResponse>(() => Post("config/values", new ValuesRequest(keys), token), retry: true, cancellationToken);
}

/// <summary>Tell the server this device was sent a secret it cannot open.</summary>
public Task<ApiResponse<JsonElementBox>> ReportKeyFaultAsync(string token, CancellationToken cancellationToken = default)
{
return SendAsync<JsonElementBox>(() => Post("tablet/key-fault", new { }, token), retry: false, cancellationToken);
return SendAsync<JsonElementBox>(() => Post("tablet/key-fault", new Dictionary<string, string>(StringComparer.Ordinal), token), retry: false, cancellationToken);
}

/// <summary>Sign this device out.</summary>
Expand Down Expand Up @@ -200,6 +241,17 @@ private async Task<ApiResponse<T>> SendAsync<T>(Func<HttpRequestMessage> build,
using var request = build();
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

// A connection per request. The firewall's refusal is of a
// connection's handshake, and a retry over the same pooled
// connection is refused again; a new one resumes the TLS session
// and gets through. Freedom makes a handful of requests per start,
// so keep-alive buys nothing worth that.
request.Headers.ConnectionClose = true;
if (request.Headers.UserAgent.Count == 0 && _http.DefaultRequestHeaders.UserAgent.Count == 0)
{
request.Headers.TryAddWithoutValidation("User-Agent", _userAgent);
}

HttpResponseMessage response;
try
{
Expand All @@ -223,6 +275,13 @@ private async Task<ApiResponse<T>> SendAsync<T>(Func<HttpRequestMessage> build,
var status = response.StatusCode;
var transient = (int)status >= 500 || status == HttpStatusCode.TooManyRequests;

if (status == HttpStatusCode.Forbidden && IsFirewallPage(response) && attempt <= MaxFirewallRetries)
{
_logger.LogWarning("Freedom: {Method} {Path} was refused by the site's firewall, not the plugin; retrying", request.Method, request.RequestUri?.AbsolutePath);
await Task.Delay(_retryDelay, cancellationToken).ConfigureAwait(false);
continue;
}

if (transient && attempt < attempts)
{
_logger.LogWarning("Freedom: {Method} {Path} answered {Status}; retrying", request.Method, request.RequestUri?.AbsolutePath, (int)status);
Expand Down Expand Up @@ -257,6 +316,19 @@ private async Task<ApiResponse<T>> SendAsync<T>(Func<HttpRequestMessage> build,
}
}

/// <summary>
/// Whether a 403 is a web server's or firewall's page rather than the
/// plugin's JSON refusal. integrity-sharp's rule: no Content-Type is not
/// assumed to be a firewall, because a genuine refusal served without one
/// must not be retried.
/// </summary>
private static bool IsFirewallPage(HttpResponseMessage response)
{
var mediaType = response.Content.Headers.ContentType?.MediaType;

return !string.IsNullOrEmpty(mediaType) && !mediaType.Contains("json", StringComparison.OrdinalIgnoreCase);
}

private static async Task<ApiError> ReadErrorAsync(HttpResponseMessage response, CancellationToken cancellationToken)
{
try
Expand Down
2 changes: 1 addition & 1 deletion TheBleedingDeacons.Freedom.Client/FreedomClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ public FreedomClient(
// here: an app whose settings were left out of a build should start and
// say so on its setup screen, not crash on launch.
_api = options.IsConfigured
? new FreedomApi(options.BaseUrl, httpClient, _logger, options.AllowInsecureBaseUrl)
? new FreedomApi(options.BaseUrl, httpClient, _logger, options.AllowInsecureBaseUrl, userAgent: options.UserAgent ?? FreedomApi.DefaultUserAgent(options.Application))
: null;
}

Expand Down
7 changes: 7 additions & 0 deletions TheBleedingDeacons.Freedom.Client/FreedomOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,13 @@ public sealed record FreedomOptions
/// </summary>
public bool ClearOnRefusal { get; init; } = true;

/// <summary>
/// Gets the <c>User-Agent</c> every request carries. Null for
/// <see cref="FreedomApi.DefaultUserAgent"/>. Something is always sent: the
/// site's firewall refuses a .NET request without one.
/// </summary>
public string? UserAgent { get; init; }

/// <summary>Gets a value indicating whether these options are complete enough to talk to a server.</summary>
public bool IsConfigured => IsAllowedBaseUrl(BaseUrl, AllowInsecureBaseUrl) && !string.IsNullOrWhiteSpace(Application);

Expand Down
2 changes: 1 addition & 1 deletion TheBleedingDeacons.Freedom.Client/JsonElementBox.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,5 @@ public sealed class JsonElementBox
{
/// <summary>Gets the fields the server sent.</summary>
[JsonExtensionData]
public Dictionary<string, JsonElement> Fields { get; init; } = [];
public Dictionary<string, JsonElement> Fields { get; set; } = [];
}
Loading
Loading