Route Return to Writer through a scoped authenticated launcher
This commit is contained in:
parent
470a90cf55
commit
ae06dca3da
@ -183,7 +183,29 @@ public sealed partial class CloudGateway : IDisposable
|
||||
{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);}}
|
||||
{
|
||||
if (string.IsNullOrEmpty(path) || !path.StartsWith("/native-companion/", StringComparison.Ordinal))
|
||||
throw new InvalidDataException("The Companion page link is invalid. Reopen the manuscript and try again.");
|
||||
OpenAuthenticatedPage(path, context);
|
||||
}
|
||||
internal void OpenWriterPage(int book, Guid instance, Guid session, Guid context)
|
||||
{
|
||||
if (book <= 0 || instance == Guid.Empty || session == Guid.Empty)
|
||||
throw new InvalidOperationException("Open an associated manuscript before returning to Writer.");
|
||||
OpenAuthenticatedPage(FormattableString.Invariant($"/Writer/Write?bookId={book}&wordInstanceId={instance:D}&wordSessionId={session:D}"), context);
|
||||
}
|
||||
private void OpenAuthenticatedPage(string path, Guid context)
|
||||
{
|
||||
lock (gate)
|
||||
{
|
||||
Expire();
|
||||
if (context != authenticationContext || token == null || origin == null)
|
||||
throw new InvalidOperationException("Sign in and reconnect Word before opening PlotDirector.");
|
||||
if (!Uri.TryCreate(origin, path, out var url) || url.GetLeftPart(UriPartial.Authority) != origin.GetLeftPart(UriPartial.Authority))
|
||||
throw new InvalidDataException("The PlotDirector page link is invalid. Reconnect and try again.");
|
||||
openBrowser(url.AbsoluteUri);
|
||||
}
|
||||
}
|
||||
public async Task<NativePresence> Presence(Guid instance,Guid session,NativePresence presence,Guid context){var reply=await Post<NativePresence>($"api/native-companion/instances/{instance}/documents/{session}/presence",presence,context);await ObserveCatalog(reply.CatalogVersion,context);return reply;}
|
||||
private async Task ObserveCatalog(Guid version,Guid context){if(version==Guid.Empty)return;Task running;lock(gate){if(context!=authenticationContext||catalogVersion==version)return;catalogVersion=version;running=connectionCheck;}await running;lock(gate)if(context!=authenticationContext)return;await CheckConnection();}
|
||||
public async Task RemovePresence(Guid instance,Guid session,long? throughSequence=null){Guid context;lock(gate)context=authenticationContext;try{await Send<NativePresence>(HttpMethod.Delete,$"api/native-companion/instances/{instance}/documents/{session}/presence?throughSequence={throughSequence}",null,context);}catch(Exception e)when(e is HttpRequestException or IOException or InvalidDataException or InvalidOperationException or OperationCanceledException or JsonException or ObjectDisposedException){}}
|
||||
|
||||
@ -104,7 +104,7 @@ internal sealed class CompanionWindow:Form
|
||||
{if(!IsDisposed)MessageBox.Show(this,"Windows media discovery is unavailable.","Audio Review");}
|
||||
}
|
||||
private Button Button(string text,Action action){var button=new Button{Text=text,AutoSize=true,MinimumSize=new(0,34)};button.Click+=(_,_)=>Safe(action);return button;}
|
||||
private void Safe(Action action){try{error="";action();}catch(Exception e)when(e is InvalidOperationException or ArgumentException or IOException or System.ComponentModel.Win32Exception){error=e.Message;}if(dialogNotice is {IsDisposed:false})SetText(dialogNotice,error);RefreshState();}
|
||||
private void Safe(Action action){try{error="";action();}catch(Exception e)when(e is InvalidOperationException or InvalidDataException or ArgumentException or IOException or System.ComponentModel.Win32Exception){error=e.Message;}if(dialogNotice is {IsDisposed:false})SetText(dialogNotice,error);RefreshState();}
|
||||
private void SavePreferences(){var size=WindowState==FormWindowState.Normal?Size:RestoreBounds.Size;var prefs=cloud.Preferences;prefs.CompactLayoutApplied=true;prefs.Width=size.Width;prefs.Height=size.Height;prefs.AdvancedMode=advanced;prefs.LastManuscript=Current?.Manuscript??prefs.LastManuscript;cloud.SavePreferences(prefs);}
|
||||
public void Reveal(){Show();WindowState=FormWindowState.Normal;Activate();}
|
||||
private async void ChangeBook()
|
||||
|
||||
@ -145,12 +145,23 @@ public sealed partial class TrayCoordinator(SessionManager sessions,CloudGateway
|
||||
{
|
||||
if (!documents.TryGetValue(session, out var doc) || doc.Revision != revision) return;
|
||||
try { OpenPage(session, page); }
|
||||
catch (Exception error) when (error is InvalidOperationException or IOException or System.ComponentModel.Win32Exception)
|
||||
catch (Exception error) when (error is InvalidOperationException or InvalidDataException or IOException or System.ComponentModel.Win32Exception)
|
||||
{ doc.Status = error.Message; }
|
||||
}
|
||||
});
|
||||
|
||||
public void OpenPage(Guid session,string page){lock(gate){if(!documents.TryGetValue(session,out var doc)||!cloud.Allows(doc.Authentication,doc.Book))throw new InvalidOperationException("Select an authorised book first.");cloud.OpenCompanionPage(page=="writer"?$"/Writer/Write?bookId={doc.Book}&wordInstanceId={doc.Instance}&wordSessionId={doc.Session}":page=="review"&&!string.IsNullOrEmpty(doc.ReviewPath)?doc.ReviewPath:$"/native-companion/workspace?bookId={doc.Book}&instanceId={doc.Instance}&sessionId={doc.Session}&view={page}",doc.Authentication);}}
|
||||
public void OpenPage(Guid session,string page)
|
||||
{
|
||||
lock(gate)
|
||||
{
|
||||
if(!documents.TryGetValue(session,out var doc)||!cloud.Allows(doc.Authentication,doc.Book))
|
||||
throw new InvalidOperationException("Open a connected manuscript and select an authorised book first.");
|
||||
if(page=="writer")
|
||||
cloud.OpenWriterPage(doc.Book,doc.Instance,doc.Session,doc.Authentication);
|
||||
else
|
||||
cloud.OpenCompanionPage(page=="review"&&!string.IsNullOrEmpty(doc.ReviewPath)?doc.ReviewPath:$"/native-companion/workspace?bookId={doc.Book}&instanceId={doc.Instance}&sessionId={doc.Session}&view={page}",doc.Authentication);
|
||||
}
|
||||
}
|
||||
public async Task Heartbeat(CancellationToken cancellation)
|
||||
{
|
||||
while(!cancellation.IsCancellationRequested){await Task.Delay(TimeSpan.FromMilliseconds(500),cancellation);var available=Documents.Where(d=>d.Authentication==cloud.Status().AuthenticationContext&&cloud.Status().Health?.Authentication=="verified").ToArray();
|
||||
|
||||
@ -1 +1 @@
|
||||
<Project><PropertyGroup><ApplicationVersion>1.0.0.39</ApplicationVersion></PropertyGroup></Project>
|
||||
<Project><PropertyGroup><ApplicationVersion>1.0.0.40</ApplicationVersion></PropertyGroup></Project>
|
||||
|
||||
@ -6,7 +6,7 @@ internal static class TrayTests
|
||||
{
|
||||
public static async Task Run(Action<bool,string> check)
|
||||
{
|
||||
var handler=new Server();using var cloud=new CloudGateway(handler,_=>{});cloud.Connect("https://fixture.invalid/");await Until(()=>cloud.Status().Books.Length>0);
|
||||
var handler=new Server();var launched=new List<string>();using var cloud=new CloudGateway(handler,launched.Add);cloud.Connect("https://fixture.invalid/");await Until(()=>cloud.Status().Books.Length>0);
|
||||
using var ai=new ChapterAiWork(cloud);var sessions=new SessionManager(cloud,ai);var control=new TrayCoordinator(sessions,cloud,ai);var instance=Guid.NewGuid();var lease=Guid.NewGuid();sessions.Attach(instance,lease);control.Attach(instance,lease,true);long sequence=0;
|
||||
var first=new DocumentDescriptor{SessionId=Guid.NewGuid(),ManuscriptId=Guid.NewGuid(),Title="One",Revision=1};var second=new DocumentDescriptor{SessionId=Guid.NewGuid(),ManuscriptId=Guid.NewGuid(),Title="Two",Revision=1};
|
||||
Message Apply(Message m){m.WordInstanceId=instance;m.Sequence=++sequence;return control.Exchange(instance,m,sessions.Apply(lease,m));}
|
||||
@ -25,6 +25,20 @@ internal static class TrayTests
|
||||
Apply(new(){Kind="snapshot-fragment",SessionId=second.SessionId,Revision=1,SnapshotId=frontSnapshot,Fragment=new(){Start=10,End=20,ParagraphIndex=2,OutlineLevel=1,Text="Opening\r",CompletesParagraph=true}});
|
||||
Apply(new(){Kind="snapshot-end",SessionId=second.SessionId,Revision=1,SnapshotId=frontSnapshot});check(control.Documents.Single(d=>d.Session==second.SessionId).Chapters.Single().Start==10,"tray preserves original leading front-matter exclusions before Heading 1 chapters");
|
||||
control.SelectBook(first.SessionId,3,false);check(control.Documents.Single(d=>d.Session==first.SessionId).Book==3&&control.Documents.Single(d=>d.Session==second.SessionId).Book==0,"tray book association is explicit and isolated");
|
||||
var writerPath=$"/Writer/Write?bookId=3&wordInstanceId={instance:D}&wordSessionId={first.SessionId:D}";
|
||||
var auth=cloud.Status().AuthenticationContext;
|
||||
launched.Clear();
|
||||
var invalidData=false;
|
||||
try{cloud.OpenCompanionPage(writerPath,auth);}catch(InvalidDataException){invalidData=true;}
|
||||
check(invalidData&&launched.Count==0,"native workspace allowlist rejects Writer before URI decoding or browser invocation");
|
||||
control.OpenPage(first.SessionId,"writer");
|
||||
check(launched.Single()=="https://fixture.invalid"+writerPath,"Return to Writer launches the authenticated same-origin URL for the exact bound document");
|
||||
invalidData=false;
|
||||
try{cloud.OpenCompanionPage("//other.invalid/native-companion/workspace",auth);}catch(InvalidDataException){invalidData=true;}
|
||||
check(invalidData&&launched.Count==1,"malformed or foreign launch path never reaches the browser");
|
||||
bool staleLaunch=false;
|
||||
try{control.OpenPage(Guid.NewGuid(),"writer");}catch(InvalidOperationException){staleLaunch=true;}
|
||||
check(staleLaunch&&launched.Count==1,"Return to Writer rejects a stale document without launching a page");
|
||||
bool refused=false;try{control.SelectBook(second.SessionId,999,false);}catch(InvalidOperationException){refused=true;}check(refused,"tray refuses unauthorised books before Word metadata command");
|
||||
using(var heartbeatStop=new CancellationTokenSource()){
|
||||
var heartbeat=control.Heartbeat(heartbeatStop.Token);await Until(()=>handler.Heartbeats==1);await Task.Delay(600);
|
||||
|
||||
@ -3,6 +3,6 @@ using System.Runtime.InteropServices;
|
||||
[assembly: AssemblyTitle("PlotDirector Word Companion — Native development")]
|
||||
[assembly: AssemblyCompany("Nick Beckley")]
|
||||
[assembly: AssemblyProduct("PlotDirector")]
|
||||
[assembly: AssemblyVersion("1.0.0.39")]
|
||||
[assembly: AssemblyFileVersion("1.0.0.39")]
|
||||
[assembly: AssemblyVersion("1.0.0.40")]
|
||||
[assembly: AssemblyFileVersion("1.0.0.40")]
|
||||
[assembly: ComVisible(false)]
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
{
|
||||
"version": "1.0.0.39",
|
||||
"msiVersion": "1.0.39",
|
||||
"productCode": "{42F15A51-BC72-4783-814C-E8C8E5708839}",
|
||||
"version": "1.0.0.40",
|
||||
"msiVersion": "1.0.40",
|
||||
"productCode": "{BA2E0C19-E8D2-4EF8-90B0-C4F2CEB93B15}",
|
||||
"upgradeCode": "{641A087B-9779-458C-B290-BCBBAD49319A}",
|
||||
"atlasBaseline": "9fed339879887964d526cff00772ffc4dc522c5d",
|
||||
"baselineProductCode": "{98F46939-764D-407F-BD1F-1D88315D010A}",
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user