70 lines
5.0 KiB
JavaScript
70 lines
5.0 KiB
JavaScript
import * as Sentry from '@sentry/node';
|
|
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.js';
|
|
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/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});
|
|
if (req.method === 'GET' && files.has(path)) {
|
|
const [file,type] = files.get(path);
|
|
res.writeHead(200,{'Content-Type':type+'; charset=utf-8'});res.end(await readFile(resolve(root,file)));return;
|
|
}
|
|
if (req.method === 'GET' && path === '/api/telemetry') 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);
|
|
const token = req.headers.cookie?.match(/(?:^|;\s*)session=([a-f0-9]{64})(?:;|$)/)?.[1];
|
|
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');
|