House rules: primary constructors, a cancellation token on every async call, and the rules fail the build
Build / Build (push) Successful in 30s
Build / Build (push) Successful in 30s
- 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
This commit is contained in:
1 parent
f0a14c737f
commit
0f73f69239
176 files changed
+2789
-3974
No files matched your search
@@ -41,36 +41,36 @@ namespace PrivaPub.Infrastructure.Cli
|
||||
/// <summary>Whether a command runs before migrations: backups are of the database as it was.</summary>
|
||||
public static bool BeforeMigrations(string[] args) => args is ["backup", ..] or ["backups"] or ["restore", ..];
|
||||
|
||||
public static async Task<int> Run(string[] args, IServiceProvider services, TextReader input = default, TextWriter output = default)
|
||||
public static async Task<int> Run(string[] args, IServiceProvider services, TextReader input = default, TextWriter output = default, CancellationToken token = default)
|
||||
{
|
||||
input ??= Console.In;
|
||||
output ??= Console.Out;
|
||||
switch (args)
|
||||
{
|
||||
case [("promote" or "demote") and var verb, var userName]:
|
||||
return await Role(services, userName, verb == "promote" ? RootRole.Admin : RootRole.User, output);
|
||||
return await Role(services, userName, verb == "promote" ? RootRole.Admin : RootRole.User, output, token: token);
|
||||
case ["role", var userName, var role] when RootUser.TryParseRole(role, out var parsed):
|
||||
return await Role(services, userName, parsed, output);
|
||||
return await Role(services, userName, parsed, output, token: token);
|
||||
case ["create-root", var login, .. var flags] when flags.All(f => f == "--admin"):
|
||||
return await CreateRoot(services, login, input.ReadLine(), flags.Contains("--admin"), output);
|
||||
return await CreateRoot(services, login, input.ReadLine(), flags.Contains("--admin"), output, token);
|
||||
case ["move-persona", var persona, var root]:
|
||||
return await MovePersona(services, persona, root, output);
|
||||
return await MovePersona(services, persona, root, output, token);
|
||||
case ["delete-root", var root]:
|
||||
return await DeleteRoot(services, root, output);
|
||||
return await DeleteRoot(services, root, output, token);
|
||||
case ["reset-totp", var root]:
|
||||
return await ResetTotp(services, root, output);
|
||||
return await ResetTotp(services, root, output, token);
|
||||
case ["media", "audit", .. var flags] when flags.All(f => f == "--fix"):
|
||||
return await AuditMedia(services, flags.Contains("--fix"), output);
|
||||
return await AuditMedia(services, flags.Contains("--fix"), output, token);
|
||||
case ["backup", "verify", var id]:
|
||||
return await VerifyBackup(services, id, output);
|
||||
return await VerifyBackup(services, id, output, token);
|
||||
case ["backup", .. var flags] when BackupFlags(flags, out var kind, out var dbOnly):
|
||||
return await BackUp(services, kind, dbOnly, output);
|
||||
return await BackUp(services, kind, dbOnly, output, token);
|
||||
case ["backups"]:
|
||||
return ListBackups(services, output);
|
||||
case ["restore", "--status"]:
|
||||
return await RestoreStatus(services, output);
|
||||
return await RestoreStatus(services, output, token);
|
||||
case ["restore", var id] when !id.StartsWith('-'):
|
||||
return await Restore(services, id, output);
|
||||
return await Restore(services, id, output, token);
|
||||
default:
|
||||
Console.Error.WriteLine(Usage);
|
||||
return 2;
|
||||
@@ -98,7 +98,7 @@ namespace PrivaPub.Infrastructure.Cli
|
||||
return true;
|
||||
}
|
||||
|
||||
static async Task<int> BackUp(IServiceProvider services, string kind, bool dbOnly, TextWriter output)
|
||||
static async Task<int> BackUp(IServiceProvider services, string kind, bool dbOnly, TextWriter output, CancellationToken token = default)
|
||||
{
|
||||
var (made, error) = await services.GetRequiredService<Backups>().Create(kind, dbOnly, CancellationToken.None);
|
||||
if (made == default)
|
||||
@@ -123,7 +123,7 @@ namespace PrivaPub.Infrastructure.Cli
|
||||
return 0;
|
||||
}
|
||||
|
||||
static async Task<int> VerifyBackup(IServiceProvider services, string id, TextWriter output)
|
||||
static async Task<int> VerifyBackup(IServiceProvider services, string id, TextWriter output, CancellationToken token = default)
|
||||
{
|
||||
var problems = await services.GetRequiredService<Backups>().Verify(id, CancellationToken.None);
|
||||
foreach (var problem in problems)
|
||||
@@ -134,7 +134,7 @@ namespace PrivaPub.Infrastructure.Cli
|
||||
return 0;
|
||||
}
|
||||
|
||||
static async Task<int> Restore(IServiceProvider services, string id, TextWriter output)
|
||||
static async Task<int> Restore(IServiceProvider services, string id, TextWriter output, CancellationToken token = default)
|
||||
{
|
||||
var backups = services.GetRequiredService<Backups>();
|
||||
var refused = await ServerRestore.Request(backups.Context(), id, "cli", CancellationToken.None);
|
||||
@@ -143,18 +143,18 @@ namespace PrivaPub.Infrastructure.Cli
|
||||
Console.Error.WriteLine(refused);
|
||||
return 1;
|
||||
}
|
||||
await Log(services, AdminActions.BackupRestore, AdminTargets.Backup, id, id);
|
||||
await Log(services, AdminActions.BackupRestore, AdminTargets.Backup, id, id, token: token);
|
||||
output.WriteLine($"{id} will be restored: the running service stops within seconds and restores it when it starts again");
|
||||
output.WriteLine("(systemd starts it again; follow it with journalctl -u privapub, then PrivaPub admin restore --status)");
|
||||
return 0;
|
||||
}
|
||||
|
||||
static async Task<int> RestoreStatus(IServiceProvider services, TextWriter output)
|
||||
static async Task<int> RestoreStatus(IServiceProvider services, TextWriter output, CancellationToken token = default)
|
||||
{
|
||||
var waiting = RestoreMarker.Read(services.GetRequiredService<Backups>().Root);
|
||||
if (waiting != default)
|
||||
output.WriteLine($"waiting: {waiting.Backup}, {waiting.State}, attempt {waiting.Attempts} of {RestoreMarker.MaxAttempts}, asked by {waiting.RequestedBy} at {waiting.RequestedAt:u}{(waiting.Error == default ? string.Empty : $": {waiting.Error}")}");
|
||||
var last = await DB.Default.Find<RestoreRecord>().Sort(r => r.RestoredAt, Order.Descending).ExecuteFirstAsync();
|
||||
var last = await DB.Default.Find<RestoreRecord>().Sort(r => r.RestoredAt, Order.Descending).ExecuteFirstAsync(token);
|
||||
if (last == default)
|
||||
{
|
||||
if (waiting == default)
|
||||
@@ -177,7 +177,7 @@ namespace PrivaPub.Infrastructure.Cli
|
||||
|
||||
static string Names(List<string> names) => names.Count == 0 ? "none" : string.Join(", ", names);
|
||||
|
||||
static async Task<int> AuditMedia(IServiceProvider services, bool fix, TextWriter output)
|
||||
static async Task<int> AuditMedia(IServiceProvider services, bool fix, TextWriter output, CancellationToken token = default)
|
||||
{
|
||||
var report = await Domain.Media.MediaAudit.Run(services.GetRequiredService<Domain.Media.IMediaService>(), fix, CancellationToken.None);
|
||||
output.WriteLine($"{report.Files} files served, {report.Held} rows holding media");
|
||||
@@ -194,15 +194,15 @@ namespace PrivaPub.Infrastructure.Cli
|
||||
|
||||
// every act below is kept in the staff's log as the command line's ("cli"): a login's by its name alone, a persona's
|
||||
// without the login it went to
|
||||
static Task Log(IServiceProvider services, string action, string kind, string id, string label, string note = default) =>
|
||||
services.GetRequiredService<IModerationLog>().Write(AdminAction.Cli, action, kind, id, label, note: note);
|
||||
static Task Log(IServiceProvider services, string action, string kind, string id, string label, string note = default, CancellationToken token = default) =>
|
||||
services.GetRequiredService<IModerationLog>().Write(AdminAction.Cli, action, kind, id, label, note: note, token: token);
|
||||
|
||||
// The command line is the way back, so it may leave the server without an administrator (the client's route refuses
|
||||
// to); it says so, and `role <root> admin` gives one back.
|
||||
static async Task<int> Role(IServiceProvider services, string userName, RootRole role, TextWriter output, bool created = false)
|
||||
static async Task<int> Role(IServiceProvider services, string userName, RootRole role, TextWriter output, bool created = false, CancellationToken token = default)
|
||||
{
|
||||
userName = userName.ToLowerInvariant();
|
||||
var user = await DB.Default.Find<RootUser>().Match(u => u.UserName == userName && u.DeletedAt == null).ExecuteFirstAsync();
|
||||
var user = await DB.Default.Find<RootUser>().Match(u => u.UserName == userName && u.DeletedAt == null).ExecuteFirstAsync(token);
|
||||
if (user == default)
|
||||
{
|
||||
Console.Error.WriteLine($"no root user '{userName}'");
|
||||
@@ -211,17 +211,17 @@ namespace PrivaPub.Infrastructure.Cli
|
||||
|
||||
var was = user.Role;
|
||||
user.SetRole(role);
|
||||
await DB.Default.Update<RootUser>().MatchID(user.ID).Modify(u => u.Policies, user.Policies).Modify(u => u.UpdatedAt, user.UpdatedAt).ExecuteAsync();
|
||||
await DB.Default.Update<RootUser>().MatchID(user.ID).Modify(u => u.Policies, user.Policies).Modify(u => u.UpdatedAt, user.UpdatedAt).ExecuteAsync(token);
|
||||
if (role == RootRole.Admin)
|
||||
await ServerSetup.Seal(user.ID, default);//an administrator exists: the client's setup is closed
|
||||
if (!created && was != role)
|
||||
await Log(services, role == RootRole.Admin && was == RootRole.User ? AdminActions.RootPromote
|
||||
: role == RootRole.User && was == RootRole.Admin ? AdminActions.RootDemote
|
||||
: AdminActions.RootRole, AdminTargets.Root, user.ID, userName, $"{Name(was)} → {Name(role)}");
|
||||
: AdminActions.RootRole, AdminTargets.Root, user.ID, userName, $"{Name(was)} → {Name(role)}", token);
|
||||
|
||||
output.WriteLine($"{userName}: {string.Join(", ", user.Policies)}");
|
||||
if (was == RootRole.Admin && role != RootRole.Admin
|
||||
&& !await DB.Default.Find<RootUser>().Match(u => u.DeletedAt == null && !u.IsBanned && u.Policies.Contains(Policies.IsAdmin)).ExecuteAnyAsync())
|
||||
&& !await DB.Default.Find<RootUser>().Match(u => u.DeletedAt == null && !u.IsBanned && u.Policies.Contains(Policies.IsAdmin)).ExecuteAnyAsync(token))
|
||||
Console.Error.WriteLine("no administrator is left: `PrivaPub admin role <root> admin` makes one");
|
||||
return 0;
|
||||
}
|
||||
@@ -230,7 +230,7 @@ namespace PrivaPub.Infrastructure.Cli
|
||||
|
||||
// With sign-up closed, this or the client's setup (while no administrator exists) makes the first root; group invitations
|
||||
// make the rest.
|
||||
static async Task<int> CreateRoot(IServiceProvider services, string login, string password, bool admin, TextWriter output)
|
||||
static async Task<int> CreateRoot(IServiceProvider services, string login, string password, bool admin, TextWriter output, CancellationToken token = default)
|
||||
{
|
||||
var form = new LoginForm { UserName = login, Password = password?.Trim() };
|
||||
var problems = new List<ValidationResult>();
|
||||
@@ -239,18 +239,18 @@ namespace PrivaPub.Infrastructure.Cli
|
||||
Console.Error.WriteLine(string.Join(Environment.NewLine, problems.Select(p => p.ErrorMessage)));
|
||||
return 1;
|
||||
}
|
||||
var created = await services.GetRequiredService<IRootUsersService>().SignUpAsync(form);
|
||||
var created = await services.GetRequiredService<IRootUsersService>().SignUpAsync(form, token);
|
||||
if (!created.IsValid)
|
||||
{
|
||||
Console.Error.WriteLine(created.ErrorMessage);
|
||||
return 1;
|
||||
}
|
||||
var made = await DB.Default.Find<RootUser>().Match(u => u.UserName == login.ToLowerInvariant()).ExecuteFirstAsync();
|
||||
await Log(services, AdminActions.RootCreate, AdminTargets.Root, made?.ID, login.ToLowerInvariant(), admin ? "administrator" : default);
|
||||
return admin ? await Role(services, login, RootRole.Admin, output, created: true) : await Report(login, output);
|
||||
var made = await DB.Default.Find<RootUser>().Match(u => u.UserName == login.ToLowerInvariant()).ExecuteFirstAsync(token);
|
||||
await Log(services, AdminActions.RootCreate, AdminTargets.Root, made?.ID, login.ToLowerInvariant(), admin ? "administrator" : default, token);
|
||||
return admin ? await Role(services, login, RootRole.Admin, output, created: true, token) : await Report(login, output, token);
|
||||
}
|
||||
|
||||
static Task<int> Report(string login, TextWriter output)
|
||||
static Task<int> Report(string login, TextWriter output, CancellationToken token = default)
|
||||
{
|
||||
output.WriteLine($"{login.ToLowerInvariant()}: created");
|
||||
return Task.FromResult(0);
|
||||
@@ -259,23 +259,23 @@ namespace PrivaPub.Infrastructure.Cli
|
||||
// A persona given to another login (owner decision 2026-10-17, made for @thepra): its link moves first, so the old
|
||||
// login can no longer exchange a token for it, then its Mastodon tokens and authorizations end. Its actor, posts and
|
||||
// followers stay as they are, and nobody outside is told: nothing they hold changes.
|
||||
static async Task<int> MovePersona(IServiceProvider services, string personaName, string login, TextWriter output)
|
||||
static async Task<int> MovePersona(IServiceProvider services, string personaName, string login, TextWriter output, CancellationToken token = default)
|
||||
{
|
||||
personaName = personaName.TrimStart('@').ToLowerInvariant();
|
||||
login = login.ToLowerInvariant();
|
||||
var persona = await DB.Default.Find<Avatar>().Match(a => a.UserName == personaName && !a.DeletionAt.HasValue).ExecuteFirstAsync();
|
||||
var persona = await DB.Default.Find<Avatar>().Match(a => a.UserName == personaName && !a.DeletionAt.HasValue).ExecuteFirstAsync(token);
|
||||
if (persona == default)
|
||||
{
|
||||
Console.Error.WriteLine($"no persona '@{personaName}'");
|
||||
return 1;
|
||||
}
|
||||
var root = await DB.Default.Find<RootUser>().Match(u => u.UserName == login).ExecuteFirstAsync();
|
||||
var root = await DB.Default.Find<RootUser>().Match(u => u.UserName == login).ExecuteFirstAsync(token);
|
||||
if (root == default || root.DeletedAt.HasValue || root.IsBanned)
|
||||
{
|
||||
Console.Error.WriteLine($"no root user '{login}' that can take it");
|
||||
return 1;
|
||||
}
|
||||
var link = await DB.Default.Find<RootToAvatar>().Match(ra => ra.AvatarId == persona.ID).ExecuteFirstAsync();
|
||||
var link = await DB.Default.Find<RootToAvatar>().Match(ra => ra.AvatarId == persona.ID).ExecuteFirstAsync(token);
|
||||
if (link == default)
|
||||
{
|
||||
Console.Error.WriteLine($"'@{personaName}' belongs to no login");
|
||||
@@ -287,52 +287,52 @@ namespace PrivaPub.Infrastructure.Cli
|
||||
return 0;
|
||||
}
|
||||
|
||||
await DB.Default.Update<RootToAvatar>().MatchID(link.ID).Modify(ra => ra.RootId, root.ID).ExecuteAsync();
|
||||
await services.GetRequiredService<IOpenIddictTokenManager>().RevokeBySubjectAsync(persona.ID);
|
||||
await services.GetRequiredService<IOpenIddictAuthorizationManager>().RevokeBySubjectAsync(persona.ID);
|
||||
await Domain.Social.WebPush.Forget(new[] { persona.ID });//its Web Push subscriptions go with its tokens (R9)
|
||||
await Log(services, AdminActions.PersonaMove, AdminTargets.Persona, persona.ID, "@" + personaName, "moved to another login");
|
||||
await DB.Default.Update<RootToAvatar>().MatchID(link.ID).Modify(ra => ra.RootId, root.ID).ExecuteAsync(token);
|
||||
await services.GetRequiredService<IOpenIddictTokenManager>().RevokeBySubjectAsync(persona.ID, token);
|
||||
await services.GetRequiredService<IOpenIddictAuthorizationManager>().RevokeBySubjectAsync(persona.ID, token);
|
||||
await Domain.Social.WebPush.Forget(new[] { persona.ID }, token);//its Web Push subscriptions go with its tokens (R9)
|
||||
await Log(services, AdminActions.PersonaMove, AdminTargets.Persona, persona.ID, "@" + personaName, "moved to another login", token);
|
||||
output.WriteLine($"@{personaName}: moved to {login}");
|
||||
return 0;
|
||||
}
|
||||
|
||||
// The way back for a login that lost its authenticator and its recovery codes: its two-factor sign-in goes, its
|
||||
// password stays.
|
||||
static async Task<int> ResetTotp(IServiceProvider services, string login, TextWriter output)
|
||||
static async Task<int> ResetTotp(IServiceProvider services, string login, TextWriter output, CancellationToken token = default)
|
||||
{
|
||||
login = login.ToLowerInvariant();
|
||||
var root = await DB.Default.Find<RootUser>().Match(u => u.UserName == login && u.DeletedAt == null).ExecuteFirstAsync();
|
||||
var updated = root == default ? default : await DB.Default.Update<RootUser>().MatchID(root.ID).Modify(u => u.Totp, null).ExecuteAsync();
|
||||
var root = await DB.Default.Find<RootUser>().Match(u => u.UserName == login && u.DeletedAt == null).ExecuteFirstAsync(token);
|
||||
var updated = root == default ? default : await DB.Default.Update<RootUser>().MatchID(root.ID).Modify(u => u.Totp, null).ExecuteAsync(token);
|
||||
if (updated == default || updated.MatchedCount == 0)
|
||||
{
|
||||
Console.Error.WriteLine($"no root user '{login}'");
|
||||
return 1;
|
||||
}
|
||||
await Log(services, AdminActions.RootResetTotp, AdminTargets.Root, root.ID, login);
|
||||
await Log(services, AdminActions.RootResetTotp, AdminTargets.Root, root.ID, login, token: token);
|
||||
output.WriteLine($"{login}: two-factor sign-in is off");
|
||||
return 0;
|
||||
}
|
||||
|
||||
// A login deleted from the box as the client deletes its own (RootRemoval): every persona it still has goes with it,
|
||||
// announced deleted, and its sessions end.
|
||||
static async Task<int> DeleteRoot(IServiceProvider services, string login, TextWriter output)
|
||||
static async Task<int> DeleteRoot(IServiceProvider services, string login, TextWriter output, CancellationToken token = default)
|
||||
{
|
||||
login = login.ToLowerInvariant();
|
||||
var root = await DB.Default.Find<RootUser>().Match(u => u.UserName == login && u.DeletedAt == null).ExecuteFirstAsync();
|
||||
var root = await DB.Default.Find<RootUser>().Match(u => u.UserName == login && u.DeletedAt == null).ExecuteFirstAsync(token);
|
||||
if (root == default)
|
||||
{
|
||||
Console.Error.WriteLine($"no root user '{login}'");
|
||||
return 1;
|
||||
}
|
||||
var owned = (await DB.Default.Find<RootToAvatar>().Match(ra => ra.RootId == root.ID).ExecuteAsync()).Select(ra => ra.AvatarId).ToList();
|
||||
var personas = (await DB.Default.Find<Avatar>().Match(a => owned.Contains(a.ID) && !a.DeletionAt.HasValue).ExecuteAsync())
|
||||
var owned = (await DB.Default.Find<RootToAvatar>().Match(ra => ra.RootId == root.ID).ExecuteAsync(token)).Select(ra => ra.AvatarId).ToList();
|
||||
var personas = (await DB.Default.Find<Avatar>().Match(a => owned.Contains(a.ID) && !a.DeletionAt.HasValue).ExecuteAsync(token))
|
||||
.Select(a => "@" + a.UserName).ToList();
|
||||
if (!await services.GetRequiredService<IRootRemoval>().Remove(root.ID, default))
|
||||
{
|
||||
Console.Error.WriteLine($"'{login}' could not be deleted");
|
||||
return 1;
|
||||
}
|
||||
await Log(services, AdminActions.RootDelete, AdminTargets.Root, root.ID, login);
|
||||
await Log(services, AdminActions.RootDelete, AdminTargets.Root, root.ID, login, token: token);
|
||||
output.WriteLine($"{login}: deleted{(personas.Count > 0 ? ", with " + string.Join(", ", personas) : string.Empty)}");
|
||||
return 0;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user