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/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',['sw.js','text/javascript']],['/icon.svg',['icon.svg','image/svg+xml']],['/about.html',['about.html','text/html']],['/about.i18n.json',['about.i18n.json','application/json']],['/',['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(/