shellcoreDB made... n shi
This commit is contained in:
1 parent
244bd918d6
commit
bcc9894062
19 files changed
+493
-22
No files matched your search
@@ -1,2 +1,6 @@
|
||||
bin/
|
||||
obj/
|
||||
/third-party/packages/
|
||||
.env
|
||||
appsettings.Development.json
|
||||
appsettings.Production.json
|
||||
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<configuration>
|
||||
<config>
|
||||
<add key="globalPackagesFolder" value="third-party/packages" />
|
||||
</config>
|
||||
</configuration>
|
||||
@@ -0,0 +1,42 @@
|
||||
# ShellcoreDB account service
|
||||
|
||||
## Library credits
|
||||
|
||||
Uses [ASP.NET Core and Identity](https://github.com/dotnet/aspnetcore) by Microsoft and contributors (MIT), [Dapper](https://github.com/DapperLib/Dapper) by Sam Saffron, Marc Gravell, Nick Craver, and contributors (Apache 2.0), and [Npgsql](https://github.com/npgsql/npgsql) by Francisco Figueiredo Jr. and contributors (PostgreSQL License). See [third-party](third-party/README.md) for the package inventory.
|
||||
|
||||
Internal account and session API for Zombie Lab. The game client talks to the game server; only trusted server processes call ShellcoreDB. New accounts can use a username and password or a verified Steam ticket. A Steam-only account has no local credential row; every `localCredentials.passwordHash` is required.
|
||||
|
||||
## Setup
|
||||
|
||||
Use .NET 10, PostgreSQL, and `dotnet restore`. Application source and SQL are under [`scripts/`](scripts/). For a new database, apply `scripts/sql/shellcore.sql` once. For a database using the earlier schema, back it up and apply `scripts/sql/migrations/001SeparateCredentialsAndEmail.sql` instead. That migration refuses to discard populated plaintext email values or migrate accounts with no valid credential.
|
||||
|
||||
Set `ConnectionStrings__Shellcore` and `ShellcoreServiceKey` in the service environment. Keep the service key separate from ZombieLabDB's key. A localhost start is:
|
||||
|
||||
```bash
|
||||
export ConnectionStrings__Shellcore='Host=127.0.0.1;Database=shellcore;Username=replace-me;Password=replace-me'
|
||||
export ShellcoreServiceKey='replace-with-a-long-random-secret'
|
||||
export ASPNETCORE_URLS='http://127.0.0.1:5081'
|
||||
dotnet run
|
||||
```
|
||||
|
||||
For Steam sign-in, also set `Steam__AppId`, `Steam__PublisherKey`, and `Steam__Identity`. The identity must match the string used when the native game obtains a web API ticket. Never place the publisher key in Godot or in a URL exposed to players. Steam is optional at startup; `/internal/auth/steam` returns `steamUnavailable` until configured. Use HTTPS between machines, and permit only trusted game servers and future website backends to reach this API.
|
||||
|
||||
## Internal routes
|
||||
|
||||
All routes require `X-Service-Key` and return `{ "success": true, "data": ... }` or `{ "success": false, "error": { "code": "...", "message": "..." } }`.
|
||||
|
||||
| Route | JSON body | Success data |
|
||||
| --- | --- | --- |
|
||||
| `POST /internal/auth/register` | `{"username":"player","password":"long-password"}` | `{accountId, username}`; `201` |
|
||||
| `POST /internal/auth/login` | Same | `{accountId, username, token, expiresAt}` |
|
||||
| `POST /internal/auth/steam` | `{"ticket":"hex-ticket","username":"player"}` | Same login data; username needed only for a new account |
|
||||
| `POST /internal/sessions/validate` | `{"token":"..."}` | `{accountId, expiresAt}` |
|
||||
| `POST /internal/sessions/revoke` | `{"token":"..."}` | `{revoked: true/false}` |
|
||||
|
||||
Username/password registration requires a unique username and a password of 12 to 1024 characters. ASP.NET Core Identity manages usernames and password hashes through a store for the existing tables; no schema migration or password reset is required. Session tokens are random, and only a SHA-256 hash of each token is stored. Sessions expire after 30 days. A suspended or disabled account cannot validate a session. `401` means missing service key, bad credentials, invalid ticket, or invalid session depending on the route; `400` invalid signup input; `403` unavailable account; `409` taken username; `503` database or Steam unavailable; `500` unexpected error.
|
||||
|
||||
Unexpected server errors use `application/problem+json` with standard ProblemDetails fields. They also retain `success: false` and the existing `error: {code, message}` members for current callers. Ordinary validation and authentication errors retain their existing JSON envelope.
|
||||
|
||||
## Email privacy
|
||||
|
||||
The new schema does not collect or store email. Email enrollment and delivery need a separate mail process with a separate encryption key; routine account, game, and database operators should see only usernames. A future encrypted mail store must keep plaintext out of logs, backups, and game API responses. A host administrator with control of the mail process can still access mail while it is being sent.
|
||||
+3
-1
@@ -1,11 +1,13 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<AllowMissingPrunePackageData>true</AllowMissingPrunePackageData>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Dapper" Version="2.1.89" />
|
||||
<PackageReference Include="Npgsql" Version="10.0.3" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"ConnectionStrings": {
|
||||
"Shellcore": ""
|
||||
},
|
||||
"ShellcoreServiceKey": ""
|
||||
}
|
||||
-15
@@ -1,15 +0,0 @@
|
||||
using Npgsql;
|
||||
|
||||
public static class database
|
||||
{
|
||||
private static NpgsqlDataSource? dataSource;
|
||||
|
||||
public static void init()
|
||||
{
|
||||
string connectionString =
|
||||
Environment.GetEnvironmentVariable("SHELLCORE_DB")
|
||||
?? throw new Exception("SHELLCORE_DB not configured");
|
||||
|
||||
dataSource = NpgsqlDataSource.Create(connectionString);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
using Npgsql;
|
||||
|
||||
namespace ShellcoreDB;
|
||||
|
||||
public sealed class Database(NpgsqlDataSource dataSource)
|
||||
{
|
||||
public ValueTask<NpgsqlConnection> Open(CancellationToken cancellationToken) => dataSource.OpenConnectionAsync(cancellationToken);
|
||||
}
|
||||
@@ -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() { }
|
||||
}
|
||||
@@ -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);
|
||||
@@ -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 { }
|
||||
@@ -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; } = "";
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
@@ -1,17 +1,19 @@
|
||||
CREATE TABLE IF NOT EXISTS accounts (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid (),
|
||||
username VARCHAR(32),
|
||||
username VARCHAR(32) NOT NULL,
|
||||
displayName VARCHAR(64),
|
||||
avatarURL TEXT,
|
||||
passwordHash TEXT,
|
||||
email TEXT,
|
||||
emailVerified BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
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,
|
||||
@@ -24,8 +26,6 @@ CREATE TABLE externalAccounts (
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS accountsUsernameUnique ON accounts (LOWER(username));
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS accountsEmailUnique ON accounts (LOWER(email));
|
||||
|
||||
CREATE TABLE IF NOT EXISTS sessions (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid (),
|
||||
accountId UUID NOT NULL REFERENCES accounts (id) ON DELETE CASCADE,
|
||||
Whitespace-only changes.
Vendored
+13
@@ -0,0 +1,13 @@
|
||||
# Third-party libraries
|
||||
|
||||
`packages/` contains restored NuGet packages, separate from this project's own code. It is generated by `dotnet restore` using the repository's `NuGet.Config` and is ignored by Git. Package versions are declared in `ShellcoreDB.csproj`; each package directory includes its upstream package metadata and license information.
|
||||
|
||||
| Library | Version | Role | License and credit |
|
||||
| --- | --- | --- | --- |
|
||||
| [ASP.NET Core / Identity](https://github.com/dotnet/aspnetcore) | .NET 10 shared framework | HTTP and account/password services | MIT; Microsoft and contributors |
|
||||
| [Dapper](https://github.com/DapperLib/Dapper) | 2.1.89 | SQL result mapping | Apache-2.0; Sam Saffron, Marc Gravell, Nick Craver, and contributors |
|
||||
| [Npgsql](https://github.com/npgsql/npgsql) | 10.0.3 | PostgreSQL driver | PostgreSQL License; Francisco Figueiredo Jr. and contributors |
|
||||
| Microsoft.Extensions.DependencyInjection.Abstractions and Microsoft.Extensions.Logging.Abstractions | 10.0.0 | Transitive Npgsql dependencies | MIT; Microsoft and contributors |
|
||||
| Microsoft.AspNetCore.App.Ref | 10.0.14 | ASP.NET Core compile-time reference pack | MIT; Microsoft and contributors |
|
||||
|
||||
The .NET runtime and ASP.NET Core shared framework are installed separately; the `packages/` copy is only a compile-time reference pack. The application code outside this folder is this project's code.
|
||||
Reference in new issue
Block a user