Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(database): refuse a padded DATABASE_TYPE in the migration CLI

Yudhi Armyndharis10f35f5f0e11
diff --git a/src/database/data-source.spec.ts b/src/database/data-source.spec.ts
index dbebfc049..94a137cc0 100644
--- a/src/database/data-source.spec.ts
+++ b/src/database/data-source.spec.ts
@@ -56,6 +56,24 @@ describe('data CLI DataSource', () => {
}
});
+ // Boot rejects a padded selector, but the CLI compared it raw: 'postgres ' from the host env, or
+ // quoted in .env, picked the SQLite options and migrated a file named after the Postgres database.
+ it.each(['postgres ', ' sqlite', 'postgre'])('refuses to load with DATABASE_TYPE %j', value => {
+ const prevType = process.env.DATABASE_TYPE;
+ process.env.DATABASE_TYPE = value;
+ jest.resetModules();
+ try {
+ expect(() => {
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
+ require('./data-source');
+ }).toThrow(`DATABASE_TYPE must be "sqlite" or "postgres" (got ${JSON.stringify(value)})`);
+ } finally {
+ if (prevType !== undefined) process.env.DATABASE_TYPE = prevType;
+ else delete process.env.DATABASE_TYPE;
+ jest.resetModules();
+ }
+ });
+
it('refuses to load a postgres CLI connection with a mixed-case POSTGRES_SCHEMA', () => {
// search_path is unquoted (folded to lower case) while TypeORM quotes the schema, so migration DDL
// and the ledger would land in two different schemas.
diff --git a/src/database/data-source.ts b/src/database/data-source.ts
index 3bd173b22..f4864dca8 100644
--- a/src/database/data-source.ts
+++ b/src/database/data-source.ts
@@ -9,7 +9,16 @@ import { postgresSchemaError, sqliteDataMainPathCollision } from '../config/env.
loadCliEnv();
// The TypeORM CLI never runs ConfigModule's validate(), so the boot-time guards in env.validation
-// don't apply here. The one that matters for a DDL-issuing connection is re-applied explicitly:
+// don't apply here. The selector is checked raw, as boot does: a padded 'postgres ' from the host env,
+// or a quoted one from .env (dotenv keeps the padding inside quotes), would otherwise fail the exact
+// comparison below and migrate a SQLite file named after the database. It runs after loadCliEnv, so
+// both sources reach it.
+const rawDbType = process.env.DATABASE_TYPE;
+if (rawDbType?.trim() && rawDbType !== 'sqlite' && rawDbType !== 'postgres') {
+ throw new Error(`DATABASE_TYPE must be "sqlite" or "postgres" (got ${JSON.stringify(rawDbType)})`);
+}
+
+// The other boot guard that matters for a DDL-issuing connection is re-applied explicitly:
// DATABASE_NAME must not resolve to the main (auth/audit) SQLite file, or data migrations would
// run against the wrong database. Resolved exactly like the runtime (env → default), so the CLI
// and the app make the same call.