shellcoreDB made... n shi

This commit is contained in:
gollyohmolly committed 2026-11-23 19:41:00 +01:00
1 parent 244bd918d6
commit bcc9894062
19 files changed
+493 -22

No files matched your search

+8
View File
@@ -0,0 +1,8 @@
using Npgsql;
namespace ShellcoreDB;
public sealed class Database(NpgsqlDataSource dataSource)
{
public ValueTask<NpgsqlConnection> Open(CancellationToken cancellationToken) => dataSource.OpenConnectionAsync(cancellationToken);
}
+92
View File
@@ -0,0 +1,92 @@
using Dapper;
using Microsoft.AspNetCore.Identity;
using Npgsql;
namespace ShellcoreDB;
public sealed class IdentityAccount
{
public Guid Id { get; set; }
public string UserName { get; set; } = "";
public string? NormalizedUserName { get; set; }
public string? PasswordHash { get; set; }
public string Status { get; set; } = "active";
}
// Identity storage over the existing schema; Steam-only accounts have no password row.
public sealed class IdentityAccountStore(Database database) : IUserPasswordStore<IdentityAccount>
{
public Task<string> GetUserIdAsync(IdentityAccount user, CancellationToken cancellationToken) => Task.FromResult(user.Id.ToString("D"));
public Task<string?> GetUserNameAsync(IdentityAccount user, CancellationToken cancellationToken) => Task.FromResult<string?>(user.UserName);
public Task SetUserNameAsync(IdentityAccount user, string? userName, CancellationToken cancellationToken)
{
user.UserName = userName ?? "";
return Task.CompletedTask;
}
public Task<string?> GetNormalizedUserNameAsync(IdentityAccount user, CancellationToken cancellationToken) => Task.FromResult(user.NormalizedUserName);
public Task SetNormalizedUserNameAsync(IdentityAccount user, string? normalizedName, CancellationToken cancellationToken)
{
user.NormalizedUserName = normalizedName;
return Task.CompletedTask;
}
public Task SetPasswordHashAsync(IdentityAccount user, string? passwordHash, CancellationToken cancellationToken)
{
user.PasswordHash = passwordHash;
return Task.CompletedTask;
}
public Task<string?> GetPasswordHashAsync(IdentityAccount user, CancellationToken cancellationToken) => Task.FromResult(user.PasswordHash);
public Task<bool> HasPasswordAsync(IdentityAccount user, CancellationToken cancellationToken) => Task.FromResult(user.PasswordHash is not null);
public async Task<IdentityResult> CreateAsync(IdentityAccount user, CancellationToken cancellationToken)
{
await using var connection = await database.Open(cancellationToken);
await using var transaction = await connection.BeginTransactionAsync(cancellationToken);
try
{
user.Id = await connection.QuerySingleAsync<Guid>(new CommandDefinition(
"INSERT INTO accounts (username) VALUES (@UserName) RETURNING id", user, transaction, cancellationToken: cancellationToken));
if (user.PasswordHash is not null)
await connection.ExecuteAsync(new CommandDefinition(
"INSERT INTO localCredentials (accountId, passwordHash) VALUES (@Id, @PasswordHash)", user, transaction, cancellationToken: cancellationToken));
await transaction.CommitAsync(cancellationToken);
return IdentityResult.Success;
}
catch (PostgresException exception) when (exception.SqlState == PostgresErrorCodes.UniqueViolation)
{
return IdentityResult.Failed(new IdentityError { Code = "DuplicateUserName", Description = "Username is unavailable." });
}
}
public async Task<IdentityResult> UpdateAsync(IdentityAccount user, CancellationToken cancellationToken)
{
await using var connection = await database.Open(cancellationToken);
if (user.PasswordHash is not null)
await connection.ExecuteAsync(new CommandDefinition(
"INSERT INTO localCredentials (accountId, passwordHash) VALUES (@Id, @PasswordHash) " +
"ON CONFLICT (accountId) DO UPDATE SET passwordHash = EXCLUDED.passwordHash", user, cancellationToken: cancellationToken));
return IdentityResult.Success;
}
public Task<IdentityResult> DeleteAsync(IdentityAccount user, CancellationToken cancellationToken) =>
throw new NotSupportedException("Account deletion requires a separate audited workflow.");
public async Task<IdentityAccount?> FindByIdAsync(string userId, CancellationToken cancellationToken)
{
if (!Guid.TryParse(userId, out var id)) return null;
await using var connection = await database.Open(cancellationToken);
return await connection.QuerySingleOrDefaultAsync<IdentityAccount>(new CommandDefinition(
"SELECT a.id, a.username AS UserName, c.passwordHash, a.status FROM accounts a " +
"LEFT JOIN localCredentials c ON c.accountId = a.id WHERE a.id = @id", new { id }, cancellationToken: cancellationToken));
}
public async Task<IdentityAccount?> FindByNameAsync(string normalizedUserName, CancellationToken cancellationToken)
{
await using var connection = await database.Open(cancellationToken);
return await connection.QuerySingleOrDefaultAsync<IdentityAccount>(new CommandDefinition(
"SELECT a.id, a.username AS UserName, c.passwordHash, a.status FROM accounts a " +
"LEFT JOIN localCredentials c ON c.accountId = a.id WHERE lower(a.username) = lower(@normalizedUserName)",
new { normalizedUserName }, cancellationToken: cancellationToken));
}
public void Dispose() { }
}
+11
View File
@@ -0,0 +1,11 @@
namespace ShellcoreDB;
public sealed record Credentials(string username, string password);
public sealed record SteamTicket(string ticket, string? username);
public sealed record SessionToken(string token);
public sealed record AccountData(Guid accountId, string username);
public sealed record LoginData(Guid accountId, string username, string token, DateTime expiresAt);
public sealed record ValidationData(Guid accountId, DateTime expiresAt);
public sealed record ApiError(string code, string message);
public sealed record Success<T>(bool success, T data);
public sealed record Failure(bool success, ApiError error);
+121
View File
@@ -0,0 +1,121 @@
using System.Security.Cryptography;
using System.Text;
using Npgsql;
using ShellcoreDB;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Diagnostics;
var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("Shellcore");
var serviceKey = builder.Configuration["ShellcoreServiceKey"];
if (string.IsNullOrWhiteSpace(connectionString))
throw new InvalidOperationException("ConnectionStrings:Shellcore is required.");
if (string.IsNullOrWhiteSpace(serviceKey))
throw new InvalidOperationException("ShellcoreServiceKey is required.");
builder.Services.AddSingleton(NpgsqlDataSource.Create(connectionString));
builder.Services.AddSingleton<Database>();
builder.Services.AddIdentityCore<IdentityAccount>(options =>
{
options.User.AllowedUserNameCharacters = "";
options.Password.RequiredLength = 12;
options.Password.RequiredUniqueChars = 1;
options.Password.RequireDigit = false;
options.Password.RequireLowercase = false;
options.Password.RequireUppercase = false;
options.Password.RequireNonAlphanumeric = false;
}).AddUserStore<IdentityAccountStore>();
builder.Services.AddSingleton(new SessionsLifetime(TimeSpan.FromDays(30)));
builder.Services.AddScoped<Sessions>(provider => new(provider.GetRequiredService<Database>(), provider.GetRequiredService<SessionsLifetime>().Value));
builder.Services.AddScoped<Auth>();
builder.Services.AddHttpClient<SteamVerifier>(client => client.Timeout = TimeSpan.FromSeconds(10));
builder.Services.AddScoped<SteamAuth>();
builder.Services.AddProblemDetails();
var app = builder.Build();
app.UseExceptionHandler(errorApp => errorApp.Run(async context =>
{
var exception = context.Features.Get<IExceptionHandlerFeature>()?.Error;
var (status, code, message) = exception switch
{
SteamUnavailableException => (503, "steamUnavailable", "Steam authentication is unavailable."),
NpgsqlException => (503, "databaseUnavailable", "Authentication storage is unavailable."),
_ => (500, "internalError", "An unexpected server error occurred.")
};
if (exception is not null) app.Logger.LogError(exception, "Authentication request failed");
await Results.Problem(statusCode: status, title: message,
extensions: new Dictionary<string, object?> { ["success"] = false, ["error"] = new ApiError(code, message) })
.ExecuteAsync(context);
}));
var expectedHash = SHA256.HashData(Encoding.UTF8.GetBytes(serviceKey));
var internalApi = app.MapGroup("/internal");
internalApi.AddEndpointFilter(async (context, next) =>
{
var supplied = context.HttpContext.Request.Headers["X-Service-Key"].ToString();
var suppliedHash = SHA256.HashData(Encoding.UTF8.GetBytes(supplied));
if (string.IsNullOrEmpty(supplied) || !CryptographicOperations.FixedTimeEquals(expectedHash, suppliedHash))
return Results.Json(new Failure(false, new("unauthorized", "A valid service key is required.")), statusCode: 401);
return await next(context);
});
internalApi.MapPost("/auth/register", async (Credentials body, Auth auth, CancellationToken cancellationToken) =>
{
if (string.IsNullOrWhiteSpace(body.username) || body.username.Length > 32 || body.username != body.username.Trim())
return Results.Json(new Failure(false, new("invalidUsername", "username must be 1 to 32 characters without surrounding spaces.")), statusCode: 400);
if (string.IsNullOrWhiteSpace(body.password) || body.password.Length < 12 || body.password.Length > 1024)
return Results.Json(new Failure(false, new("invalidPassword", "password must be 12 to 1024 characters.")), statusCode: 400);
var account = await auth.Register(body.username, body.password, cancellationToken);
return account is null
? Results.Json(new Failure(false, new("usernameTaken", "This username is unavailable.")), statusCode: 409)
: Results.Json(new Success<AccountData>(true, account), statusCode: 201);
});
internalApi.MapPost("/auth/login", async (Credentials body, Auth auth, CancellationToken cancellationToken) =>
{
if (string.IsNullOrWhiteSpace(body.username) || string.IsNullOrEmpty(body.password))
return Results.Json(new Failure(false, new("invalidCredentials", "Invalid username or password.")), statusCode: 401);
var login = await auth.Login(body.username, body.password, cancellationToken);
return login is null
? Results.Json(new Failure(false, new("invalidCredentials", "Invalid username or password.")), statusCode: 401)
: Results.Json(new Success<LoginData>(true, login));
});
internalApi.MapPost("/auth/steam", async (SteamTicket body, SteamAuth steam, CancellationToken cancellationToken) =>
{
if (string.IsNullOrWhiteSpace(body.ticket))
return Results.Json(new Failure(false, new("invalidSteamTicket", "A valid Steam ticket is required.")), statusCode: 401);
if (body.username is not null &&
(string.IsNullOrWhiteSpace(body.username) || body.username.Length > 32 || body.username != body.username.Trim()))
return Results.Json(new Failure(false, new("invalidUsername", "username must be 1 to 32 characters without surrounding spaces.")), statusCode: 400);
var (login, error) = await steam.Authenticate(body.ticket, body.username, cancellationToken);
return error switch
{
null => Results.Json(new Success<LoginData>(true, login!)),
"usernameTaken" => Results.Json(new Failure(false, new(error, "This username is unavailable.")), statusCode: 409),
"usernameRequired" => Results.Json(new Failure(false, new(error, "Choose a username to create a Steam account.")), statusCode: 400),
"accountUnavailable" => Results.Json(new Failure(false, new(error, "This account is unavailable.")), statusCode: 403),
_ => Results.Json(new Failure(false, new("invalidSteamTicket", "Steam authentication failed.")), statusCode: 401)
};
});
internalApi.MapPost("/sessions/validate", async (SessionToken body, Sessions sessions, CancellationToken cancellationToken) =>
{
if (string.IsNullOrWhiteSpace(body.token))
return Results.Json(new Failure(false, new("invalidSession", "Session is invalid or expired.")), statusCode: 401);
var validation = await sessions.Validate(body.token, cancellationToken);
return validation is null
? Results.Json(new Failure(false, new("invalidSession", "Session is invalid or expired.")), statusCode: 401)
: Results.Json(new Success<ValidationData>(true, validation));
});
internalApi.MapPost("/sessions/revoke", async (SessionToken body, Sessions sessions, CancellationToken cancellationToken) =>
{
var revoked = !string.IsNullOrWhiteSpace(body.token) && await sessions.Revoke(body.token, cancellationToken);
return Results.Json(new Success<object>(true, new { revoked }));
});
app.Run();
public sealed record SessionsLifetime(TimeSpan Value);
public partial class Program { }
+46
View File
@@ -0,0 +1,46 @@
using Npgsql;
using Dapper;
namespace ShellcoreDB;
public sealed class SteamAuth(Database database, Sessions sessions, SteamVerifier verifier)
{
public async Task<(LoginData? login, string? error)> Authenticate(string ticket, string? username, CancellationToken cancellationToken)
{
var steamId = await verifier.Verify(ticket, cancellationToken);
if (steamId is null) return (null, "invalidSteamTicket");
await using var connection = await database.Open(cancellationToken);
await using var transaction = await connection.BeginTransactionAsync(cancellationToken);
var linked = await connection.QuerySingleOrDefaultAsync<SteamAccount>(new CommandDefinition(
"SELECT a.id, a.username, a.status FROM externalAccounts e JOIN accounts a ON a.id = e.accountId WHERE e.provider = 'steam' AND e.providerUserId = @steamId",
new { steamId }, transaction, cancellationToken: cancellationToken));
if (linked is not null)
{
await transaction.CommitAsync(cancellationToken);
return linked.status == "active" ? (await sessions.Issue(linked.id, linked.username, cancellationToken), null) : (null, "accountUnavailable");
}
if (string.IsNullOrWhiteSpace(username)) return (null, "usernameRequired");
try
{
var accountId = await connection.QuerySingleAsync<Guid>(new CommandDefinition(
"INSERT INTO accounts (username) VALUES (@username) RETURNING id",
new { username }, transaction, cancellationToken: cancellationToken));
await connection.ExecuteAsync(new CommandDefinition(
"INSERT INTO externalAccounts (accountId, provider, providerUserId) VALUES (@accountId, 'steam', @steamId)",
new { accountId, steamId }, transaction, cancellationToken: cancellationToken));
await transaction.CommitAsync(cancellationToken);
return (await sessions.Issue(accountId, username, cancellationToken), null);
}
catch (PostgresException exception) when (exception.SqlState == PostgresErrorCodes.UniqueViolation)
{
return (null, "usernameTaken");
}
}
public sealed class SteamAccount
{
public Guid id { get; set; }
public string username { get; set; } = "";
public string status { get; set; } = "";
}
}
+40
View File
@@ -0,0 +1,40 @@
using System.Text.Json;
namespace ShellcoreDB;
public sealed class SteamVerifier(IConfiguration configuration, HttpClient client)
{
public async Task<string?> Verify(string ticket, CancellationToken cancellationToken)
{
if (ticket.Length is < 2 or > 8192 || ticket.Length % 2 != 0 || !ticket.All(Uri.IsHexDigit))
return null;
var key = configuration["Steam:PublisherKey"];
var appId = configuration["Steam:AppId"];
var identity = configuration["Steam:Identity"];
if (string.IsNullOrWhiteSpace(key) || !uint.TryParse(appId, out var parsedAppId) || parsedAppId == 0 || string.IsNullOrWhiteSpace(identity))
throw new SteamUnavailableException();
var url = "https://partner.steam-api.com/ISteamUserAuth/AuthenticateUserTicket/v1/" +
$"?key={Uri.EscapeDataString(key)}&appid={parsedAppId}&ticket={ticket}&identity={Uri.EscapeDataString(identity)}";
try
{
using var response = await client.GetAsync(url, cancellationToken);
if (!response.IsSuccessStatusCode) throw new SteamUnavailableException();
using var document = await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync(cancellationToken), cancellationToken: cancellationToken);
if (!document.RootElement.TryGetProperty("response", out var responseBody))
throw new SteamUnavailableException();
if (!responseBody.TryGetProperty("params", out var root))
return responseBody.TryGetProperty("error", out _) ? null : throw new SteamUnavailableException();
if (root.GetProperty("result").GetString() != "OK") return null;
var steamId = root.GetProperty("steamid").GetString();
return ulong.TryParse(steamId, out var parsed) && parsed != 0 ? steamId : null;
}
catch (HttpRequestException) { throw new SteamUnavailableException(); }
catch (TaskCanceledException) when (!cancellationToken.IsCancellationRequested) { throw new SteamUnavailableException(); }
catch (JsonException) { throw new SteamUnavailableException(); }
catch (KeyNotFoundException) { throw new SteamUnavailableException(); }
}
}
public sealed class SteamUnavailableException : Exception;
+21
View File
@@ -0,0 +1,21 @@
using Microsoft.AspNetCore.Identity;
namespace ShellcoreDB;
public sealed class Auth(UserManager<IdentityAccount> users, Sessions sessions)
{
public async Task<AccountData?> Register(string username, string password, CancellationToken cancellationToken)
{
var user = new IdentityAccount { UserName = username };
var result = await users.CreateAsync(user, password);
return result.Succeeded ? new(user.Id, user.UserName) : null;
}
public async Task<LoginData?> Login(string username, string password, CancellationToken cancellationToken)
{
var user = await users.FindByNameAsync(username);
if (user is null || user.Status != "active" || !await users.CheckPasswordAsync(user, password))
return null;
return await sessions.Issue(user.Id, user.UserName, cancellationToken);
}
}
+37
View File
@@ -0,0 +1,37 @@
using System.Security.Cryptography;
using Dapper;
namespace ShellcoreDB;
public sealed class Sessions(Database database, TimeSpan lifetime)
{
public async Task<LoginData> Issue(Guid accountId, string username, CancellationToken cancellationToken)
{
var token = Convert.ToBase64String(RandomNumberGenerator.GetBytes(32))
.TrimEnd('=').Replace('+', '-').Replace('/', '_');
var expiresAt = DateTime.UtcNow.Add(lifetime);
await using var connection = await database.Open(cancellationToken);
await connection.ExecuteAsync(new CommandDefinition(
"INSERT INTO sessions (accountId, tokenHash, expiresAt) VALUES (@accountId, @tokenHash, @expiresAt)",
new { accountId, tokenHash = Hash(token), expiresAt }, cancellationToken: cancellationToken));
return new(accountId, username, token, expiresAt);
}
public async Task<ValidationData?> Validate(string token, CancellationToken cancellationToken)
{
await using var connection = await database.Open(cancellationToken);
return await connection.QuerySingleOrDefaultAsync<ValidationData>(new CommandDefinition(
"SELECT s.accountId, s.expiresAt FROM sessions s JOIN accounts a ON a.id = s.accountId WHERE s.tokenHash = @tokenHash AND s.expiresAt > NOW() AND s.revokedAt IS NULL AND a.status = 'active'",
new { tokenHash = Hash(token) }, cancellationToken: cancellationToken));
}
public async Task<bool> Revoke(string token, CancellationToken cancellationToken)
{
await using var connection = await database.Open(cancellationToken);
return await connection.ExecuteScalarAsync<Guid?>(new CommandDefinition(
"UPDATE sessions SET revokedAt = NOW() WHERE tokenHash = @tokenHash AND revokedAt IS NULL RETURNING id",
new { tokenHash = Hash(token) }, cancellationToken: cancellationToken)) is not null;
}
private static string Hash(string token) => Convert.ToHexString(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(token)));
}
@@ -0,0 +1,37 @@
-- Apply to an existing database created from the original shellcore.sql.
-- This intentionally refuses to discard any populated plaintext email values.
BEGIN;
DO $$
BEGIN
IF EXISTS (SELECT 1 FROM accounts WHERE email IS NOT NULL) THEN
RAISE EXCEPTION 'Existing email data requires a separately designed encrypted mail-store migration';
END IF;
IF EXISTS (SELECT 1 FROM accounts WHERE username IS NULL) THEN
RAISE EXCEPTION 'Every existing account needs a username before migration';
END IF;
IF EXISTS (
SELECT 1 FROM accounts a
WHERE a.passwordHash IS NULL
AND NOT EXISTS (SELECT 1 FROM externalAccounts e WHERE e.accountId = a.id AND e.provider = 'steam')
) THEN
RAISE EXCEPTION 'An account without a local password needs a verified Steam link before migration';
END IF;
END $$;
CREATE TABLE IF NOT EXISTS localCredentials (
accountId UUID PRIMARY KEY REFERENCES accounts (id) ON DELETE CASCADE,
passwordHash TEXT NOT NULL
);
INSERT INTO localCredentials (accountId, passwordHash)
SELECT id, passwordHash FROM accounts WHERE passwordHash IS NOT NULL
ON CONFLICT (accountId) DO NOTHING;
ALTER TABLE accounts ALTER COLUMN username SET NOT NULL;
DROP INDEX IF EXISTS accountsEmailUnique;
ALTER TABLE accounts DROP COLUMN passwordHash;
ALTER TABLE accounts DROP COLUMN emailVerified;
ALTER TABLE accounts DROP COLUMN email;
COMMIT;
+39
View File
@@ -0,0 +1,39 @@
CREATE TABLE IF NOT EXISTS accounts (
id UUID PRIMARY KEY DEFAULT gen_random_uuid (),
username VARCHAR(32) NOT NULL,
displayName VARCHAR(64),
avatarURL TEXT,
status TEXT NOT NULL DEFAULT 'active' CHECK (status in ('active', 'suspended', 'disabled')),
createdAt TIMESTAMPTZ NOT NULL DEFAULT NOW (),
updatedAt TIMESTAMPTZ NOT NULL DEFAULT NOW (),
lastLoginAt TIMESTAMPTZ
);
CREATE TABLE IF NOT EXISTS localCredentials (
accountId UUID PRIMARY KEY REFERENCES accounts (id) ON DELETE CASCADE,
passwordHash TEXT NOT NULL
);
CREATE TABLE externalAccounts (
id UUID PRIMARY KEY DEFAULT gen_random_uuid (),
accountId UUID NOT NULL REFERENCES accounts (id) ON DELETE CASCADE,
provider TEXT NOT NULL,
providerUserId TEXT NOT NULL,
linkedAt TIMESTAMPTZ NOT NULL DEFAULT NOW (),
UNIQUE (provider, providerUserId),
UNIQUE (accountId, provider)
);
CREATE UNIQUE INDEX IF NOT EXISTS accountsUsernameUnique ON accounts (LOWER(username));
CREATE TABLE IF NOT EXISTS sessions (
id UUID PRIMARY KEY DEFAULT gen_random_uuid (),
accountId UUID NOT NULL REFERENCES accounts (id) ON DELETE CASCADE,
tokenHash TEXT NOT NULL UNIQUE,
createdAt TIMESTAMPTZ NOT NULL DEFAULT NOW (),
expiresAt TIMESTAMPTZ NOT NULL,
lastUsedAt TIMESTAMPTZ,
revokedAt TIMESTAMPTZ
);
CREATE INDEX IF NOT EXISTS lookUp ON sessions (accountId);