Move browser authentication behind a generated-contract BFF
This commit is contained in:
parent
6f0f20f5cc
commit
fa7220ee33
1 changed files with 7259 additions and 2825 deletions
342
web/server.mjs
342
web/server.mjs
|
|
@ -1,68 +1,101 @@
|
|||
import { createReadStream, statSync } from 'node:fs'
|
||||
import { createServer } from 'node:http'
|
||||
import { extname, resolve, sep } from 'node:path'
|
||||
import { pathToFileURL } from 'node:url'
|
||||
|
||||
const root = resolve(process.env.REMORA_WEB_ROOT ?? '/app/dist')
|
||||
const port = numberEnvironment('REMORA_WEB_PORT', 8080)
|
||||
const runtimeConfig = {
|
||||
apiUrl: environment('REMORA_WEB_API_URL', '/v1/'),
|
||||
eventsUrl: environment('REMORA_WEB_EVENTS_URL', ''),
|
||||
oidcAuthority: environment('REMORA_WEB_OIDC_AUTHORITY', '/oidc'),
|
||||
oidcClientId: environment('REMORA_WEB_OIDC_CLIENT_ID', 'remora-web'),
|
||||
oidcRedirectUri: environment('REMORA_WEB_OIDC_REDIRECT_URI', '/'),
|
||||
oidcPostLogoutRedirectUri: environment(
|
||||
'REMORA_WEB_OIDC_POST_LOGOUT_REDIRECT_URI',
|
||||
'/',
|
||||
),
|
||||
oidcScope: environment('REMORA_WEB_OIDC_SCOPE', 'openid profile'),
|
||||
}
|
||||
const startedAt = Date.now()
|
||||
let requests = 0
|
||||
import { loadConfig } from './server/config.mjs'
|
||||
import { OAuthClient } from './server/oauth.mjs'
|
||||
import { ApiProxy } from './server/proxy.mjs'
|
||||
import { SessionStore } from './server/sessions.mjs'
|
||||
|
||||
createServer((request, response) => {
|
||||
requests += 1
|
||||
const traceId = traceIdentifier(request.headers.traceparent)
|
||||
response.setHeader('X-Content-Type-Options', 'nosniff')
|
||||
response.setHeader('Referrer-Policy', 'no-referrer')
|
||||
response.setHeader('X-Frame-Options', 'DENY')
|
||||
response.setHeader('Cross-Origin-Opener-Policy', 'same-origin')
|
||||
response.setHeader('Content-Security-Policy', contentSecurityPolicy())
|
||||
response.setHeader('Traceparent', `00-${traceId}-0000000000000001-01`)
|
||||
response.once('finish', () => {
|
||||
process.stdout.write(
|
||||
`${JSON.stringify({
|
||||
timestamp: new Date().toISOString(),
|
||||
level: 'info',
|
||||
component: 'remora-web',
|
||||
trace_id: traceId,
|
||||
method: request.method,
|
||||
path: requestPath(request.url),
|
||||
status: response.statusCode,
|
||||
})}\n`,
|
||||
)
|
||||
export function createWebServer(config, dependencies = {}) {
|
||||
const store = dependencies.store ?? new SessionStore(config)
|
||||
const oauth =
|
||||
dependencies.oauth ??
|
||||
new OAuthClient(config, store, dependencies.fetchImplementation)
|
||||
const proxy =
|
||||
dependencies.proxy ??
|
||||
new ApiProxy(config, oauth, dependencies.fetchImplementation)
|
||||
const startedAt = Date.now()
|
||||
let requests = 0
|
||||
|
||||
const server = createServer(async (request, response) => {
|
||||
requests += 1
|
||||
const traceId = traceIdentifier(request.headers.traceparent)
|
||||
secureHeaders(response, traceId)
|
||||
response.once('finish', () => {
|
||||
process.stdout.write(
|
||||
`${JSON.stringify({
|
||||
timestamp: new Date().toISOString(),
|
||||
level: 'info',
|
||||
component: 'remora-web',
|
||||
trace_id: traceId,
|
||||
method: request.method,
|
||||
path: requestPath(request.url),
|
||||
status: response.statusCode,
|
||||
})}\n`,
|
||||
)
|
||||
})
|
||||
try {
|
||||
await route(
|
||||
request,
|
||||
response,
|
||||
config,
|
||||
store,
|
||||
oauth,
|
||||
proxy,
|
||||
startedAt,
|
||||
requests,
|
||||
)
|
||||
} catch {
|
||||
if (!response.headersSent)
|
||||
response.writeHead(502, { 'Cache-Control': 'no-store' })
|
||||
response.end()
|
||||
}
|
||||
})
|
||||
route(request, response)
|
||||
}).listen(port, '0.0.0.0', () => {
|
||||
process.stdout.write(
|
||||
`${JSON.stringify({
|
||||
timestamp: new Date().toISOString(),
|
||||
level: 'info',
|
||||
component: 'remora-web',
|
||||
message: 'web application ready',
|
||||
port,
|
||||
})}\n`,
|
||||
)
|
||||
})
|
||||
server.on('upgrade', async (request, socket, head) => {
|
||||
try {
|
||||
if (!(await proxy.upgrade(request, socket, head))) socket.destroy()
|
||||
} catch {
|
||||
socket.destroy()
|
||||
}
|
||||
})
|
||||
return { server, store }
|
||||
}
|
||||
|
||||
function route(request, response) {
|
||||
async function route(
|
||||
request,
|
||||
response,
|
||||
config,
|
||||
store,
|
||||
oauth,
|
||||
proxy,
|
||||
startedAt,
|
||||
requests,
|
||||
) {
|
||||
const url = new URL(request.url ?? '/', config.publicOrigin)
|
||||
if (request.method === 'POST' && url.pathname === '/client-errors') {
|
||||
await recordClientError(request, response, config)
|
||||
return
|
||||
}
|
||||
if (await oauth.route(request, response, url)) return
|
||||
if (await proxy.route(request, response, url)) return
|
||||
if (request.method !== 'GET' && request.method !== 'HEAD') {
|
||||
response.writeHead(405, { Allow: 'GET, HEAD' })
|
||||
response.end()
|
||||
return
|
||||
}
|
||||
const url = new URL(request.url ?? '/', 'http://localhost')
|
||||
if (url.pathname === '/health/live' || url.pathname === '/health/ready') {
|
||||
json(response, 200, { status: 'ready' })
|
||||
if (url.pathname === '/health/live') {
|
||||
json(response, 200, { status: 'live' }, request.method)
|
||||
return
|
||||
}
|
||||
if (url.pathname === '/health/ready') {
|
||||
json(
|
||||
response,
|
||||
store.ready ? 200 : 503,
|
||||
{ status: store.ready ? 'ready' : 'unavailable' },
|
||||
request.method,
|
||||
)
|
||||
return
|
||||
}
|
||||
if (url.pathname === '/metrics') {
|
||||
|
|
@ -81,9 +114,10 @@ function route(request, response) {
|
|||
return
|
||||
}
|
||||
if (url.pathname === '/runtime-config.js') {
|
||||
const body = `window.remoraRuntimeConfig=${JSON.stringify(
|
||||
normalizedRuntimeConfig(),
|
||||
)};\n`
|
||||
const body = `window.remoraRuntimeConfig=${JSON.stringify({
|
||||
apiUrl: '/bff/api/',
|
||||
eventsUrl: `${config.publicOrigin.replace(/^http/, 'ws')}/bff/events`,
|
||||
})};\n`
|
||||
response.writeHead(200, {
|
||||
'Cache-Control': 'no-store',
|
||||
'Content-Type': 'text/javascript; charset=utf-8',
|
||||
|
|
@ -92,27 +126,116 @@ function route(request, response) {
|
|||
response.end(request.method === 'HEAD' ? undefined : body)
|
||||
return
|
||||
}
|
||||
const candidate = safeFile(url.pathname)
|
||||
const file = candidate ?? resolve(root, 'index.html')
|
||||
const body = regularFile(file) ? file : resolve(root, 'index.html')
|
||||
if (!regularFile(body)) {
|
||||
serveStatic(request, response, url, config.root)
|
||||
}
|
||||
|
||||
async function recordClientError(request, response, config) {
|
||||
if (
|
||||
request.headers.origin !== config.publicOrigin ||
|
||||
request.headers['sec-fetch-site'] === 'cross-site'
|
||||
) {
|
||||
response.writeHead(403, { 'Cache-Control': 'no-store' })
|
||||
response.end()
|
||||
return
|
||||
}
|
||||
const chunks = []
|
||||
let size = 0
|
||||
for await (const chunk of request) {
|
||||
size += chunk.length
|
||||
if (size > 4096) {
|
||||
response.writeHead(413, { 'Cache-Control': 'no-store' })
|
||||
response.end()
|
||||
return
|
||||
}
|
||||
chunks.push(chunk)
|
||||
}
|
||||
let body
|
||||
try {
|
||||
body = JSON.parse(Buffer.concat(chunks).toString())
|
||||
} catch {
|
||||
response.writeHead(400, { 'Cache-Control': 'no-store' })
|
||||
response.end()
|
||||
return
|
||||
}
|
||||
const validKind =
|
||||
body?.kind === 'error' || body?.kind === 'unhandled_rejection'
|
||||
if (
|
||||
!validKind ||
|
||||
typeof body.path !== 'string' ||
|
||||
body.path.length > 1024 ||
|
||||
!body.path.startsWith('/')
|
||||
) {
|
||||
response.writeHead(400, { 'Cache-Control': 'no-store' })
|
||||
response.end()
|
||||
return
|
||||
}
|
||||
process.stdout.write(
|
||||
`${JSON.stringify({
|
||||
timestamp: new Date().toISOString(),
|
||||
level: 'error',
|
||||
component: 'remora-web',
|
||||
event: 'browser_error',
|
||||
kind: body.kind,
|
||||
path: body.path,
|
||||
})}\n`,
|
||||
)
|
||||
response.writeHead(204, { 'Cache-Control': 'no-store' })
|
||||
response.end()
|
||||
}
|
||||
|
||||
function serveStatic(request, response, url, root) {
|
||||
const candidate = safeFile(url.pathname, root)
|
||||
let file = candidate && regularFile(candidate) ? candidate : null
|
||||
if (
|
||||
file === null &&
|
||||
request.headers.accept?.includes('text/html') &&
|
||||
!url.pathname.includes('.')
|
||||
)
|
||||
file = resolve(root, 'index.html')
|
||||
if (file === null || !regularFile(file)) {
|
||||
response.writeHead(404)
|
||||
response.end()
|
||||
return
|
||||
}
|
||||
const size = statSync(body).size
|
||||
response.writeHead(200, {
|
||||
'Cache-Control': body.endsWith('index.html')
|
||||
const compressed = compressedFile(file, request.headers['accept-encoding'])
|
||||
const served = compressed?.path ?? file
|
||||
const size = statSync(served).size
|
||||
const headers = {
|
||||
'Cache-Control': file.endsWith('index.html')
|
||||
? 'no-cache'
|
||||
: 'public, max-age=31536000, immutable',
|
||||
'Content-Type': contentType(body),
|
||||
'Content-Type': contentType(file),
|
||||
'Content-Length': size,
|
||||
})
|
||||
if (request.method === 'HEAD') {
|
||||
response.end()
|
||||
} else {
|
||||
createReadStream(body).pipe(response)
|
||||
}
|
||||
if (compressed !== null) {
|
||||
headers['Content-Encoding'] = compressed.encoding
|
||||
headers.Vary = 'Accept-Encoding'
|
||||
}
|
||||
response.writeHead(200, headers)
|
||||
if (request.method === 'HEAD') response.end()
|
||||
else createReadStream(served).pipe(response)
|
||||
}
|
||||
|
||||
function compressedFile(path, accepted = '') {
|
||||
for (const [encoding, suffix] of [
|
||||
['br', '.br'],
|
||||
['gzip', '.gz'],
|
||||
])
|
||||
if (accepted.includes(encoding) && regularFile(`${path}${suffix}`))
|
||||
return { encoding, path: `${path}${suffix}` }
|
||||
return null
|
||||
}
|
||||
|
||||
function secureHeaders(response, traceId) {
|
||||
response.setHeader('X-Content-Type-Options', 'nosniff')
|
||||
response.setHeader('Referrer-Policy', 'no-referrer')
|
||||
response.setHeader('X-Frame-Options', 'DENY')
|
||||
response.setHeader('Cross-Origin-Opener-Policy', 'same-origin')
|
||||
response.setHeader(
|
||||
'Content-Security-Policy',
|
||||
"default-src 'self'; base-uri 'none'; frame-ancestors 'none'; object-src 'none'; connect-src 'self'",
|
||||
)
|
||||
response.setHeader('Traceparent', `00-${traceId}-0000000000000001-01`)
|
||||
}
|
||||
|
||||
function requestPath(value) {
|
||||
|
|
@ -123,32 +246,7 @@ function requestPath(value) {
|
|||
}
|
||||
}
|
||||
|
||||
function normalizedRuntimeConfig() {
|
||||
const origin = requiredEnvironment('REMORA_WEB_PUBLIC_ORIGIN')
|
||||
return {
|
||||
...runtimeConfig,
|
||||
eventsUrl:
|
||||
runtimeConfig.eventsUrl ||
|
||||
absolute(runtimeConfig.apiUrl.replace(/\/?$/, '/events'), origin, true),
|
||||
oidcAuthority: absolute(runtimeConfig.oidcAuthority, origin, false),
|
||||
oidcRedirectUri: absolute(runtimeConfig.oidcRedirectUri, origin, false),
|
||||
oidcPostLogoutRedirectUri: absolute(
|
||||
runtimeConfig.oidcPostLogoutRedirectUri,
|
||||
origin,
|
||||
false,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
function absolute(value, origin, websocket) {
|
||||
if (/^[a-z][a-z0-9+.-]*:/i.test(value)) return value
|
||||
if (!origin) return value
|
||||
const url = new URL(value, origin)
|
||||
if (websocket) url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:'
|
||||
return url.toString()
|
||||
}
|
||||
|
||||
function safeFile(pathname) {
|
||||
function safeFile(pathname, root) {
|
||||
let decoded
|
||||
try {
|
||||
decoded = decodeURIComponent(pathname)
|
||||
|
|
@ -169,13 +267,13 @@ function regularFile(path) {
|
|||
}
|
||||
}
|
||||
|
||||
function json(response, status, value) {
|
||||
function json(response, status, value, method) {
|
||||
const body = JSON.stringify(value)
|
||||
response.writeHead(status, {
|
||||
'Content-Type': 'application/json',
|
||||
'Content-Length': Buffer.byteLength(body),
|
||||
})
|
||||
response.end(body)
|
||||
response.end(method === 'HEAD' ? undefined : body)
|
||||
}
|
||||
|
||||
function contentType(path) {
|
||||
|
|
@ -191,11 +289,6 @@ function contentType(path) {
|
|||
)
|
||||
}
|
||||
|
||||
function contentSecurityPolicy() {
|
||||
const connect = environment('REMORA_WEB_CSP_CONNECT_SRC', "'self'")
|
||||
return `default-src 'self'; base-uri 'none'; frame-ancestors 'none'; object-src 'none'; connect-src ${connect}`
|
||||
}
|
||||
|
||||
function traceIdentifier(traceparent) {
|
||||
const match =
|
||||
typeof traceparent === 'string'
|
||||
|
|
@ -204,23 +297,32 @@ function traceIdentifier(traceparent) {
|
|||
return match?.[1] ?? crypto.randomUUID().replaceAll('-', '')
|
||||
}
|
||||
|
||||
function environment(name, fallback) {
|
||||
const value = process.env[name]
|
||||
return value === undefined || value === '' ? fallback : value
|
||||
async function main() {
|
||||
const config = loadConfig()
|
||||
const { server, store } = createWebServer(config)
|
||||
await store.connect()
|
||||
server.listen(config.port, '0.0.0.0', () => {
|
||||
process.stdout.write(
|
||||
`${JSON.stringify({
|
||||
timestamp: new Date().toISOString(),
|
||||
level: 'info',
|
||||
component: 'remora-web',
|
||||
message: 'web application ready',
|
||||
port: config.port,
|
||||
})}\n`,
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
function requiredEnvironment(name) {
|
||||
const value = process.env[name]
|
||||
if (value === undefined || value === '') {
|
||||
throw new Error(`${name} is required`)
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
function numberEnvironment(name, fallback) {
|
||||
const value = Number(environment(name, String(fallback)))
|
||||
if (!Number.isSafeInteger(value) || value < 1 || value > 65535) {
|
||||
throw new Error(`${name} must be a valid port`)
|
||||
}
|
||||
return value
|
||||
}
|
||||
if (import.meta.url === pathToFileURL(process.argv[1] || '').href)
|
||||
main().catch((error) => {
|
||||
process.stderr.write(
|
||||
`${JSON.stringify({
|
||||
timestamp: new Date().toISOString(),
|
||||
level: 'error',
|
||||
component: 'remora-web',
|
||||
message: error.message,
|
||||
})}\n`,
|
||||
)
|
||||
process.exitCode = 1
|
||||
})
|
||||
|
|
|
|||
Loading…
Reference in a new issue