using System.Security.Claims; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using PlotLine.Services.NativeCompanion; namespace PlotLine.Controllers; [RequestSizeLimit(4096)] [Microsoft.AspNetCore.RateLimiting.EnableRateLimiting("native-pair")] public sealed class NativeCompanionAuthController(DesktopPairing pairing):Controller { [AllowAnonymous,HttpPost("api/native-companion/pair")] public IActionResult Start([FromBody] PairStart request) { Response.Headers.CacheControl="no-store"; if(request==null)return BadRequest(); try{return Ok(new{code=pairing.Start(request.Challenge??"")});} catch(ArgumentException){return BadRequest();}catch(InvalidOperationException){return StatusCode(429);} } [Authorize,HttpGet("native-companion/authorize")] public IActionResult Approve(string code) {Response.Headers.CacheControl="no-store";Response.Headers["Referrer-Policy"]="no-referrer";return !string.IsNullOrEmpty(code)&&pairing.Exists(code)?View("Approve",code):BadRequest("This request expired. Start Connect again in Word.");} [Authorize,HttpPost("native-companion/authorize"),ValidateAntiForgeryToken] public IActionResult ApproveGrant(string code) { if(string.IsNullOrEmpty(code))return BadRequest(); if(!int.TryParse(User.FindFirstValue(ClaimTypes.NameIdentifier),out var user)||!Guid.TryParse(User.FindFirstValue("PlotLine.SecurityStamp"),out var stamp))return Forbid(); Response.Headers.CacheControl="no-store"; return pairing.Approve(code,user,stamp)?Content("Word Companion connected. You may close this tab. The grant expires in four hours; signing out in Word discards it."):BadRequest("This request expired or was already approved."); } [AllowAnonymous,HttpPost("api/native-companion/token")] public IActionResult Token([FromBody] PairRedeem request) {Response.Headers.CacheControl="no-store";if(request==null)return BadRequest();var token=pairing.Redeem(request.Code??"",request.Verifier??"");return token==null?Accepted(new{status="pending-or-expired"}):Ok(new{accessToken=token});} public sealed record PairStart(string Challenge); public sealed record PairRedeem(string Code,string Verifier); }