diff --git a/.gitignore b/.gitignore
index cd42ee3..405735b 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,2 +1,6 @@
bin/
obj/
+/third-party/packages/
+.env
+appsettings.Development.json
+appsettings.Production.json
diff --git a/NuGet.Config b/NuGet.Config
new file mode 100644
index 0000000..3447f0c
--- /dev/null
+++ b/NuGet.Config
@@ -0,0 +1,6 @@
+
+
+
+
+
+
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..05f2460
--- /dev/null
+++ b/README.md
@@ -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.
diff --git a/ShellcoreDB.csproj b/ShellcoreDB.csproj
index da8aa6f..4cb36c7 100644
--- a/ShellcoreDB.csproj
+++ b/ShellcoreDB.csproj
@@ -1,11 +1,13 @@
-
+
net10.0
enable
enable
+ true
+
diff --git a/appsettings.json b/appsettings.json
new file mode 100644
index 0000000..33931eb
--- /dev/null
+++ b/appsettings.json
@@ -0,0 +1,6 @@
+{
+ "ConnectionStrings": {
+ "Shellcore": ""
+ },
+ "ShellcoreServiceKey": ""
+}
diff --git a/auth.cs b/auth.cs
deleted file mode 100644
index e69de29..0000000
diff --git a/database.cs b/database.cs
deleted file mode 100644
index d82c017..0000000
--- a/database.cs
+++ /dev/null
@@ -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);
- }
-}
diff --git a/scripts/Database.cs b/scripts/Database.cs
new file mode 100644
index 0000000..043ed2d
--- /dev/null
+++ b/scripts/Database.cs
@@ -0,0 +1,8 @@
+using Npgsql;
+
+namespace ShellcoreDB;
+
+public sealed class Database(NpgsqlDataSource dataSource)
+{
+ public ValueTask Open(CancellationToken cancellationToken) => dataSource.OpenConnectionAsync(cancellationToken);
+}
diff --git a/scripts/IdentityAccountStore.cs b/scripts/IdentityAccountStore.cs
new file mode 100644
index 0000000..44a43e5
--- /dev/null
+++ b/scripts/IdentityAccountStore.cs
@@ -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
+{
+ public Task GetUserIdAsync(IdentityAccount user, CancellationToken cancellationToken) => Task.FromResult(user.Id.ToString("D"));
+ public Task GetUserNameAsync(IdentityAccount user, CancellationToken cancellationToken) => Task.FromResult(user.UserName);
+ public Task SetUserNameAsync(IdentityAccount user, string? userName, CancellationToken cancellationToken)
+ {
+ user.UserName = userName ?? "";
+ return Task.CompletedTask;
+ }
+ public Task 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 GetPasswordHashAsync(IdentityAccount user, CancellationToken cancellationToken) => Task.FromResult(user.PasswordHash);
+ public Task HasPasswordAsync(IdentityAccount user, CancellationToken cancellationToken) => Task.FromResult(user.PasswordHash is not null);
+
+ public async Task 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(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 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 DeleteAsync(IdentityAccount user, CancellationToken cancellationToken) =>
+ throw new NotSupportedException("Account deletion requires a separate audited workflow.");
+
+ public async Task 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(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 FindByNameAsync(string normalizedUserName, CancellationToken cancellationToken)
+ {
+ await using var connection = await database.Open(cancellationToken);
+ return await connection.QuerySingleOrDefaultAsync(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() { }
+}
diff --git a/scripts/Models.cs b/scripts/Models.cs
new file mode 100644
index 0000000..8b47697
--- /dev/null
+++ b/scripts/Models.cs
@@ -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(bool success, T data);
+public sealed record Failure(bool success, ApiError error);
diff --git a/scripts/Program.cs b/scripts/Program.cs
new file mode 100644
index 0000000..d0535a9
--- /dev/null
+++ b/scripts/Program.cs
@@ -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();
+builder.Services.AddIdentityCore(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();
+builder.Services.AddSingleton(new SessionsLifetime(TimeSpan.FromDays(30)));
+builder.Services.AddScoped(provider => new(provider.GetRequiredService(), provider.GetRequiredService().Value));
+builder.Services.AddScoped();
+builder.Services.AddHttpClient(client => client.Timeout = TimeSpan.FromSeconds(10));
+builder.Services.AddScoped();
+builder.Services.AddProblemDetails();
+
+var app = builder.Build();
+app.UseExceptionHandler(errorApp => errorApp.Run(async context =>
+{
+ var exception = context.Features.Get()?.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 { ["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(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(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(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(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