-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
203 lines (175 loc) · 4.76 KB
/
server.js
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
import 'dotenv/config'
import crypto from 'crypto'
import { createRequestHandler } from '@react-router/express'
import chalk from 'chalk'
import closeWithGrace from 'close-with-grace'
import compression from 'compression'
import express from 'express'
import { rateLimit } from 'express-rate-limit'
import getPort, { portNumbers } from 'get-port'
import helmet from 'helmet'
import morgan from 'morgan'
import sourceMapSupport from 'source-map-support'
import { printUrls } from './server-utils.js'
const MODE = process.env.NODE_ENV ?? 'development'
const DISALLOW_INDEXING = process.env.DISALLOW_INDEXING === 'true'
sourceMapSupport.install()
if (MODE === 'production' && process.env.SENTRY_DSN) {
import('./server-monitoring.js').then(({ init }) => init())
}
const viteDevServer =
MODE === 'production'
? undefined
: await import('vite').then((vite) =>
vite.createServer({
server: { middlewareMode: true },
}),
)
const app = express()
app.use(compression())
// http://expressjs.com/en/advanced/best-practice-security.html#at-a-minimum-disable-x-powered-by-header
app.disable('x-powered-by')
app.use(
morgan('tiny', {
skip:
MODE === 'development'
? (req, res) => {
if (
req.url.startsWith('/node_modules') ||
req.url.startsWith('/app') ||
req.url.startsWith('/@') ||
req.url.startsWith('/__')
) {
if (res.statusCode === 200 || res.statusCode === 304) {
return true
}
}
}
: undefined,
}),
)
const rateLimitConfig = {
skip: () => MODE !== 'production',
windowMs: 60 * 1000,
max: 1000,
standardHeaders: true,
legacyHeaders: false,
keyGenerator: (req) => {
return req.get('fly-client-ip') ?? `${req.ip}`
},
}
const strongestRateLimit = rateLimit({ ...rateLimitConfig, max: 10 })
const strongRateLimit = rateLimit({ ...rateLimitConfig, max: 100 })
const generalRateLimit = rateLimit(rateLimitConfig)
app.use((req, res, next) => {
const criticalActions = ['/auth', '/onboarding']
if (req.method !== 'GET' && req.method !== 'HEAD') {
if (criticalActions.some((p) => req.path.startsWith(p))) {
return strongestRateLimit(req, res, next)
}
return strongRateLimit(req, res, next)
}
return generalRateLimit(req, res, next)
})
app.use((_, res, next) => {
res.locals.cspNonce = crypto.randomBytes(16).toString('hex')
next()
})
app.use(
helmet({
referrerPolicy: { policy: 'same-origin' },
crossOriginEmbedderPolicy: false,
contentSecurityPolicy: {
directives: {
'connect-src': [
MODE === 'development' ? 'ws:' : null,
process.env.SENTRY_DSN ? '*.sentry.io' : null,
"'self'",
].filter(Boolean),
'font-src': ["'self'"],
'frame-src': ["'self'"],
'img-src': [
"'self'",
'data:',
'avatars.githubusercontent.com',
'cdn.discordapp.com',
'res.cloudinary.com',
],
'form-action': ["'self'", 'github.com/login/oauth/authorize'],
'script-src': [
"'strict-dynamic'",
"'self'",
(_, res) => `'nonce-${res.locals.cspNonce}'`,
"'unsafe-inline'", // backward compatibility for 'nonces'
'https:', // backward compatibility for 'strict-dynamic'
"'unsafe-eval'", // mdx-bundler needs this
],
'script-src-attr': [(_, res) => `'nonce-${res.locals.cspNonce}'`],
'upgrade-insecure-requests': null,
},
},
}),
)
if (DISALLOW_INDEXING) {
app.use((_, res, next) => {
res.set('X-Robots-Tag', 'noindex, nofollow')
next()
})
}
// handle asset requests
if (viteDevServer) {
app.use(viteDevServer.middlewares)
} else {
app.use(
'/assets',
express.static('build/client/assets', {
immutable: true,
maxAge: '1y',
}),
)
}
app.use(express.static('build/client', { maxAge: '1h' }))
function getBuild() {
return viteDevServer
? viteDevServer.ssrLoadModule('virtual:react-router/server-build')
: import('./build/server/index.js')
}
// handle SSR requests
app.all(
'*',
createRequestHandler({
getLoadContext: (_, res) => ({
cspNonce: res.locals.cspNonce,
serverBuild: getBuild(),
}),
build: getBuild,
}),
)
const desiredPort = Number(process.env.PORT || 3000)
const portToUse = await getPort({
port: portNumbers(desiredPort, desiredPort + 100),
})
const server = app.listen(portToUse, async () => {
const addr = server.address()
const portUsed = typeof addr === 'object' ? addr.port : addr
if (portUsed !== desiredPort) {
console.warn(
chalk.yellow(
`⚠️ Port ${desiredPort} is not available, using ${portUsed} instead.`,
),
)
}
console.log(`🚀 App started`)
printUrls(portUsed)
console.log(chalk.bold('Press Ctrl+C to stop'))
})
closeWithGrace(async ({ err }) => {
if (err) {
console.error(chalk.red(err))
console.error(chalk.red(err.stack))
process.exit(1)
}
await new Promise((resolve, reject) => {
server.close((e) => (e ? reject(e) : resolve('ok')))
})
})