using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using System.Security.Cryptography; using System.Text; using System.Text.Json; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Win32; namespace NexoAuth; public sealed record NexoResult( bool Ok, int HttpStatus = 0, string ErrorCode = "", string Message = "", string SessionToken = "", long? SecondsLeft = null, int HeartbeatIntervalSeconds = 45, Dictionary? Variables = null, string RawJson = "", string Value = "", bool Transient = false, JsonElement Data = default ); public sealed class NexoAuthClient : IAsyncDisposable { private readonly HttpClient _http; private readonly string _productId; // Sin contacto con el servidor durante este tiempo, la sesión se da por perdida. private static readonly TimeSpan Grace = TimeSpan.FromSeconds(150); private const int RetrySeconds = 15; private readonly string _appSecret; private readonly string _publicKey; private readonly string _hwidPrevious; private long _lastContact; public int SubscriptionLevel { get; private set; } public string SubscriptionName { get; private set; } = ""; private readonly string _clientName; private readonly string _clientVersion; private readonly string _hwid; private readonly bool _ownsHttpClient; private CancellationTokenSource? _heartbeatCancellation; private Task? _heartbeatTask; private string _sessionToken = ""; private int _heartbeatSeconds = 45; public Dictionary Variables { get; private set; } = new(); public bool IsAuthenticated => !string.IsNullOrEmpty(_sessionToken); /// Clave pública del producto (04…, 130 caracteres; recomendada) o el secreto antiguo. public NexoAuthClient(string baseUrl, string productId, string clientName, string clientVersion, string appSecret = "", HttpClient? httpClient = null) { var uri = new Uri((baseUrl ?? "http://127.0.0.1:8787").TrimEnd('/') + "/"); if (uri.Scheme != Uri.UriSchemeHttps && !uri.IsLoopback) throw new ArgumentException("HTTP sin TLS solo está permitido para localhost.", nameof(baseUrl)); _http = httpClient ?? new HttpClient { Timeout = TimeSpan.FromSeconds(15) }; _ownsHttpClient = httpClient is null; _http.BaseAddress = uri; _productId = productId; appSecret ??= ""; var isPublic = appSecret.Length == 130 && appSecret.StartsWith("04") && Regex.IsMatch(appSecret, "^[0-9a-fA-F]+$"); _publicKey = isPublic ? appSecret : ""; _appSecret = isPublic ? "" : appSecret; _clientName = clientName; _clientVersion = clientVersion; _hwid = GenerateStableHwid(); _hwidPrevious = LegacyHwid(); } // Handshake inicial: valida estado de aplicación, versión, hash y firma del servidor public Task InitAsync(string programHash = "", CancellationToken cancellationToken = default) => PostAsync("v1/auth/init", string.IsNullOrEmpty(programHash) ? (object)new { productId = _productId, client = ClientInfo() } : new { productId = _productId, programHash, client = ClientInfo() }, false, cancellationToken); // Modo 1: Autenticación directa solo con License Key (tipo KeyAuth License) public Task LicenseAsync(string licenseKey, CancellationToken cancellationToken = default) => AuthenticateAsync("v1/auth/license", new { productId = _productId, licenseKey, hwid = _hwid, hwidPrevious = _hwidPrevious, client = ClientInfo() }, cancellationToken); // Modo 2: Registro con Usuario, Contraseña y Key public Task RegisterAsync(string username, string password, string licenseKey, CancellationToken cancellationToken = default) => AuthenticateAsync("v1/auth/register-credentials", new { productId = _productId, licenseKey, username, password, hwid = _hwid, hwidPrevious = _hwidPrevious, client = ClientInfo() }, cancellationToken); // Modo 3: Login solo con Usuario y Contraseña public Task LoginAsync(string username, string password, string licenseKey = "", CancellationToken cancellationToken = default) => AuthenticateAsync("v1/auth/login", string.IsNullOrEmpty(licenseKey) ? (object)new { productId = _productId, username, password, hwid = _hwid, hwidPrevious = _hwidPrevious, client = ClientInfo() } : (object)new { productId = _productId, username, password, licenseKey, hwid = _hwid, hwidPrevious = _hwidPrevious, client = ClientInfo() }, cancellationToken); // Modo 4: Canjear key para extender tiempo public Task UpgradeAsync(string username, string password, string licenseKey, CancellationToken cancellationToken = default) => PostAsync("v1/auth/upgrade", new { productId = _productId, username, password, licenseKey }, false, cancellationToken); public Task ChangePasswordAsync(string username, string password, string newPassword, CancellationToken cancellationToken = default) => PostAsync("v1/auth/change-password", new { productId = _productId, username, password, newPassword }, false, cancellationToken); /// Contraseña olvidada: pide la key y solo funciona en un equipo ya vinculado a la cuenta. public Task ResetPasswordAsync(string username, string licenseKey, string newPassword, CancellationToken cancellationToken = default) => PostAsync("v1/auth/reset-password", new { productId = _productId, username, licenseKey, newPassword, hwid = _hwid, hwidPrevious = _hwidPrevious }, false, cancellationToken); // Variables propias de este cliente (se guardan en el servidor) public Task SetVarAsync(string key, string value, CancellationToken cancellationToken = default) => SessionAsync("v1/auth/setvar", new { key, value }, cancellationToken); public Task GetUserVarAsync(string key, CancellationToken cancellationToken = default) => SessionAsync("v1/auth/getvar", new { key }, cancellationToken); public Task OnlineAsync(CancellationToken cancellationToken = default) => SessionAsync("v1/auth/online", new { }, cancellationToken); public Task ChatSendAsync(string message, string channel = "general", CancellationToken cancellationToken = default) => SessionAsync("v1/auth/chat/send", new { message, channel }, cancellationToken); public Task ChatFetchAsync(long after = 0, string channel = "general", CancellationToken cancellationToken = default) => SessionAsync("v1/auth/chat/fetch", new { after, channel }, cancellationToken); public Task ListFilesAsync(CancellationToken cancellationToken = default) => SessionAsync("v1/auth/files", new { }, cancellationToken); /// Guarda el archivo en path solo si su SHA-256 coincide con el que firmó el servidor. public async Task DownloadFileAsync(string fileId, string path, CancellationToken cancellationToken = default) { var meta = await SessionAsync("v1/auth/file", new { id = fileId }, cancellationToken); if (!meta.Ok) return meta; try { var external = meta.Data.GetProperty("external").GetBoolean(); using var request = new HttpRequestMessage(HttpMethod.Get, external ? ReadString(meta.Data, "url") : ReadString(meta.Data, "url").TrimStart('/')); if (!external) request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _sessionToken); using var response = await _http.SendAsync(request, cancellationToken); if (!response.IsSuccessStatusCode) return new(false, (int)response.StatusCode, "DOWNLOAD_FAILED", "No se pudo descargar el archivo"); var bytes = await response.Content.ReadAsByteArrayAsync(cancellationToken); if (!Convert.ToHexString(SHA256.HashData(bytes)).Equals(ReadString(meta.Data, "sha256"), StringComparison.OrdinalIgnoreCase)) return new(false, ErrorCode: "FILE_TAMPERED", Message: "El archivo descargado no coincide con el original"); await File.WriteAllBytesAsync(path, bytes, cancellationToken); return meta; } catch (Exception error) when (error is HttpRequestException or TaskCanceledException) { return new(false, ErrorCode: "NETWORK_ERROR", Message: error.Message, Transient: true); } } private Task SessionAsync(string endpoint, object payload, CancellationToken cancellationToken) => IsAuthenticated ? PostAsync(endpoint, payload, true, cancellationToken) : Task.FromResult(new NexoResult(false, ErrorCode: "SESSION_REQUIRED", Message: "No hay una sesión iniciada")); public async Task FetchVarAsync(string key, CancellationToken cancellationToken = default) { if (!IsAuthenticated) return new(false, ErrorCode: "SESSION_REQUIRED", Message: "No hay una sesión iniciada"); return await PostAsync("v1/auth/var", new { key }, true, cancellationToken); } public async Task LogAsync(string message, CancellationToken cancellationToken = default) { if (!IsAuthenticated) return new(false, ErrorCode: "SESSION_REQUIRED", Message: "No hay una sesión iniciada"); return await PostAsync("v1/auth/log", new { message, pcName = Environment.MachineName }, true, cancellationToken); } public async Task HeartbeatAsync(CancellationToken cancellationToken = default) { if (!IsAuthenticated) return new(false, ErrorCode: "SESSION_REQUIRED", Message: "No hay una sesión iniciada"); var result = await PostAsync("v1/auth/heartbeat", new { }, true, cancellationToken); if (result.Ok) _lastContact = Stopwatch.GetTimestamp(); // Un corte de red o del servidor no cierra la sesión hasta agotar el margen; un rechazo real, sí. else if (!result.Transient || Stopwatch.GetElapsedTime(_lastContact) >= Grace) { _sessionToken = ""; result = result with { Transient = false }; } return result; } public async Task LogoutAsync(CancellationToken cancellationToken = default) { await StopHeartbeatAsync(); if (!IsAuthenticated) return new(false, ErrorCode: "SESSION_REQUIRED", Message: "No hay una sesión iniciada"); var result = await PostAsync("v1/auth/logout", new { }, true, cancellationToken); _sessionToken = ""; return result; } public void StartHeartbeat(Func? onResult = null) { _heartbeatCancellation?.Cancel(); _heartbeatCancellation = new CancellationTokenSource(); var token = _heartbeatCancellation.Token; _heartbeatTask = Task.Run(async () => { var delay = _heartbeatSeconds; while (!token.IsCancellationRequested) { try { await Task.Delay(TimeSpan.FromSeconds(delay), token); } catch (OperationCanceledException) { break; } var result = await HeartbeatAsync(token); if (token.IsCancellationRequested) break; if (result.Transient) { delay = RetrySeconds; continue; } if (onResult is not null) await onResult(result); if (!result.Ok) break; delay = _heartbeatSeconds = Math.Max(15, result.HeartbeatIntervalSeconds); } }, token); } public async Task StopHeartbeatAsync() { if (_heartbeatCancellation is null) return; _heartbeatCancellation.Cancel(); if (_heartbeatTask is not null) { try { await _heartbeatTask; } catch (OperationCanceledException) { } } _heartbeatCancellation.Dispose(); _heartbeatCancellation = null; _heartbeatTask = null; } public string GetVar(string key, string fallback = "") => Variables.TryGetValue(key, out var val) ? val : fallback; private object ClientInfo() => new { name = _clientName, version = _clientVersion, platform = "windows", pcName = Environment.MachineName }; private async Task AuthenticateAsync(string endpoint, object payload, CancellationToken cancellationToken) { var result = await PostAsync(endpoint, payload, false, cancellationToken); if (result.Ok) { _sessionToken = result.SessionToken; _heartbeatSeconds = Math.Max(15, result.HeartbeatIntervalSeconds); if (result.Variables is not null) Variables = result.Variables; _lastContact = Stopwatch.GetTimestamp(); if (result.Data.TryGetProperty("subscription", out var sub)) { SubscriptionLevel = ReadInt32(sub, "level", 1); SubscriptionName = ReadString(sub, "levelName"); } } return result; } private async Task PostAsync(string endpoint, object payload, bool authorized, CancellationToken cancellationToken) { try { var nonce = Convert.ToHexString(RandomNumberGenerator.GetBytes(16)).ToLowerInvariant(); using var request = new HttpRequestMessage(HttpMethod.Post, endpoint) { Content = JsonContent.Create(payload) }; request.Headers.TryAddWithoutValidation("x-nexo-nonce", nonce); if (authorized && !string.IsNullOrEmpty(_sessionToken)) request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _sessionToken); using var response = await _http.SendAsync(request, cancellationToken); var raw = await response.Content.ReadAsStringAsync(cancellationToken); // Se comprueba el texto tal como llegó. La firma cubre nonce, estado y cuerpo, también en errores. var verified = _publicKey.Length == 0 || VerifyPublic($"{nonce}.{(int)response.StatusCode}.{raw}", response.Headers.TryGetValues("x-nexo-signature-v2", out var v2) ? string.Join("", v2) : ""); if (!verified && response.IsSuccessStatusCode) return new(false, (int)response.StatusCode, "INVALID_SIGNATURE", "Firma criptográfica del servidor inválida", RawJson: raw); using var json = JsonDocument.Parse(raw); var root = json.RootElement; var success = response.IsSuccessStatusCode && root.TryGetProperty("success", out var ok) && ok.GetBoolean(); var data = root.TryGetProperty("data", out var d) ? d : default; var error = root.TryGetProperty("error", out var e) ? e : default; if (success) { var respNonce = ReadString(data, "nonce"); // Con firma activa el nonce es obligatorio: sin él se podría reutilizar una respuesta capturada. if ((!string.IsNullOrEmpty(respNonce) || !string.IsNullOrEmpty(_appSecret)) && !CryptographicOperations.FixedTimeEquals( Encoding.UTF8.GetBytes(respNonce), Encoding.UTF8.GetBytes(nonce))) { return new(false, (int)response.StatusCode, "REPLAY_DETECTED", "Nonce de respuesta inválido", RawJson: raw); } } if (success && !string.IsNullOrEmpty(_appSecret)) { var sig = response.Headers.TryGetValues("x-nexo-signature", out var hdrs) ? string.Join("", hdrs) : ReadString(root, "signature"); if (!VerifySignature(data, sig)) { return new(false, (int)response.StatusCode, "INVALID_SIGNATURE", "Firma criptográfica del servidor inválida", RawJson: raw); } } var vars = new Dictionary(); if (data.ValueKind == JsonValueKind.Object && data.TryGetProperty("variables", out var vObj) && vObj.ValueKind == JsonValueKind.Object) { foreach (var prop in vObj.EnumerateObject()) vars[prop.Name] = prop.Value.GetString() ?? ""; } var result = new NexoResult( success, (int)response.StatusCode, ReadString(error, "code"), ReadString(error, "message"), ReadString(data, "sessionToken"), ReadNullableInt64(data, "secondsLeft"), ReadInt32(data, data.ValueKind == JsonValueKind.Object && data.TryGetProperty("nextHeartbeatSeconds", out _) ? "nextHeartbeatSeconds" : "heartbeatIntervalSeconds", 45), vars, raw, ReadString(data, "value"), !success && ReadString(error, "code") != "MAINTENANCE" && ((int)response.StatusCode >= 500 || (int)response.StatusCode == 429 || !verified), data.ValueKind == JsonValueKind.Undefined ? default : data.Clone() ); return !result.Ok && string.IsNullOrEmpty(result.ErrorCode) ? result with { ErrorCode = "HTTP_ERROR", Message = "Solicitud rechazada" } : result; } catch (Exception error) when (error is HttpRequestException or TaskCanceledException or JsonException) { return new(false, ErrorCode: "NETWORK_ERROR", Message: error.Message, Transient: true); } } private bool VerifyPublic(string message, string signature) { if (!Regex.IsMatch(signature, "^[0-9a-fA-F]{128}$")) return false; var point = Convert.FromHexString(_publicKey); try { using var key = ECDsa.Create(new ECParameters { Curve = ECCurve.NamedCurves.nistP256, Q = new ECPoint { X = point[1..33], Y = point[33..65] }, }); return key.VerifyData(Encoding.UTF8.GetBytes(message), Convert.FromHexString(signature), HashAlgorithmName.SHA256); } catch (CryptographicException) { return false; } } private bool VerifySignature(JsonElement data, string signature) { if (string.IsNullOrEmpty(_appSecret)) return true; if (string.IsNullOrEmpty(signature) || data.ValueKind == JsonValueKind.Undefined) return false; var hmacKeyHex = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(_appSecret))).ToLowerInvariant(); var dataJson = data.GetRawText(); var expectedHex = Convert.ToHexString(HMACSHA256.HashData( Encoding.UTF8.GetBytes(hmacKeyHex), Encoding.UTF8.GetBytes(dataJson) )).ToLowerInvariant(); return CryptographicOperations.FixedTimeEquals( Encoding.UTF8.GetBytes(expectedHex), Encoding.UTF8.GetBytes(signature.Trim().ToLowerInvariant()) ); } private static string ReadString(JsonElement element, string name) => element.ValueKind == JsonValueKind.Object && element.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String ? value.GetString() ?? "" : ""; private static long? ReadNullableInt64(JsonElement element, string name) => element.ValueKind == JsonValueKind.Object && element.TryGetProperty(name, out var value) && value.TryGetInt64(out var number) ? number : null; private static int ReadInt32(JsonElement element, string name, int fallback) => element.ValueKind == JsonValueKind.Object && element.TryGetProperty(name, out var value) && value.TryGetInt32(out var number) ? number : fallback; /// Solo el identificador de la instalación de Windows: no cambia con las actualizaciones ni al renombrar el PC. public static string GenerateStableHwid() { using var machine = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64); using var key = machine.OpenSubKey(@"SOFTWARE\Microsoft\Cryptography"); var guid = key?.GetValue("MachineGuid")?.ToString(); return string.IsNullOrEmpty(guid) ? LegacyHwid() : Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes("nexo-dotnet|" + guid))).ToLowerInvariant(); } // HWID de versiones anteriores (incluía la versión de Windows): se envía para que el servidor lo sustituya por el nuevo. private static string LegacyHwid() { var machineGuid = Registry.GetValue( @"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography", "MachineGuid", "")?.ToString() ?? ""; var material = string.Join("|", machineGuid, Environment.MachineName, Environment.SystemDirectory, Environment.OSVersion.VersionString, Environment.Is64BitOperatingSystem ? "x64" : "x86"); return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(material))).ToLowerInvariant(); } public async ValueTask DisposeAsync() { await StopHeartbeatAsync(); if (_ownsHttpClient) _http.Dispose(); } }