feat: Phase 0 shells, design system, server skeleton, Docker and CI
- Titano.Ui: DESIGN.md tokens (dark/light), generated 16-px icon set, styles for all standard controls, custom chrome window with snap layouts, rail, job bar, Auto/manual slider, chips, toasts. - Titano desktop shell with sections, Settings (language, theme), About and a --capture screenshot mode. - Titano Server skeleton: env/server.json configuration, self-signed TLS with fingerprint, /health, /server/info, i18n endpoint and the embedded admin panel; in-process server tests. - Docker image (multi-arch, PUID/PGID, health check), compose file, Unraid template; CI, release and nightly workflows; changelog tool. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
122 files changed
+6838
-22
No files matched your search
@@ -0,0 +1,79 @@
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Security.Cryptography;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using Titano.Server.Configuration;
|
||||
|
||||
namespace Titano.Server.Hosting;
|
||||
|
||||
/// <summary>
|
||||
/// TLS certificate for Kestrel (BRIEF §14.2): self-signed ECDSA P-256 generated once and kept in /data/tls
|
||||
/// (mode auto), loaded from PEM files (mode pem), or none (mode proxy).
|
||||
/// </summary>
|
||||
public static class CertificateStore
|
||||
{
|
||||
public static X509Certificate2? Load(ServerOptions options, ILogger logger)
|
||||
{
|
||||
switch (options.TlsMode)
|
||||
{
|
||||
case TlsMode.Proxy:
|
||||
return null;
|
||||
case TlsMode.Pem:
|
||||
{
|
||||
var pem = X509Certificate2.CreateFromPemFile(options.TlsCert!, options.TlsKey);
|
||||
return Exportable(pem);
|
||||
}
|
||||
default:
|
||||
{
|
||||
Directory.CreateDirectory(options.TlsPath);
|
||||
var path = Path.Combine(options.TlsPath, "server.pfx");
|
||||
if (File.Exists(path))
|
||||
{
|
||||
var existing = X509CertificateLoader.LoadPkcs12FromFile(path, password: null, X509KeyStorageFlags.Exportable);
|
||||
if (existing.NotAfter > DateTime.UtcNow.AddDays(30)) return existing;
|
||||
logger.LogWarning("Self-signed certificate expires {NotAfter:u}; generating a new one (clients will see a new fingerprint).", existing.NotAfter);
|
||||
}
|
||||
var created = CreateSelfSigned(options.ServerName);
|
||||
File.WriteAllBytes(path, created.Export(X509ContentType.Pkcs12));
|
||||
if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(path, UnixFileMode.UserRead | UnixFileMode.UserWrite);
|
||||
logger.LogInformation("Generated self-signed TLS certificate, SHA-256 fingerprint {Fingerprint}", Fingerprint(created));
|
||||
return created;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>SHA-256 fingerprint as colon-separated upper-case hex, as shown to users for trust-on-first-use.</summary>
|
||||
public static string Fingerprint(X509Certificate2 certificate) =>
|
||||
string.Join(':', certificate.GetCertHash(HashAlgorithmName.SHA256).Select(b => b.ToString("X2", System.Globalization.CultureInfo.InvariantCulture)));
|
||||
|
||||
public static X509Certificate2 CreateSelfSigned(string serverName)
|
||||
{
|
||||
using var key = ECDsa.Create(ECCurve.NamedCurves.nistP256);
|
||||
var request = new CertificateRequest(new X500DistinguishedName($"CN={Sanitize(serverName)}, O=Titano"), key, HashAlgorithmName.SHA256);
|
||||
var san = new SubjectAlternativeNameBuilder();
|
||||
san.AddDnsName("localhost");
|
||||
try
|
||||
{
|
||||
var host = Dns.GetHostName();
|
||||
san.AddDnsName(host);
|
||||
foreach (var address in Dns.GetHostAddresses(host).Where(a => a.AddressFamily is AddressFamily.InterNetwork or AddressFamily.InterNetworkV6))
|
||||
san.AddIpAddress(address);
|
||||
}
|
||||
catch (SocketException)
|
||||
{
|
||||
// Without name resolution the certificate still covers localhost.
|
||||
}
|
||||
san.AddIpAddress(IPAddress.Loopback);
|
||||
request.CertificateExtensions.Add(san.Build());
|
||||
request.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, true));
|
||||
request.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature, true));
|
||||
request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension([new Oid("1.3.6.1.5.5.7.3.1")], false));
|
||||
using var certificate = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddYears(5));
|
||||
return Exportable(certificate);
|
||||
}
|
||||
|
||||
private static X509Certificate2 Exportable(X509Certificate2 certificate) =>
|
||||
X509CertificateLoader.LoadPkcs12(certificate.Export(X509ContentType.Pkcs12), password: null, X509KeyStorageFlags.Exportable);
|
||||
|
||||
private static string Sanitize(string name) => new(name.Where(c => char.IsLetterOrDigit(c) || c is ' ' or '-' or '.').Take(60).ToArray());
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
using System.Collections.Frozen;
|
||||
using System.Reflection;
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace Titano.Server.Hosting;
|
||||
|
||||
/// <summary>
|
||||
/// Serves the admin panel from embedded resources named <c>admin/…</c> (no build step, single-file friendly),
|
||||
/// with strong ETags, conditional GET and SPA fallback to <c>index.html</c>.
|
||||
/// </summary>
|
||||
public sealed class EmbeddedStaticFiles
|
||||
{
|
||||
private static readonly FrozenDictionary<string, string> ContentTypes = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
[".html"] = "text/html; charset=utf-8",
|
||||
[".js"] = "text/javascript; charset=utf-8",
|
||||
[".mjs"] = "text/javascript; charset=utf-8",
|
||||
[".css"] = "text/css; charset=utf-8",
|
||||
[".svg"] = "image/svg+xml",
|
||||
[".png"] = "image/png",
|
||||
[".json"] = "application/json; charset=utf-8",
|
||||
[".ico"] = "image/x-icon",
|
||||
[".woff2"] = "font/woff2",
|
||||
}.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
private readonly FrozenDictionary<string, (byte[] Content, string ETag, string ContentType)> _files;
|
||||
|
||||
public EmbeddedStaticFiles(Assembly assembly, string prefix)
|
||||
{
|
||||
var files = new Dictionary<string, (byte[], string, string)>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var name in assembly.GetManifestResourceNames().Where(n => n.StartsWith(prefix, StringComparison.Ordinal)))
|
||||
{
|
||||
using var stream = assembly.GetManifestResourceStream(name)!;
|
||||
using var ms = new MemoryStream();
|
||||
stream.CopyTo(ms);
|
||||
var bytes = ms.ToArray();
|
||||
var path = name[prefix.Length..].Replace('\\', '/');
|
||||
var etag = "\"" + Convert.ToHexString(SHA256.HashData(bytes).AsSpan(0, 12)) + "\"";
|
||||
var type = ContentTypes.TryGetValue(Path.GetExtension(path), out var t) ? t : "application/octet-stream";
|
||||
files[path] = (bytes, etag, type);
|
||||
}
|
||||
_files = files.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
public int Count => _files.Count;
|
||||
|
||||
public async Task<bool> TryServeAsync(HttpContext context, string relativePath)
|
||||
{
|
||||
var path = relativePath.TrimStart('/');
|
||||
if (path.Length == 0) path = "index.html";
|
||||
if (!_files.TryGetValue(path, out var file))
|
||||
{
|
||||
// Client-side routes (no extension) fall back to the shell.
|
||||
if (Path.HasExtension(path) || !_files.TryGetValue("index.html", out file)) return false;
|
||||
}
|
||||
var response = context.Response;
|
||||
response.Headers.ETag = file.ETag;
|
||||
response.Headers.CacheControl = path.EndsWith(".html", StringComparison.OrdinalIgnoreCase) ? "no-cache" : "public, max-age=3600";
|
||||
response.Headers.XContentTypeOptions = "nosniff";
|
||||
if (context.Request.Headers.IfNoneMatch == file.ETag)
|
||||
{
|
||||
response.StatusCode = StatusCodes.Status304NotModified;
|
||||
return true;
|
||||
}
|
||||
response.ContentType = file.ContentType;
|
||||
response.ContentLength = file.Content.Length;
|
||||
if (!HttpMethods.IsHead(context.Request.Method)) await response.Body.WriteAsync(file.Content, context.RequestAborted);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
using Titano.Core.Diagnostics;
|
||||
using CoreLogLevel = Titano.Core.Diagnostics.LogLevel;
|
||||
using MsLogLevel = Microsoft.Extensions.Logging.LogLevel;
|
||||
|
||||
namespace Titano.Server.Hosting;
|
||||
|
||||
/// <summary>In-house structured file logging for ASP.NET Core (rotating daily files under /data/logs).</summary>
|
||||
public sealed class FileLoggerProvider(FileLogSink sink) : ILoggerProvider
|
||||
{
|
||||
public ILogger CreateLogger(string categoryName) => new FileLogger(sink, categoryName);
|
||||
|
||||
public void Dispose() => sink.Dispose();
|
||||
|
||||
private sealed class FileLogger(FileLogSink sink, string category) : ILogger
|
||||
{
|
||||
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
|
||||
|
||||
public bool IsEnabled(MsLogLevel logLevel) => logLevel >= MsLogLevel.Information;
|
||||
|
||||
public void Log<TState>(MsLogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
|
||||
{
|
||||
if (!IsEnabled(logLevel)) return;
|
||||
var level = logLevel switch
|
||||
{
|
||||
MsLogLevel.Trace => CoreLogLevel.Trace,
|
||||
MsLogLevel.Debug => CoreLogLevel.Debug,
|
||||
MsLogLevel.Information => CoreLogLevel.Info,
|
||||
MsLogLevel.Warning => CoreLogLevel.Warning,
|
||||
_ => CoreLogLevel.Error,
|
||||
};
|
||||
sink.Write(level, category, formatter(state, exception), exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Bridges engine logging (Titano.Core.Diagnostics.Log) into ASP.NET Core logging.</summary>
|
||||
public sealed class LoggerSink(ILoggerFactory factory) : ILogSink
|
||||
{
|
||||
public void Write(CoreLogLevel level, string category, string message, Exception? exception)
|
||||
{
|
||||
var logger = factory.CreateLogger("Titano." + category);
|
||||
var ms = level switch
|
||||
{
|
||||
CoreLogLevel.Trace => MsLogLevel.Trace,
|
||||
CoreLogLevel.Debug => MsLogLevel.Debug,
|
||||
CoreLogLevel.Info => MsLogLevel.Information,
|
||||
CoreLogLevel.Warning => MsLogLevel.Warning,
|
||||
_ => MsLogLevel.Error,
|
||||
};
|
||||
#pragma warning disable CA2254 // Engine messages are preformatted.
|
||||
logger.Log(ms, exception, message);
|
||||
#pragma warning restore CA2254
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
using Titano.Server.Configuration;
|
||||
|
||||
namespace Titano.Server.Hosting;
|
||||
|
||||
/// <summary>
|
||||
/// <c>Titano.Server --healthcheck</c>: probes the local /health endpoint and exits 0/1, so the container
|
||||
/// HEALTHCHECK needs no curl/wget in the image.
|
||||
/// </summary>
|
||||
public static class HealthProbe
|
||||
{
|
||||
public static async Task<int> RunAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
var port = ServerOptions.Load().HttpPort;
|
||||
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(5) };
|
||||
using var response = await http.GetAsync(new Uri($"http://127.0.0.1:{port}/health")).ConfigureAwait(false);
|
||||
return response.IsSuccessStatusCode ? 0 : 1;
|
||||
}
|
||||
catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or InvalidOperationException)
|
||||
{
|
||||
await Console.Error.WriteLineAsync(ex.Message).ConfigureAwait(false);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
using Microsoft.AspNetCore.HttpOverrides;
|
||||
using Microsoft.AspNetCore.Server.Kestrel.Core;
|
||||
using Titano.Core.Diagnostics;
|
||||
using Titano.Protocol;
|
||||
using Titano.Server.Api;
|
||||
using Titano.Server.Configuration;
|
||||
|
||||
namespace Titano.Server.Hosting;
|
||||
|
||||
/// <summary>Builds the Titano Server web application from <see cref="ServerOptions"/> (used by Program and tests).</summary>
|
||||
public static class ServerHost
|
||||
{
|
||||
public static WebApplication Build(ServerOptions options, string[] args)
|
||||
{
|
||||
Directory.CreateDirectory(options.DataPath);
|
||||
Directory.CreateDirectory(options.LogPath);
|
||||
|
||||
var builder = WebApplication.CreateSlimBuilder(args);
|
||||
builder.Logging.ClearProviders();
|
||||
builder.Logging.AddSimpleConsole(c => c.SingleLine = true);
|
||||
builder.Logging.AddProvider(new FileLoggerProvider(new FileLogSink(options.LogPath, "server")));
|
||||
builder.Logging.AddFilter("Microsoft.AspNetCore", Microsoft.Extensions.Logging.LogLevel.Warning);
|
||||
builder.Logging.AddFilter("Microsoft.Hosting.Lifetime", Microsoft.Extensions.Logging.LogLevel.Information);
|
||||
|
||||
using var bootLoggerFactory = LoggerFactory.Create(l => l.AddSimpleConsole(c => c.SingleLine = true));
|
||||
var certificate = CertificateStore.Load(options, bootLoggerFactory.CreateLogger("Titano.Server"));
|
||||
var state = new ServerState { TlsFingerprint = certificate is null ? null : CertificateStore.Fingerprint(certificate) };
|
||||
|
||||
builder.WebHost.ConfigureKestrel(k =>
|
||||
{
|
||||
k.AddServerHeader = false;
|
||||
k.Limits.MaxRequestBodySize = options.ChunkSizeBytes + 64 * 1024;
|
||||
k.ListenAnyIP(options.HttpPort);
|
||||
if (certificate is not null) k.ListenAnyIP(options.HttpsPort, l =>
|
||||
{
|
||||
l.Protocols = HttpProtocols.Http1AndHttp2;
|
||||
l.UseHttps(certificate);
|
||||
});
|
||||
});
|
||||
builder.Services.AddSingleton(options);
|
||||
builder.Services.AddSingleton(state);
|
||||
builder.Services.ConfigureHttpJsonOptions(j => j.SerializerOptions.TypeInfoResolverChain.Insert(0, ProtocolJson.Default));
|
||||
if (options.TlsMode == TlsMode.Proxy)
|
||||
{
|
||||
builder.Services.Configure<ForwardedHeadersOptions>(f =>
|
||||
{
|
||||
f.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedHost;
|
||||
f.KnownIPNetworks.Clear();
|
||||
f.KnownProxies.Clear();
|
||||
});
|
||||
}
|
||||
|
||||
var app = builder.Build();
|
||||
Log.SetSink(new LoggerSink(app.Services.GetRequiredService<ILoggerFactory>()));
|
||||
var logger = app.Logger;
|
||||
logger.LogInformation("Titano Server {Version} · archive {Archive} · data {Data} · TLS {Tls}{Fingerprint}",
|
||||
SystemEndpoints.Version, options.ArchivePath, options.DataPath, options.TlsMode,
|
||||
state.TlsFingerprint is null ? string.Empty : " · SHA-256 " + state.TlsFingerprint);
|
||||
|
||||
if (options.TlsMode == TlsMode.Proxy) app.UseForwardedHeaders();
|
||||
|
||||
app.Use(async (context, next) =>
|
||||
{
|
||||
context.Response.Headers[ApiVersion.Header] = ApiVersion.Current.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
context.Response.Headers.XContentTypeOptions = "nosniff";
|
||||
context.Response.Headers["Referrer-Policy"] = "no-referrer";
|
||||
try
|
||||
{
|
||||
await next(context);
|
||||
}
|
||||
catch (Exception ex) when (!context.Response.HasStarted && ex is not OperationCanceledException)
|
||||
{
|
||||
logger.LogError(ex, "Unhandled error on {Method} {Path}", context.Request.Method, context.Request.Path);
|
||||
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
|
||||
await context.Response.WriteAsJsonAsync(new ApiError("internal", "Unexpected server error."), ProtocolJson.Default.ApiError);
|
||||
}
|
||||
});
|
||||
|
||||
var admin = new EmbeddedStaticFiles(typeof(ServerHost).Assembly, "admin/");
|
||||
app.MapGet("/", () => Results.Redirect("/admin/"));
|
||||
app.MapMethods("/admin/{**path}", ["GET", "HEAD"], async (HttpContext context, string? path) =>
|
||||
{
|
||||
// Relative asset URLs need the trailing slash.
|
||||
if (!context.Request.Path.Value!.EndsWith('/') && string.IsNullOrEmpty(path))
|
||||
{
|
||||
context.Response.Redirect("/admin/");
|
||||
return;
|
||||
}
|
||||
if (!await admin.TryServeAsync(context, path ?? string.Empty)) context.Response.StatusCode = StatusCodes.Status404NotFound;
|
||||
});
|
||||
|
||||
SystemEndpoints.Map(app, options, state);
|
||||
|
||||
app.MapFallback("/api/{**path}", () => Results.Json(new ApiError("not_found", "No such endpoint."), ProtocolJson.Default.ApiError, statusCode: 404));
|
||||
app.Lifetime.ApplicationStopping.Register(() => logger.LogInformation("Titano Server stopping"));
|
||||
return app;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user