-
-
Notifications
You must be signed in to change notification settings - Fork 472
Expand file tree
/
Copy pathserver.js
More file actions
204 lines (181 loc) · 5.49 KB
/
server.js
File metadata and controls
204 lines (181 loc) · 5.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
import { Hono } from 'hono';
import { bodyLimit } from 'hono/body-limit';
import { serveStatic } from 'hono/bun';
import { compress } from 'hono/compress';
import { HTTPException } from 'hono/http-exception';
import { secureHeaders } from 'hono/secure-headers';
import { createRequestHandler } from 'react-router';
const isProd = process.env.NODE_ENV === 'production';
const viteDevServer = isProd
? undefined
: await import('vite').then((vite) =>
vite.createServer({
server: { middlewareMode: true },
}),
);
const app = new Hono();
app.onError((err, c) => {
// React Router handles all route actions internally and we're now catching HTTPException within the actions themselves, app.onError won't catch those errors.
// However, it's still a good safety net for:
// - Errors in Hono middleware (compression, secure headers)
// - Errors in static file serving
// - Any unexpected errors at the Hono layer
// Handle HTTPException (from hono/http-exception)
if (err instanceof HTTPException) {
return err.getResponse();
}
// Log unexpected errors
console.error('Unexpected error:', err);
// Return generic error response
return c.json(
{
error: 'Internal Server Error',
status: 500,
},
500,
);
});
// Compression
app.use(compress());
app.use('*', async (c, next) => {
if (c.req.path.startsWith('/api/documents')) {
return next(); // Skip limit — Bun's 300MB cap is the backstop
}
return bodyLimit({ maxSize: 10 * 1024 * 1024 })(c, next);
});
// Security headers (replaces helmet)
const wsUrls = process.env.WS_URLS?.split(',').map((url) => url.trim()) ?? [];
const imgSrc = [
"'self'",
'data:',
'blob:',
'google.com',
'*.openstreetmap.org',
'onearmy.github.io',
'cdn.jsdelivr.net',
'*.google-analytics.com',
'*.patreonusercontent.com',
'*.basemaps.cartocdn.com',
'*.supabase.co',
process.env.SUPABASE_API_URL,
].filter(Boolean);
app.use(
secureHeaders({
contentSecurityPolicy: {
styleSrc: ["'self'", "'unsafe-inline'", 'fonts.googleapis.com'],
fontSrc: ["'self'", 'fonts.gstatic.com', 'fonts.googleapis.com'],
connectSrc: [
"'self'",
'*.run.app',
'securetoken.googleapis.com',
'identitytoolkit.googleapis.com',
'*.openstreetmap.org',
'*.google-analytics.com',
'*.cloudfunctions.net',
'sentry.io',
'*.sentry.io',
...wsUrls,
],
defaultSrc: [
"'self'",
'googletagmanager.com',
'*.googletagmanager.com',
'analytics.google.com',
'*.analytics.google.com',
'*.google-analytics.com',
'googleapis.com',
],
scriptSrc: [
"'self'",
'googletagmanager.com',
'*.googletagmanager.com',
'fonts.gstatic.com',
'fonts.googleapis.com',
'*.analytics.google.com',
'*.google-analytics.com',
'www.youtube.com',
'donorbox.org',
"'unsafe-eval'",
"'unsafe-inline'",
],
frameSrc: [
"'self'",
'onearmy.github.io',
'*.youtube.com',
'*.donorbox.org',
'donorbox.org',
'*.run.app',
'*.netlify.app',
'projectkamp.com',
'*.projectkamp.com',
'preciousplastic.com',
'*.preciousplastic.com',
'fixing.fashion',
'*.fixing.fashion',
],
imgSrc: imgSrc,
objectSrc: ["'self'"],
upgradeInsecureRequests: isProd ? [] : undefined,
},
strictTransportSecurity: isProd ? 'max-age=31536000; preload' : false,
xContentTypeOptions: 'nosniff',
referrerPolicy: 'origin',
xXssProtection: '1; mode=block',
xDnsPrefetchControl: 'on',
}),
);
// React Router request handler
const handler = createRequestHandler(
viteDevServer
? () => viteDevServer.ssrLoadModule('virtual:react-router/server-build')
: await import('./build/server/index.js'),
);
const port = Number(process.env.PORT) || 3456; // 3456 is default port for ci
if (isProd) {
// Fingerprinted assets — cache forever
app.use(
'/assets/*',
serveStatic({
root: './build/client',
onFound: (_path, c) => {
c.header('Cache-Control', 'public, max-age=31536000, immutable');
},
}),
);
// Other static files — cache for 1 hour
app.use(
'*',
serveStatic({
root: './build/client',
onFound: (_path, c) => {
c.header('Cache-Control', 'public, max-age=3600');
},
}),
);
// All remaining requests go to React Router
app.all('*', (c) => handler(c.req.raw));
Bun.serve({
port,
hostname: '0.0.0.0',
fetch: app.fetch,
maxRequestBodySize: 300 * 1024 * 1024, // Must accommodate /api/documents - protected by Hono middleware
});
console.log(`Hono server started on http://0.0.0.0:${port}`);
} else {
// Development: Node-compatible HTTP server so Vite middleware works
const http = await import('node:http');
const { getRequestListener } = await import('@hono/node-server');
// All requests go to React Router
app.all('*', (c) => handler(c.req.raw));
const honoListener = getRequestListener(app.fetch);
const server = http.createServer((req, res) => {
// Vite middleware handles HMR, module transforms, and client assets.
// When it doesn't handle the request it calls next(), falling through to Hono.
viteDevServer.middlewares(req, res, () => {
honoListener(req, res);
});
});
server.listen(port, '0.0.0.0', () => {
console.log(`Hono dev server started on http://0.0.0.0:${port}`);
});
}