fix(security): no dev key, demo seed or open CORS in production (SEC-04, SEC-05)

- production refuses to boot without JWT_SECRET instead of signing
  admin tokens with the published development key
- CORS_ORIGINS restricts browser callers; blank keeps allow-all with a
  production warning so a running deployment is not cut off
- the boot-time seed creates only roles and permissions in production;
  the demo customers, orders, debt and known-password accounts need
  SEED_DEMO_DATA=true

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
s.esmaeili
2026-10-08 11:00:45 +03:30
co-authored by Claude Opus 5.5
parent fb25b2251b
commit 1c850216e9
5 changed files with 111 additions and 29 deletions
+37 -1
View File
@@ -18,7 +18,43 @@ const EXTRA_MIME_TYPES: Record<string, string> = {
'.avif': 'image/avif',
};
/**
* SEC-04 — production must not run on the published development key. Both JWT
* modules fall back to 'dev-only-insecure-secret' (a string anyone can read
* in this repository), with which anyone could mint an admin token. Outside
* production that fallback is kept, so a fresh checkout still runs.
*/
function assertProductionSecrets() {
if (process.env.NODE_ENV !== 'production') return;
if (!envOrNull('JWT_SECRET')) {
throw new Error(
'JWT_SECRET تنظیم نشده است — سرور در حالت production بدون آن اجرا نمی‌شود.\n' +
'JWT_SECRET is not set: refusing to start in production on the public development key.',
);
}
}
/**
* 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).
* Unset keeps the old allow-all, with a warning in production, so an existing
* deployment keeps working until the list is filled in.
*/
function corsOrigins(): string[] | true {
const list = (envOrNull('CORS_ORIGINS') ?? '')
.split(',')
.map((o) => o.trim().replace(/\/+$/, ''))
.filter(Boolean);
if (list.length) return list;
if (process.env.NODE_ENV === 'production') {
console.warn('⚠ CORS_ORIGINS تنظیم نشده — هر سایتی می‌تواند به API درخواست بفرستد. / CORS_ORIGINS is not set: any website may call this API.');
}
return true;
}
async function bootstrap() {
assertProductionSecrets();
// D20 — reports the SMS configuration and never throws. A missing credential
// no longer stops the boot; messages are logged instead of sent.
assertSmsConfigured();
@@ -85,7 +121,7 @@ async function bootstrap() {
app.setGlobalPrefix('api');
app.useGlobalPipes(new ValidationPipe({ whitelist: true, transform: true }));
app.useGlobalFilters(new PrismaExceptionFilter());
app.enableCors();
app.enableCors({ origin: corsOrigins() });
// Uploaded files, mounted OUTSIDE the /api prefix so the URLs stored on
// UploadedFile.url ("/uploads/<name>") resolve directly.
app.useStaticAssets(envOr('UPLOAD_DIR', join(process.cwd(), 'storage', 'uploads')), {