// SPDX-License-Identifier: MPL-2.0
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
namespace OpenGenesisLINK.Addons.OSWebInterface;
///
/// Optional integration with the separately installed and independently
/// authenticated OGL G1 live-update systemd service. This DLL NEVER runs
/// a shell and NEVER receives script paths/commands from the browser.
///
internal sealed class LiveUpdateBridge : IDisposable
{
private readonly bool _enabled;
private readonly string _nodeId;
private readonly string _token;
private readonly HttpClient _http;
public LiveUpdateBridge(bool requested, string nodeId, string serviceUrl, string token)
{
_nodeId = nodeId;
_token = token;
bool goodId = nodeId.Length is >= 1 and <= 64 &&
char.IsLetterOrDigit(nodeId[0]) &&
nodeId.All(c => char.IsLetterOrDigit(c) || c is '.' or '_' or '-');
bool local = Uri.TryCreate(serviceUrl, UriKind.Absolute, out Uri? u) &&
u.Scheme == "http" && u.Host == "127.0.0.1" &&
u.Port is >= 1025 and <= 65535 &&
u.AbsolutePath == "/" && u.Query.Length == 0 && u.Fragment.Length == 0;
_enabled = requested && goodId && local && Encoding.UTF8.GetByteCount(token) >= 32 &&
!OperatingSystem.IsWindows();
_http = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false })
{
BaseAddress = _enabled ? new Uri(serviceUrl.TrimEnd('/') + "/") :
new Uri("http://127.0.0.1:19090/"),
Timeout = TimeSpan.FromSeconds(6)
};
}
private HttpRequestMessage Request(HttpMethod method, string relative, object? body = null)
{
var req = new HttpRequestMessage(method, relative);
req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _token);
if (body is not null)
{
req.Content = new StringContent(JsonSerializer.Serialize(body), Encoding.UTF8, "application/json");
}
return req;
}
public async Task