API+Front: Host z portem i normalizacja same-origin (przegladarkowy Origin na srodowisku po IP dawal 403 CORS)

This commit is contained in:
Tilumca
2026-10-14 05:05:11 +02:00
parent 359b10443d
commit d5c2c20102
6 changed files with 86 additions and 6 deletions

View File

@@ -8,6 +8,7 @@ import type { AppDeps } from './deps.js';
import { config } from './config.js';
import { logger } from './lib/logger.js';
import { forbidden } from './lib/errors.js';
import { isSameOrigin } from './lib/sameOrigin.js';
import { apiLimiter } from './middleware/rateLimit.js';
import { errorHandler, notFoundHandler } from './middleware/errorHandler.js';
import { openapi } from './swagger.js';
@@ -42,8 +43,8 @@ export function createApp(deps: AppDeps): express.Express {
// Zgadzający się z bieżącym originem nagłówek usuwamy, przez co middleware `cors`
// traktuje request jak bez-origin (pełna semantyka RFC).
app.use((req, _res, next) => {
const own = `${req.protocol}://${req.headers.host ?? ''}`;
if (req.headers.origin && req.headers.origin === own) {
const origin = req.headers.origin;
if (origin && isSameOrigin(origin, req.protocol, req.headers.host)) {
delete req.headers.origin;
}
next();

26
api/src/lib/sameOrigin.ts Normal file
View File

@@ -0,0 +1,26 @@
/**
* Czy nagłówek Origin to dokładnie origin bieżącego requesta (scheme + host + port).
* Notacja originów normalizuje domyślne porty (http:80, https:443) i wielkość liter;
* inne protokoły (albo inny port = inna instancja) to już cross-origin — bez wyjątku.
* Chodzi wyłącznie o requesty same-origin: przeglądarka i tak wysyła Origin dla metod
* niebezpiecznych, a wzorce CORS dotyczą tylko realnych przekroczeń originu.
*/
export function isSameOrigin(originHeader: string, proto: string, hostHeader?: string): boolean {
const normalize = (scheme: string, hostPort: string): string | null => {
const hp = hostPort.trim().toLowerCase();
if (!hp) return null;
const defaultPort = scheme === 'http' ? ':80' : scheme === 'https' ? ':443' : '';
if (defaultPort && hp.endsWith(defaultPort)) return hp.slice(0, -defaultPort.length);
return hp;
};
try {
const url = new URL(originHeader);
const originProto = url.protocol.replace(':', '');
if (originProto !== proto) return false;
const originHost = normalize(originProto, url.host);
const requestHost = normalize(proto, hostHeader ?? '');
return originHost !== null && requestHost !== null && originHost === requestHost;
} catch {
return false;
}
}