Files
akyldash/tools/frontend-visual-review/preview-server.cjs
codex 830e1d0f0d
CI / tests-and-images (pull_request) Successful in 2m26s
Runner smoke test / runner-smoke (pull_request) Successful in 2s
fix: localize account roles and align lab brand
2026-10-24 23:17:43 +03:00

84 lines
6.6 KiB
JavaScript

#!/usr/bin/env node
const http = require('node:http');
const fs = require('node:fs');
const path = require('node:path');
const {visualDocs, visualReviewDocs, visualReviewArticles, visualArticle, articleKy, catalogs, passwordChangeAccount} = require('./fixtures.cjs');
const repo = path.resolve(__dirname, '../..');
const htmlPath = path.join(repo, 'backend/search/review.html');
const staticRoot = path.join(repo, 'backend/search/static');
const html = fs.readFileSync(htmlPath, 'utf8');
const port = Number(process.argv[2] || 4173);
let users = [{username:'admin',role:'Администратор',can_manage_users:true,must_change_password:false,last_login_at:null,first_login_at:1780000000,password_reset_at:null},{username:'fixture-user',role:'Пользователь',can_manage_users:false,must_change_password:false,last_login_at:null,first_login_at:1780000000,password_reset_at:null}];
const warning = `<div style="position:relative;z-index:1000;padding:5px 12px;background:#38262a;color:#fff;font:600 12px/1.4 sans-serif;text-align:center;letter-spacing:.02em">ЛОКАЛЬНЫЙ PREVIEW · только синтетические данные · внешние ссылки отключены</div><script>document.addEventListener('click',event=>{const link=event.target.closest('a[href]');if(!link)return;const target=new URL(link.href,location.href);if(target.origin!==location.origin){event.preventDefault();event.stopImmediatePropagation();}},true);</script>`;
const previewHtml = html.replace('<body>', `<body>${warning}`);
const json = (response, status, value) => {
response.writeHead(status, {'Content-Type':'application/json; charset=utf-8','Cache-Control':'no-store','X-Content-Type-Options':'nosniff'});
response.end(JSON.stringify(value));
};
const readBody = (request) => new Promise((resolve) => {
let body = '';
request.on('data', (chunk) => { body += chunk; if (body.length > 32768) request.destroy(); });
request.on('end', () => { try { resolve(JSON.parse(body || '{}')); } catch { resolve({}); } });
});
const sendHtml = (response) => {
response.writeHead(200, {
'Content-Type':'text/html; charset=utf-8',
'Cache-Control':'no-store',
'X-Content-Type-Options':'nosniff',
'Referrer-Policy':'no-referrer',
'Content-Security-Policy':"default-src 'self' data:; connect-src 'self'; img-src 'self' data:; font-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; form-action 'self'; base-uri 'none'; object-src 'none'; frame-ancestors 'none'; navigate-to 'self'"
});
response.end(previewHtml);
};
const server = http.createServer(async (request, response) => {
const url = new URL(request.url, 'http://127.0.0.1');
const method = request.method || 'GET';
if (method === 'GET' && ['/', '/review', '/users'].includes(url.pathname)) return sendHtml(response);
if (method === 'GET' && url.pathname === '/auth/me') return json(response, 200, {account:passwordChangeAccount});
if (method === 'POST' && url.pathname === '/auth/logout') return json(response, 200, {ok:true});
if (method === 'POST' && url.pathname === '/auth/change-password') return json(response, 200, {account:passwordChangeAccount});
if (method === 'GET' && url.pathname === '/search/filters') return json(response, 200, catalogs);
if (method === 'GET' && url.pathname === '/search') {
const query = url.searchParams.get('q') || '';
const lab = url.searchParams.has('page_size') && !url.searchParams.has('sort');
return json(response, 200, {results:query === 'not-found' ? [] : (lab ? visualReviewDocs : visualDocs),has_next:false,review_token:'fixture-only-token'});
}
if (method === 'GET' && url.pathname === '/documents/doc-2/editions') return json(response, 200, {available_languages:[],editions:[]});
if (method === 'GET' && url.pathname === '/documents/doc-3/editions') return json(response, 503, {error:'Fixture editions error'});
if (method === 'GET' && url.pathname === '/documents/doc-1/editions') return json(response, 200, {available_languages:['ru','ky'],editions:[{source_code:'2024',name:{ru:'Редакция от 12 января 2024 года',ky:'2024-жылдын 12-январындагы редакция'},available_languages:['ru','ky']},{source_code:'2023',name:{ru:'Редакция только на русском'},available_languages:['ru']}]});
const visualReviewEdition = url.pathname.match(/^\/documents\/(review-a|review-b)\/editions\/(2026|2025)$/);
if (method === 'GET' && visualReviewEdition) return json(response, 200, {content:{ru:{html:visualReviewArticles[visualReviewEdition[1]]}}});
const edition = url.pathname.match(/^\/documents\/doc-1\/editions\/(2024|2023)$/);
if (method === 'GET' && edition) {
const language = url.searchParams.get('language') || 'ru';
const content = edition[1] === '2023' ? '<h2>Russian-only edition</h2><p>Regression fixture.</p>' : language === 'ky' ? articleKy : visualArticle;
return json(response, 200, {content:{[language]:{html:content}}});
}
if (method === 'GET' && url.pathname === '/admin/users') return json(response, 200, {users});
if (method === 'POST' && url.pathname === '/admin/users') {
const body = await readBody(request); const username = String(body.username || 'fixture-created');
users.push({username,role:'Пользователь',can_manage_users:false,must_change_password:true,last_login_at:null,first_login_at:1780000000,password_reset_at:null});
return json(response, 201, {username});
}
if (method === 'POST' && /^\/admin\/users\/[^/]+\/reset-password$/.test(url.pathname)) return json(response, 200, {ok:true});
if (method === 'DELETE' && /^\/admin\/users\/[^/]+$/.test(url.pathname)) return json(response, 200, {ok:true});
if (method === 'POST' && url.pathname === '/search-reviews') return json(response, 200, {id:42});
if (method === 'GET' && url.pathname.startsWith('/static/')) {
const name = path.basename(url.pathname);
const file = path.join(staticRoot, url.pathname.endsWith('.woff2') ? 'fonts' : '', name);
if (!fs.existsSync(file) || !fs.statSync(file).isFile()) return json(response, 404, {error:'Not found'});
const type = name.endsWith('.woff2') ? 'font/woff2' : name.endsWith('.svg') ? 'image/svg+xml' : 'image/png';
response.writeHead(200, {'Content-Type':type,'Cache-Control':'no-store','X-Content-Type-Options':'nosniff'});
return fs.createReadStream(file).pipe(response);
}
return json(response, 404, {error:'Fixture route not found'});
});
server.on('error', (error) => { process.stderr.write(`${error.code || error.name}\n`); process.exitCode = 1; });
server.listen(port, '127.0.0.1', () => {
process.stdout.write(`fixture preview listening at http://127.0.0.1:${port}/ (pid ${process.pid})\n`);
});