From 1c850216e98cef1d0196a9a4ecd7900b80a1857f Mon Sep 17 00:00:00 2001 From: "s.esmaeili" Date: Thu, 8 Oct 2026 11:00:45 +0330 Subject: [PATCH] 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 --- apps/api/.env.example | 13 +++++++ apps/api/prisma/seed.ts | 80 +++++++++++++++++++++++++++-------------- apps/api/src/main.ts | 38 +++++++++++++++++++- docker-compose.yml | 5 +++ docs/parity/ISSUES.md | 4 +-- 5 files changed, 111 insertions(+), 29 deletions(-) diff --git a/apps/api/.env.example b/apps/api/.env.example index 29837ac..e8661a2 100644 --- a/apps/api/.env.example +++ b/apps/api/.env.example @@ -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= diff --git a/apps/api/prisma/seed.ts b/apps/api/prisma/seed.ts index 758916c..d14b99b 100644 --- a/apps/api/prisma/seed.ts +++ b/apps/api/prisma/seed.ts @@ -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) ──────────────────── diff --git a/apps/api/src/main.ts b/apps/api/src/main.ts index 45e89a9..baa74dd 100644 --- a/apps/api/src/main.ts +++ b/apps/api/src/main.ts @@ -18,7 +18,43 @@ const EXTRA_MIME_TYPES: Record = { '.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/") resolve directly. app.useStaticAssets(envOr('UPLOAD_DIR', join(process.cwd(), 'storage', 'uploads')), { diff --git a/docker-compose.yml b/docker-compose.yml index aa38d89..590ff0b 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -37,6 +37,11 @@ services: - JWT_EXPIRES_IN=${JWT_EXPIRES_IN:-} - JWT_CUSTOMER_SECRET=${JWT_CUSTOMER_SECRET:-} - JWT_CUSTOMER_EXPIRES_IN=${JWT_CUSTOMER_EXPIRES_IN:-} + # SEC-04: comma-separated browser origins allowed to call the API + # (e.g. https://adm.example.ir,https://app.example.ir). Blank = any. + - CORS_ORIGINS=${CORS_ORIGINS:-} + # SEC-05: demo seed data is never created in production unless "true". + - SEED_DEMO_DATA=${SEED_DEMO_DATA:-} # ⚠ DELIVERY ONLY — a fixed OTP that signs in ANY active customer. # Empty/unset disables it, which is the correct state for production. # See ISSUES REL-01. Must be exactly 4 digits to be typable in the apps. diff --git a/docs/parity/ISSUES.md b/docs/parity/ISSUES.md index f583e12..438275a 100644 --- a/docs/parity/ISSUES.md +++ b/docs/parity/ISSUES.md @@ -21,8 +21,8 @@ Severity: `Critical` (money loss / security / data loss) · `High` · `Medium` | SEC-08 | ~~Critical~~ **FIXED — hotfix stage 2** | TGT `apps/api/src/modules/customers/customers.service.ts:6-23,44-50` + `customers.controller.ts:10` (`@Public()`) | **Full customer book exposed to anonymous callers.** Login downloads `GET /customers` and matches the phone client-side, so the endpoint returns **every** active customer with `fullName`, `mobile`, **`nationalCode`**, `goldDebtGrams`, `fiatDebtRial`, `goldCreditLimitGrams`, and the URLs of **national-ID / business-licence / shop scans** (and `GET uploads/:filename` is public too, so those URLs resolve). `passwordHash` is correctly excluded. Not possible in the reference, where `userVerfiy` returned **one** customer after the code matched. | Read `customers.service.ts:5-23`; `DECISIONS.md` D8 | ✅ Closed. The whole controller is deleted — no route accepts a customer id any more. Reads moved to token-derived `/customer/me*`. Stage 1 had only narrowed the fields, which left the ids and the `:id` routes exposed. | | SEC-09 | ~~Critical~~ **FIXED — hotfix stage 1** | TGT `apps/api/src/modules/accounting/accounting.controller.ts:7` | `@Public()` on the whole accounting controller exposes **5 routes, 4 of them writes**: reconcile a balance, record a gold repayment, record a rial repayment, confirm a ledger entry. Faithful to the reference (whose admin routes were all unauthenticated) but contradicts the confirmed decision D1. | `DECISIONS.md` §"@Public audit" group A | ✅ Done: rids `wallet.list`, `wallet.charge`, `document.create` ×2, `document.list.confirm`. Verified 401/403/pass-through by `apps/api/scripts/auth-smoke.sh`. | | SEC-10 | ~~High~~ **FIXED — hotfix stage 1** | TGT `apps/api/src/modules/orders/orders.controller.ts:22` | `PATCH orders/:id/status` is public **and** its DTO accepts a client-supplied `actorAdminUserId`, so an anonymous caller can move an order's status and attribute it to any admin. In the reference this was an admin operation. | `DECISIONS.md` §"@Public audit" B3 | ✅ Done: `order.list.sts.submit`. Had no caller — the admin panel uses `admin/orders/status`. | -| SEC-04 | High | TGT `apps/api` (two files) | `JWT_SECRET` falls back to `'dev-only-insecure-secret'` and is absent from `.env.example`. `enableCors()` is wide open. | Reported by api inventory; see `_inv-tgt-api.md` §11. | Require the env var at boot; restrict CORS origins. | -| SEC-05 | High | TGT `apps/api/prisma/seed.ts` | Seed creates a SUPER_ADMIN (`09128081392`) whose **password equals the phone number**, holding all 144 rids. Marked DEV-ONLY in comments but lives in the normal seed. | `docs/CHANGELOG-PORT-HISTORY.md` §4 documents this as intentional for dev. | Gate behind an explicit env flag so it can never run outside dev. | +| SEC-04 | ~~High~~ **FIXED 2026-10-08** — production (`NODE_ENV=production`) refuses to boot without `JWT_SECRET`; CORS reads `CORS_ORIGINS` (exact origins, comma-separated), blank = allow-all with a boot warning in production. Verified: boot refused with a blank key in production only; a listed origin gets `Access-Control-Allow-Origin`, an unlisted one does not. | TGT `apps/api` (two files) | `JWT_SECRET` falls back to `'dev-only-insecure-secret'` and is absent from `.env.example`. `enableCors()` is wide open. | Reported by api inventory; see `_inv-tgt-api.md` §11. | Require the env var at boot; restrict CORS origins. | +| SEC-05 | ~~High~~ **FIXED 2026-10-08** — worse than logged: the app runs the seed once on a fresh database at boot (`bootstrap.ts`), and the WHOLE seed was demo data (sample customers, products, orders, posted debt, and admin accounts with known passwords). Now only roles + permissions run in production; the rest needs `SEED_DEMO_DATA=true`. ⚠ Any deployment that already booted on an empty database has these demo rows and must be checked. | TGT `apps/api/prisma/seed.ts` | Seed creates a SUPER_ADMIN (`09128081392`) whose **password equals the phone number**, holding all 144 rids. Marked DEV-ONLY in comments but lives in the normal seed. | `docs/CHANGELOG-PORT-HISTORY.md` §4 documents this as intentional for dev. | Gate behind an explicit env flag so it can never run outside dev. | | SEC-06 | High | REF `henza_server` | Hardcoded secrets committed to the repo: SMS panel password, PayPing bearer token, Tahesab bearer + IP allowlist, wallet hash pepper (`"yhoenszeaf"`). | See `_inv-ref-server.md` §11.4. | Rotate all of them before any deployment that reuses these credentials. | | SEC-07 | Medium | TGT `apps/api/src/modules/admin-customers/admin-customers.service.ts` | `setRoles` stores arbitrary strings as rids with no validation against `ALL_RIDS`. | api inventory §9. | Validate against the rid catalogue. |