mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-28 07:30:04 +00:00
style: format server and shared with prettier
A mechanical prettier --write over server/src, server/tests, server/scripts and shared/src with the workspaces' .prettierrc; nothing but layout and import order changes, and every file keeps the same set of imports. shared is formatted throughout and its format baseline is empty. The server baseline keeps the 35 files that Prettier would grow past their lint:size limit (they need a split first, which is not a formatting change), and the generated entity files stay as their generator writes them.
This commit is contained in:
@@ -1,14 +1,6 @@
|
||||
import express, { Request, Response, NextFunction } from 'express';
|
||||
import { AsyncResource } from 'node:async_hooks';
|
||||
import compression from 'compression';
|
||||
import cors from 'cors';
|
||||
import helmet from 'helmet';
|
||||
import cookieParser from 'cookie-parser';
|
||||
import type { ConfigType } from '@nestjs/config';
|
||||
import { readEnv } from '../app-config';
|
||||
import { httpConfig } from '../nest/app-config/tokens';
|
||||
import { logDebug, logWarn, logError } from '../nest/audit/audit-log.logger';
|
||||
import { isSameHostOrigin } from '../nest/common/same-origin';
|
||||
import {
|
||||
ACCESS_LOG_ATTACHED,
|
||||
REQUEST_ID_HEADER,
|
||||
@@ -17,6 +9,15 @@ import {
|
||||
newCorrelationId,
|
||||
runWithCorrelation,
|
||||
} from '../nest/common/request-correlation';
|
||||
import { isSameHostOrigin } from '../nest/common/same-origin';
|
||||
import type { ConfigType } from '@nestjs/config';
|
||||
|
||||
import compression from 'compression';
|
||||
import cookieParser from 'cookie-parser';
|
||||
import cors from 'cors';
|
||||
import express, { Request, Response, NextFunction } from 'express';
|
||||
import helmet from 'helmet';
|
||||
import { AsyncResource } from 'node:async_hooks';
|
||||
|
||||
/**
|
||||
* Field names redacted from request-log query/body dumps (case-insensitive —
|
||||
@@ -245,120 +246,135 @@ export function applyGlobalMiddleware(
|
||||
// session per tool call until the per-user cap wedges the connection. Same reasoning for
|
||||
// WWW-Authenticate, which carries the RFC 9728 resource-metadata challenge that drives
|
||||
// OAuth discovery.
|
||||
app.use(
|
||||
(req: Request, _res: Response, next: NextFunction) => {
|
||||
if (
|
||||
req.path.startsWith('/.well-known/') ||
|
||||
req.path === '/oauth/register' ||
|
||||
req.path === '/oauth/authorize' ||
|
||||
req.path === '/oauth/userinfo' ||
|
||||
req.path === '/mcp'
|
||||
) {
|
||||
cors({
|
||||
origin: '*',
|
||||
credentials: false,
|
||||
exposedHeaders: ['Mcp-Session-Id', 'MCP-Protocol-Version', 'WWW-Authenticate'],
|
||||
})(req, _res, next);
|
||||
} else {
|
||||
next();
|
||||
}
|
||||
},
|
||||
);
|
||||
app.use((req: Request, _res: Response, next: NextFunction) => {
|
||||
if (
|
||||
req.path.startsWith('/.well-known/') ||
|
||||
req.path === '/oauth/register' ||
|
||||
req.path === '/oauth/authorize' ||
|
||||
req.path === '/oauth/userinfo' ||
|
||||
req.path === '/mcp'
|
||||
) {
|
||||
cors({
|
||||
origin: '*',
|
||||
credentials: false,
|
||||
exposedHeaders: ['Mcp-Session-Id', 'MCP-Protocol-Version', 'WWW-Authenticate'],
|
||||
})(req, _res, next);
|
||||
} else {
|
||||
next();
|
||||
}
|
||||
});
|
||||
app.use(cors(corsOptions));
|
||||
app.use(helmet({
|
||||
contentSecurityPolicy: {
|
||||
directives: {
|
||||
defaultSrc: ["'self'"],
|
||||
// 'unsafe-eval' is load-bearing, not leftover: heic-to's libheif build
|
||||
// initialises embind through new Function(), and that is what converts
|
||||
// an iPhone .heic the moment somebody picks one. 'wasm-unsafe-eval'
|
||||
// alone was tried first and was not enough (93b51a0b). The package
|
||||
// ships a CSP-safe entry point at heic-to/csp; dropping this directive
|
||||
// means switching client/src/utils/convertHeic.ts over to it and
|
||||
// verifying a real .heic upload in a browser, not just deleting the
|
||||
// string here.
|
||||
scriptSrc: ["'self'", "'wasm-unsafe-eval'", "'unsafe-eval'"],
|
||||
styleSrc: ["'self'", "'unsafe-inline'", "https://fonts.googleapis.com", "https://unpkg.com"],
|
||||
imgSrc: ["'self'", "data:", "blob:", "https:"],
|
||||
connectSrc: [
|
||||
"'self'", "ws:", "wss:",
|
||||
"https://nominatim.openstreetmap.org", "https://overpass-api.de",
|
||||
"https://places.googleapis.com", "https://api.openweathermap.org",
|
||||
"https://en.wikipedia.org", "https://commons.wikimedia.org",
|
||||
// Both forms here too: CARTO documents the apex host on its key page,
|
||||
// so that is the template users paste in, and the {s} sharded form is
|
||||
// what TREK ships (#2054).
|
||||
"https://basemaps.cartocdn.com", "https://*.basemaps.cartocdn.com",
|
||||
// Both forms: a CSP wildcard host never matches the apex, and OSM
|
||||
// serves everything from the bare tile.openstreetmap.org since it
|
||||
// retired the a/b/c/d shards (#1733). The sharded hosts stay listed
|
||||
// for tile templates users saved before that.
|
||||
"https://tile.openstreetmap.org", "https://*.tile.openstreetmap.org",
|
||||
// The other two raster presets TREK ships. `mode: 'no-cors'` relaxes
|
||||
// CORS, not CSP, so without these the tile prefetch is refused in the
|
||||
// document and never reaches the Service Worker that would cache it
|
||||
// (#2180). routing.openstreetmap.de below is a different host.
|
||||
"https://tile.openstreetmap.de", "https://tiles.stadiamaps.com",
|
||||
// OpenTopoMap is the key-free raster layer offered only by the Tours
|
||||
// planner. Leaflet uses its a/b/c shards; the apex is named too so a
|
||||
// future unsharded template does not repeat the OSM CSP gap above.
|
||||
"https://tile.opentopomap.org", "https://*.tile.opentopomap.org",
|
||||
// The imagery host, for the same reason and one more. Leaflet fetches a tile
|
||||
// as an <img>, which img-src's blanket `https:` waves through, so the satellite
|
||||
// view worked on Leaflet with this host missing. A GL map reads the raster
|
||||
// through fetch to hand it to WebGL, and the prefetch does too, so both were
|
||||
// refused here while nothing in the app could see it: the switch flipped, the
|
||||
// layer went on, and no tile ever arrived (#2307).
|
||||
"https://server.arcgisonline.com",
|
||||
// Amap's raster tiles, for an install whose users are in China, for the
|
||||
// same reason as the hosts above (#2180). Road (webrd01..04) and
|
||||
// satellite (webst01..04) are numbered shards of one domain, so the
|
||||
// wildcard is the whole list.
|
||||
"https://*.is.autonavi.com",
|
||||
"https://unpkg.com", "https://open-meteo.com", "https://api.open-meteo.com",
|
||||
"https://geocoding-api.open-meteo.com", "https://api.frankfurter.dev",
|
||||
"https://router.project-osrm.org/route/v1/", "https://routing.openstreetmap.de/",
|
||||
// The second routing engine, shipped as a default the same way the OSRM hosts
|
||||
// above are. It is asked only when a leg should avoid tolls, motorways or a
|
||||
// ferry — which the OSRM hosts answer with HTTP 400, because their car profile
|
||||
// carries no excludable classes. Origin only, no path: unlike OSRM this one is
|
||||
// a POST to /route and would grow more endpoints if isochrones ever land.
|
||||
"https://valhalla1.openstreetmap.de",
|
||||
"https://api.mapbox.com", "https://*.tiles.mapbox.com", "https://events.mapbox.com",
|
||||
"https://tiles.openfreemap.org",
|
||||
// A self-hosted routing engine, when the instance has one configured. Without
|
||||
// this the browser blocks it silently: no error the app can catch, just legs
|
||||
// that never route (#1797).
|
||||
...extraConnectSrc,
|
||||
],
|
||||
workerSrc: ["'self'", "blob:"],
|
||||
childSrc: ["'self'", "blob:"],
|
||||
// blob: because a picked clip is previewed and its poster frame grabbed
|
||||
// through a <video> on an object URL, before any byte reaches the server.
|
||||
// Unset, this fell back to default-src, which refuses blob: outright: the
|
||||
// editor showed nothing and every clip landed without a poster, so its
|
||||
// thumbnail answered 404 (#2341). Invisible in dev, where Vite serves the
|
||||
// document without this header.
|
||||
mediaSrc: ["'self'", "blob:"],
|
||||
fontSrc: ["'self'", "https://fonts.gstatic.com", "data:"],
|
||||
// 'self' so same-origin file previews can embed PDFs via <object>/<embed>
|
||||
// (Firefox/Chrome enforce object-src; 'none' broke inline PDF previews there).
|
||||
objectSrc: ["'self'"],
|
||||
// 'self' so the app can embed same-origin, sandboxed plugin frames
|
||||
// (/plugin-frame/*). Those frames are sandboxed WITHOUT allow-same-origin,
|
||||
// so they run at an opaque origin and get their own locked-down CSP.
|
||||
frameSrc: ["'self'"],
|
||||
frameAncestors: ["'self'"],
|
||||
// Restrict <form> submission targets (form-action has no default-src
|
||||
// fallback, so it must be set explicitly).
|
||||
formAction: ["'self'"],
|
||||
upgradeInsecureRequests: shouldForceHttps ? [] : null
|
||||
}
|
||||
},
|
||||
crossOriginEmbedderPolicy: false,
|
||||
hsts: hstsActive ? { maxAge: 31536000, includeSubDomains: hstsIncludeSubdomains } : false,
|
||||
referrerPolicy: { policy: 'strict-origin-when-cross-origin' },
|
||||
}));
|
||||
app.use(
|
||||
helmet({
|
||||
contentSecurityPolicy: {
|
||||
directives: {
|
||||
defaultSrc: ["'self'"],
|
||||
// 'unsafe-eval' is load-bearing, not leftover: heic-to's libheif build
|
||||
// initialises embind through new Function(), and that is what converts
|
||||
// an iPhone .heic the moment somebody picks one. 'wasm-unsafe-eval'
|
||||
// alone was tried first and was not enough (93b51a0b). The package
|
||||
// ships a CSP-safe entry point at heic-to/csp; dropping this directive
|
||||
// means switching client/src/utils/convertHeic.ts over to it and
|
||||
// verifying a real .heic upload in a browser, not just deleting the
|
||||
// string here.
|
||||
scriptSrc: ["'self'", "'wasm-unsafe-eval'", "'unsafe-eval'"],
|
||||
styleSrc: ["'self'", "'unsafe-inline'", 'https://fonts.googleapis.com', 'https://unpkg.com'],
|
||||
imgSrc: ["'self'", 'data:', 'blob:', 'https:'],
|
||||
connectSrc: [
|
||||
"'self'",
|
||||
'ws:',
|
||||
'wss:',
|
||||
'https://nominatim.openstreetmap.org',
|
||||
'https://overpass-api.de',
|
||||
'https://places.googleapis.com',
|
||||
'https://api.openweathermap.org',
|
||||
'https://en.wikipedia.org',
|
||||
'https://commons.wikimedia.org',
|
||||
// Both forms here too: CARTO documents the apex host on its key page,
|
||||
// so that is the template users paste in, and the {s} sharded form is
|
||||
// what TREK ships (#2054).
|
||||
'https://basemaps.cartocdn.com',
|
||||
'https://*.basemaps.cartocdn.com',
|
||||
// Both forms: a CSP wildcard host never matches the apex, and OSM
|
||||
// serves everything from the bare tile.openstreetmap.org since it
|
||||
// retired the a/b/c/d shards (#1733). The sharded hosts stay listed
|
||||
// for tile templates users saved before that.
|
||||
'https://tile.openstreetmap.org',
|
||||
'https://*.tile.openstreetmap.org',
|
||||
// The other two raster presets TREK ships. `mode: 'no-cors'` relaxes
|
||||
// CORS, not CSP, so without these the tile prefetch is refused in the
|
||||
// document and never reaches the Service Worker that would cache it
|
||||
// (#2180). routing.openstreetmap.de below is a different host.
|
||||
'https://tile.openstreetmap.de',
|
||||
'https://tiles.stadiamaps.com',
|
||||
// OpenTopoMap is the key-free raster layer offered only by the Tours
|
||||
// planner. Leaflet uses its a/b/c shards; the apex is named too so a
|
||||
// future unsharded template does not repeat the OSM CSP gap above.
|
||||
'https://tile.opentopomap.org',
|
||||
'https://*.tile.opentopomap.org',
|
||||
// The imagery host, for the same reason and one more. Leaflet fetches a tile
|
||||
// as an <img>, which img-src's blanket `https:` waves through, so the satellite
|
||||
// view worked on Leaflet with this host missing. A GL map reads the raster
|
||||
// through fetch to hand it to WebGL, and the prefetch does too, so both were
|
||||
// refused here while nothing in the app could see it: the switch flipped, the
|
||||
// layer went on, and no tile ever arrived (#2307).
|
||||
'https://server.arcgisonline.com',
|
||||
// Amap's raster tiles, for an install whose users are in China, for the
|
||||
// same reason as the hosts above (#2180). Road (webrd01..04) and
|
||||
// satellite (webst01..04) are numbered shards of one domain, so the
|
||||
// wildcard is the whole list.
|
||||
'https://*.is.autonavi.com',
|
||||
'https://unpkg.com',
|
||||
'https://open-meteo.com',
|
||||
'https://api.open-meteo.com',
|
||||
'https://geocoding-api.open-meteo.com',
|
||||
'https://api.frankfurter.dev',
|
||||
'https://router.project-osrm.org/route/v1/',
|
||||
'https://routing.openstreetmap.de/',
|
||||
// The second routing engine, shipped as a default the same way the OSRM hosts
|
||||
// above are. It is asked only when a leg should avoid tolls, motorways or a
|
||||
// ferry — which the OSRM hosts answer with HTTP 400, because their car profile
|
||||
// carries no excludable classes. Origin only, no path: unlike OSRM this one is
|
||||
// a POST to /route and would grow more endpoints if isochrones ever land.
|
||||
'https://valhalla1.openstreetmap.de',
|
||||
'https://api.mapbox.com',
|
||||
'https://*.tiles.mapbox.com',
|
||||
'https://events.mapbox.com',
|
||||
'https://tiles.openfreemap.org',
|
||||
// A self-hosted routing engine, when the instance has one configured. Without
|
||||
// this the browser blocks it silently: no error the app can catch, just legs
|
||||
// that never route (#1797).
|
||||
...extraConnectSrc,
|
||||
],
|
||||
workerSrc: ["'self'", 'blob:'],
|
||||
childSrc: ["'self'", 'blob:'],
|
||||
// blob: because a picked clip is previewed and its poster frame grabbed
|
||||
// through a <video> on an object URL, before any byte reaches the server.
|
||||
// Unset, this fell back to default-src, which refuses blob: outright: the
|
||||
// editor showed nothing and every clip landed without a poster, so its
|
||||
// thumbnail answered 404 (#2341). Invisible in dev, where Vite serves the
|
||||
// document without this header.
|
||||
mediaSrc: ["'self'", 'blob:'],
|
||||
fontSrc: ["'self'", 'https://fonts.gstatic.com', 'data:'],
|
||||
// 'self' so same-origin file previews can embed PDFs via <object>/<embed>
|
||||
// (Firefox/Chrome enforce object-src; 'none' broke inline PDF previews there).
|
||||
objectSrc: ["'self'"],
|
||||
// 'self' so the app can embed same-origin, sandboxed plugin frames
|
||||
// (/plugin-frame/*). Those frames are sandboxed WITHOUT allow-same-origin,
|
||||
// so they run at an opaque origin and get their own locked-down CSP.
|
||||
frameSrc: ["'self'"],
|
||||
frameAncestors: ["'self'"],
|
||||
// Restrict <form> submission targets (form-action has no default-src
|
||||
// fallback, so it must be set explicitly).
|
||||
formAction: ["'self'"],
|
||||
upgradeInsecureRequests: shouldForceHttps ? [] : null,
|
||||
},
|
||||
},
|
||||
crossOriginEmbedderPolicy: false,
|
||||
hsts: hstsActive ? { maxAge: 31536000, includeSubDomains: hstsIncludeSubdomains } : false,
|
||||
referrerPolicy: { policy: 'strict-origin-when-cross-origin' },
|
||||
}),
|
||||
);
|
||||
|
||||
// The instance's own hostname, when the operator configured one. The redirect
|
||||
// below is a 301, so echoing a client-supplied Host header would let a stranger
|
||||
@@ -400,25 +416,33 @@ export function applyGlobalMiddleware(
|
||||
};
|
||||
// A response the filter had to cut off after its headers went out never
|
||||
// finishes; it is reported when the socket closes, with its failure.
|
||||
res.on('close', AsyncResource.bind(() => {
|
||||
if (reported || res.locals[UNHANDLED_ERROR] === undefined) return;
|
||||
reported = true;
|
||||
logError(`${req.method} ${req.path} aborted after headers ${Date.now() - startedAt}ms ip=${req.ip}${failureSuffix()}`);
|
||||
}));
|
||||
res.on('finish', AsyncResource.bind(() => {
|
||||
reported = true;
|
||||
const ms = Date.now() - startedAt;
|
||||
if (res.statusCode >= 500) {
|
||||
logError(`${req.method} ${req.path} ${res.statusCode} ${ms}ms ip=${req.ip}${failureSuffix()}`);
|
||||
} else if (res.statusCode === 401 || res.statusCode === 403) {
|
||||
logDebug(`${req.method} ${req.path} ${res.statusCode} ${ms}ms ip=${req.ip}`);
|
||||
} else if (res.statusCode >= 400) {
|
||||
logWarn(`${req.method} ${req.path} ${res.statusCode} ${ms}ms ip=${req.ip}`);
|
||||
}
|
||||
const q = Object.keys(req.query).length ? ` query=${JSON.stringify(redact(req.query))}` : '';
|
||||
const b = req.body && Object.keys(req.body).length ? ` body=${JSON.stringify(redact(req.body))}` : '';
|
||||
logDebug(`${req.method} ${req.path} ${res.statusCode} ${ms}ms ip=${req.ip}${q}${b}`);
|
||||
}));
|
||||
res.on(
|
||||
'close',
|
||||
AsyncResource.bind(() => {
|
||||
if (reported || res.locals[UNHANDLED_ERROR] === undefined) return;
|
||||
reported = true;
|
||||
logError(
|
||||
`${req.method} ${req.path} aborted after headers ${Date.now() - startedAt}ms ip=${req.ip}${failureSuffix()}`,
|
||||
);
|
||||
}),
|
||||
);
|
||||
res.on(
|
||||
'finish',
|
||||
AsyncResource.bind(() => {
|
||||
reported = true;
|
||||
const ms = Date.now() - startedAt;
|
||||
if (res.statusCode >= 500) {
|
||||
logError(`${req.method} ${req.path} ${res.statusCode} ${ms}ms ip=${req.ip}${failureSuffix()}`);
|
||||
} else if (res.statusCode === 401 || res.statusCode === 403) {
|
||||
logDebug(`${req.method} ${req.path} ${res.statusCode} ${ms}ms ip=${req.ip}`);
|
||||
} else if (res.statusCode >= 400) {
|
||||
logWarn(`${req.method} ${req.path} ${res.statusCode} ${ms}ms ip=${req.ip}`);
|
||||
}
|
||||
const q = Object.keys(req.query).length ? ` query=${JSON.stringify(redact(req.query))}` : '';
|
||||
const b = req.body && Object.keys(req.body).length ? ` body=${JSON.stringify(redact(req.body))}` : '';
|
||||
logDebug(`${req.method} ${req.path} ${res.statusCode} ${ms}ms ip=${req.ip}${q}${b}`);
|
||||
}),
|
||||
);
|
||||
next();
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user