69 lines
4.1 KiB
C#
69 lines
4.1 KiB
C#
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;
|
|
|
|
// Short lived, browser-approved desktop grants. No password/cookie export or refresh secret.
|
|
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<string,Pending> pending=[];
|
|
public string Start(string challenge)
|
|
{
|
|
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.Expires<clock.GetUtcNow()).Select(p=>p.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));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)
|
|
{lock(gate){if(!pending.TryGetValue(code,out var p)||p.Expires<=clock.GetUtcNow()||p.UserId!=null)return false;p.UserId=userId;p.Stamp=stamp;return true;}}
|
|
public string? Redeem(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 protector.Protect(JsonSerializer.Serialize(new Grant(user,p.Stamp,clock.GetUtcNow().AddHours(4))));
|
|
}
|
|
}
|
|
public Grant? Read(string token)
|
|
{
|
|
try{var grant=JsonSerializer.Deserialize<Grant>(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);
|
|
private sealed class Pending(string challenge,DateTimeOffset expires){public string Challenge=challenge;public DateTimeOffset Expires=expires;public int? UserId;public Guid Stamp;}
|
|
}
|
|
|
|
public sealed class DesktopAuthentication(IOptionsMonitor<AuthenticationSchemeOptions> options,ILoggerFactory logger,UrlEncoder encoder,DesktopPairing pairing,IUserRepository users)
|
|
: AuthenticationHandler<AuthenticationSchemeOptions>(options,logger,encoder)
|
|
{
|
|
protected override async Task<AuthenticateResult> 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.");
|
|
var identity=new ClaimsIdentity([new(ClaimTypes.NameIdentifier,grant.UserId.ToString()),new("PlotLine.SecurityStamp",grant.Stamp.ToString())],DesktopPairing.Scheme);
|
|
return AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(identity),DesktopPairing.Scheme));
|
|
}
|
|
}
|