Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(config): use a CORS origin written with a path as its origin
Yudhi Armyndharis5c3321a009d2
diff --git a/.env.example b/.env.exampleindex 5bf6d7ad6..3b736f1eb 100644--- a/.env.example+++ b/.env.example@@ -96,6 +96,7 @@ STATUS_SEED_ON_READY=false# CORS Configuration: comma-separated allowed origins. The wildcard "*" is allowed# only in development; in production it is REFUSED (cross-origin browser requests are# blocked) — set explicit origin(s) there, e.g. https://dashboard.yourdomain.com+# (an entry's path or trailing slash is dropped, since a browser never sends one in Origin).# CORS_ORIGINS=*# SSL/TLS: terminate TLS at your own reverse proxy (nginx, Caddy, a cloud loaddiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 564adcfbf..9d220646c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -48,6 +48,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- MCP tools refuse a `chatId`, `fromChatId` or `toChatId` over 255 characters, as the send routes do, where PostgreSQL answered an internal tool error.- A start that fails while another start of the same session is in flight leaves the claim to that start, so its engine is no longer left on a row no node holds.- Uninstalling a plugin hands the chats it had taken over back to the bot, so other plugins are no longer silent there.+- A `CORS_ORIGINS` entry written with a path or a trailing slash is used as the origin it names, and a warning at boot lists it, where it matched no `Origin` header.- Index ingress dead letters by delivery id, so the reconciler's per-delivery checks stop scanning every dead letter of an instance; the first boot builds the index.- Replay stranded ingress events past one whose stored payload is not valid JSON, instead of failing every sweep on it.- Hand a chat back to the bot when the plugin instance that took it over is deleted, instead of silencing every other plugin on it.diff --git a/src/config/bootstrap-security.spec.ts b/src/config/bootstrap-security.spec.tsindex a659d651a..780336ad9 100644--- a/src/config/bootstrap-security.spec.ts+++ b/src/config/bootstrap-security.spec.ts@@ -9,6 +9,7 @@ import {isApiKeyPepperMissingInProduction,isMainDbSynchronizeInProduction,isNodeEnvUnset,+ rewrittenCorsOrigins,} from './bootstrap-security';describe('resolveCorsPolicy', () => {@@ -20,6 +21,32 @@ describe('resolveCorsPolicy', () => {});});+ // A browser sends `Origin: https://dashboard.example.com`, never a path or a trailing slash, so an entry+ // copied from the address bar could not match until it is used as the origin it names.+ it('uses an entry written with a path or a trailing slash as its origin', () => {+ expect(+ resolveCorsPolicy('https://dashboard.example.com/, http://localhost:3000/app, https://b.com', 'production'),+ ).toEqual({+ origins: ['https://dashboard.example.com', 'http://localhost:3000', 'https://b.com'],+ allowAnyOrigin: false,+ credentials: true,+ });+ expect(rewrittenCorsOrigins('https://dashboard.example.com/, http://localhost:3000/app, https://b.com')).toEqual([+ 'https://dashboard.example.com/',+ 'http://localhost:3000/app',+ ]);+ expect(rewrittenCorsOrigins(undefined)).toEqual([]);+ });++ it('keeps a wildcard and a value that is not an http(s) URL as written', () => {+ expect(resolveCorsPolicy('*', 'development').origins).toEqual(['*']);+ expect(resolveCorsPolicy('localhost:3000,not a url', 'production').origins).toEqual([+ 'localhost:3000',+ 'not a url',+ ]);+ expect(rewrittenCorsOrigins('*,localhost:3000,not a url')).toEqual([]);+ });+it('honors an explicit allowlist and enables credentials (no wildcard)', () => {expect(resolveCorsPolicy('https://a.com, https://b.com', 'production')).toEqual({origins: ['https://a.com', 'https://b.com'],diff --git a/src/config/bootstrap-security.ts b/src/config/bootstrap-security.tsindex beb15436e..ef20d2c1d 100644--- a/src/config/bootstrap-security.ts+++ b/src/config/bootstrap-security.ts@@ -7,6 +7,29 @@ export interface CorsPolicy {credentials: boolean;}+/**+ * A CORS_ORIGINS entry as a browser sends it in `Origin`: scheme, host and port, with no path or trailing+ * slash. An address copied from the bar of a browser carries both and would never equal a header.+ * Anything that is not an http(s) URL is kept as written.+ */+function asOrigin(entry: string): string {+ if (entry === '*') return entry;+ try {+ const url = new URL(entry);+ return url.protocol === 'http:' || url.protocol === 'https:' ? url.origin : entry;+ } catch {+ return entry;+ }+}++/** The CORS_ORIGINS entries that are used without part of what was written (a path or a trailing slash). */+export function rewrittenCorsOrigins(corsOriginsEnv?: string): string[] {+ return (corsOriginsEnv ?? '')+ .split(',')+ .map(o => o.trim())+ .filter(o => o && asOrigin(o) !== o);+}+/*** Resolves the effective CORS policy from CORS_ORIGINS + NODE_ENV.* - Dev: wildcard allowed (no credentials with wildcard — spec-compliant).@@ -17,7 +40,8 @@ export function resolveCorsPolicy(corsOriginsEnv?: string, nodeEnv?: string): Coconst origins = corsOriginsEnv?.split(',').map(o => o.trim())- .filter(Boolean) ?? ['*'];+ .filter(Boolean)+ .map(asOrigin) ?? ['*'];const hasWildcard = origins.includes('*');// In production a wildcard origin is refused: collapse to same-origin only.diff --git a/src/main.ts b/src/main.tsindex 8eba494df..1ab2bb45c 100644--- a/src/main.ts+++ b/src/main.ts@@ -29,6 +29,7 @@ import {isApiKeyPepperMissingInProduction,isMainDbSynchronizeInProduction,isNodeEnvUnset,+ rewrittenCorsOrigins,} from './config/bootstrap-security';import { BullBoardAuthMiddleware } from './common/security/bull-board-auth.middleware';import { invalidTrustedProxies } from './common/utils/ip';@@ -126,6 +127,15 @@ async function bootstrap() {);}+ // Advisory: an origin copied from the address bar carries a path or a trailing slash that a browser never+ // sends in `Origin`. It is used without them, which is what the operator meant.+ const rewrittenOrigins = rewrittenCorsOrigins(process.env.CORS_ORIGINS);+ if (rewrittenOrigins.length > 0) {+ bootstrapLogger.warn(+ `CORS_ORIGINS entries are used as an origin, without their path or trailing slash: ${rewrittenOrigins.join(', ')}`,+ );+ }+// Fail fast on a media storage root the app cannot write to, BEFORE Nest builds the module graph:// StorageService only checks that the root EXISTS, so a root owned by another user passes boot and// fails later on the first media write instead (#1065). Runs ahead of NestFactory.create so