Этап 6: авторизация и роли

- вход по почте и паролю (argon2id), сессия в httpOnly-cookie, в БД только хеш токена
- «Запомнить устройство» на 90 дней, rate-limit на вход, защита от CSRF заголовком
- роли VIEWER / EDITOR / ADMIN: requireAuth и requireRole на сервере
- без входа: только экран логина и статьи с visibility PUBLIC (и их файлы в /uploads)
- приглашение по одноразовой ссылке с ролью
- избранное и недавние синхронизируются с сервером, при выходе кеш закрытых статей стирается
- экран входа по макету, блок пользователя с выходом

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
deonisii
2026-10-04 12:52:26 +03:00
co-authored by Claude Opus 5.5
parent 27cdca3967
commit 9f08158607
14 changed files with 989 additions and 26 deletions
+61 -3
View File
@@ -1,9 +1,49 @@
import express, { type ErrorRequestHandler } from 'express';
import path from 'node:path';
import cookieParser from 'cookie-parser';
import express, { type ErrorRequestHandler, type RequestHandler } from 'express';
import { ZodError } from 'zod';
import type { HealthResponse } from '@kb/shared';
import { csrfGuard, loadUser } from './auth.js';
import { prisma } from './db.js';
import { env } from './env.js';
import { HttpError } from './http.js';
import { authRouter } from './routes/auth.js';
import { contentRouter } from './routes/content.js';
import { meRouter } from './routes/me.js';
// Кеш «этот файл относится к публичной статье?»: чтобы не ходить в БД за каждой картинкой
const publicFiles = new Map<string, { ok: boolean; at: number }>();
const PUBLIC_TTL = 60_000;
async function isPublicFile(rel: string): Promise<boolean> {
const hit = publicFiles.get(rel);
if (hit && Date.now() - hit.at < PUBLIC_TTL) return hit.ok;
// Превью fig-1.480.webp относится к той же записи, что и fig-1.webp
const assetPath = rel.replace(/\.480\.webp$/, '.webp');
const open = { status: 'PUBLISHED', visibility: 'PUBLIC' } as const;
const [asset, attachment] = await Promise.all([
prisma.asset.findFirst({ where: { path: assetPath, article: open }, select: { id: true } }),
prisma.attachment.findFirst({ where: { path: rel, article: open }, select: { id: true } }),
]);
const ok = !!asset || !!attachment;
if (publicFiles.size > 5000) publicFiles.clear();
publicFiles.set(rel, { ok, at: Date.now() });
return ok;
}
/** Файлы закрытых статей отдаём только вошедшим пользователям. */
const uploadsGuard: RequestHandler = async (req, res, next) => {
if (req.user) return next();
let rel: string;
try {
rel = path.posix.normalize(decodeURIComponent(req.path)).replace(/^\/+/, '');
} catch {
res.status(400).json({ error: 'Некорректный адрес' });
return;
}
if (await isPublicFile(rel)) return next();
res.status(401).json({ error: 'Нужно войти' });
};
export function createApp() {
const app = express();
@@ -12,6 +52,7 @@ export function createApp() {
app.set('trust proxy', 2);
app.disable('x-powered-by');
app.use(express.json({ limit: '2mb' }));
app.use(cookieParser());
// Healthcheck: проверяет и сам процесс, и соединение с БД.
app.get('/api/health', async (_req, res) => {
@@ -20,16 +61,20 @@ export function createApp() {
res.json(body);
});
// Загруженные файлы. Имена картинок не меняются при замене содержимого редко,
// поэтому кешируем на сутки, а дальше браузер перепроверяет по ETag.
app.use(loadUser);
// Загруженные файлы: кешируются на сутки, дальше браузер перепроверяет по ETag.
app.use(
'/uploads',
uploadsGuard,
express.static(env.UPLOADS_DIR, {
index: false,
dotfiles: 'deny',
maxAge: '1d',
setHeaders(res, file) {
res.setHeader('X-Content-Type-Options', 'nosniff');
// private: общие прокси не должны хранить файлы закрытых статей
res.setHeader('Cache-Control', 'private, max-age=86400');
// Исходники (PDF/DOCX) всегда скачиваются, а не открываются в браузере
if (!/\.(webp|png|jpe?g|gif)$/i.test(file)) res.setHeader('Content-Disposition', 'attachment');
},
@@ -39,6 +84,9 @@ export function createApp() {
res.status(404).json({ error: 'Файл не найден' });
});
app.use('/api', csrfGuard);
app.use('/api/auth', authRouter);
app.use('/api/me', meRouter);
app.use('/api', contentRouter);
app.use('/api', (_req, res) => {
@@ -51,6 +99,16 @@ export function createApp() {
res.status(err.status).json({ error: err.message });
return;
}
// Ошибка проверки входных данных (Zod): показываем первое понятное сообщение
if (err instanceof ZodError) {
const first = err.issues[0];
res.status(400).json({ error: first?.message ?? 'Некорректные данные', field: first?.path.join('.') });
return;
}
if (err?.type === 'entity.parse.failed' || err?.type === 'entity.too.large') {
res.status(400).json({ error: 'Некорректный запрос' });
return;
}
console.error(err);
res.status(500).json({ error: 'Внутренняя ошибка сервера' });
};
+106
View File
@@ -0,0 +1,106 @@
// Сессии и проверка прав.
//
// Как это устроено:
// - при входе создаём случайный токен, кладём его в httpOnly-cookie (JavaScript страницы его не видит),
// а в БД сохраняем только SHA-256 от токена;
// - на каждом запросе по cookie находим сессию и пользователя (req.user);
// - requireAuth / requireRole стоят перед обработчиками: права проверяет сервер, а не только интерфейс.
import crypto from 'node:crypto';
import type { NextFunction, Request, RequestHandler, Response } from 'express';
import type { Role, User } from '@prisma/client';
import type { UserDto } from '@kb/shared';
import { prisma } from './db.js';
import { env } from './env.js';
import { HttpError } from './http.js';
export const COOKIE = 'kb_session';
const DAY = 24 * 60 * 60 * 1000;
export const REMEMBER_MS = 90 * DAY; // «Запомнить устройство»
export const SHORT_MS = 1 * DAY; // без галочки: сутки, cookie живёт до закрытия браузера
// Добавляем свои поля в тип запроса Express (так это принято делать в его типах)
declare global {
// eslint-disable-next-line @typescript-eslint/no-namespace
namespace Express {
interface Request {
user?: User;
sessionId?: string;
}
}
}
const sha256 = (s: string) => crypto.createHash('sha256').update(s).digest('hex');
export const toUserDto = (u: User): UserDto => ({ id: u.id, email: u.email, name: u.name, role: u.role });
export async function createSession(res: Response, user: User, remember: boolean, userAgent?: string) {
const token = crypto.randomBytes(32).toString('base64url');
const ttl = remember ? REMEMBER_MS : SHORT_MS;
await prisma.session.create({
data: {
tokenHash: sha256(token),
userId: user.id,
expiresAt: new Date(Date.now() + ttl),
userAgent: userAgent?.slice(0, 300),
},
});
res.cookie(COOKIE, token, {
httpOnly: true,
secure: env.COOKIE_SECURE,
sameSite: 'lax',
path: '/',
// Без maxAge cookie сессионная: пропадает при закрытии браузера
...(remember ? { maxAge: ttl } : {}),
});
}
export async function destroySession(req: Request, res: Response) {
const token = req.cookies?.[COOKIE] as string | undefined;
if (token) await prisma.session.deleteMany({ where: { tokenHash: sha256(token) } });
res.clearCookie(COOKIE, { path: '/' });
}
/** Находит пользователя по cookie. Не требует входа: просто заполняет req.user, если сессия жива. */
export const loadUser: RequestHandler = async (req, _res, next) => {
const token = req.cookies?.[COOKIE] as string | undefined;
if (!token) return next();
const session = await prisma.session.findUnique({ where: { tokenHash: sha256(token) }, include: { user: true } });
if (!session || session.expiresAt < new Date() || session.user.blocked) return next();
req.user = session.user;
req.sessionId = session.id;
// Отметку «был в сети» обновляем не чаще раза в 10 минут, чтобы не писать в БД на каждый запрос
if (!session.user.lastSeenAt || Date.now() - session.user.lastSeenAt.getTime() > 10 * 60 * 1000) {
void prisma.user.update({ where: { id: session.user.id }, data: { lastSeenAt: new Date() } }).catch(() => undefined);
}
next();
};
export const requireAuth: RequestHandler = (req, _res, next) => {
if (!req.user) throw new HttpError(401, 'Нужно войти');
next();
};
const RANK: Record<Role, number> = { VIEWER: 1, EDITOR: 2, ADMIN: 3 };
/** Доступ с роли и выше: requireRole('EDITOR') пускает редакторов и админов. */
export const requireRole =
(role: Role): RequestHandler =>
(req, _res, next) => {
if (!req.user) throw new HttpError(401, 'Нужно войти');
if (RANK[req.user.role] < RANK[role]) throw new HttpError(403, 'Недостаточно прав');
next();
};
export const canEdit = (u?: User) => !!u && RANK[u.role] >= RANK.EDITOR;
/**
* Защита от CSRF: на изменяющих запросах требуем заголовок X-Requested-With.
* Чужой сайт не может отправить его из браузера пользователя без разрешения CORS,
* а CORS у нас открыт только для своего домена.
*/
export function csrfGuard(req: Request, _res: Response, next: NextFunction) {
if (['GET', 'HEAD', 'OPTIONS'].includes(req.method)) return next();
if (req.get('X-Requested-With') !== 'kb') throw new HttpError(403, 'Запрос отклонён');
next();
}
+84
View File
@@ -0,0 +1,84 @@
import { Router } from 'express';
import rateLimit from 'express-rate-limit';
import { z } from 'zod';
import { createSession, destroySession, requireAuth, toUserDto } from '../auth.js';
import { prisma } from '../db.js';
import { HttpError } from '../http.js';
import { hashPassword, verifyPassword } from '../services/password.js';
export const authRouter = Router();
// Не больше 10 неудачных попыток входа с одного адреса за 15 минут
const loginLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
limit: 10,
skipSuccessfulRequests: true,
standardHeaders: 'draft-7',
legacyHeaders: false,
message: { error: 'Слишком много попыток входа. Подождите 15 минут.' },
});
const inviteLimiter = rateLimit({ windowMs: 15 * 60 * 1000, limit: 30, standardHeaders: 'draft-7', legacyHeaders: false });
const email = z.string().trim().toLowerCase().email('Некорректная почта').max(200);
const loginBody = z.object({ email, password: z.string().min(1).max(200), remember: z.boolean().default(false) });
// Заранее посчитанный хеш: если пользователя нет, всё равно тратим время на проверку пароля,
// чтобы по скорости ответа нельзя было узнать, зарегистрирована ли почта.
const dummyHash = hashPassword('not-a-real-password');
authRouter.post('/login', loginLimiter, async (req, res) => {
const body = loginBody.parse(req.body);
const user = await prisma.user.findUnique({ where: { email: body.email } });
const ok = await verifyPassword(user?.passwordHash ?? (await dummyHash), body.password);
if (!user || !ok) throw new HttpError(401, 'Неверная почта или пароль');
if (user.blocked) throw new HttpError(403, 'Учётная запись заблокирована');
await createSession(res, user, body.remember, req.get('user-agent'));
res.json({ user: toUserDto(user) });
});
authRouter.post('/logout', async (req, res) => {
await destroySession(req, res);
res.status(204).end();
});
authRouter.get('/me', requireAuth, (req, res) => {
res.json({ user: toUserDto(req.user!) });
});
// ---------- Приглашения ----------
async function findInvite(token: string) {
const invite = await prisma.invite.findUnique({ where: { token } });
if (!invite || invite.usedAt || invite.expiresAt < new Date()) {
throw new HttpError(404, 'Ссылка-приглашение недействительна или уже использована');
}
return invite;
}
authRouter.get('/invite/:token', inviteLimiter, async (req, res) => {
const invite = await findInvite(String(req.params.token));
res.json({ role: invite.role, expiresAt: invite.expiresAt.toISOString() });
});
const acceptBody = z.object({
email,
name: z.string().trim().min(2, 'Укажите имя').max(100),
password: z.string().min(8, 'Пароль не короче 8 символов').max(200),
});
authRouter.post('/invite/:token', inviteLimiter, async (req, res) => {
const body = acceptBody.parse(req.body);
const invite = await findInvite(String(req.params.token));
if (await prisma.user.findUnique({ where: { email: body.email } })) {
throw new HttpError(409, 'Пользователь с такой почтой уже есть. Войдите с паролем.');
}
const passwordHash = await hashPassword(body.password);
// В одной транзакции: приглашение одноразовое, два человека по одной ссылке не зарегистрируются
const user = await prisma.$transaction(async (tx) => {
const used = await tx.invite.updateMany({ where: { id: invite.id, usedAt: null }, data: { usedAt: new Date() } });
if (used.count !== 1) throw new HttpError(404, 'Ссылка-приглашение уже использована');
return tx.user.create({ data: { email: body.email, name: body.name, passwordHash, role: invite.role } });
});
await createSession(res, user, true, req.get('user-agent'));
res.status(201).json({ user: toUserDto(user) });
});
+19 -6
View File
@@ -2,6 +2,7 @@ import { Router } from 'express';
import type { Article, Section, Space } from '@prisma/client';
import { parseCheatSheet, renderMarkdown } from '@kb/md';
import type { ArticleDto, ArticleListItem, SectionDto, SpaceDto, TreeResponse, PlaqueColor } from '@kb/shared';
import { canEdit } from '../auth.js';
import { prisma } from '../db.js';
import { HttpError } from '../http.js';
import { search } from '../search.js';
@@ -45,18 +46,28 @@ export const toListItem = (a: ArticleWithAssets): ArticleListItem => ({
// Всё дерево одним запросом: пространства, разделы и список статей (без текста).
// Статей сотни, не тысячи, поэтому отдельные запросы на каждый раздел не нужны,
// а для офлайна один ответ кешировать проще.
contentRouter.get('/tree', async (_req, res) => {
const [spaces, sections, articles] = await Promise.all([
// Кто что видит: без входа только опубликованные статьи с visibility PUBLIC;
// читатель: все опубликованные; редактор и админ: ещё и черновики.
contentRouter.get('/tree', async (req, res) => {
const where = !req.user
? { status: 'PUBLISHED' as const, visibility: 'PUBLIC' as const }
: canEdit(req.user)
? {}
: { status: 'PUBLISHED' as const };
const [spaces, allSections, articles] = await Promise.all([
prisma.space.findMany({ orderBy: { order: 'asc' } }),
prisma.section.findMany({ orderBy: { order: 'asc' } }),
prisma.article.findMany({
where: { status: 'PUBLISHED' },
where,
orderBy: [{ order: 'asc' }, { title: 'asc' }],
include: { assets: { select: { size: true } } },
}),
]);
// Гостю не показываем даже названия разделов, в которых нет публичных статей
const used = new Set(articles.map((a) => a.sectionId));
const sections = req.user ? allSections : allSections.filter((s) => used.has(s.id));
const body: TreeResponse = {
spaces: spaces.map(toSpaceDto),
spaces: req.user || sections.length ? spaces.map(toSpaceDto) : [],
sections: sections.map(toSectionDto),
articles: articles.map(toListItem),
};
@@ -72,7 +83,9 @@ contentRouter.get('/articles/:slug', async (req, res) => {
author: { select: { name: true } },
},
});
if (!art || art.status !== 'PUBLISHED') throw new HttpError(404, 'Статья не найдена');
if (!art || (art.status !== 'PUBLISHED' && !canEdit(req.user))) throw new HttpError(404, 'Статья не найдена');
// Закрытая статья без входа: 401, клиент покажет экран входа
if (!req.user && art.visibility !== 'PUBLIC') throw new HttpError(401, 'Нужно войти');
// Список картинок берём из самого текста (а не из Asset): так порядок совпадает с порядком в статье
const { figures, toc } = renderMarkdown(art.bodyMd);
@@ -98,5 +111,5 @@ contentRouter.get('/articles/:slug', async (req, res) => {
// Поиск. Пустой запрос: пустой ответ (подсказки рисует клиент).
contentRouter.get('/search', async (req, res) => {
const q = String(req.query.q ?? '').slice(0, 100);
res.json(await search(q, false));
res.json(await search(q, !req.user));
});
+50
View File
@@ -0,0 +1,50 @@
// Личные данные пользователя: избранное и недавно открытые.
// На устройстве они хранятся локально (работают без сети), а здесь синхронизируются между устройствами.
import { Router } from 'express';
import { z } from 'zod';
import { requireAuth } from '../auth.js';
import { prisma } from '../db.js';
export const meRouter = Router();
meRouter.use(requireAuth);
meRouter.get('/state', async (req, res) => {
const userId = req.user!.id;
const [favs, recent] = await Promise.all([
prisma.favorite.findMany({ where: { userId }, orderBy: { createdAt: 'desc' }, include: { article: { select: { slug: true } } } }),
prisma.recentView.findMany({ where: { userId }, orderBy: { viewedAt: 'desc' }, take: 12, include: { article: { select: { slug: true } } } }),
]);
res.json({
favorites: favs.map((f) => f.article.slug),
recent: recent.map((r) => ({ slug: r.article.slug, at: r.viewedAt.getTime() })),
});
});
const slugs = z.object({ slugs: z.array(z.string().max(200)).max(500) });
// Клиент присылает полный список избранного: сервер приводит своё к нему
meRouter.put('/favorites', async (req, res) => {
const userId = req.user!.id;
const body = slugs.parse(req.body);
const articles = await prisma.article.findMany({ where: { slug: { in: body.slugs } }, select: { id: true } });
const ids = articles.map((a) => a.id);
await prisma.$transaction([
prisma.favorite.deleteMany({ where: { userId, articleId: { notIn: ids } } }),
prisma.favorite.createMany({ data: ids.map((articleId) => ({ userId, articleId })), skipDuplicates: true }),
]);
res.status(204).end();
});
meRouter.post('/recent', async (req, res) => {
const userId = req.user!.id;
const { slug } = z.object({ slug: z.string().max(200) }).parse(req.body);
const article = await prisma.article.findUnique({ where: { slug }, select: { id: true } });
if (article) {
await prisma.recentView.upsert({
where: { userId_articleId: { userId, articleId: article.id } },
create: { userId, articleId: article.id },
update: { viewedAt: new Date() },
});
}
res.status(204).end();
});