using System.Diagnostics; using System.Net; using System.Net.Http.Headers; using System.Net.Http.Json; using System.Security.Cryptography; using System.Text; using System.Text.Json; using PlotDirector.Companion.Protocol; namespace PlotDirector.Companion.Agent; // All browser launching, HTTP and credentials stay in the agent. Tokens are memory-only. public sealed class CloudGateway : IDisposable { private readonly object gate=new(); private readonly HttpClient http; private readonly Action openBrowser; private CancellationTokenSource? pairing; private Uri? origin; private string? token; private string state="Not signed in"; private CompanionBook[] books=[]; private readonly string? settingsPath; private static readonly JsonSerializerOptions Json=new(JsonSerializerDefaults.Web); public CloudGateway(HttpMessageHandler? handler=null,Action? browser=null,string? settingsPath=null) { http=new(handler??new HttpClientHandler{AllowAutoRedirect=false}){Timeout=TimeSpan.FromMinutes(6)}; openBrowser=browser??(url=>Process.Start(new ProcessStartInfo(url){UseShellExecute=true}));this.settingsPath=settingsPath; } public static Uri ValidateOrigin(string value) { if(!Uri.TryCreate(value,UriKind.Absolute,out var uri)||uri.Scheme!=Uri.UriSchemeHttps||!string.IsNullOrEmpty(uri.UserInfo)||uri.AbsolutePath!="/"||!string.IsNullOrEmpty(uri.Query)||!string.IsNullOrEmpty(uri.Fragment))throw new ArgumentException("Enter the HTTPS PlotDirector site root."); return uri; } public Message Status() {lock(gate)return new(){Status=state,Books=books,ServerUrl=origin?.AbsoluteUri??ReadOrigin()};} private string ReadOrigin(){try{return settingsPath!=null&&File.Exists(settingsPath)?File.ReadAllText(settingsPath):"";}catch(IOException){return "";}} public void Connect(string address) { var uri=ValidateOrigin(address);CancellationTokenSource stop; lock(gate){pairing?.Cancel();pairing=stop=new(TimeSpan.FromMinutes(5));origin=uri;token=null;books=[];state="Starting browser sign-in…";} _=Task.Run(async()=>{ try { if(settingsPath!=null){Directory.CreateDirectory(Path.GetDirectoryName(settingsPath)!);await File.WriteAllTextAsync(settingsPath,uri.AbsoluteUri,stop.Token);} var verifier=Convert.ToHexString(RandomNumberGenerator.GetBytes(32)); var challenge=Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(verifier))); using var start=await http.PostAsJsonAsync(new Uri(uri,"api/native-companion/pair"),new{challenge},stop.Token);start.EnsureSuccessStatusCode(); var data=await start.Content.ReadFromJsonAsync(Json,stop.Token)??throw new InvalidDataException(); if(data.Code==null||data.Code.Length!=24||!data.Code.All(Uri.IsHexDigit))throw new InvalidDataException(); lock(gate)if(pairing==stop)state="Approve in browser · code "+data.Code[^6..]; openBrowser(new Uri(uri,"native-companion/authorize?code="+data.Code).AbsoluteUri); while(!stop.IsCancellationRequested) { await Task.Delay(2000,stop.Token); using var response=await http.PostAsJsonAsync(new Uri(uri,"api/native-companion/token"),new{code=data.Code,verifier},stop.Token); if(response.StatusCode==HttpStatusCode.Accepted)continue; response.EnsureSuccessStatusCode();var grant=await response.Content.ReadFromJsonAsync(Json,stop.Token)??throw new InvalidDataException(); using var request=new HttpRequestMessage(HttpMethod.Get,new Uri(uri,"api/native-companion/books"));request.Headers.Authorization=new("Bearer",grant.AccessToken); using var list=await http.SendAsync(request,stop.Token);list.EnsureSuccessStatusCode(); var available=await list.Content.ReadFromJsonAsync(Json,stop.Token)??[]; lock(gate)if(pairing==stop&&!stop.IsCancellationRequested){token=grant.AccessToken;books=available.Where(b=>b!=null&&b.BookId>0&&b.Title!=null).Take(200).Select(b=>new CompanionBook{BookId=b.BookId,Title=b.Title.Length>160?b.Title[..160]:b.Title}).ToArray();state="Signed in (four-hour grant)";} return; } } catch(Exception e)when(e is HttpRequestException or OperationCanceledException or IOException or JsonException or System.ComponentModel.Win32Exception or UnauthorizedAccessException or InvalidOperationException or ArgumentException) {lock(gate)if(pairing==stop)state="Sign-in failed or expired. Check the site address and try Connect again.";} }); } public void SignOut(){lock(gate){pairing?.Cancel();pairing=null;token=null;books=[];state="Not signed in";}} public async Task Analyse(AiChapterRequest chapter,CancellationToken cancellation) { Uri site;string access; lock(gate){site=origin??throw new InvalidOperationException("Connect to PlotDirector first.");access=token??throw new InvalidOperationException("Sign in first.");} using var request=new HttpRequestMessage(HttpMethod.Post,new Uri(site,"api/native-companion/analyse-chapter")){Content=JsonContent.Create(chapter,options:Json)}; request.Headers.Authorization=new AuthenticationHeaderValue("Bearer",access); using var response=await http.SendAsync(request,HttpCompletionOption.ResponseHeadersRead,cancellation); if(response.StatusCode==HttpStatusCode.Unauthorized){lock(gate)if(token==access){token=null;books=[];state="Sign-in expired. Connect again.";}throw new InvalidOperationException("Sign-in expired. Connect again.");} if(!response.IsSuccessStatusCode)throw new InvalidOperationException(response.StatusCode switch{HttpStatusCode.Forbidden=>"Book/subscription access denied.",HttpStatusCode.TooManyRequests=>"Server busy. Retry this chapter later.",HttpStatusCode.BadRequest=>"Chapter mapping or size was rejected. Check boundaries.",_=>"Server unavailable. Check the deployed native API."}); // Bound server response before deserializing; never log a body/provider message. await using var stream=await response.Content.ReadAsStreamAsync(cancellation);using var buffer=new MemoryStream();var bytes=new byte[8192]; int count;while((count=await stream.ReadAsync(bytes,cancellation))>0){if(buffer.Length+count>1024*1024)throw new InvalidDataException("AI response too large.");buffer.Write(bytes,0,count);} buffer.Position=0;var result=await JsonSerializer.DeserializeAsync(buffer,Json,cancellation)??throw new InvalidDataException(); if(result.RequestId!=chapter.RequestId||result.Scenes==null||result.Scenes.Length>500||result.Scenes.Any(s=>s==null||s.Startchapter.ChapterEnd||s.End<=s.Start||s.Title.Length>200||s.Reason.Length>600))throw new InvalidDataException("Invalid AI mapping."); return result; } public async Task CancelRemote(Guid id) { try { Uri? site;string? access;lock(gate){site=origin;access=token;}if(site==null||access==null)return; using var timeout=new CancellationTokenSource(TimeSpan.FromSeconds(5));using var request=new HttpRequestMessage(HttpMethod.Post,new Uri(site,$"api/native-companion/analysis/{id}/cancel"));request.Headers.Authorization=new("Bearer",access); using var response=await http.SendAsync(request,timeout.Token); } catch(Exception e)when(e is HttpRequestException or OperationCanceledException){ } } public void Dispose(){SignOut();http.Dispose();} private sealed record PairStart(string Code); private sealed record TokenReply(string AccessToken); }