фронт и secure browser session

This commit is contained in:
2026-10-23 14:48:57 +03:00
parent bd28f1ae26
commit 34618bd423
43 changed files with 5374 additions and 28 deletions
+3
View File
@@ -16,5 +16,8 @@ backups
.venv
__pycache__
node_modules
**/node_modules
frontend/dist
frontend/.vite
evidence
.DS_Store
+2
View File
@@ -12,6 +12,8 @@ POSTGRES_DB=messenger
SESSION_TTL_SECONDS=3600
SESSION_STORE=postgres
# Keep false only for local HTTP. Set true when the public entrypoint uses HTTPS.
SESSION_COOKIE_SECURE=false
CURSOR_SIGNING_KEY_FILE=/run/secrets/cursor_signing_key
API_REPLICAS=2
+48 -6
View File
@@ -5,9 +5,10 @@
- Итоговая цель: оценка «5»; трек будет выбран после реализации уровня «4»
- Commit/PR: заполняется автором после локального коммита и публикации
- Использованные источники и библиотеки: преподавательские README/OpenAPI/tests,
документация Go, pgx, PostgreSQL, Docker Compose и Nginx. Для разбора
архитектуры, рефакторинга, реализации и проверок использовался OpenAI Codex;
решения проверены тестами и описанными ниже воспроизводимыми сценариями.
документация Go, pgx, PostgreSQL, Docker Compose, Nginx, React, TypeScript,
Vite, TanStack Query, React Router, Lucide и Vitest. Для разбора архитектуры,
рефакторинга, реализации и проверок использовался OpenAI Codex; решения
проверены тестами и описанными ниже воспроизводимыми сценариями.
## Запуск из чистого clone
@@ -39,6 +40,14 @@ docker compose --env-file .env up -d --wait api
make test-persistence ACTION_SCRIPT=./scripts/restart.sh
```
По этому же адресу Nginx отдаёт production-сборку React. Переход на
`http://localhost:8080` открывает Messenger, а `/api/v1/*` и health endpoints
остаются доступны автоматическим проверкам. Отдельный Node.js на машине для
обычного запуска не нужен: multi-stage image сам выполняет `npm ci`, Vitest,
TypeScript build и копирует статические файлы в Nginx. Для production с HTTPS
нужно установить `SESSION_COOKIE_SECURE=true`; локально по HTTP значение остаётся
`false`.
`stop-one.sh` оставляет выбранную тестом реплику остановленной. Команда `up` в
примере явно возвращает желаемые две реплики перед следующей проверкой.
Обычная остановка не удаляет named volumes:
@@ -124,6 +133,37 @@ commit откатывает и бизнес-эффект, и запись клю
фиксируется как успешный результат. Перед replay снова выполняются обычная
проверка bearer-сессии и проверка членства в чате.
### Frontend и браузерная сессия
Клиент находится в `frontend/` и собран на React + TypeScript + Vite. TanStack
Query отвечает за серверное состояние и периодическое обновление списков,
React Router — за маршруты login/register, выбранного чата и профиля. UI сделан
адаптивным: на широком экране одновременно видны навигация, список и разговор,
а на узком список и чат переключаются как отдельные мобильные экраны. Фон чата
добавлен из предоставленного изображения; нейтральная графитово-белая палитра,
мягкая системная типографика и скруглённая геометрия компонентов подобраны
самостоятельно, без копирования Telegram.
Токен не хранится в `localStorage` и недоступен JavaScript. Успешный login
по-прежнему возвращает преподавательский JSON с bearer token, но дополнительно
ставит host-only cookie `mtusi_session` с `Path=/`, `HttpOnly` и
`SameSite=Strict`. Флаг `Secure` управляется `SESSION_COOKIE_SECURE`: `false`
нужен только локальному HTTP, на HTTPS должен быть `true`.
Контрактные `/api/v1/*` сознательно остались Bearer-only. Nginx предоставляет
отдельный браузерный адаптер `/web-api/v1/*`: берёт token из HttpOnly-cookie,
формирует `Authorization: Bearer ...`, удаляет исходный `Cookie` и проксирует на
обычный `/api/v1/*`. Поэтому преподавательские тесты и внешние API-клиенты не
получили скрытый альтернативный способ авторизации. Same-origin deployment,
`SameSite=Strict`, JSON-only изменяющие запросы и отсутствие CORS для сторонних
origin уменьшают CSRF-поверхность. Logout удаляет серверную сессию и истекает
cookie.
Список чатов показывает только данные, реально существующие в контракте: title
и число участников. Превью последнего сообщения и unread counter не имитируются,
поскольку backend их пока не отдаёт. При неопределённой ошибке отправки клиент
сохраняет текст вместе с `Idempotency-Key`; повтор использует тот же ключ.
## Доказательства критериев
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
@@ -136,6 +176,7 @@ commit откатывает и бизнес-эффект, и запись клю
| Failover каждой API-реплики | два последовательных запуска `make test-failover ACTION_SCRIPT=./scripts/stop-one.sh` с восстановлением между ними | реально остановлены `api-2`, затем `api-1`; получено 142/143 успешных записи, 0 ошибок, восстановление 0.963/0.750 с | `scripts/stop-one.sh`, `evidence/lab3-summary.md` |
| Persistence после рестартов | `make test-persistence ACTION_SCRIPT=./scripts/restart.sh` | PASS; прежняя сессия и данные доступны после рестарта PostgreSQL, Redis, API и LB | `scripts/restart.sh`, `evidence/lab3-summary.md` |
| Миграции перед API | `docker compose --env-file .env ps -a` и логи `migrate` | миграции 1 и 2 применены; one-shot контейнер завершился с кодом 0; API healthy | `migrations/000002_message_idempotency.up.sql`, `evidence/lab3-summary.md` |
| React frontend и HttpOnly BFF | `docker compose build load-balancer`; browser QA; cookie-only curl-сценарий | Vitest/TypeScript/Vite build PASS; register/login 201; прямой `/api` 401; `/web-api` 200; logout 204, после logout 401; browser console без warning/error | `frontend/`, `infrastructure/nginx/Dockerfile`, `infrastructure/nginx/nginx.conf` |
## Эксперименты и отказы
@@ -164,8 +205,9 @@ API-реплики; лимиты CPU/RAM пока не задавались, м
очистки без изменения схемы.
- Resource limits, количественный нагрузочный эксперимент и сценарий rolling
update ещё не реализованы; это следующий этап уровня «4».
- Frontend на React + TypeScript + Vite будет отдельным этапом и отдельным
коммитом после фиксации уровня «3». Тогда же будет спроектирована cookie-based
авторизация с учётом текущего bearer-контракта API.
- Текущий API не содержит endpoint поиска пользователей, аватаров, изменения
имени/пароля и агрегатов last message/unread. Поэтому UI принимает UUID
участников при создании чата, а профиль честно показывает только доступные
поля. Эти функции требуют сначала расширить и зафиксировать API-контракт.
- Трек уровня «5» пока не заявлен: сначала необходимо завершить и измерить
обязательный уровень «4».
+1
View File
@@ -101,6 +101,7 @@ func main() {
databasePool,
cfg.ReadinessTimeout,
),
handlers.WithSessionCookieSecure(cfg.SessionCookieSecure),
)
mux := http.NewServeMux()
+5 -3
View File
@@ -1,10 +1,11 @@
services:
load-balancer:
image: nginx:1.30.6-alpine@sha256:970364228b1e4f932abc22d321932816782cca8a20b85a77552a7cfe9acfb3b5
build:
context: .
dockerfile: infrastructure/nginx/Dockerfile
image: mtusi2026lab3-web
ports:
- "127.0.0.1:${APP_PORT:-8080}:8080"
volumes:
- ./infrastructure/nginx/nginx.conf:/etc/nginx/nginx.conf:ro
depends_on:
api:
condition: service_healthy
@@ -96,6 +97,7 @@ services:
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400}
SESSION_STORE: ${SESSION_STORE:-postgres}
SESSION_COOKIE_SECURE: ${SESSION_COOKIE_SECURE:-false}
CURSOR_SIGNING_KEY_FILE: ${CURSOR_SIGNING_KEY_FILE:-/run/secrets/cursor_signing_key}
CACHE_URL: ${CACHE_URL:-redis://redis:6379/0}
+3
View File
@@ -0,0 +1,3 @@
node_modules
dist
coverage
+17
View File
@@ -0,0 +1,17 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="theme-color" content="#11110f" />
<meta
name="description"
content="Минималистичный веб-клиент распределённого MTUCI Messenger"
/>
<title>MTUCI Messenger</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+1688
View File
File diff suppressed because it is too large Load Diff
+27
View File
@@ -0,0 +1,27 @@
{
"name": "mtusi-messenger-web",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "vite --host 0.0.0.0",
"build": "tsc -b && vite build",
"test": "vitest run",
"test:watch": "vitest"
},
"dependencies": {
"@tanstack/react-query": "^5.104.5",
"lucide-react": "^1.61.0",
"react": "^19.3.1",
"react-dom": "^19.3.1",
"react-router-dom": "^7.18.4"
},
"devDependencies": {
"@types/react": "^19.3.0",
"@types/react-dom": "^19.3.0",
"@vitejs/plugin-react": "^6.1.2",
"typescript": "^7.0.2",
"vite": "^8.3.5",
"vitest": "^5.0.5"
}
}
+158
View File
@@ -0,0 +1,158 @@
import type {
ApiErrorBody,
Chat,
CreateChatInput,
LoginInput,
Message,
Page,
RegisterInput,
Session,
User,
} from "./types";
const publicApi = "/api/v1";
const browserApi = "/web-api/v1";
export class ApiError extends Error {
readonly status: number;
readonly code?: string;
readonly requestId?: string;
constructor(status: number, body: ApiErrorBody) {
super(body.error?.message || `HTTP ${status}`);
this.name = "ApiError";
this.status = status;
this.code = body.error?.code;
this.requestId = body.error?.request_id;
}
}
type RequestOptions = Omit<RequestInit, "body"> & {
body?: unknown;
};
async function request<T>(path: string, options: RequestOptions = {}): Promise<T> {
const headers = new Headers(options.headers);
if (options.body !== undefined) {
headers.set("Content-Type", "application/json");
}
const response = await fetch(path, {
...options,
headers,
credentials: "same-origin",
body: options.body === undefined ? undefined : JSON.stringify(options.body),
});
if (!response.ok) {
let body: ApiErrorBody = {};
try {
body = (await response.json()) as ApiErrorBody;
} catch {
// Preserve a useful HTTP-level error when a proxy returned non-JSON.
}
throw new ApiError(response.status, body);
}
if (response.status === 204) {
return undefined as T;
}
return (await response.json()) as T;
}
function encodeBasic({ username, password }: LoginInput): string {
const bytes = new TextEncoder().encode(`${username}:${password}`);
let binary = "";
for (const byte of bytes) {
binary += String.fromCharCode(byte);
}
return btoa(binary);
}
async function collectPages<T>(path: string): Promise<T[]> {
const items: T[] = [];
let cursor: string | null = null;
for (let pageIndex = 0; pageIndex < 100; pageIndex += 1) {
const search = new URLSearchParams({ limit: "100" });
if (cursor) {
search.set("cursor", cursor);
}
const page = await request<Page<T>>(`${path}?${search.toString()}`);
items.push(...page.items);
cursor = page.next_cursor;
if (!cursor) {
return items;
}
}
throw new Error("pagination safety limit exceeded");
}
export const api = {
register(input: RegisterInput): Promise<User> {
return request<User>(`${publicApi}/users`, {
method: "POST",
body: {
username: input.username,
display_name: input.displayName,
password: input.password,
},
});
},
login(input: LoginInput): Promise<Session> {
return request<Session>(`${publicApi}/auth/sessions`, {
method: "POST",
headers: {
Authorization: `Basic ${encodeBasic(input)}`,
},
});
},
logout(): Promise<void> {
return request<void>(`${browserApi}/auth/sessions/current`, {
method: "DELETE",
});
},
me(): Promise<User> {
return request<User>(`${browserApi}/users/me`);
},
chats(): Promise<Chat[]> {
return collectPages<Chat>(`${browserApi}/chats`);
},
chat(chatID: string): Promise<Chat> {
return request<Chat>(`${browserApi}/chats/${encodeURIComponent(chatID)}`);
},
createChat(input: CreateChatInput): Promise<Chat> {
return request<Chat>(`${browserApi}/chats`, {
method: "POST",
body: {
title: input.title,
member_ids: input.memberIds,
},
});
},
messages(chatID: string): Promise<Message[]> {
return collectPages<Message>(
`${browserApi}/chats/${encodeURIComponent(chatID)}/messages`,
);
},
sendMessage(chatID: string, text: string, idempotencyKey: string): Promise<Message> {
return request<Message>(
`${browserApi}/chats/${encodeURIComponent(chatID)}/messages`,
{
method: "POST",
headers: {
"Idempotency-Key": idempotencyKey,
},
body: { text },
},
);
},
};
+57
View File
@@ -0,0 +1,57 @@
export type User = {
id: string;
username: string;
display_name: string;
created_at: string;
};
export type Session = {
token: string;
token_type: "Bearer";
expires_at: string;
user: User;
};
export type Chat = {
id: string;
title: string;
member_ids: string[];
created_at: string;
};
export type Message = {
id: string;
chat_id: string;
sender_id: string;
text: string;
created_at: string;
};
export type Page<T> = {
items: T[];
next_cursor: string | null;
};
export type ApiErrorBody = {
error?: {
code?: string;
message?: string;
request_id?: string;
};
};
export type RegisterInput = {
username: string;
displayName: string;
password: string;
};
export type CreateChatInput = {
title: string;
memberIds: string[];
};
export type LoginInput = {
username: string;
password: string;
};
+51
View File
@@ -0,0 +1,51 @@
import { Navigate, Outlet, Route, Routes, useLocation } from "react-router-dom";
import { useAuth } from "../auth/AuthProvider";
import { LoadingScreen } from "../components/LoadingScreen";
import { AuthPage } from "../pages/AuthPage";
import { MessengerPage } from "../pages/MessengerPage";
function ProtectedRoute() {
const { user, isLoading } = useAuth();
const location = useLocation();
if (isLoading) {
return <LoadingScreen />;
}
if (!user) {
return <Navigate to="/login" replace state={{ from: location.pathname }} />;
}
return <Outlet />;
}
function PublicOnlyRoute() {
const { user, isLoading } = useAuth();
if (isLoading) {
return <LoadingScreen />;
}
if (user) {
return <Navigate to="/app" replace />;
}
return <Outlet />;
}
export function App() {
return (
<Routes>
<Route element={<PublicOnlyRoute />}>
<Route path="/login" element={<AuthPage initialMode="login" />} />
<Route path="/register" element={<AuthPage initialMode="register" />} />
</Route>
<Route element={<ProtectedRoute />}>
<Route path="/app" element={<MessengerPage />} />
<Route path="/app/chats/:chatId" element={<MessengerPage />} />
<Route path="/app/profile" element={<MessengerPage profileOpen />} />
</Route>
<Route path="/" element={<Navigate to="/app" replace />} />
<Route path="*" element={<Navigate to="/app" replace />} />
</Routes>
);
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 540 KiB

+90
View File
@@ -0,0 +1,90 @@
import { useQuery, useQueryClient } from "@tanstack/react-query";
import {
createContext,
useCallback,
useContext,
type PropsWithChildren,
} from "react";
import { api, ApiError } from "../api/client";
import type { LoginInput, RegisterInput, User } from "../api/types";
type AuthContextValue = {
user: User | null;
isLoading: boolean;
login: (input: LoginInput) => Promise<void>;
register: (input: RegisterInput) => Promise<void>;
logout: () => Promise<void>;
};
const AuthContext = createContext<AuthContextValue | null>(null);
const meQueryKey = ["current-user"] as const;
async function loadCurrentUser(): Promise<User | null> {
try {
return await api.me();
} catch (error) {
if (error instanceof ApiError && error.status === 401) {
return null;
}
throw error;
}
}
export function AuthProvider({ children }: PropsWithChildren) {
const queryClient = useQueryClient();
const meQuery = useQuery({
queryKey: meQueryKey,
queryFn: loadCurrentUser,
retry: false,
staleTime: 30_000,
});
const login = useCallback(
async (input: LoginInput) => {
const session = await api.login(input);
queryClient.setQueryData(meQueryKey, session.user);
},
[queryClient],
);
const register = useCallback(
async (input: RegisterInput) => {
await api.register(input);
const session = await api.login({
username: input.username,
password: input.password,
});
queryClient.setQueryData(meQueryKey, session.user);
},
[queryClient],
);
const logout = useCallback(async () => {
await api.logout();
queryClient.setQueryData(meQueryKey, null);
queryClient.removeQueries({ queryKey: ["chats"] });
}, [queryClient]);
return (
<AuthContext.Provider
value={{
user: meQuery.data ?? null,
isLoading: meQuery.isLoading,
login,
register,
logout,
}}
>
{children}
</AuthContext.Provider>
);
}
export function useAuth(): AuthContextValue {
const context = useContext(AuthContext);
if (!context) {
throw new Error("useAuth must be used within AuthProvider");
}
return context;
}
+26
View File
@@ -0,0 +1,26 @@
import { initials } from "../lib/format";
type AvatarProps = {
label: string;
seed?: string;
size?: "small" | "medium" | "large";
};
function tone(seed: string): number {
let hash = 0;
for (const character of seed) {
hash = (hash * 31 + character.codePointAt(0)!) >>> 0;
}
return hash % 5;
}
export function Avatar({ label, seed = label, size = "medium" }: AvatarProps) {
return (
<span
aria-hidden="true"
className={`avatar avatar--${size} avatar--tone-${tone(seed)}`}
>
{initials(label)}
</span>
);
}
+121
View File
@@ -0,0 +1,121 @@
import { MessageSquarePlus, Search, UsersRound, X } from "lucide-react";
import { useMemo, useState } from "react";
import { useNavigate } from "react-router-dom";
import type { Chat, User } from "../api/types";
import { formatMemberCount } from "../lib/format";
import { Avatar } from "./Avatar";
type ChatListProps = {
chats: Chat[];
currentUser: User;
error: boolean;
isLoading: boolean;
selectedChatID?: string;
onCreateChat: () => void;
};
export function ChatList({
chats,
currentUser,
error,
isLoading,
selectedChatID,
onCreateChat,
}: ChatListProps) {
const navigate = useNavigate();
const [search, setSearch] = useState("");
const filteredChats = useMemo(() => {
const normalized = search.trim().toLocaleLowerCase("ru");
if (!normalized) {
return chats;
}
return chats.filter((chat) =>
chat.title.toLocaleLowerCase("ru").includes(normalized),
);
}, [chats, search]);
return (
<aside className="chat-sidebar">
<header className="chat-sidebar__header">
<div>
<p className="eyebrow">Сообщения</p>
<h1>Чаты</h1>
</div>
<button
aria-label="Создать чат"
className="soft-icon-button"
onClick={onCreateChat}
type="button"
>
<MessageSquarePlus aria-hidden="true" />
</button>
</header>
<div className="search-box">
<Search aria-hidden="true" />
<input
aria-label="Поиск чатов"
onChange={(event) => setSearch(event.target.value)}
placeholder="Поиск"
value={search}
/>
{search && (
<button aria-label="Очистить поиск" onClick={() => setSearch("")} type="button">
<X aria-hidden="true" />
</button>
)}
</div>
<div className="chat-list" aria-live="polite">
{isLoading && (
<div className="sidebar-state">
<span className="loading-line" />
<p>Загружаем чаты…</p>
</div>
)}
{error && (
<div className="sidebar-state sidebar-state--error">
<p>Не удалось загрузить список чатов.</p>
</div>
)}
{!isLoading && !error && filteredChats.length === 0 && (
<div className="sidebar-state">
<UsersRound aria-hidden="true" />
<p>{search ? "Ничего не найдено" : "У вас пока нет чатов"}</p>
{!search && (
<button className="text-button" onClick={onCreateChat} type="button">
Создать первый
</button>
)}
</div>
)}
{filteredChats.map((chat) => (
<button
className={`chat-row ${selectedChatID === chat.id ? "chat-row--active" : ""}`}
key={chat.id}
onClick={() => navigate(`/app/chats/${chat.id}`)}
type="button"
>
<Avatar label={chat.title} seed={chat.id} />
<span className="chat-row__body">
<strong>{chat.title}</strong>
<small>{formatMemberCount(chat.member_ids.length)}</small>
</span>
{chat.member_ids.includes(currentUser.id) && (
<span className="chat-row__status" title="Вы участник">
•
</span>
)}
</button>
))}
</div>
<footer className="sidebar-footer">
<span className="status-dot" />
API подключён
</footer>
</aside>
);
}
+236
View File
@@ -0,0 +1,236 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
ArrowLeft,
CheckCheck,
RefreshCcw,
Send,
ShieldCheck,
UsersRound,
} from "lucide-react";
import {
useEffect,
useMemo,
useRef,
useState,
type FormEvent,
type KeyboardEvent,
} from "react";
import { api } from "../api/client";
import type { Chat, Message, User } from "../api/types";
import {
dayKey,
formatDay,
formatMemberCount,
formatMessageTime,
shortID,
} from "../lib/format";
import { createIdempotencyKey } from "../lib/idempotency";
import { Avatar } from "./Avatar";
type ChatViewProps = {
chat: Chat;
currentUser: User;
onBack: () => void;
};
type SendEnvelope = {
text: string;
idempotencyKey: string;
};
export function ChatView({ chat, currentUser, onBack }: ChatViewProps) {
const queryClient = useQueryClient();
const messagesEnd = useRef<HTMLDivElement>(null);
const [draft, setDraft] = useState("");
const [failedEnvelope, setFailedEnvelope] = useState<SendEnvelope | null>(null);
const messagesQuery = useQuery({
queryKey: ["messages", chat.id],
queryFn: () => api.messages(chat.id),
refetchInterval: 3_000,
staleTime: 1_000,
});
const messages = messagesQuery.data ?? [];
useEffect(() => {
messagesEnd.current?.scrollIntoView({
behavior: messages.length > 1 ? "smooth" : "auto",
block: "end",
});
}, [chat.id, messages.length]);
const mutation = useMutation({
mutationFn: (envelope: SendEnvelope) =>
api.sendMessage(chat.id, envelope.text, envelope.idempotencyKey),
onSuccess: (message) => {
setFailedEnvelope(null);
queryClient.setQueryData<Message[]>(
["messages", chat.id],
(current = []) => {
if (current.some((item) => item.id === message.id)) {
return current;
}
return [...current, message];
},
);
},
onError: (_error, envelope) => {
setFailedEnvelope(envelope);
},
});
const groups = useMemo(() => {
const result: Array<{ key: string; label: string; messages: Message[] }> = [];
for (const message of messages) {
const key = dayKey(message.created_at);
const current = result.at(-1);
if (!current || current.key !== key) {
result.push({
key,
label: formatDay(message.created_at),
messages: [message],
});
} else {
current.messages.push(message);
}
}
return result;
}, [messages]);
function send(envelope: SendEnvelope) {
if (!mutation.isPending) {
mutation.mutate(envelope);
}
}
function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
const text = draft.trim();
if (!text || Array.from(text).length > 4_000) {
return;
}
const envelope = { text, idempotencyKey: createIdempotencyKey() };
setDraft("");
setFailedEnvelope(null);
send(envelope);
}
function handleKeyDown(event: KeyboardEvent<HTMLTextAreaElement>) {
if (event.key === "Enter" && !event.shiftKey) {
event.preventDefault();
event.currentTarget.form?.requestSubmit();
}
}
return (
<section className="conversation">
<header className="conversation-header">
<button
aria-label="Назад к списку чатов"
className="mobile-back-button"
onClick={onBack}
type="button"
>
<ArrowLeft aria-hidden="true" />
</button>
<Avatar label={chat.title} seed={chat.id} size="small" />
<div className="conversation-header__title">
<strong>{chat.title}</strong>
<span>{formatMemberCount(chat.member_ids.length)}</span>
</div>
<div className="conversation-header__security">
<ShieldCheck aria-hidden="true" />
<span>сессия защищена</span>
</div>
</header>
<div className="message-canvas">
<div className="message-canvas__shade" />
<div className="message-stream" aria-live="polite">
{messagesQuery.isLoading && (
<div className="floating-state">
<span className="loading-line" />
Загружаем историю
</div>
)}
{messagesQuery.isError && (
<div className="floating-state floating-state--error">
<p>История временно недоступна</p>
<button onClick={() => messagesQuery.refetch()} type="button">
<RefreshCcw aria-hidden="true" /> Повторить
</button>
</div>
)}
{!messagesQuery.isLoading && !messagesQuery.isError && messages.length === 0 && (
<div className="floating-state">
<UsersRound aria-hidden="true" />
<p>Сообщений пока нет. Начните разговор.</p>
</div>
)}
{groups.map((group) => (
<div className="message-day" key={group.key}>
<div className="date-divider"><span>{group.label}</span></div>
{group.messages.map((message) => {
const own = message.sender_id === currentUser.id;
return (
<article
className={`message-bubble ${own ? "message-bubble--own" : ""}`}
key={message.id}
>
<span className="message-bubble__sender">
{own ? "Вы" : shortID(message.sender_id)}
</span>
<p>{message.text}</p>
<span className="message-bubble__meta">
{formatMessageTime(message.created_at)}
{own && <CheckCheck aria-label="Доставлено серверу" />}
</span>
</article>
);
})}
</div>
))}
<div ref={messagesEnd} />
</div>
</div>
<footer className="composer">
{failedEnvelope && (
<div className="send-error" role="alert">
<span>Отправка не подтверждена.</span>
<button onClick={() => send(failedEnvelope)} type="button">
Повторить с тем же ключом
</button>
</div>
)}
<form onSubmit={submit}>
<textarea
aria-label="Текст сообщения"
maxLength={4_000}
onChange={(event) => setDraft(event.target.value)}
onKeyDown={handleKeyDown}
placeholder="Сообщение…"
rows={1}
value={draft}
/>
<span className="composer__counter">
{draft.length > 3_600 ? `${Array.from(draft).length}/4000` : ""}
</span>
<button
aria-label="Отправить"
className="send-button"
disabled={!draft.trim() || mutation.isPending}
type="submit"
>
<Send aria-hidden="true" />
</button>
</form>
</footer>
</section>
);
}
@@ -0,0 +1,148 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { Plus, UserRoundPlus, X } from "lucide-react";
import { useEffect, useState, type FormEvent } from "react";
import { useNavigate } from "react-router-dom";
import { api, ApiError } from "../api/client";
import type { Chat, User } from "../api/types";
import { shortID } from "../lib/format";
type CreateChatDialogProps = {
currentUser: User;
onClose: () => void;
};
const uuidPattern =
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
export function CreateChatDialog({
currentUser,
onClose,
}: CreateChatDialogProps) {
const navigate = useNavigate();
const queryClient = useQueryClient();
const [title, setTitle] = useState("");
const [memberInput, setMemberInput] = useState("");
const [validationError, setValidationError] = useState("");
useEffect(() => {
function closeOnEscape(event: KeyboardEvent) {
if (event.key === "Escape") {
onClose();
}
}
window.addEventListener("keydown", closeOnEscape);
return () => window.removeEventListener("keydown", closeOnEscape);
}, [onClose]);
const mutation = useMutation({
mutationFn: api.createChat,
onSuccess: (chat) => {
queryClient.setQueryData<Chat[]>(["chats"], (current = []) => [
...current,
chat,
]);
onClose();
navigate(`/app/chats/${chat.id}`);
},
});
function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
setValidationError("");
const enteredIDs = memberInput
.split(/[\s,;]+/)
.map((value) => value.trim())
.filter(Boolean);
const memberIds = Array.from(new Set([currentUser.id, ...enteredIDs]));
if (!title.trim() || Array.from(title.trim()).length > 100) {
setValidationError("Название должно содержать от 1 до 100 символов");
return;
}
const invalidID = enteredIDs.find((id) => !uuidPattern.test(id));
if (invalidID) {
setValidationError(`Некорректный UUID: ${invalidID}`);
return;
}
mutation.mutate({ title: title.trim(), memberIds });
}
const serverError =
mutation.error instanceof ApiError
? mutation.error.message
: mutation.error
? "Не удалось создать чат"
: "";
return (
<div className="dialog-backdrop" onMouseDown={onClose}>
<section
aria-labelledby="create-chat-title"
aria-modal="true"
className="dialog-card"
onMouseDown={(event) => event.stopPropagation()}
role="dialog"
>
<header className="dialog-card__header">
<div>
<p className="eyebrow">Новый разговор</p>
<h2 id="create-chat-title">Создать чат</h2>
</div>
<button
aria-label="Закрыть"
className="soft-icon-button"
onClick={onClose}
type="button"
>
<X aria-hidden="true" />
</button>
</header>
<form className="dialog-form" onSubmit={submit}>
<label>
<span>Название</span>
<div className="input-shell">
<Plus aria-hidden="true" />
<input
autoFocus
maxLength={100}
onChange={(event) => setTitle(event.target.value)}
placeholder="Например, Команда проекта"
required
value={title}
/>
</div>
</label>
<label>
<span>UUID участников</span>
<div className="textarea-shell">
<UserRoundPlus aria-hidden="true" />
<textarea
onChange={(event) => setMemberInput(event.target.value)}
placeholder="Вставьте UUID через пробел, запятую или с новой строки"
rows={4}
value={memberInput}
/>
</div>
<small>
Ваш ID добавлен автоматически: <code>{shortID(currentUser.id)}</code>
</small>
</label>
{(validationError || serverError) && (
<div className="form-error" role="alert">
{validationError || serverError}
</div>
)}
<button className="primary-button" disabled={mutation.isPending} type="submit">
{mutation.isPending ? "Создаём…" : "Создать чат"}
</button>
</form>
</section>
</div>
);
}
+29
View File
@@ -0,0 +1,29 @@
import { MessageSquarePlus } from "lucide-react";
type EmptyChatProps = {
hasChats: boolean;
onCreateChat: () => void;
};
export function EmptyChat({ hasChats, onCreateChat }: EmptyChatProps) {
return (
<section className="conversation conversation--empty">
<div className="empty-chat-card">
<span className="empty-chat-card__line" />
<p className="eyebrow">MTUCI Messenger</p>
<h2>{hasChats ? "Выберите чат" : "Начните разговор"}</h2>
<p>
{hasChats
? "История и новые сообщения появятся здесь."
: "Создайте первый чат и пригласите участников по UUID."}
</p>
{!hasChats && (
<button className="primary-button" onClick={onCreateChat} type="button">
<MessageSquarePlus aria-hidden="true" />
Создать чат
</button>
)}
</div>
</section>
);
}
+11
View File
@@ -0,0 +1,11 @@
export function LoadingScreen() {
return (
<main className="loading-screen" aria-live="polite">
<div className="brand-mark brand-mark--large" aria-hidden="true">
M
</div>
<p>Подключаемся к Messenger</p>
<span className="loading-line" />
</main>
);
}
@@ -0,0 +1,42 @@
import { MessagesSquare, UserRound } from "lucide-react";
import { Link } from "react-router-dom";
import type { User } from "../api/types";
import { Avatar } from "./Avatar";
type NavigationRailProps = {
user: User;
profileOpen: boolean;
};
export function NavigationRail({ user, profileOpen }: NavigationRailProps) {
return (
<nav className="navigation-rail" aria-label="Основная навигация">
<Link className="rail-brand" to="/app" aria-label="MTUCI Messenger">
M
</Link>
<div className="rail-actions">
<Link
className={`rail-action ${profileOpen ? "" : "rail-action--active"}`}
to="/app"
>
<MessagesSquare aria-hidden="true" />
<span>Чаты</span>
</Link>
<Link
className={`rail-action ${profileOpen ? "rail-action--active" : ""}`}
to="/app/profile"
>
<UserRound aria-hidden="true" />
<span>Профиль</span>
</Link>
</div>
<Link className="rail-profile" to="/app/profile" aria-label="Открыть профиль">
<Avatar label={user.display_name} seed={user.id} size="small" />
<span className="presence-dot" />
</Link>
</nav>
);
}
+123
View File
@@ -0,0 +1,123 @@
import {
CalendarDays,
Check,
Copy,
LogOut,
ShieldCheck,
UserRound,
X,
} from "lucide-react";
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import type { User } from "../api/types";
import { useAuth } from "../auth/AuthProvider";
import { Avatar } from "./Avatar";
type ProfileDrawerProps = {
user: User;
};
const createdAtFormatter = new Intl.DateTimeFormat("ru-RU", {
day: "numeric",
month: "long",
year: "numeric",
});
export function ProfileDrawer({ user }: ProfileDrawerProps) {
const { logout } = useAuth();
const navigate = useNavigate();
const [copied, setCopied] = useState(false);
const [error, setError] = useState("");
const [isLoggingOut, setIsLoggingOut] = useState(false);
async function copyID() {
await navigator.clipboard.writeText(user.id);
setCopied(true);
window.setTimeout(() => setCopied(false), 1800);
}
async function submitLogout() {
setError("");
setIsLoggingOut(true);
try {
await logout();
navigate("/login", { replace: true });
} catch {
setError("Не удалось завершить сессию. Попробуйте ещё раз.");
setIsLoggingOut(false);
}
}
return (
<>
<button
aria-label="Закрыть профиль"
className="drawer-backdrop"
onClick={() => navigate("/app")}
type="button"
/>
<aside className="profile-drawer" aria-label="Профиль пользователя">
<header className="profile-drawer__header">
<p className="eyebrow">Ваш аккаунт</p>
<button
aria-label="Закрыть"
className="soft-icon-button"
onClick={() => navigate("/app")}
type="button"
>
<X aria-hidden="true" />
</button>
</header>
<div className="profile-identity">
<Avatar label={user.display_name} seed={user.id} size="large" />
<h2>{user.display_name}</h2>
<p>@{user.username}</p>
<span className="profile-badge">
<ShieldCheck aria-hidden="true" />
серверная сессия
</span>
</div>
<dl className="profile-details">
<div>
<dt><UserRound aria-hidden="true" /> ID аккаунта</dt>
<dd>
<code>{user.id}</code>
<button
aria-label="Скопировать ID"
className="copy-button"
onClick={copyID}
type="button"
>
{copied ? <Check /> : <Copy />}
</button>
</dd>
</div>
<div>
<dt><CalendarDays aria-hidden="true" /> Дата регистрации</dt>
<dd>{createdAtFormatter.format(new Date(user.created_at))}</dd>
</div>
</dl>
<div className="profile-roadmap">
<strong>Следующие версии</strong>
<p>Аватар, редактирование имени и смена пароля появятся после API-контрактов.</p>
</div>
{error && <div className="form-error" role="alert">{error}</div>}
<button
className="logout-button"
disabled={isLoggingOut}
onClick={submitLogout}
type="button"
>
<LogOut aria-hidden="true" />
{isLoggingOut ? "Завершаем…" : "Выйти из аккаунта"}
</button>
</aside>
</>
);
}
+58
View File
@@ -0,0 +1,58 @@
const timeFormatter = new Intl.DateTimeFormat("ru-RU", {
hour: "2-digit",
minute: "2-digit",
});
const dayFormatter = new Intl.DateTimeFormat("ru-RU", {
day: "numeric",
month: "long",
});
const fullDateFormatter = new Intl.DateTimeFormat("ru-RU", {
day: "numeric",
month: "long",
year: "numeric",
});
export function formatMessageTime(value: string): string {
return timeFormatter.format(new Date(value));
}
export function formatDay(value: string): string {
const date = new Date(value);
const now = new Date();
const sameYear = date.getFullYear() === now.getFullYear();
return (sameYear ? dayFormatter : fullDateFormatter).format(date);
}
export function dayKey(value: string): string {
const date = new Date(value);
return [date.getFullYear(), date.getMonth(), date.getDate()].join("-");
}
export function formatMemberCount(count: number): string {
const mod10 = count % 10;
const mod100 = count % 100;
if (mod10 === 1 && mod100 !== 11) {
return `${count} участник`;
}
if (mod10 >= 2 && mod10 <= 4 && (mod100 < 12 || mod100 > 14)) {
return `${count} участника`;
}
return `${count} участников`;
}
export function shortID(id: string): string {
return id.length > 12 ? `${id.slice(0, 8)}…` : id;
}
export function initials(value: string): string {
const parts = value.trim().split(/\s+/).filter(Boolean);
if (parts.length === 0) {
return "?";
}
return parts
.slice(0, 2)
.map((part) => Array.from(part)[0]?.toUpperCase() ?? "")
.join("");
}
+19
View File
@@ -0,0 +1,19 @@
import { describe, expect, it, vi } from "vitest";
import { createIdempotencyKey } from "./idempotency";
describe("createIdempotencyKey", () => {
it("creates an API-compatible unique key", () => {
vi.stubGlobal("crypto", {
randomUUID: () => "12345678-1234-1234-1234-123456789abc",
});
const key = createIdempotencyKey();
expect(key).toMatch(/^[A-Za-z0-9._:-]{1,128}$/);
expect(key).toContain("12345678123412341234123456789abc");
expect(key.length).toBeLessThanOrEqual(128);
vi.unstubAllGlobals();
});
});
+4
View File
@@ -0,0 +1,4 @@
export function createIdempotencyKey(): string {
const random = crypto.randomUUID().replaceAll("-", "");
return `web-${Date.now().toString(36)}-${random}`;
}
+32
View File
@@ -0,0 +1,32 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { BrowserRouter } from "react-router-dom";
import { App } from "./app/App";
import { AuthProvider } from "./auth/AuthProvider";
import "./styles.css";
const queryClient = new QueryClient({
defaultOptions: {
queries: {
retry: 1,
refetchOnWindowFocus: true,
},
mutations: {
retry: false,
},
},
});
createRoot(document.getElementById("root")!).render(
<StrictMode>
<QueryClientProvider client={queryClient}>
<BrowserRouter>
<AuthProvider>
<App />
</AuthProvider>
</BrowserRouter>
</QueryClientProvider>
</StrictMode>,
);
+190
View File
@@ -0,0 +1,190 @@
import {
ArrowRight,
Eye,
EyeOff,
LockKeyhole,
MessageCircleMore,
UserRound,
} from "lucide-react";
import { useState, type FormEvent } from "react";
import { Link, useNavigate } from "react-router-dom";
import { ApiError } from "../api/client";
import { useAuth } from "../auth/AuthProvider";
type AuthMode = "login" | "register";
type AuthPageProps = {
initialMode: AuthMode;
};
function errorMessage(error: unknown): string {
if (error instanceof ApiError) {
if (error.status === 401) {
return "Неверный логин или пароль";
}
if (error.status === 409) {
return "Такой username уже занят";
}
return error.message;
}
return "Не удалось связаться с сервером. Попробуйте ещё раз.";
}
export function AuthPage({ initialMode }: AuthPageProps) {
const { login, register } = useAuth();
const navigate = useNavigate();
const [username, setUsername] = useState("");
const [displayName, setDisplayName] = useState("");
const [password, setPassword] = useState("");
const [showPassword, setShowPassword] = useState(false);
const [error, setError] = useState("");
const [isSubmitting, setIsSubmitting] = useState(false);
const isRegister = initialMode === "register";
async function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
setError("");
if (!/^[a-z0-9_]{3,32}$/.test(username)) {
setError("Username: 3–32 символа, только a–z, цифры и _");
return;
}
if (isRegister && displayName.trim().length === 0) {
setError("Укажите отображаемое имя");
return;
}
if (password.length < 12 || Array.from(password).length > 128) {
setError("Пароль должен содержать от 12 до 128 символов");
return;
}
setIsSubmitting(true);
try {
if (isRegister) {
await register({ username, displayName: displayName.trim(), password });
} else {
await login({ username, password });
}
navigate("/app", { replace: true });
} catch (submitError) {
setError(errorMessage(submitError));
} finally {
setIsSubmitting(false);
}
}
return (
<main className="auth-page">
<section className="auth-story" aria-label="О приложении">
<div className="auth-brand">
<div className="brand-mark" aria-hidden="true">
M
</div>
<span>MTUCI Messenger</span>
</div>
<div className="auth-copy">
<p className="eyebrow">Распределённый мессенджер</p>
<h1>Разговоры, которые остаются с вами.</h1>
<p>
Минималистичный клиент поверх отказоустойчивого Go API. Одна сессия,
несколько реплик, никаких лишних отвлечений.
</p>
<div className="auth-status">
<span className="status-dot" />
защищённая серверная сессия
</div>
</div>
</section>
<section className="auth-panel">
<div className="auth-card">
<MessageCircleMore className="auth-card__icon" aria-hidden="true" />
<p className="eyebrow">{isRegister ? "Новый аккаунт" : "С возвращением"}</p>
<h2>{isRegister ? "Создать профиль" : "Войти в Messenger"}</h2>
<p className="auth-card__lead">
{isRegister
? "Данные профиля можно будет расширить в следующих версиях."
: "Продолжите общение с того места, где остановились."}
</p>
<form className="auth-form" onSubmit={submit}>
{isRegister && (
<label>
<span>Отображаемое имя</span>
<div className="input-shell">
<UserRound aria-hidden="true" />
<input
autoComplete="name"
maxLength={100}
onChange={(event) => setDisplayName(event.target.value)}
placeholder="Как к вам обращаться"
required
value={displayName}
/>
</div>
</label>
)}
<label>
<span>Username</span>
<div className="input-shell">
<UserRound aria-hidden="true" />
<input
autoCapitalize="none"
autoComplete="username"
maxLength={32}
onChange={(event) => setUsername(event.target.value.toLowerCase())}
placeholder="username"
required
value={username}
/>
</div>
</label>
<label>
<span>Пароль</span>
<div className="input-shell">
<LockKeyhole aria-hidden="true" />
<input
autoComplete={isRegister ? "new-password" : "current-password"}
maxLength={128}
minLength={12}
onChange={(event) => setPassword(event.target.value)}
placeholder="Минимум 12 символов"
required
type={showPassword ? "text" : "password"}
value={password}
/>
<button
aria-label={showPassword ? "Скрыть пароль" : "Показать пароль"}
className="icon-button"
onClick={() => setShowPassword((value) => !value)}
type="button"
>
{showPassword ? <EyeOff /> : <Eye />}
</button>
</div>
</label>
{error && <div className="form-error" role="alert">{error}</div>}
<button className="primary-button" disabled={isSubmitting} type="submit">
<span>{isSubmitting ? "Подождите…" : isRegister ? "Создать аккаунт" : "Войти"}</span>
{!isSubmitting && <ArrowRight aria-hidden="true" />}
</button>
</form>
<p className="auth-switch">
{isRegister ? "Уже есть аккаунт?" : "Впервые здесь?"}{" "}
<Link to={isRegister ? "/login" : "/register"}>
{isRegister ? "Войти" : "Создать профиль"}
</Link>
</p>
</div>
</section>
</main>
);
}
+81
View File
@@ -0,0 +1,81 @@
import { useQuery } from "@tanstack/react-query";
import { useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { api } from "../api/client";
import { useAuth } from "../auth/AuthProvider";
import { ChatList } from "../components/ChatList";
import { ChatView } from "../components/ChatView";
import { CreateChatDialog } from "../components/CreateChatDialog";
import { EmptyChat } from "../components/EmptyChat";
import { NavigationRail } from "../components/NavigationRail";
import { ProfileDrawer } from "../components/ProfileDrawer";
type MessengerPageProps = {
profileOpen?: boolean;
};
export function MessengerPage({ profileOpen = false }: MessengerPageProps) {
const { user } = useAuth();
const { chatId } = useParams();
const navigate = useNavigate();
const [createChatOpen, setCreateChatOpen] = useState(false);
const chatsQuery = useQuery({
queryKey: ["chats"],
queryFn: api.chats,
refetchInterval: 10_000,
staleTime: 5_000,
});
if (!user) {
return null;
}
const chats = chatsQuery.data ?? [];
const selectedChat = chatId
? chats.find((chat) => chat.id === chatId)
: undefined;
return (
<main
className={[
"messenger-shell",
chatId ? "messenger-shell--chat-open" : "",
profileOpen ? "messenger-shell--drawer-open" : "",
].join(" ")}
>
<NavigationRail profileOpen={profileOpen} user={user} />
<ChatList
chats={chats}
currentUser={user}
error={chatsQuery.isError}
isLoading={chatsQuery.isLoading}
onCreateChat={() => setCreateChatOpen(true)}
selectedChatID={chatId}
/>
{selectedChat ? (
<ChatView
chat={selectedChat}
currentUser={user}
onBack={() => navigate("/app")}
/>
) : (
<EmptyChat
hasChats={chats.length > 0}
onCreateChat={() => setCreateChatOpen(true)}
/>
)}
{profileOpen && <ProfileDrawer user={user} />}
{createChatOpen && (
<CreateChatDialog
currentUser={user}
onClose={() => setCreateChatOpen(false)}
/>
)}
</main>
);
}
File diff suppressed because it is too large Load Diff
+1
View File
@@ -0,0 +1 @@
/// <reference types="vite/client" />
+21
View File
@@ -0,0 +1,21 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2022",
"useDefineForClassFields": true,
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"allowJs": false,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "ESNext",
"moduleResolution": "Bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": ["src"]
}
+7
View File
@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}
+15
View File
@@ -0,0 +1,15 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "ES2023",
"lib": ["ES2023"],
"module": "ESNext",
"skipLibCheck": true,
"moduleResolution": "Bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true
},
"include": ["vite.config.ts"]
}
+23
View File
@@ -0,0 +1,23 @@
import { defineConfig } from "vitest/config";
import react from "@vitejs/plugin-react";
export default defineConfig({
plugins: [react()],
server: {
port: 5173,
strictPort: true,
proxy: {
"/api": "http://localhost:8080",
"/web-api": "http://localhost:8080",
"/health": "http://localhost:8080",
},
},
preview: {
port: 4173,
strictPort: true,
},
test: {
environment: "node",
include: ["src/**/*.test.ts"],
},
});
+15
View File
@@ -0,0 +1,15 @@
FROM node:24-alpine@sha256:44fce696f38ba8c987c4db89954051000bbd05ffd8d8659ba15ed4a8602e937f AS frontend-build
WORKDIR /frontend
COPY frontend/package.json frontend/package-lock.json ./
RUN npm ci
COPY frontend/ ./
RUN npm test && npm run build
FROM nginx:1.30.6-alpine@sha256:970364228b1e4f932abc22d321932816782cca8a20b85a77552a7cfe9acfb3b5
COPY infrastructure/nginx/nginx.conf /etc/nginx/nginx.conf
COPY --from=frontend-build /frontend/dist /usr/share/nginx/html
EXPOSE 8080
+58 -7
View File
@@ -5,8 +5,15 @@ events {
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
resolver 127.0.0.11 valid=1s ipv6=off;
map $cookie_mtusi_session $web_authorization {
default "Bearer $cookie_mtusi_session";
"" "";
}
upstream api_backend {
zone api_backend 64k;
least_conn;
@@ -16,26 +23,70 @@ http {
server {
listen 8080;
server_name _;
root /usr/share/nginx/html;
index index.html;
location / {
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "no-referrer" always;
add_header X-Frame-Options "DENY" always;
add_header Content-Security-Policy "default-src 'self'; img-src 'self' data:; style-src 'self'; script-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'" always;
location /api/ {
proxy_pass http://api_backend;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Connection "";
proxy_set_header Cookie "";
proxy_connect_timeout 1s;
proxy_send_timeout 20s;
proxy_read_timeout 20s;
# Safe methods may transparently move to another healthy peer.
# Nginx deliberately does not retry non-idempotent POST requests:
# the client retries message POSTs with its Idempotency-Key.
proxy_next_upstream error timeout http_502 http_503 http_504;
proxy_next_upstream_tries 2;
}
location /web-api/ {
rewrite ^/web-api/(.*)$ /api/$1 break;
proxy_pass http://api_backend;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Connection "";
proxy_set_header Authorization $web_authorization;
proxy_set_header Cookie "";
proxy_connect_timeout 1s;
proxy_send_timeout 20s;
proxy_read_timeout 20s;
proxy_next_upstream error timeout http_502 http_503 http_504;
proxy_next_upstream_tries 2;
}
location /health/ {
proxy_pass http://api_backend;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Connection "";
proxy_connect_timeout 1s;
proxy_read_timeout 5s;
proxy_next_upstream error timeout http_502 http_503 http_504;
proxy_next_upstream_tries 2;
}
location /assets/ {
try_files $uri =404;
expires 1y;
add_header Cache-Control "public, immutable";
}
location / {
try_files $uri $uri/ /index.html;
}
}
}
+29 -9
View File
@@ -16,9 +16,10 @@ type Config struct {
HTTPPort string
InstanceID string
SessionTTL time.Duration
IdempotencyTTL time.Duration
CursorSigningKey string
SessionTTL time.Duration
IdempotencyTTL time.Duration
SessionCookieSecure bool
CursorSigningKey string
DatabaseURL string
DatabaseMaxConns int32
@@ -60,6 +61,10 @@ func Load() (Config, error) {
return Config{}, err
}
sessionCookieSecure, err := boolFromEnv("SESSION_COOKIE_SECURE", false)
if err != nil {
return Config{}, err
}
databaseURL, err := requiredValueOrFile(
"DATABASE_URL",
"DATABASE_URL_FILE",
@@ -181,12 +186,13 @@ func Load() (Config, error) {
}
return Config{
HTTPHost: envOrDefault("APP_HOST", "0.0.0.0"),
HTTPPort: envOrDefault("APP_PORT", "8080"),
InstanceID: instanceID,
SessionTTL: sessionTTL,
IdempotencyTTL: idempotencyTTL,
CursorSigningKey: cursorSigningKey,
HTTPHost: envOrDefault("APP_HOST", "0.0.0.0"),
HTTPPort: envOrDefault("APP_PORT", "8080"),
InstanceID: instanceID,
SessionTTL: sessionTTL,
IdempotencyTTL: idempotencyTTL,
SessionCookieSecure: sessionCookieSecure,
CursorSigningKey: cursorSigningKey,
DatabaseURL: databaseURL,
DatabaseMaxConns: databaseMaxConns,
@@ -345,6 +351,20 @@ func int32FromEnv(name string, fallback, minimum int32) (int32, error) {
return int32(value), nil
}
func boolFromEnv(name string, fallback bool) (bool, error) {
raw := strings.TrimSpace(os.Getenv(name))
if raw == "" {
return fallback, nil
}
value, err := strconv.ParseBool(raw)
if err != nil {
return false, fmt.Errorf("%s must be true or false: %w", name, err)
}
return value, nil
}
func durationFromEnv(name string, fallback time.Duration) (time.Duration, error) {
raw := strings.TrimSpace(os.Getenv(name))
if raw == "" {
+29
View File
@@ -0,0 +1,29 @@
package config
import "testing"
func TestBoolFromEnv(t *testing.T) {
t.Run("fallback", func(t *testing.T) {
t.Setenv("TEST_BOOL", "")
value, err := boolFromEnv("TEST_BOOL", true)
if err != nil || !value {
t.Fatalf("boolFromEnv() = %v, %v; want true, nil", value, err)
}
})
t.Run("explicit false", func(t *testing.T) {
t.Setenv("TEST_BOOL", "false")
value, err := boolFromEnv("TEST_BOOL", true)
if err != nil || value {
t.Fatalf("boolFromEnv() = %v, %v; want false, nil", value, err)
}
})
t.Run("invalid", func(t *testing.T) {
t.Setenv("TEST_BOOL", "sometimes")
_, err := boolFromEnv("TEST_BOOL", false)
if err == nil {
t.Fatal("boolFromEnv() error = nil, want validation error")
}
})
}
@@ -15,5 +15,6 @@ func (h *Handler) DeleteCurrentSession(w http.ResponseWriter, r *http.Request) {
"service is temporarily unavailable", requestID)
return
}
h.clearSessionCookie(w)
response.WriteJSON(w, http.StatusNoContent, nil, requestID)
}
+10 -3
View File
@@ -30,9 +30,10 @@ type ReadinessChecker interface {
type Option func(*Handler)
type Handler struct {
service *application.Service
readinessChecker ReadinessChecker
readinessTimeout time.Duration
service *application.Service
readinessChecker ReadinessChecker
readinessTimeout time.Duration
sessionCookieSecure bool
}
func NewHandler(
@@ -61,6 +62,12 @@ func WithReadiness(
}
}
func WithSessionCookieSecure(secure bool) Option {
return func(handler *Handler) {
handler.sessionCookieSecure = secure
}
}
func decodeJSON(r *http.Request, destination any) error {
mediaType, parameters, err := mime.ParseMediaType(
r.Header.Get("Content-Type"),
@@ -0,0 +1,39 @@
package handlers
import (
"net/http"
"time"
)
const sessionCookieName = "mtusi_session"
func (h *Handler) setSessionCookie(
w http.ResponseWriter,
token string,
expiresAt time.Time,
) {
maxAge := int(time.Until(expiresAt).Seconds())
if maxAge < 1 {
maxAge = 1
}
h.writeSessionCookie(w, token, expiresAt, maxAge)
}
func (h *Handler) clearSessionCookie(w http.ResponseWriter) {
h.writeSessionCookie(w, "", time.Unix(1, 0).UTC(), -1)
}
func (h *Handler) writeSessionCookie(
w http.ResponseWriter,
value string,
expiresAt time.Time,
maxAge int,
) {
http.SetCookie(w, &http.Cookie{
Name: sessionCookieName, Value: value, Path: "/",
Expires: expiresAt, MaxAge: maxAge,
HttpOnly: true, Secure: h.sessionCookieSecure,
SameSite: http.SameSiteStrictMode,
})
}
@@ -0,0 +1,61 @@
package handlers
import (
"net/http"
"net/http/httptest"
"testing"
"time"
)
func TestSessionCookieIsHardened(t *testing.T) {
handler := &Handler{sessionCookieSecure: true}
recorder := httptest.NewRecorder()
handler.setSessionCookie(
recorder,
"secret-token",
time.Now().Add(time.Hour),
)
cookies := recorder.Result().Cookies()
if len(cookies) != 1 {
t.Fatalf("cookie count = %d, want 1", len(cookies))
}
cookie := cookies[0]
if cookie.Name != sessionCookieName || cookie.Value != "secret-token" {
t.Fatalf("unexpected cookie: %#v", cookie)
}
if cookie.Path != "/" || cookie.Domain != "" {
t.Fatalf("cookie scope = path %q domain %q", cookie.Path, cookie.Domain)
}
if !cookie.HttpOnly || !cookie.Secure {
t.Fatalf("cookie flags: HttpOnly=%v Secure=%v", cookie.HttpOnly, cookie.Secure)
}
if cookie.SameSite != http.SameSiteStrictMode {
t.Fatalf("SameSite = %v, want Strict", cookie.SameSite)
}
if cookie.MaxAge < 1 {
t.Fatalf("MaxAge = %d, want positive", cookie.MaxAge)
}
}
func TestClearSessionCookieExpiresIt(t *testing.T) {
handler := &Handler{}
recorder := httptest.NewRecorder()
handler.clearSessionCookie(recorder)
cookies := recorder.Result().Cookies()
if len(cookies) != 1 {
t.Fatalf("cookie count = %d, want 1", len(cookies))
}
cookie := cookies[0]
if cookie.Value != "" || cookie.MaxAge != -1 {
t.Fatalf("clear cookie = value %q MaxAge %d", cookie.Value, cookie.MaxAge)
}
if !cookie.Expires.Before(time.Now()) {
t.Fatalf("clear cookie expiry %v is not in the past", cookie.Expires)
}
}
@@ -55,6 +55,8 @@ func (h *Handler) CreateSession(
return
}
h.setSessionCookie(w, session.Token, session.ExpiresAt)
response.WriteJSON(
w,
http.StatusCreated,