Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
90 lines (83 loc) · 4.55 KB
/
Copy pathserver.js
File metadata and controls
90 lines (83 loc) · 4.55 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
// Production server: what `react-router-serve` does, with Express `trust proxy` on.
//
// TLS usually ends at a reverse proxy in front of the app (nginx, Caddy, an ingress), which
// forwards plain HTTP with `X-Forwarded-Proto: https`. React Router (since 8.3.1) refuses an
// action whose `Origin` does not match the request URL, scheme included, and the Express adapter
// builds that URL from `req.protocol`, which ignores `X-Forwarded-Proto` unless `trust proxy` is
// on. Without it every form submission behind HTTPS fails with a 400.
//
// `X-Forwarded-*` is honoured only when the TCP peer is on loopback or a private network, or as
// configured by UNITAE_TRUST_PROXY (Express `trust proxy` syntax). That is not an authentication
// boundary, and `Host` is always chosen by the client: never build absolute URLs from
// `request.url`, use UNITAE_BASE_URL.
import path from 'node:path'
import url from 'node:url'
import compression from 'compression'
import express from 'express'
import morgan from 'morgan'
// React and the app build read NODE_ENV once, when they load (development React, non-secure
// cookies), so default it before importing either. A static import would run before this line.
process.env.NODE_ENV ??= 'production'
const { createRequestHandler } = await import('@react-router/express')
const build = await import(url.pathToFileURL(path.resolve('build/server/index.js')).href)
const assetsDirectory = path.resolve(build.assetsBuildDirectory)
const port = Number(process.env.PORT) || 3000
const HOP_COUNT = /^\d+$/
// `true`, a hop count, or a comma-separated list of addresses, subnets and preset names.
function parseTrustProxy(value) {
if (!value) return 'loopback, linklocal, uniquelocal'
if (value === 'true' || value === 'false') return value === 'true'
return HOP_COUNT.test(value) ? Number(value) : value
}
const app = express()
app.set('trust proxy', parseTrustProxy(process.env.UNITAE_TRUST_PROXY))
app.disable('x-powered-by')
// Map label glyphs are protobuf, which compression leaves alone by default: they shrink by a third.
app.use(compression({ filter: (req, res) => req.path.startsWith('/map-fonts/') || compression.filter(req, res) }))
app.use('/assets', express.static(path.join(assetsDirectory, 'assets'), { immutable: true, maxAge: '1y' }))
app.use(express.static(assetsDirectory))
app.use(express.static('public', { maxAge: '1h' }))
app.use('/.well-known', express.static(path.join(assetsDirectory, '.well-known')))
// `tiny`, minus what must not be kept in logs: the query string (search terms, names) and the secret
// segment of the paths that carry one — a calendar feed's token is long-lived and its URL is polled
// for as long as the subscription lives. Kubernetes probes, several a minute, are not logged.
const SECRET_PATH_SEGMENTS = [
[/^\/feed\/[^/]+\/calendar\.ics$/, '/feed/:token/calendar.ics'],
[/^\/verify-email\/[^/]+$/, '/verify-email/:token'],
[/^\/password\/[^/]+\/reset(\.data)?$/, '/password/:userHash/reset'],
]
const PROBE_PATHS = new Set(['/health', '/livez'])
morgan.token('path', req => {
const pathname = req.originalUrl.split('?')[0]
const secret = SECRET_PATH_SEGMENTS.find(([pattern]) => pattern.test(pathname))
return secret ? secret[1] : pathname
})
app.use(
morgan(':method :path :status :res[content-length] - :response-time ms', { skip: req => PROBE_PATHS.has(req.path) }),
)
// The client address, as resolved by `trust proxy` above: X-Forwarded-For walked from the right,
// past trusted proxies. The leftmost entry is whatever the client sent, so the app must not key
// rate limits on it. Pass the resolved address on in a header of our own, overwriting any value
// the client sent under that name. Read by app/shared/utils/get-client-ip.ts.
const CLIENT_IP_HEADER = 'x-unitae-client-ip'
const IPV4_MAPPED_PREFIX = '::ffff:'
app.use((req, _res, next) => {
delete req.headers[CLIENT_IP_HEADER]
const ip = req.ip?.startsWith(IPV4_MAPPED_PREFIX) ? req.ip.slice(IPV4_MAPPED_PREFIX.length) : req.ip
if (ip) req.headers[CLIENT_IP_HEADER] = ip
next()
})
app.all('/{*splat}', createRequestHandler({ build, mode: process.env.NODE_ENV }))
// Express 5 hands a bind failure (port taken, no permission) to this callback instead of throwing:
// rethrow it, or the process would report success while serving nothing.
const server = app.listen(port, error => {
if (error) throw error
process.stdout.write(`Server listening on http://localhost:${port}\n`)
})
for (const signal of ['SIGTERM', 'SIGINT']) {
process.once(signal, () =>
server.close(error => {
if (error) process.stderr.write(`${error.stack ?? error}\n`)
}),
)
}