diff --git a/ErsatzTV.Application/Troubleshooting/Commands/PrepareTroubleshootingPlaybackHandler.cs b/ErsatzTV.Application/Troubleshooting/Commands/PrepareTroubleshootingPlaybackHandler.cs
index b98cd1498..4bbcab92e 100644
--- a/ErsatzTV.Application/Troubleshooting/Commands/PrepareTroubleshootingPlaybackHandler.cs
+++ b/ErsatzTV.Application/Troubleshooting/Commands/PrepareTroubleshootingPlaybackHandler.cs
@@ -3,6 +3,7 @@ using ErsatzTV.Application.Streaming;
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Domain.Filler;
+using ErsatzTV.Core.Errors;
using ErsatzTV.Core.Extensions;
using ErsatzTV.Core.FFmpeg;
using ErsatzTV.Core.Interfaces.Emby;
@@ -72,7 +73,7 @@ public class PrepareTroubleshootingPlaybackHandler(
// already holds it (no check-then-set race, no double-owner)
if (!entityLocker.LockTroubleshootingPlayback())
{
- return BaseError.New("Troubleshooting playback is locked");
+ return new LockedError("Troubleshooting playback is locked");
}
lockAcquired = true;
@@ -143,7 +144,7 @@ public class PrepareTroubleshootingPlaybackHandler(
// report the conflict. Ownership is tracked so the catch never cross-releases.
if (!entityLocker.LockTroubleshootingPlayback())
{
- return BaseError.New("Troubleshooting playback is locked");
+ return new LockedError("Troubleshooting playback is locked");
}
lockAcquired = true;
diff --git a/ErsatzTV.Core/Api/Troubleshooting/TroubleshootingPlaybackStartedResponseModel.cs b/ErsatzTV.Core/Api/Troubleshooting/TroubleshootingPlaybackStartedResponseModel.cs
new file mode 100644
index 000000000..f7f13c413
--- /dev/null
+++ b/ErsatzTV.Core/Api/Troubleshooting/TroubleshootingPlaybackStartedResponseModel.cs
@@ -0,0 +1,6 @@
+#nullable enable
+namespace ErsatzTV.Core.Api.Troubleshooting;
+
+// Returned once a troubleshooting playback session has started producing segments; Url is the
+// rooted /iptv path the SPA feeds straight to hls.js (HlsPlayer never inspects the status code).
+public record TroubleshootingPlaybackStartedResponseModel(string Url);
diff --git a/ErsatzTV.Core/Errors/LockedError.cs b/ErsatzTV.Core/Errors/LockedError.cs
new file mode 100644
index 000000000..6765df728
--- /dev/null
+++ b/ErsatzTV.Core/Errors/LockedError.cs
@@ -0,0 +1,13 @@
+namespace ErsatzTV.Core.Errors;
+
+///
+/// A raised when a mutation races another operation that already holds an
+/// exclusive lock (e.g. a troubleshooting playback session in flight). REST endpoints map this to
+/// HTTP 409 Conflict, distinguishing it from the generic 422 other values get.
+///
+public class LockedError : BaseError
+{
+ public LockedError(string value) : base(value)
+ {
+ }
+}
diff --git a/ErsatzTV.Tests/Application/Troubleshooting/PrepareTroubleshootingPlaybackHandlerTests.cs b/ErsatzTV.Tests/Application/Troubleshooting/PrepareTroubleshootingPlaybackHandlerTests.cs
index 7079901a2..68e1febb8 100644
--- a/ErsatzTV.Tests/Application/Troubleshooting/PrepareTroubleshootingPlaybackHandlerTests.cs
+++ b/ErsatzTV.Tests/Application/Troubleshooting/PrepareTroubleshootingPlaybackHandlerTests.cs
@@ -2,6 +2,7 @@ using System.IO.Abstractions;
using ErsatzTV.Application.Troubleshooting;
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
+using ErsatzTV.Core.Errors;
using ErsatzTV.Core.Interfaces.Emby;
using ErsatzTV.Core.Interfaces.FFmpeg;
using ErsatzTV.Core.Interfaces.Jellyfin;
@@ -84,6 +85,43 @@ public class PrepareTroubleshootingPlaybackHandlerTests
_entityLocker.Received(1).UnlockTroubleshootingPlayback();
}
+ [Test]
+ public async Task Handle_Should_Return_LockedError_When_Lock_Already_Held()
+ {
+ await SeedFFmpegConfig();
+ int profileId = await SeedFFmpegProfile();
+ int movieId = await SeedMovieWithMissingFile();
+
+ // another session already holds the troubleshooting lock
+ _entityLocker.LockTroubleshootingPlayback().Returns(false);
+
+ PrepareTroubleshootingPlaybackHandler handler = CreateHandler();
+
+ var request = new PrepareTroubleshootingPlayback(
+ Guid.NewGuid(),
+ StreamingMode.HttpLiveStreamingSegmenter,
+ movieId,
+ ChannelId: 0,
+ profileId,
+ StreamSelector: string.Empty,
+ WatermarkIds: [],
+ GraphicsElementIds: [],
+ SubtitleId: null,
+ SeekSeconds: Option.None,
+ Start: Option.None);
+
+ Either result = await handler.Handle(request, CancellationToken.None);
+
+ result.IsLeft.ShouldBeTrue();
+ foreach (BaseError error in result.LeftToSeq())
+ {
+ error.ShouldBeOfType();
+ }
+
+ // never acquired, so never releases
+ _entityLocker.DidNotReceive().UnlockTroubleshootingPlayback();
+ }
+
[Test]
public async Task Handle_Should_Not_Release_Lock_It_Never_Acquired()
{
diff --git a/ErsatzTV.Tests/Controllers/AuthControllerTests.cs b/ErsatzTV.Tests/Controllers/AuthControllerTests.cs
index 84d34c320..a669015ea 100644
--- a/ErsatzTV.Tests/Controllers/AuthControllerTests.cs
+++ b/ErsatzTV.Tests/Controllers/AuthControllerTests.cs
@@ -1,7 +1,9 @@
using System.Collections.Generic;
+using System.Security.Claims;
using ErsatzTV.Application.Auth;
using ErsatzTV.Controllers.Api;
using ErsatzTV.Controllers.Api.Requests;
+using ErsatzTV.Services;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
@@ -23,13 +25,20 @@ public class AuthControllerTests
: new Dictionary())
.Build();
+ private static IApiKeyProvider ApiKeyProvider(string key = "the-machine-key")
+ {
+ var provider = Substitute.For();
+ provider.ApiKey.Returns(key);
+ return provider;
+ }
+
[Test]
public async Task Config_Reports_Setup_Not_Required_When_Env_Seed_Configured()
{
var mediator = Substitute.For();
mediator.Send(Arg.Any(), Arg.Any()).Returns(false);
- var controller = new AuthController(mediator, Config(envSeed: true));
+ var controller = new AuthController(mediator, Config(envSeed: true), ApiKeyProvider());
var result = await controller.Config(CancellationToken.None) as OkObjectResult;
var body = result!.Value.ShouldBeOfType();
@@ -44,7 +53,7 @@ public class AuthControllerTests
var mediator = Substitute.For();
mediator.Send(Arg.Any(), Arg.Any()).Returns(false);
- var controller = new AuthController(mediator, Config(envSeed: false));
+ var controller = new AuthController(mediator, Config(envSeed: false), ApiKeyProvider());
var result = await controller.Config(CancellationToken.None) as OkObjectResult;
var body = result!.Value.ShouldBeOfType();
@@ -56,7 +65,7 @@ public class AuthControllerTests
public async Task Setup_Is_Closed_With_409_When_Env_Seed_Configured()
{
var mediator = Substitute.For();
- var controller = new AuthController(mediator, Config(envSeed: true))
+ var controller = new AuthController(mediator, Config(envSeed: true), ApiKeyProvider())
{
ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() }
};
@@ -68,4 +77,61 @@ public class AuthControllerTests
// The claim must never be attempted while the env seed owns the credential.
await mediator.DidNotReceive().Send(Arg.Any(), Arg.Any());
}
+
+ [Test]
+ public void MachineKey_Returns_401_When_Anonymous()
+ {
+ var mediator = Substitute.For();
+ var controller = new AuthController(mediator, Config(envSeed: false), ApiKeyProvider())
+ {
+ ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() }
+ };
+
+ IActionResult result = controller.MachineKey();
+
+ var unauthorized = result.ShouldBeOfType();
+ unauthorized.Value.ShouldBeOfType().Status.ShouldBe(401);
+ }
+
+ [Test]
+ public void MachineKey_Returns_The_Key_For_An_Authenticated_Session()
+ {
+ var mediator = Substitute.For();
+ var controller = new AuthController(mediator, Config(envSeed: false), ApiKeyProvider("the-machine-key"))
+ {
+ ControllerContext = new ControllerContext
+ {
+ HttpContext = new DefaultHttpContext
+ {
+ User = new ClaimsPrincipal(
+ new ClaimsIdentity([new Claim(ClaimTypes.Name, "admin")], AuthConstants.CookieScheme))
+ }
+ }
+ };
+
+ IActionResult result = controller.MachineKey();
+
+ var ok = result.ShouldBeOfType();
+ ok.Value.ShouldBeOfType().ApiKey.ShouldBe("the-machine-key");
+ }
+
+ [Test]
+ public void MachineKey_Sets_CacheControl_NoStore_For_An_Authenticated_Session()
+ {
+ var mediator = Substitute.For();
+ var httpContext = new DefaultHttpContext
+ {
+ User = new ClaimsPrincipal(
+ new ClaimsIdentity([new Claim(ClaimTypes.Name, "admin")], AuthConstants.CookieScheme))
+ };
+ var controller = new AuthController(mediator, Config(envSeed: false), ApiKeyProvider("the-machine-key"))
+ {
+ ControllerContext = new ControllerContext { HttpContext = httpContext }
+ };
+
+ controller.MachineKey();
+
+ httpContext.Response.Headers.CacheControl.ToString().ShouldBe("no-store");
+ httpContext.Response.Headers.Pragma.ToString().ShouldBe("no-cache");
+ }
}
diff --git a/ErsatzTV.Tests/Controllers/GraphicsElementControllerTests.cs b/ErsatzTV.Tests/Controllers/GraphicsElementControllerTests.cs
index 55bdff023..5dfcc6297 100644
--- a/ErsatzTV.Tests/Controllers/GraphicsElementControllerTests.cs
+++ b/ErsatzTV.Tests/Controllers/GraphicsElementControllerTests.cs
@@ -3,6 +3,7 @@ using ErsatzTV.Application.Graphics;
using ErsatzTV.Controllers.Api;
using ErsatzTV.Core.Api.Graphics;
using MediatR;
+using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Routing;
using NSubstitute;
using NUnit.Framework;
@@ -24,7 +25,7 @@ public class GraphicsElementControllerTests
}
[Test]
- public void Controller_Should_Expose_Idiomatic_Rest_Route()
+ public void Controller_Should_Expose_Idiomatic_Rest_Route_For_GetAll()
{
MethodInfo action = typeof(GraphicsElementController).GetMethod(nameof(GraphicsElementController.GetAll))
?? throw new AssertionException("Missing action GetAll");
@@ -34,6 +35,17 @@ public class GraphicsElementControllerTests
attribute.Template.ShouldBe("/api/graphics-elements");
}
+ [Test]
+ public void Controller_Should_Expose_Idiomatic_Rest_Route_For_Refresh()
+ {
+ MethodInfo action = typeof(GraphicsElementController).GetMethod(nameof(GraphicsElementController.Refresh))
+ ?? throw new AssertionException("Missing action Refresh");
+
+ HttpMethodAttribute attribute = action.GetCustomAttributes(inherit: true).Single();
+ attribute.HttpMethods.ShouldContain("POST");
+ attribute.Template.ShouldBe("/api/graphics-elements/refresh");
+ }
+
[Test]
public async Task GetAll_Should_Return_GraphicsElements()
{
@@ -45,7 +57,7 @@ public class GraphicsElementControllerTests
_mediator.Send(Arg.Any(), Arg.Any())
.Returns(models);
- List result = await _controller.GetAll(refresh: false, CancellationToken.None);
+ List result = await _controller.GetAll(CancellationToken.None);
result.ShouldBe(models);
}
@@ -56,34 +68,29 @@ public class GraphicsElementControllerTests
_mediator.Send(Arg.Any(), Arg.Any())
.Returns([]);
- List result = await _controller.GetAll(refresh: false, CancellationToken.None);
+ List result = await _controller.GetAll(CancellationToken.None);
result.ShouldBeEmpty();
}
[Test]
- public async Task GetAll_Should_Not_Refresh_When_Refresh_Is_False()
+ public async Task GetAll_Should_Never_Trigger_A_Refresh()
{
+ // the GET must be a pure read (CSRF vector when it wrote to the DB — ersatztv#316 review)
_mediator.Send(Arg.Any(), Arg.Any())
.Returns([]);
- await _controller.GetAll(refresh: false, CancellationToken.None);
+ await _controller.GetAll(CancellationToken.None);
await _mediator.DidNotReceive().Send(Arg.Any(), Arg.Any());
}
[Test]
- public async Task GetAll_Should_Refresh_Before_Listing_When_Refresh_Is_True()
+ public async Task Refresh_Should_Send_RefreshGraphicsElements_And_Return_204()
{
- _mediator.Send(Arg.Any(), Arg.Any())
- .Returns([]);
+ IActionResult result = await _controller.Refresh(CancellationToken.None);
- await _controller.GetAll(refresh: true, CancellationToken.None);
-
- Received.InOrder(() =>
- {
- _mediator.Send(Arg.Any(), Arg.Any());
- _mediator.Send(Arg.Any(), Arg.Any());
- });
+ result.ShouldBeOfType();
+ await _mediator.Received(1).Send(Arg.Any(), Arg.Any());
}
}
diff --git a/ErsatzTV.Tests/Controllers/OpenApiContractHonestyTests.cs b/ErsatzTV.Tests/Controllers/OpenApiContractHonestyTests.cs
index da94713c7..124e5ecea 100644
--- a/ErsatzTV.Tests/Controllers/OpenApiContractHonestyTests.cs
+++ b/ErsatzTV.Tests/Controllers/OpenApiContractHonestyTests.cs
@@ -72,34 +72,37 @@ public class OpenApiContractHonestyTests
}
[Test]
- public void Colliding_Troubleshoot_HeadGet_Pairs_Should_Carry_VerbDerived_OperationIds()
+ public void Troubleshoot_Playback_Actions_Should_Carry_Stable_Explicit_OperationIds()
{
- // The 3 Troubleshoot HEAD/GET pairs share a controller+action and differ only by verb. Their
- // synthesized operationIds must be verb-suffixed (structural, order-independent) — NOT one bare
- // base + one arbitrary suffix that depends on ApiExplorer visitation order. See #197 Bundle C.
+ // #301 POST-ified these three side-effecting actions (each now a single POST with an explicit
+ // Name=), which removed the former HEAD/GET collision entirely — so the synthesized verb-suffix
+ // disambiguation (#197 Bundle C) no longer applies to them. Pin the explicit ids instead, and
+ // assert the old synthesized/colliding forms are gone.
var ids = EnumerateOperations().Select(op => op.Operation.OperationId!).ToHashSet(StringComparer.Ordinal);
foreach (string expected in new[]
{
- "TroubleshootTroubleshootPlaybackGet",
- "TroubleshootTroubleshootPlaybackHead",
- "TroubleshootTroubleshootPlaybackArchiveGet",
- "TroubleshootTroubleshootPlaybackArchiveHead",
- "TroubleshootTroubleshootPlaybackSampleGet",
- "TroubleshootTroubleshootPlaybackSampleHead"
+ "StartTroubleshootingPlayback",
+ "DownloadTroubleshootingArchive",
+ "DownloadTroubleshootingMediaSample"
})
{
ids.ShouldContain(expected);
}
- // The old order-dependent forms (bare base + "...GET" suffix) must be gone.
foreach (string stale in new[]
{
"TroubleshootTroubleshootPlayback",
- "TroubleshootTroubleshootPlaybackArchive",
- "TroubleshootTroubleshootPlaybackSample",
+ "TroubleshootTroubleshootPlaybackGet",
+ "TroubleshootTroubleshootPlaybackHead",
"TroubleshootTroubleshootPlaybackGET",
+ "TroubleshootTroubleshootPlaybackArchive",
+ "TroubleshootTroubleshootPlaybackArchiveGet",
+ "TroubleshootTroubleshootPlaybackArchiveHead",
"TroubleshootTroubleshootPlaybackArchiveGET",
+ "TroubleshootTroubleshootPlaybackSample",
+ "TroubleshootTroubleshootPlaybackSampleGet",
+ "TroubleshootTroubleshootPlaybackSampleHead",
"TroubleshootTroubleshootPlaybackSampleGET"
})
{
diff --git a/ErsatzTV.Tests/Controllers/OpenApiErrorResponseContractTests.cs b/ErsatzTV.Tests/Controllers/OpenApiErrorResponseContractTests.cs
index c4ea019bc..14e03d18e 100644
--- a/ErsatzTV.Tests/Controllers/OpenApiErrorResponseContractTests.cs
+++ b/ErsatzTV.Tests/Controllers/OpenApiErrorResponseContractTests.cs
@@ -270,8 +270,9 @@ public class OpenApiErrorResponseContractTests
[TestCase("/api/trakt/lists/{id}", "put", "404")]
[TestCase("/api/trakt/lists/{id}", "put", "422")]
[TestCase("/api/troubleshoot/playback/subtitles/{mediaItemId}", "get", "404")]
- [TestCase("/api/troubleshoot/playback.m3u8", "get", "409")]
- [TestCase("/api/troubleshoot/playback.m3u8", "head", "409")]
+ [TestCase("/api/troubleshoot/playback/start", "post", "404")]
+ [TestCase("/api/troubleshoot/playback/start", "post", "409")]
+ [TestCase("/api/troubleshoot/playback/start", "post", "422")]
[TestCase("/api/libraries/{id}/scan-show", "post", "404")]
[TestCase("/api/libraries/{id}/scan", "post", "404")]
[TestCase("/api/libraries/{id}/scan", "post", "409")]
diff --git a/ErsatzTV.Tests/Controllers/TroubleshootControllerTests.cs b/ErsatzTV.Tests/Controllers/TroubleshootControllerTests.cs
index 31d470256..4f9436ba8 100644
--- a/ErsatzTV.Tests/Controllers/TroubleshootControllerTests.cs
+++ b/ErsatzTV.Tests/Controllers/TroubleshootControllerTests.cs
@@ -20,6 +20,7 @@ using ErsatzTV.Core.Notifications;
using ErsatzTV.Core.Troubleshooting;
using LanguageExt;
using MediatR;
+using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NSubstitute;
using NUnit.Framework;
@@ -249,22 +250,64 @@ public class TroubleshootControllerTests
attribute.Name.ShouldBe("GetTroubleshootingPlaybackStatus");
}
+ private static StartTroubleshootingPlaybackRequest DefaultPlaybackRequest(int mediaItem = 1, int channel = 0) =>
+ new(
+ mediaItem,
+ channel,
+ FfmpegProfile: 1,
+ StreamingMode.HttpLiveStreamingSegmenter,
+ Watermark: [],
+ GraphicsElement: [],
+ StreamSelector: string.Empty,
+ SubtitleId: null,
+ SeekSeconds: 0,
+ Start: null);
+
+ [Test]
+ public void Controller_Should_Expose_Idiomatic_Rest_Route_For_TroubleshootPlayback()
+ {
+ MethodInfo action = typeof(TroubleshootController).GetMethod(nameof(TroubleshootController.TroubleshootPlayback))
+ ?? throw new AssertionException("Missing action TroubleshootPlayback");
+
+ var attribute = action.GetCustomAttributes().Single();
+ attribute.Template.ShouldBe("api/troubleshoot/playback/start");
+ attribute.Name.ShouldBe("StartTroubleshootingPlayback");
+ action.GetParameters()[0].ParameterType.ShouldBe(typeof(StartTroubleshootingPlaybackRequest));
+ }
+
+ [Test]
+ public void Controller_Should_Expose_Idiomatic_Rest_Route_For_PlaybackArchive()
+ {
+ MethodInfo action = typeof(TroubleshootController).GetMethod(nameof(TroubleshootController.TroubleshootPlaybackArchive))
+ ?? throw new AssertionException("Missing action TroubleshootPlaybackArchive");
+
+ var attribute = action.GetCustomAttributes().Single();
+ attribute.Template.ShouldBe("api/troubleshoot/playback/archive");
+ attribute.Name.ShouldBe("DownloadTroubleshootingArchive");
+ action.GetCustomAttributes().ShouldBeEmpty();
+ action.GetCustomAttributes().ShouldBeEmpty();
+ }
+
+ [Test]
+ public void Controller_Should_Expose_Idiomatic_Rest_Route_For_PlaybackSample()
+ {
+ MethodInfo action = typeof(TroubleshootController).GetMethod(nameof(TroubleshootController.TroubleshootPlaybackSample))
+ ?? throw new AssertionException("Missing action TroubleshootPlaybackSample");
+
+ var attribute = action.GetCustomAttributes().Single();
+ attribute.Template.ShouldBe("api/troubleshoot/playback/sample/{mediaItemId:int}");
+ attribute.Name.ShouldBe("DownloadTroubleshootingMediaSample");
+ action.GetCustomAttributes().ShouldBeEmpty();
+ action.GetCustomAttributes().ShouldBeEmpty();
+ }
+
[Test]
public async Task TroubleshootPlayback_Should_Return_409_When_Already_Locked()
{
_entityLocker.IsTroubleshootingPlaybackLocked().Returns(true);
IActionResult result = await _controller.TroubleshootPlayback(
- mediaItem: 1,
- channel: 0,
- ffmpegProfile: 1,
- StreamingMode.HttpLiveStreamingSegmenter,
- watermark: [],
- graphicsElement: [],
- streamSelector: string.Empty,
- subtitleId: null,
- seekSeconds: 0,
- start: null,
+ DefaultPlaybackRequest(),
CancellationToken.None);
ConflictObjectResult conflict = result.ShouldBeOfType();
@@ -275,6 +318,24 @@ public class TroubleshootControllerTests
.Send(Arg.Any(), Arg.Any());
}
+ [Test]
+ public async Task TroubleshootPlayback_Should_Return_409_ProblemDetails_When_Prepare_Loses_Lock_Race()
+ {
+ // pre-check passes, but the handler's atomic acquire loses the race to another session
+ // that grabbed the lock in between -> still a 409, not a 422 (ersatztv#316 review)
+ _entityLocker.IsTroubleshootingPlaybackLocked().Returns(false);
+ _mediator.Send(Arg.Any(), Arg.Any())
+ .Returns(Either.Left(
+ new ErsatzTV.Core.Errors.LockedError("Troubleshooting playback is locked")));
+
+ IActionResult result = await _controller.TroubleshootPlayback(
+ DefaultPlaybackRequest(),
+ CancellationToken.None);
+
+ var conflict = result.ShouldBeOfType();
+ conflict.Value.ShouldBeOfType().Status.ShouldBe(409);
+ }
+
[Test]
public async Task TroubleshootPlayback_Should_Return_404_ProblemDetails_When_Prepare_Not_Found()
{
@@ -284,16 +345,7 @@ public class TroubleshootControllerTests
new ErsatzTV.Core.Errors.NotFoundError("no such media item")));
IActionResult result = await _controller.TroubleshootPlayback(
- mediaItem: 999,
- channel: 0,
- ffmpegProfile: 1,
- StreamingMode.HttpLiveStreamingSegmenter,
- watermark: [],
- graphicsElement: [],
- streamSelector: string.Empty,
- subtitleId: null,
- seekSeconds: 0,
- start: null,
+ DefaultPlaybackRequest(mediaItem: 999),
CancellationToken.None);
var notFound = result.ShouldBeOfType();
@@ -308,22 +360,94 @@ public class TroubleshootControllerTests
.Returns(Either.Left(BaseError.New("unable to prepare")));
IActionResult result = await _controller.TroubleshootPlayback(
- mediaItem: 1,
- channel: 0,
- ffmpegProfile: 1,
- StreamingMode.HttpLiveStreamingSegmenter,
- watermark: [],
- graphicsElement: [],
- streamSelector: string.Empty,
- subtitleId: null,
- seekSeconds: 0,
- start: null,
+ DefaultPlaybackRequest(),
CancellationToken.None);
var unprocessable = result.ShouldBeOfType();
unprocessable.Value.ShouldBeOfType().Status.ShouldBe(422);
}
+ [Test]
+ public async Task TroubleshootPlayback_Should_Return_200_With_Rooted_Iptv_Url_On_Success()
+ {
+ // The segment-readiness poll shells out to the real filesystem (Directory.GetFiles), not the
+ // injected IFileSystem abstraction, so this test seeds real files under the troubleshooting
+ // transcode folder rather than mocking it.
+ Directory.CreateDirectory(FileSystemLayout.TranscodeTroubleshootingFolder);
+ string segmentPath = Path.Combine(FileSystemLayout.TranscodeTroubleshootingFolder, "seg-test-0.ts");
+ string segmentPath2 = Path.Combine(FileSystemLayout.TranscodeTroubleshootingFolder, "seg-test-1.ts");
+ await File.WriteAllTextAsync(segmentPath, string.Empty);
+ await File.WriteAllTextAsync(segmentPath2, string.Empty);
+
+ try
+ {
+ _entityLocker.IsTroubleshootingPlaybackLocked().Returns(false);
+
+ var playoutItemResult = new PlayoutItemResult(
+ new CliWrap.Command("ffmpeg"),
+ Option.None,
+ Option.Some(1));
+
+ _mediator.Send(Arg.Any(), Arg.Any())
+ .Returns(Either.Right(playoutItemResult));
+ _mediator.Send(Arg.Any(), Arg.Any())
+ .Returns(Either.Right(FakeMediaItemInfo()));
+ _mediator.Send(Arg.Any(), Arg.Any())
+ .Returns(new TroubleshootingInfo(
+ "1.2.3",
+ new Dictionary(),
+ [],
+ [],
+ [],
+ new ErsatzTV.Application.FFmpegProfiles.FFmpegSettingsViewModel(),
+ [],
+ [],
+ [],
+ false,
+ false,
+ null,
+ null,
+ null,
+ null));
+
+ var fileSystem = Substitute.For();
+ fileSystem.File.Exists(Arg.Any()).Returns(true);
+
+ var configElementRepository = Substitute.For();
+ configElementRepository
+ .GetValue(ConfigElementKey.FFmpegInitialSegmentCount, Arg.Any())
+ .Returns(Option.Some(2));
+
+ var controller = new TroubleshootController(
+ System.Threading.Channels.Channel.CreateUnbounded().Writer,
+ fileSystem,
+ configElementRepository,
+ Substitute.For(),
+ _entityLocker,
+ _statusStore,
+ _mediator)
+ {
+ ControllerContext = new ControllerContext
+ {
+ HttpContext = new DefaultHttpContext { Request = { PathBase = "/etv" } }
+ }
+ };
+
+ IActionResult result = await controller.TroubleshootPlayback(
+ DefaultPlaybackRequest(),
+ CancellationToken.None);
+
+ var ok = result.ShouldBeOfType();
+ var body = ok.Value.ShouldBeOfType();
+ body.Url.ShouldBe("/etv/iptv/session/.troubleshooting/live.m3u8");
+ }
+ finally
+ {
+ File.Delete(segmentPath);
+ File.Delete(segmentPath2);
+ }
+ }
+
[Test]
public async Task GetPlaybackStatus_Should_Report_Idle_When_No_Result_And_Unlocked()
{
diff --git a/ErsatzTV.Tests/Extensions/ApiResultsTests.cs b/ErsatzTV.Tests/Extensions/ApiResultsTests.cs
index 3e37238e4..fc8916dad 100644
--- a/ErsatzTV.Tests/Extensions/ApiResultsTests.cs
+++ b/ErsatzTV.Tests/Extensions/ApiResultsTests.cs
@@ -38,6 +38,24 @@ public class ApiResultsTests
problemDetails.Detail.ShouldBe("missing");
}
+ [Test]
+ public void ToErrorResult_Should_Map_LockedError_To_409()
+ {
+ IActionResult result = new LockedError("locked").ToErrorResult();
+ result.ShouldBeOfType().StatusCode.ShouldBe(409);
+ }
+
+ [Test]
+ public void ToErrorResult_Should_Return_ProblemDetails_For_LockedError()
+ {
+ IActionResult result = new LockedError("locked").ToErrorResult();
+
+ var conflict = result.ShouldBeOfType();
+ var problemDetails = conflict.Value.ShouldBeOfType();
+ problemDetails.Status.ShouldBe(409);
+ problemDetails.Detail.ShouldBe("locked");
+ }
+
[Test]
public void ToErrorResult_Should_Map_Other_Error_To_422()
{
diff --git a/ErsatzTV/Controllers/Api/AuthController.cs b/ErsatzTV/Controllers/Api/AuthController.cs
index cc633a61d..732e6d462 100644
--- a/ErsatzTV/Controllers/Api/AuthController.cs
+++ b/ErsatzTV/Controllers/Api/AuthController.cs
@@ -4,6 +4,7 @@ using ErsatzTV.Controllers.Api.Requests;
using ErsatzTV.Core;
using ErsatzTV.Extensions;
using ErsatzTV.Filters;
+using ErsatzTV.Services;
using MediatR;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
@@ -21,7 +22,8 @@ namespace ErsatzTV.Controllers.Api;
[ApiController]
[ApiExplorerSettings(IgnoreApi = true)]
[SkipApiAuthorization]
-public class AuthController(IMediator mediator, IConfiguration configuration) : ControllerBase
+public class AuthController(IMediator mediator, IConfiguration configuration, IApiKeyProvider apiKeyProvider)
+ : ControllerBase
{
// When the operator has set an env seed, the local admin is managed via configuration — the browser
// setup-claim is closed. This also eliminates the startup race where an attacker could claim admin in the
@@ -48,6 +50,30 @@ public class AuthController(IMediator mediator, IConfiguration configuration) :
return Ok(new AuthSessionResponse(true, User.Identity?.Name, User.FindFirst(AuthConstants.AuthMethodClaim)?.Value));
}
+ ///
+ /// The effective machine X-Api-Key (issue #301), for the ChicoryTV "API Key" settings screen to
+ /// display once it moves off session-managed auth. Requires any authenticated session (OIDC or local);
+ /// 401 otherwise. Never CSRF-gated — it's a GET, and SOP already blocks a cross-site page from reading a
+ /// credentialed response body.
+ ///
+ [HttpGet("/api/auth/machine-key")]
+ public IActionResult MachineKey()
+ {
+ if (User.Identity?.IsAuthenticated != true)
+ {
+ return Unauthorized(new ProblemDetails
+ {
+ Status = StatusCodes.Status401Unauthorized,
+ Title = "Unauthorized",
+ Detail = "An authenticated session is required."
+ });
+ }
+
+ Response.Headers.CacheControl = "no-store";
+ Response.Headers.Pragma = "no-cache";
+ return Ok(new MachineKeyResponse(apiKeyProvider.ApiKey));
+ }
+
/// First-run setup-claim: create the local admin. Fails 409 if one already exists.
[HttpPost("/api/auth/setup")]
[EnableRateLimiting("auth")]
@@ -232,3 +258,5 @@ public class AuthController(IMediator mediator, IConfiguration configuration) :
public record AuthConfigResponse(bool OidcEnabled, bool LocalLoginEnabled, bool SetupRequired);
public record AuthSessionResponse(bool Authenticated, string Username, string Method);
+
+public record MachineKeyResponse(string ApiKey);
diff --git a/ErsatzTV/Controllers/Api/GraphicsElementController.cs b/ErsatzTV/Controllers/Api/GraphicsElementController.cs
index 3496d7d96..ba63df156 100644
--- a/ErsatzTV/Controllers/Api/GraphicsElementController.cs
+++ b/ErsatzTV/Controllers/Api/GraphicsElementController.cs
@@ -12,20 +12,23 @@ public class GraphicsElementController(IMediator mediator) : ControllerBase
[HttpGet("/api/graphics-elements", Name = "GetGraphicsElements")]
[Tags("Graphics Elements")]
[EndpointSummary("Get all graphics elements")]
- [EndpointDescription(
- "Returns all graphics elements. Pass refresh=true to first re-sync the on-disk graphics element " +
- "definitions into the database (matching the legacy Blazor behavior) so newly added files appear.")]
+ [EndpointDescription("Returns all graphics elements.")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(List), StatusCodes.Status200OK)]
- public async Task> GetAll(
- [FromQuery] bool refresh,
- CancellationToken cancellationToken)
- {
- if (refresh)
- {
- await mediator.Send(new RefreshGraphicsElements(), cancellationToken);
- }
+ public async Task> GetAll(CancellationToken cancellationToken) =>
+ await mediator.Send(new GetAllGraphicsElementsForApi(), cancellationToken);
- return await mediator.Send(new GetAllGraphicsElementsForApi(), cancellationToken);
+ [HttpPost("/api/graphics-elements/refresh", Name = "RefreshGraphicsElements")]
+ [Tags("Graphics Elements")]
+ [EndpointSummary("Re-sync graphics elements from disk")]
+ [EndpointDescription(
+ "Re-syncs the on-disk graphics element definitions into the database (matching the legacy Blazor " +
+ "behavior) so newly added files appear.")]
+ [EndpointGroupName("general")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public async Task Refresh(CancellationToken cancellationToken)
+ {
+ await mediator.Send(new RefreshGraphicsElements(), cancellationToken);
+ return NoContent();
}
}
diff --git a/ErsatzTV/Controllers/Api/Requests/StartTroubleshootingPlaybackRequest.cs b/ErsatzTV/Controllers/Api/Requests/StartTroubleshootingPlaybackRequest.cs
new file mode 100644
index 000000000..2a7374740
--- /dev/null
+++ b/ErsatzTV/Controllers/Api/Requests/StartTroubleshootingPlaybackRequest.cs
@@ -0,0 +1,15 @@
+using ErsatzTV.Core.Domain;
+
+namespace ErsatzTV.Controllers.Api.Requests;
+
+public record StartTroubleshootingPlaybackRequest(
+ int MediaItem,
+ int Channel,
+ int FfmpegProfile,
+ StreamingMode StreamingMode,
+ List Watermark,
+ List GraphicsElement,
+ string StreamSelector,
+ int? SubtitleId,
+ int SeekSeconds,
+ DateTimeOffset? Start);
diff --git a/ErsatzTV/Controllers/Api/TroubleshootController.cs b/ErsatzTV/Controllers/Api/TroubleshootController.cs
index f2b2158b0..3fadd189f 100644
--- a/ErsatzTV/Controllers/Api/TroubleshootController.cs
+++ b/ErsatzTV/Controllers/Api/TroubleshootController.cs
@@ -112,37 +112,30 @@ public class TroubleshootController(
new ValidateSequentialScheduleResponseModel(result.IsValid, result.Messages, result.Json));
}
- [HttpHead("api/troubleshoot/playback.m3u8")]
- [HttpGet("api/troubleshoot/playback.m3u8")]
+ [HttpPost("api/troubleshoot/playback/start", Name = "StartTroubleshootingPlayback")]
[Tags("Troubleshooting")]
[EndpointSummary("Start a troubleshooting playback session")]
[EndpointGroupName("general")]
+ [ProducesResponseType(typeof(TroubleshootingPlaybackStartedResponseModel), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status409Conflict)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
public async Task TroubleshootPlayback(
- [FromQuery]
- int mediaItem,
- [FromQuery]
- int channel,
- [FromQuery]
- int ffmpegProfile,
- [FromQuery]
- StreamingMode streamingMode,
- [FromQuery]
- List watermark,
- [FromQuery]
- List graphicsElement,
- [FromQuery]
- string streamSelector,
- [FromQuery]
- int? subtitleId,
- [FromQuery]
- int seekSeconds,
- [FromQuery]
- DateTimeOffset? start,
+ [FromBody]
+ StartTroubleshootingPlaybackRequest request,
CancellationToken cancellationToken)
{
+ int mediaItem = request.MediaItem;
+ int channel = request.Channel;
+ int ffmpegProfile = request.FfmpegProfile;
+ StreamingMode streamingMode = request.StreamingMode;
+ List watermark = request.Watermark;
+ List graphicsElement = request.GraphicsElement;
+ string streamSelector = request.StreamSelector;
+ int? subtitleId = request.SubtitleId;
+ int seekSeconds = request.SeekSeconds;
+ DateTimeOffset? start = request.Start;
+
var sessionId = Guid.NewGuid();
using var logContext = LogContext.PushProperty(InMemoryLogService.CorrelationIdKey, sessionId);
@@ -261,7 +254,9 @@ public class TroubleshootController(
if (!notifier.IsFailed(sessionId))
{
- return Redirect("~/iptv/session/.troubleshooting/live.m3u8");
+ return Ok(
+ new TroubleshootingPlaybackStartedResponseModel(
+ $"{Request.PathBase}/iptv/session/.troubleshooting/live.m3u8"));
}
}
finally
@@ -292,8 +287,7 @@ public class TroubleshootController(
"Troubleshooting playback did not produce any output. It may have failed to start or been cancelled.");
}
- [HttpHead("api/troubleshoot/playback/archive")]
- [HttpGet("api/troubleshoot/playback/archive")]
+ [HttpPost("api/troubleshoot/playback/archive", Name = "DownloadTroubleshootingArchive")]
[Tags("Troubleshooting")]
[EndpointSummary("Download the last troubleshooting playback session archive")]
[EndpointGroupName("general")]
@@ -318,8 +312,7 @@ public class TroubleshootController(
return NotFound();
}
- [HttpHead("api/troubleshoot/playback/sample/{mediaItemId:int}")]
- [HttpGet("api/troubleshoot/playback/sample/{mediaItemId:int}")]
+ [HttpPost("api/troubleshoot/playback/sample/{mediaItemId:int}", Name = "DownloadTroubleshootingMediaSample")]
[Tags("Troubleshooting")]
[EndpointSummary("Download a media sample archive for troubleshooting")]
[EndpointGroupName("general")]
@@ -357,7 +350,7 @@ public class TroubleshootController(
[EndpointSummary("List selectable subtitle streams for a media item")]
[EndpointDescription(
"Returns the subtitle streams that can be burned in for a troubleshooting playback. Each item's id is the " +
- "value to pass back as the playback.m3u8 endpoint's subtitleId query parameter.")]
+ "value to pass back as the POST /api/troubleshoot/playback/start request body's subtitleId field.")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(List), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
diff --git a/ErsatzTV/Extensions/ApiResults.cs b/ErsatzTV/Extensions/ApiResults.cs
index b520e9ef5..e3d32db3f 100644
--- a/ErsatzTV/Extensions/ApiResults.cs
+++ b/ErsatzTV/Extensions/ApiResults.cs
@@ -18,7 +18,8 @@ public static class ApiResults
///
/// Maps a failure to 404 when it is a , 412 when it is a
/// (optimistic-concurrency mismatch, issue #253),
- /// otherwise 422.
+ /// 409 when it is a (a mutation raced another operation's exclusive
+ /// lock), otherwise 422.
///
public static IActionResult ToErrorResult(this BaseError error) =>
error switch
@@ -30,6 +31,8 @@ public static class ApiResults
{
StatusCode = StatusCodes.Status412PreconditionFailed
},
+ LockedError =>
+ ConflictProblem("Troubleshooting playback is locked", error.Value),
_ =>
new UnprocessableEntityObjectResult(CreateProblemDetails(422, "Validation failed", error.Value))
};
diff --git a/ErsatzTV/wwwroot/openapi/v1.json b/ErsatzTV/wwwroot/openapi/v1.json
index f6abb3756..228df4de5 100644
--- a/ErsatzTV/wwwroot/openapi/v1.json
+++ b/ErsatzTV/wwwroot/openapi/v1.json
@@ -7532,17 +7532,8 @@
"Graphics Elements"
],
"summary": "Get all graphics elements",
- "description": "Returns all graphics elements. Pass refresh=true to first re-sync the on-disk graphics element definitions into the database (matching the legacy Blazor behavior) so newly added files appear.",
+ "description": "Returns all graphics elements.",
"operationId": "GetGraphicsElements",
- "parameters": [
- {
- "name": "refresh",
- "in": "query",
- "schema": {
- "type": "boolean"
- }
- }
- ],
"responses": {
"200": {
"description": "OK",
@@ -7582,13 +7573,31 @@
}
}
}
+ }
+ },
+ "security": [
+ { }
+ ]
+ }
+ },
+ "/api/graphics-elements/refresh": {
+ "post": {
+ "tags": [
+ "Graphics Elements"
+ ],
+ "summary": "Re-sync graphics elements from disk",
+ "description": "Re-syncs the on-disk graphics element definitions into the database (matching the legacy Blazor behavior) so newly added files appear.",
+ "operationId": "RefreshGraphicsElements",
+ "responses": {
+ "204": {
+ "description": "No Content"
},
- "400": {
- "description": "Request validation failed (model binding or FluentValidation).",
+ "401": {
+ "description": "API key missing or invalid.",
"content": {
"application/json": {
"schema": {
- "$ref": "#/components/schemas/ValidationProblemDetails"
+ "$ref": "#/components/schemas/ProblemDetails"
}
}
}
@@ -21113,278 +21122,59 @@
]
}
},
- "/api/troubleshoot/playback.m3u8": {
- "head": {
+ "/api/troubleshoot/playback/start": {
+ "post": {
"tags": [
"Troubleshooting"
],
"summary": "Start a troubleshooting playback session",
- "operationId": "TroubleshootTroubleshootPlaybackHead",
- "parameters": [
- {
- "name": "mediaItem",
- "in": "query",
- "schema": {
- "type": "integer",
- "format": "int32"
- }
- },
- {
- "name": "channel",
- "in": "query",
- "schema": {
- "type": "integer",
- "format": "int32"
- }
- },
- {
- "name": "ffmpegProfile",
- "in": "query",
- "schema": {
- "type": "integer",
- "format": "int32"
- }
- },
- {
- "name": "streamingMode",
- "in": "query",
- "schema": {
- "$ref": "#/components/schemas/StreamingMode"
- }
- },
- {
- "name": "watermark",
- "in": "query",
- "schema": {
- "type": "array",
- "items": {
- "type": "integer",
- "format": "int32"
+ "operationId": "StartTroubleshootingPlayback",
+ "requestBody": {
+ "content": {
+ "application/json-patch+json": {
+ "schema": {
+ "$ref": "#/components/schemas/StartTroubleshootingPlaybackRequest"
+ }
+ },
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/StartTroubleshootingPlaybackRequest"
+ }
+ },
+ "text/json": {
+ "schema": {
+ "$ref": "#/components/schemas/StartTroubleshootingPlaybackRequest"
+ }
+ },
+ "application/*+json": {
+ "schema": {
+ "$ref": "#/components/schemas/StartTroubleshootingPlaybackRequest"
}
}
},
- {
- "name": "graphicsElement",
- "in": "query",
- "schema": {
- "type": "array",
- "items": {
- "type": "integer",
- "format": "int32"
- }
- }
- },
- {
- "name": "streamSelector",
- "in": "query",
- "schema": {
- "type": "string"
- }
- },
- {
- "name": "subtitleId",
- "in": "query",
- "schema": {
- "type": "integer",
- "format": "int32"
- }
- },
- {
- "name": "seekSeconds",
- "in": "query",
- "schema": {
- "type": "integer",
- "format": "int32"
- }
- },
- {
- "name": "start",
- "in": "query",
- "schema": {
- "type": "string",
- "format": "date-time"
- }
- }
- ],
- "responses": {
- "404": {
- "description": "Not Found",
- "content": {
- "text/plain": {
- "schema": {
- "$ref": "#/components/schemas/ProblemDetails"
- }
- },
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/ProblemDetails"
- }
- },
- "text/json": {
- "schema": {
- "$ref": "#/components/schemas/ProblemDetails"
- }
- }
- }
- },
- "409": {
- "description": "Conflict",
- "content": {
- "text/plain": {
- "schema": {
- "$ref": "#/components/schemas/ProblemDetails"
- }
- },
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/ProblemDetails"
- }
- },
- "text/json": {
- "schema": {
- "$ref": "#/components/schemas/ProblemDetails"
- }
- }
- }
- },
- "422": {
- "description": "Unprocessable Entity",
- "content": {
- "text/plain": {
- "schema": {
- "$ref": "#/components/schemas/ProblemDetails"
- }
- },
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/ProblemDetails"
- }
- },
- "text/json": {
- "schema": {
- "$ref": "#/components/schemas/ProblemDetails"
- }
- }
- }
- },
- "401": {
- "description": "API key missing or invalid.",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/ProblemDetails"
- }
- }
- }
- },
- "400": {
- "description": "Request validation failed (model binding or FluentValidation).",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/ValidationProblemDetails"
- }
- }
- }
- }
+ "required": true
},
- "security": [
- { }
- ]
- },
- "get": {
- "tags": [
- "Troubleshooting"
- ],
- "summary": "Start a troubleshooting playback session",
- "operationId": "TroubleshootTroubleshootPlaybackGet",
- "parameters": [
- {
- "name": "mediaItem",
- "in": "query",
- "schema": {
- "type": "integer",
- "format": "int32"
- }
- },
- {
- "name": "channel",
- "in": "query",
- "schema": {
- "type": "integer",
- "format": "int32"
- }
- },
- {
- "name": "ffmpegProfile",
- "in": "query",
- "schema": {
- "type": "integer",
- "format": "int32"
- }
- },
- {
- "name": "streamingMode",
- "in": "query",
- "schema": {
- "$ref": "#/components/schemas/StreamingMode"
- }
- },
- {
- "name": "watermark",
- "in": "query",
- "schema": {
- "type": "array",
- "items": {
- "type": "integer",
- "format": "int32"
- }
- }
- },
- {
- "name": "graphicsElement",
- "in": "query",
- "schema": {
- "type": "array",
- "items": {
- "type": "integer",
- "format": "int32"
- }
- }
- },
- {
- "name": "streamSelector",
- "in": "query",
- "schema": {
- "type": "string"
- }
- },
- {
- "name": "subtitleId",
- "in": "query",
- "schema": {
- "type": "integer",
- "format": "int32"
- }
- },
- {
- "name": "seekSeconds",
- "in": "query",
- "schema": {
- "type": "integer",
- "format": "int32"
- }
- },
- {
- "name": "start",
- "in": "query",
- "schema": {
- "type": "string",
- "format": "date-time"
- }
- }
- ],
"responses": {
+ "200": {
+ "description": "OK",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "$ref": "#/components/schemas/TroubleshootingPlaybackStartedResponseModel"
+ }
+ },
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/TroubleshootingPlaybackStartedResponseModel"
+ }
+ },
+ "text/json": {
+ "schema": {
+ "$ref": "#/components/schemas/TroubleshootingPlaybackStartedResponseModel"
+ }
+ }
+ }
+ },
"404": {
"description": "Not Found",
"content": {
@@ -21472,37 +21262,12 @@
}
},
"/api/troubleshoot/playback/archive": {
- "head": {
+ "post": {
"tags": [
"Troubleshooting"
],
"summary": "Download the last troubleshooting playback session archive",
- "operationId": "TroubleshootTroubleshootPlaybackArchiveHead",
- "responses": {
- "200": {
- "description": "OK"
- },
- "401": {
- "description": "API key missing or invalid.",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/ProblemDetails"
- }
- }
- }
- }
- },
- "security": [
- { }
- ]
- },
- "get": {
- "tags": [
- "Troubleshooting"
- ],
- "summary": "Download the last troubleshooting playback session archive",
- "operationId": "TroubleshootTroubleshootPlaybackArchiveGet",
+ "operationId": "DownloadTroubleshootingArchive",
"responses": {
"200": {
"description": "OK"
@@ -21524,58 +21289,12 @@
}
},
"/api/troubleshoot/playback/sample/{mediaItemId}": {
- "head": {
+ "post": {
"tags": [
"Troubleshooting"
],
"summary": "Download a media sample archive for troubleshooting",
- "operationId": "TroubleshootTroubleshootPlaybackSampleHead",
- "parameters": [
- {
- "name": "mediaItemId",
- "in": "path",
- "required": true,
- "schema": {
- "type": "integer",
- "format": "int32"
- }
- }
- ],
- "responses": {
- "200": {
- "description": "OK"
- },
- "401": {
- "description": "API key missing or invalid.",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/ProblemDetails"
- }
- }
- }
- },
- "400": {
- "description": "Request validation failed (model binding or FluentValidation).",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/ValidationProblemDetails"
- }
- }
- }
- }
- },
- "security": [
- { }
- ]
- },
- "get": {
- "tags": [
- "Troubleshooting"
- ],
- "summary": "Download a media sample archive for troubleshooting",
- "operationId": "TroubleshootTroubleshootPlaybackSampleGet",
+ "operationId": "DownloadTroubleshootingMediaSample",
"parameters": [
{
"name": "mediaItemId",
@@ -21676,7 +21395,7 @@
"Troubleshooting"
],
"summary": "List selectable subtitle streams for a media item",
- "description": "Returns the subtitle streams that can be burned in for a troubleshooting playback. Each item's id is the value to pass back as the playback.m3u8 endpoint's subtitleId query parameter.",
+ "description": "Returns the subtitle streams that can be burned in for a troubleshooting playback. Each item's id is the value to pass back as the POST /api/troubleshoot/playback/start request body's subtitleId field.",
"operationId": "GetTroubleshootingSubtitles",
"parameters": [
{
@@ -30188,6 +29907,82 @@
}
}
},
+ "StartTroubleshootingPlaybackRequest": {
+ "required": [
+ "mediaItem",
+ "channel",
+ "ffmpegProfile",
+ "streamingMode",
+ "watermark",
+ "graphicsElement",
+ "streamSelector",
+ "subtitleId",
+ "seekSeconds",
+ "start"
+ ],
+ "type": "object",
+ "properties": {
+ "mediaItem": {
+ "type": "integer",
+ "format": "int32"
+ },
+ "channel": {
+ "type": "integer",
+ "format": "int32"
+ },
+ "ffmpegProfile": {
+ "type": "integer",
+ "format": "int32"
+ },
+ "streamingMode": {
+ "$ref": "#/components/schemas/StreamingMode"
+ },
+ "watermark": {
+ "type": [
+ "null",
+ "array"
+ ],
+ "items": {
+ "type": "integer",
+ "format": "int32"
+ }
+ },
+ "graphicsElement": {
+ "type": [
+ "null",
+ "array"
+ ],
+ "items": {
+ "type": "integer",
+ "format": "int32"
+ }
+ },
+ "streamSelector": {
+ "type": [
+ "null",
+ "string"
+ ]
+ },
+ "subtitleId": {
+ "type": [
+ "null",
+ "integer"
+ ],
+ "format": "int32"
+ },
+ "seekSeconds": {
+ "type": "integer",
+ "format": "int32"
+ },
+ "start": {
+ "type": [
+ "null",
+ "string"
+ ],
+ "format": "date-time"
+ }
+ }
+ },
"StartType": {
"enum": [
"Dynamic",
@@ -30427,6 +30222,17 @@
}
}
},
+ "TroubleshootingPlaybackStartedResponseModel": {
+ "required": [
+ "url"
+ ],
+ "type": "object",
+ "properties": {
+ "url": {
+ "type": "string"
+ }
+ }
+ },
"TroubleshootingPlaybackStatusResponseModel": {
"required": [
"state",
diff --git a/docs/api-conventions.md b/docs/api-conventions.md
index 68f790d05..4c97516e7 100644
--- a/docs/api-conventions.md
+++ b/docs/api-conventions.md
@@ -94,7 +94,7 @@ hand-rolling `IActionResult` status codes:
| Method | Input | Output |
|---|---|---|
-| `ToErrorResult()` | `BaseError` | 404 if `NotFoundError`, **412 if `PreconditionFailedError`** (optimistic-concurrency mismatch, §7a), else 422 (`ProblemDetails`) |
+| `ToErrorResult()` | `BaseError` | 404 if `NotFoundError`, **412 if `PreconditionFailedError`** (optimistic-concurrency mismatch, §7a), **409 if `LockedError`** (a handler's own lock-acquire lost the race, §3a), else 422 (`ProblemDetails`) |
| `ToCreatedResult(location, body)` | `Either` | `Left` → `ToErrorResult()`; `Right` → 201 + `Location` header |
| `ToUpdatedResult()` | `Either` | `Left` → `ToErrorResult()`; `Right` → 200 + body |
| `ToDeletedResult()` | `Either` | `Left` → `ToErrorResult()`; `Right` → 204 |
@@ -142,6 +142,15 @@ action. Precedent for the 409 shape: `TraktController` (its private `ConflictPro
contract keys on `Id`, never the user-mutable `Number` (re-keyed in #197 Bundle C; see
`docs/decisions.md` 2026-07-12). The broadcast-side lookup (`GetPlayoutIdByChannelNumber`, used by
`HlsSessionWorker`) stays number-keyed — a separate contract. Reserve 200 for a synchronous durable result.
+- **Handler-side atomic lock loss also maps to 409, via a typed error, not 422** (issue #316 review):
+ when the *handler itself* is the one that atomically acquires an `IEntityLocker` lock (not just a
+ controller pre-check) and loses the race, return `new LockedError(...)` (`ErsatzTV.Core/Errors/LockedError.cs`,
+ sibling of `NotFoundError`/`PreconditionFailedError`) from the handler — `ToErrorResult()` maps it to
+ 409 automatically. Exemplar: `PrepareTroubleshootingPlaybackHandler` — `TroubleshootController` does a
+ cheap `IsTroubleshootingPlaybackLocked()` pre-check (advisory, §3a's check-then-act caveat applies),
+ but the handler's own `LockTroubleshootingPlayback()` is the atomic acquire; if *that* loses the race
+ it returns `LockedError`, so the 409 survives even when the pre-check passed a moment too early. Don't
+ let a handler-side lock loss fall through to the generic 422 `BaseError.New(...)`.
### 3b. Map a "queue a background job" outcome to status codes with an enum, not a `bool`
@@ -599,7 +608,8 @@ OpenAPI generation, so the spec can't drift). When you add an endpoint:
**only** auth-exempt controllers.
- **The `/api/auth/*` surface** (`AuthController`, `[ApiExplorerSettings(IgnoreApi = true)]` → excluded from the
OpenAPI doc, whose audience is machine clients): `GET config` (what auth options exist + `setupRequired`),
- `GET session`, `POST setup` (first-run claim), `POST login`, `POST logout`, `POST password`. The browser-nav
+ `GET session`, `POST setup` (first-run claim), `POST login`, `POST logout`, `POST password`, `GET machine-key`
+ (returns the server machine key to an authenticated session — the SPA's machine-key-management screen). The browser-nav
OIDC challenge is `GET /auth/oidc/login` (outside `/api`). `login`/`setup`/`password` carry a per-IP rate
limit (`[EnableRateLimiting("auth")]`, 10 / 5 min). The local admin is a single credential in `ConfigElement`
rows (`AuthLocalAdminUsername`/`AuthLocalAdminPasswordHash` (PBKDF2) / `AuthSecurityStamp`) — **no DB
@@ -620,15 +630,19 @@ OpenAPI generation, so the spec can't drift). When you add an endpoint:
`KnownProxies`. **Strongly set `KnownProxies`/`:KnownNetworks`** when exposing ErsatzTV behind a proxy — it
also gives the #295 login rate limiter an unspoofable client IP and lets the session cookie be marked
`Secure` behind TLS.
-- **Side-effecting GET endpoints are not CSRF-covered by the filter** (it only checks mutating verbs). A few
- `[RequiresAuthentication]` GETs have side effects (e.g. `GET /api/troubleshoot/playback.m3u8` starts playback).
- Once a session cookie is a normal SPA credential (PR2), those need POST-ification or an explicit `X-CSRF` gate
- — tracked as **#301**, which gates PR2 (latent in PR1: the SPA still uses the machine key, so no session
- reaches them in normal use).
-- **PR1 scope note (this change is server-only).** The SPA still authenticates with the stored key
- (`ctv-api-key`, `X-Api-Key`) until the SPA login flow lands (PR2) — PR1 is backward compatible. The
- `ApiKeyScreen` → machine-key-management repurpose, the SPA login/setup screens, and `spa-conventions §5e`
- update all land in PR2.
+- **Never add a side-effecting GET/HEAD under `/api`.** The filter's CSRF check only covers mutating verbs, so
+ a side-effecting GET is a CSRF vector the moment a session cookie is a normal credential (a `SameSite=Lax`
+ cookie rides a cross-site top-level GET navigation). The former `GET /api/troubleshoot/playback.m3u8` (started
+ an FFmpeg workload) and the archive/sample GETs were **POST-ified for #301** (PR2): `POST
+ /api/troubleshoot/playback/start` (returns `{ url }` pointing at the open `/iptv` manifest), `POST
+ /api/troubleshoot/playback/archive`, `POST /api/troubleshoot/playback/sample/{mediaItemId}` — so the standard
+ session-mutation CSRF gate covers them with no new filter machinery (removing HEAD also fixed a latent
+ `DeleteOnClose`-on-HEAD artifact-destruction bug). Any new endpoint that *does* something must be a mutating
+ verb; a GET must be a pure read.
+- **The SPA cutover shipped in PR2 (#295 + #301).** The browser now authenticates with the session cookie only —
+ it no longer sends `X-Api-Key`; the machine key is external/MCP-only, surfaced read-only by the machine-key
+ screen (`GET /api/auth/machine-key`). See `spa-conventions.md §5e` for the SPA seams (boot gate, central
+ `X-Csrf` on mutations, fetch-blob downloads).
**The OpenAPI "v1" document declares the machine posture by construction (#287).** An `ApiKey` security
scheme (`X-Api-Key`, `in: header`) is declared in `components.securitySchemes`, and
diff --git a/docs/decisions.md b/docs/decisions.md
index 1a595aee3..73d3fb834 100644
--- a/docs/decisions.md
+++ b/docs/decisions.md
@@ -80,6 +80,7 @@ keep append-only from accreting stale, contradictory, or unreadably-large histor
- [2026-07-12 — Formatting-as-you-touch, enforced; rebase-not-merge for PR branches (#311 H11 + format CI)](#2026-07-12--formatting-as-you-touch-enforced-rebase-not-merge-for-pr-branches-311-h11--format-ci)
- [2026-07-12 — Merge-consent gate auto-grants when satisfied (no redundant prompt); state IS the consent (#314)](#2026-07-12--merge-consent-gate-auto-grants-when-satisfied-no-redundant-prompt-state-is-the-consent-314)
- [2026-07-12 — Release path rehearses migrations on a prod-DB copy before promoting (#315)](#2026-07-12--release-path-rehearses-migrations-on-a-prod-db-copy-before-promoting-315)
+- [2026-07-12 — #295 PR2: SPA session cutover + #301 side-effecting-GET POST-ification](#2026-07-12--295-pr2-spa-session-cutover--301-side-effecting-get-post-ification)
---
@@ -1574,3 +1575,44 @@ afterwards. Always operates on a copy, never the live DB. Home: the script + doc
into the Komodo **pre-deploy** step (which already produces the backup) is a server-management concern.
Rationale: data-plane rigor — catch a bad migration on a disposable copy, not on live prod data.
See `docs/ci-cd.md` → Migration-on-prod-copy smoke. Cross-repo wiring tracked in server-management.
+---
+
+## 2026-07-12 — #295 PR2: SPA session cutover + #301 side-effecting-GET POST-ification
+
+PR1 shipped the server side (previous entry): `/api` accepts a session cookie OR the machine `X-Api-Key`, with
+`X-CSRF` required on session-authenticated mutations. **PR2 is the SPA cutover** — the browser now authenticates
+with the session only — plus **#301** (a session-cookie CSRF hole in side-effecting GETs).
+
+**Browser is cookie-only; the machine key is external/MCP-only.** `web/src/api/client.ts` no longer attaches
+`X-Api-Key`; it relies on the same-origin session cookie and sets `X-Csrf: '1'` on every mutating verb centrally.
+The former "paste your key" `ApiKeyScreen` is repurposed to **machine-key management**: it reads the server key
+from the new `GET /api/auth/machine-key` (session-gated; masked with Reveal + Copy) so an operator can hand it to
+MCP / external REST clients — the browser itself never sends it again. *Why:* one credential per audience (the
+ratified #295 model); leaving a browser key path alive would keep a CSRF-immune bypass around and defeat the
+point.
+
+**Boot gate, not a route** (`web/src/AuthGate.tsx`, wrapping `` in `main.tsx`): on load it calls the public
+`GET /api/auth/config` then `GET /api/auth/session` and renders Setup (first-run local-admin claim) / Login
+(local form + an OIDC "Sign in with SSO" button when `oidcEnabled`) / the app. Login and Setup mint **no URL** —
+the gate renders them at whatever `/app/*` path was requested, so a deep link survives login for free and **no
+`blazor-route-parity.md`/`domain-model.md` route rows are added**. It publishes `AuthContext`
+(`{ username, method, signOut, requireLogin }`); the 401 signal (`notifyUnauthorized`) now drives re-login via a
+passive shell banner (never yanks a dirty draft — it consults the navigation guard first). Auth flows that expect
+a 401 inline (login, change-password) pass `suppressUnauthorizedSignal`.
+
+**#301 — POST-ify, don't gate-the-GET.** A side-effecting GET is a CSRF vector once a `SameSite=Lax` cookie is a
+normal credential (it rides a cross-site top-level navigation). The three offenders became mutating verbs so the
+existing filter CSRF gate covers them with zero new machinery: `GET /api/troubleshoot/playback.m3u8` →
+**`POST /api/troubleshoot/playback/start`** returning `200 { url }` (the open `/iptv` manifest the player then
+loads — so hls.js/native-HLS needs no header injection, strictly better than X-CSRF-on-GET); the archive and
+sample GETs → **POST** (SPA downloads them via a fetch-blob helper, never `window.open`). Removing the HEAD
+variants also fixed a latent bug: a HEAD opened the `DeleteOnClose` stream and destroyed the artifact. Standing
+rule added to `api-conventions.md §9`: **never add a side-effecting GET/HEAD under `/api`.**
+
+**Machine-key GET discloses the key to any authenticated session** — deliberate: the session principal is the
+single admin (local or OIDC), same-origin policy blocks a cross-site page from reading the response body, and it
+is how the "copy the key for MCP" UX works without a rotation endpoint (rotation is a later PR). **Accepted
+residual (OIDC logout):** `POST /api/auth/logout` ends the *app* cookie but not the IdP session, so an OIDC user
+who clicks "Sign out" then "Sign in with SSO" returns without re-entering credentials — a `returnUrl`/RP-initiated
+logout is a future nicety. Docs: `spa-conventions.md §5e` (SPA seams), `api-conventions.md §9`, `e2e-local.md`
+(browser setup/login flow). Refs #295 #301 #197.
diff --git a/docs/e2e-local.md b/docs/e2e-local.md
index 64c1a6a4c..122c16f6f 100644
--- a/docs/e2e-local.md
+++ b/docs/e2e-local.md
@@ -76,9 +76,10 @@ skip rubric uses (kickoff workflow lore).
may 404/error. The UI and the entire `/api/*` surface are served on the **same port**, 8409 by
default (override with `ETV_UI_PORT`).
-5. **Seed data** as needed via the API — no API key is required for local mutating requests by
- default (`ApiKeyAuthorizationFilter` only enforces the `X-Api-Key` header when
- `Api:WriteKey` is configured; it's empty/unset in a fresh local config, so writes are open).
+5. **Seed data** as needed via the API. **The `/api` surface is fail-closed since #197** (writes always,
+ and reads because `Api:RequireKeyForReads` defaults true), so curl seeding must send the machine key the
+ server generates at startup: `-H "X-Api-Key: $(cat "$CONFIG_DIR/api.key")"`. (Mutations from a *session*
+ also need `-H 'X-CSRF: 1'`, but for scripted seeding the machine key is simpler and CSRF-immune.)
Examples:
- Create a channel: `POST /api/channels` — check the current
`ErsatzTV/wwwroot/openapi/v1.json` (or `CreateChannelRequest.cs`) for the exact required field
@@ -89,6 +90,13 @@ skip rubric uses (kickoff workflow lore).
`{"channelId": , "scheduleKind": "Block"}` (or `"Classic"`/`"Scripted"`/`"Sequential"` per
`ChannelPlayoutSource`/schedule-kind enums — check `v1.json` for the current set).
+5b. **Browser flow (since #295 session auth)**: the first `/app` load hits a **boot gate**. On a fresh
+ config it shows **Setup** — claim the local admin (pick any username/password); that issues the session
+ cookie and drops you into the app. On a subsequent run of the *same* config it shows **Login** instead.
+ (To skip the browser claim in automation, set `Auth:LocalAdmin:Password` before launch — the env seed
+ provisions the admin and disables the browser setup-claim.) The machine key still works for curl seeding
+ regardless. Driving this with Playwright: fill the Setup/Login form before asserting any authed screen.
+
6. **Tear down**: kill the `dotnet ErsatzTV.dll` process and confirm the port is freed
(`lsof -i :8409` should return nothing) before starting another run — a stray process holding
the port will make the next run's health check hang or fail confusingly.
diff --git a/docs/endpoint-index.md b/docs/endpoint-index.md
index 9d1d65709..c64754d74 100644
--- a/docs/endpoint-index.md
+++ b/docs/endpoint-index.md
@@ -2,7 +2,7 @@
*Generated by `scripts/generate-endpoint-index.py` from `ErsatzTV/wwwroot/openapi/v1.json`. Do not edit by hand -- regenerated by `scripts/update-openapi.sh`.*
-159 endpoints, 244 operations.
+160 endpoints, 242 operations.
## Artists
@@ -150,6 +150,7 @@
| Method | Path | Operation | Summary |
|---|---|---|---|
| GET | `/api/graphics-elements` | GetGraphicsElements | Get all graphics elements |
+| POST | `/api/graphics-elements/refresh` | RefreshGraphicsElements | Re-sync graphics elements from disk |
## Health
@@ -416,12 +417,9 @@
| Method | Path | Operation | Summary |
|---|---|---|---|
| GET | `/api/troubleshoot/info` | GetTroubleshootingInfo | Get troubleshooting diagnostic info |
-| GET | `/api/troubleshoot/playback.m3u8` | TroubleshootTroubleshootPlaybackGet | Start a troubleshooting playback session |
-| HEAD | `/api/troubleshoot/playback.m3u8` | TroubleshootTroubleshootPlaybackHead | Start a troubleshooting playback session |
-| GET | `/api/troubleshoot/playback/archive` | TroubleshootTroubleshootPlaybackArchiveGet | Download the last troubleshooting playback session archive |
-| HEAD | `/api/troubleshoot/playback/archive` | TroubleshootTroubleshootPlaybackArchiveHead | Download the last troubleshooting playback session archive |
-| GET | `/api/troubleshoot/playback/sample/{mediaItemId}` | TroubleshootTroubleshootPlaybackSampleGet | Download a media sample archive for troubleshooting |
-| HEAD | `/api/troubleshoot/playback/sample/{mediaItemId}` | TroubleshootTroubleshootPlaybackSampleHead | Download a media sample archive for troubleshooting |
+| POST | `/api/troubleshoot/playback/archive` | DownloadTroubleshootingArchive | Download the last troubleshooting playback session archive |
+| POST | `/api/troubleshoot/playback/sample/{mediaItemId}` | DownloadTroubleshootingMediaSample | Download a media sample archive for troubleshooting |
+| POST | `/api/troubleshoot/playback/start` | StartTroubleshootingPlayback | Start a troubleshooting playback session |
| GET | `/api/troubleshoot/playback/status` | GetTroubleshootingPlaybackStatus | Get the status of the current or last troubleshooting playback session |
| GET | `/api/troubleshoot/playback/stream-selectors` | GetTroubleshootingStreamSelectors | List available channel stream selectors |
| GET | `/api/troubleshoot/playback/subtitles/{mediaItemId}` | GetTroubleshootingSubtitles | List selectable subtitle streams for a media item |
diff --git a/docs/spa-conventions.md b/docs/spa-conventions.md
index 8c0789a93..dc8838ce9 100644
--- a/docs/spa-conventions.md
+++ b/docs/spa-conventions.md
@@ -207,28 +207,43 @@ session — if a preference needs to be shared across devices or is really serve
(e.g. Blazor's `ConfigElement`-backed settings), it belongs behind an API endpoint instead; see
`docs/decisions.md` 2026-07-11 for the specific reasoning on logs page-size.
-## 5e. API key: the one keyless screen + the global 401 signal (#197)
+## 5e. Session auth: the boot gate, the machine-key screen + the global 401 signal (#295)
-The whole `/api` surface is gated behind an `X-Api-Key` header (server-side #197): writes always
-require it and reads require it too (`Api:RequireKeyForReads` defaults true), so a missing/wrong key
-yields **401** on every call. Two SPA seams support this:
+Since #295 the browser authenticates with a **session cookie**, not an API key. The whole `/api`
+surface still answers a missing/expired session with **401**, and mutating verbs additionally require a
+CSRF header. The former keyless-bootstrap `ApiKeyScreen` (the `X-Api-Key`/`localStorage` model of #197)
+is gone. The SPA seams now are:
-- **The request client sends the key on every request** (`web/src/api/client.ts`): whenever
- `getStoredApiKey()` returns a value it's attached to `X-Api-Key`, regardless of method (there is no
- reads-vs-mutations split — that older guard was removed). The key lives in `localStorage`
- (`ctv-api-key`) via `web/src/api/auth.ts` (`get/set/clearStoredApiKey`), per §5d.
-- **The API Key screen is the one screen that must render with ZERO successful `/api` calls**
- (`web/src/screens/ApiKeyScreen.tsx`, route `/app/api-key`, System nav group). A keyless first load
- 401s every read, so this screen reads/writes **only** `localStorage` (the `auth.ts` helpers) and
- never fetches from `/api`. It shows a masked "key set / no key" state (never echoes the stored key
- in plaintext — a `type="password"` input), Save (`setStoredApiKey`) and Clear (`clearStoredApiKey`),
- and copy pointing at the server-generated `/config/api.key`. If you add a keyless bootstrap screen,
- keep it `localStorage`-only for the same reason.
+- **The request client sends no API key; it relies on the cookie and adds CSRF automatically**
+ (`web/src/api/client.ts`): the session cookie rides along with every same-origin request, and every
+ mutating verb (POST/PUT/PATCH/DELETE) gets an `X-Csrf` header set automatically — screens making a
+ POST get CSRF for free. There is **no** `getStoredApiKey`/`X-Api-Key` path anymore; the only residual
+ `localStorage` touch is `clearLegacyStoredApiKey()` (`web/src/api/auth.ts`), a one-shot cleanup the
+ boot gate runs once to purge any stale `ctv-api-key`.
+- **The boot gate owns login/setup** (`web/src/AuthGate.tsx`), wrapping `` outside the
+ shell/router. It asks the PUBLIC `/api/auth/config`, then `/api/auth/session`, and renders Setup /
+ Login / the app. It also publishes `AuthContext` (`{ username, method, signOut, requireLogin }`) —
+ read `method` via `useContext(AuthContext)` to branch on the auth kind (e.g. `'local'` vs OIDC).
+- **The machine-key screen is a normal authenticated screen** (`web/src/screens/ApiKeyScreen.tsx`,
+ route `/app/api-key`, System nav group). It loads the server machine key from `/api/auth/machine-key`
+ (via `getMachineKey()`) and displays it **masked** (a masked `` that never puts the key in the
+ DOM until Reveal) with Reveal + Copy affordances — the key is for MCP / external REST clients; the
+ browser no longer uses it. For **local** accounts only (`AuthContext.method === 'local'`) it also
+ renders a "Local admin password" card that calls `changePassword(current, new)`, mapping a wrong-
+ current-password **401** to the server ProblemDetails detail inline.
+- **File-download endpoints go through a fetch-blob helper, never a browser tab.** Endpoints that
+ return a binary body (the troubleshooting archive / media-sample POSTs) must **not** go through
+ `request()` (it JSON-parses) and must **not** be opened with `window.open` (a session-cookie GET in a
+ new tab can't carry the CSRF header and bypasses error handling). Instead `fetch(path, { method:
+ 'POST', headers: { 'X-Csrf': '1' } })`, then `response.blob()` → object URL → anchor-click →
+ revoke, reading the filename from `Content-Disposition`; a non-ok response throws an `ApiError`. See
+ `downloadTroubleshootingArchive` / `downloadTroubleshootingMediaSample` in `web/src/api/troubleshoot.ts`.
- **401 UX is one shell-level banner, not per-screen handling.** Rather than special-casing 401 in
every screen's error path, the request client emits a single app-wide signal on 401
(`auth.ts` `notifyUnauthorized` / `subscribeUnauthorized`), and `web/src/UnauthorizedBanner.tsx`
- (rendered once in the App shell) subscribes and points the user at `/app/api-key`. This is the DRY
- seam for "the server rejected us" — reuse it instead of adding bespoke 401 branches.
+ (rendered once in the App shell) subscribes and prompts re-login. This is the DRY seam for "the server
+ rejected us" — reuse it instead of adding bespoke 401 branches. Auth flows that expect a 401 as an
+ inline answer (login, change-password) pass `suppressUnauthorizedSignal` so they don't trip it.
## 6. Tests
diff --git a/scripts/update-openapi.sh b/scripts/update-openapi.sh
index dd9edbd42..3be869c49 100755
--- a/scripts/update-openapi.sh
+++ b/scripts/update-openapi.sh
@@ -5,7 +5,13 @@ REPO_ROOT="$(pwd)"
# Only regenerate the endpoint index if the spec build succeeded, so a failed
# build can't render docs/endpoint-index.md from a stale/partial v1.json.
-(cd ErsatzTV && dotnet build -t:GenerateOpenApiDocuments) || exit
+#
+# A full `dotnet build` MUST run before the doc-gen target: OpenApiGenerateDocumentsOnBuild
+# is false, so `-t:GenerateOpenApiDocuments` alone does NOT compile the project — it invokes
+# dotnet-getdocument against ErsatzTV.dll + ErsatzTV.deps.json, which don't exist in a clean
+# tree (e.g. the CI api-docs job, which only restores). Without the build the target fails with
+# "The specified deps.json … does not exist" (exit 129). Build first, then generate.
+(cd ErsatzTV && dotnet build && dotnet build -t:GenerateOpenApiDocuments) || exit
cd "$REPO_ROOT" || exit
python3 scripts/generate-endpoint-index.py
diff --git a/web/src/App.tsx b/web/src/App.tsx
index e3302c1d8..7190a5ced 100644
--- a/web/src/App.tsx
+++ b/web/src/App.tsx
@@ -84,6 +84,7 @@ import { SearchScreen } from './screens/SearchScreen';
import { SettingsScreen } from './screens/SettingsScreen';
import { ApiKeyScreen } from './screens/ApiKeyScreen';
import { UnauthorizedBanner } from './UnauthorizedBanner';
+import { UserMenu } from './UserMenu';
import { TraktListsScreen } from './screens/TraktListsScreen';
import { TrashScreen } from './screens/TrashScreen';
import { TroubleshootingScreen } from './screens/TroubleshootingScreen';
@@ -900,6 +901,7 @@ function TopBar({ route }: { route: ScreenRoute | null }) {