Исправление: том ./mods:/lampac/mods в compose и копии 10 модулей с enable:true; конфиг без SkipModules

This commit is contained in:
2026-10-02 12:11:49 +03:00
parent 8dcbc6bc52
commit 7b8e28b3bf
151 changed files with 68625 additions and 44 deletions
+14
View File
@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<OutputType>library</OutputType>
<IsPackable>true</IsPackable>
<RootNamespace>AdminPanel</RootNamespace>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\Shared\Shared.csproj" />
</ItemGroup>
</Project>
+366
View File
@@ -0,0 +1,366 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using Shared;
using Shared.Attributes;
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AdminPanel;
[Authorization(redirectUri: "/adminpanel/auth")]
public class AdminPanelController : BaseController
{
const string InitFile = "init.conf";
const string CurrentFile = "current.conf";
const string UsersFile = "users.json";
[HttpGet]
[AllowAnonymous]
[Route("/adminpanel/auth")]
public ActionResult Auth()
{
var path = Path.Combine(ModInit.modpath, "auth.html");
var html = System.IO.File.ReadAllText(path, Encoding.UTF8);
return Content(html, "text/html; charset=utf-8");
}
[HttpGet]
[Route("/adminpanel")]
public ActionResult Index()
{
var path = Path.Combine(ModInit.modpath, "index.html");
var html = System.IO.File.ReadAllText(path, Encoding.UTF8);
return Content(html, "text/html; charset=utf-8");
}
[HttpGet]
[Route("/adminpanel/api/groups")]
public ActionResult Groups()
{
var current = LoadCurrentRoot();
var built = ConfigSectionGroups.Build(current);
var json = JsonConvert.SerializeObject(built, new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
NullValueHandling = NullValueHandling.Ignore
});
return Content(json, "application/json; charset=utf-8");
}
[HttpGet]
[Route("/adminpanel/api/groups/catalog")]
public ActionResult GroupsCatalog()
{
var built = ConfigSectionGroups.BuildCatalog();
var current = LoadCurrentRoot();
var inCatalog = ConfigSectionGroups.CatalogRootKeys;
var orphans = current.Properties()
.Select(p => p.Name)
.Where(k => !inCatalog.Contains(k))
.OrderBy(k => k, StringComparer.Ordinal)
.ToArray();
if (orphans.Length > 0)
built.Add(new GroupDto("other", "Прочее", "Ключи из current, не из каталога групп.", orphans));
var json = JsonConvert.SerializeObject(built, new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
NullValueHandling = NullValueHandling.Ignore
});
return Content(json, "application/json; charset=utf-8");
}
static JObject LoadCurrentRoot()
{
try
{
if (System.IO.File.Exists(CurrentFile))
return JObject.Parse(System.IO.File.ReadAllText(CurrentFile, Encoding.UTF8));
}
catch (JsonException)
{
}
if (CoreInit.CurrentConf != null)
{
try
{
return (JObject)CoreInit.CurrentConf.DeepClone();
}
catch
{
}
}
return new JObject();
}
[HttpGet]
[Route("/adminpanel/api/init")]
public ActionResult GetInit()
{
if (!System.IO.File.Exists(InitFile))
return Content("{}", "application/json; charset=utf-8");
var text = System.IO.File.ReadAllText(InitFile, Encoding.UTF8);
return Content(NormalizeJsonText(text), "application/json; charset=utf-8");
}
[HttpGet]
[Route("/adminpanel/api/current")]
public ActionResult GetCurrent()
{
if (!System.IO.File.Exists(CurrentFile))
{
if (CoreInit.CurrentConf != null)
return Content(CoreInit.CurrentConf.ToString(Formatting.Indented), "application/json; charset=utf-8");
return Content("{}", "application/json; charset=utf-8");
}
var text = System.IO.File.ReadAllText(CurrentFile, Encoding.UTF8);
return Content(NormalizeJsonText(text), "application/json; charset=utf-8");
}
[HttpPost]
[Route("/adminpanel/api/init")]
public async Task<IActionResult> SaveInit()
{
string body;
using (var reader = new StreamReader(Request.Body, Encoding.UTF8, detectEncodingFromByteOrderMarks: false, bufferSize: 1024, leaveOpen: true))
body = await reader.ReadToEndAsync().ConfigureAwait(false);
if (string.IsNullOrWhiteSpace(body))
return AdminJsonError(400, "empty body");
try
{
var parsed = JToken.Parse(body);
if (parsed.Type != JTokenType.Object)
return AdminJsonError(400, "root must be a JSON object");
var formatted = ((JObject)parsed).ToString(Formatting.Indented);
await WriteInitAtomicAsync(formatted).ConfigureAwait(false);
return AdminJsonOk();
}
catch (JsonException ex)
{
return AdminJsonError(400, "invalid json", ex.Message);
}
catch (IOException ex)
{
return AdminJsonError(500, "failed to write init.conf", ex.Message);
}
}
[HttpPost]
[Route("/adminpanel/api/init/section/{key}")]
public async Task<IActionResult> SaveInitSection(string key)
{
if (string.IsNullOrWhiteSpace(key) || key.Contains('/') || key.Contains('\\'))
return AdminJsonError(400, "invalid section key");
string body;
using (var reader = new StreamReader(Request.Body, Encoding.UTF8, detectEncodingFromByteOrderMarks: false, bufferSize: 1024, leaveOpen: true))
body = await reader.ReadToEndAsync().ConfigureAwait(false);
if (string.IsNullOrWhiteSpace(body))
return AdminJsonError(400, "empty body");
JToken sectionToken;
try
{
sectionToken = JToken.Parse(body);
}
catch (JsonException ex)
{
return AdminJsonError(400, "invalid json", ex.Message);
}
try
{
JObject root;
if (System.IO.File.Exists(InitFile))
{
try
{
root = JObject.Parse(System.IO.File.ReadAllText(InitFile, Encoding.UTF8));
}
catch (JsonException)
{
root = new JObject();
}
}
else
root = new JObject();
root[key] = sectionToken.DeepClone();
var formatted = root.ToString(Formatting.Indented);
await WriteInitAtomicAsync(formatted).ConfigureAwait(false);
return AdminJsonOk();
}
catch (IOException ex)
{
return AdminJsonError(500, "failed to write init.conf", ex.Message);
}
}
// tmp+Move — атомарно; на bind mount Move(..., overwrite) часто EBUSY → пишем в init.conf напрямую.
static async Task WriteInitAtomicAsync(string formatted)
{
var tmp = InitFile + ".tmp";
await System.IO.File.WriteAllTextAsync(tmp, formatted, Encoding.UTF8).ConfigureAwait(false);
try
{
try
{
System.IO.File.Move(tmp, InitFile, overwrite: true);
}
catch (IOException ex) when (IsReplaceTargetBusy(ex))
{
await System.IO.File.WriteAllTextAsync(InitFile, formatted, Encoding.UTF8).ConfigureAwait(false);
}
}
finally
{
try
{
if (System.IO.File.Exists(tmp))
System.IO.File.Delete(tmp);
}
catch
{
}
}
}
static bool IsReplaceTargetBusy(IOException ex)
{
for (Exception e = ex; e != null; e = e.InnerException)
{
if (e.Message != null && e.Message.Contains("busy", StringComparison.OrdinalIgnoreCase))
return true;
}
return false;
}
static ContentResult AdminJsonOk()
{
return new ContentResult
{
Content = "{\"ok\":true}",
ContentType = "application/json; charset=utf-8",
StatusCode = 200
};
}
static ContentResult AdminJsonError(int status, string error, string detail = null)
{
var o = new JObject { ["error"] = error };
if (!string.IsNullOrEmpty(detail))
o["detail"] = detail;
return new ContentResult
{
Content = o.ToString(Formatting.None),
ContentType = "application/json; charset=utf-8",
StatusCode = status
};
}
static string NormalizeJsonText(string raw)
{
try
{
return JToken.Parse(raw).ToString(Formatting.Indented);
}
catch
{
return raw;
}
}
[HttpGet]
[Route("/adminpanel/api/users-json")]
public ActionResult GetUsersJson()
{
if (!System.IO.File.Exists(UsersFile))
return Content("[]", "application/json; charset=utf-8");
var text = System.IO.File.ReadAllText(UsersFile, Encoding.UTF8);
if (string.IsNullOrWhiteSpace(text))
return Content("[]", "application/json; charset=utf-8");
return Content(NormalizeJsonText(text), "application/json; charset=utf-8");
}
[HttpPost]
[Route("/adminpanel/api/users-json")]
public async Task<IActionResult> SaveUsersJson()
{
string body;
using (var reader = new StreamReader(Request.Body, Encoding.UTF8, detectEncodingFromByteOrderMarks: false, bufferSize: 1024, leaveOpen: true))
body = await reader.ReadToEndAsync().ConfigureAwait(false);
if (string.IsNullOrWhiteSpace(body))
return AdminJsonError(400, "empty body");
try
{
var parsed = JToken.Parse(body);
if (parsed.Type != JTokenType.Array)
return AdminJsonError(400, "root must be a JSON array", "users.json must be a list of AccsUser objects");
foreach (var item in (JArray)parsed)
{
if (item.Type != JTokenType.Object)
return AdminJsonError(400, "invalid array item", "each element must be a JSON object");
}
var formatted = ((JArray)parsed).ToString(Formatting.Indented);
await WriteUsersAtomicAsync(formatted).ConfigureAwait(false);
return AdminJsonOk();
}
catch (JsonException ex)
{
return AdminJsonError(400, "invalid json", ex.Message);
}
catch (IOException ex)
{
return AdminJsonError(500, "failed to write users.json", ex.Message);
}
}
static async Task WriteUsersAtomicAsync(string formatted)
{
var tmp = UsersFile + ".tmp";
await System.IO.File.WriteAllTextAsync(tmp, formatted, Encoding.UTF8).ConfigureAwait(false);
try
{
try
{
System.IO.File.Move(tmp, UsersFile, overwrite: true);
}
catch (IOException ex) when (IsReplaceTargetBusy(ex))
{
await System.IO.File.WriteAllTextAsync(UsersFile, formatted, Encoding.UTF8).ConfigureAwait(false);
}
}
finally
{
try
{
if (System.IO.File.Exists(tmp))
System.IO.File.Delete(tmp);
}
catch
{
}
}
}
}
+107
View File
@@ -0,0 +1,107 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json.Linq;
namespace AdminPanel;
public static class ConfigSectionGroups
{
public sealed record GroupSpec(string Id, string Title, string Hint, string[] Keys);
public static readonly GroupSpec[] Catalog =
{
new("runtime", "Рантайм", "Поля снимка; обычно приходят из current, в init не обязательны.",
new[] { "guid", "freeDiskSpace" }),
new("listen", "HTTP-сервер (listen)", "Адрес, порт, схема, таймауты, compression.",
new[] { "listen" }),
new("security", "Безопасность и доступ", "WAF, accsdb, список модулей и middleware ядра.",
new[] { "WAF", "accsdb", "BaseModule" }),
new("network", "Сеть и прокси", "Прокси исходящих запросов, CORS, доверенные сети.",
new[] { "serverproxy", "proxy", "globalproxy", "corsehost", "KnownProxies" }),
new("pools", "Пулы и служебное", "Буферы, apn, kit.",
new[] { "pool", "apn", "kit" }),
new("cache-gc", "Кэш и память", "Гибридный кэш, Staticache, настройки GC.",
new[] { "cache", "Staticache", "GC" }),
new("media", "Изображения и постеры", "Движок картинок, Poster API.",
new[] { "imagelibrary", "posterApi" }),
new("realtime", "WebSocket и RCH", "Нативные сокеты и удалённый хаб.",
new[] { "WebSocket", "rch" }),
new("browser", "Браузеры (Playwright)", "Chromium / Firefox для автоматизации.",
new[] { "chromium", "firefox" }),
new("diagnostics", "Логи и диагностика", "Serilog, обработчик исключений, openstat.",
new[] { "serilog", "useDeveloperExceptionPage", "exceptionHandlerLogTarget", "exceptionHandlerLogFile", "watcherInit", "openstat" }),
new("app", "Приложение и оболочка", "online, cub, sisi, реклама, дефолты, omdb.",
new[] { "online", "cub", "sisi", "vast", "disableEng", "defaultOn", "omdbapi_key", "overrideResponse" }),
new("client", "Клиент Lampa и API", "Оболочка Lampa, cookie, PidTor, TMDB.",
new[] { "tmdb", "LampaWeb", "Cookie", "PidTor" }),
new("modules", "Модули расширения", "Секции подключаемых модулей в корне конфига.",
new[] { "Catalog", "DLNA", "JacRed", "Sync", "TimeCode", "TorrServer", "Tracks", "transcoding", "TmdbProxy", "CubProxy", "WebLog" }),
new("src-anime", "Источники · аниме", "Онлайн-балансеры аниме и смежные (в т.ч. Kodik).",
new[] { "AniLiberty", "AniLibria", "Animebesst", "AnimeGo", "AnimeLib", "AnimeON", "Animevost", "AniMedia", "Dreamerscast", "Kodik", "Mikai", "MoonAnime" }),
new("src-embed", "Источники · встраиваемые плееры", "Embed и агрегаторы сторонних плееров.",
new[] { "Autoembed", "Hydraflix", "MovPI", "Playembed", "Rgshows", "Smashystream", "Twoembed", "VidLink", "Videasy", "Vidsrc" }),
new("src-vod", "Источники · VOD и CDN", "Кино, сериалы, региональные и CDN-провайдеры.",
new[]
{
"Alloha", "Ashdi", "AsiaGe", "BamBoo", "CDNvideohub", "Collaps", "Eneyida", "FanCDN", "Filmix", "FilmixPartner", "FilmixTV", "FlixCDN",
"Geosaitebi", "GetsTV", "HDVB", "HdvbUA", "IptvOnline", "iRemux", "Kinobase", "Kinoflix", "Kinogo", "Kinotochka", "Kinoukr", "KinoPub",
"LeProduction", "Mirage", "Rezka", "RezkaPrem", "RutubeMovie", "Tortuga", "UaKino", "VideoDB", "Videoseed", "VeoVeo", "Vibix", "VkMovie", "VoKino"
}),
new("src-adult", "Источники · 18+", "SISI / взрослые сайты.",
new[]
{
"BongaCams", "Chaturbate", "Ebalovo", "Eporner", "HQporner", "PornHub", "PornHubPremium", "Porntrex", "Runetki", "Spankbang", "Tizam",
"Xhamster", "Xnxx", "Xvideos", "XvideosRED"
}),
};
public static List<GroupDto> Build(JObject currentRoot)
{
if (currentRoot == null)
currentRoot = new JObject();
var inFile = new HashSet<string>(
currentRoot.Properties().Select(p => p.Name),
StringComparer.Ordinal);
var assigned = new HashSet<string>(StringComparer.Ordinal);
var result = new List<GroupDto>();
foreach (var g in Catalog)
{
var keys = g.Keys.Where(inFile.Contains).OrderBy(k => k, StringComparer.Ordinal).ToArray();
foreach (var k in keys)
assigned.Add(k);
if (keys.Length == 0)
continue;
result.Add(new GroupDto(g.Id, g.Title, g.Hint, keys));
}
var orphans = inFile.Where(k => !assigned.Contains(k)).OrderBy(k => k, StringComparer.Ordinal).ToArray();
if (orphans.Length > 0)
result.Add(new GroupDto("other", "Прочее", "Ключи из current.conf, не попавшие в каталог (новые модули).", orphans));
return result;
}
public static List<GroupDto> BuildCatalog()
{
var list = new List<GroupDto>(Catalog.Length);
foreach (var g in Catalog)
list.Add(new GroupDto(g.Id, g.Title, g.Hint, g.Keys.ToArray()));
return list;
}
public static HashSet<string> CatalogRootKeys { get; } = new(
Catalog.SelectMany(g => g.Keys),
StringComparer.Ordinal);
}
public sealed record GroupDto(string Id, string Title, string Hint, string[] Keys);
+18
View File
@@ -0,0 +1,18 @@
using Shared.Models.Module;
using Shared.Models.Module.Interfaces;
namespace AdminPanel;
public class ModInit : IModuleLoaded
{
public static string modpath;
public void Loaded(InitspaceModel baseconf)
{
modpath = baseconf.path;
}
public void Dispose()
{
}
}
+98
View File
@@ -0,0 +1,98 @@
# AdminPanel
Веб-**админка** Lampac: статический UI (**`auth.html`**, **`index.html`**) и JSON API для просмотра и правки **`init.conf`**, снимка **`current.conf`** и пользователей **`users.json`** (режим **accsdb**). Доступ к закрытым маршрутам — после ввода **root-пароля** из файла **`passwd`** (cookie **`accspasswd`**; см. ниже); при отказе **`[Authorization]`** перенаправляет на **`/adminpanel/auth`**.
## Быстрый старт
1. Включите модуль в **`manifest.json`** (`"enable": true`). По умолчанию в репозитории стоит **`false`**.
2. Соберите и задеплойте сборку так же, как остальные модули (динамический модуль; список файлов — поле **`tree`** в **`manifest.json`**).
3. Откройте **`http(s)://<хост>:<порт>/adminpanel/auth`** и войдите **root-паролем из файла `passwd`** в рабочей директории сервера (см. [Вход](#вход)).
4. Рабочая панель: **`/adminpanel`**.
Удобный порт в dev-сборке через Docker часто задаёт compose (например **9118**); точный адрес зависит от **`listen`** в конфигурации Lampac.
## Вход и сессия
Страница **`/adminpanel/auth`** сохраняет пароль в cookie **`accspasswd`** (срок **180 дней**, **`path=/`**, **`SameSite=Lax`**, в HTTPS добавляется **`Secure`**).
Панель дергает API с **`credentials: 'same-origin'`**, поэтому cookie должна быть установлена для того же origin, что и сервер Lampac.
### Файл `passwd` (root-пароль)
Вход в админку **не** берётся из **`users.json`** и не совпадает с **`accsdb.shared_passwd`** в **`init.conf`**. Для маршрутов с **`[Authorization]`** ядро сравнивает cookie **`accspasswd`** с **`CoreInit.rootPasswd`**, который читается из файла **`passwd`** в **рабочей директории** процесса (рядом с **`init.conf`**):
- если **`passwd`** есть при старте — содержимое файла загружается в память, пробелы и переводы строк снимаются;
- если файла нет при старте — генерируется случайная строка и записывается в **`passwd`** (имеет смысл сразу задать свой пароль и при необходимости перезапустить процесс).
В форме входа нужно указывать **именно эту** root-строку.
Дополнительно ядро ограничивает число **разных** попыток пароля в cookie с одного IP за сутки; после порога ответы к защищённым маршрутам выглядят как **404** (см. **`Core/Middlewares/Accsdb.cs`**).
Тот же **`rootPasswd`** используется для внутренних вызовов с HTTP-заголовком **`lcrqpasswd`** (это не форма входа в браузере).
Остальная политика (локальный доступ без проверки, **accsdb** для клиентов Lampa, WAF и т.д.) накладывается **поверх** этой проверки — см. конфигурацию ядра. Не выкладывайте **`passwd`** в Git и не публикуйте админку в открытый интернет без осознанной защиты. В Docker/Kubernetes **`passwd`** обычно монтируют вместе с **`init.conf`** (см. комментарии в **`docker-compose.yaml`**, чарт **`charts/lampac`**).
## Где лежат файлы
Пути **`passwd`**, **`init.conf`**, **`current.conf`**, **`users.json`** задаются относительно **текущей рабочей директории процесса** Lampac (не от каталога модуля).
- Если **`current.conf`** на диске отсутствует или повреждён как JSON, при чтении подставляется снимок из **`CoreInit.CurrentConf`** (если доступен хостом).
- HTML читаются из **`ModInit.modpath`** (каталог загруженного модуля): **`auth.html`**, **`index.html`**.
В Docker проверьте, что том с конфигом смонтирован туда же, откуда процесс видит те же имена файлов, что вы правите через UI.
### Запись на диск
Сохранение **`init.conf`** и **`users.json`** делается атомарно: сначала запись во временный файл, затем **`Move`** с перезаписью. Если на bind mount **`Move`** даёт ошибку занятости цели (**EBUSY**), выполняется прямая запись в целевой файл — это осознанный fallback для некоторых сценариев Docker.
Ответ успешной записи: **`{"ok":true}`**. Ошибки: **`400`/`500`** с телом **`{"error":"...", "detail":"..."}`** (поле **`detail`** опционально).
## Различие «init» и «current» в UI
| Файл | Роль |
|------|------|
| **`init.conf`** | То, что можно **сохранять** через API: целиком (**`POST /adminpanel/api/init`**) или по корневым ключам (**`POST .../init/section/{key}`**). |
| **`current.conf`** | **Только чтение** в админке (**`GET /adminpanel/api/current`**): актуальный снимок/мердж конфигурации для просмотра и группировки секций в интерфейсе. Прямой POST для **`current`** в контроллере не предусмотрен. |
Если нужно изменить один корневой ключ в **`init.conf`**, тело **`POST /adminpanel/api/init/section/{key}`** — валидный JSON **значения** секции (объект, массив, примитив — как в корне конфига). Ключ секции не должен содержать **`/`** или **`\`**.
## HTTP API
Подробности тел запросов и валидации — в **`AdminPanelController.cs`**.
| Метод и маршрут | Описание |
|-----------------|----------|
| **`GET /adminpanel/auth`** | Страница входа (**`AllowAnonymous`**). |
| **`GET /adminpanel`** | Главная панель (**`index.html`**). |
| **`GET /adminpanel/api/groups`** | Группы секций по ключам, **присутствующим** в **`current.conf`** (или в памяти, если файл не прочитан), плюс блок **«Прочее»** для ключей без каталога. |
| **`GET /adminpanel/api/groups/catalog`** | Полный **каталог** групп из **`ConfigSectionGroups.Catalog`**; если в актуальном конфиге есть ключи вне каталога — добавляется **«Прочее»** для них (подписи ориентированы на ключи из current). |
| **`GET /adminpanel/api/init`** | Содержимое **`init.conf`** (пустой объект, если файла нет); JSON приводится к отформатированному виду когда возможно. |
| **`POST /adminpanel/api/init`** | Тело — один JSON **объект** (корень **`init.conf`**). Целиком перезаписывает файл. |
| **`POST /adminpanel/api/init/section/{key}`** | Обновить один корневой ключ в **`init.conf`**. |
| **`GET /adminpanel/api/current`** | **`current.conf`** или fallback из **`CoreInit.CurrentConf`**. |
| **`GET /adminpanel/api/users-json`** | Массив пользователей; если файла нет — **`[]`**. |
| **`POST /adminpanel/api/users-json`** | Тело — JSON **массив** объектов пользователей (схема **accsdb**); перезаписывает **`users.json`**. |
## Группы в редакторе
Класс **`ConfigSectionGroups`** задаёт человекочитаемые группы и подсказки для бокового каталога: какие корневые ключи конфига к какой группе относятся (рантайм, listen, модули, источники и т.д.).
При добавлении нового модуля с секцией в корне JSON имеет смысл дописать её ключ в **`Catalog`** нужной группы или в блок **«modules»**, чтобы ключ не попадал только в **«Прочее»**.
Публичный **`GroupDto`** (см. низ **`ConfigSectionGroups.cs`**): **`id`**, **`title`**, **`hint`**, массив **`keys`**.
## Конфигурация модуля
Отдельной секции настроек в **`ModInit`** нет — только **`manifest.json`** (**`enable`**, **`dynamic`**, **`tree`**).
Статические ассеты панели лежат рядом с кодом модуля (**`index.html`**, **`auth.html`**); при изменении их в репозитории нужна перезагрузка/пересборка в соответствии с тем, как хост подхватывает динамические модули.
## Файлы модуля
| Файл | Роль |
|------|------|
| **`AdminPanelController.cs`** | Маршруты UI и API, работа с файлами конфигурации. |
| **`ConfigSectionGroups.cs`** | Каталог групп и билдер **`GroupDto`**. |
| **`ModInit.cs`** | **`IModuleLoaded`**: сохраняет **`modpath`** для раздачи HTML. |
| **`manifest.json`** | Включение модуля и список подгружаемых **`.cs`**. |
| **`auth.html`**, **`index.html`** | Интерфейс входа и панели. |
+401
View File
@@ -0,0 +1,401 @@
<!DOCTYPE html>
<html lang="ru" data-theme="dark">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="theme-color" content="#0c0e12" id="metaTheme">
<title>Вход — Lampac Admin</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link
href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap"
rel="stylesheet">
<script>
(function () {
try {
var t = localStorage.getItem('lampac-theme');
var dark = t === 'light' ? false : t === 'dark' ? true : window.matchMedia('(prefers-color-scheme: dark)').matches;
document.documentElement.setAttribute('data-theme', dark ? 'dark' : 'light');
} catch (e) { /* ignore */ }
})();
</script>
<style>
*,
*::before,
*::after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
:root {
--font-body: 'Inter', system-ui, -apple-system, sans-serif;
--font-mono: 'JetBrains Mono', ui-monospace, SFMono-Regular, Consolas, monospace;
--text-xs: 0.6875rem;
--text-sm: 0.8125rem;
--text-base: 0.875rem;
--text-lg: 1rem;
--sp-1: 0.25rem;
--sp-2: 0.5rem;
--sp-3: 0.75rem;
--sp-4: 1rem;
--sp-5: 1.25rem;
--sp-6: 1.5rem;
--sp-8: 2rem;
--r-sm: 6px;
--r-md: 8px;
--r-lg: 12px;
--r-xl: 16px;
--ease: cubic-bezier(0.16, 1, 0.3, 1);
--dur: 180ms;
}
[data-theme="dark"] {
--bg: #0c0e12;
--surface: #13161d;
--surface-2: #1a1e28;
--surface-3: #222733;
--border: #2a3040;
--border-subtle: rgba(255, 255, 255, 0.06);
--text: #e2e6ef;
--text-muted: #7c849a;
--text-faint: #4d5568;
--accent: #3ec9d1;
--accent-soft: #2ea8b0;
--accent-dim: rgba(62, 201, 209, 0.12);
--accent-hover: rgba(62, 201, 209, 0.22);
--shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.3);
--shadow-md: 0 4px 16px rgba(0, 0, 0, 0.35);
--shadow-lg: 0 12px 40px rgba(0, 0, 0, 0.45);
}
[data-theme="light"] {
--bg: #f4f5f8;
--surface: #ffffff;
--surface-2: #f0f1f5;
--surface-3: #e8eaf0;
--border: #d4d8e3;
--border-subtle: rgba(0, 0, 0, 0.06);
--text: #1a1e28;
--text-muted: #6b7280;
--text-faint: #9ca3af;
--accent: #0d9499;
--accent-soft: #0b7d82;
--accent-dim: rgba(13, 148, 153, 0.1);
--accent-hover: rgba(13, 148, 153, 0.18);
--shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.06);
--shadow-md: 0 4px 12px rgba(0, 0, 0, 0.08);
--shadow-lg: 0 12px 32px rgba(0, 0, 0, 0.12);
}
html,
body {
min-height: 100%;
}
body {
font-family: var(--font-body);
font-size: var(--text-base);
color: var(--text);
background: var(--bg);
line-height: 1.5;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.auth-app {
display: flex;
flex-direction: column;
min-height: 100dvh;
}
.topbar {
display: flex;
align-items: center;
gap: var(--sp-4);
padding: var(--sp-3) var(--sp-6);
min-height: 52px;
background: var(--surface);
border-bottom: 1px solid var(--border);
flex-shrink: 0;
flex-wrap: wrap;
}
.topbar-logo {
display: flex;
align-items: center;
gap: var(--sp-2);
font-weight: 700;
font-size: var(--text-lg);
letter-spacing: -0.02em;
color: var(--text);
flex-shrink: 0;
white-space: nowrap;
}
.topbar-logo svg {
flex-shrink: 0;
}
.topbar-logo span {
font-weight: 400;
color: var(--text-muted);
margin-left: 2px;
}
.topbar-spacer {
flex: 1;
min-width: var(--sp-2);
}
.btn-icon {
width: 34px;
height: 34px;
padding: 0;
border: 1px solid var(--border);
border-radius: var(--r-md);
background: var(--surface-2);
color: var(--text-muted);
cursor: pointer;
display: inline-flex;
align-items: center;
justify-content: center;
transition: all var(--dur) var(--ease);
flex-shrink: 0;
}
.btn-icon:hover {
color: var(--text);
background: var(--surface-3);
}
.btn-icon svg {
width: 16px;
height: 16px;
}
.auth-main {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
padding: var(--sp-6) var(--sp-4);
}
.auth-card {
width: 100%;
max-width: 380px;
padding: var(--sp-6);
background: var(--surface);
border: 1px solid var(--border);
border-radius: var(--r-xl);
box-shadow: var(--shadow-lg);
animation: authIn 280ms var(--ease);
}
@keyframes authIn {
from {
opacity: 0;
transform: translateY(6px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.auth-card h1 {
font-size: var(--text-lg);
font-weight: 700;
letter-spacing: -0.01em;
margin-bottom: var(--sp-1);
}
.auth-card .lead {
font-size: var(--text-xs);
color: var(--text-muted);
margin-bottom: var(--sp-5);
line-height: 1.6;
}
.auth-form {
display: flex;
flex-direction: column;
gap: var(--sp-4);
}
.auth-field label {
display: block;
font-size: var(--text-xs);
font-weight: 500;
color: var(--text-muted);
margin-bottom: var(--sp-2);
}
.auth-field input[type="password"] {
font: inherit;
font-size: var(--text-sm);
width: 100%;
padding: 8px 12px;
border-radius: var(--r-md);
border: 1px solid var(--border);
background: var(--surface-2);
color: var(--text);
transition: border-color var(--dur) var(--ease), box-shadow var(--dur) var(--ease);
}
[data-theme="light"] .auth-field input[type="password"] {
background: var(--surface);
}
.auth-field input[type="password"]:focus {
outline: none;
border-color: var(--accent);
box-shadow: 0 0 0 3px var(--accent-dim);
}
.auth-field input::placeholder {
color: var(--text-faint);
}
.btn {
font: inherit;
font-size: var(--text-xs);
font-weight: 600;
padding: 10px 16px;
border-radius: var(--r-md);
border: 1px solid var(--accent);
cursor: pointer;
transition: all var(--dur) var(--ease);
display: inline-flex;
align-items: center;
justify-content: center;
gap: var(--sp-2);
width: 100%;
}
.btn-primary {
background: var(--accent);
color: #fff;
border-color: var(--accent);
}
.btn-primary:hover {
background: var(--accent-soft);
border-color: var(--accent-soft);
transform: translateY(-1px);
box-shadow: var(--shadow-sm);
}
.btn-primary:active {
transform: translateY(0);
}
@media (max-width: 480px) {
.topbar-logo span {
display: none;
}
}
</style>
<script>
(function () {
var dark = document.documentElement.getAttribute('data-theme') === 'dark';
var m = document.getElementById('metaTheme');
if (m) m.setAttribute('content', dark ? '#0c0e12' : '#f4f5f8');
})();
</script>
</head>
<body>
<div class="auth-app">
<header class="topbar">
<div class="topbar-logo">
<svg width="28" height="28" viewBox="0 0 28 28" fill="none" aria-hidden="true">
<rect x="2" y="2" width="24" height="24" rx="6" stroke="currentColor" stroke-width="1.5" fill="none" />
<rect x="7" y="16" width="3" height="6" rx="1" fill="var(--accent)" />
<rect x="12.5" y="11" width="3" height="11" rx="1" fill="var(--accent)" opacity="0.7" />
<rect x="18" y="6" width="3" height="16" rx="1" fill="var(--accent)" opacity="0.45" />
</svg>
Lampac <span>Admin</span>
</div>
<div class="topbar-spacer"></div>
<button type="button" class="btn-icon" id="themeBtn" title="Сменить тему (Alt+T)" aria-label="Сменить тему">
<svg id="themeIcon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
stroke-linecap="round">
<path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z" />
</svg>
</button>
</header>
<main class="auth-main">
<div class="auth-card">
<h1>Вход</h1>
<p class="lead">Введите пароль доступа к панели. Сессия сохраняется в cookie на 180 дней.</p>
<form class="auth-form" id="loginForm">
<div class="auth-field">
<label for="password">Пароль</label>
<input type="password" id="password" name="password" placeholder="Пароль" required autocomplete="current-password" />
</div>
<button type="submit" class="btn btn-primary">Войти</button>
</form>
</div>
</main>
</div>
<script>
(function () {
var LAMPAC_THEME_STORAGE_KEY = 'lampac-theme';
function $(sel) { return document.querySelector(sel); }
function setTheme(dark) {
document.documentElement.setAttribute('data-theme', dark ? 'dark' : 'light');
var meta = $('#metaTheme');
if (meta) meta.setAttribute('content', dark ? '#0c0e12' : '#f4f5f8');
try { localStorage.setItem(LAMPAC_THEME_STORAGE_KEY, dark ? 'dark' : 'light'); } catch (e) { }
syncThemeIcon();
}
function syncThemeIcon() {
var d = document.documentElement.getAttribute('data-theme') === 'dark';
var icon = $('#themeIcon');
if (!icon) return;
if (d) {
icon.innerHTML = '<path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/>';
} else {
icon.innerHTML = '<circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/>';
}
}
syncThemeIcon();
$('#themeBtn').addEventListener('click', function () {
var d = document.documentElement.getAttribute('data-theme') === 'dark';
setTheme(!d);
});
document.addEventListener('keydown', function (e) {
if (e.altKey && (e.key === 't' || e.key === 'T')) {
e.preventDefault();
var d = document.documentElement.getAttribute('data-theme') === 'dark';
setTheme(!d);
}
});
$('#loginForm').addEventListener('submit', function (e) {
e.preventDefault();
var password = $('#password').value;
var maxAge = 60 * 60 * 24 * 180;
document.cookie = 'accspasswd=' + encodeURIComponent(password) +
'; max-age=' + maxAge +
'; path=/; SameSite=Lax' +
(window.isSecureContext ? '; Secure' : '');
window.location.href = '/adminpanel';
});
})();
</script>
</body>
</html>
File diff suppressed because it is too large Load Diff
+9
View File
@@ -0,0 +1,9 @@
{
"enable": true,
"dynamic": true,
"tree": [
"AdminPanelController.cs",
"ConfigSectionGroups.cs",
"ModInit.cs"
]
}