ЛР 2: PostgreSQL, сессии, Redis и исследование

This commit is contained in:
Никита
2026-10-06 13:34:34 +03:00
parent 65003b6119
commit 6a8908ab99
111 changed files with 6686 additions and 38 deletions
@@ -0,0 +1,7 @@
namespace Messenger.Api.Contracts;
public sealed record ChatCursor(
string Scope,
string CreatedAt,
Guid Id
);
+3
View File
@@ -0,0 +1,3 @@
namespace Messenger.Api.Contracts;
public sealed record ChatDto(Guid Id, string Title, List<Guid> MemberIds, string CreatedAt);
@@ -0,0 +1,6 @@
namespace Messenger.Api.Contracts;
public sealed record CreateChatRequest(
string? Title,
List<Guid>? MemberIds
);
@@ -0,0 +1,5 @@
namespace Messenger.Api.Contracts;
public sealed record CreateMessageRequest(
string? Text
);
@@ -0,0 +1,7 @@
namespace Messenger.Api.Contracts;
public sealed record CreateUserRequest(
string? Username,
string? DisplayName,
string? Password
);
@@ -0,0 +1,3 @@
namespace Messenger.Api.Contracts;
public sealed record MessageDto(Guid Id, Guid ChatId, Guid SenderId, string Text, string CreatedAt);
@@ -0,0 +1,3 @@
namespace Messenger.Api.Contracts;
public sealed record SessionDto(string Token, string TokenType, string ExpiresAt, UserDto User);
+3
View File
@@ -0,0 +1,3 @@
namespace Messenger.Api.Contracts;
public sealed record UserDto(Guid Id, string Username, string DisplayName, string CreatedAt);
@@ -0,0 +1,60 @@
using System.Text;
using System.Text.RegularExpressions;
using Messenger.Api.Services;
using static Messenger.Api.Services.ApiSupport;
namespace Messenger.Api.Endpoints;
public static class AuthEndpoints
{
private static readonly UTF8Encoding StrictUtf8 = new(false, true);
public static IEndpointRouteBuilder MapAuthEndpoints(this IEndpointRouteBuilder app)
{
app.MapPost("/api/v1/auth/sessions", async (HttpContext context, SessionService sessions) =>
{
if (!context.Request.Headers.TryGetValue("Authorization", out var header))
return Unauthorized(context, basic: true);
var authorization = header.ToString();
if (!authorization.StartsWith("Basic ", StringComparison.OrdinalIgnoreCase))
return Unauthorized(context, basic: true);
string credentials;
try
{
credentials = StrictUtf8.GetString(Convert.FromBase64String(authorization[6..]));
}
catch (Exception exception) when (exception is FormatException or DecoderFallbackException)
{
return Unauthorized(context, basic: true);
}
var delimiter = credentials.IndexOf(':');
if (delimiter < 0) return Unauthorized(context, basic: true);
var username = credentials[..delimiter];
var password = credentials[(delimiter + 1)..];
if (!Regex.IsMatch(username, "\\A[a-z0-9_]{3,32}\\z"))
return Unauthorized(context, basic: true);
if (context.Request.ContentLength > 0 || context.Request.Headers.ContainsKey("Transfer-Encoding"))
return ApiError(context, 400, "invalid_request", "Вход принимает Basic без тела запроса");
var session = await sessions.LoginAsync(username, password);
return session is null
? Unauthorized(context, basic: true)
: Results.Json(session, statusCode: StatusCodes.Status201Created);
});
app.MapDelete("/api/v1/auth/sessions/current", async (HttpContext context, SessionService sessions) =>
{
var (user, tokenHash) = await sessions.AuthenticateAsync(context);
if (user is null || tokenHash is null) return Unauthorized(context);
return await sessions.RevokeAsync(tokenHash)
? Results.NoContent()
: Unauthorized(context);
});
return app;
}
}
@@ -0,0 +1,67 @@
using Messenger.Api.Contracts;
using Messenger.Api.Services;
using static Messenger.Api.Services.ApiSupport;
namespace Messenger.Api.Endpoints;
public static class ChatEndpoints
{
public static IEndpointRouteBuilder MapChatEndpoints(this IEndpointRouteBuilder app)
{
app.MapPost("/api/v1/chats", async (HttpContext context, SessionService sessions, ChatService chats) =>
{
var (actor, _) = await sessions.AuthenticateAsync(context);
if (actor is null) return Unauthorized(context);
var (request, error) = await ReadJsonAsync<CreateChatRequest>(context);
if (error is not null) return error;
if (string.IsNullOrWhiteSpace(request!.Title) || request.Title.EnumerateRunes().Count() > 100)
return ApiError(context, 400, "invalid_request", "Некорректное название чата");
if (request.MemberIds is null || request.MemberIds.Count is < 1 or > 100 ||
request.MemberIds.Distinct().Count() != request.MemberIds.Count ||
!request.MemberIds.Contains(actor.Id))
return ApiError(context, 400, "invalid_request", "Некорректный список участников");
var chat = await chats.CreateAsync(request.Title, request.MemberIds);
return chat is null
? ApiError(context, 400, "invalid_request", "Один из участников не существует")
: Results.Json(chat, statusCode: StatusCodes.Status201Created);
});
app.MapGet("/api/v1/chats", async (HttpContext context, SessionService sessions, ChatService chats) =>
{
var (actor, _) = await sessions.AuthenticateAsync(context);
if (actor is null) return Unauthorized(context);
var (limit, limitError) = ParseLimit(context);
if (limitError is not null) return limitError;
var (cursor, cursorTime, cursorError) = ParseCursor(context, $"user:{actor.Id}");
if (cursorError is not null) return cursorError;
var page = await chats.ListAsync(actor.Id, cursorTime, cursor?.Id, limit + 1);
string? nextCursor = null;
if (page.Count > limit)
{
var last = page[limit - 1];
nextCursor = CursorService.EncodeChatCursor(new ChatCursor($"user:{actor.Id}", last.CreatedAt, last.Id));
page = page.Take(limit).ToList();
}
return Results.Ok(new { items = page, next_cursor = nextCursor });
});
app.MapGet("/api/v1/chats/{chat_id}", async (
string chat_id, HttpContext context, SessionService sessions, ChatService chats) =>
{
var (actor, _) = await sessions.AuthenticateAsync(context);
if (actor is null) return Unauthorized(context);
if (!Guid.TryParse(chat_id, out var chatId))
return ApiError(context, 400, "invalid_request", "Некорректный chat_id");
var chat = await chats.FindForMemberAsync(chatId, actor.Id);
return chat is null
? ApiError(context, 404, "not_found", "Чат не найден")
: Results.Ok(chat);
});
return app;
}
}
@@ -0,0 +1,17 @@
using Messenger.Api.Data;
using Messenger.Api.Services;
namespace Messenger.Api.Endpoints;
public static class HealthEndpoints
{
public static IEndpointRouteBuilder MapHealthEndpoints(this IEndpointRouteBuilder app)
{
app.MapGet("/health/live", () => Results.Ok(new { status = "ok" }));
app.MapGet("/health/ready", async (HttpContext context, AppDatabase database) =>
await database.IsReadyAsync()
? Results.Ok(new { status = "ok" })
: ApiSupport.ApiError(context, 503, "unavailable", "База данных недоступна"));
return app;
}
}
@@ -0,0 +1,57 @@
using Messenger.Api.Contracts;
using Messenger.Api.Services;
using static Messenger.Api.Services.ApiSupport;
namespace Messenger.Api.Endpoints;
public static class MessageEndpoints
{
public static IEndpointRouteBuilder MapMessageEndpoints(this IEndpointRouteBuilder app)
{
app.MapPost("/api/v1/chats/{chat_id}/messages", async (
string chat_id, HttpContext context, SessionService sessions, ChatService chats, MessageService messages) =>
{
var (actor, _) = await sessions.AuthenticateAsync(context);
if (actor is null) return Unauthorized(context);
if (!Guid.TryParse(chat_id, out var chatId))
return ApiError(context, 400, "invalid_request", "Некорректный chat_id");
if (await chats.FindForMemberAsync(chatId, actor.Id) is null)
return ApiError(context, 404, "not_found", "Чат не найден");
var (request, error) = await ReadJsonAsync<CreateMessageRequest>(context);
if (error is not null) return error;
if (string.IsNullOrWhiteSpace(request!.Text) || request.Text.EnumerateRunes().Count() > 4000)
return ApiError(context, 400, "invalid_request", "Некорректный текст сообщения");
var message = await messages.CreateAsync(chatId, actor.Id, request.Text);
return Results.Json(message, statusCode: StatusCodes.Status201Created);
});
app.MapGet("/api/v1/chats/{chat_id}/messages", async (
string chat_id, HttpContext context, SessionService sessions, ChatService chats, MessageService messages) =>
{
var (actor, _) = await sessions.AuthenticateAsync(context);
if (actor is null) return Unauthorized(context);
if (!Guid.TryParse(chat_id, out var chatId))
return ApiError(context, 400, "invalid_request", "Некорректный chat_id");
if (await chats.FindForMemberAsync(chatId, actor.Id) is null)
return ApiError(context, 404, "not_found", "Чат не найден");
var (limit, limitError) = ParseLimit(context);
if (limitError is not null) return limitError;
var (cursor, cursorTime, cursorError) = ParseCursor(context, $"chat:{chatId}");
if (cursorError is not null) return cursorError;
var page = await messages.ListAsync(chatId, cursorTime, cursor?.Id, limit + 1);
string? nextCursor = null;
if (page.Count > limit)
{
var last = page[limit - 1];
nextCursor = CursorService.EncodeChatCursor(new ChatCursor($"chat:{chatId}", last.CreatedAt, last.Id));
page = page.Take(limit).ToList();
}
return Results.Ok(new { items = page, next_cursor = nextCursor });
});
return app;
}
}
@@ -0,0 +1,51 @@
using Messenger.Api.Contracts;
using Messenger.Api.Services;
using static Messenger.Api.Services.ApiSupport;
namespace Messenger.Api.Endpoints;
public static class UiEndpoints
{
// The required /api/v1 history stays ascending. The web client has a separate,
// optional route to open a large chat at its newest page and page backwards.
public static IEndpointRouteBuilder MapUiEndpoints(this IEndpointRouteBuilder app)
{
app.MapGet("/api/ui/chats/{chat_id}/members", async (
string chat_id, HttpContext context, SessionService sessions, ChatService chats, UserService users) =>
{
var (actor, _) = await sessions.AuthenticateAsync(context);
if (actor is null) return Unauthorized(context);
if (!Guid.TryParse(chat_id, out var chatId))
return ApiError(context, 400, "invalid_request", "Некорректный chat_id");
if (await chats.FindForMemberAsync(chatId, actor.Id) is null)
return ApiError(context, 404, "not_found", "Чат не найден");
return Results.Ok(new { items = await users.ListForChatAsync(chatId) });
});
app.MapGet("/api/ui/chats/{chat_id}/messages", async (
string chat_id, HttpContext context, SessionService sessions, ChatService chats, MessageService messages) =>
{
var (actor, _) = await sessions.AuthenticateAsync(context);
if (actor is null) return Unauthorized(context);
if (!Guid.TryParse(chat_id, out var chatId))
return ApiError(context, 400, "invalid_request", "Некорректный chat_id");
if (await chats.FindForMemberAsync(chatId, actor.Id) is null)
return ApiError(context, 404, "not_found", "Чат не найден");
var (limit, limitError) = ParseLimit(context);
if (limitError is not null) return limitError;
var (cursor, cursorTime, cursorError) = ParseCursor(context, $"recent-chat:{chatId}");
if (cursorError is not null) return cursorError;
var page = await messages.ListAsync(chatId, cursorTime, cursor?.Id, limit + 1, newestFirst: true);
string? nextCursor = null;
if (page.Count > limit)
{
var last = page[limit - 1];
nextCursor = CursorService.EncodeChatCursor(new ChatCursor($"recent-chat:{chatId}", last.CreatedAt, last.Id));
page = page.Take(limit).ToList();
}
return Results.Ok(new { items = page, next_cursor = nextCursor });
});
return app;
}
}
@@ -0,0 +1,40 @@
using System.Text.RegularExpressions;
using Messenger.Api.Contracts;
using Messenger.Api.Services;
using static Messenger.Api.Services.ApiSupport;
namespace Messenger.Api.Endpoints;
public static class UserEndpoints
{
public static IEndpointRouteBuilder MapUserEndpoints(this IEndpointRouteBuilder app)
{
app.MapPost("/api/v1/users", async (HttpContext context, UserService users) =>
{
var (request, error) = await ReadJsonAsync<CreateUserRequest>(context);
if (error is not null) return error;
if (request!.Username is null || !Regex.IsMatch(request.Username, "\\A[a-z0-9_]{3,32}\\z"))
return ApiError(context, 400, "invalid_request", "Некорректный username");
if (string.IsNullOrWhiteSpace(request.DisplayName) ||
request.DisplayName.EnumerateRunes().Count() is < 1 or > 100)
return ApiError(context, 400, "invalid_request", "Некорректный display_name");
if (string.IsNullOrWhiteSpace(request.Password) ||
request.Password.EnumerateRunes().Count() is < 12 or > 128)
return ApiError(context, 400, "invalid_request", "Пароль должен содержать 12-128 символов");
var user = await users.RegisterAsync(request.Username, request.DisplayName, request.Password);
return user is null
? ApiError(context, 409, "conflict", "Username уже занят")
: Results.Json(user, statusCode: StatusCodes.Status201Created);
});
app.MapGet("/api/v1/users/me", async (HttpContext context, SessionService sessions) =>
{
var (user, _) = await sessions.AuthenticateAsync(context);
return user is null ? Unauthorized(context) : Results.Ok(user);
});
return app;
}
}
@@ -0,0 +1,58 @@
using System.Text.Json;
using Messenger.Api.Contracts;
using StackExchange.Redis;
namespace Messenger.Api.Infrastructure;
// PostgreSQL validates the session on every request. This cache saves the user lookup
// and never grants access independently of the durable session row.
public sealed class RedisSessionCache(IConnectionMultiplexer connection, ILogger<RedisSessionCache> logger)
{
private static readonly TimeSpan OperationBudget = TimeSpan.FromMilliseconds(750);
private static string Key(byte[] hash) => "messenger:session:" + Convert.ToHexString(hash).ToLowerInvariant();
public sealed record Entry(UserDto User, DateTime ExpiresAt);
public async Task<Entry?> GetAsync(byte[] hash)
{
if (!connection.IsConnected) return null;
try
{
var value = await connection.GetDatabase().StringGetAsync(Key(hash)).WaitAsync(OperationBudget);
return value.IsNullOrEmpty ? null : JsonSerializer.Deserialize<Entry>(value.ToString());
}
catch (Exception exception) when (exception is RedisException or TimeoutException or OperationCanceledException or JsonException)
{
logger.LogWarning("Session cache read unavailable; using PostgreSQL");
return null;
}
}
public async Task SetAsync(byte[] hash, UserDto user, DateTime expiresAt)
{
var remaining = expiresAt - DateTime.UtcNow;
if (!connection.IsConnected || remaining <= TimeSpan.Zero) return;
try
{
await connection.GetDatabase().StringSetAsync(Key(hash),
JsonSerializer.Serialize(new Entry(user, expiresAt)), remaining).WaitAsync(OperationBudget);
}
catch (Exception exception) when (exception is RedisException or TimeoutException or OperationCanceledException)
{
logger.LogWarning("Session cache write unavailable; using PostgreSQL");
}
}
public async Task RemoveAsync(byte[] hash)
{
if (!connection.IsConnected) return;
try
{
await connection.GetDatabase().KeyDeleteAsync(Key(hash)).WaitAsync(OperationBudget);
}
catch (Exception exception) when (exception is RedisException or TimeoutException or OperationCanceledException)
{
logger.LogWarning("Session cache invalidation unavailable; PostgreSQL still enforces revocation");
}
}
}
+19
View File
@@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<EmbeddedResource Include="Data/Migrations/*.sql" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Isopoh.Cryptography.Argon2" Version="2.0.0" />
<PackageReference Include="Npgsql" Version="9.0.5" />
<PackageReference Include="StackExchange.Redis" Version="2.8.58" />
</ItemGroup>
</Project>
@@ -0,0 +1,28 @@
using Messenger.Api.Services;
using System.Net.Sockets;
using Npgsql;
namespace Messenger.Api.Middleware;
public sealed class ExceptionHandlingMiddleware(RequestDelegate next, ILogger<ExceptionHandlingMiddleware> logger)
{
public async Task InvokeAsync(HttpContext context)
{
try
{
await next(context);
}
catch (Exception exception) when (exception is NpgsqlException or SocketException or TimeoutException)
{
logger.LogError(exception, "Database request failed");
if (!context.Response.HasStarted)
await ApiSupport.ApiError(context, 503, "unavailable", "Сервис временно недоступен").ExecuteAsync(context);
}
catch (Exception exception)
{
logger.LogError(exception, "Request failed");
if (!context.Response.HasStarted)
await ApiSupport.ApiError(context, 500, "internal_error", "Внутренняя ошибка").ExecuteAsync(context);
}
}
}
@@ -0,0 +1,16 @@
namespace Messenger.Api.Middleware;
public sealed class RequestIdMiddleware
{
private readonly RequestDelegate _next;
public RequestIdMiddleware(RequestDelegate next) => _next = next;
public async Task InvokeAsync(HttpContext context)
{
var requestId = Guid.NewGuid().ToString();
context.Items["RequestId"] = requestId;
context.Response.Headers["X-Request-Id"] = requestId;
await _next(context);
}
}
@@ -0,0 +1,25 @@
namespace Messenger.Api.Middleware;
public sealed class RequestLoggingMiddleware
{
private readonly RequestDelegate _next;
public RequestLoggingMiddleware(RequestDelegate next) => _next = next;
public async Task InvokeAsync(HttpContext context)
{
var logger = context.RequestServices
.GetRequiredService<ILoggerFactory>()
.CreateLogger("Http");
await _next(context);
logger.LogInformation(
"{Method} {Path} -> {StatusCode} request_id={RequestId}",
context.Request.Method,
context.Request.Path,
context.Response.StatusCode,
context.Items["RequestId"]
);
}
}
+73
View File
@@ -0,0 +1,73 @@
using System.Text.Json;
using System.Text.Json.Serialization;
using Messenger.Api.Data;
using Messenger.Api.Endpoints;
using Messenger.Api.Infrastructure;
using Messenger.Api.Middleware;
using Messenger.Api.Services;
using Npgsql;
using StackExchange.Redis;
var builder = WebApplication.CreateBuilder(args);
var host = Environment.GetEnvironmentVariable("APP_HOST") ?? "0.0.0.0";
var port = Environment.GetEnvironmentVariable("APP_PORT") ?? "8080";
builder.WebHost.UseUrls($"http://{host}:{port}");
builder.Services.ConfigureHttpJsonOptions(options =>
{
options.SerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower;
options.SerializerOptions.UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow;
});
var databaseUrlFile = Environment.GetEnvironmentVariable("DATABASE_URL_FILE");
var databaseUrl = databaseUrlFile is not null
? File.ReadAllText(databaseUrlFile).Trim()
: Environment.GetEnvironmentVariable("DATABASE_URL");
if (string.IsNullOrWhiteSpace(databaseUrl))
throw new InvalidOperationException("Set DATABASE_URL_FILE or DATABASE_URL before starting the API");
var connectionString = new NpgsqlConnectionStringBuilder(databaseUrl)
{
MaxPoolSize = 20,
Timeout = 5,
CommandTimeout = 10
};
var dataSource = NpgsqlDataSource.Create(connectionString.ConnectionString);
builder.Services.AddSingleton(dataSource);
builder.Services.AddSingleton<AppDatabase>();
var redisOptions = ConfigurationOptions.Parse(builder.Configuration["REDIS_URL"] ?? "localhost:6379");
redisOptions.AbortOnConnectFail = false;
redisOptions.ConnectTimeout = 500;
redisOptions.ConnectRetry = 0;
redisOptions.AsyncTimeout = 500;
redisOptions.SyncTimeout = 500;
redisOptions.BacklogPolicy = BacklogPolicy.FailFast;
builder.Services.AddSingleton<IConnectionMultiplexer>(await ConnectionMultiplexer.ConnectAsync(redisOptions));
builder.Services.AddSingleton<RedisSessionCache>();
builder.Services.AddSingleton<PasswordService>();
builder.Services.AddSingleton<UserService>();
builder.Services.AddSingleton<SessionService>();
builder.Services.AddSingleton<ChatService>();
builder.Services.AddSingleton<MessageService>();
var app = builder.Build();
await DatabaseMigrator.ApplyAsync(dataSource);
app.UseMiddleware<RequestIdMiddleware>();
app.UseMiddleware<RequestLoggingMiddleware>();
app.UseMiddleware<ExceptionHandlingMiddleware>();
app.UseDefaultFiles();
app.UseStaticFiles(new StaticFileOptions
{
OnPrepareResponse = context => context.Context.Response.Headers.CacheControl = "no-cache"
});
app.MapHealthEndpoints();
app.MapUserEndpoints();
app.MapAuthEndpoints();
app.MapChatEndpoints();
app.MapMessageEndpoints();
app.MapUiEndpoints();
app.Run();
@@ -0,0 +1,23 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:5052",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7253;http://localhost:5052",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
+93
View File
@@ -0,0 +1,93 @@
using System.Globalization;
using System.Text.Json;
using Messenger.Api.Contracts;
namespace Messenger.Api.Services;
public static class ApiSupport
{
public static async Task<(T? Value, IResult? Error)> ReadJsonAsync<T>(HttpContext context)
{
if (!context.Request.HasJsonContentType())
return (default, ApiError(context, 400, "invalid_request", "Требуется application/json"));
try
{
var value = await context.Request.ReadFromJsonAsync<T>();
return value is null
? (default, ApiError(context, 400, "invalid_request", "Тело запроса обязательно"))
: (value, null);
}
catch (Exception exception) when (exception is JsonException or NotSupportedException or BadHttpRequestException)
{
return (default, ApiError(context, 400, "invalid_request", "Некорректный JSON"));
}
}
public static IResult Unauthorized(HttpContext context, bool basic = false)
{
context.Response.Headers["WWW-Authenticate"] = basic
? "Basic realm=\"messenger\", charset=\"UTF-8\""
: "Bearer realm=\"messenger\"";
return ApiError(context, 401, "unauthorized", "Требуется действительная сессия");
}
public static (ChatCursor? Cursor, DateTime? Time, IResult? Error) ParseCursor(
HttpContext context, string scope)
{
if (!context.Request.Query.TryGetValue("cursor", out var value))
return (null, null, null);
var cursor = CursorService.DecodeChatCursor(value.ToString());
if (cursor is null || cursor.Scope != scope || cursor.Id == Guid.Empty ||
!DateTime.TryParse(cursor.CreatedAt, CultureInfo.InvariantCulture,
DateTimeStyles.RoundtripKind, out var time) || time.Kind != DateTimeKind.Utc)
return (null, null, ApiError(context, 400, "invalid_request", "Некорректный cursor"));
return (cursor, time, null);
}
public static (int Limit, IResult? Error) ParseLimit(HttpContext context)
{
const int defaultLimit = 50;
if (!context.Request.Query.TryGetValue("limit", out var value))
return (defaultLimit, null);
if (!int.TryParse(value.ToString(), out var limit) ||
limit < 1 ||
limit > 100)
{
return (
0,
ApiError(context, 400, "invalid_request", "limit должен быть от 1 до 100")
);
}
return (limit, null);
}
public static IResult ApiError(
HttpContext context,
int status,
string code,
string message)
{
var requestId =
context.Items["RequestId"]?.ToString()
?? Guid.NewGuid().ToString();
return Results.Json(
new
{
error = new
{
code,
message,
request_id = requestId
}
},
statusCode: status
);
}
}
+16
View File
@@ -0,0 +1,16 @@
using Messenger.Api.Contracts;
using Messenger.Api.Data;
namespace Messenger.Api.Services;
public sealed class ChatService(AppDatabase database)
{
public async Task<ChatDto?> CreateAsync(string title, List<Guid> memberIds) =>
(await database.CreateChatAsync(title, memberIds))?.ToDto();
public async Task<ChatDto?> FindForMemberAsync(Guid chatId, Guid userId) =>
(await database.FindChatForMemberAsync(chatId, userId))?.ToDto();
public async Task<List<ChatDto>> ListAsync(Guid userId, DateTime? cursorTime, Guid? cursorId, int count) =>
(await database.ListChatsAsync(userId, cursorTime, cursorId, count)).Select(chat => chat.ToDto()).ToList();
}
@@ -0,0 +1,49 @@
using System.Text;
using System.Text.Json;
using Messenger.Api.Contracts;
namespace Messenger.Api.Services;
public static class CursorService
{
public static string EncodeChatCursor(ChatCursor cursor)
{
var json = JsonSerializer.Serialize(cursor);
return Convert.ToBase64String(Encoding.UTF8.GetBytes(json))
.TrimEnd('=')
.Replace('+', '-')
.Replace('/', '_');
}
public static ChatCursor? DecodeChatCursor(string cursor)
{
try
{
var base64 = cursor
.Replace('-', '+')
.Replace('_', '/');
switch (base64.Length % 4)
{
case 2:
base64 += "==";
break;
case 3:
base64 += "=";
break;
case 1:
return null;
}
var bytes = Convert.FromBase64String(base64);
var json = Encoding.UTF8.GetString(bytes);
return JsonSerializer.Deserialize<ChatCursor>(json);
}
catch
{
return null;
}
}
}
@@ -0,0 +1,13 @@
using Messenger.Api.Contracts;
using Messenger.Api.Data;
namespace Messenger.Api.Services;
public sealed class MessageService(AppDatabase database)
{
public async Task<MessageDto> CreateAsync(Guid chatId, Guid senderId, string text) =>
(await database.CreateMessageAsync(chatId, senderId, text)).ToDto();
public async Task<List<MessageDto>> ListAsync(Guid chatId, DateTime? cursorTime, Guid? cursorId, int count, bool newestFirst = false) =>
(await database.ListMessagesAsync(chatId, cursorTime, cursorId, count, newestFirst)).Select(message => message.ToDto()).ToList();
}
@@ -0,0 +1,28 @@
using System.Security.Cryptography;
using System.Text;
using Isopoh.Cryptography.Argon2;
namespace Messenger.Api.Services;
public sealed class PasswordService
{
public string Hash(string password)
{
var salt = RandomNumberGenerator.GetBytes(16);
var config = new Argon2Config
{
Type = Argon2Type.HybridAddressing,
Version = Argon2Version.Nineteen,
TimeCost = 3,
MemoryCost = 32768,
Lanes = 1,
Threads = 1,
Password = Encoding.UTF8.GetBytes(password),
Salt = salt,
HashLength = 32
};
return Argon2.Hash(config);
}
public bool Verify(string hash, string password) => Argon2.Verify(hash, password);
}
@@ -0,0 +1,65 @@
using System.Security.Cryptography;
using System.Text;
using Messenger.Api.Contracts;
using Messenger.Api.Data;
using Messenger.Api.Infrastructure;
namespace Messenger.Api.Services;
public sealed class SessionService(AppDatabase database, PasswordService passwords, RedisSessionCache cache, IConfiguration configuration)
{
private readonly int _ttlSeconds = int.TryParse(configuration["SESSION_TTL_SECONDS"], out var ttl) && ttl > 0
? ttl : 3600;
public async Task<SessionDto?> LoginAsync(string username, string password)
{
var user = await database.FindUserByUsernameAsync(username);
if (user is null || !passwords.Verify(user.PasswordHash, password))
return null;
var token = Convert.ToBase64String(RandomNumberGenerator.GetBytes(32))
.TrimEnd('=').Replace('+', '-').Replace('/', '_');
var expiresAt = UtcClock.Now().AddSeconds(_ttlSeconds);
var hash = HashToken(token);
await database.CreateSessionAsync(hash, user.Id, expiresAt);
await cache.SetAsync(hash, user.ToDto(), expiresAt);
return new SessionDto(token, "Bearer", expiresAt.ToString("O"), user.ToDto());
}
public async Task<(UserDto? User, byte[]? TokenHash)> AuthenticateAsync(HttpContext context)
{
if (!context.Request.Headers.TryGetValue("Authorization", out var value))
return (null, null);
var authorization = value.ToString();
if (!authorization.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
return (null, null);
var token = authorization[7..];
if (token.Length != 43 || token.Any(c => !char.IsAsciiLetterOrDigit(c) && c != '-' && c != '_'))
return (null, null);
var hash = HashToken(token);
var session = await database.FindActiveSessionAsync(hash);
if (session is null) return (null, null);
var cached = await cache.GetAsync(hash);
if (cached is not null && cached.User.Id == session.UserId && cached.ExpiresAt == session.ExpiresAt)
return (cached.User, hash);
var user = await database.FindUserByIdAsync(session.UserId);
if (user is null) return (null, null);
var dto = user.ToDto();
await cache.SetAsync(hash, dto, session.ExpiresAt);
return (dto, hash);
}
public async Task<bool> RevokeAsync(byte[] tokenHash)
{
var revoked = await database.RevokeSessionAsync(tokenHash);
if (revoked) await cache.RemoveAsync(tokenHash);
return revoked;
}
private static byte[] HashToken(string token) => SHA256.HashData(Encoding.ASCII.GetBytes(token));
}
+24
View File
@@ -0,0 +1,24 @@
using Messenger.Api.Contracts;
using Messenger.Api.Data;
using Npgsql;
namespace Messenger.Api.Services;
public sealed class UserService(AppDatabase database, PasswordService passwords)
{
public async Task<List<UserDto>> ListForChatAsync(Guid chatId) =>
(await database.ListChatUsersAsync(chatId)).Select(user => user.ToDto()).ToList();
public async Task<UserDto?> RegisterAsync(string username, string displayName, string password)
{
var hash = passwords.Hash(password);
try
{
return (await database.CreateUserAsync(username, displayName, hash)).ToDto();
}
catch (PostgresException exception) when (exception.SqlState == PostgresErrorCodes.UniqueViolation)
{
return null;
}
}
}
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
+9
View File
@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
+408
View File
@@ -0,0 +1,408 @@
:root {
color-scheme: dark;
--ink: #FFE135;
--muted: #b6b5aa;
--accent: #FFE135;
--accent-hover: #ffeb79;
--paper: #262626;
--surface: #303030;
--soft: #38382c;
--border: #414139;
--danger: #ffaaa0;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
color: var(--ink);
background: #262626;
font-size: 15px;
}
* { box-sizing: border-box; }
body { margin: 0; }
button, input, textarea { font: inherit; }
button, a, input, textarea { -webkit-tap-highlight-color: transparent; }
button { cursor: pointer; }
button:disabled { cursor: default; opacity: .5; }
button, textarea, input { outline: none; }
button:focus-visible, a:focus-visible { outline: 2px solid var(--accent); outline-offset: 4px; }
input:focus, textarea:focus { border-color: var(--accent); box-shadow: 0 0 0 3px #ffe13515; }
a { color: inherit; text-decoration: none; }
[hidden] { display: none !important; }
svg { width: 21px; height: 21px; fill: none; stroke: currentColor; stroke-width: 1.7; stroke-linecap: round; stroke-linejoin: round; flex-shrink: 0; }
.svg-sprite { position: absolute; width: 0; height: 0; overflow: hidden; }
.visually-hidden { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0,0,0,0); white-space: nowrap; border: 0; }
::selection { color: #262626; background: var(--accent); }
/* Brand and shared controls */
.brand { display: inline-flex; align-items: center; font-size: 30px; font-weight: 750; letter-spacing: -1.6px; gap: 10px; line-height: 1; }
.brand-dot { color: var(--accent); margin-left: -8px; }
.brand-mark { height: 36px; width: 36px; background: var(--accent); border-radius: 12px; display: flex; flex-direction: column; justify-content: center; gap: 4px; padding: 9px; }
.brand-mark i { display: block; height: 2px; border-radius: 2px; background: #262626; }
.brand-mark i:nth-child(2) { width: 75%; }
.brand-mark i:nth-child(3) { width: 45%; }
.eyebrow { display: block; color: var(--muted); font-size: 10px; font-weight: 650; letter-spacing: 2px; text-transform: uppercase; line-height: 1.6; }
.muted { color: var(--muted); font-size: 14px; line-height: 1.7; }
label { display: grid; gap: 9px; font-size: 12px; font-weight: 550; color: var(--ink); }
input, textarea { width: 100%; color: var(--ink); background: #292929; border: 1px solid #4b4b42; border-radius: 12px; padding: 14px 15px; font-size: 14px; transition: border-color .18s, box-shadow .18s; }
input::placeholder, textarea::placeholder { color: #a6a69a; }
textarea { resize: vertical; line-height: 1.5; }
.field-note { color: var(--muted); font-size: 11px; font-weight: 400; line-height: 1.7; }
.button { display: inline-flex; align-items: center; justify-content: center; gap: 10px; border-radius: 12px; border: 1px solid transparent; padding: 14px 20px; font-weight: 650; font-size: 13px; transition: background .18s, transform .18s; }
.button.primary { background: var(--accent); color: #262626; }
.button.primary:hover { background: var(--accent-hover); transform: translateY(-1px); }
.button.secondary { background: #3a3a32; border-color: var(--border); color: var(--ink); }
.button.secondary:hover { background: #454538; }
.button.wide { width: 100%; }
.icon-button { display: inline-flex; align-items: center; justify-content: center; border: 1px solid transparent; background: transparent; color: var(--muted); width: 36px; height: 36px; border-radius: 11px; flex-shrink: 0; transition: background .18s, color .18s; }
.icon-button:hover { background: #3c3c32; color: var(--accent); }
.icon-button.filled { background: var(--accent); color: #262626; }
.icon-button.filled:hover { background: var(--accent-hover); }
.text-button { background: none; border: 0; color: var(--accent); font-size: 11px; padding: 10px 14px; border-radius: 9px; }
.text-button:hover { background: #ffe1350e; }
.form-notice { color: var(--danger); font-size: 12px; line-height: 1.6; background: #452f2d; border: 1px solid #70453e; border-radius: 10px; padding: 11px 13px; }
.form-notice.success { color: var(--ink); background: var(--soft); border-color: #686032; }
/* Entry screen */
.auth-layout { min-height: 100svh; display: grid; grid-template-columns: 1.1fr 1fr; max-width: 1440px; margin: auto; }
.intro { position: relative; min-height: 760px; padding: 50px 64px 40px; overflow: hidden; background: radial-gradient(ellipse at 5% 95%, #ffe13508, transparent 65%), var(--paper); }
.intro::before { content: ""; position: absolute; inset: auto auto -270px -250px; width: 760px; height: 760px; border: 1px solid #ffe13520; border-radius: 50%; pointer-events: none; }
.intro::after { content: ""; position: absolute; right: -190px; top: 90px; width: 440px; height: 440px; border: 1px solid #ffe13512; border-radius: 50%; pointer-events: none; }
.intro-copy { margin-top: 82px; position: relative; z-index: 1; }
.intro-copy .eyebrow { color: var(--accent); padding-left: 22px; position: relative; }
.intro-copy .eyebrow::before { content: ""; width: 7px; height: 7px; background: var(--accent); border-radius: 50%; position: absolute; left: 0; top: 5px; }
.intro h1 { font-size: clamp(48px, 5vw, 72px); line-height: 1.04; font-weight: 700; letter-spacing: -3.5px; margin: 22px 0 26px; }
.intro em, .welcome em { font-family: Georgia, "Times New Roman", serif; font-weight: 400; color: var(--accent); }
.intro-copy p { color: var(--muted); line-height: 1.8; font-size: 15px; }
.conversation-art { position: relative; width: 330px; height: 165px; margin: 38px 0 25px 34px; z-index: 1; }
.art-bubble { position: absolute; padding: 17px 22px 13px; border-radius: 18px; font-size: 14px; box-shadow: 0 12px 30px #00000020; }
.art-bubble span { display: block; font-size: 10px; text-align: right; margin-top: 8px; opacity: .65; }
.art-bubble b { font-weight: 500; }
.art-one { background: #353530; border: 1px solid #4a4a3c; left: 0; top: 0; transform: rotate(-4deg); border-bottom-left-radius: 5px; min-width: 195px; }
.art-two { background: var(--accent); color: #262626; right: 0; top: 67px; transform: rotate(3deg); border-bottom-right-radius: 5px; min-width: 218px; }
.art-typing { position: absolute; bottom: 0; left: 15px; display: flex; gap: 5px; border-radius: 12px; background: #353530; border: 1px solid var(--border); padding: 13px 19px; }
.art-typing i { background: var(--accent); width: 5px; height: 5px; border-radius: 50%; }
.art-orbit { position: absolute; right: -45px; top: 5px; width: 11px; height: 11px; background: var(--accent); border-radius: 50%; box-shadow: 0 0 0 9px #ffe13508; }
.intro-footer { font-size: 11px; color: var(--muted); display: flex; align-items: center; gap: 9px; margin-top: 38px; position: relative; }
.status-dot { height: 6px; width: 6px; background: var(--accent); border-radius: 50%; }
.auth-side { background: #2c2c2a; border-left: 1px solid var(--border); display: flex; flex-direction: column; justify-content: center; align-items: center; padding: 50px 64px 25px; min-height: 760px; }
.auth-card { width: 100%; max-width: 360px; }
.auth-switch { display: flex; padding: 5px; background: #222222; border: 1px solid #404037; border-radius: 14px; margin-bottom: 42px; }
.auth-switch button { width: 50%; background: transparent; border: 0; border-radius: 9px; color: var(--muted); padding: 11px; font-size: 12px; font-weight: 600; }
.auth-switch .active { background: var(--accent); color: #262626; box-shadow: 0 3px 12px #00000018; }
.auth-card h2 { font-weight: 650; font-size: 40px; letter-spacing: -1.7px; line-height: 1.15; margin: 12px 0; }
.auth-card .muted { margin: 13px 0 30px; }
.auth-card form { display: grid; gap: 20px; }
.auth-card .wide { margin-top: 5px; justify-content: space-between; }
.auth-card .wide > span { font-size: 21px; line-height: 1; }
.auth-footnote { font-size: 11px; color: var(--muted); margin: 24px 0; text-align: center; }
.auth-bottom { color: var(--muted); font-size: 10px; letter-spacing: .6px; margin-top: 40px; }
/* Conversations */
.app-shell { display: grid; grid-template-columns: 310px minmax(0,1fr); height: calc(100svh - 44px); max-width: 1440px; margin: 22px auto; border: 1px solid #46463c; border-radius: 24px; overflow: hidden; box-shadow: 0 20px 70px #00000025; background: var(--paper); }
.sidebar { min-height: 0; background: #222222; border-right: 1px solid var(--border); display: flex; flex-direction: column; padding: 29px 19px 0; }
.sidebar-top { display: flex; align-items: center; justify-content: space-between; padding: 0 9px; }
.sidebar .brand { font-size: 28px; }
.sidebar .brand-mark { width: 32px; height: 32px; border-radius: 10px; }
.sidebar-heading { display: flex; justify-content: space-between; align-items: center; padding: 35px 9px 22px; }
.sidebar-heading .eyebrow { font-size: 9px; letter-spacing: 1.7px; }
.sidebar-heading h2 { margin: 6px 0 0; font-size: 22px; font-weight: 650; letter-spacing: -.7px; }
.count { font-size: 11px; font-weight: 600; background: #ffe13516; border: 1px solid #ffe13525; border-radius: 7px; margin-left: 9px; padding: 3px 7px; vertical-align: middle; color: var(--accent); }
.count:empty { display: none; }
.search-field { display: flex; align-items: center; background: #2d2d2b; border: 1px solid #414139; border-radius: 12px; margin: 0 9px 22px; padding: 0 11px; gap: 8px; }
.search-field > span:not(.visually-hidden) { font-size: 25px; line-height: 1; color: var(--muted); }
.search-field input { border: 0; background: transparent; padding: 12px 0; font-size: 12px; box-shadow: none; }
.search-field:focus-within { border-color: var(--accent); }
.chat-list { flex: 1; overflow: auto; min-height: 0; scrollbar-width: thin; scrollbar-color: #646451 transparent; }
.chat-row { display: flex; align-items: center; gap: 13px; position: relative; border: 1px solid transparent; background: transparent; text-align: left; padding: 15px 11px; width: 100%; border-radius: 14px; color: var(--ink); margin-bottom: 6px; transition: background .18s, border-color .18s; }
.chat-row:hover { background: #2e2e29; }
.chat-row.active { background: #ffe1350f; border-color: #ffe13540; }
.chat-row.active::after { content: ""; position: absolute; right: 11px; height: 6px; width: 6px; border-radius: 50%; background: var(--accent); box-shadow: 0 0 0 4px #ffe1350b; }
.avatar { display: flex; align-items: center; justify-content: center; width: 43px; height: 43px; border-radius: 14px; background: #45432a; color: var(--accent); font-size: 14px; font-weight: 650; flex-shrink: 0; letter-spacing: -.5px; border: 1px solid #ffe1351a; }
.avatar.tone-1 { background: #4b3e2a; color: #ffd68a; border-color: #ffd68a20; }
.avatar.tone-2 { background: #3b4032; color: #d9df9d; border-color: #d9df9d20; }
.avatar.tone-3 { background: #493b36; color: #edc5a5; border-color: #edc5a520; }
.chat-row.active .avatar { background: var(--accent); color: #262626; border-color: transparent; }
.chat-row-text { display: grid; gap: 6px; min-width: 0; flex: 1; }
.chat-row strong { font-size: 13px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; padding-right: 10px; }
.chat-row small { font-size: 11px; color: var(--muted); }
.list-empty { font-size: 12px; text-align: center; line-height: 1.7; color: var(--muted); padding: 20px 15px; }
.profile { border-top: 1px solid var(--border); display: flex; align-items: center; gap: 6px; margin-top: 12px; padding: 20px 7px; }
.profile-main { display: flex; align-items: center; gap: 11px; text-align: left; background: none; border: 0; padding: 0; min-width: 0; flex: 1; color: var(--ink); }
.profile .avatar { border-radius: 50%; background: #39392c; color: var(--accent); width: 37px; height: 37px; font-size: 12px; }
.profile-text { display: grid; gap: 5px; min-width: 0; }
.profile-text strong { font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-weight: 600; }
.profile-text > span { font-size: 10px; color: var(--muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.workspace { min-width: 0; min-height: 0; position: relative; background: var(--paper); }
.welcome { height: 100%; display: flex; align-items: center; justify-content: center; flex-direction: column; text-align: center; position: relative; padding: 35px; background: radial-gradient(ellipse at center, #ffe13505, transparent 70%); }
.welcome-symbol { width: 110px; height: 110px; background: #ffe1350b; border: 1px solid #ffe13529; border-radius: 34px; position: relative; display: flex; align-items: center; justify-content: center; margin-bottom: 34px; transform: rotate(-6deg); }
.welcome-symbol svg { width: 44px; height: 44px; color: var(--accent); stroke-width: 1.4; transform: rotate(6deg); }
.tiny-dot { position: absolute; width: 17px; height: 17px; right: -4px; top: 4px; border-radius: 50%; background: var(--accent); border: 4px solid var(--paper); }
.welcome .eyebrow { font-size: 9px; letter-spacing: 1.5px; }
.welcome h1 { font-weight: 650; font-size: 43px; letter-spacing: -1.7px; line-height: 1.2; margin: 18px 0; }
.welcome p { font-size: 13px; line-height: 1.8; color: var(--muted); margin: 0 0 27px; }
.welcome .button svg { width: 17px; height: 17px; }
.welcome-bottom { position: absolute; bottom: 30px; font-size: 10px; color: var(--muted); letter-spacing: .4px; }
.conversation { height: 100%; display: flex; flex-direction: column; }
.chat-header { display: flex; align-items: center; gap: 14px; padding: 21px 30px; border-bottom: 1px solid var(--border); min-height: 90px; background: #292929; }
.chat-header .chat-avatar { height: 43px; width: 43px; }
.chat-heading { flex: 1; min-width: 0; }
.chat-heading h2 { font-size: 17px; font-weight: 650; margin: 0 0 6px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; letter-spacing: -.3px; }
.chat-heading span { font-size: 11px; color: var(--muted); }
.message-scroll { flex: 1; min-height: 0; overflow: auto; padding: 12px 32px 24px; scrollbar-width: thin; scrollbar-color: #646451 transparent; scroll-behavior: auto; background: radial-gradient(ellipse at 100% 100%, #ffe13504, transparent 70%); }
.history-control { text-align: center; min-height: 18px; }
.message-list { display: flex; flex-direction: column; gap: 14px; }
.date-separator { align-self: center; background: #30302c; border: 1px solid #414139; border-radius: 20px; padding: 6px 12px; text-align: center; color: var(--muted); font-size: 10px; letter-spacing: .3px; margin: 20px 0 12px; }
.message { max-width: 76%; align-self: flex-start; display: grid; gap: 6px; }
.message.mine { align-self: flex-end; }
.message-author { font-size: 10px; color: var(--muted); padding-left: 8px; }
.message-bubble { background: #343430; border: 1px solid #46463b; border-radius: 17px 17px 17px 5px; padding: 13px 16px 10px; min-width: 90px; box-shadow: 0 4px 14px #00000008; }
.mine .message-bubble { background: var(--accent); color: #262626; border: 1px solid var(--accent); border-radius: 17px 17px 5px 17px; }
.message-text { font-size: 14px; white-space: pre-wrap; overflow-wrap: anywhere; line-height: 1.65; margin: 0; }
.message-time { font-size: 10px; display: block; text-align: right; color: var(--muted); margin-top: 7px; }
.mine .message-time { color: #5c5324; }
.empty-conversation { text-align: center; position: relative; top: 28%; font-size: 13px; color: var(--muted); line-height: 1.9; }
.composer { display: grid; grid-template-columns: minmax(0,1fr) 46px; gap: 10px; align-items: end; border-top: 1px solid var(--border); padding: 20px 29px 16px; background: #292929; }
.composer textarea { border: 1px solid #4b4b42; background: #30302d; border-radius: 13px; padding: 13px 15px; font-size: 14px; resize: none; max-height: 140px; min-height: 47px; scrollbar-width: thin; }
.send-button { display: flex; align-items: center; justify-content: center; background: var(--accent); border: 0; color: #262626; width: 46px; height: 47px; border-radius: 13px; margin-bottom: 1px; transition: background .18s; }
.send-button:hover { background: var(--accent-hover); }
.send-button:disabled { background: #444439; opacity: 1; color: #abab95; }
.send-button svg { height: 21px; width: 21px; }
.composer-note { grid-column: 1/-1; display: flex; justify-content: space-between; font-size: 9px; color: var(--muted); padding: 2px 3px; gap: 15px; }
.composer-note .over-limit { color: var(--danger); }
.mobile-only { display: none; }
.toast { position: fixed; bottom: 27px; left: 50%; transform: translateX(-50%); background: var(--accent); color: #262626; border: 1px solid #ffec7d; box-shadow: 0 8px 35px #00000030; border-radius: 13px; padding: 13px 20px; font-size: 12px; line-height: 1.5; max-width: min(90%,520px); z-index: 20; }
.toast.error { background: #452f2d; color: var(--danger); border-color: #70453e; }
/* Dialogs */
dialog { border: 1px solid #575744; border-radius: 22px; padding: 28px; max-width: 440px; width: calc(100% - 36px); color: var(--ink); background: #2c2c2a; box-shadow: 0 24px 100px #00000060; }
dialog::backdrop { background: #151515aa; backdrop-filter: blur(6px); }
.dialog-heading { display: flex; align-items: center; justify-content: space-between; gap: 15px; }
.dialog-heading h2 { font-size: 25px; font-weight: 650; letter-spacing: -.8px; margin: 0; }
.dialog-heading .icon-button { width: 30px; height: 30px; }
dialog .muted { font-size: 12px; margin: 14px 0 25px; }
dialog form { display: grid; gap: 20px; }
.dialog-actions { display: flex; justify-content: flex-end; gap: 10px; margin-top: 3px; }
#my-id { font-size: 12px; font-family: ui-monospace, monospace; background: #242424; }
#profile-dialog .wide { margin-top: 17px; }
.members-list { display: grid; gap: 16px; padding-top: 25px; }
.member-item { display: grid; gap: 8px; }
.member-item strong { font-size: 13px; font-weight: 550; }
.member-item code { font-size: 11px; overflow-wrap: anywhere; color: var(--muted); background: #242424; border: 1px solid var(--border); padding: 12px; border-radius: 10px; }
/* Optional API explanation panel */
.defense-toggle { display: flex; align-items: center; justify-content: center; gap: 8px; background: transparent; border: 1px solid #515143; border-radius: 11px; padding: 11px 12px; color: var(--muted); font-size: 11px; font-weight: 550; }
.defense-toggle svg { width: 15px; height: 15px; }
.defense-toggle:hover, .defense-toggle[aria-expanded=true] { background: #ffe1350d; border-color: #ffe13565; color: var(--accent); }
.auth-bottom .defense-toggle { margin: 15px auto 0; }
.sidebar-defense { margin: 10px 9px 0; flex-shrink: 0; }
.defense-panel { position: fixed; z-index: 15; right: 30px; top: 108px; width: 330px; max-height: min(56svh,490px); overflow: auto; background: #2c2c2a; border: 1px solid #66603a; border-radius: 20px; box-shadow: 0 18px 55px #00000030; padding: 20px; scrollbar-width: thin; scrollbar-color: #646451 transparent; }
.defense-heading { display: flex; justify-content: space-between; align-items: center; gap: 10px; margin-bottom: 18px; }
.defense-heading .eyebrow { font-size: 9px; letter-spacing: 1.4px; }
.defense-heading h2 { font-size: 19px; font-weight: 650; letter-spacing: -.5px; margin: 5px 0 0; }
.defense-heading .icon-button { width: 30px; height: 30px; }
.defense-label { display: block; font-size: 10px; color: var(--muted); margin-bottom: 6px; }
.defense-summary { display: grid; grid-template-columns: minmax(0,1fr) auto; gap: 14px; background: #ffe1350c; border: 1px solid #ffe13520; border-radius: 12px; padding: 12px; }
.defense-summary strong { display: block; font-size: 11px; overflow-wrap: anywhere; }
.defense-history { padding: 16px 0; border-bottom: 1px solid var(--border); }
.defense-history > strong { display: block; font-size: 13px; overflow-wrap: anywhere; }
.defense-history > p { font-size: 11px; color: var(--muted); margin: 8px 0 0; }
.defense-request { padding-top: 16px; }
.defense-section-heading { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-bottom: 12px; }
.defense-section-heading h3 { font-size: 12px; margin: 0; font-weight: 600; }
.defense-section-heading time { font-size: 10px; color: var(--muted); }
.defense-request-line { display: flex; align-items: center; gap: 8px; }
.defense-method, .defense-status { font: 600 11px ui-monospace, monospace; padding: 6px 8px; border-radius: 6px; background: #404036; color: var(--accent); }
.defense-status { background: var(--accent); color: #262626; }
.defense-status.failed { background: #56332e; color: var(--danger); }
.defense-path { display: block; font: 11px/1.6 ui-monospace, monospace; overflow-wrap: anywhere; color: var(--muted); margin-top: 10px; }
.defense-result { font-size: 12px; line-height: 1.6; color: var(--accent); margin: 10px 0 14px; }
.defense-result.failed { color: var(--danger); }
.defense-metrics { display: grid; grid-template-columns: 1fr 1fr; margin: 0 0 14px; gap: 12px; }
.defense-metrics dt { font-size: 10px; color: var(--muted); margin-bottom: 6px; }
.defense-metrics dd { font: 550 12px ui-monospace, monospace; margin: 0; color: var(--ink); }
.defense-request-id { display: block; font: 10px/1.7 ui-monospace, monospace; overflow-wrap: anywhere; color: var(--muted); }
.defense-previous { list-style: none; margin: 15px 0 0; padding: 12px 0 0; border-top: 1px solid var(--border); display: grid; gap: 10px; }
.defense-previous li { display: flex; gap: 8px; align-items: center; min-width: 0; }
.defense-mini-status { font: 550 10px ui-monospace, monospace; color: var(--accent); min-width: 23px; }
.defense-mini-status.failed { color: var(--danger); }
.defense-previous code { font: 10px ui-monospace, monospace; color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.defense-background { font-size: 10px; color: var(--muted); margin: 12px 0 0; line-height: 1.7; }
.defense-note { font-size: 11px; color: var(--muted); line-height: 1.7; margin: 0; }
.defense-footnote { border-top: 1px solid var(--border); padding-top: 12px; margin-top: 14px; font-size: 10px; }
@media (min-width: 1490px) {
.app-shell { height: calc(100svh - 64px); margin: 32px auto; }
}
@media (max-width: 1100px) {
.intro { padding: 40px 38px; }
.auth-side { padding: 40px 35px; }
.app-shell { margin: 14px; height: calc(100svh - 28px); grid-template-columns: 280px minmax(0,1fr); }
.conversation-art { margin-left: 0; width: 290px; }
.intro h1 { font-size: 56px; }
.sidebar { padding-left: 14px; padding-right: 14px; }
.message-scroll { padding-left: 24px; padding-right: 24px; }
}
@media (max-width: 720px) {
.auth-layout { display: block; }
.intro { min-height: 0; padding: 28px; }
.intro-copy { margin-top: 30px; }
.intro h1 { font-size: 42px; letter-spacing: -2px; line-height: 1.08; margin: 14px 0 0; }
.intro h1 br { display: none; }
.intro-copy .eyebrow { font-size: 9px; }
.intro-copy p, .conversation-art, .intro-footer { display: none; }
.auth-side { min-height: 0; padding: 30px 28px; align-items: center; border-left: 0; border-top: 1px solid var(--border); }
.auth-card { max-width: 440px; }
.auth-switch { margin-bottom: 28px; }
.auth-card h2 { font-size: 32px; }
.auth-card h2 br { display: none; }
.auth-card .muted { margin-bottom: 22px; }
.auth-card form { gap: 17px; }
.auth-bottom { margin-top: 20px; }
.app-shell { margin: 0; border: 0; border-radius: 0; height: 100svh; display: block; }
.sidebar { height: 100%; width: 100%; padding: 25px 18px 0; border: 0; }
.sidebar-heading { padding-top: 30px; }
.workspace { display: none; height: 100%; }
.app-shell.chat-open .sidebar { display: none; }
.app-shell.chat-open .workspace { display: block; }
.welcome { display: none; }
.mobile-only { display: flex; }
.chat-header { padding: 15px; gap: 7px; min-height: 75px; }
.chat-header .avatar { width: 35px; height: 35px; border-radius: 11px; }
.chat-heading h2 { font-size: 14px; }
.chat-header .icon-button { width: 31px; height: 31px; }
.chat-header .icon-button svg { width: 19px; height: 19px; }
.message-scroll { padding: 10px 16px 20px; }
.message { max-width: 88%; }
.composer { padding: 14px 16px max(13px, env(safe-area-inset-bottom)); }
.composer-note { font-size: 9px; }
.composer-note > span:first-child { max-width: 70%; }
.profile { padding-bottom: max(18px, env(safe-area-inset-bottom)); }
.toast { bottom: 20px; }
.defense-panel { top: 83px; right: 12px; width: calc(100% - 24px); max-height: 52svh; padding: 16px; }
.sidebar-defense { margin-top: 9px; }
}
@media (min-width: 721px) {
body:not(.has-session) .defense-panel { right: 24px; left: auto; }
}
@media (min-width: 1100px) {
.defense-open.has-session .app-shell { margin-left: 22px; margin-right: 380px; }
.defense-open.has-session .defense-panel { top: 22px; max-height: calc(100svh - 44px); }
}
@media (prefers-reduced-motion: reduce) {
* { transition: none !important; scroll-behavior: auto !important; }
}
/* Animated CSS silhouettes and faces, no image assets. */
.password-field { position: relative; display: block; }
.password-field input { padding-right: 47px; }
.password-toggle { position: absolute; right: 7px; top: 7px; width: 33px; height: 33px; border: 0; background: transparent; border-radius: 9px; color: var(--muted); display: flex; align-items: center; justify-content: center; }
.password-toggle:hover, .password-toggle[aria-pressed=true] { color: var(--accent); background: #ffe1350c; }
.password-toggle svg { width: 18px; height: 18px; }
/* Each character is one complete geometric silhouette. */
.mascot-stage { position: relative; width: 330px; height: 205px; margin: 32px 0 0 18px; z-index: 2; isolation: isolate; pointer-events: none; --scene-surface: #262626; --gaze-x: 0px; --gaze-y: 0px; }
.mascot-stage::before { content: ""; position: absolute; bottom: 20px; left: 0; right: 0; height: 1px; background: linear-gradient(90deg, transparent, #ffe13545, transparent); }
.mascot { position: absolute; bottom: 21px; z-index: 2; width: 64px; transform-origin: center bottom; will-change: transform; --mascot-color: var(--accent); }
.mascot-tall { left: 24px; }
.mascot-round { left: 82px; z-index: 3; width: 82px; --mascot-color: #e1e0d6; }
.mascot-triangle { left: 154px; width: 84px; --mascot-color: #f7b560; }
.mascot-conversation { position: absolute; inset: 0; z-index: 0; transition: opacity .65s ease; }
.mascot-stage:is([data-trip=forward], [data-trip=near], [data-trip=back]) .mascot-conversation { opacity: .25; }
.mascot-bubble { position: absolute; border-radius: 18px; animation: mascot-bubble-float 5.6s ease-in-out infinite; }
.mascot-bubble-filled { left: 146px; top: 0; width: 96px; height: 54px; background: var(--accent); display: flex; align-items: center; justify-content: center; gap: 7px; rotate: -6deg; }
.mascot-bubble-filled::after { content: ""; position: absolute; bottom: -7px; left: 18px; width: 17px; height: 17px; background: var(--accent); clip-path: polygon(0 0, 100% 0, 0 100%); }
.mascot-bubble-filled span { width: 6px; height: 6px; border-radius: 50%; background: #262626; animation: mascot-typing 1.8s ease-in-out infinite; }
.mascot-bubble-filled span:nth-child(2) { animation-delay: .16s; }
.mascot-bubble-filled span:nth-child(3) { animation-delay: .32s; }
.mascot-bubble-outline { left: 226px; top: 73px; width: 84px; height: 60px; border: 1.5px solid #ffe13555; background: var(--scene-surface); rotate: 7deg; animation-delay: -2.8s; padding: 20px 17px; }
.mascot-bubble-outline::after { content: ""; position: absolute; bottom: -6px; right: 16px; width: 11px; height: 11px; border-right: 1.5px solid #ffe13555; border-bottom: 1.5px solid #ffe13555; background: var(--scene-surface); rotate: 45deg; }
.mascot-bubble-outline i { display: block; height: 2px; width: 100%; margin-bottom: 8px; border-radius: 2px; background: #ffe13555; }
.mascot-bubble-outline i:last-child { width: 65%; }
@keyframes mascot-bubble-float { 0%, 100% { translate: 0 0; } 50% { translate: 0 -5px; } }
@keyframes mascot-typing { 0%, 55%, 100% { translate: 0 0; opacity: .4; } 28% { translate: 0 -3px; opacity: 1; } }
.mascot-body { position: relative; width: 64px; height: 150px; border-radius: 16px; background: var(--mascot-color); transform-origin: center bottom; }
.mascot-round .mascot-body { width: 82px; height: 102px; border-radius: 44px 44px 16px 16px; }
.mascot-triangle .mascot-body { width: 84px; height: 110px; border-radius: 8px; clip-path: polygon(50% 0, 100% 100%, 0 100%); }
.mascot-face { position: absolute; top: 44px; left: 50%; width: 38px; margin-left: -19px; display: flex; gap: 6px; justify-content: center; transition: opacity .45s, transform .5s cubic-bezier(.22, 1, .36, 1); }
.mascot-round .mascot-face { top: 34px; }
.mascot-triangle .mascot-face { top: 66px; width: 38px; margin-left: -19px; gap: 6px; }
.mascot-eye { position: relative; display: block; width: 14px; height: 18px; border-radius: 50%; background: #fffdf2; overflow: hidden; animation: mascot-blink 7s infinite; transition: scale .45s ease; }
.mascot-round .mascot-eye { animation-delay: 1.7s; }
.mascot-triangle .mascot-eye { width: 14px; height: 17px; animation-delay: 3.1s; }
.mascot-eye i { position: absolute; width: 6px; height: 8px; left: 4px; top: 5px; border-radius: 50%; background: #262626; transform: translate(var(--gaze-x), var(--gaze-y)); transition: transform .4s cubic-bezier(.22, 1, .36, 1); }
.mascot-triangle .mascot-eye i { left: 4px; top: 5px; }
.mascot-mouth { position: absolute; left: 50%; top: 28px; width: 11px; height: 5px; margin-left: -5px; border-bottom: 2px solid #262626; border-radius: 0 0 50% 50%; transition: width .4s, height .4s, border-radius .4s; }
.mascot-triangle .mascot-mouth { top: 21px; width: 9px; }
.mascot-arm { position: absolute; height: 23px; width: 54px; top: 32px; left: 14px; border-radius: 10px; background: #b7b6ab; opacity: 0; translate: 0 24px; rotate: -9deg; transition: translate .5s, opacity .45s; }
.mascot-stage[data-mood=looking] { --gaze-x: 4px !important; --gaze-y: 3px !important; }
.mascot-stage:is([data-mood=private],[data-mood=short],[data-mood=revealed]) .mascot-tall .mascot-face { opacity: 0; transform: translateX(-10px) scaleX(.75); }
.mascot-stage:is([data-mood=private],[data-mood=short],[data-mood=revealed]) .mascot-round .mascot-arm { opacity: 1; translate: 0 0; }
.mascot-stage:is([data-mood=private],[data-mood=short]) .mascot-triangle .mascot-eye:first-child { transform: scaleY(.12); animation: none; }
.mascot-stage:is([data-mood=private],[data-mood=short]) .mascot-triangle .mascot-eye:last-child { animation: mascot-peek-eye 6.4s ease-in-out infinite; }
.mascot-stage:is([data-mood=private],[data-mood=short]) .mascot-triangle .mascot-eye i { transform: translate(3px, 0); }
.mascot-stage[data-mood=revealed] .mascot-triangle .mascot-face { opacity: 0; transform: translateX(8px) scaleX(.75); }
.mascot-stage.is-scared { --gaze-x: 3px !important; --gaze-y: -3px !important; }
.mascot-stage.is-scared .mascot-eye { animation: none; scale: 1.12; }
.mascot-stage.is-scared .mascot-mouth { width: 6px; height: 9px; border: 2px solid #262626; border-radius: 50%; }
.mascot-stage.is-sleepy .mascot-eye { animation: none; scale: 1 .3; }
.mascot-stage[data-mood=revealed] .mascot-triangle { z-index: 1; }
@keyframes mascot-blink { 0%, 42%, 46%, 100% { transform: scaleY(1); } 44% { transform: scaleY(.08); } }
@keyframes mascot-peek-eye { 0%, 16%, 65%, 100% { transform: scaleY(.12); } 24%, 57% { transform: scaleY(1); } }
.scenario-section { padding: 17px 0 15px; border-bottom: 1px solid var(--border); }
.scenario-section h3 { font-size: 13px; margin: 0 0 9px; }
.scenario-description { font-size: 10px; line-height: 1.7; color: var(--muted); margin: 0 0 12px; }
.scenario-actions { display: grid; gap: 8px; }
.scenario-actions .button { padding: 11px 10px; font-size: 11px; }
.scenario-status { font-size: 11px; line-height: 1.6; margin: 12px 0 0; color: var(--ink); }
.scenario-status.failed { color: var(--danger); }
.scenario-scope { margin: 12px 0 0; }
.scenario-steps { list-style: none; padding: 0; margin: 12px 0 0; display: grid; gap: 8px; max-height: 245px; overflow: auto; scrollbar-width: thin; scrollbar-color: #646451 transparent; }
.scenario-step { border: 1px solid var(--border); border-radius: 10px; background: #262626; padding: 10px; }
.scenario-step[data-state=failed] { border-color: #9a5b51; }
.scenario-step summary { display: flex; align-items: flex-start; gap: 8px; cursor: pointer; font-size: 11px; line-height: 1.5; list-style: none; }
.scenario-step summary::before { content: "▸"; color: var(--muted); }
.scenario-step[open] summary::before { content: "▾"; }
.scenario-step summary::-webkit-details-marker { display: none; }
.scenario-step-badge { flex-shrink: 0; color: var(--accent); font: 650 10px/1.65 ui-monospace, monospace; }
.scenario-step[data-state=failed] .scenario-step-badge { color: var(--danger); }
.scenario-step[data-state=pending] .scenario-step-badge { color: var(--muted); }
.scenario-step p { color: var(--muted); font-size: 10px; line-height: 1.7; margin: 9px 0 0; }
.scenario-step code { display: block; color: var(--muted); font: 10px/1.7 ui-monospace, monospace; overflow-wrap: anywhere; margin-top: 7px; }
@media (max-width: 1100px) and (min-width: 721px) {
.mascot-stage { margin-left: 0; width: 315px; }
}
@media (max-width: 720px) {
.mascot-stage { width: 300px; height: 150px; margin: 18px auto 0; }
.mascot-stage::before { bottom: 10px; }
.mascot { bottom: 11px; }
.mascot-tall { left: calc(50% - 84px); }
.mascot-round { left: calc(50% - 44px); }
.mascot-triangle { left: calc(50% + 2px); width: 84px; }
.mascot-body { scale: .62; transform-origin: center bottom; }
.mascot-bubble { border-radius: 13px; }
.mascot-bubble-filled { left: calc(50% - 14px); top: 12px; width: 64px; height: 35px; gap: 5px; }
.mascot-bubble-filled span { width: 4px; height: 4px; }
.mascot-bubble-filled::after { width: 12px; height: 12px; bottom: -5px; left: 13px; }
.mascot-bubble-outline { left: calc(50% + 68px); top: 59px; width: 56px; height: 42px; padding: 13px 11px; }
.mascot-bubble-outline i { margin-bottom: 6px; }
.mascot-bubble-outline::after { width: 8px; height: 8px; bottom: -5px; right: 12px; }
.intro h1 { font-size: 36px; }
.intro { padding-bottom: 18px; }
.scenario-steps { max-height: 175px; }
}
@media (max-width: 370px) {
.mascot-stage { width: 264px; }
}
@media (prefers-reduced-motion: reduce) {
.mascot-stage *, .mascot-stage *::before { animation: none !important; transition: none !important; }
}
.defense-origin { margin-top: 10px; }
@media (max-width: 720px) {
.auth-card .mascot-stage { position: sticky; top: 0; z-index: 3; width: 100%; margin-top: -9px; margin-bottom: 22px; background: #2c2c2a; --scene-surface: #2c2c2a; border-bottom: 1px solid var(--border); box-shadow: 0 6px 0 #2c2c2a; }
}
.auth-card form { margin-top: 24px; }
.auth-card .muted + form { margin-top: 0; }
.defense-help { border-top: 1px solid var(--border); margin-top: 14px; padding-top: 12px; }
.defense-help summary { color: var(--muted); font-size: 10px; cursor: pointer; }
.defense-help .defense-note { margin-top: 10px; font-size: 10px; }
@media (prefers-reduced-motion: reduce) {
.mascot-stage *, .mascot-stage *::before { animation: none !important; transition: none !important; }
}
+453
View File
@@ -0,0 +1,453 @@
import { recordDefenseRequest, updateDefenseSession, updateDefenseHistory } from "/defense.js";
import { setMascotMood, celebrateMascots } from "/mascots.js";
import { configureScenarios, updateScenarioAccess } from "/scenarios.js";
const $ = id => document.getElementById(id);
const storageKey = "linia.session";
const state = { session: null, chats: [], chatsCursor: null, current: null, messages: new Map(),
serverIds: new Set(), members: new Map(), olderCursor: null, historyReady: false, epoch: 0, syncing: false, sending: false, drafts: new Map() };
let toastTimer;
class ApiError extends Error {
constructor(message, status = 0) { super(message); this.status = status; }
}
function notice(id, message, success = false) {
const element = $(id);
element.textContent = message;
element.hidden = !message;
element.classList.toggle("success", success);
}
function toast(message, error = false) {
clearTimeout(toastTimer);
$("toast").textContent = message;
$("toast").classList.toggle("error", error);
$("toast").hidden = false;
toastTimer = setTimeout(() => { $("toast").hidden = true; }, error ? 6500 : 3000);
}
async function request(path, { method = "GET", body, headers = {}, auth = true, background = false } = {}) {
const started = performance.now();
let httpStatus = null, requestId = null, outcome = "network";
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 12000);
// Authorization is explicit; disable the browser's implicit Basic-auth handling.
const options = { method, headers: { Accept: "application/json", ...headers }, signal: controller.signal, cache: "no-store", credentials: "omit" };
if (auth && state.session) options.headers.Authorization = "Bearer " + state.session.token;
if (body !== undefined) {
options.body = JSON.stringify(body);
options.headers["Content-Type"] = "application/json";
}
try {
const response = await fetch(path, options);
httpStatus = response.status;
requestId = response.headers.get("X-Request-Id");
outcome = "unreadable";
const data = response.status === 204 ? null : await response.json();
outcome = response.ok ? "success" : "http_error";
if (!response.ok) {
if (response.status === 401 && auth) endSession("Сессия закончилась. Войдите снова.");
throw new ApiError(data?.error?.message || "Не удалось выполнить запрос.", response.status);
}
return data;
} catch (error) {
if (error instanceof ApiError) throw error;
throw new ApiError("Нет ответа от сервера. Проверьте соединение и попробуйте позже.");
} finally {
clearTimeout(timer);
recordDefenseRequest({ method, path, status: httpStatus, requestId, outcome, background,
durationMs: Math.round(performance.now() - started),
authorization: options.headers.Authorization?.split(" ")[0] || "Без авторизации" });
}
}
function basic(username, password) {
const bytes = new TextEncoder().encode(username + ":" + password);
return "Basic " + btoa(Array.from(bytes, byte => String.fromCharCode(byte)).join(""));
}
function selectAuthTab(register) {
$("register-panel").hidden = !register;
$("login-panel").hidden = register;
$("tab-register").classList.toggle("active", register);
$("tab-login").classList.toggle("active", !register);
$("tab-register").setAttribute("aria-pressed", String(register));
$("tab-login").setAttribute("aria-pressed", String(!register));
notice("auth-notice", "");
}
function setFormBusy(form, busy) {
form.querySelectorAll("input, textarea, button").forEach(element => { element.disabled = busy; });
}
function persistSession(session) {
try { sessionStorage.setItem(storageKey, JSON.stringify(session)); } catch { /* session still works in memory */ }
}
async function enterSession(session) {
state.epoch++;
state.session = session;
updateScenarioAccess();
updateDefenseSession({ name: session.user.display_name, expiresAt: session.expires_at });
updateDefenseHistory(null);
state.current = null;
state.messages.clear();
state.serverIds.clear();
state.chats = [];
state.chatsCursor = null;
state.drafts.clear();
state.syncing = false;
state.sending = false;
persistSession(session);
$("auth-screen").hidden = true;
$("app-screen").hidden = false;
$("app-screen").classList.remove("chat-open");
$("welcome").hidden = false;
$("conversation").hidden = true;
$("profile-name").textContent = session.user.display_name;
$("profile-username").textContent = "@" + session.user.username;
$("profile-avatar").textContent = initials(session.user.display_name);
$("chat-search").value = "";
renderChats();
try { await loadChats(false, true); } catch (error) { toast(error.message, true); }
}
function endSession(message = "") {
state.epoch++;
state.session = null;
updateScenarioAccess();
updateDefenseSession(null);
updateDefenseHistory(null);
state.current = null;
state.chats = [];
state.messages.clear();
state.serverIds.clear();
state.drafts.clear();
try { sessionStorage.removeItem(storageKey); } catch { /* storage unavailable */ }
document.querySelectorAll("dialog[open]").forEach(dialog => dialog.close());
$("message-list").replaceChildren();
$("chat-list").replaceChildren();
$("message-input").value = "";
$("app-screen").hidden = true;
$("auth-screen").hidden = false;
$("login-password").value = "";
selectAuthTab(false);
notice("auth-notice", message);
}
$("tab-login").addEventListener("click", () => selectAuthTab(false));
$("tab-register").addEventListener("click", () => selectAuthTab(true));
$("login-form").addEventListener("submit", async event => {
event.preventDefault();
const form = event.currentTarget;
const username = $("login-username").value.trim();
const password = $("login-password").value;
setFormBusy(form, true);
setMascotMood("pending");
notice("auth-notice", "");
try {
const session = await request("/api/v1/auth/sessions", { method: "POST", auth: false, headers: { Authorization: basic(username, password) } });
form.reset();
await celebrateMascots();
await enterSession(session);
} catch (error) { setMascotMood("error"); notice("auth-notice", error.status === 401 ? "Неверный логин или пароль." : error.message); }
finally { setFormBusy(form, false); }
});
$("register-form").addEventListener("submit", async event => {
event.preventDefault();
const form = event.currentTarget;
const username = $("register-username").value.trim();
const displayName = $("register-name").value.trim();
const password = $("register-password").value;
if (Array.from(displayName).length > 100) return notice("auth-notice", "Имя должно содержать от 1 до 100 символов.");
if (Array.from(password).length < 12 || Array.from(password).length > 128 || !password.trim()) {
setMascotMood("short");
return notice("auth-notice", "Пароль должен содержать от 12 до 128 символов.");
}
setFormBusy(form, true);
setMascotMood("pending");
notice("auth-notice", "");
let registered = false;
try {
await request("/api/v1/users", { method: "POST", auth: false, body: { username, display_name: displayName, password } });
registered = true;
const session = await request("/api/v1/auth/sessions", { method: "POST", auth: false, headers: { Authorization: basic(username, password) } });
form.reset();
await celebrateMascots();
await enterSession(session);
toast("Добро пожаловать, " + session.user.display_name + "!");
} catch (error) {
setMascotMood("error");
if (registered) {
form.reset();
selectAuthTab(false);
$("login-username").value = username;
notice("auth-notice", "Аккаунт создан. Войдите, когда сервер будет доступен.");
} else notice("auth-notice", error.status === 409 ? "Это имя пользователя уже занято. Выберите другое." : error.message);
} finally { setFormBusy(form, false); }
});
function initials(value) { return (value.match(/[\p{L}\p{N}]+/gu) || []).slice(0, 2).map(part => Array.from(part)[0]).join("").toUpperCase(); }
function memberCount(count) { const n = count % 100, d = count % 10; return count + " " + (n >= 11 && n <= 14 ? "участников" : d === 1 ? "участник" : d >= 2 && d <= 4 ? "участника" : "участников"); }
function avatarTone(id) { return "tone-" + (parseInt(id.slice(0, 4), 16) % 4); }
async function loadChats(more = false, background = false) {
const token = state.session?.token;
const cursor = more ? state.chatsCursor : null;
const data = await request("/api/v1/chats?limit=100" + (cursor ? "&cursor=" + encodeURIComponent(cursor) : ""), { background });
if (token !== state.session?.token) return;
state.chats = more ? [...state.chats, ...data.items.filter(chat => !state.chats.some(existing => existing.id === chat.id))] : data.items;
state.chatsCursor = data.next_cursor;
renderChats();
}
function renderChats() {
const query = $("chat-search").value.trim().toLocaleLowerCase("ru-RU");
const chats = [...state.chats].sort((a, b) => b.created_at.localeCompare(a.created_at) || b.id.localeCompare(a.id))
.filter(chat => chat.title.toLocaleLowerCase("ru-RU").includes(query));
$("chat-count").textContent = state.chats.length || "";
$("more-chats").hidden = !state.chatsCursor;
const nodes = chats.map(chat => {
const button = document.createElement("button");
button.className = "chat-row" + (chat.id === state.current?.id ? " active" : "");
button.setAttribute("aria-pressed", String(chat.id === state.current?.id));
const avatar = document.createElement("span"); avatar.className = "avatar " + avatarTone(chat.id); avatar.textContent = initials(chat.title);
const description = document.createElement("span"); description.className = "chat-row-text";
const title = document.createElement("strong"); title.textContent = chat.title;
const members = document.createElement("small"); members.textContent = memberCount(chat.member_ids.length);
description.append(title, members); button.append(avatar, description);
button.addEventListener("click", () => selectChat(chat));
return button;
});
if (!nodes.length) {
const empty = document.createElement("p"); empty.className = "list-empty";
empty.textContent = query ? "Чаты не найдены." : "Пока нет чатов.";
nodes.push(empty);
}
$("chat-list").replaceChildren(...nodes);
}
$("chat-search").addEventListener("input", renderChats);
$("refresh-chats").addEventListener("click", async () => { try { await loadChats(); } catch (error) { toast(error.message, true); } });
$("more-chats").addEventListener("click", async () => { try { await loadChats(true); } catch (error) { toast(error.message, true); } });
async function selectChat(chat) {
if (state.current?.id === chat.id) { $("app-screen").classList.add("chat-open"); return; }
if (state.current) state.drafts.set(state.current.id, $("message-input").value);
state.epoch++;
state.current = chat;
state.members = new Map([[state.session.user.id, state.session.user]]);
renderChats();
state.messages = new Map();
state.serverIds = new Set();
state.olderCursor = null;
state.historyReady = false;
updateDefenseHistory({ title: chat.title, loaded: 0, hasOlder: false, ready: false });
state.syncing = false;
$("current-title").textContent = chat.title;
$("current-members").textContent = memberCount(chat.member_ids.length);
$("current-avatar").textContent = initials(chat.title);
$("current-avatar").className = "avatar chat-avatar " + avatarTone(chat.id);
$("welcome").hidden = true;
$("conversation").hidden = false;
$("app-screen").classList.add("chat-open");
$("message-input").value = state.drafts.get(chat.id) || "";
updateComposer();
$("message-list").replaceChildren();
$("empty-conversation").hidden = true;
$("older-messages").hidden = true;
try { await Promise.all([syncRecent(true), loadMembers(state.epoch, chat.id)]); }
catch (error) { toast(error.message, true); }
}
async function loadMembers(epoch, chatId) {
const data = await request(`/api/ui/chats/${chatId}/members`, { background: true });
if (epoch !== state.epoch) return;
state.members = new Map(data.items.map(user => [user.id, user]));
renderMessages();
}
async function syncRecent(initial = false, background = false) {
if (!state.current || !state.session || state.syncing) return;
const epoch = state.epoch, chatId = state.current.id;
state.syncing = true;
try {
const page = await request(`/api/ui/chats/${chatId}/messages?limit=50`, { background });
if (epoch !== state.epoch) return;
state.historyReady = true;
const overlap = page.items.some(item => state.serverIds.has(item.id));
// On a large burst, the older button pages through the newly discovered gap.
if (initial || (!overlap && page.items.length === 50)) state.olderCursor = page.next_cursor;
page.items.forEach(item => { state.messages.set(item.id, item); state.serverIds.add(item.id); });
renderMessages(initial ? "bottom" : "preserve");
} finally { if (epoch === state.epoch) state.syncing = false; }
}
$("older-messages").addEventListener("click", async () => {
if (!state.olderCursor || !state.current) return;
const epoch = state.epoch;
$("older-messages").disabled = true;
try {
const page = await request(`/api/ui/chats/${state.current.id}/messages?limit=50&cursor=${encodeURIComponent(state.olderCursor)}`);
if (epoch !== state.epoch) return;
page.items.forEach(item => { state.messages.set(item.id, item); state.serverIds.add(item.id); });
state.olderCursor = page.next_cursor;
renderMessages("prepend");
} catch (error) { toast(error.message, true); }
finally { $("older-messages").disabled = false; }
});
function renderMessages(mode = "preserve") {
const scroll = $("message-scroll"), oldHeight = scroll.scrollHeight, oldTop = scroll.scrollTop;
const atBottom = oldHeight - oldTop - scroll.clientHeight < 85;
const messages = [...state.messages.values()].sort((a, b) => a.created_at.localeCompare(b.created_at) || a.id.localeCompare(b.id));
const nodes = []; let previousDay = "";
for (const message of messages) {
const date = new Date(message.created_at);
const day = date.toLocaleDateString("ru-RU", { day: "numeric", month: "long", year: "numeric" });
if (day !== previousDay) {
const divider = document.createElement("div"); divider.className = "date-separator"; divider.textContent = day; nodes.push(divider); previousDay = day;
}
const mine = message.sender_id === state.session?.user.id;
const article = document.createElement("article"); article.className = "message" + (mine ? " mine" : "");
if (!mine) {
const author = document.createElement("span"); author.className = "message-author"; author.textContent = state.members.get(message.sender_id)?.display_name || "Участник " + message.sender_id.slice(0, 8); author.title = message.sender_id; article.append(author);
}
const bubble = document.createElement("div"); bubble.className = "message-bubble";
const text = document.createElement("p"); text.className = "message-text"; text.textContent = message.text;
const stamp = document.createElement("time"); stamp.className = "message-time"; stamp.dateTime = message.created_at;
stamp.textContent = date.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" });
bubble.append(text, stamp); article.append(bubble); nodes.push(article);
}
$("message-list").replaceChildren(...nodes);
$("empty-conversation").hidden = messages.length !== 0;
$("older-messages").hidden = !state.olderCursor;
updateDefenseHistory({ title: state.current?.title, loaded: messages.length, hasOlder: Boolean(state.olderCursor), ready: state.historyReady });
if (mode === "bottom" || (mode === "preserve" && atBottom)) scroll.scrollTop = scroll.scrollHeight;
else if (mode === "prepend") scroll.scrollTop = oldTop + scroll.scrollHeight - oldHeight;
else scroll.scrollTop = oldTop;
}
function updateComposer() {
const text = $("message-input").value, count = Array.from(text).length;
$("message-count").textContent = `${count} / 4000`;
$("message-count").classList.toggle("over-limit", count > 4000);
$("send-message").disabled = state.sending || !text.trim() || count > 4000;
$("message-input").style.height = "auto";
const height = $("message-input").scrollHeight + 2;
$("message-input").style.height = Math.min(140, height) + "px";
$("message-input").style.overflowY = height > 140 ? "auto" : "hidden";
if (state.current) state.drafts.set(state.current.id, text);
}
$("message-input").addEventListener("input", updateComposer);
$("message-input").addEventListener("keydown", event => {
if (event.key === "Enter" && !event.shiftKey && !event.isComposing) {
event.preventDefault();
if (!$("send-message").disabled) $("message-form").requestSubmit();
}
});
$("message-form").addEventListener("submit", async event => {
event.preventDefault();
if (state.sending || !state.current || $("send-message").disabled) return;
const epoch = state.epoch, chatId = state.current.id, text = $("message-input").value;
state.sending = true; updateComposer();
try {
const message = await request(`/api/v1/chats/${chatId}/messages`, { method: "POST", body: { text } });
if (epoch !== state.epoch) return;
state.messages.set(message.id, message);
if ($("message-input").value === text) $("message-input").value = "";
renderMessages("bottom");
await syncRecent(false, true);
} catch (error) { toast(error.status === 0 ? "Отправка не подтверждена. Обновите чат перед повторной отправкой." : error.message, true); }
finally { state.sending = false; updateComposer(); }
});
function openNewChat() {
$("new-chat-form").reset(); notice("chat-dialog-notice", "");
$("new-chat-dialog").showModal(); $("new-chat-title").focus();
}
$("new-chat").addEventListener("click", openNewChat);
$("welcome-new-chat").addEventListener("click", openNewChat);
document.querySelectorAll("[data-close-dialog]").forEach(button => button.addEventListener("click", () => button.closest("dialog").close()));
$("new-chat-form").addEventListener("submit", async event => {
event.preventDefault();
const form = event.currentTarget, token = state.session?.token;
const title = $("new-chat-title").value.trim();
if (!title || Array.from(title).length > 100) return notice("chat-dialog-notice", "Название должно содержать от 1 до 100 символов.");
const ids = $("new-chat-members").value.split(/[\s,;]+/u).filter(Boolean);
if (ids.some(id => !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(id)))
return notice("chat-dialog-notice", "Проверьте ID участников: нужен полный ID из профиля.");
const members = [...new Set([state.session.user.id, ...ids.map(id => id.toLowerCase())])];
if (members.length > 100) return notice("chat-dialog-notice", "В чате может быть не более 100 участников.");
setFormBusy(form, true); notice("chat-dialog-notice", "");
try {
const chat = await request("/api/v1/chats", { method: "POST", body: { title, member_ids: members } });
if (token !== state.session?.token) return;
$("new-chat-dialog").close(); state.chats.push(chat); renderChats();
await selectChat(chat); toast("Чат создан.");
} catch (error) { notice("chat-dialog-notice", error.message); }
finally { setFormBusy(form, false); }
});
$("open-profile").addEventListener("click", () => {
$("profile-details").textContent = state.session.user.display_name + " · @" + state.session.user.username;
$("my-id").value = state.session.user.id; $("profile-dialog").showModal();
});
$("copy-id").addEventListener("click", async () => {
try { await navigator.clipboard.writeText(state.session.user.id); toast("ID скопирован."); }
catch { $("my-id").select(); toast("Выделили ID. Скопируйте его сочетанием ⌘C или Ctrl+C."); }
});
$("show-members").addEventListener("click", () => {
$("members-list").replaceChildren(...state.current.member_ids.map(id => {
const item = document.createElement("div"); item.className = "member-item";
const label = document.createElement("strong"); label.textContent = (state.members.get(id)?.display_name || "Участник") + (id === state.session.user.id ? " (вы)" : "");
const code = document.createElement("code"); code.textContent = id; item.append(label, code); return item;
}));
$("members-dialog").showModal();
});
$("logout").addEventListener("click", async () => {
$("logout").disabled = true;
try { await request("/api/v1/auth/sessions/current", { method: "DELETE" }); endSession(); }
catch (error) { if (error.status !== 401) toast(error.message, true); }
finally { $("logout").disabled = false; }
});
$("back-to-chats").addEventListener("click", () => $("app-screen").classList.remove("chat-open"));
$("refresh-messages").addEventListener("click", async () => {
try { await syncRecent(); } catch (error) { toast(error.message, true); }
});
setInterval(async () => {
if (!state.session || document.hidden) return;
if (new Date(state.session.expires_at).getTime() <= Date.now()) return endSession("Сессия закончилась. Войдите снова.");
if (state.current) { try { await syncRecent(false, true); } catch { /* manual actions still show errors */ } }
}, 4000);
async function resume() {
try {
const stored = sessionStorage.getItem(storageKey);
if (!stored) return;
const session = JSON.parse(stored);
if (!session?.token || !session.user || !(new Date(session.expires_at).getTime() > Date.now())) return endSession();
state.session = session;
const user = await request("/api/v1/users/me");
await enterSession({ ...session, user });
} catch (error) {
state.session = null;
if (error instanceof ApiError) notice("auth-notice", error.message);
else { try { sessionStorage.removeItem(storageKey); } catch { /* storage unavailable */ } }
}
}
configureScenarios({
getActor: () => state.session ? { id: state.session.user.id, token: state.session.token } : null,
openChat: async (chat, owner) => {
await loadChats(false, true);
if (state.session?.token !== owner.token) throw new Error("Основной вход изменился. Откройте демочат из списка после входа.");
await selectChat(chat);
}
});
void resume();
+109
View File
@@ -0,0 +1,109 @@
// Only explicitly selected HTTP metadata reaches this view. Never pass request
// headers, bodies, session objects or raw response JSON into the panel.
const $ = id => document.getElementById(id);
const preferenceKey = "linia.defense";
const requests = [];
let session = null, history = null, backgroundRequest = null, returnFocus = null;
function setOpen(open) {
$("defense-panel").hidden = !open;
document.body.classList.toggle("defense-open", open);
document.querySelectorAll("[data-defense-toggle]").forEach(button => button.setAttribute("aria-expanded", String(open)));
try { sessionStorage.setItem(preferenceKey, open ? "on" : "off"); } catch { /* optional preference */ }
if (open) { render(); $("defense-close").focus(); }
else if (returnFocus?.isConnected) returnFocus.focus();
}
document.querySelectorAll("[data-defense-toggle]").forEach(button => button.addEventListener("click", () => {
returnFocus = button;
setOpen($("defense-panel").hidden);
}));
$("defense-close").addEventListener("click", () => setOpen(false));
document.addEventListener("keydown", event => {
if (event.key === "Escape" && !$("defense-panel").hidden && !document.querySelector("dialog[open]")) {
event.preventDefault(); setOpen(false);
}
});
export function updateDefenseSession(value) {
session = value ? { name: value.name, expiresAt: value.expiresAt } : null;
document.body.classList.toggle("has-session", Boolean(session));
if (!$("defense-panel").hidden) renderSession();
}
export function updateDefenseHistory(value) {
history = value ? { title: value.title, loaded: value.loaded, hasOlder: value.hasOlder, ready: value.ready } : null;
if (!$("defense-panel").hidden) renderHistory();
}
export function recordDefenseRequest(value) {
const entry = {
method: value.method, path: value.path.split("?")[0], status: value.status,
authorization: value.authorization, durationMs: value.durationMs,
requestId: value.requestId, outcome: value.outcome, source: value.source, at: new Date()
};
if (value.background) backgroundRequest = entry;
else { requests.unshift(entry); requests.length = Math.min(requests.length, 4); }
if (!$("defense-panel").hidden) renderRequests();
}
function renderSession() {
$("defense-user").textContent = session?.name || "Вход не выполнен";
const seconds = session ? Math.max(0, Math.ceil((new Date(session.expiresAt).getTime() - Date.now()) / 1000)) : null;
$("defense-session").textContent = seconds === null ? "-" : seconds === 0 ? "Срок истёк" : `${Math.floor(seconds / 60)} мин ${String(seconds % 60).padStart(2, "0")} с`;
}
function renderHistory() {
$("defense-chat").textContent = history?.title || "Выберите чат";
$("defense-messages").textContent = history
? `Загружено: ${history.loaded} · ${!history.ready ? "страница ещё не получена" : history.hasOlder ? "есть старые сообщения ↑" : "старых страниц нет"}`
: "Сообщения ещё не загружены";
}
function result(entry) {
if (entry.status === null) return "Ответ не получен: соединение или таймаут. Результат записи может быть неизвестен.";
if (entry.outcome === "unreadable") return "HTTP-ответ получен, но его данные не удалось прочитать.";
if (entry.status === 204 && entry.method === "DELETE" && entry.path === "/api/v1/auth/sessions/current") return "Сессия отозвана. Ответ без тела.";
return ({200: "Запрос выполнен", 201: "Объект создан", 204: "Выполнено без тела ответа",
400: "Некорректные данные", 401: "Нужен действующий вход", 404: "Ресурс отсутствует или недоступен",
409: "Конфликт данных", 415: "Неподдерживаемый формат", 503: "Сервис временно недоступен",
500: "Внутренняя ошибка сервера"})[entry.status] || `HTTP ${entry.status}`;
}
function shortPath(path) { return path.replace(/\/[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}(?=\/|$)/gi, "/…"); }
function renderRequests() {
const current = requests[0];
$("defense-empty").hidden = Boolean(current);
$("defense-request-details").hidden = !current;
$("defense-request-time").textContent = current ? current.at.toLocaleTimeString("ru-RU") : "";
if (current) {
const failed = current.status === null || current.status >= 400 || current.outcome === "unreadable";
$("defense-method").textContent = current.method;
$("defense-status").textContent = current.status ?? "Нет ответа";
$("defense-status").classList.toggle("failed", failed);
$("defense-origin").textContent = current.source || "Основной интерфейс";
$("defense-path").textContent = shortPath(current.path);
$("defense-path").title = current.path;
$("defense-result").textContent = result(current);
$("defense-result").classList.toggle("failed", failed);
$("defense-auth").textContent = current.authorization;
$("defense-duration").textContent = `${current.durationMs} мс`;
$("defense-request-id").textContent = current.requestId || "Не получен";
}
const previous = requests.slice(1).map(entry => {
const item = document.createElement("li");
const status = document.createElement("span"); status.textContent = entry.status ?? "-";
status.className = "defense-mini-status" + (entry.status === null || entry.status >= 400 ? " failed" : "");
const route = document.createElement("code"); route.textContent = `${entry.method} ${shortPath(entry.path)}`;
route.title = entry.path; item.append(status, route); return item;
});
$("defense-previous").replaceChildren(...previous);
$("defense-previous").hidden = previous.length === 0;
$("defense-background").hidden = !backgroundRequest;
if (backgroundRequest) $("defense-background").textContent = `Фоновый запрос: ${backgroundRequest.status ?? "нет ответа"} · ${backgroundRequest.durationMs} мс · ${backgroundRequest.at.toLocaleTimeString("ru-RU")}`;
}
function render() { renderSession(); renderHistory(); renderRequests(); }
setInterval(() => { if (!$("defense-panel").hidden) renderSession(); }, 1000);
try { if (sessionStorage.getItem(preferenceKey) === "on") setOpen(true); } catch { /* optional preference */ }
+97
View File
@@ -0,0 +1,97 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#262626">
<meta name="description" content="n1k0der - место для ваших разговоров.">
<title>n1k0der · Мессенджер</title>
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 40 40'%3E%3Crect width='40' height='40' rx='12' fill='%23262626'/%3E%3Cpath d='M11 14h18M11 20h13M11 26h8' stroke='%23FFE135' stroke-width='3' stroke-linecap='round'/%3E%3C/svg%3E">
<link rel="stylesheet" href="/app.css">
<script type="module" src="/app.js"></script>
</head>
<body>
<svg class="svg-sprite" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
<symbol id="i-plus" viewBox="0 0 24 24"><path d="M12 5v14M5 12h14"/></symbol>
<symbol id="i-send" viewBox="0 0 24 24"><path d="m4 4 17 8-17 8 3-8-3-8ZM7 12h14"/></symbol>
<symbol id="i-chat" viewBox="0 0 24 24"><path d="M5 4h14a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H9l-6 4V6a2 2 0 0 1 2-2Z"/><path d="M7 9h10M7 13h6"/></symbol>
<symbol id="i-arrow" viewBox="0 0 24 24"><path d="m14 6-6 6 6 6M8 12h13"/></symbol>
<symbol id="i-refresh" viewBox="0 0 24 24"><path d="M20 7v5h-5M4 17v-5h5M6 7a7 7 0 0 1 12-1l2 3M4 15l2 3a7 7 0 0 0 12-1"/></symbol>
<symbol id="i-exit" viewBox="0 0 24 24"><path d="M9 4H4v16h5M10 12h11m-4-4 4 4-4 4"/></symbol>
<symbol id="i-copy" viewBox="0 0 24 24"><rect x="8" y="8" width="12" height="12" rx="2"/><path d="M16 8V4H4v12h4"/></symbol>
<symbol id="i-close" viewBox="0 0 24 24"><path d="m6 6 12 12M18 6 6 18"/></symbol>
<symbol id="i-users" viewBox="0 0 24 24"><circle cx="9" cy="8" r="3"/><path d="M3 20v-2a6 6 0 0 1 12 0v2M16 5a3 3 0 0 1 0 6M18 15a5 5 0 0 1 3 5"/></symbol>
<symbol id="i-eye" viewBox="0 0 24 24"><path d="M2 12s4-7 10-7 10 7 10 7-4 7-10 7-10-7-10-7Z"/><circle cx="12" cy="12" r="3"/></symbol>
<symbol id="i-code" viewBox="0 0 24 24"><path d="m7 7-5 5 5 5m10-10 5 5-5 5M14 4l-4 16"/></symbol>
</svg>
<section id="auth-screen" class="auth-layout">
<div class="intro">
<a class="brand" href="/" aria-label="n1k0der, главная"><span class="brand-mark"><i></i><i></i><i></i></span>n1k0der<span class="brand-dot">.</span></a>
<div class="intro-copy"><h1>Место для<br> ваших<br> <em>разговоров.</em></h1></div>
<div id="mascot-stage" class="mascot-stage" aria-hidden="true" data-mood="idle">
<div class="mascot-conversation">
<div class="mascot-bubble mascot-bubble-filled"><span></span><span></span><span></span></div>
<div class="mascot-bubble mascot-bubble-outline"><i></i><i></i></div>
</div>
<div class="mascot mascot-tall"><div class="mascot-body"><div class="mascot-face"><span class="mascot-eye"><i></i></span><span class="mascot-eye"><i></i></span><span class="mascot-mouth"></span></div><span class="mascot-arm"></span></div></div>
<div class="mascot mascot-round"><div class="mascot-body"><div class="mascot-face"><span class="mascot-eye"><i></i></span><span class="mascot-eye"><i></i></span><span class="mascot-mouth"></span></div><span class="mascot-arm"></span></div></div>
<div class="mascot mascot-triangle"><div class="mascot-body"><div class="mascot-face"><span class="mascot-eye"><i></i></span><span class="mascot-eye"><i></i></span><span class="mascot-mouth"></span></div><span class="mascot-arm"></span></div></div>
</div>
</div>
<div class="auth-side">
<div class="auth-card">
<div class="auth-switch" aria-label="Выберите действие"><button id="tab-login" class="active" type="button" aria-pressed="true">Вход</button><button id="tab-register" type="button" aria-pressed="false">Регистрация</button></div>
<div id="login-panel"><h2>С возвращением.</h2>
<form id="login-form"><label>Имя пользователя<input id="login-username" name="username" autocomplete="username" placeholder="например, n1k0der" pattern="[a-z0-9_]{3,32}" required autocapitalize="none" spellcheck="false"></label><label>Пароль<span class="password-field"><input id="login-password" aria-label="Пароль" name="password" type="password" autocomplete="current-password" placeholder="Пароль" required><button class="password-toggle" type="button" data-password-toggle="login-password" aria-label="Показать пароль" aria-pressed="false"><svg><use href="#i-eye"/></svg></button></span></label><button class="button primary wide" type="submit">Войти <span aria-hidden="true">↗</span></button></form>
</div>
<div id="register-panel" hidden><h2>А зачем этот<br> мессенджер?</h2><p class="muted">Чтобы сдать лабу.</p>
<form id="register-form"><label>Имя<input id="register-name" name="display_name" autocomplete="nickname" placeholder="Никита" required></label><label>Имя пользователя<input id="register-username" name="username" autocomplete="username" placeholder="n1k0der" pattern="[a-z0-9_]{3,32}" required autocapitalize="none" spellcheck="false"><span class="field-note">3-32 символа: a-z, цифры и _</span></label><label>Пароль<span class="password-field"><input id="register-password" aria-label="Пароль" name="password" type="password" autocomplete="new-password" placeholder="Придумайте пароль" required><button class="password-toggle" type="button" data-password-toggle="register-password" aria-label="Показать пароль" aria-pressed="false"><svg><use href="#i-eye"/></svg></button></span><span class="field-note">12-128 символов</span></label><button class="button primary wide" type="submit">Создать аккаунт <span aria-hidden="true">↗</span></button></form>
</div>
<p id="auth-notice" class="form-notice" role="status" aria-live="polite" hidden></p>
</div>
<div class="auth-bottom">n1k0der<button class="defense-toggle" type="button" data-defense-toggle aria-controls="defense-panel" aria-expanded="false"><svg><use href="#i-code"/></svg>Режим защиты</button></div>
</div>
</section>
<section id="app-screen" class="app-shell" hidden>
<aside class="sidebar">
<div class="sidebar-top"><a class="brand" href="/" aria-label="n1k0der"><span class="brand-mark"><i></i><i></i><i></i></span>n1k0der<span class="brand-dot">.</span></a><button class="icon-button" id="refresh-chats" title="Обновить чаты" aria-label="Обновить чаты"><svg><use href="#i-refresh"/></svg></button></div>
<div class="sidebar-heading"><div><span class="eyebrow">На связи</span><h2>Ваши чаты<span id="chat-count" class="count"></span></h2></div><button id="new-chat" class="icon-button filled" aria-label="Создать чат" title="Создать чат"><svg><use href="#i-plus"/></svg></button></div>
<label class="search-field"><span class="visually-hidden">Поиск среди загруженных чатов</span><span aria-hidden="true">⌕</span><input id="chat-search" placeholder="Найти разговор" type="search" autocomplete="off"></label>
<div id="chat-list" class="chat-list" aria-label="Список чатов"></div><button id="more-chats" class="text-button" hidden>Ещё чаты</button>
<button class="defense-toggle sidebar-defense" type="button" data-defense-toggle aria-controls="defense-panel" aria-expanded="false"><svg><use href="#i-code"/></svg>Режим защиты</button>
<div class="profile"><button id="open-profile" class="profile-main" title="Открыть профиль"><span id="profile-avatar" class="avatar"></span><span class="profile-text"><strong id="profile-name"></strong><span id="profile-username"></span></span></button><button id="logout" class="icon-button" aria-label="Выйти" title="Выйти"><svg><use href="#i-exit"/></svg></button></div>
</aside>
<main class="workspace">
<div id="welcome" class="welcome"><div class="welcome-symbol"><svg><use href="#i-chat"/></svg><span class="tiny-dot"></span></div><h1>Начните<br><em>разговор.</em></h1><p>Выберите чат или создайте новый.</p><button id="welcome-new-chat" class="button primary"><svg><use href="#i-plus"/></svg>Создать чат</button></div>
<section id="conversation" class="conversation" hidden>
<header class="chat-header"><button id="back-to-chats" class="icon-button mobile-only" aria-label="К списку чатов"><svg><use href="#i-arrow"/></svg></button><span id="current-avatar" class="avatar chat-avatar"></span><div class="chat-heading"><h2 id="current-title"></h2><span id="current-members"></span></div><button id="refresh-messages" class="icon-button" aria-label="Обновить сообщения" title="Обновить сообщения"><svg><use href="#i-refresh"/></svg></button><button id="show-members" class="icon-button" aria-label="Участники чата" title="Участники чата"><svg><use href="#i-users"/></svg></button><button class="icon-button mobile-only" type="button" data-defense-toggle aria-label="Режим защиты" title="Режим защиты" aria-controls="defense-panel" aria-expanded="false"><svg><use href="#i-code"/></svg></button></header>
<div id="message-scroll" class="message-scroll"><div class="history-control"><button id="older-messages" class="text-button" hidden>Ранее в разговоре ↑</button></div><div id="message-list" class="message-list" aria-label="Сообщения"></div><p id="empty-conversation" class="empty-conversation" hidden>Пока нет сообщений.</p></div>
<form id="message-form" class="composer"><label class="visually-hidden" for="message-input">Сообщение</label><textarea id="message-input" rows="1" placeholder="Сообщение…" enterkeyhint="send"></textarea><button id="send-message" class="send-button" aria-label="Отправить сообщение" title="Отправить сообщение" disabled><svg><use href="#i-send"/></svg></button><div class="composer-note"><span>Enter - отправить · Shift + Enter - новая строка</span><span id="message-count">0 / 4000</span></div></form>
</section>
</main>
</section>
<aside id="defense-panel" class="defense-panel" aria-labelledby="defense-title" hidden>
<div class="defense-heading"><div><span class="eyebrow">Показ работы API</span><h2 id="defense-title">Режим защиты</h2></div><button id="defense-close" class="icon-button" type="button" aria-label="Закрыть режим защиты"><svg><use href="#i-close"/></svg></button></div>
<div class="defense-summary"><div><span class="defense-label">Пользователь</span><strong id="defense-user">Вход не выполнен</strong></div><div><span class="defense-label">До конца сессии</span><strong id="defense-session">-</strong></div></div>
<section class="scenario-section" aria-labelledby="scenario-title">
<h3 id="scenario-title">Проверки API</h3>
<p class="scenario-description">2 пользователя · чат · 3 сообщения</p>
<div class="scenario-actions"><button id="scenario-prepare" class="button primary" type="button" disabled>Подготовить демонстрацию</button><button id="scenario-check" class="button secondary" type="button" disabled>Проверить типичные вопросы</button></div>
<p id="scenario-status" class="scenario-status" role="status" aria-live="polite">Войдите, чтобы запустить сценарии.</p>
<ol id="scenario-steps" class="scenario-steps" aria-label="Шаги сценария" hidden></ol>
</section>
<section class="defense-history"><span class="defense-label">История выбранного чата</span><strong id="defense-chat">Выберите чат</strong><p id="defense-messages">Сообщения ещё не загружены</p></section>
<section class="defense-request"><div class="defense-section-heading"><h3>Последний запрос</h3><time id="defense-request-time"></time></div><p id="defense-empty" class="defense-note">Войдите, откройте чат или отправьте сообщение.</p><div id="defense-request-details" hidden><div class="defense-request-line"><span id="defense-method" class="defense-method"></span><span id="defense-status" class="defense-status"></span></div><span id="defense-origin" class="defense-label defense-origin"></span><code id="defense-path" class="defense-path"></code><p id="defense-result" class="defense-result" role="status" aria-live="polite"></p><dl class="defense-metrics"><div><dt>Авторизация</dt><dd id="defense-auth"></dd></div><div><dt>Время запроса</dt><dd id="defense-duration"></dd></div></dl><span class="defense-label">X-Request-Id</span><code id="defense-request-id" class="defense-request-id"></code></div></section>
<ol id="defense-previous" class="defense-previous" aria-label="Предыдущие запросы" hidden></ol>
<p id="defense-background" class="defense-background" hidden></p>
<details class="defense-help"><summary>О проверках</summary><p class="defense-note">Шаги раскрываются нажатием. Демоданные остаются в базе; после обновления страницы нужен новый набор. Тестовые сессии завершаются отдельно от вашего входа.</p><p class="defense-note">Время и срок сессии - по часам браузера. Фоновые чтения показаны отдельно. Пароли и токены скрыты. Redis, индексы и backup проверяются в терминале.</p></details>
</aside>
<div id="toast" class="toast" role="status" aria-live="polite" hidden></div>
<dialog id="new-chat-dialog"><div class="dialog-heading"><h2>Собрать чат</h2><button class="icon-button" data-close-dialog aria-label="Закрыть"><svg><use href="#i-close"/></svg></button></div><form id="new-chat-form"><label>Название чата<input id="new-chat-title" placeholder="Название" required></label><label>ID участников<textarea id="new-chat-members" rows="3" placeholder="Вставьте ID через запятую или с новой строки" spellcheck="false"></textarea><span class="field-note">Вы добавитесь автоматически. Для чата с собой оставьте поле пустым.</span></label><p id="chat-dialog-notice" class="form-notice" role="status" hidden></p><div class="dialog-actions"><button class="button secondary" type="button" data-close-dialog>Отмена</button><button class="button primary" type="submit">Создать чат</button></div></form></dialog>
<dialog id="profile-dialog"><div class="dialog-heading"><h2>Ваш профиль</h2><button class="icon-button" data-close-dialog aria-label="Закрыть"><svg><use href="#i-close"/></svg></button></div><p id="profile-details" class="muted"></p><label>Ваш ID<input id="my-id" readonly spellcheck="false"></label><p class="field-note">Поделитесь ID для приглашения в чат.</p><button id="copy-id" class="button primary wide"><svg><use href="#i-copy"/></svg>Скопировать ID</button></dialog>
<dialog id="members-dialog"><div class="dialog-heading"><h2>Участники чата</h2><button class="icon-button" data-close-dialog aria-label="Закрыть"><svg><use href="#i-close"/></svg></button></div><div id="members-list" class="members-list"></div></dialog>
</body>
</html>
+249
View File
@@ -0,0 +1,249 @@
// Decorative reactions use focus and password length only, never password text.
const stage = document.getElementById("mascot-stage");
const auth = document.getElementById("auth-screen");
const reduceMotion = matchMedia("(prefers-reduced-motion: reduce)");
const mobile = matchMedia("(max-width: 720px)");
let feedbackTimer = null, pending = false, feedback = false;
let frame = null, lastFrame = 0, hopStarted = -Infinity, lastInput = -Infinity;
let lastActivity = performance.now(), ready = false;
let pointer = { x: 0, y: 0 }, closeHovered = false, closeFocused = false;
const trip = { phase: "home", started: 0, from: 0, progress: 0, field: null, anchor: null };
const clamp = value => Math.max(0, Math.min(1, value));
const ease = value => { const t = clamp(value); return t * t * (3 - 2 * t); };
const specs = [
{ width: 64, height: 150, home: 24 },
{ width: 82, height: 102, home: 82 },
{ width: 84, height: 110, home: 154 }
];
const shapes = [...stage.querySelectorAll(".mascot")].map((element, index) => ({
...specs[index], element, body: element.querySelector(".mascot-body"),
position: { tilt: 0, squash: 0, x: 0, y: 0 },
velocity: { tilt: 0, squash: 0, x: 0, y: 0 }
}));
function homeFor(shape, index, width) {
return mobile.matches ? Math.max(0, (width - 168) / 2) + [0, 40, 86][index] : shape.home;
}
function activeField() {
const focused = document.activeElement;
return focused?.matches("[data-password-toggle]")
? document.getElementById(focused.dataset.passwordToggle) : focused;
}
function beginTrip(field) {
lastActivity = lastInput = performance.now(); trip.field = field;
if (trip.phase === "home" || trip.phase === "back") {
trip.from = trip.progress; trip.phase = "forward"; trip.started = lastInput;
}
}
function goBack(time = performance.now()) {
if (trip.phase === "forward" || trip.phase === "near") {
trip.from = trip.progress; trip.phase = "back"; trip.started = time;
}
}
function updateTrip(time) {
if (trip.phase === "forward" && time - trip.started > 1960) trip.phase = "near";
if (trip.phase === "near" && time > Math.max(lastInput + 1700, trip.started + 3200)) goBack(time);
if (trip.phase === "back" && time - trip.started > 1960) {
trip.phase = "home"; trip.progress = 0;
}
stage.dataset.trip = trip.phase;
}
function stride(time, index) {
if (trip.phase === "home") return { progress: 0, hop: 0 };
if (trip.phase === "near") return { progress: 1, hop: 0 };
const t = clamp((time - trip.started - index * 80) / 1800);
const step = t * 8, fraction = step % 1;
const stepped = (Math.floor(step) + ease(fraction)) / 8;
const progress = trip.phase === "forward" ? trip.from + (1 - trip.from) * stepped : trip.from * (1 - stepped);
const hop = t > 0 && t < 1 ? -(Math.sin(fraction * Math.PI) ** 2) * (trip.phase === "back" ? 14 : 10) : 0;
return { progress, hop };
}
function paint(shape, movement = { hop: 0 }) {
const { tilt, squash, x, y } = shape.position;
// One complete silhouette: gentle posture changes, no added neck or body.
shape.body.style.transform = `rotate(${tilt.toFixed(2)}deg) scale(${(1 + squash * .4).toFixed(3)}, ${(1 - squash).toFixed(3)})`;
shape.element.style.transform = `translate(${x.toFixed(2)}px, ${(y + movement.hop).toFixed(2)}px)`;
}
function targets(shape, index, time, movement, bounds, fieldBounds) {
const state = stage.dataset.mood, phase = time / 1000 + index * .65;
const scale = mobile.matches ? .62 : 1;
const home = homeFor(shape, index, bounds.width);
const baseX = bounds.left + home;
const baseY = bounds.bottom - (mobile.matches ? 11 : 21);
let tilt = pointer.x * 3 + Math.sin(phase * .65), squash = Math.sin(phase) * .012, x = 0, y = 0;
if (fieldBounds) {
// Whole figures approach the field, staying inside their stage on mobile.
const goalX = mobile.matches ? baseX + [6, 0, -6][index] : fieldBounds.left - 272 + [0, 72, 152][index];
x = (goalX - baseX) * movement.progress;
const goalY = mobile.matches ? -8 : fieldBounds.top + fieldBounds.height / 2 + shape.height / 2 - baseY;
y = goalY * movement.progress;
if (state === "looking") tilt += 5;
}
if (state === "private" || state === "short") tilt += [-7, -3, 7][index];
if (state === "revealed" && index === 2) {
const round = shapes[1], roundHome = homeFor(round, 1, bounds.width);
x = roundHome + round.position.x - home + (round.width - shape.width) * scale / 2 + 6;
y = round.position.y - (round.height - shape.height) * scale / 2 + 4;
tilt = -3;
}
if (state === "pending") { tilt += Math.sin(phase * 2) * 3; y += Math.sin(phase * 2) * 2; }
if (state === "error") { x += Math.sin(phase * 12) * 3; squash += .04; }
if (state === "success") {
const progress = (time - hopStarted - index * 65) / 480;
y += progress >= 0 && progress < 1 ? -Math.sin(progress * Math.PI) * 18 : 0;
}
if (ready) squash += .07;
if (stage.classList.contains("is-sleepy")) { squash += .05; tilt += Math.sin(phase * .3) * 2; }
if (stage.classList.contains("is-scared")) {
tilt = -5 + Math.sin(phase * 21) * 3; squash = .13;
x -= 3 + Math.sin(phase * 21) * 2; y += 2;
}
return { tilt, squash, x, y, home, baseY };
}
function animate(time) {
frame = null;
if (auth.hidden || document.hidden || reduceMotion.matches) { lastFrame = 0; return; }
const dt = Math.min((time - (lastFrame || time - 16)) / 1000, .032); lastFrame = time;
updateTrip(time);
stage.classList.toggle("is-sleepy", trip.phase === "home" && stage.dataset.mood === "idle" && time - lastActivity > 12000);
const bounds = stage.getBoundingClientRect();
const field = trip.field?.isConnected && !trip.field.closest("[hidden]") ? trip.field : activeField();
const fieldBounds = field?.matches("input") ? field.getBoundingClientRect() : (trip.phase === "back" ? trip.anchor : null);
if (field?.matches("input")) trip.anchor = fieldBounds;
for (const [index, shape] of shapes.entries()) {
const movement = stride(time, index);
if (index === 0) trip.progress = movement.progress;
const target = targets(shape, index, time, movement, bounds, fieldBounds);
// Fixed desktop wrappers escape the clipped decorative intro without
// changing the form's layout or hit targets. Mobile stays inside the stage.
shape.element.style.position = mobile.matches ? "absolute" : "fixed";
shape.element.style.left = `${mobile.matches ? target.home : bounds.left + target.home}px`;
shape.element.style.top = mobile.matches ? "auto" : `${target.baseY - shape.height}px`;
shape.element.style.bottom = mobile.matches ? "11px" : "auto";
for (const key of Object.keys(shape.position)) {
shape.velocity[key] += ((target[key] - shape.position[key]) * 170 - shape.velocity[key] * 22) * dt;
shape.position[key] += shape.velocity[key] * dt;
}
paint(shape, movement);
}
frame = requestAnimationFrame(animate);
}
function startAnimation() {
if (reduceMotion.matches) {
trip.phase = "home"; trip.progress = 0; stage.classList.remove("is-sleepy");
for (const [index, shape] of shapes.entries()) {
shape.element.style.position = "absolute";
shape.element.style.left = `${homeFor(shape, index, stage.clientWidth)}px`;
shape.element.style.top = "auto"; shape.element.style.bottom = mobile.matches ? "11px" : "21px";
shape.position = { tilt: 0, squash: 0, x: 0, y: 0 };
shape.velocity = { tilt: 0, squash: 0, x: 0, y: 0 };
paint(shape);
}
} else if (frame === null && !auth.hidden && !document.hidden) frame = requestAnimationFrame(animate);
}
function mood(value) {
stage.dataset.mood = value;
stage.style.setProperty("--gaze-x", "0px"); stage.style.setProperty("--gaze-y", "0px");
startAnimation();
}
function focusedMood() {
if (pending || feedback) return;
const field = activeField();
if (field?.id === "login-password" || field?.id === "register-password") {
if (field.type === "text") mood("revealed");
else if (field.id === "register-password" && field.value.length > 0 && Array.from(field.value).length < 12) mood("short");
else mood("private");
} else if (field?.matches("#login-username, #register-name, #register-username")) mood("looking");
else mood("idle");
}
export function setMascotMood(value) {
if (value === "pending") goBack();
clearTimeout(feedbackTimer);
pending = value === "pending";
feedback = value === "error" || value === "success" || value === "short";
if (value === "success") hopStarted = performance.now();
mood(value);
if (feedback) feedbackTimer = setTimeout(() => { feedback = false; focusedMood(); }, 3500);
}
for (const form of document.querySelectorAll("#login-form, #register-form")) {
form.addEventListener("focusin", () => {
const field = activeField();
if (trip.phase !== "home" && field?.matches("input")) trip.field = field;
if (!pending) { feedback = false; clearTimeout(feedbackTimer); }
lastActivity = performance.now();
focusedMood();
});
form.addEventListener("invalid", () => setMascotMood("error"), true);
form.addEventListener("focusout", () => requestAnimationFrame(() => {
focusedMood();
if (!activeField()?.matches("input, [data-password-toggle]")) goBack();
}));
form.addEventListener("input", event => {
feedback = false; focusedMood(); beginTrip(event.target);
});
form.addEventListener("reset", () => {
for (const button of form.querySelectorAll("[data-password-toggle]")) {
document.getElementById(button.dataset.passwordToggle).type = "password";
button.setAttribute("aria-pressed", "false"); button.setAttribute("aria-label", "Показать пароль");
}
});
}
for (const button of document.querySelectorAll("[data-password-toggle]")) {
button.addEventListener("click", () => {
const field = document.getElementById(button.dataset.passwordToggle), shown = field.type === "password";
field.type = shown ? "text" : "password";
button.setAttribute("aria-pressed", String(shown)); button.setAttribute("aria-label", shown ? "Скрыть пароль" : "Показать пароль");
feedback = false; focusedMood();
});
}
for (const button of document.querySelectorAll(".auth-switch button")) {
button.addEventListener("click", () => { pending = false; feedback = false; goBack(); trip.field = null; lastActivity = performance.now(); mood("idle"); });
}
auth.addEventListener("pointermove", event => {
lastActivity = performance.now();
if (reduceMotion.matches || event.pointerType === "touch" || stage.dataset.mood !== "idle") return;
const bounds = stage.getBoundingClientRect();
pointer = { x: Math.max(-1, Math.min(1, (event.clientX - bounds.left - bounds.width / 2) / 320)),
y: Math.max(-1, Math.min(1, (event.clientY - bounds.top - bounds.height / 2) / 220)) };
stage.style.setProperty("--gaze-x", `${pointer.x * 4}px`); stage.style.setProperty("--gaze-y", `${pointer.y * 3}px`);
});
auth.addEventListener("pointerleave", () => {
pointer = { x: 0, y: 0 }; stage.style.setProperty("--gaze-x", "0px"); stage.style.setProperty("--gaze-y", "0px");
});
const close = document.getElementById("defense-close");
function reactToClose() { stage.classList.toggle("is-scared", (closeHovered || (closeFocused && close.matches(":focus-visible"))) && !close.closest("[hidden]")); }
close.addEventListener("pointerenter", event => { if (event.pointerType !== "touch") { closeHovered = true; reactToClose(); } });
close.addEventListener("pointerleave", () => { closeHovered = false; reactToClose(); });
close.addEventListener("focus", () => { closeFocused = true; reactToClose(); });
close.addEventListener("blur", () => { closeFocused = false; reactToClose(); });
close.addEventListener("keydown", () => requestAnimationFrame(reactToClose));
new MutationObserver(() => { if (close.closest("[hidden]")) { closeHovered = false; closeFocused = false; reactToClose(); } }).observe(document.getElementById("defense-panel"), { attributes: true, attributeFilter: ["hidden"] });
for (const button of auth.querySelectorAll("form .button.primary")) {
button.addEventListener("pointerenter", event => { if (event.pointerType !== "touch") ready = true; });
button.addEventListener("pointerleave", () => { ready = false; });
}
reduceMotion.addEventListener("change", startAnimation);
document.addEventListener("visibilitychange", startAnimation);
new MutationObserver(() => {
lastActivity = performance.now();
if (auth.hidden) {
trip.phase = "home"; trip.progress = 0; trip.field = null; trip.anchor = null;
ready = pending = feedback = false; hopStarted = -Infinity; clearTimeout(feedbackTimer);
stage.dataset.mood = "idle";
for (const shape of shapes) {
shape.position = { tilt: 0, squash: 0, x: 0, y: 0 };
shape.velocity = { tilt: 0, squash: 0, x: 0, y: 0 }; paint(shape);
}
}
startAnimation();
}).observe(auth, { attributes: true, attributeFilter: ["hidden"] });
export async function celebrateMascots() {
setMascotMood("success");
if (!reduceMotion.matches) await new Promise(resolve => setTimeout(resolve, 650));
}
function placeStage() {
if (mobile.matches) {
const anchor = document.getElementById("login-panel"); anchor.parentElement.insertBefore(stage, anchor);
} else document.querySelector(".intro").append(stage);
}
mobile.addEventListener("change", () => { trip.phase = "home"; trip.progress = 0; trip.field = null; trip.anchor = null; placeStage(); });
placeStage(); startAnimation();
+223
View File
@@ -0,0 +1,223 @@
import { recordDefenseRequest } from "/defense.js";
const $ = id => document.getElementById(id);
let hooks = null, busy = false, fixture = null;
const shortPath = path => path.replace(/\/[a-f0-9-]{36}(?=\/|$)/gi, "/…");
export function configureScenarios(value) { hooks = value; updateScenarioAccess(); }
export function updateScenarioAccess() {
const actor = hooks?.getActor();
if (!busy && fixture && fixture.ownerId !== actor?.id) fixture = null;
$("scenario-prepare").disabled = busy || !actor;
$("scenario-check").disabled = busy || !actor || fixture?.ownerId !== actor.id;
$("scenario-prepare").textContent = fixture && actor?.id === fixture.ownerId ? "Открыть демочат" : "Подготовить демонстрацию";
if (!busy && !actor) status("Войдите для запуска.");
else if (!busy && fixture?.ownerId !== actor?.id) status("Сначала подготовьте демочат.");
}
function status(message, failed = false) {
$("scenario-status").textContent = message;
$("scenario-status").classList.toggle("failed", failed);
}
function begin(message) {
busy = true;
updateScenarioAccess();
$("scenario-steps").replaceChildren();
$("scenario-steps").hidden = false;
status(message);
}
// The view receives selected metadata only. Credentials and response bodies stay
// in this module's memory and are never placed in DOM, storage or console output.
async function step(label, { path, method = "GET", expected = 200, body, token, credentials, source, explanation }) {
const item = document.createElement("li");
const details = document.createElement("details"); details.className = "scenario-step"; details.dataset.state = "pending";
const summary = document.createElement("summary");
const badge = document.createElement("span"); badge.className = "scenario-step-badge"; badge.textContent = "…";
const name = document.createElement("span"); name.textContent = label;
summary.append(badge, name);
const description = document.createElement("p"); description.textContent = explanation;
const route = document.createElement("code"); route.textContent = `${method} ${shortPath(path)}`;
const result = document.createElement("p"); result.textContent = `Ожидаем HTTP ${expected}. Запрос выполняется…`;
const trace = document.createElement("code");
details.append(summary, description, route, result, trace); item.append(details);
$("scenario-steps").append(item);
$("scenario-steps").scrollTop = $("scenario-steps").scrollHeight;
status(label + "…");
const started = performance.now(), controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 12000);
const headers = { Accept: "application/json" };
if (body !== undefined) headers["Content-Type"] = "application/json";
if (token) headers.Authorization = "Bearer " + token;
if (credentials) headers.Authorization = "Basic " + btoa(credentials.username + ":" + credentials.password);
let httpStatus = null, requestId = null, outcome = "network";
try {
const response = await fetch(path, { method, headers, body: body === undefined ? undefined : JSON.stringify(body),
credentials: "omit", cache: "no-store", signal: controller.signal });
httpStatus = response.status;
requestId = response.headers.get("X-Request-Id");
outcome = "unreadable";
const data = httpStatus === 204 ? null : await response.json();
outcome = response.ok ? "success" : "http_error";
const passed = httpStatus === expected;
details.dataset.state = passed ? "passed" : "failed";
badge.textContent = `${passed ? "✓" : "✕"} ${httpStatus}`;
result.textContent = `Ожидали HTTP ${expected} · получили HTTP ${httpStatus}.`;
trace.textContent = `X-Request-Id: ${requestId || "не получен"} · ${Math.round(performance.now() - started)} мс`;
if (!passed) {
details.open = true;
throw new Error(`«${label}»: ожидали HTTP ${expected}, получили ${httpStatus}. Сценарий остановлен.`);
}
return data;
} catch (error) {
details.dataset.state = "failed";
details.open = true;
if (outcome === "network" || outcome === "unreadable") {
badge.textContent = httpStatus === null ? "✕ -" : `✕ ${httpStatus}`;
result.textContent = httpStatus === null
? "Ответ не получен. Результат записи неизвестен; перед повторным запуском проверьте список чатов."
: `Получили HTTP ${httpStatus}, но не смогли прочитать ответ.`;
trace.textContent = `X-Request-Id: ${requestId || "не получен"}`;
throw new Error(result.textContent);
}
throw error;
} finally {
clearTimeout(timer);
recordDefenseRequest({ method, path, status: httpStatus, requestId, outcome,
authorization: credentials ? "Basic" : token ? "Bearer" : "Без авторизации",
durationMs: Math.round(performance.now() - started), source: "Сценарий · " + source });
}
}
function actor() {
const value = hooks?.getActor();
if (!value) throw new Error("Войдите в основной аккаунт, чтобы запустить сценарий.");
return value;
}
async function openDemo(owner) {
if (hooks.getActor()?.id !== owner.id || hooks.getActor()?.token !== owner.token)
throw new Error("Основной вход изменился. Войдите в исходный аккаунт и откройте созданный чат из списка.");
await hooks.openChat(fixture.chat, owner);
}
function account(prefix, suffix, displayName) {
return { username: `demo_${prefix}_${suffix}`, display_name: displayName, password: "Lab-demo:" + crypto.randomUUID() };
}
async function login(user, label, cleanup) {
const session = await step(label, { path: "/api/v1/auth/sessions", method: "POST", expected: 201,
credentials: user, source: user.display_name, explanation: "Basic передаёт логин и пароль. Сервер выдаёт отдельную сессию." });
cleanup.push({ token: session.token, name: user.display_name, revoked: false });
return session;
}
async function finishSessions(cleanup) {
let failure = null;
for (const session of cleanup) {
if (session.revoked) continue;
try {
await step(`Завершить тестовый вход: ${session.name}`, { path: "/api/v1/auth/sessions/current", method: "DELETE", expected: 204,
token: session.token, source: session.name, explanation: "Отзываем только тестовую сессию. Ваш основной вход остаётся действующим." });
session.revoked = true;
} catch (error) { failure ||= error; }
}
if (failure) throw new Error("Не удалось подтвердить завершение всех тестовых сессий. " + failure.message);
}
async function prepare() {
if (busy) return;
const owner = actor();
if (fixture?.ownerId === owner.id) {
busy = true;
updateScenarioAccess();
status("Открываем уже созданный демочат…");
try {
await openDemo(owner);
status("Демочат открыт.");
} catch (error) { status(error.message, true); }
finally { busy = false; updateScenarioAccess(); }
return;
}
begin("Подготовка демочата…");
const cleanup = [];
let failure = null;
try {
const suffix = crypto.randomUUID().replaceAll("-", "").slice(0, 12);
const alice = account("a", suffix, "Демо участник");
const observer = account("b", suffix, "Демо наблюдатель");
alice.user = await step("Создать участника", { path: "/api/v1/users", method: "POST", expected: 201,
body: { username: alice.username, display_name: alice.display_name, password: alice.password }, source: "без входа",
explanation: "Уникальный логин и пароль длиннее 12 символов. Пользователь сохраняется в базе." });
observer.user = await step("Создать наблюдателя", { path: "/api/v1/users", method: "POST", expected: 201,
body: { username: observer.username, display_name: observer.display_name, password: observer.password }, source: "без входа",
explanation: "Этот пользователь не войдёт в чат: он понадобится для проверки доступа." });
const aliceSession = await login(alice, "Войти как участник", cleanup);
await login(observer, "Войти как наблюдатель", cleanup);
const chat = await step("Создать общий чат", { path: "/api/v1/chats", method: "POST", expected: 201, token: owner.token,
body: { title: "Демо · " + suffix.slice(0, 4), member_ids: [owner.id, alice.user.id] }, source: "ваш аккаунт",
explanation: "В чате два участника. Наблюдатель остаётся снаружи." });
for (const [label, text, token, source] of [
["Сообщение от вас", "Привет! Проверяем сообщения.", owner.token, "ваш аккаунт"],
["Ответ участника", "Привет! Сообщение получил.", aliceSession.token, alice.display_name],
["Ещё одно сообщение от вас", "Чат работает.", owner.token, "ваш аккаунт"]
]) await step(label, { path: `/api/v1/chats/${chat.id}/messages`, method: "POST", expected: 201, token, body: { text }, source,
explanation: "Настоящий POST создаёт сообщение. Оно появится в общей переписке." });
fixture = { ownerId: owner.id, chat, alice, observer };
await openDemo(owner);
} catch (error) { failure = error; }
finally {
try { await finishSessions(cleanup); } catch (error) { failure ||= error; }
busy = false;
updateScenarioAccess();
status(failure ? failure.message : "Демочат готов.", Boolean(failure));
}
}
async function checks() {
if (busy) return;
const owner = actor();
if (!fixture || fixture.ownerId !== owner.id) return;
begin("Проверяем API…");
const cleanup = [];
let failure = null;
try {
const { alice, observer, chat } = fixture;
const a = await login(alice, "Тестовый вход участника", cleanup);
const b = await login(observer, "Тестовый вход постороннего", cleanup);
await step("Повторный логин при регистрации", { path: "/api/v1/users", method: "POST", expected: 409, source: "без входа",
body: { username: alice.username, display_name: alice.display_name, password: alice.password },
explanation: "Повторное имя пользователя отклоняется: username должен быть уникальным." });
await step("Неверный пароль", { path: "/api/v1/auth/sessions", method: "POST", expected: 401, source: alice.display_name,
credentials: { username: alice.username, password: alice.password + "wrong" },
explanation: "Неверные учётные данные не дают сессию. Ваш основной вход при этом сохраняется." });
await step("Слишком короткий пароль", { path: "/api/v1/users", method: "POST", expected: 400, source: "без входа",
body: { username: "short_" + crypto.randomUUID().replaceAll("-", "").slice(0, 12), display_name: "Короткий пароль", password: "125125" },
explanation: "Регистрация требует 12-128 символов. Шесть цифр не проходят проверку." });
await step("Пустое сообщение", { path: `/api/v1/chats/${chat.id}/messages`, method: "POST", expected: 400,
token: a.token, body: { text: " " }, source: alice.display_name,
explanation: "Пробелы не считаются сообщением. Сервер должен отклонить отправку." });
await step("Один участник дважды", { path: "/api/v1/chats", method: "POST", expected: 400, token: owner.token, source: "ваш аккаунт",
body: { title: "Повтор участника", member_ids: [owner.id, alice.user.id, alice.user.id] },
explanation: "API отклоняет повтор ID в списке участников. Два одинаковых участника не создаются." });
await step("Посторонний открывает чат", { path: `/api/v1/chats/${chat.id}`, expected: 404, token: b.token, source: observer.display_name,
explanation: "Наблюдатель не состоит в чате. Сервер не раскрывает ему чат и отвечает 404." });
await step("Выход тестового пользователя", { path: "/api/v1/auth/sessions/current", method: "DELETE", expected: 204,
token: b.token, source: observer.display_name, explanation: "Выход отзывает тестовую сессию наблюдателя." });
cleanup.find(session => session.token === b.token).revoked = true;
await step("Старый токен после выхода", { path: "/api/v1/users/me", expected: 401, token: b.token, source: observer.display_name,
explanation: "Отозванная сессия больше не разрешает запросы. Старый токен не работает." });
} catch (error) { failure = error; }
finally {
try { await finishSessions(cleanup); } catch (error) { failure ||= error; }
busy = false;
updateScenarioAccess();
status(failure ? failure.message : "Пройдено 8 из 8.", Boolean(failure));
}
}
$("scenario-prepare").addEventListener("click", () => { void prepare().catch(error => status(error.message, true)); });
$("scenario-check").addEventListener("click", () => { void checks().catch(error => status(error.message, true)); });