175 lines
6.5 KiB
TypeScript
175 lines
6.5 KiB
TypeScript
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
import { type Account, verifyCredentials } from "./auth.ts";
|
|
import { type Lang, pickLang } from "./i18n.ts";
|
|
import { createRevocationList, createSessionToken, readSessionToken } from "./session.ts";
|
|
import { homePage, loginPage, messagePage, STYLESHEET } from "./views.ts";
|
|
|
|
export interface AppOptions {
|
|
account: Account;
|
|
/** true — показывать на странице входа пробные логин и пароль (мок). */
|
|
mockAuth: boolean;
|
|
sessionSecret: Buffer;
|
|
cookieSecure: boolean;
|
|
now?: () => number;
|
|
onError?: (error: unknown) => void;
|
|
}
|
|
|
|
const SESSION_COOKIE = "session";
|
|
const LANG_COOKIE = "lang";
|
|
const MAX_BODY_BYTES = 10_000;
|
|
const YEAR_SECONDS = 365 * 24 * 60 * 60;
|
|
|
|
class BodyTooLargeError extends Error {}
|
|
|
|
function parseCookies(header: string | undefined): Record<string, string> {
|
|
const cookies: Record<string, string> = {};
|
|
for (const part of (header ?? "").split(";")) {
|
|
const eq = part.indexOf("=");
|
|
if (eq > 0) cookies[part.slice(0, eq).trim()] = part.slice(eq + 1).trim();
|
|
}
|
|
return cookies;
|
|
}
|
|
|
|
async function readForm(req: IncomingMessage): Promise<URLSearchParams> {
|
|
const chunks: Buffer[] = [];
|
|
let size = 0;
|
|
for await (const chunk of req as AsyncIterable<Buffer>) {
|
|
size += chunk.length;
|
|
if (size > MAX_BODY_BYTES) throw new BodyTooLargeError();
|
|
chunks.push(chunk);
|
|
}
|
|
return new URLSearchParams(Buffer.concat(chunks).toString("utf8"));
|
|
}
|
|
|
|
export function createApp(options: AppOptions) {
|
|
const now = options.now ?? Date.now;
|
|
const secure = options.cookieSecure ? "; Secure" : "";
|
|
const demo = options.mockAuth ? options.account : undefined;
|
|
const revoked = createRevocationList();
|
|
|
|
// Без Max-Age: вход действует, пока открыт браузер (долгий вход — вне TR-1).
|
|
const sessionCookie = (value: string) =>
|
|
`${SESSION_COOKIE}=${value}; Path=/; HttpOnly; SameSite=Lax${secure}`;
|
|
const clearSessionCookie = `${sessionCookie("")}; Max-Age=0`;
|
|
|
|
function send(
|
|
res: ServerResponse,
|
|
status: number,
|
|
body: string,
|
|
type = "text/html; charset=utf-8",
|
|
) {
|
|
res.statusCode = status;
|
|
res.setHeader("Content-Type", type);
|
|
res.setHeader("Content-Length", Buffer.byteLength(body));
|
|
res.end(res.req.method === "HEAD" ? undefined : body);
|
|
}
|
|
|
|
function redirect(res: ServerResponse, location: string) {
|
|
res.statusCode = 303;
|
|
res.setHeader("Location", location);
|
|
res.end();
|
|
}
|
|
|
|
async function handle(req: IncomingMessage, res: ServerResponse, lang: Lang, url: URL) {
|
|
const method = req.method ?? "GET";
|
|
const read = method === "GET" || method === "HEAD";
|
|
const path = url.pathname;
|
|
const cookies = parseCookies(req.headers.cookie);
|
|
const token = cookies[SESSION_COOKIE];
|
|
const time = now();
|
|
const user =
|
|
token && !revoked.isRevoked(token, time)
|
|
? readSessionToken(token, options.sessionSecret, time)
|
|
: null;
|
|
|
|
// Открытые адреса: всё, что ниже проверки входа, доступно только вошедшему.
|
|
|
|
if (path === "/healthz" && read) return send(res, 200, "ok\n", "text/plain; charset=utf-8");
|
|
|
|
if (path === "/static/style.css" && read) {
|
|
res.setHeader("Cache-Control", "public, max-age=300");
|
|
return send(res, 200, STYLESHEET, "text/css; charset=utf-8");
|
|
}
|
|
|
|
if (path === "/login" && read) {
|
|
if (user) return redirect(res, "/");
|
|
return send(res, 200, loginPage({ lang, demo }));
|
|
}
|
|
|
|
if (path === "/login" && method === "POST") {
|
|
const form = await readForm(req);
|
|
const login = (form.get("login") ?? "").trim().slice(0, 200);
|
|
const password = form.get("password") ?? "";
|
|
if (!login || !password) {
|
|
const error = { key: "login.errorEmpty" } as const;
|
|
return send(res, 400, loginPage({ lang, login, demo, error }));
|
|
}
|
|
const verified = verifyCredentials(options.account, login, password);
|
|
if (!verified) {
|
|
const error = { key: "login.errorInvalid" } as const;
|
|
return send(res, 401, loginPage({ lang, login, demo, error }));
|
|
}
|
|
const issued = createSessionToken(verified, options.sessionSecret, time);
|
|
res.appendHeader("Set-Cookie", sessionCookie(issued));
|
|
return redirect(res, "/");
|
|
}
|
|
|
|
// Проверка входа: любой другой адрес закрыт, в том числе несуществующий.
|
|
if (!user || !token) return redirect(res, "/login");
|
|
|
|
if (path === "/" && read) return send(res, 200, homePage({ lang, login: user }));
|
|
|
|
if (path === "/logout" && method === "POST") {
|
|
revoked.revoke(token, time);
|
|
res.appendHeader("Set-Cookie", clearSessionCookie);
|
|
return redirect(res, "/login");
|
|
}
|
|
|
|
const body = messagePage({
|
|
lang,
|
|
path: "/",
|
|
title: "notFound.title",
|
|
text: "notFound.text",
|
|
link: "notFound.homeLink",
|
|
});
|
|
return send(res, 404, body);
|
|
}
|
|
|
|
return async function app(req: IncomingMessage, res: ServerResponse): Promise<void> {
|
|
let lang: Lang = "ru";
|
|
try {
|
|
const url = new URL(req.url ?? "/", "http://localhost");
|
|
const choice = url.searchParams.get("lang") ?? undefined;
|
|
const cookies = parseCookies(req.headers.cookie);
|
|
lang = pickLang(choice, cookies[LANG_COOKIE], req.headers["accept-language"]);
|
|
if (choice === lang && cookies[LANG_COOKIE] !== lang) {
|
|
res.appendHeader(
|
|
"Set-Cookie",
|
|
`${LANG_COOKIE}=${lang}; Path=/; SameSite=Lax; Max-Age=${YEAR_SECONDS}${secure}`,
|
|
);
|
|
}
|
|
res.setHeader("Content-Language", lang);
|
|
res.setHeader("Cache-Control", "no-store");
|
|
res.setHeader("X-Content-Type-Options", "nosniff");
|
|
res.setHeader("Referrer-Policy", "no-referrer");
|
|
res.setHeader(
|
|
"Content-Security-Policy",
|
|
"default-src 'none'; style-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'",
|
|
);
|
|
await handle(req, res, lang, url);
|
|
} catch (error) {
|
|
const tooLarge = error instanceof BodyTooLargeError;
|
|
if (!tooLarge) options.onError?.(error);
|
|
if (res.headersSent) {
|
|
res.destroy();
|
|
return;
|
|
}
|
|
const body = messagePage({ lang, path: "/", title: "error.title", text: "error.unexpected" });
|
|
res.statusCode = tooLarge ? 413 : 500;
|
|
res.setHeader("Content-Type", "text/html; charset=utf-8");
|
|
if (tooLarge) res.setHeader("Connection", "close");
|
|
res.end(body);
|
|
}
|
|
};
|
|
}
|