77 lines
4.0 KiB
JavaScript
77 lines
4.0 KiB
JavaScript
'use strict';
|
|
const http = require('node:http');
|
|
const crypto = require('node:crypto');
|
|
const path = require('node:path');
|
|
const { loadUsers } = require('./users');
|
|
const { createAuth } = require('./auth');
|
|
const { pick } = require('./i18n');
|
|
|
|
const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
|
|
|
function page(t, lang, body) {
|
|
return `<!doctype html><html lang="${lang}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${esc(t.title)}</title></head><body>${body}</body></html>`;
|
|
}
|
|
|
|
function loginPage(t, lang, { error = '', loginValue = '' } = {}) {
|
|
return page(t, lang, `<main><h1>${esc(t.title)}</h1><p>${esc(t.intro)}</p>${error ? `<p role="alert">${esc(error)}</p>` : ''}
|
|
<form method="post" action="/login?lang=${lang}">
|
|
<label>${esc(t.login)} <input name="login" value="${esc(loginValue)}" autocomplete="username" required></label>
|
|
<label>${esc(t.password)} <input name="password" type="password" autocomplete="current-password" required></label>
|
|
<button type="submit">${esc(t.submit)}</button></form></main>`);
|
|
}
|
|
|
|
function createServer({ usersFile = path.join(__dirname, '..', 'data', 'users.json'), now = Date.now, secret = process.env.SESSION_SECRET || crypto.randomBytes(32).toString('hex') } = {}) {
|
|
const auth = createAuth({ users: loadUsers(usersFile), now });
|
|
const sign = (v) => crypto.createHmac('sha256', secret).update(v).digest('base64url');
|
|
const sessionLogin = (req) => {
|
|
const m = /(?:^|;\s*)session=([^;]+)/.exec(req.headers.cookie || '');
|
|
if (!m) return null;
|
|
const [val, sig] = decodeURIComponent(m[1]).split('.');
|
|
if (!val || !sig || sig.length !== sign(val).length || !crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(sign(val)))) return null;
|
|
return Buffer.from(val, 'base64url').toString('utf8');
|
|
};
|
|
|
|
return http.createServer((req, res) => {
|
|
const url = new URL(req.url, 'http://localhost');
|
|
const lang = url.searchParams.get('lang');
|
|
const t = pick(lang);
|
|
const lg = lang && ['ru', 'kk', 'en'].includes(lang) ? lang : 'ru';
|
|
const html = (code, body, headers = {}) => { res.writeHead(code, { 'content-type': 'text/html; charset=utf-8', ...headers }); res.end(body); };
|
|
console.log(req.method, url.pathname); // тела запросов и пароли не логируем
|
|
|
|
if (url.pathname === '/healthz') { res.writeHead(200); return res.end('ok'); }
|
|
if (req.method === 'GET' && url.pathname === '/') return html(200, loginPage(t, lg));
|
|
if (req.method === 'GET' && url.pathname === '/welcome') {
|
|
const who = sessionLogin(req);
|
|
if (!who) { res.writeHead(302, { location: `/?lang=${lg}` }); return res.end(); }
|
|
return html(200, page(t, lg, `<main><h1>${esc(t.welcome.replace('{login}', who))}</h1></main>`));
|
|
}
|
|
if (req.method === 'POST' && url.pathname === '/login') {
|
|
let raw = '';
|
|
req.on('data', (c) => { raw += c; if (raw.length > 10000) req.destroy(); });
|
|
req.on('end', () => {
|
|
const form = new URLSearchParams(raw);
|
|
const login = form.get('login') || '';
|
|
const password = form.get('password') || '';
|
|
if (!login || !password) return html(400, loginPage(t, lg, { error: t.required, loginValue: login }));
|
|
const r = auth.login(login, password);
|
|
if (r.ok) {
|
|
const val = Buffer.from(r.login).toString('base64url');
|
|
res.writeHead(302, { location: `/welcome?lang=${lg}`, 'set-cookie': `session=${encodeURIComponent(`${val}.${sign(val)}`)}; HttpOnly; SameSite=Lax; Path=/` });
|
|
return res.end();
|
|
}
|
|
const status = r.reason === 'locked' ? 429 : 401;
|
|
return html(status, loginPage(t, lg, { error: r.reason === 'locked' ? t.locked : t.invalid, loginValue: login }));
|
|
});
|
|
return;
|
|
}
|
|
res.writeHead(404); res.end();
|
|
});
|
|
}
|
|
|
|
if (require.main === module) {
|
|
const port = Number(process.env.PORT) || 3000;
|
|
createServer().listen(port, () => console.log('listening on', port));
|
|
}
|
|
module.exports = { createServer };
|