Add HTTP routes, app wiring, V1 migration, backups, templates and API tests

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Elijah 2026-11-11 08:22:47 -07:00
parent 3e74ecd843
commit eae109c166
11 changed files with 2085 additions and 1 deletions

157
server/app.ts Normal file
View file

@ -0,0 +1,157 @@
import fs from 'node:fs';
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';
const MIME: Record<string, string> = {
'.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<Record<AIError['code'], number>> = { 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();
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.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);
}
});
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));
secured.route('/', libraryRoutes(app));
secured.route('/', studyRoutes(app));
secured.route('/', shareRoutes(app));
secured.route('/', documentRoutes(app));
secured.route('/', aiRoutes(app));
secured.route('/', dataRoutes(app));
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);
}
const urlPath = decodeURIComponent(new URL(c.req.url).pathname);
const candidate = path.normalize(path.join(webDir, urlPath));
if (candidate.startsWith(webDir) && 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;
}