Add full system audit reports and Telegram Mini App debug handoff

- Three-stream audit (security / logic / performance) with 35+ findings
  derived from actual source code, each with file:line and remediation
- Audit Index cross-references criticals across streams into prioritized
  fix tiers: immediately / before soft launch / before public launch
- Telegram Mini App debug handoff documenting what was implemented and
  all remaining work items with exact file lists and test commands
- Updated architecture, data model, auth API, and registration flow docs
  to reflect Telegram auth, TON wallet, and email verification additions

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Siavash Sameni
2026-05-24 17:20:08 +04:00
parent 2533bedb91
commit 940ad0c655
12 changed files with 1795 additions and 28 deletions

View File

@@ -38,10 +38,11 @@ flowchart TB
subgraph BE["Backend tier — Node.js / Express 5"]
REST["REST API<br/>/api/*"]
SocketS["Socket.IO server<br/>rooms per user / chat / request"]
Auth["Auth service<br/>JWT + Passkey + Google"]
Auth["Auth service<br/>JWT + Passkey + Google + Telegram"]
Market["Marketplace service<br/>Requests, Offers, Templates"]
ChatSvc["Chat service"]
PaySvc["Payment service<br/>+ PaymentCoordinator"]
PaySvc["Payment service<br/>SHKeeper + Request Network + ledger"]
TelegramSvc["Telegram service<br/>bot + Mini App + notifications"]
Disp["Dispute service"]
Points["Points / Referrals"]
BlogSvc["Blog service"]
@@ -65,6 +66,8 @@ flowchart TB
Google["Google OAuth"]
Sentry["Sentry"]
Alchemy["Alchemy RPC"]
TelegramAPI["Telegram Bot API<br/>+ Mini App"]
ReqNet["Request Network<br/>pay-in / webhooks"]
end
Browser --> SSR
@@ -78,20 +81,25 @@ flowchart TB
ClientJS --> REST
SocketC <--> SocketS
REST --> Auth & Market & ChatSvc & PaySvc & Disp & Points & BlogSvc & AISvc & Notif & Files
REST --> Auth & Market & ChatSvc & PaySvc & TelegramSvc & Disp & Points & BlogSvc & AISvc & Notif & Files
SocketS --> ChatSvc & Notif & Market
Auth & Market & ChatSvc & PaySvc & Disp & Points & BlogSvc --> Mongo
Auth & Market & ChatSvc & PaySvc & Disp & Points & BlogSvc & TelegramSvc --> Mongo
Auth & PaySvc & Notif --> RedisDB
Files --> Disk
PaySvc <--> SHK
SHK -.webhook.-> PaySvc
PaySvc <--> ReqNet
ReqNet -.webhook.-> PaySvc
PaySvc --> Chain
Wagmi --> DePay
DePay --> Chain
PaySvc -.tx fetch.-> Alchemy
TelegramSvc <--> TelegramAPI
TelegramAPI -.webhook.-> TelegramSvc
Auth --> TelegramAPI
Notif --> SMTP
Auth --> Google
AISvc --> OpenAI
@@ -103,11 +111,12 @@ flowchart TB
### Authentication & identity — [[Authentication Flow]]
Auth is the gate to every authenticated route. Amn supports three login methods in parallel:
Auth is the gate to every authenticated route. Amn supports four login methods in parallel:
- **Email + password (JWT).** Standard `bcrypt`-hashed credentials, access + refresh token pair, six-digit email verification codes, and password reset codes. Source: `backend/src/services/auth/authService.ts`.
- **Passkey (WebAuthn).** Platform and cross-platform authenticators are registered against the user account; multiple devices per user are stored in `User.passkeys[]` (`backend/src/models/User.ts:125`).
- **Google OAuth.** Server-side verification via `google-auth-library`. See `backend/src/services/auth/googleOAuthService.ts`.
- **Telegram (first-class).** `POST /api/auth/telegram` accepts a Telegram Mini App `initData` string or a Telegram Login Widget payload. The backend verifies the Telegram HMAC signature, then signs the user in or auto-creates a new Amanat account with `authProvider: "telegram"` and no required email. This means a user who opens the Telegram Mini App is authenticated with zero sign-up friction. See `backend/src/services/auth/authController.ts` (`telegramAuth`) and [[Authentication Flow#Telegram first-class auth flow]].
Roles are `admin | buyer | seller` (`backend/src/models/User.ts:94`). Role checks happen in route middleware. **Refresh tokens** are stored on the `User` document and rotated.
@@ -123,13 +132,14 @@ Services live in `backend/src/services/marketplace/` and are exposed through `/a
### Payments — [[Payments Overview]] / [[SHKeeper Integration]]
Payments are where Amn is most distinctive. The backend supports **three payment surfaces** routed through a common `Payment` model (`backend/src/models/Payment.ts`):
Payments are where Amn is most distinctive. The backend supports **four payment surfaces** routed through a common `Payment` model (`backend/src/models/Payment.ts`) via a provider-neutral adapter layer (`backend/src/services/payment/adapters/`):
- **SHKeeper** — `/api/payment/shkeeper`. Mounted at `backend/src/app.ts:327`. Issues a fresh wallet address per invoice, polls / webhooks for payment confirmation, and runs through `PaymentCoordinator` to avoid race conditions where a payment status is updated twice. Health is monitored in the background (`shkeeperHealthCheck.ts`, started in `app.ts:433`).
- **Decentralized (Wagmi + DePay)** — `/api/payment/decentralized`. The user signs and sends the transfer from their own wallet; the backend then verifies the transaction on-chain via `blockchainTxFetcher.ts` and the Alchemy SDK.
- **SHKeeper** — `/api/payment/shkeeper`. Issues a fresh wallet address per invoice, polls / webhooks for payment confirmation, and runs through `PaymentCoordinator` to avoid race conditions. Health is monitored in the background (`shkeeperHealthCheck.ts`).
- **Request Network** — `/api/payment/request-network`. Creates on-chain payment requests via the Request Network protocol, generates Secure Payment Page URLs for the buyer, and receives real-time payment status via signed webhooks (`x-request-network-signature`). Pay-in service: `requestNetworkPayInService.ts`; reconciliation: `requestNetworkReconciliationService.ts`.
- **Decentralized (Wagmi + DePay)** — `/api/payment/decentralized`. The user signs and sends the transfer from their own wallet; the backend verifies on-chain via `blockchainTxFetcher.ts` and the Alchemy SDK.
- **Payout** — `/api/payment/shkeeper/payout`. Admin-triggered release of escrow funds to the seller's wallet once delivery is confirmed.
All three surfaces converge on the same `Payment` record (with `direction: 'in' | 'out' | 'refund'`) and trigger the same downstream events: order status update, notification, points award. **Pending payments are auto-cleaned** by a background timer started in `app.ts:374`.
All surfaces converge on the same `Payment` record (with `direction: 'in' | 'out' | 'refund'`) and share the internal **funds ledger** (`backend/src/services/payment/ledger/`) which tracks available / held / releasable amounts independently of the provider. **Pending payments are auto-cleaned** by a background timer started in `app.ts`.
### Real-time chat — [[Chat System]]
@@ -202,7 +212,7 @@ OpenAI (model configurable per call) is exposed through `/api/ai/*`. The current
## Cross-cutting concerns
- **Observability** — Sentry is initialised at the very top of `app.ts` (line 2-3) and on the frontend in `sentry.{client,edge,server}.config.ts`. Logs flow through `backend/src/utils/logger.ts`.
- **Security** — `helmet`, CORS scoped to `FRONTEND_URL`, JWT with bcrypt-hashed passwords, role-gated middleware. Rate limiting is plumbed but currently disabled (see `app.ts:227`).
- **Security** — `helmet`, CORS scoped to `FRONTEND_URL`, JWT with bcrypt-hashed passwords, role-gated middleware. Rate limiting is active (10 req/15 min on auth, 30 on payment, 100 global; Request Network and Telegram webhooks are skip-listed to avoid false limits).
- **Internationalisation** — Six locales (en, fr, vi, cn, ar, fa), with `fa` as default. RTL via `stylis-plugin-rtl`. See `frontend/src/locales/`.
- **Theming** — MUI v7 with a custom theme in `frontend/src/theme/`. Dark mode is on the roadmap.
- **Containerisation** — Docker Compose stacks for dev and prod live in both repos (`docker-compose.dev.yml`, `docker-compose.production.yml`).

View File

@@ -129,7 +129,7 @@ The backend is `amn-backend@2.6.3-beta`, an Express 5 server in TypeScript backe
| body-parser | ^2.2.0 | Body parsing (legacy fallback) | Body middleware |
| helmet | ^8.1.0 | HTTP security headers | `app.ts:189` |
| cors | ^2.8.5 | Cross-origin policy | `app.ts:194` |
| express-rate-limit | ^8.0.1 | Rate-limit middleware (currently off) | Plumbed in |
| express-rate-limit | ^8.0.1 | Rate-limit middleware | Active — auth 10/15min, payment 30/15min, AI 20/15min, global 100/15min |
| express-validator | ^7.2.1 | Request validation | Auth, marketplace |
| multer | ^2.0.2 | Multipart file uploads | `services/file/` |
| sharp | ^0.34.3 | Image resizing / format conversion | Upload pipeline |
@@ -211,10 +211,12 @@ The backend is `amn-backend@2.6.3-beta`, an Express 5 server in TypeScript backe
| Service | Purpose | Touchpoint in code |
|---|---|---|
| **SHKeeper** | Self-hosted crypto payment processor — issues wallets, watches for incoming USDT, pays out | `backend/src/services/payment/shkeeper/` |
| **Request Network** | On-chain payment request protocol — creates invoices, generates Secure Payment Pages, signs webhooks | `backend/src/services/payment/requestNetwork/` + adapters |
| **DePay** | Drop-in Web3 widget for wallet-to-wallet payment | `@depay/widgets` on frontend |
| **EVM chains** (BSC, Ethereum mainnet, Sepolia, Polygon) | Settlement layer for stablecoin transfers | `frontend/src/web3/config.ts`, backend `blockchain/` |
| **Alchemy RPC** | Hosted EVM RPC + transaction lookup | Frontend `alchemy-sdk`, backend `blockchainTxFetcher.ts` |
| **MetaMask / WalletConnect** | Wallet connectors via Wagmi | `web3/config.ts` (WalletConnect commented out pending SSR fix) |
| **Telegram Bot API + Mini App** | Bot commands, inline keyboards, webhook updates, Mini App launch surface, Login Widget | `backend/src/services/telegram/`, `frontend/src/app/telegram/`, `frontend/src/utils/telegram-webapp.ts` |
| **OpenAI** | LLM for drafting / summarising | `backend/src/services/ai/` |
| **Google OAuth** | Federated login | `googleOAuthService.ts` |
| **SMTP** (provider configured per env) | Transactional email | `services/email/` |