RynthServers/Plugins/RynthCore.Plugin.RynthILT/IltWiki/WikiLoginStore.cs

204 lines
8.2 KiB
C#

// WikiLoginStore.cs - The Leaftide wiki sign-in, kept on this PC only (2026-11-27).
//
// The quest guide (IltWikiGuide.cs) reads the server's wiki with the player's own login: a MediaWiki
// bot password (Special:BotPasswords, "Basic rights" only), which the player can revoke on the wiki at
// any time without changing the account's own password. That login is the only secret RynthILT keeps:
// - one file, %APPDATA%\RynthCore\RynthILT\Wiki\wiki-login.dat, the whole record (address, login name,
// password) sealed with Windows DPAPI for the current Windows user (CryptProtectData, no machine
// scope), so another Windows user, or a copy of the file on another PC, can't open it;
// - never in settings.json, the Hub state, profiles, logs, the status JSON, the remote dashboard or
// anything RynthCore shares; never in a chat line or a status line;
// - Sign out (and "/ilt wiki signout") deletes the file.
// The login is tied to the wiki address it was made for: it is only ever sent to that address.
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
namespace RynthCore.Plugin.RynthILT.IltWiki;
/// <summary>A wiki sign-in: the API address it is for, the login name ("YourName@botname") and its password.</summary>
internal sealed class WikiLogin
{
public WikiLogin(string api, string user, string password)
{
Api = api;
User = user;
Password = password;
}
public string Api { get; }
public string User { get; }
public string Password { get; }
/// <summary>Never the password: a WikiLogin that ends up in a log line or a message says only whose it is.</summary>
public override string ToString() => $"wiki login {User} for {WikiAddress.HostOf(Api)}";
}
internal static class WikiLoginStore
{
public const string FileName = "wiki-login.dat";
/// <summary>The tests' scratch folder; null is %APPDATA%\RynthCore\RynthILT\Wiki.</summary>
internal static string? FolderOverride;
public static string Folder => FolderOverride ?? Path.Combine(RynthILTPlugin.SettingsRoot, "Wiki");
public static string FilePath => Path.Combine(Folder, FileName);
/// <summary>A sign-in is saved (it may still be unreadable: <see cref="Load"/> says).</summary>
public static bool Exists
{
get
{
try { return File.Exists(FilePath); }
catch { return false; }
}
}
// Ties the sealed bytes to this use: another program's DPAPI blob doesn't open as a wiki login.
private static readonly byte[] Entropy = Encoding.UTF8.GetBytes("RynthILT.WikiLogin.v1");
/// <summary>Seals and saves the login (written to a temporary file, then moved over the old one).</summary>
public static bool Save(WikiLogin login, out string error)
{
error = string.Empty;
byte[] plain = Array.Empty<byte>();
try
{
plain = Serialize(login);
byte[] sealedBytes = Dpapi.Protect(plain, Entropy);
Directory.CreateDirectory(Folder);
string tmp = FilePath + ".tmp";
File.WriteAllBytes(tmp, sealedBytes);
File.Move(tmp, FilePath, overwrite: true);
return true;
}
catch (Exception ex)
{
error = "couldn't save the sign-in: " + ex.GetType().Name;
return false;
}
finally { Array.Clear(plain); }
}
/// <summary>The saved login, or null (none, or it can't be opened: another Windows user's, damaged).</summary>
public static WikiLogin? Load(out string error)
{
error = string.Empty;
byte[] plain = Array.Empty<byte>();
try
{
if (!File.Exists(FilePath)) return null;
plain = Dpapi.Unprotect(File.ReadAllBytes(FilePath), Entropy);
WikiLogin? login = Deserialize(plain);
if (login == null) error = "the saved sign-in is damaged; sign in again";
return login;
}
catch (Exception)
{
error = "the saved sign-in can't be opened by this Windows user; sign in again";
return null;
}
finally { Array.Clear(plain); }
}
/// <summary>Deletes the saved login (and a left-over temporary file). True when none is left.</summary>
public static bool Delete(out string error)
{
error = string.Empty;
try
{
if (File.Exists(FilePath)) File.Delete(FilePath);
if (File.Exists(FilePath + ".tmp")) File.Delete(FilePath + ".tmp");
return true;
}
catch (Exception ex)
{
error = "couldn't delete " + FilePath + ": " + ex.GetType().Name;
return false;
}
}
private static byte[] Serialize(WikiLogin login)
{
using var ms = new MemoryStream();
using (var w = new Utf8JsonWriter(ms))
{
w.WriteStartObject();
w.WriteNumber("v", 1);
w.WriteString("api", login.Api);
w.WriteString("user", login.User);
w.WriteString("password", login.Password);
w.WriteEndObject();
}
return ms.ToArray();
}
private static WikiLogin? Deserialize(byte[] plain)
{
try
{
using JsonDocument doc = JsonDocument.Parse(plain);
JsonElement r = doc.RootElement;
if (r.ValueKind != JsonValueKind.Object) return null;
string api = Str(r, "api"), user = Str(r, "user"), password = Str(r, "password");
return api.Length == 0 || user.Length == 0 || password.Length == 0 ? null : new WikiLogin(api, user, password);
}
catch (JsonException) { return null; }
}
private static string Str(JsonElement r, string name) =>
r.TryGetProperty(name, out JsonElement e) && e.ValueKind == JsonValueKind.String ? e.GetString() ?? string.Empty : string.Empty;
}
/// <summary>Windows DPAPI for the current user (crypt32 CryptProtectData / CryptUnprotectData), blittable P/Invoke for NativeAOT.</summary>
internal static unsafe class Dpapi
{
[StructLayout(LayoutKind.Sequential)]
private struct DataBlob
{
public int Size;
public IntPtr Data;
}
private const int UiForbidden = 0x1;
[DllImport("crypt32.dll", EntryPoint = "CryptProtectData", SetLastError = true)]
private static extern int CryptProtectData(DataBlob* dataIn, IntPtr description, DataBlob* entropy, IntPtr reserved,
IntPtr prompt, int flags, DataBlob* dataOut);
[DllImport("crypt32.dll", EntryPoint = "CryptUnprotectData", SetLastError = true)]
private static extern int CryptUnprotectData(DataBlob* dataIn, IntPtr description, DataBlob* entropy, IntPtr reserved,
IntPtr prompt, int flags, DataBlob* dataOut);
[DllImport("kernel32.dll", EntryPoint = "LocalFree")]
private static extern IntPtr LocalFree(IntPtr mem);
public static byte[] Protect(byte[] plain, byte[] entropy) => Run(plain, entropy, protect: true);
public static byte[] Unprotect(byte[] sealedBytes, byte[] entropy) => Run(sealedBytes, entropy, protect: false);
private static byte[] Run(byte[] input, byte[] entropy, bool protect)
{
fixed (byte* pIn = input)
fixed (byte* pEnt = entropy)
{
var inBlob = new DataBlob { Size = input.Length, Data = (IntPtr)pIn };
var entBlob = new DataBlob { Size = entropy.Length, Data = (IntPtr)pEnt };
var outBlob = new DataBlob();
int ok = protect
? CryptProtectData(&inBlob, IntPtr.Zero, &entBlob, IntPtr.Zero, IntPtr.Zero, UiForbidden, &outBlob)
: CryptUnprotectData(&inBlob, IntPtr.Zero, &entBlob, IntPtr.Zero, IntPtr.Zero, UiForbidden, &outBlob);
if (ok == 0) throw new InvalidOperationException((protect ? "CryptProtectData" : "CryptUnprotectData") + " failed: " + Marshal.GetLastWin32Error());
try
{
var result = new byte[outBlob.Size];
Marshal.Copy(outBlob.Data, result, 0, outBlob.Size);
if (!protect) new Span<byte>((void*)outBlob.Data, outBlob.Size).Clear();
return result;
}
finally { LocalFree(outBlob.Data); }
}
}
}