fix: Change Account signed out BEFORE the browser opened

Reported 2026-09-27: click avatar -> Change Account -> cancel in the Google
chooser -> back to a signed-out app, then "cannot sign-in because the callback
url was not released".

Two independent defects:

1. ChangeAccountAsync ran `await SignOutYouTubeAsync(); await SignInAsync();`.
   SignOutYouTubeAsync -> TokenStore.Clear() -> deletes ytLlive.auth, so the
   working account's token was destroyed before the browser even opened. It is
   now just `await SignInAsync()`: success overwrites the token via the
   sessionChanged hook, cancel/failure keeps the current session. The explicit
   sign-out was never needed.

2. Abandoning the browser gives the app no signal, so the OAuth attempt held
   localhost:8765 for its full 5-minute timeout and a retry could not bind. A
   new AuthenticateAsync now cancels and awaits the abandoned attempt first.
   That takeover is serialised by a SemaphoreSlim: the first version cleared
   the in-flight marker before awaiting, so a caller arriving in that window saw
   a free port and raced to bind it -- reproducing the very failure it was
   written to prevent. My own test caught that; reasoning had "proved" it fine.

Also adds an `openBrowser` ctor seam so tests never shell out to a real
browser, and corrects the ai.md line that documented "Logout / Change Account ->
SignOutYouTubeAsync" as intended behaviour.

Test: YouTubeAuthServiceTests.RetryingAfterAnAbandonedAttempt_ReleasesTheCallbackPort
Full suite 370/370, 0 warnings. Coverage gap noted in HANDOFF.md: the ordering
fix has no automated test because _youtubeAuth is hardcoded in MainViewModel
and ChangeAccountAsync is private.

The reported cross-instance effect is NOT this cause and stays open -- no code
path can sign out a second instance (per-instance TokenStore, local delete, no
server-side revoke).
This commit is contained in:
2026-09-27 16:02:05 -07:00
parent 536676f11a
commit 44344c9327
6 changed files with 200 additions and 13 deletions
+57 -7
View File
@@ -21,16 +21,36 @@ public class YouTubeAuthService
private readonly string _clientSecret;
private readonly HttpClient _http;
private readonly Action<YouTubeChannel>? _sessionChanged;
private readonly Action<string> _openBrowser;
/// <summary>Serialises "take over from the previous attempt". Without this, two
/// overlapping calls both see a free port and race to bind it, which is the same
/// failure the cancel-and-await is meant to prevent.</summary>
private readonly SemaphoreSlim _authGate = new(1, 1);
/// <summary>The attempt currently holding the loopback callback port, if any.
/// A creator who abandons the Google account chooser gives the app no signal, so
/// the attempt simply waits out its 5-minute timeout while still holding port
/// 8765 — and a retry in that window cannot bind. A new attempt cancels and
/// awaits the abandoned one first, which releases the port (creator report
/// 2026-09-27: "cannot sign-in because the callback url was not released").
/// Both fields below are only touched while holding <see cref="_authGate"/>.</summary>
private Task<YouTubeChannel?>? _authInFlight;
private CancellationTokenSource? _authCts;
public YouTubeChannel? CurrentChannel { get; private set; }
public YouTubeAuthService(string clientId, string clientSecret, HttpClient? http = null,
Action<YouTubeChannel>? sessionChanged = null)
Action<YouTubeChannel>? sessionChanged = null,
Action<string>? openBrowser = null)
{
_clientId = clientId;
_clientSecret = clientSecret;
_http = http ?? new HttpClient();
_sessionChanged = sessionChanged;
// Seam: the real flow shells out to the default browser, which a test must not do.
_openBrowser = openBrowser ?? (url =>
Process.Start(new ProcessStartInfo(url) { UseShellExecute = true }));
}
/// <summary>Replaces the current session (used when a saved token loads at startup).</summary>
@@ -65,23 +85,53 @@ public class YouTubeAuthService
public async Task<YouTubeChannel?> AuthenticateAsync()
{
const int port = 8765;
var redirectUri = $"http://localhost:{port}/oauth2/callback";
if (string.IsNullOrWhiteSpace(_clientId) || string.IsNullOrWhiteSpace(_clientSecret))
return null;
// Taking over from an abandoned attempt has to be atomic: cancel it, wait for
// it to actually let go of the port, then bind. Letting the gate go before the
// bind reopens the race the takeover exists to close.
Task<YouTubeChannel?> attempt;
await _authGate.WaitAsync().ConfigureAwait(false);
try
{
var previousCts = _authCts;
_authCts = null;
previousCts?.Cancel();
if (_authInFlight is { } previous)
{
try { await previous.ConfigureAwait(false); } catch { /* its result is irrelevant */ }
_authInFlight = null;
}
var cts = new CancellationTokenSource(TimeSpan.FromMinutes(5));
_authCts = cts;
_authInFlight = attempt = RunAuthFlowAsync(cts.Token);
}
finally
{
_authGate.Release();
}
return await attempt.ConfigureAwait(false);
}
private async Task<YouTubeChannel?> RunAuthFlowAsync(CancellationToken cancellationToken)
{
const int port = 8765;
var redirectUri = $"http://localhost:{port}/oauth2/callback";
using var listener = new HttpListener();
listener.Prefixes.Add($"{redirectUri}/");
listener.Start();
Process.Start(new ProcessStartInfo(GetAuthorizationUrl(redirectUri)) { UseShellExecute = true });
_openBrowser(GetAuthorizationUrl(redirectUri));
HttpListenerContext context;
try
{
using var cts = new CancellationTokenSource(TimeSpan.FromMinutes(5));
context = await listener.GetContextAsync().WaitAsync(cts.Token);
context = await listener.GetContextAsync().WaitAsync(cancellationToken);
}
catch (OperationCanceledException)
{