import fs from 'node:fs'; import { setLocalEmbeddingDefault } from './services/semantic.ts'; import path from 'node:path'; import { Hono } from 'hono'; import { compress } from 'hono/compress'; import { z } from 'zod'; import { AIError } from './ai/types.ts'; import { authRoutes, csrfGuard, requireAuth } from './auth.ts'; import { HttpError, zodIssues, type AppContext } from './http.ts'; import { aiRoutes } from './routes/ai.ts'; import { APP_VERSION, dataRoutes } from './routes/data.ts'; import { documentRoutes, mediaRoute } from './routes/documents.ts'; import { libraryRoutes } from './routes/library.ts'; import { publicRoutes, shareRoutes } from './routes/shares.ts'; import { studyRoutes } from './routes/study.ts'; import { liveChanges } from './routes/events.ts'; import { notifyChange, topicOfWrite } from './services/events.ts'; import { expireOverdueAttempts } from './services/attempts.ts'; const MIME: Record = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.json': 'application/json; charset=utf-8', '.webmanifest': 'application/manifest+json; charset=utf-8', '.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg', '.ico': 'image/x-icon', '.woff2': 'font/woff2', '.woff': 'font/woff', '.txt': 'text/plain; charset=utf-8', '.map': 'application/json; charset=utf-8', }; const CSP = [ "default-src 'self'", "script-src 'self'", "style-src 'self' 'unsafe-inline'", "img-src 'self' data: blob:", "font-src 'self' data:", "connect-src 'self'", "frame-src 'self' blob:", "worker-src 'self' blob:", "object-src 'none'", "base-uri 'self'", "form-action 'self'", "frame-ancestors 'self'", ].join('; '); const AI_STATUS: Partial> = { not_configured: 409, bad_request: 400, unsupported: 400, context_length: 413, rate_limit: 429, quota: 402, aborted: 499 }; export function createApp(app: AppContext): Hono { const hono = new Hono(); setLocalEmbeddingDefault(app.config.localEmbeddings); hono.onError((err, c) => { if (err instanceof HttpError) { if (err.status === 429 && typeof (err.details as { retryAfter?: number } | undefined)?.retryAfter === 'number') { c.header('Retry-After', String((err.details as { retryAfter: number }).retryAfter)); } return c.json({ error: { code: err.code, message: err.message, details: err.details } }, err.status as never); } if (err instanceof z.ZodError) { const issues = zodIssues(err); const first = issues[0]; return c.json({ error: { code: 'validation', message: first ? `${first.path ? `${first.path}: ` : ''}${first.message}` : 'Invalid input', details: issues } }, 422); } if (err instanceof AIError) { return c.json({ error: { code: `ai_${err.code}`, message: err.message, details: err.providerMessage } }, (AI_STATUS[err.code] ?? 502) as never); } // Hono's own HTTP exceptions (body limit etc.) const maybe = err as { status?: number; message?: string; getResponse?: () => Response }; if (typeof maybe.status === 'number' && maybe.status >= 400 && maybe.status < 500) { return c.json({ error: { code: 'bad_request', message: maybe.message || 'Bad request' } }, maybe.status as never); } app.log('error', `Unhandled error on ${c.req.method} ${new URL(c.req.url).pathname}`, err); return c.json({ error: { code: 'internal', message: 'Something went wrong on the server.' } }, 500); }); // Security headers on everything. hono.use('*', async (c, next) => { await next(); const h = c.res.headers; if (!h.has('X-Content-Type-Options')) h.set('X-Content-Type-Options', 'nosniff'); if (!h.has('Referrer-Policy')) h.set('Referrer-Policy', 'same-origin'); h.set('X-Frame-Options', 'SAMEORIGIN'); h.set('Permissions-Policy', 'camera=(), microphone=(), geolocation=(), payment=()'); if ((h.get('Content-Type') ?? '').startsWith('text/html') && !h.has('Content-Security-Policy')) h.set('Content-Security-Policy', CSP); }); // gzip for API JSON and static text; event streams must not be buffered. const gzip = compress(); hono.use('*', async (c, next) => { const p = c.req.path; if (p === '/api/ai/chat' || p === '/api/ai/explain' || p === '/api/events' || p.endsWith('/stream') || /^\/api\/public\/[^/]+\/(chat|explain)$/.test(p) || p.startsWith('/api/backup') || p.endsWith('/file') || p.startsWith('/media/')) return next(); return gzip(c, next); }); hono.get('/api/health', (c) => { try { app.db.get('SELECT 1 AS ok'); return c.json({ ok: true, version: APP_VERSION }); } catch { return c.json({ ok: false }, 503); } }); // Tell open tabs when drafts, documents or the library change (see /api/events). app.db.onWrite = (sql) => { const topic = topicOfWrite(sql); if (topic) notifyChange(topic); }; const api = new Hono(); api.use('*', async (c, next) => { c.header('Cache-Control', 'no-store'); await next(); }); api.use('*', csrfGuard()); api.route('/auth', authRoutes(app)); api.route('/public', publicRoutes(app)); const secured = new Hono(); secured.use('*', requireAuth(app)); // Timed exams end on the wall clock even if nobody has the session open: submit any that are // overdue before reading data, so lists never offer to resume an expired exam. secured.use('*', async (c, next) => { if (c.req.method === 'GET') { try { expireOverdueAttempts(app.db); } catch (err) { app.log('warn', 'Could not submit overdue timed sessions', err); } } await next(); }); secured.route('/', libraryRoutes(app)); secured.route('/', studyRoutes(app)); secured.route('/', shareRoutes(app)); secured.route('/', documentRoutes(app)); secured.route('/', aiRoutes(app)); secured.route('/', dataRoutes(app)); secured.get('/events', (c) => liveChanges(c)); api.route('/', secured); api.all('*', (c) => c.json({ error: { code: 'not_found', message: 'Unknown API route' } }, 404)); hono.route('/api', api); hono.route('/media', mediaRoute(app)); /* ------------------------------ web app ------------------------------ */ const webDir = app.config.webDir; const sendFile = (file: string, cache: string): Response => { const ext = path.extname(file).toLowerCase(); return new Response(fs.readFileSync(file), { headers: { 'Content-Type': MIME[ext] ?? 'application/octet-stream', 'Cache-Control': cache } }); }; hono.get('*', (c) => { if (!webDir) { return c.text('The web app has not been built. Run "npm run build", or use "npm run dev" and open the Vite dev server.', 404); } let urlPath: string; try { urlPath = decodeURIComponent(new URL(c.req.url).pathname); } catch { return c.text('Invalid URL', 400); } const candidate = path.normalize(path.join(webDir, urlPath)); const relative = path.relative(webDir, candidate); const inside = relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative); if (!inside) return c.text('Not found', 404); if (urlPath !== '/' && fs.existsSync(candidate) && fs.statSync(candidate).isFile()) { // Hashed build assets never change; everything else is revalidated. const immutable = urlPath.startsWith('/assets/'); return sendFile(candidate, immutable ? 'public, max-age=31536000, immutable' : 'no-cache'); } if (path.extname(urlPath) && !urlPath.startsWith('/s/')) return c.text('Not found', 404); const res = sendFile(path.join(webDir, 'index.html'), 'no-cache'); if (urlPath.startsWith('/s/')) { res.headers.set('X-Robots-Tag', 'noindex, nofollow'); res.headers.set('Referrer-Policy', 'no-referrer'); } return res; }); return hono; }