From 88d82266b6bf3bf85fb17e99b1d2c489755af7e0 Mon Sep 17 00:00:00 2001 From: Timothy Date: Sun, 12 Jul 2026 20:17:23 +0200 Subject: [PATCH 1/9] feat(api): #301 POST-ify side-effecting troubleshoot GETs + GET /api/auth/machine-key Co-Authored-By: Claude Opus 4.8 (1M context) --- ...bleshootingPlaybackStartedResponseModel.cs | 6 + .../Controllers/AuthControllerTests.cs | 52 +- .../OpenApiContractHonestyTests.cs | 29 +- .../TroubleshootControllerTests.cs | 166 ++++-- ErsatzTV/Controllers/Api/AuthController.cs | 28 +- .../StartTroubleshootingPlaybackRequest.cs | 15 + .../Controllers/Api/TroubleshootController.cs | 47 +- ErsatzTV/wwwroot/openapi/v1.json | 473 +++++------------- docs/endpoint-index.md | 11 +- web/src/api/generated/v1.d.ts | 15 + 10 files changed, 423 insertions(+), 419 deletions(-) create mode 100644 ErsatzTV.Core/Api/Troubleshooting/TroubleshootingPlaybackStartedResponseModel.cs create mode 100644 ErsatzTV/Controllers/Api/Requests/StartTroubleshootingPlaybackRequest.cs 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.Tests/Controllers/AuthControllerTests.cs b/ErsatzTV.Tests/Controllers/AuthControllerTests.cs index 84d34c320..ef9e85780 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,41 @@ 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"); + } } 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/TroubleshootControllerTests.cs b/ErsatzTV.Tests/Controllers/TroubleshootControllerTests.cs index 31d470256..705f356ef 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(); @@ -284,16 +327,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 +342,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/Controllers/Api/AuthController.cs b/ErsatzTV/Controllers/Api/AuthController.cs index cc633a61d..3ccfdb4ff 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,28 @@ 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." + }); + } + + 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 +256,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/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..ed3e0490f 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")] diff --git a/ErsatzTV/wwwroot/openapi/v1.json b/ErsatzTV/wwwroot/openapi/v1.json index f6abb3756..b43b250a8 100644 --- a/ErsatzTV/wwwroot/openapi/v1.json +++ b/ErsatzTV/wwwroot/openapi/v1.json @@ -21113,278 +21113,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 +21253,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 +21280,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", @@ -30188,6 +29898,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 +30213,17 @@ } } }, + "TroubleshootingPlaybackStartedResponseModel": { + "required": [ + "url" + ], + "type": "object", + "properties": { + "url": { + "type": "string" + } + } + }, "TroubleshootingPlaybackStatusResponseModel": { "required": [ "state", diff --git a/docs/endpoint-index.md b/docs/endpoint-index.md index 9d1d65709..93783a3bf 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. +159 endpoints, 241 operations. ## Artists @@ -416,12 +416,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/web/src/api/generated/v1.d.ts b/web/src/api/generated/v1.d.ts index 22f0e30ce..ad9f715d3 100644 --- a/web/src/api/generated/v1.d.ts +++ b/web/src/api/generated/v1.d.ts @@ -1434,6 +1434,18 @@ export interface components { "id": number; "name": string; "query": string; + }; + "StartTroubleshootingPlaybackRequest": { + "mediaItem": number; + "channel": number; + "ffmpegProfile": number; + "streamingMode": components["schemas"]["StreamingMode"]; + "watermark": null | Array; + "graphicsElement": null | Array; + "streamSelector": null | string; + "subtitleId": null | number; + "seekSeconds": number; + "start": null | string; }; "StartType": "Dynamic" | "Fixed"; "StreamingMode": "TransportStream" | "HttpLiveStreamingDirect" | "HttpLiveStreamingSegmenter" | "TransportStreamHybrid"; @@ -1485,6 +1497,9 @@ export interface components { "qsvCapabilities": null | string; "vaapiCapabilities": null | string; "videoToolboxCapabilities": null | string; + }; + "TroubleshootingPlaybackStartedResponseModel": { + "url": string; }; "TroubleshootingPlaybackStatusResponseModel": { "state": string; -- 2.47.3 From 9348a9938a192735692e3741b12ac760f6108758 Mon Sep 17 00:00:00 2001 From: Timothy Date: Sun, 12 Jul 2026 20:23:34 +0200 Subject: [PATCH 2/9] feat(web): #295 PR2 SPA session-auth foundation (boot gate, CSRF header, login/setup/logout) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replace the API-key SPA model with the session-cookie auth from PR1: - client.ts: stop sending X-Api-Key; attach X-Csrf on mutating verbs (POST/PUT/ PATCH/DELETE); add suppressUnauthorizedSignal to skip the global 401 signal on expected wrong-credentials 401s (login / change-password). - api/auth.ts: hand-written wire types (AuthConfig/AuthSession/MachineKey — the auth surface is IgnoreApi, deliberately not in generated types) + endpoint fns (getAuthConfig/getAuthSession/login/setup/logout/changePassword/getMachineKey); keep the notifyUnauthorized/subscribeUnauthorized 401 signal; add clearLegacyStoredApiKey. Legacy get/set/clearStoredApiKey retained ONLY so the still-shipping ApiKeyScreen (machine-key slice) compiles without a cross-slice conflict — the client no longer reads them. - AuthGate.tsx: boot gate wrapping outside the shell (mints no URL, deep links survive login). checking -> setup | login | ready | error, with a safe default AuthContext so App.test.tsx renders without a provider; config-fetch failure lands on an explicit error+Retry, never a blank screen. - LoginScreen / SetupScreen: shell-less centered cards; inline 401 / 409 handling; SSO button + local-form gating from AuthConfig. - UnauthorizedBanner: rewritten to prompt re-login (passive; consults the unsaved-changes guard before flipping the gate). - UserMenu: TopBar sign-out (guard -> logout -> signOut), mounted next to ConnectMenu. - main.tsx: wrap inside StrictMode. Tests: client/auth/AuthGate/LoginScreen/SetupScreen/UnauthorizedBanner/UserMenu (723 pass). Lint + build green. Co-Authored-By: Claude Opus 4.8 (1M context) --- web/src/App.tsx | 2 + web/src/AuthGate.test.tsx | 147 ++++++++++++++++++++++ web/src/AuthGate.tsx | 181 +++++++++++++++++++++++++++ web/src/UnauthorizedBanner.test.tsx | 53 ++++++-- web/src/UnauthorizedBanner.tsx | 35 +++--- web/src/UserMenu.test.tsx | 62 +++++++++ web/src/UserMenu.tsx | 95 ++++++++++++++ web/src/api/auth.test.ts | 147 ++++++++++++++++++---- web/src/api/auth.ts | 101 +++++++++++++-- web/src/api/client.test.ts | 93 +++++++------- web/src/api/client.ts | 31 +++-- web/src/main.tsx | 5 +- web/src/screens/LoginScreen.test.tsx | 84 +++++++++++++ web/src/screens/LoginScreen.tsx | 120 ++++++++++++++++++ web/src/screens/SetupScreen.test.tsx | 64 ++++++++++ web/src/screens/SetupScreen.tsx | 140 +++++++++++++++++++++ web/src/shell.css | 11 ++ 17 files changed, 1254 insertions(+), 117 deletions(-) create mode 100644 web/src/AuthGate.test.tsx create mode 100644 web/src/AuthGate.tsx create mode 100644 web/src/UserMenu.test.tsx create mode 100644 web/src/UserMenu.tsx create mode 100644 web/src/screens/LoginScreen.test.tsx create mode 100644 web/src/screens/LoginScreen.tsx create mode 100644 web/src/screens/SetupScreen.test.tsx create mode 100644 web/src/screens/SetupScreen.tsx 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 }) {
+ diff --git a/web/src/AuthGate.test.tsx b/web/src/AuthGate.test.tsx new file mode 100644 index 000000000..1173ffe73 --- /dev/null +++ b/web/src/AuthGate.test.tsx @@ -0,0 +1,147 @@ +import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { AuthGate } from './AuthGate'; +import type { AuthConfig, AuthSession } from './api'; + +const APP_MARKER = 'APP CONTENT'; + +function jsonResponse(body: unknown, status = 200): Response { + return new Response(JSON.stringify(body), { + headers: { 'Content-Type': 'application/json' }, + status + }); +} + +interface Scenario { + config: AuthConfig | { fail: true }; + session?: AuthSession; + login?: AuthSession; +} + +function mockFetch(scenario: Scenario) { + return vi.spyOn(window, 'fetch').mockImplementation((input, init) => { + const url = typeof input === 'string' ? input : (input as Request).url; + const method = (init?.method ?? 'GET').toUpperCase(); + + if (url.endsWith('/api/auth/config')) { + if ('fail' in scenario.config) { + return Promise.resolve(jsonResponse({ status: 500, title: 'Server error' }, 500)); + } + return Promise.resolve(jsonResponse(scenario.config)); + } + + if (url.endsWith('/api/auth/session')) { + return Promise.resolve(jsonResponse(scenario.session ?? { authenticated: false, username: null, method: null })); + } + + if (url.endsWith('/api/auth/login') && method === 'POST') { + return Promise.resolve(jsonResponse(scenario.login ?? { authenticated: true, username: 'admin', method: 'local' })); + } + + return Promise.resolve(new Response(null, { status: 404 })); + }); +} + +const localConfig: AuthConfig = { oidcEnabled: false, localLoginEnabled: true, setupRequired: false }; + +describe('AuthGate', () => { + beforeEach(() => { + window.localStorage.clear(); + vi.restoreAllMocks(); + }); + + afterEach(() => { + cleanup(); + }); + + it('renders the setup screen when setup is required', async () => { + mockFetch({ config: { oidcEnabled: false, localLoginEnabled: true, setupRequired: true } }); + + render( + +
{APP_MARKER}
+
+ ); + + expect(await screen.findByText('Create the first administrator account')).toBeTruthy(); + expect(screen.queryByText(APP_MARKER)).toBeNull(); + }); + + it('renders the login screen when unauthenticated, with the SSO button only when OIDC is enabled', async () => { + mockFetch({ config: { oidcEnabled: true, localLoginEnabled: true, setupRequired: false } }); + + render( + +
{APP_MARKER}
+
+ ); + + expect(await screen.findByRole('button', { name: /Sign in with SSO/ })).toBeTruthy(); + expect(screen.queryByText(APP_MARKER)).toBeNull(); + }); + + it('omits the SSO button when OIDC is disabled', async () => { + mockFetch({ config: localConfig }); + + render( + +
{APP_MARKER}
+
+ ); + + expect(await screen.findByRole('button', { name: 'Sign in' })).toBeTruthy(); + expect(screen.queryByRole('button', { name: /SSO/ })).toBeNull(); + }); + + it('renders children when already authenticated and clears the legacy API key', async () => { + window.localStorage.setItem('ctv-api-key', 'legacy-secret'); + mockFetch({ config: localConfig, session: { authenticated: true, username: 'admin', method: 'local' } }); + + render( + +
{APP_MARKER}
+
+ ); + + expect(await screen.findByText(APP_MARKER)).toBeTruthy(); + await waitFor(() => expect(window.localStorage.getItem('ctv-api-key')).toBeNull()); + }); + + it('transitions from login to the app after a successful sign-in', async () => { + mockFetch({ config: localConfig, login: { authenticated: true, username: 'admin', method: 'local' } }); + + render( + +
{APP_MARKER}
+
+ ); + + const button = await screen.findByRole('button', { name: 'Sign in' }); + + fireEvent.change(screen.getByPlaceholderText('Username'), { target: { value: 'admin' } }); + fireEvent.change(screen.getByPlaceholderText('Password'), { target: { value: 'hunter2' } }); + fireEvent.click(button); + + expect(await screen.findByText(APP_MARKER)).toBeTruthy(); + }); + + it('shows an error state with Retry when the config fetch fails, then recovers', async () => { + const scenario: Scenario = { config: { fail: true } }; + mockFetch(scenario); + + render( + +
{APP_MARKER}
+
+ ); + + expect(await screen.findByRole('alert')).toBeTruthy(); + const retry = screen.getByRole('button', { name: 'Retry' }); + + // Config now succeeds — Retry should re-run the gate and land on the login screen. + scenario.config = localConfig; + fireEvent.click(retry); + + expect(await screen.findByRole('button', { name: 'Sign in' })).toBeTruthy(); + }); +}); diff --git a/web/src/AuthGate.tsx b/web/src/AuthGate.tsx new file mode 100644 index 000000000..fe481d943 --- /dev/null +++ b/web/src/AuthGate.tsx @@ -0,0 +1,181 @@ +import { createContext, useCallback, useEffect, useRef, useState, type ReactNode } from 'react'; +import { RefreshCw, TriangleAlert } from 'lucide-react'; +import { Button, Card, Spinner } from './components'; +import { + clearLegacyStoredApiKey, + getAuthConfig, + getAuthSession, + type AuthConfig, + type AuthSession +} from './api'; +import { LoginScreen } from './screens/LoginScreen'; +import { SetupScreen } from './screens/SetupScreen'; + +// The boot gate (#295). It wraps OUTSIDE the shell/router, so Login and Setup mint no URLs and a +// deep link survives an intervening sign-in. On mount it asks the PUBLIC `/api/auth/config`, then (unless +// setup is required) `/api/auth/session`, and renders Setup / Login / the app accordingly. A config-fetch +// failure lands on an explicit error state with Retry — a keyless, sessionless browser must ALWAYS be able +// to reach the login form, never a blank screen. + +export interface AuthContextValue { + username: string | null; + method: string | null; + /** Return to the login screen after the caller has POSTed `/api/auth/logout`. */ + signOut: () => void; + /** Flip the gate to the login screen (e.g. the 401 banner's "Sign in"). */ + requireLogin: () => void; +} + +// A safe default so consumers (App, UserMenu, UnauthorizedBanner) render without a provider — e.g. +// `App.test.tsx` renders directly. AuthGate publishes the real value only in the `ready` state. +// Colocated with the gate that owns it (per the #295 plan); the fast-refresh rule is disabled to allow +// this non-component export alongside AuthGate, matching LocalLibraryEditScreen's established pattern. +// eslint-disable-next-line react-refresh/only-export-components +export const AuthContext = createContext({ + username: null, + method: null, + signOut: () => {}, + requireLogin: () => {} +}); + +type GateState = + | { status: 'checking' } + | { status: 'error' } + | { status: 'setup'; config: AuthConfig } + | { status: 'login'; config: AuthConfig } + | { status: 'ready'; session: AuthSession }; + +export function AuthGate({ children }: { children: ReactNode }) { + const [state, setState] = useState({ status: 'checking' }); + const activeRef = useRef(true); + const seqRef = useRef(0); + const configRef = useRef(null); + const clearedRef = useRef(false); + + useEffect(() => { + // Mount/unmount tracker — guards against the StrictMode double-mount and a slow fetch resolving + // after unmount (spa-conventions §3). Re-arm on (re)mount so the second StrictMode pass is live. + activeRef.current = true; + return () => { + activeRef.current = false; + }; + }, []); + + // Runs the boot fetch, setting state ONLY in the async completions (never synchronously) so it's safe + // to invoke from the mount effect without tripping the react-hooks "no set-state-in-effect" rule (§3): + // the initial `checking` state is the useState default, so the effect path needs no synchronous reset. + const runGate = useCallback(() => { + const seq = ++seqRef.current; + + getAuthConfig() + .then((config) => { + if (!activeRef.current || seq !== seqRef.current) { + return undefined; + } + + configRef.current = config; + + if (config.setupRequired) { + setState({ status: 'setup', config }); + return undefined; + } + + return getAuthSession().then((session) => { + if (!activeRef.current || seq !== seqRef.current) { + return; + } + + if (session.authenticated) { + setState({ status: 'ready', session }); + } else { + setState({ status: 'login', config }); + } + }); + }) + .catch(() => { + if (!activeRef.current || seq !== seqRef.current) { + return; + } + setState({ status: 'error' }); + }); + }, []); + + useEffect(() => { + runGate(); + }, [runGate]); + + // Re-run the gate from an event handler (Retry / recovery), resetting to the checking state first. + const restart = useCallback(() => { + setState({ status: 'checking' }); + runGate(); + }, [runGate]); + + useEffect(() => { + // Reaching the app once means any pre-session `ctv-api-key` is now dead — clear it a single time. + if (state.status === 'ready' && !clearedRef.current) { + clearedRef.current = true; + clearLegacyStoredApiKey(); + } + }, [state.status]); + + const onAuthenticated = useCallback((session: AuthSession) => { + setState({ status: 'ready', session }); + }, []); + + const requireLogin = useCallback(() => { + const config = configRef.current; + if (config) { + setState({ status: 'login', config }); + } else { + // No config cached (shouldn't happen post-boot) — re-run the whole gate to recover safely. + restart(); + } + }, [restart]); + + if (state.status === 'checking') { + return ( +
+ +
+ ); + } + + if (state.status === 'error') { + return ( +
+ +
+
+
+ +
+
+
+ ); + } + + if (state.status === 'setup') { + return ; + } + + if (state.status === 'login') { + return ; + } + + return ( + + {children} + + ); +} diff --git a/web/src/UnauthorizedBanner.test.tsx b/web/src/UnauthorizedBanner.test.tsx index f707b1828..3b6d290a5 100644 --- a/web/src/UnauthorizedBanner.test.tsx +++ b/web/src/UnauthorizedBanner.test.tsx @@ -1,41 +1,68 @@ import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'; -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { afterEach, describe, expect, it, vi } from 'vitest'; import { notifyUnauthorized } from './api'; +import { AuthContext, type AuthContextValue } from './AuthGate'; +import { registerNavigationGuard } from './navigationGuard'; import { UnauthorizedBanner } from './UnauthorizedBanner'; -describe('UnauthorizedBanner', () => { - beforeEach(() => { - window.history.pushState(null, '', '/app'); - }); +function renderBanner(overrides: Partial = {}) { + const requireLogin = overrides.requireLogin ?? vi.fn(); + const value: AuthContextValue = { + username: null, + method: null, + signOut: vi.fn(), + requireLogin, + ...overrides + }; + render( + + + + ); + return { requireLogin }; +} +describe('UnauthorizedBanner', () => { afterEach(() => { cleanup(); }); it('stays hidden until a 401 signal fires', () => { - render(); + renderBanner(); expect(screen.queryByRole('alert')).toBeNull(); act(() => notifyUnauthorized()); expect(screen.getByRole('alert')).toBeTruthy(); - expect(screen.getByText(/requires an API key/)).toBeTruthy(); - expect(screen.getByText(/Settings → API Key/)).toBeTruthy(); + expect(screen.getByText(/session has expired or you are signed out/)).toBeTruthy(); }); - it('navigates to the API Key screen from the pointer link', () => { - render(); + it('flips the gate to login via requireLogin when navigation is allowed', () => { + const { requireLogin } = renderBanner(); act(() => notifyUnauthorized()); - fireEvent.click(screen.getByRole('button', { name: 'Open API Key' })); + fireEvent.click(screen.getByRole('button', { name: 'Sign in' })); - expect(window.location.pathname).toBe('/app/api-key'); + expect(requireLogin).toHaveBeenCalledTimes(1); expect(screen.queryByRole('alert')).toBeNull(); }); + it('respects the unsaved-changes guard — a vetoed leave keeps the banner and skips requireLogin', () => { + const { requireLogin } = renderBanner(); + const unregister = registerNavigationGuard(() => false); + act(() => notifyUnauthorized()); + + fireEvent.click(screen.getByRole('button', { name: 'Sign in' })); + + expect(requireLogin).not.toHaveBeenCalled(); + expect(screen.getByRole('alert')).toBeTruthy(); + + unregister(); + }); + it('can be dismissed', () => { - render(); + renderBanner(); act(() => notifyUnauthorized()); fireEvent.click(screen.getByRole('button', { name: 'Dismiss' })); diff --git a/web/src/UnauthorizedBanner.tsx b/web/src/UnauthorizedBanner.tsx index e5b3cba8b..bfeaaa5c9 100644 --- a/web/src/UnauthorizedBanner.tsx +++ b/web/src/UnauthorizedBanner.tsx @@ -1,15 +1,19 @@ -import { useEffect, useState } from 'react'; -import { KeyRound, X } from 'lucide-react'; +import { useContext, useEffect, useState } from 'react'; +import { LogIn, X } from 'lucide-react'; import { subscribeUnauthorized } from './api'; -import { navigateToPath } from './routing'; +import { AuthContext } from './AuthGate'; +import { canLeaveCurrentScreen } from './navigationGuard'; -const API_KEY_PATH = '/app/api-key'; - -// Shell-level pointer shown when any `/api` request returns 401 (#197). Rather than teach every -// screen's error path to special-case 401, the request client emits one app-wide signal (auth.ts) +// Shell-level pointer shown when any `/api` request returns 401 (#295 session-auth). Rather than teach +// every screen's error path to special-case 401, the request client emits one app-wide signal (auth.ts) // and this single banner subscribes — DRY, and it renders regardless of which screen triggered it. +// +// It stays PASSIVE: a background 401 must not yank the user mid-edit, so it only surfaces the banner. The +// "Sign in" affordance consults the unsaved-changes guard before flipping the gate to the login screen, so +// a dirty draft isn't silently discarded. export function UnauthorizedBanner() { const [visible, setVisible] = useState(false); + const { requireLogin } = useContext(AuthContext); useEffect(() => subscribeUnauthorized(() => setVisible(true)), []); @@ -17,19 +21,20 @@ export function UnauthorizedBanner() { return null; } - const goToApiKey = () => { + const signIn = () => { + if (!canLeaveCurrentScreen()) { + return; + } setVisible(false); - navigateToPath(API_KEY_PATH); + requireLogin(); }; return (
-
+ + )} +
+ ); +} diff --git a/web/src/api/auth.test.ts b/web/src/api/auth.test.ts index f6c9d4eb0..b3a575a4c 100644 --- a/web/src/api/auth.test.ts +++ b/web/src/api/auth.test.ts @@ -1,46 +1,141 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; -import { clearStoredApiKey, getStoredApiKey, notifyUnauthorized, setStoredApiKey, subscribeUnauthorized } from './auth'; +import { + changePassword, + clearLegacyStoredApiKey, + getAuthConfig, + getAuthSession, + getMachineKey, + login, + logout, + notifyUnauthorized, + setup, + subscribeUnauthorized +} from './auth'; -describe('API key storage', () => { +function jsonResponse(body: unknown, status = 200): Response { + return new Response(JSON.stringify(body), { + headers: { 'Content-Type': 'application/json' }, + status + }); +} + +describe('legacy API-key cleanup', () => { beforeEach(() => { window.localStorage.clear(); }); - it('stores and reads the API key from local storage', () => { - setStoredApiKey('write-secret'); + it('removes a leftover ctv-api-key entry', () => { + window.localStorage.setItem('ctv-api-key', 'legacy-secret'); - expect(getStoredApiKey()).toBe('write-secret'); - expect(window.localStorage.getItem('ctv-api-key')).toBe('write-secret'); - }); + clearLegacyStoredApiKey(); - it('trims blank API keys and clears storage', () => { - setStoredApiKey(' '); - - expect(getStoredApiKey()).toBeNull(); expect(window.localStorage.getItem('ctv-api-key')).toBeNull(); }); - it('clears a stored API key', () => { - setStoredApiKey('write-secret'); + it('is a no-op when localStorage is unavailable', () => { + const localStorageGetter = vi.spyOn(window, 'localStorage', 'get').mockImplementation(() => { + throw new Error('localStorage unavailable'); + }); - clearStoredApiKey(); - - expect(getStoredApiKey()).toBeNull(); - }); - - it('ignores unavailable local storage when reading the API key', () => { - const localStorageGetter = vi - .spyOn(window, 'localStorage', 'get') - .mockImplementation(() => { - throw new Error('localStorage unavailable'); - }); - - expect(getStoredApiKey()).toBeNull(); + expect(() => clearLegacyStoredApiKey()).not.toThrow(); localStorageGetter.mockRestore(); }); }); +describe('auth endpoints', () => { + beforeEach(() => { + vi.restoreAllMocks(); + }); + + it('GET /api/auth/config', async () => { + const fetchMock = vi + .spyOn(window, 'fetch') + .mockResolvedValue(jsonResponse({ oidcEnabled: true, localLoginEnabled: true, setupRequired: false })); + + const config = await getAuthConfig(); + + expect(config).toEqual({ oidcEnabled: true, localLoginEnabled: true, setupRequired: false }); + expect(fetchMock).toHaveBeenCalledWith('/api/auth/config', expect.objectContaining({ method: 'GET' })); + }); + + it('GET /api/auth/session', async () => { + const fetchMock = vi + .spyOn(window, 'fetch') + .mockResolvedValue(jsonResponse({ authenticated: true, username: 'admin', method: 'local' })); + + const session = await getAuthSession(); + + expect(session).toEqual({ authenticated: true, username: 'admin', method: 'local' }); + expect(fetchMock).toHaveBeenCalledWith('/api/auth/session', expect.objectContaining({ method: 'GET' })); + }); + + it('POST /api/auth/login with credentials in the body', async () => { + const fetchMock = vi + .spyOn(window, 'fetch') + .mockResolvedValue(jsonResponse({ authenticated: true, username: 'admin', method: 'local' })); + + await login('admin', 'hunter2'); + + expect(fetchMock).toHaveBeenCalledWith( + '/api/auth/login', + expect.objectContaining({ body: JSON.stringify({ username: 'admin', password: 'hunter2' }), method: 'POST' }) + ); + }); + + it('login does not trip the global 401 banner on a wrong-password 401', async () => { + vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse({ status: 401, title: 'Unauthorized' }, 401)); + const onUnauthorized = vi.fn(); + const unsubscribe = subscribeUnauthorized(onUnauthorized); + + await expect(login('admin', 'wrong')).rejects.toMatchObject({ status: 401 }); + + expect(onUnauthorized).not.toHaveBeenCalled(); + unsubscribe(); + }); + + it('POST /api/auth/setup with credentials in the body', async () => { + const fetchMock = vi + .spyOn(window, 'fetch') + .mockResolvedValue(jsonResponse({ authenticated: true, username: 'admin', method: 'local' })); + + await setup('admin', 'hunter2'); + + expect(fetchMock).toHaveBeenCalledWith( + '/api/auth/setup', + expect.objectContaining({ body: JSON.stringify({ username: 'admin', password: 'hunter2' }), method: 'POST' }) + ); + }); + + it('POST /api/auth/logout', async () => { + const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(new Response(null, { status: 204 })); + + await logout(); + + expect(fetchMock).toHaveBeenCalledWith('/api/auth/logout', expect.objectContaining({ method: 'POST' })); + }); + + it('POST /api/auth/password with both passwords, suppressing the 401 banner', async () => { + const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(new Response(null, { status: 204 })); + + await changePassword('old', 'new'); + + expect(fetchMock).toHaveBeenCalledWith( + '/api/auth/password', + expect.objectContaining({ body: JSON.stringify({ currentPassword: 'old', newPassword: 'new' }), method: 'POST' }) + ); + }); + + it('GET /api/auth/machine-key', async () => { + const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse({ key: 'abc123' })); + + const result = await getMachineKey(); + + expect(result).toEqual({ key: 'abc123' }); + expect(fetchMock).toHaveBeenCalledWith('/api/auth/machine-key', expect.objectContaining({ method: 'GET' })); + }); +}); + describe('unauthorized signal', () => { it('notifies subscribers and stops after unsubscribe', () => { const listener = vi.fn(); diff --git a/web/src/api/auth.ts b/web/src/api/auth.ts index e028af88c..11ead6458 100644 --- a/web/src/api/auth.ts +++ b/web/src/api/auth.ts @@ -1,4 +1,32 @@ -const apiKeyStorageKey = 'ctv-api-key'; +import { request } from './client'; + +// --- wire types ------------------------------------------------------------- +// The auth surface (`/api/auth/*`) is deliberately excluded from the OpenAPI document (server-side +// [IgnoreApi]), so — unlike every other domain module (spa-conventions §4) — these DTOs are NOT in the +// generated types and are hand-written here. Keep the field names camelCase to match the server records +// exactly (the JSON the auth endpoints emit). This deviation is intentional; do not try to source these +// from `./generated/v1`. + +/** `GET /api/auth/config` — PUBLIC; drives the boot gate. */ +export interface AuthConfig { + oidcEnabled: boolean; + localLoginEnabled: boolean; + setupRequired: boolean; +} + +/** `GET /api/auth/session` — anonymous callers get 200 with `authenticated: false` (never 401). */ +export interface AuthSession { + authenticated: boolean; + username: string | null; + method: string | null; +} + +/** `GET /api/auth/machine-key` — the server-generated machine API key (consumed by another slice). */ +export interface MachineKey { + key: string; +} + +const legacyApiKeyStorageKey = 'ctv-api-key'; function getStorage(): Storage | undefined { if (typeof window === 'undefined') { @@ -12,8 +40,21 @@ function getStorage(): Storage | undefined { } } +// The SPA no longer stores or sends an API key — it authenticates with the session cookie (#295). This +// one-shot cleanup removes any legacy `ctv-api-key` left over from the pre-session model; AuthGate calls +// it once on reaching `ready`. +export function clearLegacyStoredApiKey(): void { + getStorage()?.removeItem(legacyApiKeyStorageKey); +} + +// --- legacy API-key storage (DEPRECATED, #295) ------------------------------ +// The session-auth plan (PR #295 slice B) deletes these — the client no longer sends the key and the +// key is no longer stored by the SPA. They are retained here ONLY so the still-shipping +// `screens/ApiKeyScreen.tsx` (migrated by the separate machine-key slice) keeps compiling without a +// cross-slice merge conflict; nothing else reads them and `client.ts` no longer attaches the key. +// Remove these with the ApiKeyScreen slice. export function getStoredApiKey(): string | null { - const value = getStorage()?.getItem(apiKeyStorageKey); + const value = getStorage()?.getItem(legacyApiKeyStorageKey); return value && value.trim().length > 0 ? value : null; } @@ -25,19 +66,18 @@ export function setStoredApiKey(apiKey: string): void { return; } - getStorage()?.setItem(apiKeyStorageKey, trimmed); + getStorage()?.setItem(legacyApiKeyStorageKey, trimmed); } export function clearStoredApiKey(): void { - getStorage()?.removeItem(apiKeyStorageKey); + getStorage()?.removeItem(legacyApiKeyStorageKey); } // --- 401 signal ------------------------------------------------------------- -// The whole `/api` surface is gated behind the API key (#197). Rather than teach -// every screen's error path to special-case 401, the request client emits a single -// app-wide signal when any request comes back Unauthorized; a shell-level banner -// subscribes and points the user at the API Key screen. Kept here (next to the key -// storage it concerns) so it never depends on a successful `/api` call. +// The whole `/api` surface is gated behind an authenticated session cookie (#295). Rather than teach +// every screen's error path to special-case 401, the request client emits a single app-wide signal when +// any request comes back Unauthorized; a shell-level banner subscribes and prompts the user to sign in. +// Kept here (in the auth domain module) so it never depends on a successful `/api` call. type UnauthorizedListener = () => void; const unauthorizedListeners = new Set(); @@ -54,3 +94,46 @@ export function notifyUnauthorized(): void { listener(); } } + +// --- auth endpoints --------------------------------------------------------- + +export function getAuthConfig(): Promise { + return request('/api/auth/config'); +} + +export function getAuthSession(): Promise { + return request('/api/auth/session'); +} + +export function login(username: string, password: string): Promise { + // A wrong-password 401 is an expected inline answer here — it must NOT trip the global 401 banner. + return request('/api/auth/login', { + body: { username, password }, + method: 'POST', + suppressUnauthorizedSignal: true + }); +} + +export function setup(username: string, password: string): Promise { + return request('/api/auth/setup', { + body: { username, password }, + method: 'POST' + }); +} + +export function logout(): Promise { + return request('/api/auth/logout', { method: 'POST' }); +} + +export function changePassword(currentPassword: string, newPassword: string): Promise { + // A wrong current-password 401 is shown inline, not via the global banner. + return request('/api/auth/password', { + body: { currentPassword, newPassword }, + method: 'POST', + suppressUnauthorizedSignal: true + }); +} + +export function getMachineKey(): Promise { + return request('/api/auth/machine-key'); +} diff --git a/web/src/api/client.test.ts b/web/src/api/client.test.ts index 06aa893fc..0863d5d57 100644 --- a/web/src/api/client.test.ts +++ b/web/src/api/client.test.ts @@ -1,33 +1,37 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; -import { setStoredApiKey, subscribeUnauthorized } from './auth'; +import { subscribeUnauthorized } from './auth'; import { ApiError, request, requestWithMeta } from './client'; +// Reads the X-Csrf header off the object handed to fetch (the client sets it post-normalization). +function csrfHeaderFrom(fetchMock: ReturnType): unknown { + const init = fetchMock.mock.calls[0]?.[1] as RequestInit | undefined; + return (init?.headers as Record | undefined)?.['X-Csrf']; +} + describe('API request client', () => { beforeEach(() => { window.localStorage.clear(); vi.restoreAllMocks(); }); - it('adds the API key header for read requests when a key is stored', async () => { - const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue( - new Response(JSON.stringify([{ id: 1, number: '1', name: 'News' }]), { - headers: { 'Content-Type': 'application/json' }, - status: 200 - }) - ); - setStoredApiKey('read-secret'); + it.each(['POST', 'PUT', 'PATCH', 'DELETE'] as const)( + 'attaches the X-CSRF header on %s (session-auth mutation, #295)', + async (method) => { + const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(new Response(null, { status: 204 })); - await request('/api/channels'); + await request('/api/channels/1', { method }); - expect(fetchMock).toHaveBeenCalledWith( - '/api/channels', - expect.objectContaining({ - headers: expect.objectContaining({ 'X-Api-Key': 'read-secret' }) - }) - ); - }); + expect(fetchMock).toHaveBeenCalledWith( + '/api/channels/1', + expect.objectContaining({ + headers: expect.objectContaining({ 'X-Csrf': '1' }), + method + }) + ); + } + ); - it('sends no API key header when none is stored', async () => { + it('does not attach the X-CSRF header on a GET', async () => { const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue( new Response(JSON.stringify([]), { headers: { 'Content-Type': 'application/json' }, @@ -40,24 +44,23 @@ describe('API request client', () => { expect(fetchMock).toHaveBeenCalledWith( '/api/channels', expect.objectContaining({ - headers: expect.not.objectContaining({ 'X-Api-Key': expect.anything() }) + headers: expect.not.objectContaining({ 'X-Csrf': expect.anything() }) }) ); + expect(csrfHeaderFrom(fetchMock)).toBeUndefined(); }); - it('adds the API key header for mutating requests', async () => { + it('never sends an X-Api-Key header, even with a legacy ctv-api-key in localStorage', async () => { const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(new Response(null, { status: 204 })); - setStoredApiKey('write-secret'); + window.localStorage.setItem('ctv-api-key', 'legacy-secret'); + await request('/api/channels'); await request('/api/channels/1', { method: 'DELETE' }); - expect(fetchMock).toHaveBeenCalledWith( - '/api/channels/1', - expect.objectContaining({ - headers: expect.objectContaining({ 'X-Api-Key': 'write-secret' }), - method: 'DELETE' - }) - ); + for (const call of fetchMock.mock.calls) { + const headers = (call[1] as RequestInit | undefined)?.headers as Record | undefined; + expect(headers).not.toHaveProperty('X-Api-Key'); + } }); it('throws an ApiError with problem details for non-OK responses', async () => { @@ -98,6 +101,25 @@ describe('API request client', () => { unsubscribe(); }); + it('does NOT signal unauthorized subscribers on a 401 when suppressUnauthorizedSignal is set', async () => { + vi.spyOn(window, 'fetch').mockResolvedValue( + new Response(JSON.stringify({ status: 401, title: 'Unauthorized' }), { + headers: { 'Content-Type': 'application/problem+json' }, + status: 401 + }) + ); + + const onUnauthorized = vi.fn(); + const unsubscribe = subscribeUnauthorized(onUnauthorized); + + await expect( + request('/api/auth/login', { body: { username: 'x', password: 'y' }, method: 'POST', suppressUnauthorizedSignal: true }) + ).rejects.toMatchObject({ status: 401 }); + + expect(onUnauthorized).not.toHaveBeenCalled(); + unsubscribe(); + }); + it('does not signal unauthorized subscribers on other error statuses', async () => { vi.spyOn(window, 'fetch').mockResolvedValue( new Response(JSON.stringify({ status: 403, title: 'Forbidden' }), { @@ -115,21 +137,6 @@ describe('API request client', () => { unsubscribe(); }); - it('reads problem details from application/problem+json responses', async () => { - vi.spyOn(window, 'fetch').mockResolvedValue( - new Response(JSON.stringify({ status: 401, title: 'Unauthorized', detail: 'A valid API key is required for write requests.' }), { - headers: { 'Content-Type': 'application/problem+json' }, - status: 401 - }) - ); - - await expect(request('/api/channels', { method: 'POST' })).rejects.toMatchObject({ - detail: 'A valid API key is required for write requests.', - message: 'Unauthorized', - status: 401 - } satisfies Partial); - }); - it('does not add a duplicate JSON content type when callers provide lowercase content-type', async () => { const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(new Response(null, { status: 204 })); diff --git a/web/src/api/client.ts b/web/src/api/client.ts index f68e69856..3723699c4 100644 --- a/web/src/api/client.ts +++ b/web/src/api/client.ts @@ -1,9 +1,11 @@ -import { getStoredApiKey, notifyUnauthorized } from './auth'; +import { notifyUnauthorized } from './auth'; import type { components } from './generated/v1'; type ProblemDetails = components['schemas']['ProblemDetails']; type RequestBody = BodyInit | Record | null; +const MUTATING_METHODS = ['POST', 'PUT', 'PATCH', 'DELETE']; + export class ApiError extends Error { readonly detail?: string | null; readonly problem?: ProblemDetails; @@ -20,6 +22,12 @@ export class ApiError extends Error { export interface ApiRequestOptions extends Omit { body?: RequestBody; + /** + * When set, a 401 on this request does NOT fire the app-wide unauthorized signal (#295). Used by the + * auth flows (login / change-password) where a 401 is an expected wrong-credentials answer that must + * be shown inline, not surfaced as the global "your session expired" banner. + */ + suppressUnauthorizedSignal?: boolean; } export interface ResponseWithMeta { @@ -37,6 +45,7 @@ export async function requestWithMeta( path: string, options: ApiRequestOptions = {} ): Promise> { + const { suppressUnauthorizedSignal, ...fetchOptions } = options; const method = (options.method ?? 'GET').toUpperCase(); const headers = normalizeHeaders({ Accept: 'application/json', @@ -44,25 +53,27 @@ export async function requestWithMeta( }); const body = serializeBody(options.body, headers); - const apiKey = getStoredApiKey(); - // #197/#282: the whole `/api` surface is gated (reads too, since `Api:RequireKeyForReads` - // defaults true), so send the key on every request whenever one is stored — not only mutations. - if (apiKey) { - headers['X-Api-Key'] = apiKey; + // #295: session-authenticated mutations must carry a CSRF header or the server answers 403. Set it + // post-normalization (as the API key was), so it survives header canonicalization. The server lookup + // is case-insensitive, so `X-Csrf` matches its `X-CSRF`. Machine-key (`X-Api-Key`) callers are exempt + // server-side, but sending the header on every mutation is harmless — the SPA is always session-auth. + if (MUTATING_METHODS.includes(method)) { + headers['X-Csrf'] ??= '1'; } const response = await fetch(path, { - ...options, + ...fetchOptions, body, headers, method }); if (!response.ok) { - // A gated `/api` surface answers a missing/wrong key with 401 (#197). Signal the shell so it can - // point the user at the API Key screen, regardless of which screen made the call. - if (response.status === 401) { + // A session-gated `/api` surface answers a missing/expired session with 401 (#295). Signal the + // shell so it can prompt re-login, regardless of which screen made the call — unless the caller + // opted out (an expected wrong-credentials 401 on login/change-password). + if (response.status === 401 && !suppressUnauthorizedSignal) { notifyUnauthorized(); } diff --git a/web/src/main.tsx b/web/src/main.tsx index b241e5092..9f2da3c6f 100644 --- a/web/src/main.tsx +++ b/web/src/main.tsx @@ -1,11 +1,14 @@ import { StrictMode } from 'react'; import { createRoot } from 'react-dom/client'; import { App } from './App'; +import { AuthGate } from './AuthGate'; import './designSystem'; import './shell.css'; createRoot(document.getElementById('root')!).render( - + + + ); diff --git a/web/src/screens/LoginScreen.test.tsx b/web/src/screens/LoginScreen.test.tsx new file mode 100644 index 000000000..70419b911 --- /dev/null +++ b/web/src/screens/LoginScreen.test.tsx @@ -0,0 +1,84 @@ +import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { LoginScreen } from './LoginScreen'; +import type { AuthConfig } from '../api'; + +function jsonResponse(body: unknown, status = 200): Response { + return new Response(JSON.stringify(body), { + headers: { 'Content-Type': 'application/json' }, + status + }); +} + +const localConfig: AuthConfig = { oidcEnabled: false, localLoginEnabled: true, setupRequired: false }; + +describe('LoginScreen', () => { + beforeEach(() => { + vi.restoreAllMocks(); + }); + + afterEach(() => { + cleanup(); + }); + + it('signs in and calls onAuthenticated with the session', async () => { + const session = { authenticated: true, username: 'admin', method: 'local' }; + vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse(session)); + const onAuthenticated = vi.fn(); + + render(); + + fireEvent.change(screen.getByPlaceholderText('Username'), { target: { value: 'admin' } }); + fireEvent.change(screen.getByPlaceholderText('Password'), { target: { value: 'hunter2' } }); + fireEvent.click(screen.getByRole('button', { name: 'Sign in' })); + + await waitFor(() => expect(onAuthenticated).toHaveBeenCalledWith(session)); + }); + + it('shows an inline error on a 401 without calling onAuthenticated', async () => { + vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse({ status: 401, title: 'Unauthorized' }, 401)); + const onAuthenticated = vi.fn(); + + render(); + + fireEvent.change(screen.getByPlaceholderText('Username'), { target: { value: 'admin' } }); + fireEvent.change(screen.getByPlaceholderText('Password'), { target: { value: 'wrong' } }); + fireEvent.click(screen.getByRole('button', { name: 'Sign in' })); + + expect(await screen.findByText('Invalid username or password.')).toBeTruthy(); + expect(onAuthenticated).not.toHaveBeenCalled(); + }); + + it('renders the SSO button and navigates to the OIDC endpoint', () => { + const originalLocation = window.location; + // jsdom: replace location with a settable href sink. + Object.defineProperty(window, 'location', { + configurable: true, + value: { ...originalLocation, href: '' } + }); + + render( + + ); + + fireEvent.click(screen.getByRole('button', { name: /Sign in with SSO/ })); + expect(window.location.href).toBe('/auth/oidc/login'); + + Object.defineProperty(window, 'location', { configurable: true, value: originalLocation }); + }); + + it('hides the local form when local login is disabled', () => { + render( + + ); + + expect(screen.queryByPlaceholderText('Username')).toBeNull(); + expect(screen.getByRole('button', { name: /Sign in with SSO/ })).toBeTruthy(); + }); +}); diff --git a/web/src/screens/LoginScreen.tsx b/web/src/screens/LoginScreen.tsx new file mode 100644 index 000000000..387d84926 --- /dev/null +++ b/web/src/screens/LoginScreen.tsx @@ -0,0 +1,120 @@ +import { useState, type FormEvent } from 'react'; +import { KeyRound, LogIn, ShieldCheck, User } from 'lucide-react'; +import { Button, Card, Input } from '../components'; +import { ApiError, login, type AuthConfig, type AuthSession } from '../api'; + +// Shell-less centered sign-in card (#295). Rendered by AuthGate OUTSIDE the app shell — it mints no URL, +// so a deep link is preserved across the sign-in. Local username/password form shows only when the server +// enables local login; SSO button shows when OIDC is enabled (a top-level browser redirect, not an `/api` +// call). A wrong-credentials 401 is shown inline (login() suppresses the global 401 banner). +export interface LoginScreenProps { + config: AuthConfig; + onAuthenticated: (session: AuthSession) => void; +} + +export function LoginScreen({ config, onAuthenticated }: LoginScreenProps) { + const [username, setUsername] = useState(''); + const [password, setPassword] = useState(''); + const [error, setError] = useState(null); + const [submitting, setSubmitting] = useState(false); + + const canSubmit = username.trim().length > 0 && password.length > 0 && !submitting; + + const onSubmit = (event: FormEvent) => { + event.preventDefault(); + + if (!canSubmit) { + return; + } + + setSubmitting(true); + setError(null); + + login(username.trim(), password) + .then((session) => { + onAuthenticated(session); + }) + .catch((caught: unknown) => { + if (caught instanceof ApiError && caught.status === 401) { + setError('Invalid username or password.'); + } else { + setError('Sign-in failed. Please try again.'); + } + setSubmitting(false); + }); + }; + + return ( +
+ + {config.localLoginEnabled && ( +
+
+ } + onChange={(event) => { + setUsername(event.target.value); + setError(null); + }} + placeholder="Username" + value={username} + /> + } + onChange={(event) => { + setPassword(event.target.value); + setError(null); + }} + placeholder="Password" + type="password" + value={password} + /> +
+ + {error && ( +
+ {error} +
+ )} + +
+ +
+
+ )} + + {config.oidcEnabled && ( +
+ +
+ )} + + {!config.localLoginEnabled && !config.oidcEnabled && ( +
+ No sign-in method is enabled on this server. Check the server configuration. +
+ )} +
+
+ ); +} diff --git a/web/src/screens/SetupScreen.test.tsx b/web/src/screens/SetupScreen.test.tsx new file mode 100644 index 000000000..ec8f21dac --- /dev/null +++ b/web/src/screens/SetupScreen.test.tsx @@ -0,0 +1,64 @@ +import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { SetupScreen } from './SetupScreen'; + +function jsonResponse(body: unknown, status = 200): Response { + return new Response(JSON.stringify(body), { + headers: { 'Content-Type': 'application/json' }, + status + }); +} + +describe('SetupScreen', () => { + beforeEach(() => { + vi.restoreAllMocks(); + }); + + afterEach(() => { + cleanup(); + }); + + it('creates the first account and calls onAuthenticated', async () => { + const session = { authenticated: true, username: 'admin', method: 'local' }; + const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse(session)); + const onAuthenticated = vi.fn(); + + render(); + + fireEvent.change(screen.getByPlaceholderText('Choose a username'), { target: { value: 'admin' } }); + fireEvent.change(screen.getByPlaceholderText('Choose a password'), { target: { value: 'hunter2' } }); + fireEvent.change(screen.getByPlaceholderText('Re-enter the password'), { target: { value: 'hunter2' } }); + fireEvent.click(screen.getByRole('button', { name: 'Create account' })); + + await waitFor(() => expect(onAuthenticated).toHaveBeenCalledWith(session)); + expect(fetchMock).toHaveBeenCalledWith('/api/auth/setup', expect.objectContaining({ method: 'POST' })); + }); + + it('blocks submit and warns when the passwords do not match', () => { + const fetchMock = vi.spyOn(window, 'fetch'); + render(); + + fireEvent.change(screen.getByPlaceholderText('Choose a username'), { target: { value: 'admin' } }); + fireEvent.change(screen.getByPlaceholderText('Choose a password'), { target: { value: 'hunter2' } }); + fireEvent.change(screen.getByPlaceholderText('Re-enter the password'), { target: { value: 'nope' } }); + + expect(screen.getAllByText('Passwords do not match.').length).toBeGreaterThan(0); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it('shows the already-configured message on a 409', async () => { + vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse({ status: 409, title: 'Conflict' }, 409)); + const onAuthenticated = vi.fn(); + + render(); + + fireEvent.change(screen.getByPlaceholderText('Choose a username'), { target: { value: 'admin' } }); + fireEvent.change(screen.getByPlaceholderText('Choose a password'), { target: { value: 'hunter2' } }); + fireEvent.change(screen.getByPlaceholderText('Re-enter the password'), { target: { value: 'hunter2' } }); + fireEvent.click(screen.getByRole('button', { name: 'Create account' })); + + expect(await screen.findByText(/already been set up/)).toBeTruthy(); + expect(screen.getByRole('button', { name: 'Reload' })).toBeTruthy(); + expect(onAuthenticated).not.toHaveBeenCalled(); + }); +}); diff --git a/web/src/screens/SetupScreen.tsx b/web/src/screens/SetupScreen.tsx new file mode 100644 index 000000000..9a6b38f04 --- /dev/null +++ b/web/src/screens/SetupScreen.tsx @@ -0,0 +1,140 @@ +import { useState, type FormEvent } from 'react'; +import { KeyRound, RotateCcw, User, UserPlus } from 'lucide-react'; +import { Button, Card, Input } from '../components'; +import { ApiError, setup, type AuthSession } from '../api'; + +// First-run setup card (#295). AuthGate renders this (shell-less, mints no URL) when +// `/api/auth/config.setupRequired` is true — the very first admin account. On success the server returns a +// session and we hand off to the app. A 409 means someone else already configured the server between the +// config read and the submit — offer a reload to pick up the now-required login. +export interface SetupScreenProps { + onAuthenticated: (session: AuthSession) => void; +} + +export function SetupScreen({ onAuthenticated }: SetupScreenProps) { + const [username, setUsername] = useState(''); + const [password, setPassword] = useState(''); + const [confirm, setConfirm] = useState(''); + const [error, setError] = useState(null); + const [alreadyConfigured, setAlreadyConfigured] = useState(false); + const [submitting, setSubmitting] = useState(false); + + const passwordsMatch = password.length > 0 && password === confirm; + const canSubmit = username.trim().length > 0 && passwordsMatch && !submitting; + + const onSubmit = (event: FormEvent) => { + event.preventDefault(); + + if (!canSubmit) { + if (password.length > 0 && confirm.length > 0 && !passwordsMatch) { + setError('Passwords do not match.'); + } + return; + } + + setSubmitting(true); + setError(null); + + setup(username.trim(), password) + .then((session) => { + onAuthenticated(session); + }) + .catch((caught: unknown) => { + if (caught instanceof ApiError && caught.status === 409) { + setAlreadyConfigured(true); + } else { + setError('Setup failed. Please try again.'); + } + setSubmitting(false); + }); + }; + + if (alreadyConfigured) { + return ( +
+ +
+ This server has already been set up. Reload to sign in. +
+
+ +
+
+
+ ); + } + + return ( +
+ +
+
+ } + onChange={(event) => { + setUsername(event.target.value); + setError(null); + }} + placeholder="Choose a username" + value={username} + /> + } + onChange={(event) => { + setPassword(event.target.value); + setError(null); + }} + placeholder="Choose a password" + type="password" + value={password} + /> + 0 && !passwordsMatch ? 'Passwords do not match.' : null} + label="Confirm password" + leadingIcon={
+ + {error && ( +
+ {error} +
+ )} + +
+ +
+
+
+
+ ); +} diff --git a/web/src/shell.css b/web/src/shell.css index 600186bd9..1a9b7f06d 100644 --- a/web/src/shell.css +++ b/web/src/shell.css @@ -4465,3 +4465,14 @@ body { padding: 4px; border-radius: var(--radius-sm); } + +/* Shell-less boot pages (login / setup / checking / error) — the AuthGate renders these OUTSIDE the app + shell, so they own their own full-viewport centered layout (#295). */ +.ctv-auth-page { + display: flex; + align-items: center; + justify-content: center; + min-height: 100vh; + padding: 24px; + background: var(--surface-app); +} -- 2.47.3 From de9fc7e8ccb6b72ad5f137bf9dad990b73b16ef3 Mon Sep 17 00:00:00 2001 From: Timothy Date: Sun, 12 Jul 2026 20:37:54 +0200 Subject: [PATCH 3/9] =?UTF-8?q?feat(web):=20#295=20PR2=20SPA=20consumers?= =?UTF-8?q?=20=E2=80=94=20troubleshoot=20POST/blob=20downloads=20+=20machi?= =?UTF-8?q?ne-key=20screen=20+=20password=20change?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 4.8 (1M context) --- docs/spa-conventions.md | 49 ++- web/src/api/auth.ts | 29 +- web/src/api/troubleshoot.test.ts | 141 +++++++- web/src/api/troubleshoot.ts | 85 +++++ web/src/screens/ApiKeyScreen.test.tsx | 143 ++++++-- web/src/screens/ApiKeyScreen.tsx | 317 +++++++++++++----- .../PlaybackTroubleshootingScreen.test.tsx | 142 ++++++-- .../screens/PlaybackTroubleshootingScreen.tsx | 127 +++++-- 8 files changed, 799 insertions(+), 234 deletions(-) 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/web/src/api/auth.ts b/web/src/api/auth.ts index 11ead6458..cd11213f6 100644 --- a/web/src/api/auth.ts +++ b/web/src/api/auth.ts @@ -42,37 +42,12 @@ function getStorage(): Storage | undefined { // The SPA no longer stores or sends an API key — it authenticates with the session cookie (#295). This // one-shot cleanup removes any legacy `ctv-api-key` left over from the pre-session model; AuthGate calls -// it once on reaching `ready`. +// it once on reaching `ready`. (The former `get/set/clearStoredApiKey` shims were removed once the +// ApiKeyScreen stopped consuming them — this is the sole remaining reader of the legacy key.) export function clearLegacyStoredApiKey(): void { getStorage()?.removeItem(legacyApiKeyStorageKey); } -// --- legacy API-key storage (DEPRECATED, #295) ------------------------------ -// The session-auth plan (PR #295 slice B) deletes these — the client no longer sends the key and the -// key is no longer stored by the SPA. They are retained here ONLY so the still-shipping -// `screens/ApiKeyScreen.tsx` (migrated by the separate machine-key slice) keeps compiling without a -// cross-slice merge conflict; nothing else reads them and `client.ts` no longer attaches the key. -// Remove these with the ApiKeyScreen slice. -export function getStoredApiKey(): string | null { - const value = getStorage()?.getItem(legacyApiKeyStorageKey); - return value && value.trim().length > 0 ? value : null; -} - -export function setStoredApiKey(apiKey: string): void { - const trimmed = apiKey.trim(); - - if (trimmed.length === 0) { - clearStoredApiKey(); - return; - } - - getStorage()?.setItem(legacyApiKeyStorageKey, trimmed); -} - -export function clearStoredApiKey(): void { - getStorage()?.removeItem(legacyApiKeyStorageKey); -} - // --- 401 signal ------------------------------------------------------------- // The whole `/api` surface is gated behind an authenticated session cookie (#295). Rather than teach // every screen's error path to special-case 401, the request client emits a single app-wide signal when diff --git a/web/src/api/troubleshoot.test.ts b/web/src/api/troubleshoot.test.ts index 75bc36f8c..fe5796bdc 100644 --- a/web/src/api/troubleshoot.test.ts +++ b/web/src/api/troubleshoot.test.ts @@ -1,12 +1,25 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; import { + downloadTroubleshootingArchive, + downloadTroubleshootingMediaSample, getTroubleshootingInfo, getTroubleshootingPlaybackStatus, getTroubleshootingStreamSelectors, getTroubleshootingSubtitles, - validateSequentialSchedule + startTroubleshootingPlayback, + validateSequentialSchedule, + type StartTroubleshootingPlaybackBody } from './troubleshoot'; +function headerValue(init: RequestInit | undefined, name: string): string | undefined { + const headers = init?.headers as Record | undefined; + if (!headers) { + return undefined; + } + const match = Object.keys(headers).find((key) => key.toLowerCase() === name.toLowerCase()); + return match ? headers[match] : undefined; +} + function jsonResponse(body: unknown, status = 200): Response { return new Response(JSON.stringify(body), { headers: { 'Content-Type': 'application/json' }, status }); } @@ -119,3 +132,129 @@ describe('troubleshooting playback wrappers', () => { expect(fetchSpy.mock.calls[0][0]).toBe('/api/troubleshoot/playback/status'); }); }); + +describe('startTroubleshootingPlayback', () => { + beforeEach(() => { + vi.restoreAllMocks(); + }); + + it('POSTs /api/troubleshoot/playback/start with the mapped body and a CSRF header, returning the url', async () => { + const fetchSpy = vi.spyOn(window, 'fetch').mockResolvedValue( + jsonResponse({ url: '/iptv/session/.troubleshooting/live.m3u8' }) + ); + + // Arrays are carried through, and the mutually-exclusive pair is preserved as the caller mapped it + // (streamSelector set → subtitleId null). + const body: StartTroubleshootingPlaybackBody = { + mediaItem: 5, + channel: 0, + ffmpegProfile: 2, + streamingMode: 'HttpLiveStreamingSegmenter', + watermark: [10, 11], + graphicsElement: [20], + streamSelector: 'selector-a', + subtitleId: null, + seekSeconds: 1200, + start: null + }; + + await expect(startTroubleshootingPlayback(body)).resolves.toEqual({ + url: '/iptv/session/.troubleshooting/live.m3u8' + }); + + const [url, init] = fetchSpy.mock.calls[0]; + expect(url).toBe('/api/troubleshoot/playback/start'); + expect((init?.method ?? 'GET').toUpperCase()).toBe('POST'); + expect(headerValue(init, 'X-Csrf')).toBe('1'); + expect(JSON.parse(String(init?.body))).toEqual(body); + }); + + it('rejects with the ApiError status (409) so the screen can surface "another session running"', async () => { + vi.spyOn(window, 'fetch').mockResolvedValue( + new Response(JSON.stringify({ status: 409, title: 'Conflict', detail: 'Another session is running.' }), { + headers: { 'Content-Type': 'application/problem+json' }, + status: 409 + }) + ); + + await expect( + startTroubleshootingPlayback({ + mediaItem: 5, + channel: 0, + ffmpegProfile: 1, + streamingMode: 'HttpLiveStreamingSegmenter', + watermark: [], + graphicsElement: [], + streamSelector: null, + subtitleId: null, + seekSeconds: 0, + start: null + }) + ).rejects.toMatchObject({ status: 409, detail: 'Another session is running.' }); + }); +}); + +describe('troubleshooting download helpers', () => { + beforeEach(() => { + vi.restoreAllMocks(); + }); + + function zipResponse(filename: string): Response { + return new Response(new Blob(['zip-bytes']), { + headers: { + 'Content-Type': 'application/zip', + 'Content-Disposition': `attachment; filename="${filename}"` + }, + status: 200 + }); + } + + function stubBrowserDownload() { + const createObjectURL = vi.fn(() => 'blob:mock'); + const revokeObjectURL = vi.fn(); + // jsdom does not implement these on URL; install spies so the anchor-click download path runs. + (URL as unknown as { createObjectURL: unknown }).createObjectURL = createObjectURL; + (URL as unknown as { revokeObjectURL: unknown }).revokeObjectURL = revokeObjectURL; + const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {}); + return { createObjectURL, revokeObjectURL, clickSpy }; + } + + it('POSTs (not GETs) the archive with a CSRF header and triggers a download', async () => { + const fetchSpy = vi.spyOn(window, 'fetch').mockResolvedValue(zipResponse('ersatztv-troubleshooting-123.zip')); + const { createObjectURL, revokeObjectURL, clickSpy } = stubBrowserDownload(); + + await downloadTroubleshootingArchive(); + + const [url, init] = fetchSpy.mock.calls[0]; + expect(url).toBe('/api/troubleshoot/playback/archive'); + expect((init?.method ?? 'GET').toUpperCase()).toBe('POST'); + expect(headerValue(init, 'X-Csrf')).toBe('1'); + expect(createObjectURL).toHaveBeenCalledTimes(1); + expect(clickSpy).toHaveBeenCalledTimes(1); + expect(revokeObjectURL).toHaveBeenCalledTimes(1); + }); + + it('POSTs the media sample for a given id with a CSRF header', async () => { + const fetchSpy = vi.spyOn(window, 'fetch').mockResolvedValue(zipResponse('ersatztv-media-sample-123.zip')); + stubBrowserDownload(); + + await downloadTroubleshootingMediaSample(42); + + const [url, init] = fetchSpy.mock.calls[0]; + expect(url).toBe('/api/troubleshoot/playback/sample/42'); + expect((init?.method ?? 'GET').toUpperCase()).toBe('POST'); + expect(headerValue(init, 'X-Csrf')).toBe('1'); + }); + + it('throws an ApiError on a non-ok download response', async () => { + vi.spyOn(window, 'fetch').mockResolvedValue( + new Response(JSON.stringify({ status: 404, title: 'Not Found' }), { + headers: { 'Content-Type': 'application/problem+json' }, + status: 404 + }) + ); + stubBrowserDownload(); + + await expect(downloadTroubleshootingArchive()).rejects.toMatchObject({ status: 404 }); + }); +}); diff --git a/web/src/api/troubleshoot.ts b/web/src/api/troubleshoot.ts index 7257ac7d3..37477144a 100644 --- a/web/src/api/troubleshoot.ts +++ b/web/src/api/troubleshoot.ts @@ -5,6 +5,8 @@ export type TroubleshootingInfo = components['schemas']['TroubleshootingInfoResp export type ValidateScheduleResult = components['schemas']['ValidateSequentialScheduleResponseModel']; export type TroubleshootingSubtitle = components['schemas']['TroubleshootingSubtitleResponseModel']; export type TroubleshootingPlaybackStatus = components['schemas']['TroubleshootingPlaybackStatusResponseModel']; +export type StartTroubleshootingPlaybackBody = components['schemas']['StartTroubleshootingPlaybackRequest']; +export type TroubleshootingPlaybackStarted = components['schemas']['TroubleshootingPlaybackStartedResponseModel']; export function getTroubleshootingInfo(): Promise { return request('/api/troubleshoot/info'); @@ -28,6 +30,89 @@ export function getTroubleshootingPlaybackStatus(): Promise('/api/troubleshoot/playback/status'); } +// Start a troubleshooting playback session (#295 — was a GET on `playback.m3u8` that started the +// session as a side effect of the manifest fetch; now an explicit POST with a JSON body). The server +// blocks until the first segments exist, then returns the open `/iptv` live manifest URL to feed to +// HlsPlayer. A 404/409/422 surfaces as an ApiError the caller can show inline. +export function startTroubleshootingPlayback( + body: StartTroubleshootingPlaybackBody +): Promise { + return request('/api/troubleshoot/playback/start', { + body, + method: 'POST' + }); +} + +// File-download endpoints — these return a binary zip, not JSON, so they must NOT go through +// `request()` (which JSON-parses the body). Fetch directly with the CSRF header (both are POST since +// #295), read the blob, and trigger a browser download. Same-origin fetch can read Content-Disposition +// so we use the server-provided filename when present. +export function downloadTroubleshootingArchive(): Promise { + return downloadViaPost('/api/troubleshoot/playback/archive', 'ersatztv-troubleshooting.zip'); +} + +export function downloadTroubleshootingMediaSample(id: number): Promise { + return downloadViaPost(`/api/troubleshoot/playback/sample/${id}`, 'ersatztv-media-sample.zip'); +} + +async function downloadViaPost(path: string, fallbackName: string): Promise { + const response = await fetch(path, { method: 'POST', headers: { 'X-Csrf': '1' } }); + + if (!response.ok) { + throw new ApiError(response.status, await readProblemDetailsSafe(response)); + } + + const blob = await response.blob(); + const filename = filenameFromContentDisposition(response.headers.get('Content-Disposition'), fallbackName); + const objectUrl = URL.createObjectURL(blob); + try { + const anchor = document.createElement('a'); + anchor.href = objectUrl; + anchor.download = filename; + document.body.appendChild(anchor); + anchor.click(); + anchor.remove(); + } finally { + URL.revokeObjectURL(objectUrl); + } +} + +async function readProblemDetailsSafe(response: Response): Promise { + const contentType = response.headers.get('Content-Type') ?? ''; + if (!contentType.includes('application/json') && !contentType.includes('problem+json')) { + return undefined; + } + try { + return (await response.json()) as components['schemas']['ProblemDetails']; + } catch { + return undefined; + } +} + +// Parse `filename="…"` / `filename*=UTF-8''…` from a Content-Disposition header, falling back when the +// header is absent or unparseable. +function filenameFromContentDisposition(header: null | string, fallback: string): string { + if (!header) { + return fallback; + } + + const extended = /filename\*=(?:UTF-8'')?([^;]+)/i.exec(header); + if (extended?.[1]) { + try { + return decodeURIComponent(extended[1].trim().replace(/^"|"$/g, '')); + } catch { + // fall through to the plain filename form + } + } + + const plain = /filename="?([^";]+)"?/i.exec(header); + if (plain?.[1]) { + return plain[1].trim(); + } + + return fallback; +} + export function validateSequentialSchedule(yaml: string, isImport: boolean): Promise { return request('/api/troubleshoot/validate-schedule', { body: { yaml, isImport }, diff --git a/web/src/screens/ApiKeyScreen.test.tsx b/web/src/screens/ApiKeyScreen.test.tsx index ae8789ac6..e867c439f 100644 --- a/web/src/screens/ApiKeyScreen.test.tsx +++ b/web/src/screens/ApiKeyScreen.test.tsx @@ -1,69 +1,138 @@ -import { cleanup, fireEvent, render, screen } from '@testing-library/react'; +import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import type { ReactNode } from 'react'; import { ApiKeyScreen } from './ApiKeyScreen'; +import { AuthContext, type AuthContextValue } from '../AuthGate'; + +// The repurposed screen (#295) is a normal authenticated screen: it loads the machine key from +// `/api/auth/machine-key` and, for local accounts, changes the password via `/api/auth/password`. Its +// self-contained fetch mock (spa-conventions §6) covers only those two endpoints. +function json(body: unknown, status = 200): Response { + return new Response(JSON.stringify(body), { headers: { 'Content-Type': 'application/json' }, status }); +} + +function installFetch(options: { machineKey?: string; passwordStatus?: number } = {}) { + const { machineKey = 'machine-secret', passwordStatus = 204 } = options; + return vi.spyOn(window, 'fetch').mockImplementation((input: RequestInfo | URL) => { + const url = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url; + if (url === '/api/auth/machine-key') { + return Promise.resolve(json({ key: machineKey })); + } + if (url === '/api/auth/password') { + if (passwordStatus >= 400) { + return Promise.resolve( + new Response(JSON.stringify({ status: passwordStatus, title: 'Unauthorized', detail: 'Wrong password.' }), { + headers: { 'Content-Type': 'application/problem+json' }, + status: passwordStatus + }) + ); + } + return Promise.resolve(new Response(null, { status: passwordStatus })); + } + return Promise.resolve(json({}, 404)); + }); +} + +function renderWith(method: string | null, children: ReactNode = ) { + const value: AuthContextValue = { + username: 'admin', + method, + signOut: () => {}, + requireLogin: () => {} + }; + return render({children}); +} describe('ApiKeyScreen', () => { beforeEach(() => { window.localStorage.clear(); vi.restoreAllMocks(); + Object.assign(navigator, { clipboard: { writeText: vi.fn().mockResolvedValue(undefined) } }); }); afterEach(() => { cleanup(); }); - it('renders and functions without any /api call', () => { - const fetchSpy = vi.spyOn(window, 'fetch'); + it('shows the machine key masked by default, then reveals it', async () => { + installFetch({ machineKey: 'machine-secret' }); - render(); + renderWith('local'); - expect(screen.getByText('No key')).toBeTruthy(); - expect(screen.getByText(/No key is stored in this browser/)).toBeTruthy(); - expect(fetchSpy).not.toHaveBeenCalled(); + // The masked code cell renders without leaking the key into the DOM. + const cell = await screen.findByTestId('machine-key'); + expect(cell.textContent).not.toContain('machine-secret'); + expect(document.body.innerHTML).not.toContain('machine-secret'); + + fireEvent.click(screen.getByRole('button', { name: /Reveal/i })); + + await waitFor(() => expect(screen.getByTestId('machine-key').textContent).toBe('machine-secret')); }); - it('saves a pasted key to local storage and shows the key-set state', () => { - render(); + it('copies the real machine key regardless of the masked state', async () => { + installFetch({ machineKey: 'machine-secret' }); - fireEvent.change(screen.getByLabelText('API key'), { target: { value: ' secret-123 ' } }); - fireEvent.click(screen.getByRole('button', { name: 'Save key' })); + renderWith('local'); + await screen.findByTestId('machine-key'); - // Trimmed and written through to the shared ctv-api-key slot. - expect(window.localStorage.getItem('ctv-api-key')).toBe('secret-123'); - expect(screen.getByText('Key set')).toBeTruthy(); - expect(screen.getByText(/Key saved/)).toBeTruthy(); + fireEvent.click(screen.getByRole('button', { name: /Copy/i })); + + expect(navigator.clipboard.writeText).toHaveBeenCalledWith('machine-secret'); }); - it('does not render the stored key value in plaintext', () => { - window.localStorage.setItem('ctv-api-key', 'super-secret'); + it('renders the local-password card only for a local account', async () => { + installFetch(); - render(); - - expect(screen.getByText('Key set')).toBeTruthy(); - // The masked state never echoes the stored key back to the DOM. - expect(screen.queryByText(/super-secret/)).toBeNull(); - expect(document.body.innerHTML).not.toContain('super-secret'); + renderWith('local'); + expect(await screen.findByText('Local admin password')).toBeTruthy(); }); - it('clears a stored key', () => { - window.localStorage.setItem('ctv-api-key', 'super-secret'); + it('hides the local-password card for a non-local (oidc) account', async () => { + installFetch(); - render(); - - fireEvent.click(screen.getByRole('button', { name: 'Clear key' })); - - expect(window.localStorage.getItem('ctv-api-key')).toBeNull(); - expect(screen.getByText('No key')).toBeTruthy(); + renderWith('oidc'); + // Machine key card still loads. + await screen.findByTestId('machine-key'); + expect(screen.queryByText('Local admin password')).toBeNull(); }); - it('ignores a save with only whitespace', () => { - render(); + it('changes the password via /api/auth/password and confirms on success', async () => { + const fetchSpy = installFetch({ passwordStatus: 204 }); - const save = screen.getByRole('button', { name: 'Save key' }); - expect(save.hasAttribute('disabled')).toBe(true); + renderWith('local'); + await screen.findByText('Local admin password'); + + fireEvent.change(screen.getByLabelText('Current password'), { target: { value: 'old-pass' } }); + fireEvent.change(screen.getByLabelText('New password'), { target: { value: 'new-pass' } }); + fireEvent.click(screen.getByRole('button', { name: /Change password/i })); + + await waitFor(() => expect(screen.getByText('Password changed.')).toBeTruthy()); + + const passwordCall = fetchSpy.mock.calls.find((call) => call[0] === '/api/auth/password'); + expect(passwordCall).toBeTruthy(); + expect((passwordCall?.[1]?.method ?? 'GET').toUpperCase()).toBe('POST'); + expect(JSON.parse(String(passwordCall?.[1]?.body))).toEqual({ currentPassword: 'old-pass', newPassword: 'new-pass' }); + }); + + it('surfaces the ProblemDetails detail inline on a wrong-current-password 401', async () => { + installFetch({ passwordStatus: 401 }); + + renderWith('local'); + await screen.findByText('Local admin password'); + + fireEvent.change(screen.getByLabelText('Current password'), { target: { value: 'wrong' } }); + fireEvent.change(screen.getByLabelText('New password'), { target: { value: 'new-pass' } }); + fireEvent.click(screen.getByRole('button', { name: /Change password/i })); + + await waitFor(() => expect(screen.getByText('Wrong password.')).toBeTruthy()); + }); + + it('never touches the legacy ctv-api-key localStorage slot', async () => { + installFetch(); + + renderWith('local'); + await screen.findByTestId('machine-key'); - fireEvent.change(screen.getByLabelText('API key'), { target: { value: ' ' } }); - expect(save.hasAttribute('disabled')).toBe(true); expect(window.localStorage.getItem('ctv-api-key')).toBeNull(); }); }); diff --git a/web/src/screens/ApiKeyScreen.tsx b/web/src/screens/ApiKeyScreen.tsx index 55c119308..34533297d 100644 --- a/web/src/screens/ApiKeyScreen.tsx +++ b/web/src/screens/ApiKeyScreen.tsx @@ -1,99 +1,256 @@ -import { useState } from 'react'; -import { Check, KeyRound, ShieldCheck, Trash2, TriangleAlert } from 'lucide-react'; -import { Badge, Button, Card, Input } from '../components'; -import { clearStoredApiKey, getStoredApiKey, setStoredApiKey } from '../api'; +import { useCallback, useContext, useEffect, useRef, useState } from 'react'; +import { Check, Copy, Eye, EyeOff, KeyRound, Lock, ShieldCheck, TriangleAlert } from 'lucide-react'; +import { Button, Card, Input, Spinner } from '../components'; +import { ApiError, changePassword, getMachineKey } from '../api'; +import { AuthContext } from '../AuthGate'; -// The one screen that must work with ZERO successful `/api` calls: a keyless first load 401s every -// read, so this screen relies only on localStorage (auth.ts helpers) and never fetches from `/api`. -// It's how a fresh install gets its key in before anything else can load (#280 / #197). -export function ApiKeyScreen() { - const [hasKey, setHasKey] = useState(() => getStoredApiKey() !== null); - const [draft, setDraft] = useState(''); - const [justSaved, setJustSaved] = useState(false); +// Since #295 the browser authenticates with the session cookie, so this screen no longer bootstraps an +// API key. It now MANAGES the server's machine key (for MCP / external REST clients) and — for local +// admin accounts — offers a password change. It's a normal authenticated screen: it reads the machine +// key from `/api/auth/machine-key` (a real `/api` call), unlike the old keyless localStorage-only shape. +type KeyState = + | { status: 'loading' } + | { status: 'error'; message: string } + | { status: 'success'; key: string }; - const trimmed = draft.trim(); +function messageFromError(error: unknown, fallback: string): string { + if (error instanceof ApiError) { + return error.detail ?? error.message; + } + if (error instanceof Error) { + return error.message; + } + return fallback; +} - const save = () => { - if (trimmed.length === 0) { - return; - } +function CopyButton({ text }: { text: string }) { + const [copied, setCopied] = useState(false); - setStoredApiKey(trimmed); - setHasKey(true); - setDraft(''); - setJustSaved(true); - }; - - const clear = () => { - clearStoredApiKey(); - setHasKey(false); - setJustSaved(false); + const copy = () => { + void navigator.clipboard?.writeText(text).then(() => { + setCopied(true); + window.setTimeout(() => setCopied(false), 1500); + }); }; return ( -
- Key set - ) : ( - No key - ) + + ); +} + +function MachineKeyCard() { + const [state, setState] = useState({ status: 'loading' }); + const [revealed, setRevealed] = useState(false); + const activeRef = useRef(true); + const seqRef = useRef(0); + + useEffect(() => { + activeRef.current = true; + return () => { + activeRef.current = false; + }; + }, []); + + // State transitions live in the promise callbacks (never synchronously in the effect body) per + // docs/spa-conventions.md §3. + const load = useCallback(() => { + const seq = ++seqRef.current; + getMachineKey() + .then((result) => { + if (!activeRef.current || seq !== seqRef.current) { + return; } - padded - subtitle="This server requires an API key on every request. The server generates one on first run and writes it to /config/api.key on the server host — open that file and paste its contents below." - title="API Key" - > - {hasKey ? ( -
-
- ) : ( -
-
- )} + setState({ status: 'success', key: result.key }); + }) + .catch((error: unknown) => { + if (!activeRef.current || seq !== seqRef.current) { + return; + } + setState({ status: 'error', message: messageFromError(error, 'Unable to load the machine key') }); + }); + }, []); -
- } - onChange={(event) => { - setDraft(event.target.value); - setJustSaved(false); - }} - placeholder="Paste the contents of /config/api.key" - style={{ fontFamily: 'var(--font-mono)' }} - type="password" - value={draft} - /> + useEffect(() => { + load(); + }, [load]); + + return ( + + {state.status === 'loading' && ( +
+ + Loading machine key…
+ )} -
- {justSaved && ( - - - )} + {state.status === 'error' && ( +
+
- + )} + + {state.status === 'success' && ( + <> +
+
+ +
+ Machine key + + + + {/* Masked by default: the real key is never in the DOM until Reveal — Copy always copies + the real value regardless of the masked/revealed toggle. */} + + {revealed ? state.key : '••••••••••••••••••••••••'} + + +
+ +
+ + + +
+ + )} + + ); +} + +function LocalPasswordCard() { + const [currentPassword, setCurrentPassword] = useState(''); + const [newPassword, setNewPassword] = useState(''); + const [saving, setSaving] = useState(false); + const [error, setError] = useState(null); + const [justSaved, setJustSaved] = useState(false); + + const canSubmit = currentPassword.length > 0 && newPassword.length > 0 && !saving; + + const submit = async () => { + if (!canSubmit) { + return; + } + setSaving(true); + setError(null); + setJustSaved(false); + try { + await changePassword(currentPassword, newPassword); + setCurrentPassword(''); + setNewPassword(''); + setJustSaved(true); + } catch (err: unknown) { + // A 401 is the expected wrong-current-password answer — surface its ProblemDetails detail inline. + if (err instanceof ApiError && err.status === 401) { + setError(err.detail ?? 'Your current password is incorrect.'); + } else { + setError(messageFromError(err, 'Unable to change your password')); + } + } finally { + setSaving(false); + } + }; + + return ( + + {error && ( +
+
+ )} + +
+ } + onChange={(event) => { + setCurrentPassword(event.target.value); + setJustSaved(false); + }} + type="password" + value={currentPassword} + /> +
+ +
+ } + onChange={(event) => { + setNewPassword(event.target.value); + setJustSaved(false); + }} + type="password" + value={newPassword} + /> +
+ +
+ {justSaved && ( + + + )} + + +
+
+ ); +} + +export function ApiKeyScreen() { + const { method } = useContext(AuthContext); + + return ( +
+ + {method === 'local' && }
); } diff --git a/web/src/screens/PlaybackTroubleshootingScreen.test.tsx b/web/src/screens/PlaybackTroubleshootingScreen.test.tsx index 63f02ed52..9612295f1 100644 --- a/web/src/screens/PlaybackTroubleshootingScreen.test.tsx +++ b/web/src/screens/PlaybackTroubleshootingScreen.test.tsx @@ -39,11 +39,43 @@ function json(body: unknown, status = 200): Response { const IDLE: Status = { state: 'idle', exitCode: null, speed: null, logs: null }; +// The open `/iptv` live manifest the start endpoint returns (was the manifest GET's own URL pre-#295). +const LIVE_MANIFEST = '/iptv/session/.troubleshooting/live.m3u8'; + +function zipResponse(): Response { + return new Response(new Blob(['zip-bytes']), { + headers: { 'Content-Type': 'application/zip', 'Content-Disposition': 'attachment; filename="out.zip"' }, + status: 200 + }); +} + // A fetch stub keyed by URL. `statusRef.current` lets a test flip the polled status over time. -function installFetch(statusRef: { current: Status }) { - return vi.spyOn(window, 'fetch').mockImplementation((input: RequestInfo | URL) => { +// `startBody` captures the POSTed start-playback body; `startStatus` lets a test force a start error. +function installFetch( + statusRef: { current: Status }, + options: { startStatus?: number; startBody?: { current: unknown } } = {} +) { + return vi.spyOn(window, 'fetch').mockImplementation((input: RequestInfo | URL, init?: RequestInit) => { const url = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url; + if (url === '/api/troubleshoot/playback/start') { + if (options.startBody) { + options.startBody.current = init?.body ? JSON.parse(String(init.body)) : null; + } + if (options.startStatus && options.startStatus >= 400) { + return Promise.resolve( + new Response(JSON.stringify({ status: options.startStatus, title: 'Conflict', detail: 'Another session is running.' }), { + headers: { 'Content-Type': 'application/problem+json' }, + status: options.startStatus + }) + ); + } + return Promise.resolve(json({ url: LIVE_MANIFEST })); + } + if (url === '/api/troubleshoot/playback/archive' || url.startsWith('/api/troubleshoot/playback/sample/')) { + return Promise.resolve(zipResponse()); + } + if (url.startsWith('/api/ffmpeg/profiles')) { return Promise.resolve(json([{ id: 1, name: 'Default' }, { id: 2, name: 'Hardware' }])); } @@ -155,10 +187,11 @@ describe('PlaybackTroubleshootingScreen', () => { expect(screen.queryByText('Seek Seconds')).toBeNull(); }); - it('sends the channel profile id (not 0) in the channel-mode playback URL', async () => { + it('sends the channel profile id (not 0) in the channel-mode start body', async () => { setLocation('/app/troubleshooting/playback?channel=7'); const statusRef = { current: IDLE }; - installFetch(statusRef); + const startBody = { current: null as unknown }; + installFetch(statusRef, { startBody }); render(); await screen.findByText(/Channel Settings — Channel Seven/i); @@ -172,21 +205,26 @@ describe('PlaybackTroubleshootingScreen', () => { fireEvent.click(screen.getByRole('button', { name: 'Play' })); - expect(hlsMock.loadSource).toHaveBeenCalledTimes(1); - const params = new URLSearchParams(String(hlsMock.loadSource.mock.calls[0][0]).split('?')[1]); + // The start endpoint returns the live manifest, which is fed to hls.js. + await waitFor(() => expect(hlsMock.loadSource).toHaveBeenCalledWith(LIVE_MANIFEST)); + // The regression this pins: the runtime channel JSON key is ffmpegProfileId (#198). Before the - // spec was aligned, reading the spec-cased fFmpegProfileId left the profile null and the URL + // spec was aligned, reading the spec-cased fFmpegProfileId left the profile null and the body // fell back to ffmpegProfile=0. - expect(params.get('ffmpegProfile')).toBe('2'); - expect(params.get('channel')).toBe('7'); - expect(params.get('start')).toBe(new Date('2026-07-09T20:00').toISOString()); - expect(params.get('mediaItem')).toBeNull(); + expect(startBody.current).toMatchObject({ + ffmpegProfile: 2, + channel: 7, + mediaItem: 0, + streamingMode: 'HttpLiveStreamingSegmenter', + start: new Date('2026-07-09T20:00').toISOString() + }); }); - it('builds the correct playback.m3u8 query on Play and starts polling', async () => { + it('POSTs the correct start body on Play, feeds the returned manifest to hls.js, and starts polling', async () => { setLocation('/app/troubleshooting/playback?mediaItem=5'); const statusRef = { current: IDLE }; - installFetch(statusRef); + const startBody = { current: null as unknown }; + installFetch(statusRef, { startBody }); vi.useFakeTimers(); try { @@ -198,15 +236,16 @@ describe('PlaybackTroubleshootingScreen', () => { fireEvent.click(screen.getByRole('button', { name: 'Play' })); - expect(hlsMock.loadSource).toHaveBeenCalledTimes(1); - const url = String(hlsMock.loadSource.mock.calls[0][0]); - expect(url.startsWith('/api/troubleshoot/playback.m3u8?')).toBe(true); - const params = new URLSearchParams(url.split('?')[1]); - expect(params.get('ffmpegProfile')).toBe('1'); - expect(params.get('streamingMode')).toBe('4'); - expect(params.get('mediaItem')).toBe('5'); - expect(params.get('seekSeconds')).toBe('1200'); // 40 min / 2 - expect(params.get('channel')).toBeNull(); + // The POST resolves with the live manifest, which is handed to hls.js. + await vi.waitFor(() => expect(hlsMock.loadSource).toHaveBeenCalledWith(LIVE_MANIFEST)); + + expect(startBody.current).toMatchObject({ + ffmpegProfile: 1, + streamingMode: 'HttpLiveStreamingSegmenter', + mediaItem: 5, + channel: 0, + seekSeconds: 1200 // 40 min / 2 + }); // Polling picks up the running status → Play becomes disabled. await vi.advanceTimersByTimeAsync(2000); @@ -216,6 +255,22 @@ describe('PlaybackTroubleshootingScreen', () => { } }); + it('surfaces the ProblemDetails detail and returns to idle when start fails (409)', async () => { + setLocation('/app/troubleshooting/playback?mediaItem=5'); + const statusRef = { current: IDLE }; + installFetch(statusRef, { startStatus: 409 }); + + render(); + await screen.findByText(/Movie Settings/i); + + fireEvent.click(screen.getByRole('button', { name: 'Play' })); + + // 409 detail surfaces via the notice, and Play returns to the idle (enabled) phase. + await waitFor(() => expect(screen.getByText('Another session is running.')).toBeTruthy()); + await waitFor(() => expect((screen.getByRole('button', { name: 'Play' }) as HTMLButtonElement).disabled).toBe(false)); + expect(hlsMock.loadSource).not.toHaveBeenCalled(); + }); + it('surfaces logs and a speed badge when polling transitions running → completed', async () => { setLocation('/app/troubleshooting/playback?mediaItem=5'); const statusRef = { current: IDLE }; @@ -256,10 +311,11 @@ describe('PlaybackTroubleshootingScreen', () => { render(); await vi.waitFor(() => expect(screen.getByText(/Movie Settings/i)).toBeTruthy()); - // First play through to completion. + // First play through to completion. The start POST resolves with the constant live manifest. statusRef.current = { state: 'running', exitCode: null, speed: null, logs: null }; fireEvent.click(screen.getByRole('button', { name: 'Play' })); - expect(hlsMock.loadSource).toHaveBeenCalledTimes(1); + await vi.waitFor(() => expect(hlsMock.loadSource).toHaveBeenCalledTimes(1)); + expect(hlsMock.loadSource.mock.calls[0][0]).toBe(LIVE_MANIFEST); await vi.advanceTimersByTimeAsync(2000); // observe running statusRef.current = { state: 'completed', exitCode: 0, speed: 1.1, logs: 'done' }; @@ -268,10 +324,11 @@ describe('PlaybackTroubleshootingScreen', () => { expect((screen.getByRole('button', { name: 'Play' }) as HTMLButtonElement).disabled).toBe(false) ); - // Repeat Play with untouched settings: identical URL, but the manifest request MUST fire - // again (the GET is what starts a session server-side). + // Repeat Play with untouched settings: the manifest URL is identical, but HlsPlayer MUST + // re-attach (the playToken bump) so the returned live manifest is re-requested. + statusRef.current = { state: 'running', exitCode: null, speed: null, logs: null }; fireEvent.click(screen.getByRole('button', { name: 'Play' })); - expect(hlsMock.loadSource).toHaveBeenCalledTimes(2); + await vi.waitFor(() => expect(hlsMock.loadSource).toHaveBeenCalledTimes(2)); expect(hlsMock.loadSource.mock.calls[1][0]).toBe(hlsMock.loadSource.mock.calls[0][0]); expect(hlsMock.destroy).toHaveBeenCalled(); // previous instance torn down before re-attach } finally { @@ -345,20 +402,32 @@ describe('PlaybackTroubleshootingScreen', () => { } }); - it('opens the archive and media-sample downloads, gated while a session is active', async () => { + it('downloads the archive and media sample via a POST-blob fetch (never a browser tab), gated while active', async () => { setLocation('/app/troubleshooting/playback?mediaItem=5'); const statusRef = { current: IDLE }; - installFetch(statusRef); + const fetchSpy = installFetch(statusRef); + // Never open a download endpoint in a browser tab. const openSpy = vi.spyOn(window, 'open').mockImplementation(() => null); + // jsdom lacks these on URL — stub the object-URL/anchor-click download path. + (URL as unknown as { createObjectURL: unknown }).createObjectURL = vi.fn(() => 'blob:mock'); + (URL as unknown as { revokeObjectURL: unknown }).revokeObjectURL = vi.fn(); + const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {}); + + const postCall = (path: string) => + fetchSpy.mock.calls.find( + (call) => call[0] === path && (call[1]?.method ?? 'GET').toUpperCase() === 'POST' + ); + vi.useFakeTimers(); try { render(); await vi.waitFor(() => expect(screen.getByText(/Movie Settings/i)).toBeTruthy()); - // Download Media Sample is available while idle. + // Download Media Sample is available while idle → POST-blob, not window.open. fireEvent.click(screen.getByRole('button', { name: /Download Media Sample/i })); - expect(openSpy).toHaveBeenCalledWith('/api/troubleshoot/playback/sample/5'); + await vi.waitFor(() => expect(postCall('/api/troubleshoot/playback/sample/5')).toBeTruthy()); + expect(openSpy).not.toHaveBeenCalled(); // Both downloads are gated while a session is starting/running. statusRef.current = { state: 'running', exitCode: null, speed: null, logs: null }; @@ -366,15 +435,18 @@ describe('PlaybackTroubleshootingScreen', () => { expect((screen.getByRole('button', { name: /Download Results/i }) as HTMLButtonElement).disabled).toBe(true); expect((screen.getByRole('button', { name: /Download Media Sample/i }) as HTMLButtonElement).disabled).toBe(true); - // Run to completion → Download Results enabled (hasPlayed && not busy). - await vi.advanceTimersByTimeAsync(2000); + // Drive to completion so Download Results enables (hasPlayed && not busy). + await vi.advanceTimersByTimeAsync(2000); // observe running statusRef.current = { state: 'completed', exitCode: 0, speed: 1, logs: 'done' }; - await vi.advanceTimersByTimeAsync(2000); + await vi.advanceTimersByTimeAsync(2000); // observe completed await vi.waitFor(() => expect((screen.getByRole('button', { name: /Download Results/i }) as HTMLButtonElement).disabled).toBe(false) ); + fireEvent.click(screen.getByRole('button', { name: /Download Results/i })); - expect(openSpy).toHaveBeenCalledWith('/api/troubleshoot/playback/archive'); + await vi.waitFor(() => expect(postCall('/api/troubleshoot/playback/archive')).toBeTruthy()); + expect(clickSpy).toHaveBeenCalled(); + expect(openSpy).not.toHaveBeenCalled(); } finally { vi.useRealTimers(); } diff --git a/web/src/screens/PlaybackTroubleshootingScreen.tsx b/web/src/screens/PlaybackTroubleshootingScreen.tsx index 4fd518aee..8bb909d97 100644 --- a/web/src/screens/PlaybackTroubleshootingScreen.tsx +++ b/web/src/screens/PlaybackTroubleshootingScreen.tsx @@ -2,6 +2,8 @@ import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } fro import { Download, DownloadCloud, PlayCircle, Stethoscope, TriangleAlert } from 'lucide-react'; import { Button, Card, Checkbox, Input, Select, Spinner, Toast } from '../components'; import { + downloadTroubleshootingArchive, + downloadTroubleshootingMediaSample, getChannelById, getFFmpegProfiles, getGraphicsElements, @@ -11,10 +13,12 @@ import { getTroubleshootingSubtitles, getWatermarks, messageFromTroubleshootError, + startTroubleshootingPlayback, type Channel, type FFmpegProfile, type GraphicsElement, type MediaItemInfo, + type StartTroubleshootingPlaybackBody, type TroubleshootingPlaybackStatus, type TroubleshootingSubtitle, type Watermark @@ -23,8 +27,9 @@ import { HlsPlayer } from '../media/HlsPlayer'; import { parseDurationSeconds } from '../media/mediaKinds'; // StreamingMode.HttpLiveStreamingSegmenter — mirrors PlaybackTroubleshooting.razor, which always -// requests the segmenter mode for troubleshooting playback. -const STREAMING_MODE_HLS_SEGMENTER = 4; +// requests the segmenter mode for troubleshooting playback. The start endpoint takes the StreamingMode +// as its serialized enum name (the generated request type is a string union), not the numeric value. +const STREAMING_MODE_HLS_SEGMENTER: StartTroubleshootingPlaybackBody['streamingMode'] = 'HttpLiveStreamingSegmenter'; const STATUS_POLL_MS = 2000; // How long after Play we keep waiting for the server to report 'running' before giving up. // PrepareTroubleshootingPlayback runs several DB queries before it takes the playback lock, so the @@ -364,15 +369,48 @@ export function PlaybackTroubleshootingScreen() { // Busy = a session this screen is aware of is starting or transcoding; gates Play + downloads. const isBusy = playPhase !== 'idle'; - // Build the playback.m3u8 query string, mirroring PlaybackTroubleshooting.razor PreviewChannel. - const buildPlaybackUrl = useCallback((): null | string => { - // Sending ffmpegProfile=0 is always wrong (no such profile) — refuse to build a URL without one. + const onDownloadArchive = async () => { + try { + await downloadTroubleshootingArchive(); + } catch (error: unknown) { + setNotice({ tone: 'error', message: messageFromTroubleshootError(error, 'Unable to download results') }); + } + }; + + const onDownloadMediaSample = async (id: number) => { + try { + await downloadTroubleshootingMediaSample(id); + } catch (error: unknown) { + setNotice({ tone: 'error', message: messageFromTroubleshootError(error, 'Unable to download media sample') }); + } + }; + + // Build the start-playback request body, mirroring PlaybackTroubleshooting.razor PreviewChannel. + // Returns null on invalid input (no profile, or a channel without a valid start datetime) — the same + // guard the old URL builder used; Play is also disabled in those states so null is defensive. + const buildPlaybackParams = useCallback((): StartTroubleshootingPlaybackBody | null => { + // Sending ffmpegProfile=0 is always wrong (no such profile) — refuse without one. if (form.ffmpegProfileId == null) { return null; } - const params = new URLSearchParams(); - params.set('ffmpegProfile', String(form.ffmpegProfileId)); - params.set('streamingMode', String(STREAMING_MODE_HLS_SEGMENTER)); + + // Stream selector and subtitle are mutually exclusive (selector wins). + let streamSelector: null | string = null; + let subtitleId: null | number = null; + if (form.streamSelector !== '') { + streamSelector = form.streamSelector; + } else if (form.subtitleId != null) { + subtitleId = form.subtitleId; + } + + const common = { + ffmpegProfile: form.ffmpegProfileId, + streamingMode: STREAMING_MODE_HLS_SEGMENTER, + watermark: form.watermarkIds, + graphicsElement: form.graphicsElementIds, + streamSelector, + subtitleId + }; if (mode.kind === 'channel') { if (form.startValue === '') { @@ -382,35 +420,31 @@ export function PlaybackTroubleshootingScreen() { if (Number.isNaN(parsed.getTime())) { return null; } - params.set('channel', String(mode.channelId)); - params.set('start', parsed.toISOString()); - } else if (mode.kind === 'media') { - params.set('mediaItem', String(mode.mediaItemId)); - params.set('seekSeconds', String(form.seekSeconds)); - } else { - return null; + return { + ...common, + mediaItem: 0, + channel: mode.channelId, + seekSeconds: 0, + start: parsed.toISOString() + }; } - for (const id of form.watermarkIds) { - params.append('watermark', String(id)); - } - for (const id of form.graphicsElementIds) { - params.append('graphicsElement', String(id)); + if (mode.kind === 'media') { + return { + ...common, + mediaItem: mode.mediaItemId, + channel: 0, + seekSeconds: form.seekSeconds, + start: null + }; } - // Stream selector and subtitle are mutually exclusive (selector wins). - if (form.streamSelector !== '') { - params.set('streamSelector', form.streamSelector); - } else if (form.subtitleId != null) { - params.set('subtitleId', String(form.subtitleId)); - } - - return `/api/troubleshoot/playback.m3u8?${params.toString()}`; + return null; }, [form, mode]); - const onPlay = () => { - const url = buildPlaybackUrl(); - if (url === null) { + const onPlay = async () => { + const body = buildPlaybackParams(); + if (body === null) { return; } setNotice(null); @@ -418,10 +452,29 @@ export function PlaybackTroubleshootingScreen() { setPhase('starting'); startingSinceRef.current = Date.now(); setHasPlayed(true); - setPlayerSrc(url); - // Bump the token so HlsPlayer re-attaches even when the URL is identical to the previous play. - setPlayToken((current) => current + 1); startPolling(); + + try { + const result = await startTroubleshootingPlayback(body); + if (!activeRef.current) { + return; + } + // The start endpoint returns the open `/iptv` live manifest — feed it to HlsPlayer. The URL is + // constant across plays, so bump the token to force a re-attach even on a repeat play. + setPlayerSrc(result.url); + setPlayToken((current) => current + 1); + } catch (error: unknown) { + if (!activeRef.current) { + return; + } + // A 409 (another session running) / 404 / 422 now surfaces its ProblemDetails detail inline. + stopPolling(); + setPhase('idle'); + setNotice({ + tone: 'error', + message: messageFromTroubleshootError(error, 'Unable to start troubleshooting playback') + }); + } }; if (mode.kind === 'empty') { @@ -506,7 +559,7 @@ export function PlaybackTroubleshootingScreen() {