using System.Security.Claims; using System.Security.Cryptography; using System.Text; using System.Text.Encodings.Web; using System.Text.Json; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.DataProtection; using Microsoft.Extensions.Options; using PlotLine.Data; namespace PlotLine.Services.NativeCompanion; // Existing browser-approved pairing. Durable installation authorisation is optional and negotiated. public sealed class DesktopPairing(IDataProtectionProvider protection, TimeProvider clock) { public const string Scheme="NativeCompanion"; private readonly IDataProtector protector=protection.CreateProtector("PlotDirector.NativeCompanion.Access.v1"); private readonly object gate=new(); private readonly Dictionary pending=[]; public string Start(string challenge,bool persistent=false,Guid connection=default,string deviceName="Windows Companion") { if(challenge.Length!=64||!challenge.All(Uri.IsHexDigit))throw new ArgumentException("Invalid pairing challenge."); lock(gate) { foreach(var key in pending.Where(p=>p.Value.Expiresp.Key).ToArray())pending.Remove(key); if(pending.Count>=100)throw new InvalidOperationException("Pairing busy. Try later."); var code=Convert.ToHexString(RandomNumberGenerator.GetBytes(12)); pending[code]=new(challenge,clock.GetUtcNow().AddMinutes(5)){Persistent=persistent,ConnectionId=connection,DeviceName=deviceName.Length>80?deviceName[..80]:deviceName};return code; } } public bool Exists(string code){lock(gate)return pending.TryGetValue(code,out var p)&&p.Expires>clock.GetUtcNow()&&p.UserId==null;} public bool Approve(string code,int userId,Guid stamp,bool retainImport=false) {lock(gate){if(!pending.TryGetValue(code,out var p)||p.Expires<=clock.GetUtcNow()||p.UserId!=null)return false;p.UserId=userId;p.Stamp=stamp;p.RetainImport=retainImport;return true;}} public bool Persistent(string code){lock(gate)return pending.TryGetValue(code,out var p)&&p.Persistent;} public sealed record Approval(int UserId,Guid Stamp,bool RetainImport,bool Persistent,Guid ConnectionId,string DeviceName); public Approval? RedeemApproval(string code,string verifier) { if(verifier.Length<43||verifier.Length>128)return null; lock(gate){ if(!pending.TryGetValue(code,out var p)||p.Expires<=clock.GetUtcNow()||!CryptographicOperations.FixedTimeEquals(Encoding.ASCII.GetBytes(p.Challenge),Encoding.ASCII.GetBytes(Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(verifier))))))return null; if(p.UserId is not int user)return null;pending.Remove(code);return new(user,p.Stamp,p.RetainImport,p.Persistent,p.ConnectionId,p.DeviceName); } } public string Issue(Grant grant)=>protector.Protect(JsonSerializer.Serialize(grant)); public string? Redeem(string code,string verifier){var approval=RedeemApproval(code,verifier);return approval==null?null:Issue(new(approval.UserId,approval.Stamp,clock.GetUtcNow().AddHours(4),approval.RetainImport));} public Grant? Read(string token) { try{var grant=JsonSerializer.Deserialize(protector.Unprotect(token));return grant?.Expires>clock.GetUtcNow()?grant:null;} catch(Exception e)when(e is CryptographicException or JsonException or FormatException){return null;} } public sealed record Grant(int UserId,Guid Stamp,DateTimeOffset Expires,bool RetainImport=false,Guid? InstallationId=null,Guid? ConnectionId=null); private sealed class Pending(string challenge,DateTimeOffset expires){public string Challenge=challenge;public DateTimeOffset Expires=expires;public int? UserId;public Guid Stamp;public bool RetainImport;public bool Persistent;public Guid ConnectionId;public string DeviceName="Windows Companion";} } public sealed class DesktopAuthentication(IOptionsMonitor options,ILoggerFactory logger,UrlEncoder encoder,DesktopPairing pairing,IUserRepository users,INativeInstallationRepository? installations=null) : AuthenticationHandler(options,logger,encoder) { protected override async Task HandleAuthenticateAsync() { var header=Request.Headers.Authorization.ToString(); if(!header.StartsWith("Bearer ",StringComparison.OrdinalIgnoreCase))return AuthenticateResult.NoResult(); if(header.Length>8192)return AuthenticateResult.Fail("Invalid grant."); var grant=pairing.Read(header[7..]);if(grant==null)return AuthenticateResult.Fail("Sign in again."); var user=await users.GetByIdAsync(grant.UserId); if(user==null||user.SecurityStamp!=grant.Stamp||(user.IsLocked&&(!user.LockoutEndUtc.HasValue||user.LockoutEndUtc>DateTime.UtcNow)))return AuthenticateResult.Fail("Sign in again."); if(grant.InstallationId.HasValue&&(grant.ConnectionId==null||installations==null||!await installations.Validate(grant.InstallationId.Value,grant.UserId,grant.Stamp,grant.ConnectionId.Value)))return AuthenticateResult.Fail("Installation approval expired or revoked."); var key=grant.InstallationId.HasValue?NativeInstallationService.GrantKey(grant.InstallationId.Value,grant.ConnectionId!.Value):Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(header[7..]))); var identity=new ClaimsIdentity([new(ClaimTypes.NameIdentifier,grant.UserId.ToString()),new("PlotLine.SecurityStamp",grant.Stamp.ToString()),new("NativeCompanion.RetainImport",grant.RetainImport?"true":"false"),new("NativeCompanion.Expires",grant.Expires.UtcDateTime.ToString("O")),new("NativeCompanion.Grant",key)],DesktopPairing.Scheme); if(grant.InstallationId.HasValue){identity.AddClaim(new("NativeCompanion.Installation",grant.InstallationId.Value.ToString("D")));identity.AddClaim(new("NativeCompanion.Connection",grant.ConnectionId!.Value.ToString("D")));} return AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(identity),new AuthenticationProperties{ExpiresUtc=grant.Expires},DesktopPairing.Scheme)); } }