using System.Net; using System.Net.Http.Headers; using System.Net.Http.Json; using System.Reflection; using System.Security.Claims; using System.Security.Cryptography; using System.Text; using System.Text.Json; using Microsoft.AspNetCore.Antiforgery; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.RateLimiting; using Microsoft.AspNetCore.Hosting.Server; using Microsoft.AspNetCore.Hosting.Server.Features; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using PlotDirector.Companion.Protocol; using PlotLine.Controllers; using PlotLine.Data; using PlotLine.Models; using PlotLine.Services; using PlotLine.Services.NativeCompanion; internal static class NativeCompanionHttpTests { private static T Proxy(Func handler)where T:class{var item=DispatchProxy.Create();((StoryPointProxy)(object)item).Handler=handler;return item;} public static async Task Run() { void Check(bool condition,string message){if(!condition)throw new Exception(message);} var user=new AppUser{UserID=7,SecurityStamp=Guid.NewGuid()};var allowed=true; var other=new AppUser{UserID=8,SecurityStamp=Guid.NewGuid()}; var users=Proxy((name,args)=>Task.FromResult((int)args![0]! ==7?user:(int)args[0]! ==8?other:null)); var repo=Proxy((name,args)=>name switch{ "ListProjectsAsync"=>Task.FromResult>([new(){ProjectId=1,Title="Fixture"}]), "ListBooksAsync"=>Task.FromResult>([new(){BookId=3,Title="Test book"}]), "GetBookStructureAsync"=>Task.FromResult((int)args![0]! ==3?new WordCompanionBookStructureResponse{BookId=3}:null), _=>throw new Exception(name)}); var subscriptions=Proxy((name,args)=>Task.FromResult(new EntitlementDecision{Allowed=allowed})); var json="""{"schemaVersion":"1.0","chapterSummary":"A fictional chapter.","sceneBoundaries":[{"sceneNumber":1,"startParagraph":1,"endParagraph":1,"suggestedTitle":"A narrative scene","structuralSummary":"The characters encounter a new problem and make a decision to resolve the immediate situation.","confidence":0.8,"reason":"A coherent dramatic unit."}]}"""; var provider=new FakeStoryIntelligenceClient(JsonSerializer.Serialize(new{output=new[]{new{content=new[]{new{type="output_text",text=json}}}}})); var coverFile=Path.Combine(Path.GetTempPath(),"pd-native-cover-"+Guid.NewGuid()+".png"); using(var bitmap=new SkiaSharp.SKBitmap(20,30)){using var image=SkiaSharp.SKImage.FromBitmap(bitmap);using var png=image.Encode(SkiaSharp.SKEncodedImageFormat.Png,90);File.WriteAllBytes(coverFile,png.ToArray());} var coverReads=0; var builder=WebApplication.CreateBuilder(new WebApplicationOptions{EnvironmentName="Development"});builder.Logging.ClearProviders();builder.WebHost.UseUrls("http://127.0.0.1:0"); builder.Services.AddSingleton(Proxy((name,args)=>throw new Exception("Activity HTTP admission must not reach a database"))); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddSingleton(provider); builder.Services.AddSingleton(NativeWorkflowTests.Proxy((n,a)=>{if(n=="GetCoverPathsAsync")coverReads++;return Task.FromResult(new(){BookID=3,ProjectID=1,BookTitle="Fixture book",CoverThumbnailPath="/uploads/books/3/cover.webp"});})); builder.Services.AddSingleton(Proxy((n,a)=>n=="TryResolvePublicPath"&&Equals(a![1],"uploads/books/3")?coverFile:throw new Exception("Unexpected cover path lookup"))); builder.Services.AddSingleton(NativeWorkflowTests.Proxy((n,a)=>n=="AnalyseManuscriptAsync"?Task.FromResult(new(){CanImport=true,Message="Preview eligible"}):throw new Exception("Unexpected write "+n))); builder.Services.AddSingleton(NativeWorkflowTests.Proxy((n,a)=>Task.FromResult(null))); builder.Services.AddSingleton(NativeWorkflowTests.Proxy((n,a)=>Task.FromResult(null))); builder.Services.AddSingleton(new MemoryNativeInstallations(user));builder.Services.AddScoped();builder.Services.AddSingleton(users);builder.Services.AddSingleton(repo);builder.Services.AddSingleton(subscriptions); builder.Services.AddSingleton(new EphemeralDataProtectionProvider());builder.Services.AddSingleton(TimeProvider.System);builder.Services.AddSingleton(); builder.Services.AddSingleton(Proxy((n,a)=>throw new Exception("Unexpected character read "+n))); builder.Services.AddSingleton(Proxy((n,a)=>throw new Exception("Unexpected location read "+n)));builder.Services.AddSingleton();builder.Services.AddSingleton();builder.Services.AddSingleton(NativeWorkflowTests.Proxy((n,a)=>n=="List"?Task.FromResult>([]):throw new Exception("Unexpected import write "+n)));builder.Services.AddScoped();builder.Services.AddSingleton();builder.Services.AddSingleton();builder.Services.AddHostedService();builder.Services.AddSingleton();builder.Services.AddSingleton(new MemoryNativeReviews()); builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options=>{options.LoginPath="/fixture-login";options.Cookie.SecurePolicy=Microsoft.AspNetCore.Http.CookieSecurePolicy.None;}) .AddScheme(DesktopPairing.Scheme,_=>{}); builder.Services.AddRateLimiter(o=>o.AddPolicy("native-pair",_=>System.Threading.RateLimiting.RateLimitPartition.GetNoLimiter("fixture"))); builder.Services.AddSignalR();builder.Services.AddAuthorization();builder.Services.AddControllersWithViews().AddApplicationPart(typeof(NativeCompanionController).Assembly); builder.Services.AddSingleton(new ManuscriptStructureAnalysisService(new FakeStoryPromptRepository(),new FakeStoryPromptVersionService(),provider,new ChapterStructureValidator(),NullLogger.Instance)); await using var app=builder.Build();app.UseRouting();app.UseRateLimiter();app.UseAuthentication();app.UseAuthorization(); app.MapGet("/fixture-login",async (Microsoft.AspNetCore.Http.HttpContext context)=>{await context.SignInAsync(new ClaimsPrincipal(new ClaimsIdentity([new(ClaimTypes.NameIdentifier,"7"),new("PlotLine.SecurityStamp",user.SecurityStamp.ToString())],CookieAuthenticationDefaults.AuthenticationScheme)));return "Fixture login";}); app.MapGet("/fixture-antiforgery",(IAntiforgery xsrf,Microsoft.AspNetCore.Http.HttpContext context)=>xsrf.GetAndStoreTokens(context).RequestToken); app.MapGet("/fixture-render-review/{id:guid}",async (Guid id,Microsoft.AspNetCore.Http.HttpContext context)=>{ var row=await context.RequestServices.GetRequiredService().Get(7,id);if(row==null)return Microsoft.AspNetCore.Http.Results.NotFound(); var action=new Microsoft.AspNetCore.Mvc.ActionContext(context,new Microsoft.AspNetCore.Routing.RouteData(),new Microsoft.AspNetCore.Mvc.Abstractions.ActionDescriptor()); var views=context.RequestServices.GetRequiredService();var view=views.GetView(null,"/Views/NativeWorkspace/Review.cshtml",false);if(!view.Success)throw new Exception("Native review Razor view unavailable"); using var writer=new StringWriter();var data=new Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary(new Microsoft.AspNetCore.Mvc.ModelBinding.EmptyModelMetadataProvider(),new Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary()){Model=new NativeReviewModel(row,JsonSerializer.Deserialize(row.ResultJson)!,string.IsNullOrEmpty(row.DecisionsJson)?[]:JsonSerializer.Deserialize(row.DecisionsJson)!,[],1)}; var temp=new Microsoft.AspNetCore.Mvc.ViewFeatures.TempDataDictionary(context,context.RequestServices.GetRequiredService()); await view.View.RenderAsync(new Microsoft.AspNetCore.Mvc.Rendering.ViewContext(action,view.View,data,temp,writer,new Microsoft.AspNetCore.Mvc.ViewFeatures.HtmlHelperOptions()));return Microsoft.AspNetCore.Http.Results.Content(writer.ToString(),"text/html"); }).RequireAuthorization(); app.MapHub("/hubs/native-companion");app.MapHub("/hubs/native-companion-agent",o=>o.CloseOnAuthenticationExpiration=true);app.MapControllers();await app.StartAsync(); try { var address=app.Services.GetRequiredService().Features.Get()!.Addresses.Single(); using var browserHandler=new HttpClientHandler{AllowAutoRedirect=false};using var browser=new HttpClient(browserHandler){BaseAddress=new Uri(address)}; using var agent=new HttpClient(new HttpClientHandler{AllowAutoRedirect=false,UseCookies=false}){BaseAddress=new Uri(address)}; Check((await agent.GetAsync("/api/native-companion/books")).StatusCode==HttpStatusCode.Unauthorized,"Native API is not anonymous"); Check((await agent.PostAsJsonAsync("/api/native-companion/writing-activity",new{})).StatusCode==HttpStatusCode.Unauthorized,"Activity observation requires a native grant before any database access"); Check((await agent.PostAsJsonAsync($"/api/native-companion/instances/{Guid.NewGuid()}/documents/{Guid.NewGuid()}/audio-review",new AudioReviewObservation{BookID=3,Sequence=1})).StatusCode==HttpStatusCode.Unauthorized,"Audio media observations require native authentication before database access"); var anonymousHub=(await agent.PostAsync("/hubs/native-companion/negotiate?negotiateVersion=1",null)).StatusCode;Check(anonymousHub is HttpStatusCode.Unauthorized or HttpStatusCode.Redirect,"Anonymous native hub subscription refused"); var verifier=new string('d',64);var challenge=Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(verifier))); var oversized=await agent.PostAsJsonAsync("/api/native-companion/pair",new{challenge=new string('A',64),padding=new string('x',5000)});Check(!oversized.IsSuccessStatusCode,"Oversized pairing bodies are refused before pairing state creation"); var paired=await agent.PostAsJsonAsync("/api/native-companion/pair",new{challenge});Check(paired.IsSuccessStatusCode,"Pairing start accepts verifier challenge"); var code=(await paired.Content.ReadFromJsonAsync()).GetProperty("code").GetString()!; Check((await browser.GetAsync("/native-companion/authorize?code="+code)).StatusCode==HttpStatusCode.Redirect,"Browser approval requires existing site sign-in"); await browser.GetAsync("/fixture-login"); var approval=await browser.GetAsync("/native-companion/authorize?code="+code);Check(approval.IsSuccessStatusCode&&(await approval.Content.ReadAsStringAsync()).Contains("Approve this Word Companion connection"),"Actual approval view renders before any upload"); Check((await browser.PostAsync("/native-companion/authorize",new FormUrlEncodedContent(new Dictionary{{"code",code}}))).StatusCode==HttpStatusCode.BadRequest,"Approval enforces antiforgery"); var antiforgery=await browser.GetStringAsync("/fixture-antiforgery"); Check((await browser.PostAsync("/native-companion/authorize",new FormUrlEncodedContent(new Dictionary{{"code",code},{"retainImport","true"},{"__RequestVerificationToken",antiforgery}}))).IsSuccessStatusCode,"Authenticated antiforgery approval succeeds"); var redeemed=await agent.PostAsJsonAsync("/api/native-companion/token",new{code,verifier});Check(redeemed.IsSuccessStatusCode,"Agent redeems approved pairing"); var token=(await redeemed.Content.ReadFromJsonAsync()).GetProperty("accessToken").GetString();agent.DefaultRequestHeaders.Authorization=new AuthenticationHeaderValue("Bearer",token); Check((await agent.PostAsJsonAsync($"/api/native-companion/instances/{Guid.NewGuid()}/documents/{Guid.NewGuid()}/audio-review",new AudioReviewObservation{BookID=3,Sequence=1})).StatusCode==HttpStatusCode.Forbidden,"Audio media observations require an exact current native lease before database access"); Check((await agent.PostAsJsonAsync("/api/native-companion/writing-activity",new{})).StatusCode==HttpStatusCode.BadRequest,"Native activity rejects malformed identities before database access"); Check((await agent.GetFromJsonAsync("/api/native-companion/books"))!.Single().BookId==3,"Grant loads authorized books through actual routing"); var listed=(await agent.GetFromJsonAsync("/api/native-companion/books"))!.Single();Check(listed.ProjectTitle=="Fixture"&&listed.BookTitle=="Test book","Native book selection includes author-facing project and book names"); Check((await agent.GetAsync("/api/native-companion/books/999/cover")).StatusCode==HttpStatusCode.Forbidden&&coverReads==0,"Foreign book cover denied before private file lookup"); var cover=await agent.GetFromJsonAsync("/api/native-companion/books/3/cover");Check(coverReads==1&&Convert.FromBase64String(cover!.Png).Take(4).SequenceEqual(new byte[]{137,80,78,71}),"Authorised cover uses an actual bounded PNG suitable for Windows"); Check((await agent.GetFromJsonAsync("/api/native-companion/connection"))?.Authentication=="verified","Authenticated health verifies current session and configuration without paid AI request"); Check((await agent.GetFromJsonAsync("/api/native-companion/books/3/workspace"))?.State=="saved-book","Saved workspace is scoped to accessible book over actual HTTP"); var preview=await agent.PostAsJsonAsync("/api/native-companion/import-preview",NativeWorkflowTests.Selection());Check(preview.IsSuccessStatusCode&&(await preview.Content.ReadFromJsonAsync())?.CommitAvailable==false,"HTTP import preview is read-only with commit explicitly unavailable"); var request=new AiChapterRequest{BookId=3,ManuscriptId=Guid.NewGuid(),SessionId=Guid.NewGuid(),RequestId=Guid.NewGuid(),ChapterStart=20,ChapterEnd=40,Paragraphs=[new(){Index=1,Start=20,End=40,Text="A fictional narrative paragraph."}]}; var response=await agent.PostAsJsonAsync("/api/native-companion/analyse-chapter",request);Check(response.IsSuccessStatusCode,"Authenticated chapter API calls canonical service"); var result=await response.Content.ReadFromJsonAsync();Check(result?.State=="complete"&&result.Scenes.Single().Start==20&&provider.Prompts.Count==1,"Actual HTTP response maps scene to Word position"); Check((await agent.PostAsJsonAsync("/api/native-companion/analyse-chapter",request)).IsSuccessStatusCode&&provider.Prompts.Count==1,"HTTP retry reuses successful provider result"); Check(result!.ReviewPath.StartsWith("/native-companion/reviews/")&&!string.IsNullOrWhiteSpace(result.Scenes.Single().Summary),"AI summary is preserved and saved PWA review handoff returned"); var reviewId=Guid.Parse(result.ReviewPath.Split('/').Last());var reviewHtml=await browser.GetStringAsync("/fixture-render-review/"+reviewId);Check(reviewHtml.Contains("Save review decisions")&&reviewHtml.Contains("Summary")&&reviewHtml.Contains("scene"),"Actual compiled Razor review renders AI title/summary form"); var decisionFields=new Dictionary{{"version","1"},{"scenes[0].Index","0"},{"scenes[0].State","approved"},{"scenes[0].Title",""},{"scenes[0].Summary","Edited summary"},{"__RequestVerificationToken",antiforgery}}; Check((await browser.PostAsync(result.ReviewPath,new FormUrlEncodedContent(decisionFields))).StatusCode==HttpStatusCode.Redirect,"Actual antiforgery-protected form binds and saves review decisions"); Check((await browser.PostAsync(result.ReviewPath,new FormUrlEncodedContent(decisionFields))).StatusCode==HttpStatusCode.Conflict,"Actual stale review form receives conflict without overwriting");reviewHtml=await browser.GetStringAsync("/fixture-render-review/"+reviewId);Check(!reviewHtml.Contains("")&&reviewHtml.Contains("Edited summary"),"Saved title is encoded while edited summary remains reviewable"); request.RequestId=Guid.NewGuid();var reused=await agent.PostAsJsonAsync("/api/native-companion/analyse-chapter",request);Check(reused.IsSuccessStatusCode&&provider.Prompts.Count==1,"Unchanged chapter content reuses durable suggestion across new request identifiers"); Check((await reused.Content.ReadFromJsonAsync())?.SourceRetained==true,"Retaining source requires explicit opt-in and reuses analysis without another provider call"); using(var previewScope=app.Services.CreateScope()){var plan=await previewScope.ServiceProvider.GetRequiredService().Preview(7,3,[reviewId]);Check(plan.Conflicts.Length==0&&plan.Items.Single().Scenes.Single().Text==request.Paragraphs.Single().Text,"Actual HTTP retained source and approved decisions produce an exact-prose import preview");} var negotiation=await browser.PostAsync("/hubs/native-companion/negotiate?negotiateVersion=1",null);Check(negotiation.IsSuccessStatusCode,"Native presence hub requires normal browser authentication and negotiates after sign-in"); var connectionToken=(await negotiation.Content.ReadFromJsonAsync()).GetProperty("connectionToken").GetString(); using var socket=new System.Net.WebSockets.ClientWebSocket();socket.Options.Cookies=browserHandler.CookieContainer;using var socketTimeout=new CancellationTokenSource(TimeSpan.FromSeconds(10)); await socket.ConnectAsync(new Uri(address.Replace("http://","ws://")+"/hubs/native-companion?id="+Uri.EscapeDataString(connectionToken!)),socketTimeout.Token); await socket.SendAsync(Encoding.UTF8.GetBytes("{\"protocol\":\"json\",\"version\":1}\u001e"),System.Net.WebSockets.WebSocketMessageType.Text,true,socketTimeout.Token); var socketBuffer=new byte[4096];await socket.ReceiveAsync(socketBuffer,socketTimeout.Token); var firstInstance=Guid.NewGuid();var firstSession=Guid.NewGuid();var firstDocument=new NativePresence{BookId=0,ManuscriptId=Guid.NewGuid(),WordRunning=true,CanCapture=true,Sequence=1,DocumentTitle="Unassociated manuscript",ChapterId=999,SceneId=999}; var firstPresence=await agent.PostAsJsonAsync($"/api/native-companion/instances/{firstInstance}/documents/{firstSession}/presence",firstDocument); var firstReply=await firstPresence.Content.ReadFromJsonAsync();Check(firstPresence.IsSuccessStatusCode&&firstReply?.ChapterId==null&&firstReply?.SceneId==null,"Authenticated unassociated Word session is visible but cannot claim saved chapter/scene data"); var status=await browser.GetFromJsonAsync("/native-companion/status");Check(status.EnumerateArray().Any(l=>l.GetProperty("bookId").GetInt32()==0&&l.GetProperty("wordRunning").GetBoolean()),"Browser sees its own unassociated manuscript without requiring a pre-existing book association"); await agent.DeleteAsync($"/api/native-companion/instances/{firstInstance}/documents/{firstSession}/presence"); var instance=Guid.NewGuid();var document=Guid.NewGuid();var live=new NativePresence{BookId=3,ManuscriptId=request.ManuscriptId,Sequence=1,DocumentTitle="Synthetic manuscript"}; Check((await agent.PostAsJsonAsync($"/api/native-companion/instances/{instance}/documents/{document}/presence",live)).IsSuccessStatusCode,"Actual bearer-scoped presence accepted"); Check((await agent.PostAsJsonAsync($"/api/native-companion/instances/{instance}/documents/{document}/audio-review",new AudioReviewObservation{BookID=3,Sequence=1,Version=2})).StatusCode==HttpStatusCode.BadRequest,"Audio media rejects unsupported versions before database access"); var notification=await socket.ReceiveAsync(socketBuffer,socketTimeout.Token);Check(Encoding.UTF8.GetString(socketBuffer,0,notification.Count).Contains("NativePresenceChanged"),"Authenticated native hub pushes only invalidation, not prose or navigation feedback");socket.Abort(); var leases=await browser.GetFromJsonAsync("/native-companion/presence?bookId=3");Check(leases?.Length==1,"Authenticated browser sees scoped native session without prose"); Check((await agent.PostAsJsonAsync($"/api/native-companion/instances/{instance}/documents/{document}/presence",live)).StatusCode==HttpStatusCode.Conflict,"Actual HTTP stale sequence refused"); Check((await browser.PostAsync(result.ReviewPath,new FormUrlEncodedContent(new Dictionary{{"version","1"}}))).StatusCode==HttpStatusCode.BadRequest,"Review decisions require antiforgery"); Check((await agent.PostAsync("/api/native-companion/presence/disconnect",null)).IsSuccessStatusCode,"Signout disconnect revokes grant presence"); live.Sequence=2;Check((await agent.PostAsJsonAsync($"/api/native-companion/instances/{instance}/documents/{document}/presence",live)).StatusCode==HttpStatusCode.Conflict,"Late heartbeat cannot restore signed-out presence"); request.BookId=999;Check((await agent.PostAsJsonAsync("/api/native-companion/analyse-chapter",request)).StatusCode==HttpStatusCode.Forbidden&&provider.Prompts.Count==1,"Foreign book rejected without provider charge");request.BookId=3; allowed=false;Check((await agent.PostAsJsonAsync("/api/native-companion/analyse-chapter",request)).StatusCode==HttpStatusCode.Forbidden,"Subscription access enforced on HTTP path");allowed=true; var runtime=Guid.NewGuid();var devicePair=await agent.PostAsJsonAsync("/api/native-companion/pair",new{challenge,persistent=true,connectionId=runtime,deviceName="HTTP fixture installation"});var deviceCode=(await devicePair.Content.ReadFromJsonAsync()).GetProperty("code").GetString()!; await browser.PostAsync("/native-companion/authorize",new FormUrlEncodedContent(new Dictionary{{"code",deviceCode},{"__RequestVerificationToken",antiforgery}})); var device=(await(await agent.PostAsJsonAsync("/api/native-companion/token",new{code=deviceCode,verifier})).Content.ReadFromJsonAsync())!; agent.DefaultRequestHeaders.Authorization=new("Bearer",device.AccessToken);Check((await agent.GetAsync("/api/native-companion/books")).IsSuccessStatusCode,"Actual HTTP trusted installation authenticates"); var rotate=new NativeDeviceRenew(device.InstallationId,device.DeviceSecret!,new string('C',64),Guid.NewGuid(),runtime);var rotatedResponse=await agent.PostAsJsonAsync("/api/native-companion/renew",rotate);Check(rotatedResponse.IsSuccessStatusCode,"Actual HTTP access renewal does not need browser approval"); var renewed=(await rotatedResponse.Content.ReadFromJsonAsync())!;Check((await agent.PostAsJsonAsync("/api/native-companion/renew",rotate)).IsSuccessStatusCode,"Actual HTTP rotation retry is idempotent"); Check((await agent.PostAsJsonAsync("/api/native-companion/renew",rotate with{RotationId=Guid.NewGuid()})).StatusCode==HttpStatusCode.Unauthorized,"Actual HTTP stale credential cannot start another rotation"); agent.DefaultRequestHeaders.Authorization=new("Bearer",renewed.AccessToken);Check((await agent.PostAsJsonAsync("/api/native-companion/revoke",rotate with{Credential=new string('C',64),NextCredential=""})).IsSuccessStatusCode,"Explicit trusted sign-out revokes installation over HTTP");Check((await agent.GetAsync("/api/native-companion/books")).StatusCode==HttpStatusCode.Unauthorized,"Actual HTTP revocation invalidates unexpired access immediately"); await NativeSignalRTests.Run(app,address,user,other); agent.DefaultRequestHeaders.Authorization=new("Bearer",token); user.SecurityStamp=Guid.NewGuid();Check((await agent.GetAsync("/api/native-companion/books")).StatusCode==HttpStatusCode.Unauthorized,"Revoked grant rejected through HTTP handler"); } finally{await app.StopAsync();File.Delete(coverFile);} Console.WriteLine("PASS actual HTTP native pairing, antiforgery, bearer/stamp, book/subscription access, canonical AI/idempotency, persistent review and live WebSocket invalidation (synthetic provider, no database)"); } }