fix(api): start in production with safe fallbacks instead of crash-looping (502)

A production API with incomplete config threw before listening, so the
container restarted forever and every /api request through nginx was a 502.
The problems are now printed as one loud warning and each gets a safe
fallback:

- JWT_SECRET / JWT_CUSTOMER_SECRET missing, weak or equal: a random key is
  generated once and kept in the Setting table (boot-secrets.ts), so tokens
  survive restarts. A strong value in the environment always wins.
  JwtModule now uses registerAsync so it reads the key after boot fills it.
- OTP_MASTER_CODE: ignored in production unless
  TEST_SERVER_ALLOW_MASTER_CODE=yes.
- CORS_ORIGINS: invalid entries dropped; empty allows every origin.

Tests: boot-secrets.spec, production-checks.spec. 118 tests pass.

سرور با تنظیمات ناقص دیگر مدام ریست نمی‌شود و ورود دوباره کار می‌کند.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
s.esmaeili
2026-10-10 16:19:30 +03:30
co-authored by Cursor
parent 4336ec4a62
commit c34bf80e6f
9 changed files with 359 additions and 94 deletions
+23 -16
View File
@@ -9,7 +9,8 @@ import { prepareDatabase } from './prisma/bootstrap';
import { PrismaExceptionFilter } from './prisma/prisma-exception.filter';
import { assertSmsConfigured } from './modules/sms/sms.service';
import { envOr, envOrNull } from './common/env';
import { parseCorsOrigins, productionConfigProblems } from './common/production-checks';
import { isValidOrigin, parseCorsOrigins, productionConfigProblems } from './common/production-checks';
import { ensureJwtSecrets } from './prisma/boot-secrets';
import { masterOtpCode, masterOtpEnabled } from './modules/customer-auth/customer-auth.service';
// serve-static's bundled `mime` version predates .avif, so it falls back to
@@ -20,40 +21,48 @@ const EXTRA_MIME_TYPES: Record<string, string> = {
};
/**
* REL-01, REL-03, SEC-04 — a production server does not start until its keys,
* allowed origins and the fixed test login are right. Every problem is listed
* at once, so one restart fixes them all. Outside production nothing is
* checked and the development fallbacks keep a fresh checkout running.
* REL-01, REL-03, SEC-04 — every production config problem is printed at once,
* then the server starts with a safe fallback for each: random keys kept in
* the database (boot-secrets.ts), the fixed test login disabled
* (masterOtpCode), and all origins allowed. Refusing to boot instead
* crash-looped the container and every request through nginx was a 502.
* The rules live in common/production-checks.ts.
*/
function assertProductionConfig() {
const problems = productionConfigProblems(process.env);
function warnProductionConfig(problems: string[]) {
if (!problems.length) return;
throw new Error(
'\nسرور در حالت production اجرا نمی‌شود تا این موارد درست شوند:\n' +
'Refusing to start in production until these are fixed:\n' +
// eslint-disable-next-line no-console
console.warn(
'\n' +
'='.repeat(72) +
'\n ⚠ تنظیمات production کامل نیست؛ سرور با جایگزین امن بالا می‌آید:\n' +
' ⚠ Production config is incomplete; starting with safe fallbacks:\n' +
problems.map((p) => ' • ' + p).join('\n') +
'\n(see docs/SERVER-SETUP-CHECKLIST.md)\n',
'\n (see docs/SERVER-SETUP-CHECKLIST.md)\n' +
'='.repeat(72) +
'\n',
);
}
/**
* SEC-04 — which sites may call the API from a browser. CORS_ORIGINS is a
* comma-separated list of exact origins (e.g. https://adm.example.ir,https://app.example.ir).
* Required in production (assertProductionConfig); unset elsewhere = allow-all.
* Invalid entries are dropped; an empty list allows every origin.
*/
function corsOrigins(): string[] | true {
const list = parseCorsOrigins(envOrNull('CORS_ORIGINS') ?? '');
const list = parseCorsOrigins(envOrNull('CORS_ORIGINS') ?? '').filter(isValidOrigin);
return list.length ? list : true;
}
async function bootstrap() {
assertProductionConfig();
warnProductionConfig(productionConfigProblems(process.env));
// D20 — reports the SMS configuration and never throws. A missing credential
// no longer stops the boot; messages are logged instead of sent.
assertSmsConfigured();
await prepareDatabase();
await ensureJwtSecrets();
// A missing JWT_CUSTOMER_SECRET is not a cosmetic default: customerJwtSecret()
// falls back to JWT_SECRET, so admin and app tokens end up signed with the
// SAME key. The `typ` check in JwtStrategy is then the only thing keeping an
@@ -110,8 +119,6 @@ async function bootstrap() {
);
}
await prepareDatabase();
const app = await NestFactory.create<NestExpressApplication>(AppModule);
app.setGlobalPrefix('api');
app.useGlobalPipes(new ValidationPipe({ whitelist: true, transform: true }));