Files
SocialPub/PrivaPub/Infrastructure/Statistics/InteractionSalts.cs
T
thepraandClaude Opus 5.5 0f73f69239
Build / Build (push) Successful in 30s
House rules: primary constructors, a cancellation token on every async call, and the rules fail the build
- Services, controllers and jobs take their dependencies through primary
  constructors and use them directly; where a method already named a local
  after a dependency, the dependency takes its type's name.
- Every async method takes a CancellationToken last and passes it down to
  MongoDB, HTTP and the job queue. The setup claim is still given back when
  a request is cancelled.
- The federation and media options are read through IOptionsMonitor.
- The Mastodon entities keep sending "" for empty strings, and every model
  field where null means something says so.
- The inbox's 503 with Retry-After, which other servers retry, is the one
  server error left, and says why.
- Arasaka.HouseRules.Analyzers checks all of this in every build, here and in
  PrivaPub.ClientModels as decePubClient builds it.

Checked against GoToSocial in the pasture: 64 passed, 0 failed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01W4YtEJrgxG12Pc39Fai8Bd
2026-11-10 01:24:43 +01:00

45 lines
1.5 KiB
C#

using MongoDB.Entities;
using PrivaPub.Models.Statistics;
using System.Collections.Concurrent;
using System.Security.Cryptography;
using System.Text;
namespace PrivaPub.Infrastructure.Statistics
{
public class InteractionSalts
{
readonly ConcurrentDictionary<DateTime, byte[]> _known = new();
public async Task<byte[]> For(DateTime day, CancellationToken token)
{
day = day.Date;
if (_known.TryGetValue(day, out var cached))
return cached;
var salt = default(InteractionSalt);
if (day == DateTime.UtcNow.Date)
salt = await DB.Default.UpdateAndGet<InteractionSalt>()
.Match(s => s.Day == day)
.Modify(b => b.SetOnInsert(s => s.Key, Convert.ToBase64String(RandomNumberGenerator.GetBytes(32))))
.Modify(b => b.SetOnInsert(s => s.ExpiresAt, day.AddHours(30)))
.Option(o => o.IsUpsert = true)
.ExecuteAsync(token);
else
salt = await DB.Default.Find<InteractionSalt>().Match(s => s.Day == day).ExecuteFirstAsync(token);
if (salt?.Key == default)
return default;
var key = Convert.FromBase64String(salt.Key);
foreach (var old in _known.Keys.Where(k => k < day.AddDays(-1)))
_known.TryRemove(old, out _);
_known[day] = key;
return key;
}
public static string Hash(byte[] salt, string actorUri) =>
salt == default || string.IsNullOrEmpty(actorUri)
? default
: Convert.ToBase64String(HMACSHA256.HashData(salt, Encoding.UTF8.GetBytes(actorUri))[..12]).TrimEnd('=').Replace('+', '-').Replace('/', '_');
}
}