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
+13
View File
@@ -51,3 +51,16 @@ SMS_ADMIN_RECIPIENTS=
ACCOUNTING_SECRET_KEY=
# "off" keeps this instance out of the background sync.
ACCOUNTING_WORKER=
# SEC-04 — browser origins allowed to call the API, comma-separated, exact
# (e.g. https://adm.example.ir,https://app.example.ir). Blank = any origin
# (development); in production a blank list prints a warning at boot.
# In production (NODE_ENV=production) JWT_SECRET is REQUIRED: the API refuses
# to start on the built-in development key.
CORS_ORIGINS=
# SEC-05 — the seed runs once on a fresh database at boot. In production it
# creates roles and permissions only; set "true" to force the demo data
# (sample customers, orders, debt and known-password accounts). Never in a
# real deployment.
SEED_DEMO_DATA=
+54 -26
View File
@@ -28,32 +28,12 @@ const DEV_TEST_PHONE_PASSWORD_HASH = bcrypt.hashSync(DEV_TEST_PHONE, 10);
// Replace these rows with real photo URLs when product photography exists.
const PLACEHOLDER_PRODUCT_IMAGE = '/img/no-items.png';
async function main() {
// ── Cities ────────────────────────────────────────────────────────────
const [tehran, mashhad, isfahan, tabriz] = await Promise.all([
prisma.city.upsert({ where: { id: 'city-tehran' }, update: {}, create: { id: 'city-tehran', name: 'تهران', province: 'تهران' } }),
prisma.city.upsert({ where: { id: 'city-mashhad' }, update: {}, create: { id: 'city-mashhad', name: 'مشهد', province: 'خراسان رضوی' } }),
prisma.city.upsert({ where: { id: 'city-isfahan' }, update: {}, create: { id: 'city-isfahan', name: 'اصفهان', province: 'اصفهان' } }),
prisma.city.upsert({ where: { id: 'city-tabriz' }, update: {}, create: { id: 'city-tabriz', name: 'تبریز', province: 'آذربایجان شرقی' } }),
]);
// ── Branches & workshop ──────────────────────────────────────────────
const branchTehran = await prisma.branch.upsert({
where: { id: 'branch-tehran-bazaar' },
update: {},
create: { id: 'branch-tehran-bazaar', name: 'شعبه بازار بزرگ تهران', cityId: tehran.id },
});
const branchMashhad = await prisma.branch.upsert({
where: { id: 'branch-mashhad-main' },
update: {},
create: { id: 'branch-mashhad-main', name: 'شعبه مرکزی مشهد', cityId: mashhad.id },
});
await prisma.workshop.upsert({
where: { id: 'workshop-central' },
update: {},
create: { id: 'workshop-central', name: 'کارگاه مرکزی ساخت طلا' },
});
/**
* Role definitions and their permissions — the one part of this file a real
* deployment needs (the admin screens and the legacy import map onto these
* ids). Idempotent: upserts and skipDuplicates only.
*/
async function seedAccessControl() {
// ── Admin user types + permissions (legacy `permission(rid, ut)`) ────
//
// In legacy these lived in the dynamic `config_static` lookup under the key
@@ -108,6 +88,54 @@ async function main() {
skipDuplicates: true,
});
}
}
/**
* Everything below is DEMO data: sample cities, branches, accounts with known
* passwords (one super admin whose password is its own phone number), sample
* customers, products, orders and posted debt. The app runs this seed once on
* a fresh database at boot (src/prisma/bootstrap.ts), so without this gate a
* production first boot would mix fake customers, fake debt and open admin
* accounts into the real data (SEC-05). Production never gets it unless
* SEED_DEMO_DATA=true is set on purpose.
*/
function demoDataAllowed(): boolean {
if (process.env.SEED_DEMO_DATA?.trim() === 'true') return true;
return process.env.NODE_ENV !== 'production';
}
async function main() {
await seedAccessControl();
if (!demoDataAllowed()) {
console.log('seed: production — roles and permissions only; demo data skipped (set SEED_DEMO_DATA=true to force)');
return;
}
// ── Cities ────────────────────────────────────────────────────────────
const [tehran, mashhad, isfahan, tabriz] = await Promise.all([
prisma.city.upsert({ where: { id: 'city-tehran' }, update: {}, create: { id: 'city-tehran', name: 'تهران', province: 'تهران' } }),
prisma.city.upsert({ where: { id: 'city-mashhad' }, update: {}, create: { id: 'city-mashhad', name: 'مشهد', province: 'خراسان رضوی' } }),
prisma.city.upsert({ where: { id: 'city-isfahan' }, update: {}, create: { id: 'city-isfahan', name: 'اصفهان', province: 'اصفهان' } }),
prisma.city.upsert({ where: { id: 'city-tabriz' }, update: {}, create: { id: 'city-tabriz', name: 'تبریز', province: 'آذربایجان شرقی' } }),
]);
// ── Branches & workshop ──────────────────────────────────────────────
const branchTehran = await prisma.branch.upsert({
where: { id: 'branch-tehran-bazaar' },
update: {},
create: { id: 'branch-tehran-bazaar', name: 'شعبه بازار بزرگ تهران', cityId: tehran.id },
});
const branchMashhad = await prisma.branch.upsert({
where: { id: 'branch-mashhad-main' },
update: {},
create: { id: 'branch-mashhad-main', name: 'شعبه مرکزی مشهد', cityId: mashhad.id },
});
await prisma.workshop.upsert({
where: { id: 'workshop-central' },
update: {},
create: { id: 'workshop-central', name: 'کارگاه مرکزی ساخت طلا' },
});
// ── Admin users (sales agents + one super admin) ────────────────────
+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')), {