treker-po-trenirovkam-i-pit.../profile-server.mjs

89 lines
7.7 KiB
JavaScript

import * as Sentry from '@sentry/node';
import { createHash } from 'node:crypto';
import { createServer } from 'node:http';
import { readFile } from 'node:fs/promises';
import { mkdirSync } from 'node:fs';
import { resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { ProfileService, InputError } from './profile/service.mjs';
if (process.env.SENTRY_DSN) Sentry.init({dsn:process.env.SENTRY_DSN,release:process.env.SENTRY_RELEASE,environment:process.env.SENTRY_ENVIRONMENT || 'dev',sendDefaultPii:false,beforeSend(event){ delete event.request; delete event.user; return event; }});
const root = fileURLToPath(new URL('.',import.meta.url));
const files = new Map([['/profile/nutrition.mjs',['profile/nutrition.mjs','text/javascript']],["/recipes.html", ["recipes.html", "text/html"]],["/recipes.css", ["recipes.css", "text/css"]],["/telemetry.js", ["generated/telemetry.js", "text/javascript"]],["/recipes.js", ["recipes.js", "text/javascript"]],["/recipes-core.js", ["recipes-core.js", "text/javascript"]],["/recipes.data.json", ["recipes.data.json", "application/json"]],["/recipes.i18n.json", ["recipes.i18n.json", "application/json"]],["/recipes-status.i18n.js", ["recipes-status.i18n.js", "text/javascript"]],["/assets/oats.jpg", ["assets/oats.jpg", "image/jpeg"]],["/assets/chicken.jpg", ["assets/chicken.jpg", "image/jpeg"]],["/assets/salad.jpg", ["assets/salad.jpg", "image/jpeg"]],['/profile/tracker-guard.js',['profile/tracker-guard.js','text/javascript']],['/gym-plan.i18n.js',['gym-plan.i18n.js','text/javascript']],['/manifest.webmanifest',['manifest.webmanifest','application/manifest+json']],['/sw.js',['profile/private-sw.js','text/javascript']],['/icon.svg',['icon.svg','image/svg+xml']],['/',['profile/index.html','text/html']],['/profile/app.js',['profile/app.js','text/javascript']],['/profile/telemetry.js',['profile/telemetry.js','text/javascript']],['/profile/style.css',['profile/style.css','text/css']],['/profile/i18n.json',['profile/i18n.json','application/json']]]);
export function createApp({database,secure = process.env.NODE_ENV === 'production'} = {}) {
if (!database) mkdirSync(process.env.DATA_DIR || resolve(root,'data'),{recursive:true,mode:0o700});
const service = new ProfileService(database || resolve(process.env.DATA_DIR || resolve(root,'data'),'profile.sqlite'));
const attempts = new Map();
let telemetryOrigin = '';
if (process.env.PUBLIC_SENTRY_DSN) {
const url = new URL(process.env.PUBLIC_SENTRY_DSN);
if (url.protocol === 'https:') telemetryOrigin = url.origin;
}
const server = createServer(async (req,res) => {
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 'self'; script-src 'self'; style-src 'self'; connect-src 'self' ${telemetryOrigin}; frame-ancestors 'none'; form-action 'self'; base-uri 'none'`);
const send = (status,data) => {res.writeHead(status,{'Content-Type':'application/json; charset=utf-8'});res.end(JSON.stringify(data));};
try {
const path = new URL(req.url,'http://localhost').pathname;
if (req.method === 'GET' && path === '/healthz') return send(200,{ok:true});
const token = req.headers.cookie?.match(/(?:^|;\s*)session=([a-f0-9]{64})(?:;|$)/)?.[1];
const htmlPolicy = html => {
const hashes = [...html.matchAll(/<script>([\s\S]*?)<\/script>/g)].map(m => "'sha256-"+createHash('sha256').update(m[1]).digest('base64')+"'").join(' ');
res.setHeader('Content-Security-Policy',`default-src 'self'; script-src 'self' ${hashes}; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; connect-src 'self' ${telemetryOrigin}; frame-ancestors 'none'; form-action 'self'; base-uri 'none'`);
};
if (req.method === 'GET' && ['/tracker','/index.html'].includes(path)) {
let personal;
try { personal=service.read(token); } catch { res.writeHead(302,{Location:'/'});res.end();return; }
const lang = new URL(req.url,'http://localhost').searchParams.get('lang');
const dictionaries = JSON.parse(await readFile(resolve(root,'profile/i18n.json'),'utf8'));
const text = Object.hasOwn(dictionaries,lang) ? dictionaries[lang] : dictionaries.ru;
let html = await readFile(resolve(root,'index.html'),'utf8');
html = html.replace('<script>',`<script>window.TPTProfile=${JSON.stringify(personal)};window.TPTProfileText=${JSON.stringify(text.profile)};window.TPTMenuText=${JSON.stringify(text.menuOpen)};</script><script>`);
html = html.replace('</body>','<script type="module" src="/profile/tracker-guard.js"></script></body>');
htmlPolicy(html);res.writeHead(200,{'Content-Type':'text/html; charset=utf-8'});res.end(html);return;
}
if (req.method === 'GET' && files.has(path)) {
const [file,type] = files.get(path);
const content = await readFile(resolve(root,file));
if (type === 'text/html') htmlPolicy(content.toString());
res.writeHead(200,{'Content-Type':type+'; charset=utf-8'});res.end(content);return;
}
if (req.method === 'GET' && ['/api/telemetry','/telemetry.json'].includes(path)) return send(200,{dsn:process.env.PUBLIC_SENTRY_DSN || '',release:process.env.SENTRY_RELEASE,environment:process.env.SENTRY_ENVIRONMENT || 'dev'});
if (!path.startsWith('/api/')) throw new InputError('notFound',404);
if (req.method === 'GET' && path === '/api/profile') return send(200,service.read(token));
if (!['POST','PUT'].includes(req.method)) throw new InputError('notFound',404);
if (!req.headers.origin || new URL(req.headers.origin).host !== req.headers.host || !['http:','https:'].includes(new URL(req.headers.origin).protocol)) throw new InputError('request',403);
if (!req.headers['content-type']?.startsWith('application/json')) throw new InputError('request',415);
let body = '';
for await (const chunk of req) {body += chunk; if (Buffer.byteLength(body)>8192) throw new InputError('request',413);}
let input; try {input = JSON.parse(body);} catch {throw new InputError('request');}
if (!input || typeof input !== 'object' || Array.isArray(input)) throw new InputError('request');
if (req.method === 'POST' && ['/api/register','/api/login'].includes(path)) {
const now = Date.now();
for (const [key,limit] of attempts) if (limit.until<now) attempts.delete(key);
const ip = req.socket.remoteAddress;
const limit = attempts.get(ip) || {count:0,until:now+60000};
if (++limit.count>20) throw new InputError('rate',429);
attempts.set(ip,limit);
const session = await service.authenticate(input,path === '/api/register');
res.setHeader('Set-Cookie',`session=${session}; HttpOnly; SameSite=Strict; Path=/; Max-Age=604800${secure ? '; Secure' : ''}`);
return send(200,service.read(session));
}
if (req.method === 'PUT' && path === '/api/profile') return send(200,service.update(token,input));
if (req.method === 'POST' && path === '/api/logout') {
service.logout(token);res.setHeader('Set-Cookie',`session=; HttpOnly; SameSite=Strict; Path=/; Max-Age=0${secure ? '; Secure' : ''}`);return send(200,{ok:true});
}
throw new InputError('notFound',404);
} catch(error) {
if (!(error instanceof InputError)) Sentry.captureException(error);
send(error instanceof InputError ? error.status : 500,{error:error instanceof InputError ? error.message : 'server'});
}
});
server.requestTimeout = 15000;
server.on('close',() => service.close());
return server;
}
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) createApp().listen(Number(process.env.PORT || 3000),'0.0.0.0');