Something went wrong. Try again.
Synapse is a study workspace. Organize courses read and annotate the material, train with generated exercises and watch your progress forked from denishovart.com/synapse
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160import 'reflect-metadata';import { NestFactory } from '@nestjs/core';import { NestExpressApplication } from '@nestjs/platform-express';import { Logger } from '@nestjs/common';import compression from 'compression';import helmet from 'helmet';import path from 'node:path';import fs from 'node:fs';import { AppModule } from './app.module';import { configureApp } from './setup';import { resolveSessionSecret } from './auth/session-secret';
async function bootstrap(): Promise<void> { const app = await NestFactory.create<NestExpressApplication>(AppModule, { bodyParser: true }); configureApp(app, resolveSessionSecret());
// Cross-origin clients (the Tauri shells, a dev frontend on another port) // are opt-in: CORS stays off unless CORS_ORIGINS lists them. Same-origin // browsers never need it, so the default deployment keeps the tighter // posture. const corsOrigins = (process.env.CORS_ORIGINS ?? '') .split(',') .map((o) => o.trim()) .filter(Boolean); if (corsOrigins.length) { app.enableCors({ origin: corsOrigins, credentials: true }); }
// Security headers (CSP, nosniff, frame-ancestors, referrer policy, ...). The // API also serves the SPA, so these harden the frontend too. The CSP allows // the app's own origin plus what the client actually needs: // - 'unsafe-inline' styles: Svelte scopes styles via inline <style> and the // theme boot script sets inline styles before hydration; // - blob: workers/scripts and worker-src: pdf.js runs its worker from a blob; // - data:/blob: images: pdf.js rasterises pages to canvas/blob URLs. // No remote origins are allowed - every asset (incl. pdf.js) is same-origin. app.use( helmet({ contentSecurityPolicy: { directives: { defaultSrc: ["'self'"], // 'wasm-unsafe-eval' lets the Loro CRDT compile its WebAssembly // module; without it the whole local-first layer fails to load. scriptSrc: ["'self'", "'wasm-unsafe-eval'", 'blob:'], workerSrc: ["'self'", 'blob:'], styleSrc: ["'self'", "'unsafe-inline'"], imgSrc: ["'self'", 'data:', 'blob:'], fontSrc: ["'self'", 'data:'], connectSrc: ["'self'"], objectSrc: ["'none'"], frameAncestors: ["'none'"], baseUri: ["'self'"], formAction: ["'self'"], }, }, // The SPA and /api are same-origin; COEP would block the no-CORS // vendor/asset loads without buying anything here. crossOriginEmbedderPolicy: false, }), );
// gzip everything compressible (JSON, JS/CSS assets, pdf.js vendor files) - // without it the 37 KiB stylesheet and 345 KiB pdf.js travel at full size // and dominate the render-critical path. app.use(compression());
// pdf.js served locally (no CDN dependency). ESM files (.mjs). // Resolved via require.resolve to survive npm workspace hoisting // (pdfjs-dist may be installed at the monorepo root). const pdfjsDir = resolvePdfjsBuildDir(); if (pdfjsDir && fs.existsSync(pdfjsDir)) { app.useStaticAssets(pdfjsDir, { prefix: '/vendor/pdfjs', setHeaders: (res) => { res.setHeader('Content-Type', 'text/javascript'); // Version-tied to the installed package, not content-hashed: cache // for a day (pdf.min.mjs and its worker must stay in step). res.setHeader('Cache-Control', 'public, max-age=86400'); }, }); }
// Static frontend build (apps/web/dist). const distDir = resolveFrontendDist(); if (distDir) { app.useStaticAssets(distDir, { setHeaders: (res, filePath) => { // Hashed build assets never change under the same name - cache them // hard; the HTML shell (and everything else) must revalidate so a // deploy is picked up. if (filePath.includes(`${path.sep}assets${path.sep}`)) { res.setHeader('Cache-Control', 'public, max-age=31536000, immutable'); } else { res.setHeader('Cache-Control', 'no-cache'); } }, }); // SPA history fallback: any non-API, non-vendor GET that didn't match a // static asset serves index.html so client-side routes (/course/1, ...) // work on hard load / refresh. Registered on the raw Express instance so // it runs after the static-asset middleware. const indexHtml = path.join(distDir, 'index.html'); interface ExpressLike { use(handler: (req: SpaReq, res: SpaRes, next: () => void) => void): void; } interface SpaReq { method: string; path: string; } interface SpaRes { sendFile(p: string): void; } const expressApp = app.getHttpAdapter().getInstance() as ExpressLike; expressApp.use((req, res, next) => { if (req.method !== 'GET' || req.path.startsWith('/api/') || req.path.startsWith('/vendor/')) { next(); return; } // Real asset requests carry a file extension; let them 404 normally. if (/\.[a-z0-9]+$/i.test(req.path)) { next(); return; } res.sendFile(indexHtml); }); } else { Logger.warn('Frontend build not found, run `pnpm build` in the web app.', 'Bootstrap'); }
const port = Number(process.env.PORT) || 3000; // Bind to loopback only by default: the API is unauthenticated, so exposing // it on all interfaces would let any LAN peer read/write data and spend the // stored AI key. Set HOST=0.0.0.0 to opt into network access - do that only // behind auth/a reverse proxy. const host = process.env.HOST || '127.0.0.1'; await app.listen(port, host); Logger.log(`✅ Synapse API started on http://${host}:${port}`, 'Bootstrap');}
function resolvePdfjsBuildDir(): string | null { try { // Path of the pdfjs-dist package, wherever it is installed (root or apps/api). const pkg = require.resolve('pdfjs-dist/package.json'); return path.join(path.dirname(pkg), 'build'); } catch { return null; }}
function resolveFrontendDist(): string | null { const candidates = [ path.join(process.cwd(), '..', 'web', 'dist'), // from apps/api (cwd) path.join(__dirname, '..', '..', 'web', 'dist'), // from compiled dist/ path.join(process.cwd(), 'apps', 'web', 'dist'), // from the monorepo root ]; return candidates.find((p) => fs.existsSync(path.join(p, 'index.html'))) ?? null;}
void bootstrap();