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 Guid authenticationContext=Guid.NewGuid(); private string state="Not signed in"; private ConnectionHealth health=new(); private int checking;private DateTime nextCheck; private readonly Dictionary successful=[]; 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() { bool refresh;Message answer; lock(gate){Expire();refresh=token!=null&&DateTime.UtcNow>=nextCheck;answer=new(){Status=state,Books=books,AuthenticationContext=authenticationContext,ServerUrl=origin?.AbsoluteUri??ReadOrigin(),Health=CopyHealth()};} if(refresh)_=CheckConnection();return answer; } private ConnectionHealth CopyHealth()=>new(){Server=health.Server,Authentication=health.Authentication,Ai=health.Ai,Explanation=health.Explanation,VerifiedUtc=health.VerifiedUtc,ExpiresUtc=health.ExpiresUtc}; private void Expire(){if(token!=null&&health.ExpiresUtc!=default&&DateTime.UtcNow>=health.ExpiresUtc){authenticationContext=Guid.NewGuid();token=null;books=[];state="Sign-in expired. Connect again.";health.Authentication="expired";health.Ai="unknown";}} public async Task CheckConnection() { if(Interlocked.Exchange(ref checking,1)!=0)return; Guid context;lock(gate){context=authenticationContext;nextCheck=DateTime.UtcNow.AddMinutes(2);health.Server="checking";} try{var result=await Get("api/native-companion/connection",context);var accessible=await Get("api/native-companion/books",context);lock(gate)if(authenticationContext==context){books=accessible.Where(b=>b!=null&&b.BookId>0&&b.Title!=null).Take(200).ToArray();result.VerifiedUtc=DateTime.UtcNow;health=result;state="Signed in (verified)";}} catch(Exception e)when(e is HttpRequestException or IOException or InvalidDataException or InvalidOperationException or OperationCanceledException or JsonException){lock(gate)if(authenticationContext==context){health.Server=token==null?"unknown":"offline";health.Explanation="Server verification failed. Check connection; local detection remains available.";}} finally{Volatile.Write(ref checking,0);} } 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);DisconnectPresence();CancellationTokenSource stop; lock(gate){pairing?.Cancel();pairing=stop=new(TimeSpan.FromMinutes(5));origin=uri;authenticationContext=Guid.NewGuid();token=null;books=[];health=new(){Server="connecting",Authentication="pending"};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)";health=new(){Server="online",Authentication="verified",VerifiedUtc=DateTime.UtcNow,ExpiresUtc=DateTime.UtcNow.AddHours(4),Ai="unknown",Explanation="Book list verified; checking AI configuration."};nextCheck=DateTime.MinValue;} return; } } catch(Exception e)when(e is HttpRequestException or OperationCanceledException or IOException or InvalidDataException 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.";health=new(){Server="unverified",Authentication="not-signed-in",Explanation=state};}} }); } public void SignOut(){DisconnectPresence();lock(gate){pairing?.Cancel();pairing=null;authenticationContext=Guid.NewGuid();token=null;books=[];state="Not signed in";health=new();successful.Clear();}} public bool Allows(Guid context,int bookId) {lock(gate){Expire();return token!=null&&context==authenticationContext&&books.Any(b=>b.BookId==bookId);}} public async Task Analyse(AiChapterRequest chapter,CancellationToken cancellation,Guid expectedContext) { var fingerprint=expectedContext+":"+chapter.BookId+":"+chapter.ManuscriptId+":"+Convert.ToHexString(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(new{chapter.ChapterStart,chapter.ChapterEnd,chapter.Paragraphs}))); Uri site;string access; lock(gate){Expire();if(successful.TryGetValue(fingerprint,out var prior)&&authenticationContext==expectedContext&&token!=null)return new(){SourceRetained=prior.SourceRetained,RequestId=chapter.RequestId,DocumentRevision=chapter.Revision,ChapterTitle=chapter.ChapterTitle,State="complete",Message="Unchanged chapter: reused saved AI suggestions without uploading prose.",ReviewPath=prior.ReviewPath,Scenes=prior.Scenes};if(authenticationContext!=expectedContext)throw new InvalidOperationException("Connection/account changed. Confirm the chapter upload again.");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); HttpResponseMessage responseValue; try{responseValue=await http.SendAsync(request,HttpCompletionOption.ResponseHeadersRead,cancellation);} catch(HttpRequestException){lock(gate)if(authenticationContext==expectedContext){health.Server="offline";health.Explanation="AI request could not reach the server.";}throw;} using var response=responseValue; if(response.StatusCode==HttpStatusCode.Unauthorized){lock(gate)if(token==access){authenticationContext=Guid.NewGuid();token=null;books=[];state="Sign-in expired. Connect again.";health.Authentication="expired";health.Server="online";health.Ai="unknown";}throw new InvalidOperationException("Sign-in expired. Connect again.");} if(!response.IsSuccessStatusCode){lock(gate)if(authenticationContext==expectedContext){health.Server="degraded";health.Ai="request-failed";health.Explanation="AI request rejected or unavailable; see chapter results.";}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.State is not ("complete" or "failed" or "cancelled")||result.Message==null||result.Message.Length>2048||result.Scenes==null||result.Scenes.Length>500||result.Scenes.Any(s=>s==null||s.Startchapter.ChapterEnd||s.End<=s.Start||s.Title==null||s.Reason==null||s.Summary==null||s.Summary.Length>600||s.Confidence==null||s.Confidence.Length>32||s.Kind!="Scene"||s.Origin!="AI"||s.Title.Length>200||s.Reason.Length>600))throw new InvalidDataException("Invalid AI mapping."); lock(gate)if(authenticationContext==expectedContext){health.Server="online";health.Authentication="verified";health.VerifiedUtc=DateTime.UtcNow;health.Ai=result.State=="complete"?"last-request-succeeded":"request-failed";health.Explanation=result.Message;if(result.State=="complete"){if(successful.Count>=64||successful.Values.Sum(r=>r.Scenes.Length)+result.Scenes.Length>8192)successful.Clear();successful[fingerprint]=result;}} return result; } public async Task Get(string path,Guid expectedContext) =>await Send(HttpMethod.Get,path,null,expectedContext); public async Task Post(string path,object body,Guid expectedContext) =>await Send(HttpMethod.Post,path,body,expectedContext); private async Task Send(HttpMethod method,string path,object? body,Guid context) { Uri site;string access;lock(gate){Expire();if(context!=authenticationContext||token==null)throw new InvalidOperationException("Sign in again and reselect the book.");site=origin!;access=token;} using var stop=new CancellationTokenSource(TimeSpan.FromSeconds(15));using var request=new HttpRequestMessage(method,new Uri(site,path));request.Headers.Authorization=new("Bearer",access);if(body!=null)request.Content=JsonContent.Create(body,options:Json); try { using var response=await http.SendAsync(request,HttpCompletionOption.ResponseHeadersRead,stop.Token); if(response.StatusCode==HttpStatusCode.Unauthorized){lock(gate)if(authenticationContext==context){authenticationContext=Guid.NewGuid();token=null;books=[];state="Sign-in expired. Connect again.";health.Authentication="expired";}throw new InvalidOperationException("Sign-in expired. Connect again.");} if(!response.IsSuccessStatusCode&&!(response.StatusCode==HttpStatusCode.BadRequest&&path=="api/native-companion/import-preview")){lock(gate)if(context==authenticationContext){health.Server=response.StatusCode is HttpStatusCode.Forbidden or HttpStatusCode.NotFound?"online":"degraded";health.VerifiedUtc=DateTime.UtcNow;health.Explanation="Server rejected the saved-data request. See the document result.";if(response.StatusCode==HttpStatusCode.Forbidden)books=[];}throw new InvalidOperationException(response.StatusCode==HttpStatusCode.Forbidden?"Access denied or subscription unavailable.":response.StatusCode==HttpStatusCode.NotFound?"No saved chapter/scene matches this book and Word marker.":"Server request failed. Check connection or update the server.");} await using var stream=await response.Content.ReadAsStreamAsync(stop.Token);using var buffer=new MemoryStream();var bytes=new byte[8192];int size; while((size=await stream.ReadAsync(bytes,stop.Token))>0){if(buffer.Length+size>1024*1024)throw new InvalidDataException();buffer.Write(bytes,0,size);}buffer.Position=0; var result=await JsonSerializer.DeserializeAsync(buffer,Json,stop.Token); lock(gate){if(context!=authenticationContext)throw new InvalidOperationException("Connection changed; discarded old response.");health.Server="online";health.Authentication="verified";health.VerifiedUtc=DateTime.UtcNow;} return result??throw new InvalidDataException(); } catch(OperationCanceledException){lock(gate)if(context==authenticationContext){health.Server="degraded";health.Explanation="Server verification timed out. Check connection before continuing.";}throw;} catch(HttpRequestException){lock(gate)if(context==authenticationContext){health.Server="offline";health.Explanation="Server unreachable. Saved information is not current.";}throw;} } public void OpenSavedPage(string path,Guid context) { lock(gate){Expire();if(context!=authenticationContext||token==null||origin==null)throw new InvalidOperationException("Sign in first."); if(!path.StartsWith("/Books/Details/",StringComparison.Ordinal)&&!path.StartsWith("/Writing/Context?",StringComparison.Ordinal)&&!path.StartsWith("/Writing/Intent?",StringComparison.Ordinal))throw new InvalidDataException(); var url=new Uri(origin,path);if(url.GetLeftPart(UriPartial.Authority)!=origin.GetLeftPart(UriPartial.Authority))throw new InvalidDataException();openBrowser(url.AbsoluteUri);} } public void OpenSite(string page="book") {Uri target;lock(gate){var site=origin??ValidateOrigin(ReadOrigin());target=new Uri(site,page switch{"help"=>"help/word-companion/install","context"=>"Writing/Context","intent"=>"Writing/Intent",_=>"/"});}openBrowser(target.AbsoluteUri);} private void DisconnectPresence(){Uri? site;string? access;lock(gate){site=origin;access=token;}if(site==null||access==null)return;_ = Task.Run(async()=>{try{using var timeout=new CancellationTokenSource(TimeSpan.FromSeconds(5));using var request=new HttpRequestMessage(HttpMethod.Post,new Uri(site,"api/native-companion/presence/disconnect"));request.Headers.Authorization=new("Bearer",access);using var response=await http.SendAsync(request,timeout.Token);}catch(Exception e)when(e is HttpRequestException or OperationCanceledException or ObjectDisposedException) {}});} public void OpenCompanionPage(string path,Guid context) {lock(gate){Expire();if(context!=authenticationContext||token==null||origin==null)throw new InvalidOperationException("Sign in first.");if(!path.StartsWith("/native-companion/",StringComparison.Ordinal))throw new InvalidDataException();var url=new Uri(origin,path);if(url.GetLeftPart(UriPartial.Authority)!=origin.GetLeftPart(UriPartial.Authority))throw new InvalidDataException();openBrowser(url.AbsoluteUri);}} public async Task Presence(Guid instance,Guid session,NativePresence presence,Guid context)=>await Post($"api/native-companion/instances/{instance}/documents/{session}/presence",presence,context); public async Task RemovePresence(Guid instance,Guid session){Guid context;lock(gate)context=authenticationContext;try{await Send(HttpMethod.Delete,$"api/native-companion/instances/{instance}/documents/{session}/presence",null,context);}catch(Exception e)when(e is HttpRequestException or IOException or InvalidDataException or InvalidOperationException or OperationCanceledException or JsonException or ObjectDisposedException){}} 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); }