feat(setup): Erstinstallation ueber den Update-Agent, Installationskonto, Downloads
Bisher gab es nur den Update-Weg: eine Anwendung musste bereits installiert und eingerichtet sein, damit sich etwas aktualisieren liess. Die Erstinstallation auf einem neuen System war Handarbeit - Paket kopieren, Konfiguration abtippen, Token besorgen. Setup-API (neu) - POST /api/setup/v1/login tauscht Benutzername und Passwort gegen ein Token mit 30 Minuten Gueltigkeit und ausschliesslich setup:install. Es wird nicht mitgeschrieben und lebt im Installer nur im Speicher. - GET /api/setup/v1/catalog zeigt nur, was zur Laufzeitkennung des anfragenden Systems passt. Ein Projekt mit ausschliesslich Windows-Paket taucht auf einem Linux-Rechner gar nicht erst auf. - POST /api/setup/v1/token stellt das Dauertoken der Anwendung aus. Welche Rechte vergeben werden, entscheidet der Server; die Anfrage kann nur einschraenken. Sonst waere der Umweg ueber ein kurzlebiges Token wirkungslos. Rollentrennung (Migration 012) - dc_users bekommt role, disabled und last_login_at. Die Rolle "installer" darf sich ueber den Setup-Weg anmelden und nicht am WebUI. Die Zugangsdaten werden auf jedem Zielsystem eingetippt; mit einem Administratorkonto verteilte man damit den Zugang zu Tokens, Lizenzen und Monitoren auf jeden Rechner, auf dem je etwas installiert wurde. - Auth::verifyCredentials() prueft sessionfrei, damit Setup- und WebUI-Login nicht zwei verschiedene Haertungsgrade haben (Drosselung, Timing-Angleichung, Rehash gelten fuer beide). - Konten mit hinterlegtem TOTP-Geheimnis werden am Setup-Weg mit 501 abgewiesen. Eine TOTP-Pruefung gibt es im Deploymentcenter noch nicht; sie stillschweigend zu uebergehen waere ein Rueckschritt. - Benutzerverwaltung im WebUI - es gab bisher gar keine, nur den einen von install_db.php angelegten Admin. Das letzte aktive Administratorkonto laesst sich weder deaktivieren noch loeschen. Installer - update-agent --action install fuehrt durch Anmeldung, Auswahl, Zielverzeichnis, Installation und Einrichtung. Die Dateien kommen ueber denselben Pfad wie ein Update - mit Pruefsumme, Signatur, Staging und Rollback. Ein zweiter Download-Weg waere ein zweiter Ort fuer dieselben Fehler. - --action configure holt die Einrichtung nachtraeglich. - setup.json im Paket beschreibt die benoetigten Werte. Bewusst im Paket und nicht zentral: so ist sie mit der Anwendung versioniert. - Gefragt wird nur, was uebrig bleibt: bereits gesetzt -> detect:... -> provision -> fragen. Platzhalter wie changeme oder <dein-wert> gelten dabei nicht als eingerichtet, sonst liefe die Anwendung mit der Vorlage los. - SetupWriter erhaelt vorhandene Inhalte. Eine appsettings.json fuehrt neben den abgefragten Werten meist Logging und anderes; sie neu zu erzeugen waere bequemer und verloere das - bei einer Neuinstallation ohne Backup. int und bool landen als JSON-Typ, nicht als Zeichenkette. Downloads - scripts/build_installer.ps1 baut selbstenthaltende Einzeldateien fuer win-x64, linux-x64 und linux-arm64 (rund 34 MB, .NET-Laufzeit inbegriffen). Ohne NativeAOT und ohne Trimming: Spectre.Console loest ueber Reflexion auf und braeche sonst erst beim Anwender. - scripts/upload_installer.py laedt sie nach /installer/. Getrennt von deploy.py, das client-dotnet bewusst ausklammert. - Bereich "Installer" auf der UpdateService-Seite mit Groessen, Pruefsummen und den wget-Befehlen; die Angaben stammen aus installer.json statt aus fest eingetragenem Text. - install.sh und install.ps1 laden, pruefen die Pruefsumme und legen ab - sie richten bewusst nichts selbst ein. Das Manifest wird BOM-frei geschrieben, sonst scheitert json_decode() daran. Enthaelt ausserdem die bislang nicht committete Arbeit an den RocketChat-Benachrichtigungen (Migrationen 010 und 011) sowie die Loesch- und Editierfunktion des UpdateService; die betroffenen Dateien liessen sich nicht getrennt stagen. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5
parent
2388b5abe1
commit
c8f3e78635
@@ -0,0 +1,128 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Deploymentcenter.Client.Models
|
||||
{
|
||||
/// <summary>
|
||||
/// Beschreibt, was eine Anwendung zum Laufen braucht - als Datei
|
||||
/// <c>setup.json</c> im Wurzelverzeichnis des Pakets, neben der
|
||||
/// manifest.json.
|
||||
///
|
||||
/// Bewusst im Paket und nicht zentral im Deploymentcenter: so ist die
|
||||
/// Beschreibung mit der Anwendung versioniert. Braucht Version 2.0 ein
|
||||
/// Feld mehr als 1.9, stimmt es automatisch - eine zweite Pflegestelle
|
||||
/// wuerde frueher oder spaeter auseinanderlaufen.
|
||||
///
|
||||
/// Fehlt die Datei, laesst sich die Anwendung trotzdem installieren; der
|
||||
/// Installer entpackt sie dann nur und fragt nichts ab.
|
||||
/// </summary>
|
||||
public class SetupDefinition
|
||||
{
|
||||
/// <summary>Format-Version dieser Datei.</summary>
|
||||
[JsonPropertyName("schema")]
|
||||
public int Schema { get; set; } = 1;
|
||||
|
||||
/// <summary>Anzeigename, sonst wird der Projekt-Slug verwendet.</summary>
|
||||
[JsonPropertyName("displayName")]
|
||||
public string DisplayName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>Kurzer Hinweistext, der vor der Abfrage angezeigt wird.</summary>
|
||||
[JsonPropertyName("description")]
|
||||
public string Description { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>Wohin die ermittelten Werte geschrieben werden.</summary>
|
||||
[JsonPropertyName("targets")]
|
||||
public List<SetupTarget> Targets { get; set; } = new List<SetupTarget>();
|
||||
|
||||
/// <summary>Die benoetigten Werte.</summary>
|
||||
[JsonPropertyName("fields")]
|
||||
public List<SetupField> Fields { get; set; } = new List<SetupField>();
|
||||
}
|
||||
|
||||
/// <summary>Eine Datei, in die Werte geschrieben werden.</summary>
|
||||
public class SetupTarget
|
||||
{
|
||||
/// <summary>Pfad relativ zum Installationsverzeichnis.</summary>
|
||||
[JsonPropertyName("file")]
|
||||
public string File { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>"json" oder "env".</summary>
|
||||
[JsonPropertyName("format")]
|
||||
public string Format { get; set; } = "json";
|
||||
|
||||
/// <summary>
|
||||
/// Kennung, ueber die Felder dieser Datei zugeordnet werden. Ohne
|
||||
/// Angabe schreiben alle Felder in das erste Ziel.
|
||||
/// </summary>
|
||||
[JsonPropertyName("id")]
|
||||
public string Id { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>Ein einzelner Konfigurationswert.</summary>
|
||||
public class SetupField
|
||||
{
|
||||
/// <summary>
|
||||
/// Schluessel im Ziel. Bei JSON trennt ein Doppelpunkt die Ebenen
|
||||
/// ("ConnectionStrings:Main"), passend zur Schreibweise von
|
||||
/// Microsoft.Extensions.Configuration.
|
||||
/// </summary>
|
||||
[JsonPropertyName("key")]
|
||||
public string Key { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>Beschriftung fuer die Abfrage.</summary>
|
||||
[JsonPropertyName("label")]
|
||||
public string Label { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>Erlaeuterung, die unter der Frage steht.</summary>
|
||||
[JsonPropertyName("help")]
|
||||
public string Help { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>string | secret | url | int | bool | enum</summary>
|
||||
[JsonPropertyName("type")]
|
||||
public string Type { get; set; } = "string";
|
||||
|
||||
/// <summary>Muss ein Wert vorliegen?</summary>
|
||||
[JsonPropertyName("required")]
|
||||
public bool Required { get; set; } = true;
|
||||
|
||||
/// <summary>Vorbelegung.</summary>
|
||||
[JsonPropertyName("default")]
|
||||
public string Default { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Woher der Wert kommt, wenn nicht gefragt werden soll:
|
||||
/// detect:hostname | detect:platform | detect:installdir | detect:username
|
||||
/// provision - Token beim Deploymentcenter anfordern
|
||||
/// ask - Vorgabe: nachfragen
|
||||
/// </summary>
|
||||
[JsonPropertyName("source")]
|
||||
public string Source { get; set; } = "ask";
|
||||
|
||||
/// <summary>Rechte fuer source = provision.</summary>
|
||||
[JsonPropertyName("scopes")]
|
||||
public List<string> Scopes { get; set; } = new List<string>();
|
||||
|
||||
/// <summary>Auswahlmoeglichkeiten fuer type = enum.</summary>
|
||||
[JsonPropertyName("options")]
|
||||
public List<string> Options { get; set; } = new List<string>();
|
||||
|
||||
/// <summary>Regulaerer Ausdruck, gegen den der Wert geprueft wird.</summary>
|
||||
[JsonPropertyName("validate")]
|
||||
public string Validate { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>Meldung, wenn die Pruefung fehlschlaegt.</summary>
|
||||
[JsonPropertyName("validationMessage")]
|
||||
public string ValidationMessage { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>Kennung des Ziels aus <see cref="SetupTarget.Id"/>.</summary>
|
||||
[JsonPropertyName("target")]
|
||||
public string Target { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>Wird der Wert verdeckt eingegeben und nicht angezeigt?</summary>
|
||||
[JsonIgnore]
|
||||
public bool IsSecret =>
|
||||
string.Equals(Type, "secret", StringComparison.OrdinalIgnoreCase)
|
||||
|| string.Equals(Source, "provision", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,329 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net.Http;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Deploymentcenter.Client
|
||||
{
|
||||
/// <summary>Ergebnis einer Setup-Anmeldung.</summary>
|
||||
public sealed class SetupSession
|
||||
{
|
||||
public string Token { get; set; } = string.Empty;
|
||||
public string Role { get; set; } = string.Empty;
|
||||
public DateTimeOffset ExpiresAt { get; set; }
|
||||
|
||||
public bool IsExpired => DateTimeOffset.UtcNow >= ExpiresAt;
|
||||
|
||||
/// <summary>Verbleibende Gueltigkeit, nie negativ.</summary>
|
||||
public TimeSpan Remaining
|
||||
{
|
||||
get
|
||||
{
|
||||
var left = ExpiresAt - DateTimeOffset.UtcNow;
|
||||
return left < TimeSpan.Zero ? TimeSpan.Zero : left;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Eine installierbare Anwendung aus dem Katalog.</summary>
|
||||
public sealed class CatalogEntry
|
||||
{
|
||||
public string Slug { get; set; } = string.Empty;
|
||||
public string Name { get; set; } = string.Empty;
|
||||
public string? Notes { get; set; }
|
||||
public List<CatalogChannel> Channels { get; set; } = new List<CatalogChannel>();
|
||||
}
|
||||
|
||||
/// <summary>Ein Kanal mit dem dort neuesten Release.</summary>
|
||||
public sealed class CatalogChannel
|
||||
{
|
||||
public string Channel { get; set; } = "prod";
|
||||
public string Version { get; set; } = string.Empty;
|
||||
public string Platform { get; set; } = PlatformId.Any;
|
||||
public long SizeBytes { get; set; }
|
||||
public bool IsCritical { get; set; }
|
||||
public bool Signed { get; set; }
|
||||
public string? ReleaseNotes { get; set; }
|
||||
public string DownloadUrl { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>Fehler beim Ansprechen der Setup-Schnittstelle.</summary>
|
||||
public sealed class SetupException : Exception
|
||||
{
|
||||
public SetupException(string message, string code = "") : base(message)
|
||||
{
|
||||
Code = code;
|
||||
}
|
||||
|
||||
/// <summary>Stabiler Fehlercode der API, sofern vorhanden.</summary>
|
||||
public string Code { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Spricht /api/setup/v1/* an: anmelden, Katalog holen, Anwendungstoken
|
||||
/// ausstellen lassen.
|
||||
///
|
||||
/// Das Setup-Token lebt ausschliesslich im Speicher dieses Objekts. Es
|
||||
/// wird nirgends abgelegt - es entsteht aus Zugangsdaten, die auf einem
|
||||
/// fremden Rechner eingegeben wurden, und laeuft nach 30 Minuten ohnehin ab.
|
||||
/// </summary>
|
||||
public sealed class SetupClient
|
||||
{
|
||||
private readonly HttpClient _http;
|
||||
private readonly string _baseUrl;
|
||||
|
||||
public SetupClient(string baseUrl, HttpClient? httpClient = null)
|
||||
{
|
||||
_baseUrl = (baseUrl ?? string.Empty).TrimEnd('/');
|
||||
_http = httpClient ?? new HttpClient();
|
||||
}
|
||||
|
||||
public SetupSession? Session { get; private set; }
|
||||
|
||||
/// <summary>Meldet sich an und merkt sich das Token fuer die Folgeaufrufe.</summary>
|
||||
public async Task<SetupSession> LoginAsync(
|
||||
string username,
|
||||
string password,
|
||||
string? hostname = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var payload = new Dictionary<string, object?>
|
||||
{
|
||||
["username"] = username,
|
||||
["password"] = password,
|
||||
["hostname"] = hostname ?? SafeHostName()
|
||||
};
|
||||
|
||||
using var doc = await PostAsync("login", payload, useToken: false, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
var root = doc.RootElement;
|
||||
|
||||
var session = new SetupSession
|
||||
{
|
||||
Token = root.TryGetProperty("setup_token", out var t) ? (t.GetString() ?? string.Empty) : string.Empty,
|
||||
Role = root.TryGetProperty("role", out var r) ? (r.GetString() ?? string.Empty) : string.Empty,
|
||||
};
|
||||
|
||||
int expiresIn = root.TryGetProperty("expires_in", out var e) && e.TryGetInt32(out int seconds)
|
||||
? seconds
|
||||
: 1800;
|
||||
|
||||
// Etwas Sicherheitsabstand, damit ein Aufruf nicht genau auf der
|
||||
// Ablaufgrenze scheitert.
|
||||
session.ExpiresAt = DateTimeOffset.UtcNow.AddSeconds(Math.Max(30, expiresIn - 15));
|
||||
|
||||
if (session.Token.Length == 0)
|
||||
{
|
||||
throw new SetupException("Die Anmeldung lieferte kein Token.", "no_token");
|
||||
}
|
||||
|
||||
Session = session;
|
||||
return session;
|
||||
}
|
||||
|
||||
/// <summary>Holt die auf dieser Plattform installierbaren Anwendungen.</summary>
|
||||
public async Task<List<CatalogEntry>> GetCatalogAsync(
|
||||
string? platform = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
RequireSession();
|
||||
|
||||
string rid = PlatformId.Normalize(platform ?? PlatformId.Current);
|
||||
string url = $"{_baseUrl}/api/setup/v1/catalog?platform={Uri.EscapeDataString(rid)}";
|
||||
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, url);
|
||||
request.Headers.Add("Authorization", "Bearer " + Session!.Token);
|
||||
|
||||
using var response = await _http.SendAsync(request, cancellationToken).ConfigureAwait(false);
|
||||
string body = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
|
||||
|
||||
using var doc = ParseOrThrow(body, response.IsSuccessStatusCode, (int)response.StatusCode);
|
||||
|
||||
var result = new List<CatalogEntry>();
|
||||
|
||||
if (!doc.RootElement.TryGetProperty("projects", out var projects)
|
||||
|| projects.ValueKind != JsonValueKind.Array)
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
foreach (var project in projects.EnumerateArray())
|
||||
{
|
||||
var entry = new CatalogEntry
|
||||
{
|
||||
Slug = GetString(project, "slug"),
|
||||
Name = GetString(project, "name"),
|
||||
Notes = project.TryGetProperty("notes", out var n) && n.ValueKind == JsonValueKind.String
|
||||
? n.GetString()
|
||||
: null
|
||||
};
|
||||
|
||||
if (project.TryGetProperty("channels", out var channels)
|
||||
&& channels.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
foreach (var channel in channels.EnumerateArray())
|
||||
{
|
||||
entry.Channels.Add(new CatalogChannel
|
||||
{
|
||||
Channel = GetString(channel, "channel"),
|
||||
Version = GetString(channel, "version"),
|
||||
Platform = GetString(channel, "platform"),
|
||||
DownloadUrl = GetString(channel, "download_url"),
|
||||
ReleaseNotes = channel.TryGetProperty("release_notes", out var rn) && rn.ValueKind == JsonValueKind.String
|
||||
? rn.GetString()
|
||||
: null,
|
||||
SizeBytes = channel.TryGetProperty("size_bytes", out var sb) && sb.TryGetInt64(out long size) ? size : 0,
|
||||
IsCritical = channel.TryGetProperty("is_critical", out var ic) && ic.ValueKind == JsonValueKind.True,
|
||||
Signed = channel.TryGetProperty("signed", out var sg) && sg.ValueKind == JsonValueKind.True
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
result.Add(entry);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Laesst ein Dauertoken fuer die eingerichtete Anwendung ausstellen.
|
||||
/// Welche Rechte tatsaechlich vergeben werden, entscheidet der Server -
|
||||
/// die Anfrage kann nur einschraenken.
|
||||
/// </summary>
|
||||
public async Task<string> RequestApplicationTokenAsync(
|
||||
string project,
|
||||
IEnumerable<string> scopes,
|
||||
string? hostname = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
RequireSession();
|
||||
|
||||
var payload = new Dictionary<string, object?>
|
||||
{
|
||||
["project"] = project,
|
||||
["scopes"] = new List<string>(scopes),
|
||||
["hostname"] = hostname ?? SafeHostName()
|
||||
};
|
||||
|
||||
using var doc = await PostAsync("token", payload, useToken: true, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
string token = GetString(doc.RootElement, "token");
|
||||
|
||||
if (token.Length == 0)
|
||||
{
|
||||
throw new SetupException("Der Server hat kein Anwendungstoken geliefert.", "no_token");
|
||||
}
|
||||
|
||||
return token;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
private void RequireSession()
|
||||
{
|
||||
if (Session == null)
|
||||
{
|
||||
throw new SetupException("Nicht angemeldet.", "not_authenticated");
|
||||
}
|
||||
|
||||
if (Session.IsExpired)
|
||||
{
|
||||
throw new SetupException(
|
||||
"Die Setup-Sitzung ist abgelaufen. Bitte erneut anmelden.", "session_expired");
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<JsonDocument> PostAsync(
|
||||
string action,
|
||||
Dictionary<string, object?> payload,
|
||||
bool useToken,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (useToken)
|
||||
{
|
||||
RequireSession();
|
||||
}
|
||||
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, $"{_baseUrl}/api/setup/v1/{action}")
|
||||
{
|
||||
Content = new StringContent(JsonSerializer.Serialize(payload), Encoding.UTF8, "application/json")
|
||||
};
|
||||
|
||||
if (useToken)
|
||||
{
|
||||
request.Headers.Add("Authorization", "Bearer " + Session!.Token);
|
||||
}
|
||||
|
||||
using var response = await _http.SendAsync(request, cancellationToken).ConfigureAwait(false);
|
||||
string body = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
|
||||
|
||||
return ParseOrThrow(body, response.IsSuccessStatusCode, (int)response.StatusCode);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Wertet die einheitliche Antwortform aus. Bei einem Fehler wird die
|
||||
/// Meldung des Servers weitergereicht - sie ist fuer Menschen gedacht
|
||||
/// und deutlich hilfreicher als ein blosser Statuscode.
|
||||
/// </summary>
|
||||
private static JsonDocument ParseOrThrow(string body, bool success, int statusCode)
|
||||
{
|
||||
JsonDocument doc;
|
||||
|
||||
try
|
||||
{
|
||||
doc = JsonDocument.Parse(body);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
throw new SetupException(
|
||||
$"Unerwartete Antwort des Servers (HTTP {statusCode}).", "invalid_response");
|
||||
}
|
||||
|
||||
if (success)
|
||||
{
|
||||
return doc;
|
||||
}
|
||||
|
||||
string message = $"HTTP {statusCode}";
|
||||
string code = string.Empty;
|
||||
|
||||
if (doc.RootElement.TryGetProperty("error", out var error)
|
||||
&& error.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
code = GetString(error, "code");
|
||||
string serverMessage = GetString(error, "message");
|
||||
if (serverMessage.Length > 0)
|
||||
{
|
||||
message = serverMessage;
|
||||
}
|
||||
}
|
||||
|
||||
doc.Dispose();
|
||||
throw new SetupException(message, code);
|
||||
}
|
||||
|
||||
private static string GetString(JsonElement element, string property)
|
||||
{
|
||||
return element.TryGetProperty(property, out var value) && value.ValueKind == JsonValueKind.String
|
||||
? (value.GetString() ?? string.Empty)
|
||||
: string.Empty;
|
||||
}
|
||||
|
||||
private static string SafeHostName()
|
||||
{
|
||||
try
|
||||
{
|
||||
return Environment.MachineName;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return "unbekannt";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
|
||||
namespace Deploymentcenter.Client
|
||||
{
|
||||
/// <summary>Ein zu schreibender Konfigurationswert.</summary>
|
||||
public sealed class SetupValue
|
||||
{
|
||||
public SetupValue(string key, string value, string type = "string")
|
||||
{
|
||||
Key = key;
|
||||
Value = value;
|
||||
Type = type;
|
||||
}
|
||||
|
||||
/// <summary>Schluessel, Ebenen durch Doppelpunkt getrennt.</summary>
|
||||
public string Key { get; }
|
||||
|
||||
public string Value { get; }
|
||||
|
||||
/// <summary>string | secret | url | int | bool | enum</summary>
|
||||
public string Type { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Schreibt ermittelte Werte in die Konfigurationsdateien der Anwendung.
|
||||
///
|
||||
/// Durchgaengiges Prinzip: <b>vorhandene Inhalte bleiben erhalten</b>. Eine
|
||||
/// appsettings.json enthaelt neben den abgefragten Werten fast immer noch
|
||||
/// Logging-Einstellungen, Feature-Schalter und anderes. Die Datei neu zu
|
||||
/// erzeugen waere der bequemere Weg und wuerde all das verlieren - und
|
||||
/// zwar genau bei einer Neuinstallation, bei der niemand ein Backup hat.
|
||||
/// </summary>
|
||||
public static class SetupWriter
|
||||
{
|
||||
/// <summary>
|
||||
/// Schreibt Werte in eine JSON-Datei. Ebenen werden aus dem Schluessel
|
||||
/// gebildet: "ConnectionStrings:Main" wird zu
|
||||
/// { "ConnectionStrings": { "Main": ... } }.
|
||||
/// </summary>
|
||||
public static void WriteJson(string path, IEnumerable<SetupValue> values)
|
||||
{
|
||||
JsonObject root = LoadJsonObject(path);
|
||||
|
||||
foreach (var value in values)
|
||||
{
|
||||
string[] segments = SplitKey(value.Key);
|
||||
if (segments.Length == 0)
|
||||
continue;
|
||||
|
||||
JsonObject node = root;
|
||||
|
||||
// Bis zur vorletzten Ebene hinabsteigen und fehlende Objekte
|
||||
// anlegen. Steht dort bereits ein Wert, der kein Objekt ist,
|
||||
// wird er ersetzt - anders liesse sich der Schluessel nicht
|
||||
// abbilden.
|
||||
for (int i = 0; i < segments.Length - 1; i++)
|
||||
{
|
||||
string segment = segments[i];
|
||||
|
||||
if (node[segment] is JsonObject child)
|
||||
{
|
||||
node = child;
|
||||
}
|
||||
else
|
||||
{
|
||||
var created = new JsonObject();
|
||||
node[segment] = created;
|
||||
node = created;
|
||||
}
|
||||
}
|
||||
|
||||
node[segments[segments.Length - 1]] = ToJsonNode(value);
|
||||
}
|
||||
|
||||
EnsureDirectory(path);
|
||||
|
||||
var options = new JsonSerializerOptions { WriteIndented = true };
|
||||
File.WriteAllText(path, root.ToJsonString(options), new UTF8Encoding(false));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Schreibt Werte in eine Datei im Stil von <c>.env</c>. Vorhandene
|
||||
/// Zeilen werden aktualisiert, unbekannte Schluessel angehaengt;
|
||||
/// Kommentare und Reihenfolge bleiben erhalten.
|
||||
/// </summary>
|
||||
public static void WriteEnv(string path, IEnumerable<SetupValue> values)
|
||||
{
|
||||
var pending = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var value in values)
|
||||
{
|
||||
pending[ToEnvKey(value.Key)] = value.Value;
|
||||
}
|
||||
|
||||
var lines = new List<string>();
|
||||
if (File.Exists(path))
|
||||
{
|
||||
lines.AddRange(File.ReadAllLines(path));
|
||||
}
|
||||
|
||||
for (int i = 0; i < lines.Count; i++)
|
||||
{
|
||||
string line = lines[i];
|
||||
string trimmed = line.TrimStart();
|
||||
|
||||
if (trimmed.Length == 0 || trimmed.StartsWith("#", StringComparison.Ordinal))
|
||||
continue;
|
||||
|
||||
int equals = line.IndexOf('=');
|
||||
if (equals <= 0)
|
||||
continue;
|
||||
|
||||
string key = line.Substring(0, equals).Trim();
|
||||
|
||||
if (pending.TryGetValue(key, out string? replacement))
|
||||
{
|
||||
lines[i] = key + "=" + QuoteEnv(replacement);
|
||||
pending.Remove(key);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var entry in pending)
|
||||
{
|
||||
lines.Add(entry.Key + "=" + QuoteEnv(entry.Value));
|
||||
}
|
||||
|
||||
EnsureDirectory(path);
|
||||
File.WriteAllLines(path, lines, new UTF8Encoding(false));
|
||||
}
|
||||
|
||||
/// <summary>Schreibt in das Format, das zum Ziel passt.</summary>
|
||||
public static void Write(string path, string format, IEnumerable<SetupValue> values)
|
||||
{
|
||||
if (string.Equals(format, "env", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
WriteEnv(path, values);
|
||||
return;
|
||||
}
|
||||
|
||||
WriteJson(path, values);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Liest einen bereits vorhandenen Wert aus einer JSON-Datei, damit der
|
||||
/// Installer nicht nach etwas fragt, das schon eingerichtet ist.
|
||||
/// Liefert null, wenn die Datei fehlt oder der Schluessel nicht gesetzt ist.
|
||||
/// </summary>
|
||||
public static string? ReadExistingJson(string path, string key)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!File.Exists(path))
|
||||
return null;
|
||||
|
||||
JsonNode? node = JsonNode.Parse(File.ReadAllText(path));
|
||||
|
||||
foreach (string segment in SplitKey(key))
|
||||
{
|
||||
if (node is not JsonObject obj)
|
||||
return null;
|
||||
|
||||
node = obj[segment];
|
||||
if (node == null)
|
||||
return null;
|
||||
}
|
||||
|
||||
if (node is JsonValue value)
|
||||
{
|
||||
return value.ToString();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
private static JsonObject LoadJsonObject(string path)
|
||||
{
|
||||
if (!File.Exists(path))
|
||||
return new JsonObject();
|
||||
|
||||
try
|
||||
{
|
||||
string content = File.ReadAllText(path);
|
||||
if (string.IsNullOrWhiteSpace(content))
|
||||
return new JsonObject();
|
||||
|
||||
// Kommentare und nachgestellte Kommata sind in appsettings.json
|
||||
// verbreitet, obwohl JSON sie nicht kennt.
|
||||
var options = new JsonNodeOptions { PropertyNameCaseInsensitive = false };
|
||||
var documentOptions = new JsonDocumentOptions
|
||||
{
|
||||
CommentHandling = JsonCommentHandling.Skip,
|
||||
AllowTrailingCommas = true
|
||||
};
|
||||
|
||||
JsonNode? parsed = JsonNode.Parse(content, options, documentOptions);
|
||||
return parsed as JsonObject ?? new JsonObject();
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
// Eine unlesbare Datei zu ueberschreiben hiesse, unbekannten
|
||||
// Inhalt zu verwerfen. Stattdessen wird sie zur Seite gelegt.
|
||||
string backup = path + ".unlesbar-" + DateTime.UtcNow.ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture);
|
||||
try { File.Copy(path, backup, overwrite: false); } catch { }
|
||||
return new JsonObject();
|
||||
}
|
||||
}
|
||||
|
||||
private static JsonNode? ToJsonNode(SetupValue value)
|
||||
{
|
||||
switch ((value.Type ?? string.Empty).ToLowerInvariant())
|
||||
{
|
||||
case "int":
|
||||
return long.TryParse(value.Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out long number)
|
||||
? JsonValue.Create(number)
|
||||
: JsonValue.Create(value.Value);
|
||||
|
||||
case "bool":
|
||||
return bool.TryParse(value.Value, out bool flag)
|
||||
? JsonValue.Create(flag)
|
||||
: JsonValue.Create(value.Value);
|
||||
|
||||
default:
|
||||
return JsonValue.Create(value.Value);
|
||||
}
|
||||
}
|
||||
|
||||
private static string[] SplitKey(string key)
|
||||
{
|
||||
return (key ?? string.Empty)
|
||||
.Split(new[] { ':', '.' }, StringSplitOptions.RemoveEmptyEntries);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// "ConnectionStrings:Main" wird zu CONNECTIONSTRINGS__MAIN - die
|
||||
/// Schreibweise, die .NET fuer Umgebungsvariablen erwartet.
|
||||
/// </summary>
|
||||
private static string ToEnvKey(string key)
|
||||
{
|
||||
if (string.IsNullOrEmpty(key))
|
||||
return key ?? string.Empty;
|
||||
|
||||
// Enthaelt der Schluessel bereits Unterstriche und keine Trenner,
|
||||
// ist er vermutlich schon eine Umgebungsvariable.
|
||||
if (key.IndexOf(':') < 0 && key.IndexOf('.') < 0)
|
||||
return key;
|
||||
|
||||
return string.Join("__", SplitKey(key).Select(s => s.ToUpperInvariant()));
|
||||
}
|
||||
|
||||
private static string QuoteEnv(string value)
|
||||
{
|
||||
if (value == null)
|
||||
return string.Empty;
|
||||
|
||||
bool needsQuotes = value.Length == 0
|
||||
|| value.IndexOfAny(new[] { ' ', '\t', '"', '\'', '#', '$' }) >= 0;
|
||||
|
||||
if (!needsQuotes)
|
||||
return value;
|
||||
|
||||
return "\"" + value.Replace("\\", "\\\\").Replace("\"", "\\\"") + "\"";
|
||||
}
|
||||
|
||||
private static void EnsureDirectory(string path)
|
||||
{
|
||||
string? dir = Path.GetDirectoryName(path);
|
||||
if (!string.IsNullOrEmpty(dir))
|
||||
{
|
||||
Directory.CreateDirectory(dir);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user