A self-hosted UPI & COD payment gateway with zero per-transaction platform fees, universal JavaScript checkout integration, dynamic QR payments, WhatsApp OTP authentication, and automated payment verification.
JavaScript
docs(security): safer default configuration and explicit residual risk register
SHIVANSHU SATYAJEETfdee1a599610
diff --git a/.env.example b/.env.exampleindex 1519b1c..c6bcb08 100644--- a/.env.example+++ b/.env.example@@ -29,19 +29,25 @@ BASE_DEMO_STORE_URL=http://localhost:5000# --- DATABASE CONFIGURATION ---# PostgreSQL connection string:-DATABASE_URL=postgresql://postgres:postgres@localhost:5432/youpi_pg+# DATABASE_URL=postgresql://YOUR_USER:YOUR_PASSWORD@YOUR_HOST:5432/youpi_pg# SQLite local file fallback for instant zero-dependency testing:USE_SQLITE_FALLBACK=trueSQLITE_DB_PATH=./data/youpi_pg.sqlite# --- CRYPTOGRAPHIC SECRETS (Generate using crypto.randomBytes(32).toString('hex')) ---# Master 256-bit encryption key for sensitive records (OAuth tokens, device keys):-ENCRYPTION_MASTER_KEY=REPLACE_WITH_64_RANDOM_HEX_CHARS_GENERATED_BY_crypto_randomBytes_32+# By default a random key is generated and saved under data/.secrets/.+# For managed deployments set a stable, strong key OUTSIDE version control.+# ENCRYPTION_MASTER_KEY=YOUR_GENERATED_64_HEX_CHAR_KEY# Session & JWT secret:-JWT_SECRET=super_secret_jwt_key_change_in_production_min_32_chars+# Do not deploy a shared or published JWT signing secret.+# JWT_SECRET=YOUR_LONG_RANDOM_SECRET# Default Admin credentials for initial setup:-INITIAL_ADMIN_PASSWORD=AdminSecurePassword123!+# The service authenticates API administration with ADMIN_API_TOKEN.+# It generates a random persisted token by default. Do not ship default passwords.+# ADMIN_API_TOKEN=YOUR_RANDOM_64_HEX_CHAR_TOKEN+# INITIAL_ADMIN_EMAIL=YOUR_ADMIN_EMAIL+# INITIAL_ADMIN_PASSWORD=YOUR_UNIQUE_STRONG_PASSWORD# --- TIMING & QUEUE ENGINE CONSTANTS ---# Payment active window (milliseconds, default 5 minutes = 300000):diff --git a/README.md b/README.mdindex dd675d1..5c5699a 100644--- a/README.md+++ b/README.md@@ -75,6 +75,8 @@ A newly terminal payment creates a SQLite **payment_webhook_outbox** entry throuThis mitigation does **not** resolve alert spoofing, UPI settlement validation, late and misattributed credits, legal/regulatory obligations, refund disputes or full production readiness.+For the implementation status and residual risk register, see [SECURITY_AUDIT.md](SECURITY_AUDIT.md).+### Before any deployment- Run `npm test` and review the CI results; perform controlled crash/restart and observation-replay testing using synthetic data.@@ -209,7 +211,7 @@ Rebrand the checkout portal completely through the Merchant Admin Panel:### 8. 5 Standardized Merchant Outcome PagesThe application includes the following customer outcome pages:- `/order-success` — Payment verified by observers, order marked paid and provisioned.-- `/order-failed` — Verification timed out, reassuring customer no money was lost.+- `/order-failed` — Verification timed out; payment may still settle, so provide reconciliation/support rather than claiming no money was lost.- `/order-suspicious` — Flagged by fraud heuristics, held for manual compliance review.- `/order-expired` — 5-minute session elapsed, slot released for queued customers.- `/order-cancelled` — Customer cancelled checkout session.diff --git a/SECURITY_AUDIT.md b/SECURITY_AUDIT.mdnew file mode 100644index 0000000..2a8c345--- /dev/null+++ b/SECURITY_AUDIT.md@@ -0,0 +1,40 @@+# YouPI-PG security & bug-fix status++**Status: EXPERIMENTAL; NOT APPROVED FOR REAL-MONEY PRODUCTION.**+Scope is limited to the fork's `security/webhook-durability-hardening` branch.+This is a targeted static review, not an exhaustive independent penetration test or UPI settlement certification.++## Implemented in this branch++| Area | Source | What changed |+| --- | --- | --- |+| Terminal event durability | `packages/db/src/sqlite-schema.sql`, `schema.sql` | An outbox trigger writes a terminal event in the same SQLite status-update transaction. Migrating existing database records does not enqueue historical terminal orders. |+| Crash-safe dispatch | `packages/core/src/webhook-engine.js` | Persist delivery body, ID and retry lease **before** sending HTTP; update result after response. Existing deliveries suppress duplicate event sends. |+| Startup recovery | `apps/payment-api/src/index.js` | Drain missing outbox deliveries on boot and during the periodic worker; existing pending deliveries continue retrying. |+| Regression coverage | `packages/core/src/__tests__/webhook-outbox-durability.test.js` | Synthetic pre-fetch persistence, pending outbox replay, duplicate prevention and unchanged body/ID retry. |+| Safer configuration templates | `.env.example`, `packages/common/src/secrets.js` | Remove published password/secret defaults, generate local service secrets when unset and restrict POSIX secret-directory/file permissions. |+| Documentation | `README.md`, `ARCHITECTURE.md` | Align runtime with Node 24 and correct claims about timed-out payment verification. |++## Deployment blockers / unresolved areas++1. **Bank settlement is not proven by notification parsing.** An SMS/email/push alert, an amount match, a browser callback or an HMAC webhook does not establish settlement. Require official bank-statement/API reconciliation with human handling for ambiguous cases.+2. **Payment attribution needs adversarial testing.** Duplicate UTR, wrong sender/account, reused amount, spoofed notification, expired session, delayed alert and restart races require traceable integration tests; no production certification has been performed.+3. **Webhook at-least-once semantics:** merchants must verify raw-body signatures, delivery freshness, expected payment/order/amount and deduplicate by `X-Gateway-Delivery-Id`. A receiver can commit before the sender receives an ACK; retry is possible.+4. **Unconfigured/invalid webhook endpoints:** events can remain in the outbox or produce undeliverable audit rows. Implement operational dashboards, manual replay after correction, alerts on backlog and exhausted retries.+5. **Network egress/SSRF:** URL validation is present, but DNS rebinding, private DNS resolutions and outbound firewall isolation have not been independently assessed. Enforce egress controls and trusted HTTPS receiver hosts.+6. **Secrets and account security:** audit every production token, API key, bank observer/OAuth credential and historical Git commit for exposure. Rotation and controlled migration of data encrypted under the old master key require an operational plan.+7. **PII/OTP and devices:** assess observer permissions, SMS/notification content retention, OTP rate limits, device revocation and lost-device behavior.+8. **Compliance and operations:** verify receiving-account terms, UPI/NPCI/banking requirements, legal role, refunds/chargebacks, backups/WAL restore, incident response and fraud reconciliation.+9. **CI not verified here:** run `npm ci`, `npm run typecheck`, `npm run build`, `npm test`, `npm audit --omit=dev --audit-level=high` and Android APK build/verification before merging. GitHub Actions availability on forks may require explicit enabling.++## Synthetic verification plan++- Transition an ACTIVE synthetic session to EXPIRED or a PROCESSING session to SUCCESS; assert exactly one `payment_webhook_outbox` row.+- Stop the API immediately after terminal DB commit but before dispatch; restart with the **same SQLite file**, ensure an eventual durable delivery appears.+- Block an HTTP webhook response; SIGKILL the API; restart and confirm the pending delivery has the **same** ID, timestamp and exact body; merchant deduplication must reject double fulfillment.+- Inject repeated observation data, altered amounts, reused UTR and out-of-order notifications; never treat a questionable event as settled without independent reconciliation.+- Run all tests with synthetic identities and localhost receivers, with no real bank accounts, phone data, OAuth tokens or live money.++## Merge policy++Keep this PR in **draft** until tests and a reviewer validate the behavior. It is not appropriate to merge or deploy based solely on this change list.diff --git a/packages/common/src/secrets.js b/packages/common/src/secrets.jsindex 67494c1..539520a 100644--- a/packages/common/src/secrets.js+++ b/packages/common/src/secrets.js@@ -26,7 +26,7 @@ export function resolveSecret(name, envVar) {let value = '';try { value = fs.readFileSync(file, 'utf8').trim(); } catch {}if (!value) {- fs.mkdirSync(SECRETS_DIR, { recursive: true });+ fs.mkdirSync(SECRETS_DIR, { recursive: true, mode: 0o700 });const fresh = crypto.randomBytes(32).toString('hex');try {fs.writeFileSync(file, fresh, { flag: 'wx', mode: 0o600 });@@ -36,6 +36,10 @@ export function resolveSecret(name, envVar) {value = fs.readFileSync(file, 'utf8').trim();}}+ // Harden permissions for pre-existing stores as well as freshly generated keys.+ // chmod can be unavailable on some hosts (e.g. Windows), so fail best-effort here.+ try { fs.chmodSync(SECRETS_DIR, 0o700); } catch {}+ try { fs.chmodSync(file, 0o600); } catch {}cache.set(name, value);return value;}