Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(config): validate numeric env vars at boot; default Swagger off in production (#402)

Yudhi Armyndharisa6abfb73d8f1
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0d0059a0f..984180b0c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -43,9 +43,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
ledger and synchronize policy — against one file, risking schema divergence and lock contention.
Startup validation now fails fast with a clear message (paths are normalized, so relative spellings
of the same file are caught). Postgres is unaffected (its `DATABASE_NAME` is a bare db name). (#399)
+- **Numeric environment variables are validated at boot.** The rate-limit windows/limits, webhook
+ timeout/retry settings, and the database pool size were parsed with an unbounded `parseInt`; a
+ non-integer value (e.g. `RATE_LIMIT_SHORT_LIMIT=abc`) became `NaN` and silently disabled the
+ corresponding limit. Startup now rejects a non-negative-integer violation with a clear message,
+ consistent with the existing port validation. (#402)
### Security
+- **Swagger UI (`/api/docs`) now defaults OFF in production.** The interactive API schema was served
+ unauthenticated by default everywhere; it is reconnaissance surface. It remains on outside
+ production and can be re-enabled in production with `ENABLE_SWAGGER=true` (and is still disabled
+ anywhere with `ENABLE_SWAGGER=false`). The startup banner only advertises the docs URL when it is
+ actually served. (#402)
- **Plugin inventory, detail, and health reads now require the ADMIN role.** `GET /plugins`,
`GET /plugins/:id`, and `GET /plugins/:id/health` were readable by any authenticated key (including
the read-only VIEWER role), exposing installed plugin versions, non-secret configuration, and
diff --git a/src/config/bootstrap-security.spec.ts b/src/config/bootstrap-security.spec.ts
index 1e9f1053e..1ec396032 100644
--- a/src/config/bootstrap-security.spec.ts
+++ b/src/config/bootstrap-security.spec.ts
@@ -52,6 +52,14 @@ describe('isSwaggerEnabled', () => {
expect(isSwaggerEnabled('true')).toBe(true);
expect(isSwaggerEnabled('')).toBe(true);
});
+ it('defaults OFF in production unless explicitly enabled (recon hygiene)', () => {
+ expect(isSwaggerEnabled(undefined, 'production')).toBe(false);
+ expect(isSwaggerEnabled('', 'production')).toBe(false);
+ expect(isSwaggerEnabled('true', 'production')).toBe(true); // explicit opt-in still honored
+ expect(isSwaggerEnabled('false', 'production')).toBe(false);
+ // non-production is unchanged (default on)
+ expect(isSwaggerEnabled(undefined, 'development')).toBe(true);
+ });
});
describe('resolveBodyLimit', () => {
diff --git a/src/config/bootstrap-security.ts b/src/config/bootstrap-security.ts
index 65bd0eb1a..5e75d2ad1 100644
--- a/src/config/bootstrap-security.ts
+++ b/src/config/bootstrap-security.ts
@@ -33,9 +33,15 @@ export function resolveCorsPolicy(corsOriginsEnv?: string, nodeEnv?: string): Co
};
}
-/** Swagger UI is served unless ENABLE_SWAGGER=false (default on, backward compatible). */
-export function isSwaggerEnabled(enableSwaggerEnv?: string): boolean {
- return enableSwaggerEnv !== 'false';
+/**
+ * Whether to serve the Swagger UI (/api/docs). An explicit ENABLE_SWAGGER wins ('true'/'false').
+ * When unset, it defaults ON outside production but OFF in production — the public API schema is
+ * reconnaissance surface, so production must opt in with ENABLE_SWAGGER=true.
+ */
+export function isSwaggerEnabled(enableSwaggerEnv?: string, nodeEnv?: string): boolean {
+ if (enableSwaggerEnv === 'true') return true;
+ if (enableSwaggerEnv === 'false') return false;
+ return nodeEnv !== 'production';
}
/** Request body-size cap (DoS hardening). Default is media-aware (base64 sends ride in the JSON body). */
diff --git a/src/config/env.validation.spec.ts b/src/config/env.validation.spec.ts
index f925fbe5c..4936696fc 100644
--- a/src/config/env.validation.spec.ts
+++ b/src/config/env.validation.spec.ts
@@ -36,6 +36,18 @@ describe('validateEnv', () => {
expect(() => validateEnv({ STORAGE_TYPE: 's3' })).not.toThrow();
});
+ it('rejects a non-integer rate-limit / webhook / pool-size value (a NaN silently disables throttling)', () => {
+ expect(() => validateEnv({ RATE_LIMIT_SHORT_LIMIT: 'abc' })).toThrow(/RATE_LIMIT_SHORT_LIMIT/);
+ expect(() => validateEnv({ WEBHOOK_TIMEOUT: '10s' })).toThrow(/WEBHOOK_TIMEOUT/);
+ expect(() => validateEnv({ DATABASE_POOL_SIZE: '1.5' })).toThrow(/DATABASE_POOL_SIZE/);
+ expect(() => validateEnv({ RATE_LIMIT_LONG_TTL: '-5' })).toThrow(/RATE_LIMIT_LONG_TTL/);
+ // valid integers (and unset) still pass
+ expect(() =>
+ validateEnv({ RATE_LIMIT_SHORT_LIMIT: '10', WEBHOOK_TIMEOUT: '10000', DATABASE_POOL_SIZE: '10' }),
+ ).not.toThrow();
+ expect(() => validateEnv({})).not.toThrow();
+ });
+
it('rejects a sqlite data DB path that collides with the internal main database file', () => {
// The 'main' (auth/audit) and 'data' connections must be separate SQLite files; sharing one
// file means two migration ledgers + synchronize policies on the same tables.
diff --git a/src/config/env.validation.ts b/src/config/env.validation.ts
index 497b458ed..2e2a4f497 100644
--- a/src/config/env.validation.ts
+++ b/src/config/env.validation.ts
@@ -68,6 +68,31 @@ export function validateEnv(config: EnvConfig): EnvConfig {
checkPort('DATABASE_PORT');
checkPort('REDIS_PORT');
+ // Other numeric knobs: a non-integer (e.g. `RATE_LIMIT_SHORT_LIMIT=abc`) parses to NaN downstream,
+ // which silently disables the corresponding limit/timeout. Reject at boot instead of coercing.
+ const checkNonNegativeInt = (key: string): void => {
+ const raw = str(key);
+ if (raw === undefined) return;
+ const n = Number(raw);
+ if (!Number.isInteger(n) || n < 0) {
+ errors.push(`${key} must be a non-negative integer (got "${raw}")`);
+ }
+ };
+ for (const key of [
+ 'RATE_LIMIT_SHORT_TTL',
+ 'RATE_LIMIT_SHORT_LIMIT',
+ 'RATE_LIMIT_MEDIUM_TTL',
+ 'RATE_LIMIT_MEDIUM_LIMIT',
+ 'RATE_LIMIT_LONG_TTL',
+ 'RATE_LIMIT_LONG_LIMIT',
+ 'WEBHOOK_TIMEOUT',
+ 'WEBHOOK_MAX_RETRIES',
+ 'WEBHOOK_RETRY_DELAY',
+ 'DATABASE_POOL_SIZE',
+ ]) {
+ checkNonNegativeInt(key);
+ }
+
if (errors.length > 0) {
throw new Error(`Invalid environment configuration:\n - ${errors.join('\n - ')}`);
}
diff --git a/src/main.ts b/src/main.ts
index 78a0c210c..1e40267dd 100644
--- a/src/main.ts
+++ b/src/main.ts
@@ -220,8 +220,10 @@ async function bootstrap() {
}),
);
- // Swagger documentation (gated by ENABLE_SWAGGER; default on)
- if (isSwaggerEnabled(process.env.ENABLE_SWAGGER)) {
+ // Swagger documentation. ENABLE_SWAGGER wins; otherwise default on outside production, off in
+ // production (the API schema is reconnaissance surface — production opts in with ENABLE_SWAGGER=true).
+ const swaggerEnabled = isSwaggerEnabled(process.env.ENABLE_SWAGGER, process.env.NODE_ENV);
+ if (swaggerEnabled) {
const config = createSwaggerConfig();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api/docs', app, document);
@@ -240,7 +242,9 @@ async function bootstrap() {
await app.listen(port);
console.log(`🚀 OpenWA is running on: http://localhost:${port}`);
- console.log(`📚 Swagger docs: http://localhost:${port}/api/docs`);
+ if (swaggerEnabled) {
+ console.log(`📚 Swagger docs: http://localhost:${port}/api/docs`);
+ }
// Make the dashboard-serving outcome explicit so a missing build (no UI on `/`)
// is obvious instead of a silent 404.