mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-06-19 13:21:46 +00:00
3c040fab11
* fix(share): serve place thumbnails in shared trip links (#1100) Google-sourced place photos are stored as image_url pointing at the JWT-guarded /api/maps/place-photo/:placeId/bytes endpoint, so they 401 for an unauthenticated shared-trip viewer and render as broken images. Rewrite place image_url values in the shared payload to a public, token-scoped proxy (/api/shared/:token/place-photo/:placeId/bytes) and add an unguarded SharedController route that validates the token and that the place belongs to its trip before streaming the cached bytes. Mirrors the existing JourneyPublicController precedent. No client changes needed. * fix(atlas): replace Natural Earth with geoBoundaries for up-to-date regions (#1119) Atlas sourced country and sub-national boundaries from Natural Earth's GitHub `master` at runtime. That data is stale (e.g. it still shows Norway's pre-2020 counties such as Oppland/Hordaland) and depicts some contested territory in unwanted ways (nvkelso/natural-earth-vector#391), so Natural Earth is dropped entirely. - Country borders (admin0) now come from the geoBoundaries CGAZ composite; sub-national regions (admin1) from per-country gbOpen, which carries ISO 3166-2 codes. A new script (server/scripts/build-atlas-geo.mjs) normalizes and quantizes them into committed gzipped bundles under server/assets/atlas, read server-side at runtime (no network at boot, no GitHub CSP allowlist entry). - New GET /addons/atlas/countries/geo serves the country layer; the client fetches it from the API instead of GitHub. - A migration reconciles manually-marked visited_regions against the new bundle (valid code -> keep; region name still matches -> re-code; curated merge crosswalk for renamed reforms; else leave intact), with UNIQUE-safe dedup. bucket_list and visited_countries hold only invariant alpha-2 country codes, so they are untouched. - Attribution added (NOTICE.md + README) per geoBoundaries CC BY 4.0. Closes #1119 * fix(packing): make templates admin-only to create, usable by members Creating a packing-list template was gated only by trip access, so any trip member could create one from the Lists feature, while applying a template silently failed for non-admins because the apply dropdown was populated from the AdminGuard-protected /api/admin/packing-templates endpoint. - save-as-template now returns 403 for non-admins; the Save-as-Template button is hidden unless the user is an admin (both the TripPlanner toolbar and the inline packing header). - add member-accessible GET /api/trips/:tripId/packing/templates so the apply dropdown lists templates for any trip member; client fetches from it instead of the admin endpoint. Closes #1120 Closes #1121 * fix(packing): show bag tracking to non-admin members The global Bag Tracking toggle was only readable via the admin-gated GET /api/admin/bag-tracking, so non-admin trip members got 403 and the weight fields, bag circles, and BAGS sidebar never rendered (#1124). Surface the flag through the already-authenticated GET /api/addons (loaded into the client addon store on app start for every user); the packing hook reads it from the store instead of the admin endpoint. The admin write path stays admin-gated and unchanged.
166 lines
7.6 KiB
TypeScript
166 lines
7.6 KiB
TypeScript
import express, { Request, Response, NextFunction } from 'express';
|
|
import cors from 'cors';
|
|
import helmet from 'helmet';
|
|
import cookieParser from 'cookie-parser';
|
|
import { logDebug, logWarn, logError } from '../services/auditLog';
|
|
import { enforceGlobalMfaPolicy } from './mfaPolicy';
|
|
|
|
/**
|
|
* The global request pipeline shared by the legacy Express app and the NestJS
|
|
* instance. Both mount the *exact same* config so a request hitting a migrated
|
|
* Nest route is protected identically to one hitting the legacy fallback
|
|
* (helmet/CSP, CORS, HSTS, forced-HTTPS, the global MFA policy and request
|
|
* logging). Keeping it in one place is what makes the strangler dispatch
|
|
* behaviourally transparent — and is the prerequisite for retiring Express,
|
|
* since the Nest instance must carry the whole shell on its own.
|
|
*
|
|
* `bodyParser` is opt-out: the Nest instance does its own body parsing, so it
|
|
* passes `false` to avoid parsing the request twice.
|
|
*/
|
|
export function applyGlobalMiddleware(
|
|
app: express.Application,
|
|
opts: { bodyParser?: boolean } = {},
|
|
): void {
|
|
const { bodyParser = true } = opts;
|
|
|
|
// Trust first proxy (nginx/Docker) for correct req.ip
|
|
if (process.env.NODE_ENV?.toLowerCase() === 'production' || process.env.TRUST_PROXY) {
|
|
app.set('trust proxy', Number.parseInt(process.env.TRUST_PROXY) || 1);
|
|
}
|
|
|
|
const allowedOrigins = process.env.ALLOWED_ORIGINS
|
|
? process.env.ALLOWED_ORIGINS.split(',').map(o => o.trim()).filter(Boolean)
|
|
: null;
|
|
|
|
let corsOrigin: cors.CorsOptions['origin'];
|
|
if (allowedOrigins) {
|
|
corsOrigin = (origin: string | undefined, callback: (err: Error | null, allow?: boolean) => void) => {
|
|
if (!origin || allowedOrigins.includes(origin)) callback(null, true);
|
|
else callback(new Error('Not allowed by CORS'));
|
|
};
|
|
} else if (process.env.NODE_ENV?.toLowerCase() === 'production') {
|
|
corsOrigin = false;
|
|
} else {
|
|
corsOrigin = true;
|
|
}
|
|
|
|
const shouldForceHttps = process.env.FORCE_HTTPS?.toLowerCase() === 'true';
|
|
// HSTS is worth enabling any time we're serving production traffic,
|
|
// not only when FORCE_HTTPS is set. Self-hosters behind Traefik /
|
|
// Caddy / Cloudflare Tunnel typically leave FORCE_HTTPS unset (the
|
|
// proxy handles the redirect for them), and the previous "HSTS off by
|
|
// default" meant those instances never advertised HSTS at all.
|
|
//
|
|
// `includeSubDomains` stays OFF by default on purpose: an instance
|
|
// running on an apex domain would otherwise force HTTPS on every
|
|
// sibling subdomain the same operator may still be running over plain
|
|
// HTTP. Operators who want the stricter policy opt in with
|
|
// `HSTS_INCLUDE_SUBDOMAINS=true`.
|
|
const hstsActive = shouldForceHttps || process.env.NODE_ENV === 'production';
|
|
const hstsIncludeSubdomains = process.env.HSTS_INCLUDE_SUBDOMAINS === 'true';
|
|
|
|
// RFC 8414 / RFC 9728 / RFC 7591: discovery docs and DCR are world-readable/writable.
|
|
// /mcp needs open CORS so external MCP clients (ChatGPT, Claude.ai, Inspector) can call it
|
|
// with Bearer tokens from any origin. /oauth/register and /oauth/authorize need it for
|
|
// browser-based DCR/authorization preflights — the global cors({ origin: false }) would
|
|
// answer OPTIONS without Access-Control-Allow-Origin before the SDK's own cors() runs.
|
|
// All /.well-known/* paths get open CORS so clients probing openid-configuration or the
|
|
// RFC 8414 path-suffixed AS metadata form don't get CORS-blocked (they get 404 JSON instead).
|
|
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 })(req, _res, next);
|
|
} else {
|
|
next();
|
|
}
|
|
},
|
|
);
|
|
app.use(cors({ origin: corsOrigin, credentials: true }));
|
|
app.use(helmet({
|
|
contentSecurityPolicy: {
|
|
directives: {
|
|
defaultSrc: ["'self'"],
|
|
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",
|
|
"https://*.basemaps.cartocdn.com", "https://*.tile.openstreetmap.org",
|
|
"https://unpkg.com", "https://open-meteo.com", "https://api.open-meteo.com",
|
|
"https://geocoding-api.open-meteo.com", "https://api.exchangerate-api.com",
|
|
"https://router.project-osrm.org/route/v1/", "https://routing.openstreetmap.de/",
|
|
"https://api.mapbox.com", "https://*.tiles.mapbox.com", "https://events.mapbox.com"
|
|
],
|
|
workerSrc: ["'self'", "blob:"],
|
|
childSrc: ["'self'", "blob:"],
|
|
fontSrc: ["'self'", "https://fonts.gstatic.com", "data:"],
|
|
objectSrc: ["'none'"],
|
|
frameSrc: ["'none'"],
|
|
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' },
|
|
}));
|
|
|
|
if (shouldForceHttps) {
|
|
app.use((req: Request, res: Response, next: NextFunction) => {
|
|
if (req.path === '/api/health') return next();
|
|
if (req.secure || req.headers['x-forwarded-proto'] === 'https') return next();
|
|
res.redirect(301, 'https://' + req.headers.host + req.url);
|
|
});
|
|
}
|
|
|
|
if (bodyParser) {
|
|
app.use(express.json({ limit: '100kb' }));
|
|
app.use(express.urlencoded({ extended: true }));
|
|
}
|
|
app.use(cookieParser());
|
|
app.use(enforceGlobalMfaPolicy);
|
|
|
|
// Request logging with sensitive field redaction
|
|
const SENSITIVE_KEYS = new Set(['password', 'new_password', 'current_password', 'token', 'jwt', 'authorization', 'cookie', 'client_secret', 'mfa_token', 'code', 'smtp_pass']);
|
|
const redact = (value: unknown): unknown => {
|
|
if (!value || typeof value !== 'object') return value;
|
|
if (Array.isArray(value)) return (value as unknown[]).map(redact);
|
|
const out: Record<string, unknown> = {};
|
|
for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
|
|
out[k] = SENSITIVE_KEYS.has(k.toLowerCase()) ? '[REDACTED]' : redact(v);
|
|
}
|
|
return out;
|
|
};
|
|
|
|
app.use((req: Request, res: Response, next: NextFunction) => {
|
|
if (req.path === '/api/health') return next();
|
|
const startedAt = Date.now();
|
|
res.on('finish', () => {
|
|
const ms = Date.now() - startedAt;
|
|
if (res.statusCode >= 500) {
|
|
logError(`${req.method} ${req.path} ${res.statusCode} ${ms}ms ip=${req.ip}`);
|
|
} 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();
|
|
});
|
|
}
|