-
Notifications
You must be signed in to change notification settings - Fork 406
/
index.ts
283 lines (253 loc) · 7.91 KB
/
index.ts
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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
import crypto from 'node:crypto'
import { createRequestHandler } from '@remix-run/express'
import { type ServerBuild } from '@remix-run/node'
import { ip as ipAddress } from 'address'
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'
const MODE = process.env.NODE_ENV ?? 'development'
const IS_PROD = MODE === 'production'
const IS_DEV = MODE === 'development'
const ALLOW_INDEXING = process.env.ALLOW_INDEXING !== 'false'
if (IS_PROD && process.env.SENTRY_DSN) {
void import('./utils/monitoring.js').then(({ init }) => init())
}
const viteDevServer = IS_PROD
? undefined
: await import('vite').then((vite) =>
vite.createServer({
server: { middlewareMode: true },
}),
)
const app = express()
const getHost = (req: { get: (key: string) => string | undefined }) =>
req.get('X-Forwarded-Host') ?? req.get('host') ?? ''
// fly is our proxy
app.set('trust proxy', true)
// ensure HTTPS only (X-Forwarded-Proto comes from Fly)
app.use((req, res, next) => {
if (req.method !== 'GET') return next()
const proto = req.get('X-Forwarded-Proto')
const host = getHost(req)
if (proto === 'http') {
res.set('X-Forwarded-Proto', 'https')
res.redirect(`https://${host}${req.originalUrl}`)
return
}
next()
})
// no ending slashes for SEO reasons
// https://github.com/epicweb-dev/epic-stack/discussions/108
app.get('*', (req, res, next) => {
if (req.path.endsWith('/') && req.path.length > 1) {
const query = req.url.slice(req.path.length)
const safepath = req.path.slice(0, -1).replace(/\/+/g, '/')
res.redirect(302, safepath + query)
} else {
next()
}
})
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')
if (viteDevServer) {
app.use(viteDevServer.middlewares)
} else {
// Remix fingerprints its assets so we can cache forever.
app.use(
'/assets',
express.static('build/client/assets', { immutable: true, maxAge: '1y' }),
)
// Everything else (like favicon.ico) is cached for an hour. You may want to be
// more aggressive with this caching.
app.use(express.static('build/client', { maxAge: '1h' }))
}
app.get(['/img/*', '/favicons/*'], (_req, res) => {
// if we made it past the express.static for these, then we're missing something.
// So we'll just send a 404 and won't bother calling other middleware.
return res.status(404).send('Not found')
})
morgan.token('url', (req) => decodeURIComponent(req.url ?? ''))
app.use(
morgan('tiny', {
skip: (req, res) =>
res.statusCode === 200 &&
(req.url?.startsWith('/resources/note-images') ||
req.url?.startsWith('/resources/user-images') ||
req.url?.startsWith('/resources/healthcheck')),
}),
)
app.use((_, res, next) => {
res.locals.cspNonce = crypto.randomBytes(16).toString('hex')
next()
})
app.use(
helmet({
xPoweredBy: false,
referrerPolicy: { policy: 'same-origin' },
crossOriginEmbedderPolicy: false,
contentSecurityPolicy: {
// NOTE: Remove reportOnly when you're ready to enforce this CSP
reportOnly: true,
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:'],
'script-src': [
"'strict-dynamic'",
"'self'",
// @ts-expect-error
(_, res) => `'nonce-${res.locals.cspNonce}'`,
],
'script-src-attr': [
// @ts-expect-error
(_, res) => `'nonce-${res.locals.cspNonce}'`,
],
'upgrade-insecure-requests': null,
},
},
}),
)
// When running tests or running in development, we want to effectively disable
// rate limiting because playwright tests are very fast and we don't want to
// have to wait for the rate limit to reset between tests.
const maxMultiple =
!IS_PROD || process.env.PLAYWRIGHT_TEST_BASE_URL ? 10_000 : 1
const rateLimitDefault = {
windowMs: 60 * 1000,
max: 1000 * maxMultiple,
standardHeaders: true,
legacyHeaders: false,
validate: { trustProxy: false },
// Malicious users can spoof their IP address which means we should not deault
// to trusting req.ip when hosted on Fly.io. However, users cannot spoof Fly-Client-Ip.
// When sitting behind a CDN such as cloudflare, replace fly-client-ip with the CDN
// specific header such as cf-connecting-ip
keyGenerator: (req: express.Request) => {
return req.get('fly-client-ip') ?? `${req.ip}`
},
}
const strongestRateLimit = rateLimit({
...rateLimitDefault,
windowMs: 60 * 1000,
max: 10 * maxMultiple,
})
const strongRateLimit = rateLimit({
...rateLimitDefault,
windowMs: 60 * 1000,
max: 100 * maxMultiple,
})
const generalRateLimit = rateLimit(rateLimitDefault)
app.use((req, res, next) => {
const strongPaths = [
'/login',
'/signup',
'/verify',
'/admin',
'/onboarding',
'/reset-password',
'/settings/profile',
'/resources/login',
'/resources/verify',
]
if (req.method !== 'GET' && req.method !== 'HEAD') {
if (strongPaths.some((p) => req.path.includes(p))) {
return strongestRateLimit(req, res, next)
}
return strongRateLimit(req, res, next)
}
// the verify route is a special case because it's a GET route that
// can have a token in the query string
if (req.path.includes('/verify')) {
return strongestRateLimit(req, res, next)
}
return generalRateLimit(req, res, next)
})
async function getBuild() {
try {
const build = viteDevServer
? await viteDevServer.ssrLoadModule('virtual:remix/server-build')
: // @ts-expect-error - the file might not exist yet but it will
// eslint-disable-next-line import/no-unresolved
await import('../build/server/index.js')
return { build: build as unknown as ServerBuild, error: null }
} catch (error) {
// Catch error and return null to make express happy and avoid an unrecoverable crash
console.error('Error creating build:', error)
return { error: error, build: null as unknown as ServerBuild }
}
}
if (!ALLOW_INDEXING) {
app.use((_, res, next) => {
res.set('X-Robots-Tag', 'noindex, nofollow')
next()
})
}
app.all(
'*',
createRequestHandler({
getLoadContext: (_: any, res: any) => ({
cspNonce: res.locals.cspNonce,
serverBuild: getBuild(),
}),
mode: MODE,
build: async () => {
const { error, build } = await getBuild()
// gracefully "catch" the error
if (error) {
throw error
}
return build
},
}),
)
const desiredPort = Number(process.env.PORT || 3000)
const portToUse = await getPort({
port: portNumbers(desiredPort, desiredPort + 100),
})
const portAvailable = desiredPort === portToUse
if (!portAvailable && !IS_DEV) {
console.log(`⚠️ Port ${desiredPort} is not available.`)
process.exit(1)
}
const server = app.listen(portToUse, () => {
if (!portAvailable) {
console.warn(
chalk.yellow(
`⚠️ Port ${desiredPort} is not available, using ${portToUse} instead.`,
),
)
}
console.log(`🚀 We have liftoff!`)
const localUrl = `http://localhost:${portToUse}`
let lanUrl: string | null = null
const localIp = ipAddress() ?? 'Unknown'
// Check if the address is a private ip
// https://en.wikipedia.org/wiki/Private_network#Private_IPv4_address_spaces
// https://github.com/facebook/create-react-app/blob/d960b9e38c062584ff6cfb1a70e1512509a966e7/packages/react-dev-utils/WebpackDevServerUtils.js#LL48C9-L54C10
if (/^10[.]|^172[.](1[6-9]|2[0-9]|3[0-1])[.]|^192[.]168[.]/.test(localIp)) {
lanUrl = `http://${localIp}:${portToUse}`
}
console.log(
`
${chalk.bold('Local:')} ${chalk.cyan(localUrl)}
${lanUrl ? `${chalk.bold('On Your Network:')} ${chalk.cyan(lanUrl)}` : ''}
${chalk.bold('Press Ctrl+C to stop')}
`.trim(),
)
})
closeWithGrace(async () => {
await new Promise((resolve, reject) => {
server.close((e) => (e ? reject(e) : resolve('ok')))
})
})