From 099792cad1ec5efa95eb7ecf1728ad8646894f7e Mon Sep 17 00:00:00 2001 From: Nick Beckley Date: Sun, 8 Nov 2026 19:50:44 +0000 Subject: [PATCH] Keep healthy Word capture authorisation alive and report precise rejection reasons --- Docs/WordCompanion/2026-11-08-capture-403.md | 32 ++++++++ PlotLine.Tests/NativeCaptureLifetimeTests.cs | 55 ++++++++++++++ PlotLine.Tests/Program.cs | 1 + .../NativeManuscriptCaptureController.cs | 3 + .../Controllers/NativePresenceController.cs | 2 +- .../NativeManuscriptCapture.cs | 74 +++++++++++++++---- 6 files changed, 150 insertions(+), 17 deletions(-) create mode 100644 Docs/WordCompanion/2026-11-08-capture-403.md create mode 100644 PlotLine.Tests/NativeCaptureLifetimeTests.cs diff --git a/Docs/WordCompanion/2026-11-08-capture-403.md b/Docs/WordCompanion/2026-11-08-capture-403.md new file mode 100644 index 00000000..d5ff3406 --- /dev/null +++ b/Docs/WordCompanion/2026-11-08-capture-403.md @@ -0,0 +1,32 @@ +# Native Word capture rejection — 8 November 2026 + +## Evidence and failure mechanism + +The failed author attempt is **The Alpha Flame, book 10152**. No test restarts that book or Reckoning. + +Sanitised Development access-log reconstruction shows the capture-command-sized native presence reply at **18:12:16 GMT**, followed at 18:12:17 by the capture-request-ID-bearing heartbeat. One native Word-instance/document-session path continues through 18:38:56, with **maximum heartbeat gap 16 seconds**. Desktop credential renewals succeeded (HTTP 200), including 18:35:48. At **18:39:06**, capture POST returned **403** and the client's cleanup DELETE returned 200. Onboarding was not reset until 18:49; book ownership and wizard book/project had not changed before submission. + +The deployed pre-fix `NativeManuscriptCapture.Start` authorisation expired **20 minutes after creation**. `Progress` updated the scan percentage but **never renewed that deadline**. `NativeCaptureExpiry`, registered as a hosted service, swept every 15 seconds and removed expired pending requests through `Fail`. Therefore this roughly 27-minute extraction outlived its request authorisation despite continuous authenticated progress. In `Accept`, the missing/expired pending-request check was folded into one `UnauthorizedAccessException`, and the controller returned a blank 403. After the sweep it is the `pending.TryGetValue` absence check; without a sweep the same compound expression rejects `request.Expires <= now`. + +Historical logs did not record a per-branch rejection code or retain the submitted payload; response sizes are used to locate the native command/capture interval, not represented as logged response bodies. The code/timeline demonstrate the fixed deadline violation independently of HTTP 403. Exact historic payload bytes cannot be reconstructed. A controlled-clock regression replays 27 minutes of the same live-session progress and access-renewal pattern; live Development protocol verification is recorded below. + +## Legacy identity and security + +A preserved legacy manuscript GUID is not itself rejected. Capture submission compares its GUID to the **same selected live document lease**, not to a globally unique book binding. The destination comes from the authorised wizard/book and is rechecked before persistence. A fresh authorised book can import a retained GUID; an actually different document/session/instance, changed revision, different account/connection or inaccessible destination remains rejected. Native book IDs, old marker IDs or names do not establish destination authority. No Word property is removed or rewritten by this correction. + +## Server correction + +- The existing 20-minute deadline is now an **inactivity deadline**, renewed only by the existing authenticated capture progress heartbeat matching the exact user/connection/request/Word instance/session/manuscript/revision. +- Progress cannot revive an expired/revoked/mismatched request. A bounded **four-hour absolute limit** remains. Existing short-lived access and installation revocation checks are unchanged; no permanent bearer credential or new pairing system. +- Expiry retains bounded request metadata briefly to return a precise timeout/disconnection reason. It does not create another session store. Failed scan text survives subsequent client cleanup. +- Named rejection codes distinguish inactive request, timeout/disconnection, authority mismatch, document mismatch, changed revision/capability, changed wizard and lost book access. Lifecycle conflicts return 409/410; genuine authority/document access failures remain 403. Current authentication failures remain 401. +- Safe structured logs include request/book/user IDs and failure code/elapsed time, never credentials or manuscript prose. +- Transient durable-storage failures return a meaningful 503 with retryability; no success is claimed until existing durable capture persistence completes. Accepted same-ID/same-payload retries remain idempotent. + +No database migration, author-data backfill, automatic import/retry of book 10152 or change to AI analysis is performed. Existing Companion 1.0.0.20 already sends the progress heartbeat needed by the server fix. + +## Verification so far + +Controlled-clock tests exercise 27-minute paragraph capture with ten-minute access lease refreshes; durable acknowledgement and same-request retries; retained GUID into a fresh authorised destination; invalid identity/connection/revision renewal refusal; inactivity timeout and meaningful 410; cleanup preserving the failure message; four-hour absolute bound. Existing native capture/durable-source tests pass. Full application regression harness passes 455 checks. + +Development deployment and live normal wizard/browser-pairing/renewal/capture evidence are appended after rollout. Any agent resilience follow-up is explicitly separated from the server correction and is not claimed installed on Windows. diff --git a/PlotLine.Tests/NativeCaptureLifetimeTests.cs b/PlotLine.Tests/NativeCaptureLifetimeTests.cs new file mode 100644 index 00000000..93cacf2f --- /dev/null +++ b/PlotLine.Tests/NativeCaptureLifetimeTests.cs @@ -0,0 +1,55 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging.Abstractions; +using PlotDirector.Companion.Protocol; +using PlotLine.Data; +using PlotLine.Models; +using PlotLine.Services; +using PlotLine.Services.NativeCompanion; +internal static class NativeCaptureLifetimeTests +{ + private sealed class Clock:TimeProvider{public DateTimeOffset Now=new(2026,11,8,18,12,16,TimeSpan.Zero);public override DateTimeOffset GetUtcNow()=>Now;} + private sealed class Memory:IManuscriptCaptureRepository + { + public readonly Dictionary Values=[]; + public Task Save(ManuscriptScanPreview p){Values[p.PreviewID]=p;return Task.CompletedTask;} + public Task Get(int u,Guid? p=null,int? o=null)=>Task.FromResult(Values.Values.FirstOrDefault(v=>v.UserID==u&&(!p.HasValue||v.PreviewID==p)&&(!o.HasValue||v.OnboardingID==o))); + public Task Clear(int u,int o)=>Task.CompletedTask;public Task CompleteBuild(int u,Guid p)=>Task.CompletedTask; + public Task GetAnalysis(int u,Guid p,string h)=>Task.FromResult(null);public Task SaveAnalysis(int u,Guid p,string h,string r)=>Task.CompletedTask; + } + public static async Task Run() + { + var clock=new Clock();var repo=new Memory();using var durable=new ServiceCollection().AddSingleton(repo).BuildServiceProvider(); + var scans=new ManuscriptScanPreviewStore(durable.GetRequiredService(),NullLogger.Instance); + int book=3;var onboarding=NativeWorkflowTests.Proxy((n,a)=>Task.FromResult(new(){UserOnboardingStateID=4,ProjectID=1,BookID=book})); + var access=NativeWorkflowTests.Proxy((n,a)=>Task.FromResult(new(){BookId=(int)a![0]!})); + using var provider=new ServiceCollection().AddSingleton(onboarding).AddSingleton(access).BuildServiceProvider(); + var presence=new NativePresenceStore(clock);var config=new Microsoft.Extensions.Configuration.ConfigurationBuilder().AddInMemoryCollection(new Dictionary{{"Features:ParagraphManuscripts","true"}}).Build();var capture=new NativeManuscriptCapture(presence,scans,clock,provider.GetRequiredService(),config); + var instance=Guid.NewGuid();var session=Guid.NewGuid();var retainedLegacyGuid=Guid.NewGuid();long seq=0; + void Beat(Guid? request=null)=>CheckPut(presence.Put(7,"installation/connection",clock.Now.AddMinutes(10),instance,session,new(){BookId=book,ManuscriptId=retainedLegacyGuid,Sequence=++seq,Revision=1,CanCapture=true,CanParagraphSync=true,WordSaved=true,Active=true,DocumentTitle="Retained legacy identity.docx",CaptureRequestId=request})); + ManuscriptCapture Payload(Guid id)=>new(){RequestId=id,InstanceId=instance,SessionId=session,ManuscriptId=retainedLegacyGuid,Revision=1,ParagraphTracking=true,End=22,Paragraphs=[new(){ParagraphIndex=1,Start=0,End=10,OutlineLevel=1,Text="Chapter 1\r",CompletesParagraph=true},new(){ParagraphIndex=2,Start=10,End=22,OutlineLevel=10,Text="Exact prose\r",CompletesParagraph=true}]}; + Beat();var started=await capture.Start(7,4,1,book);var id=started!.ScanID!.Value;presence.TakeNavigation(7,"installation/connection",instance,session); + // Replay the observed 18:12 -> 18:39 capture while short-lived access renews every ten minutes. + for(int tick=1;tick<=108;tick++){clock.Now=clock.Now.AddSeconds(15);Beat(id);await capture.Progress(7,"installation/connection",id,tick/2,instance,session,retainedLegacyGuid,1);if((await capture.Expire()).Count!=0)throw new Exception("Healthy long capture was expired");} + var accepted=await capture.Accept(7,"installation/connection",Payload(id));Check(accepted.Status==ManuscriptScanStatuses.Complete&&repo.Values.Count==1,"27-minute active capture survives old fixed deadline and short-lived access renewal, with durable acceptance"); + await capture.Accept(7,"installation/connection",Payload(id));Check(repo.Values.Count==1,"Same authorised capture retries return the existing durable acknowledgement"); + // A preserved GUID is not book authority: fresh destination comes only from the wizard and lease. + book=4;presence.Remove(7,"installation/connection",instance,session);session=Guid.NewGuid();seq=0;Beat();started=await capture.Start(7,4,1,book);id=started!.ScanID!.Value; + await capture.Accept(7,"installation/connection",Payload(id));Check(repo.Values.Values.Any(p=>p.BookID==4&&p.CompanionDocumentIdentifier==retainedLegacyGuid.ToString()),"Fresh authorised import accepts a retained legacy manuscript GUID without using its old book as authority"); + presence.Remove(7,"installation/connection",instance,session);session=Guid.NewGuid();seq=0;Beat();started=await capture.Start(7,4,1,book);id=started!.ScanID!.Value; + clock.Now=clock.Now.AddMinutes(19);Beat(id); + await capture.Progress(7,"wrong-grant",id,50,instance,session,retainedLegacyGuid,1); + await capture.Progress(7,"installation/connection",id,50,instance,Guid.NewGuid(),retainedLegacyGuid,1); + await capture.Progress(7,"installation/connection",id,50,instance,session,Guid.NewGuid(),1); + await capture.Progress(7,"installation/connection",id,50,instance,session,retainedLegacyGuid,2); + clock.Now=clock.Now.AddMinutes(2);Beat(id);var expired=await capture.Expire(); + Check(expired.Count==1,"Wrong connection, document, session or revision cannot renew capture authorisation"); + try{await capture.Accept(7,"installation/connection",Payload(id));throw new Exception("Expired capture accepted");}catch(CaptureSubmissionRejected e){Check(e.Status==410&&e.Code=="capture_timeout","Expired capture retains a precise timeout reason instead of an unexplained 403");} + await capture.Fail(7,"installation/connection",id);Check((await scans.GetStateAsync(7,4)).Message.Contains("timed out"),"Client cleanup does not replace the meaningful timeout with a generic failure"); + presence.Remove(7,"installation/connection",instance,session);session=Guid.NewGuid();seq=0;Beat();started=await capture.Start(7,4,1,book);id=started!.ScanID!.Value; + for(int tick=1;tick<=960;tick++){clock.Now=clock.Now.AddSeconds(15);Beat(id);await capture.Progress(7,"installation/connection",id,50,instance,session,retainedLegacyGuid,1);await capture.Expire();} + try{await capture.Accept(7,"installation/connection",Payload(id));throw new Exception("Unbounded capture");}catch(CaptureSubmissionRejected e){Check(e.Status==410,"Progress cannot extend a capture beyond its bounded four-hour authorisation");} + } + private static void Check(bool ok,string message){if(!ok)throw new Exception(message);Console.WriteLine("PASS "+message);} + private static void CheckPut(bool ok){if(!ok)throw new Exception("Invalid fixture presence");} +} diff --git a/PlotLine.Tests/Program.cs b/PlotLine.Tests/Program.cs index dd55ac1a..38c41e5e 100644 --- a/PlotLine.Tests/Program.cs +++ b/PlotLine.Tests/Program.cs @@ -136,6 +136,7 @@ if(args.Contains("--paragraph-chapters")){ParagraphChapterTests.Run();return;} if(args.Contains("--paragraph-manuscripts")){ParagraphChapterTests.Run();ParagraphBackupTests.Run();ParagraphManuscriptTests.Run();await ParagraphWorkflowTests.Run();return;} if(args.Contains("--native-import-corrections")){await NativeImportCorrectionTests.Run();return;} if(args.Contains("--native-captured-evidence")){await NativeImportCorrectionTests.CapturedEvidence(args[1],args[2]);return;} +if(args.Contains("--native-capture-lifetime")){await NativeCaptureLifetimeTests.Run();return;} if(args.Contains("--native-tray")){await NativeTrayIntegrationTests.Run();await NativeManuscriptCaptureTests.Run();Console.WriteLine("PASS native tray presence, expiry, scope and persistent PWA review decisions");return;} if(args.Contains("--native-workflow")){await NativeWorkflowTests.Run();Console.WriteLine("PASS native saved workspace and safe import preview validation");return;} if(args.Contains("--native-companion-http")){await NativeCompanionHttpTests.Run();return;} diff --git a/PlotLine/Controllers/NativeManuscriptCaptureController.cs b/PlotLine/Controllers/NativeManuscriptCaptureController.cs index 64165414..bb59d2c8 100644 --- a/PlotLine/Controllers/NativeManuscriptCaptureController.cs +++ b/PlotLine/Controllers/NativeManuscriptCaptureController.cs @@ -22,6 +22,9 @@ public sealed class NativeManuscriptCaptureController(NativeManuscriptCapture ca return Ok(new NativePresence{CaptureRequestId=input.RequestId,Revision=input.Revision,ParagraphRevision=state.Revision,ParagraphSnapshotHash=state.SnapshotHash,CanonicalParagraphIds=state.Paragraphs.Select(p=>p.Occurrence.Id).ToArray()}); } var stateImport=await capture.Accept(user,User.FindFirstValue("NativeCompanion.Grant")??"",input);await live.Clients.Group(WordCompanionFollowHub.PresenceGroup(user)).SendAsync("OnboardingScanCompleted",stateImport);return Ok(new NativePresence{CaptureRequestId=input.RequestId,Revision=input.Revision,CanonicalParagraphIds=capture.AcceptedParagraphIds(user,input.RequestId)});} + catch(System.IO.IOException){return StatusCode(503,new{code="capture_storage_unavailable",message="The manuscript could not be durably saved yet. Retry the same capture; no success has been claimed.",retryable=true});} + catch(Microsoft.Data.SqlClient.SqlException){return StatusCode(503,new{code="capture_storage_unavailable",message="The manuscript could not be durably saved yet. Retry the same capture; no success has been claimed.",retryable=true});} + catch(CaptureSubmissionRejected e){return StatusCode(e.Status,new{code=e.Code,message=e.Message,retryable=false});} catch(UnauthorizedAccessException){return Forbid();}catch(ArgumentException e){return BadRequest(new{message=e.Message});}catch(InvalidOperationException){return Conflict(new{message="The import wizard changed. Refresh it before retrying the transfer."});} } } diff --git a/PlotLine/Controllers/NativePresenceController.cs b/PlotLine/Controllers/NativePresenceController.cs index b0e2b549..0aee65de 100644 --- a/PlotLine/Controllers/NativePresenceController.cs +++ b/PlotLine/Controllers/NativePresenceController.cs @@ -32,7 +32,7 @@ public sealed class NativePresenceController(NativePresenceStore presence,IWordC var before=presence.Read(Author,input.BookId).FirstOrDefault(l=>l.Instance==instance&&l.Session==session); if(!presence.Put(Author,Grant,Expires,instance,session,input))return Conflict(new{message="Stale, revoked or invalid native session."}); if(live!=null&&(before==null||before.Position.BookId!=input.BookId||before.Position.ManuscriptId!=input.ManuscriptId||before.Position.Revision!=input.Revision||before.Position.ChapterId!=input.ChapterId||before.Position.SceneId!=input.SceneId||before.Position.Active!=input.Active||before.Position.WordAvailable!=input.WordAvailable||before.Position.WordRunning!=input.WordRunning))await live.Clients.Group(NativeCompanionPresenceHub.UserGroup(Author)).SendAsync("NativePresenceChanged",new{bookId=input.BookId},HttpContext.RequestAborted); - if(input.CaptureRequestId.HasValue&&capture!=null&&wizard!=null){var progress=await capture.Progress(Author,Grant,input.CaptureRequestId.Value,input.CaptureProgress);if(progress!=null)await wizard.Clients.Group(WordCompanionFollowHub.PresenceGroup(Author)).SendAsync("OnboardingScanProgress",progress,HttpContext.RequestAborted);} + if(input.CaptureRequestId.HasValue&&capture!=null&&wizard!=null){var progress=await capture.Progress(Author,Grant,input.CaptureRequestId.Value,input.CaptureProgress,instance,session,input.ManuscriptId,input.Revision);if(progress!=null)await wizard.Clients.Group(WordCompanionFollowHub.PresenceGroup(Author)).SendAsync("OnboardingScanProgress",progress,HttpContext.RequestAborted);} if(input.CanParagraphSync&&capture!=null){var lease=presence.Read(Author,input.BookId).FirstOrDefault(l=>l.Instance==instance&&l.Session==session);if(lease!=null)await capture.ObserveParagraphSave(Author,lease);} input.CatalogVersion=presence.CatalogVersion(Author);input.Navigation=presence.TakeNavigation(Author,Grant,instance,session);return Ok(input); } diff --git a/PlotLine/Services/NativeCompanion/NativeManuscriptCapture.cs b/PlotLine/Services/NativeCompanion/NativeManuscriptCapture.cs index c695d59d..c82ca946 100644 --- a/PlotLine/Services/NativeCompanion/NativeManuscriptCapture.cs +++ b/PlotLine/Services/NativeCompanion/NativeManuscriptCapture.cs @@ -8,9 +8,9 @@ namespace PlotLine.Services.NativeCompanion; // Short-lived transfer authorisation, issued only by the authenticated existing import wizard. // Prose acceptance is durable through IManuscriptScanPreviewStore, not through this dictionary. -public sealed class NativeManuscriptCapture(NativePresenceStore presence,IManuscriptScanPreviewStore scans,TimeProvider clock,IServiceScopeFactory scopes,IConfiguration? configuration=null) +public sealed class NativeManuscriptCapture(NativePresenceStore presence,IManuscriptScanPreviewStore scans,TimeProvider clock,IServiceScopeFactory scopes,IConfiguration? configuration=null,ILogger? logger=null) { - private sealed record Pending(int User,int Onboarding,int Project,int Book,NativeLease Lease,DateTimeOffset Expires,string? Hash=null,bool Paragraphs=false,bool Sync=false,long BaseRevision=-1,ManuscriptScanPreview? Prepared=null,ParagraphManuscript? AcceptedSnapshot=null); + private sealed record Pending(int User,int Onboarding,int Project,int Book,NativeLease Lease,DateTimeOffset Expires,string? Hash=null,bool Paragraphs=false,bool Sync=false,long BaseRevision=-1,ManuscriptScanPreview? Prepared=null,ParagraphManuscript? AcceptedSnapshot=null,DateTimeOffset Created=default,DateTimeOffset HardExpires=default,string? FailureCode=null,DateTimeOffset RetainUntil=default); private readonly ConcurrentDictionary pending=new(); private readonly SemaphoreSlim acceptance=new(1,1); public async Task Start(int user,int onboarding,int project,int book,bool paragraphs=false) @@ -19,7 +19,7 @@ public sealed class NativeManuscriptCapture(NativePresenceStore presence,IManusc if(paragraphs&&configuration?.GetValue("Features:ParagraphManuscripts")!=true)throw new InvalidOperationException("Paragraph tracking is not enabled on this server."); using var scope=scopes.CreateScope();var access=scope.ServiceProvider.GetRequiredService(); if(await access.GetBookStructureAsync(book,user)==null)throw new InvalidOperationException("The selected book is not accessible."); - foreach(var expired in pending.Where(p=>p.Value.Expires<=clock.GetUtcNow()).Select(p=>p.Key))pending.TryRemove(expired,out _); + foreach(var expired in pending.Where(p=>p.Value.FailureCode!=null?p.Value.RetainUntil<=clock.GetUtcNow():p.Value.Hash!=null&&p.Value.Expires<=clock.GetUtcNow()).Select(p=>p.Key))pending.TryRemove(expired,out _); var all=presence.Read(user,0).Where(l=>l.Position.WordAvailable&&l.Position.CanCapture&&(!paragraphs||l.Position.CanParagraphSync)).ToArray(); var linked=all.Where(l=>l.Position.BookId==book).ToArray(); var documents=linked.Length>0?linked:all.Where(l=>l.Position.BookId==0).ToArray(); @@ -29,10 +29,10 @@ public sealed class NativeManuscriptCapture(NativePresenceStore presence,IManusc var active=documents.Where(l=>l.Position.Active).ToArray(); var selected=active.Length==1?active[0]:documents.Length==1?documents[0]:throw new InvalidOperationException("More than one Word document is linked to this book. Activate the intended document, then retry."); paragraphs=paragraphs||(configuration?.GetValue("Features:ParagraphManuscripts")==true&&selected.Position.CanParagraphSync); - if(pending.Values.Any(p=>p.User==user&&p.Hash==null))throw new InvalidOperationException("A manuscript transfer is already pending. Wait for it to finish or expire before retrying."); + if(pending.Values.Any(p=>p.User==user&&p.Hash==null&&p.FailureCode==null&&p.Expires>clock.GetUtcNow()))throw new InvalidOperationException("A manuscript transfer is already pending. Wait for it to finish or expire before retrying."); if(pending.Count>=128)throw new InvalidOperationException("Manuscript transfers are busy. Try again later."); var state=await scans.StartAsync(user,onboarding,project,book);var id=state.ScanID!.Value; - pending[id]=new(user,onboarding,project,book,selected,clock.GetUtcNow().AddMinutes(20),Paragraphs:paragraphs); + pending[id]=new(user,onboarding,project,book,selected,clock.GetUtcNow().AddMinutes(20),Paragraphs:paragraphs,Created:clock.GetUtcNow(),HardExpires:clock.GetUtcNow().AddHours(4)); if(!presence.RequestCapture(user,selected,id,book,paragraphs)){pending.TryRemove(id,out _);await scans.FailAsync(user,onboarding,"Word changed or is busy. Retry the manuscript transfer.");throw new InvalidOperationException("Word changed or is busy. Retry the manuscript transfer.");} return state; }finally{acceptance.Release();} @@ -51,9 +51,9 @@ public sealed class NativeManuscriptCapture(NativePresenceStore presence,IManusc if(automatic!=null&&(status.Mode!="OnSave"||documents.Length!=1||!automatic.Position.WordSaved.GetValueOrDefault()||(status.SessionId==automatic.Session&&status.WordRevision==automatic.Position.Revision)))return Guid.Empty; var active=documents.Where(l=>l.Position.Active).ToArray();var selected=automatic??(active.Length==1?active[0]:documents.Length==1?documents[0]:throw new InvalidOperationException("Activate the intended Word manuscript. Multiple or no eligible documents are connected.")); if(selected.Position.ManuscriptId!=status.ManuscriptId)throw new InvalidOperationException("This is a different document. Import a different manuscript into a separate book; automatic cross-document evidence matching is refused."); - if(pending.Values.Any(p=>p.User==user&&p.Hash==null))return Guid.Empty; + if(pending.Values.Any(p=>p.User==user&&p.Hash==null&&p.FailureCode==null&&p.Expires>clock.GetUtcNow()))return Guid.Empty; if(pending.Count>=128)throw new InvalidOperationException("Manuscript transfer capacity is busy.");var id=Guid.NewGuid(); - pending[id]=new(user,0,0,book,selected,clock.GetUtcNow().AddMinutes(20),Paragraphs:true,Sync:true,BaseRevision:status.Revision); + pending[id]=new(user,0,0,book,selected,clock.GetUtcNow().AddMinutes(20),Paragraphs:true,Sync:true,BaseRevision:status.Revision,Created:clock.GetUtcNow(),HardExpires:clock.GetUtcNow().AddHours(4)); if(!presence.RequestCapture(user,selected,id,book,true,true,status.Revision,status.SnapshotHash)){pending.TryRemove(id,out _);throw new InvalidOperationException("Word changed or is busy. Request a fresh snapshot.");}return id; }finally{acceptance.Release();} } @@ -69,7 +69,7 @@ public sealed class NativeManuscriptCapture(NativePresenceStore presence,IManusc { await acceptance.WaitAsync();try{ if(!pending.TryGetValue(capture.RequestId,out var request)||!request.Sync)return false; - if(request.User!=user||request.Lease.Grant!=grant||request.Expires<=clock.GetUtcNow()||!capture.ParagraphTracking||capture.InstanceId!=request.Lease.Instance||capture.SessionId!=request.Lease.Session||capture.ManuscriptId!=request.Lease.Position.ManuscriptId||capture.Revision!=request.Lease.Position.Revision)throw new UnauthorizedAccessException(); + ValidateRequest(request,user,grant,capture); var hash=Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(capture))); if(request.Hash!=null){if(request.Hash!=hash)throw new ArgumentException("Snapshot retry has different contents.");return true;} using var scope=scopes.CreateScope();var accepted=await scope.ServiceProvider.GetRequiredService().Snapshot(user,request.Book,capture,request.BaseRevision); @@ -80,11 +80,13 @@ public sealed class NativeManuscriptCapture(NativePresenceStore presence,IManusc public async Task Accept(int user,string grant,ManuscriptCapture capture) { await acceptance.WaitAsync();try{ - if(!pending.TryGetValue(capture.RequestId,out var request)||request.Sync||request.Paragraphs!=capture.ParagraphTracking||request.Expires<=clock.GetUtcNow()||request.User!=user||request.Lease.Grant!=grant||capture.InstanceId!=request.Lease.Instance||capture.SessionId!=request.Lease.Session||capture.ManuscriptId!=request.Lease.Position.ManuscriptId||capture.Revision!=request.Lease.Position.Revision)throw new UnauthorizedAccessException(); + if(!pending.TryGetValue(capture.RequestId,out var request))throw Rejected(user,capture.RequestId,"capture_not_active",409,"This Word capture request is no longer active. Return to the existing import and request the capture again."); + if(request.Sync)throw Rejected(user,capture.RequestId,"capture_workflow_mismatch",409,"The capture belongs to another operation. Return to the existing import."); + ValidateRequest(request,user,grant,capture); using var scope=scopes.CreateScope();var access=scope.ServiceProvider.GetRequiredService();var onboardingState=scope.ServiceProvider.GetRequiredService(); var current=await onboardingState.GetAsync(user); - if(current==null||current.UserOnboardingStateID!=request.Onboarding||current.ProjectID!=request.Project||current.BookID!=request.Book)throw new UnauthorizedAccessException(); - var structure=await access.GetBookStructureAsync(request.Book,user)??throw new UnauthorizedAccessException(); + if(current==null||current.UserOnboardingStateID!=request.Onboarding||current.ProjectID!=request.Project||current.BookID!=request.Book)throw Rejected(user,capture.RequestId,"capture_wizard_changed",409,"The selected import book or setup changed during capture. Existing accepted data is unchanged; return to the intended import."); + var structure=await access.GetBookStructureAsync(request.Book,user)??throw Rejected(user,capture.RequestId,"capture_book_forbidden",403,"You no longer have access to the selected import book."); var hash=Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(capture))); if(request.Hash!=null){if(request.Hash!=hash)throw new ArgumentException("Capture identity conflict. Start a new transfer.");return await scans.GetStateAsync(user,request.Onboarding);} var preview=request.Prepared??Build(capture,user,request.Onboarding,request.Project,request.Book,request.Lease.Position.DocumentTitle,structure); @@ -96,15 +98,49 @@ public sealed class NativeManuscriptCapture(NativePresenceStore presence,IManusc return state; }finally{acceptance.Release();} } - public async Task Progress(int user,string grant,Guid id,int percent) + private CaptureSubmissionRejected Rejected(int user,Guid id,string code,int status,string message) { - if(!pending.TryGetValue(id,out var request)||request.Sync||request.User!=user||request.Lease.Grant!=grant||request.Hash!=null)return null; - return await scans.ProgressAsync(user,new(){OnboardingID=request.Onboarding,PercentComplete=Math.Clamp(percent,0,100)*9/10,Message="Reading Word manuscript in bounded batches. Keep Word open until PlotDirector acknowledges receipt."}); + logger?.LogWarning("Native capture rejected. UserID={UserID} RequestID={RequestID} Code={Code}",user,id,code); + return new(code,status,message); + } + private void ValidateRequest(Pending request,int user,string grant,ManuscriptCapture capture) + { + if(request.User!=user||request.Lease.Grant!=grant)throw Rejected(user,capture.RequestId,"capture_authority_mismatch",403,"This capture does not belong to the approved Companion connection."); + if(capture.InstanceId!=request.Lease.Instance||capture.SessionId!=request.Lease.Session||capture.ManuscriptId!=request.Lease.Position.ManuscriptId)throw Rejected(user,capture.RequestId,"capture_document_mismatch",403,"The Word document or session differs from the requested capture. Return to the intended manuscript."); + if(request.Hash==null&&(request.FailureCode!=null||request.Expires<=clock.GetUtcNow()||request.HardExpires<=clock.GetUtcNow()))throw Rejected(user,capture.RequestId,request.FailureCode??"capture_timeout",410,"The Word capture authorisation expired or disconnected before acceptance. Your Word document is unchanged. Request capture again from the existing import."); + if(request.Paragraphs!=capture.ParagraphTracking)throw Rejected(user,capture.RequestId,"capture_capability_changed",409,"The capture capabilities changed. Reconnect Companion and return to the existing import."); + if(capture.Revision!=request.Lease.Position.Revision)throw Rejected(user,capture.RequestId,"capture_revision_changed",409,"Word changed during capture. Save it, then request a fresh capture from the existing import."); + } + public async Task Progress(int user,string grant,Guid id,int percent,Guid instance,Guid session,Guid manuscript,long revision) + { + await acceptance.WaitAsync();try{ + var now=clock.GetUtcNow(); + if(!pending.TryGetValue(id,out var request)||request.User!=user||request.Lease.Grant!=grant||request.Hash!=null||request.FailureCode!=null||request.Expires<=now||request.HardExpires<=now||request.Lease.Instance!=instance||request.Lease.Session!=session||request.Lease.Position.ManuscriptId!=manuscript||request.Lease.Position.Revision!=revision)return null; + // Existing authenticated document heartbeats renew inactivity, never account approval or identity. + pending[id]=request with{Expires=now.AddMinutes(20)> Expire() { var failures=new List<(int,ManuscriptScanState)>(); - foreach(var item in pending.ToArray())if(item.Value.Hash==null&&(item.Value.Expires<=clock.GetUtcNow()||!presence.Read(item.Value.User,0).Any(l=>l.Instance==item.Value.Lease.Instance&&l.Session==item.Value.Lease.Session))){var state=await Fail(item.Value.User,item.Value.Lease.Grant,item.Key);if(state!=null)failures.Add((item.Value.User,state));} + await acceptance.WaitAsync();try{ + var now=clock.GetUtcNow(); + foreach(var item in pending.ToArray()){ + var request=item.Value; + if(request.FailureCode!=null){if(request.RetainUntil<=now)pending.TryRemove(item.Key,out _);continue;} + if(request.Hash!=null)continue; + var connected=presence.Read(request.User,0).Any(l=>l.Grant==request.Lease.Grant&&l.Instance==request.Lease.Instance&&l.Session==request.Lease.Session); + if(request.Expires>now&&request.HardExpires>now&&connected)continue; + var code=request.Expires<=now||request.HardExpires<=now?"capture_timeout":"capture_disconnected"; + // Bounded existing request metadata survives briefly for a useful response; no new store or credentials. + pending[item.Key]=request with{FailureCode=code,RetainUntil=now.AddMinutes(20)}; + logger?.LogWarning("Native capture ended before acceptance. UserID={UserID} BookID={BookID} RequestID={RequestID} Code={Code} ElapsedSeconds={ElapsedSeconds}",request.User,request.Book,item.Key,code,(now-request.Created).TotalSeconds); + if(request.Sync)continue; + var state=await scans.GetStateAsync(request.User,request.Onboarding); + if(state.ScanID==item.Key)failures.Add((request.User,await scans.FailAsync(request.User,request.Onboarding,code=="capture_timeout"?"Word capture timed out without valid progress. No manuscript was accepted; return to this import to retry.":"Word disconnected before capture acceptance. No manuscript was accepted; return to this import to retry."))); + } + }finally{acceptance.Release();} return failures; } public async Task Built(int user,Guid previewId,OnboardingManuscriptBuildResult result) @@ -129,7 +165,7 @@ public sealed class NativeManuscriptCapture(NativePresenceStore presence,IManusc await acceptance.WaitAsync();try{ if(!pending.TryGetValue(id,out var request)||request.User!=user||request.Lease.Grant!=grant||request.Hash!=null)return null; pending.TryRemove(id,out _);if(request.Sync)return null;var state=await scans.GetStateAsync(user,request.Onboarding); - return state.ScanID==id?await scans.FailAsync(user,request.Onboarding,"Word transfer interrupted before server acceptance. Retry Import manuscript; existing story data is unchanged."):null; + return state.ScanID!=id?null:state.Status==ManuscriptScanStatuses.Failed?state:await scans.FailAsync(user,request.Onboarding,"Word transfer interrupted before server acceptance. Retry Import manuscript; existing story data is unchanged."); }finally{acceptance.Release();} } public static ManuscriptScanPreview Build(ManuscriptCapture capture,int user,int onboarding,int project,int book,string title,WordCompanionBookStructureResponse? structure=null) @@ -169,3 +205,9 @@ public sealed class NativeCaptureExpiry(NativeManuscriptCapture capture,Microsof { protected override async Task ExecuteAsync(CancellationToken stoppingToken){using var timer=new PeriodicTimer(TimeSpan.FromSeconds(15));while(await timer.WaitForNextTickAsync(stoppingToken)){foreach(var failure in await capture.Expire())await Microsoft.AspNetCore.SignalR.ClientProxyExtensions.SendAsync(live.Clients.Group(PlotLine.Hubs.WordCompanionFollowHub.PresenceGroup(failure.User)),"OnboardingScanFailed",failure.State,stoppingToken);}} } + +public sealed class CaptureSubmissionRejected(string code,int status,string message):UnauthorizedAccessException(message) +{ + public string Code {get;}=code; + public int Status {get;}=status; +}