# Telegram Task Earning

## Phase 01 — Final Requirements & Configuration Map

| Document field   | Value                                                |
| ---------------- | ---------------------------------------------------- |
| Status           | **Implementation baseline v1.0**                     |
| Phase            | 01 of 20                                             |
| Last updated     | 2026-09-03                                           |
| Primary market   | Bangladesh                                           |
| Default language | Bangla (`bn`)                                        |
| Default timezone | `Asia/Dhaka`                                         |
| Default currency | Bangladeshi Taka (`BDT`, `৳`)                        |
| Application type | Telegram Mini App + Telegram Bot + Web Admin Panel   |
| Backend          | Node.js + Express                                    |
| Database         | MySQL/InnoDB                                         |
| Cache and queue  | Redis, with documented degraded-mode behavior        |
| Frontend         | EJS shells + local modular JavaScript + compiled CSS |

> This document is the authoritative product contract for the following implementation phases. If code and this document disagree, the implementation must be corrected or this document must be explicitly revised with a decision-log entry.

---

## 1. Product definition

The product is a secure, mobile-first Telegram Mini App in which eligible users can complete operator-created tasks, receive server-verified rewards, track referral progress, view an immutable wallet history, and request withdrawals through configured payout methods. Operators manage the system through a permission-based Admin Panel.

The system must be usable from Telegram mobile clients and Telegram Web. A limited unauthorized page may open in a normal browser, but earning, claiming, referral attribution, and withdrawal actions require validated Telegram authentication.

### 1.1 Product goals

1. Provide a fast and polished Bangla-first Mini App experience.
2. Make task rewards and balances resistant to client-side tampering and duplicate claims.
3. Allow non-technical operators to manage content and business settings safely.
4. Keep financial state auditable through an append-only, double-entry ledger.
5. Support future growth through queues, caching, idempotency, and horizontally safe jobs.
6. Respect advertising-provider rules and avoid deceptive earning claims.
7. Support cPanel/Passenger deployment while retaining optional PM2, systemd, Docker, Nginx, and Cloudflare deployment paths.

### 1.2 Non-goals for the initial release

- The system is not a bank, investment service, betting platform, casino, or trading product.
- Users cannot deposit money, buy spins, wager balances, or transfer funds to another user.
- The system will not fake ad engagement, automate clicks, or bypass an advertising provider's rules.
- Opening a URL or finishing a timer will never be described as proof of genuine engagement.
- Fully automated payouts are excluded until a supported payout provider, security review, and reconciliation process are configured.
- Native Android/iOS applications are outside the initial release.
- Multi-tenant/SaaS operation is outside the initial release.
- Cryptocurrency deposits, trading, and gambling-style rewards are outside the initial release.

---

## 2. Users and roles

### 2.1 End-user states

| State     | Meaning                                            | Allowed behavior                                          |
| --------- | -------------------------------------------------- | --------------------------------------------------------- |
| `new`     | Telegram identity validated; onboarding incomplete | View onboarding and complete profile requirements         |
| `active`  | Normal account                                     | Use enabled Mini App features                             |
| `limited` | Risk or eligibility restriction                    | View account; selected earning/withdrawal actions blocked |
| `banned`  | Administrator-enforced block                       | Only view ban/support notice                              |
| `deleted` | Soft-deleted/anonymization workflow started        | No authentication or earning activity                     |

`users.status` is server-controlled. A user can never set or influence it through profile APIs.

### 2.2 Administrative roles

| Role               | Purpose                                                                                |
| ------------------ | -------------------------------------------------------------------------------------- |
| Super Admin        | Full system authority, security-sensitive settings, administrator and role management  |
| Operations Manager | Users, tasks, referrals, mystery box, reminders, and operational reports               |
| Finance Manager    | Wallet review, withdrawals, payout reconciliation, and financial reports               |
| Content Manager    | Banners, announcements, tutorials, themes, and message templates                       |
| Support Agent      | Read user information, add internal notes, review common issues; no balance mutation   |
| Security Analyst   | Fraud flags, security events, session revocation, bans, and audit review               |
| Auditor            | Read-only access to reports, ledger, settings history, security events, and audit logs |

Roles are defaults, not hard-coded shortcuts. Authorization is always permission-based. A role receives permissions through database mappings, and every protected Admin API declares one or more required permissions.

### 2.3 Permission catalogue

Permissions use `resource.action` names. The first seed set includes:

```text
dashboard.view
users.view
users.update
users.ban
users.unban
users.sessions.revoke
users.export
tasks.view
tasks.create
tasks.update
tasks.publish
tasks.archive
task_attempts.view
task_attempts.review
referrals.view
referrals.review
wallet.view
wallet.adjust
ledger.view
withdrawals.view
withdrawals.hold
withdrawals.approve
withdrawals.reject
withdrawal_methods.manage
mystery_box.view
mystery_box.manage
banners.manage
announcements.manage
tutorials.manage
media.manage
notifications.view
notifications.send
reminders.manage
broadcasts.create
broadcasts.approve
bot_templates.manage
themes.manage
currencies.manage
settings.view
settings.update
settings.security.update
maintenance.manage
administrators.view
administrators.manage
roles.manage
fraud.view
fraud.review
security_events.view
audit_logs.view
system_health.view
system_jobs.manage
reports.view
reports.export
```

### 2.4 Separation-of-duty rules

- A non-Super-Admin cannot grant a permission they do not possess.
- An administrator cannot approve their own manual wallet adjustment.
- A configurable high-value withdrawal requires a second authorized approval.
- Broadcast creation and broadcast approval are separate permissions in production.
- Audit logs cannot be edited or deleted from the Admin Panel.
- The last active Super Admin cannot be disabled, deleted, or stripped of Super Admin access.
- Security-sensitive actions require recent password/2FA re-authentication.

---

## 3. Functional scope

## 3.1 Telegram authentication and onboarding

### Requirements

- `POST /api/v1/auth/telegram/exchange` accepts raw Telegram `initData`, never `initDataUnsafe` as proof.
- The server validates the signature using the bot token-derived secret and enforces `auth_date` freshness.
- Telegram user IDs are stored in MySQL `BIGINT UNSIGNED` columns and handled as decimal strings in JavaScript and JSON.
- The first successful exchange creates or updates the user profile using trusted Telegram fields.
- Telegram-supplied names, username, language, and photo URL are treated as display data and safely encoded.
- Successful exchange creates a short-lived server-side session and a secure, `HttpOnly` cookie.
- Session rotation occurs after login and privilege changes.
- Logout revokes the server-side session, not only the browser cookie.
- `/start <payload>` supports signed/validated referral attribution without overwriting an existing referrer.
- A user cannot refer themselves, and a referral relationship is immutable after valid attribution.
- Onboarding displays Terms, Privacy, Support, and earning-disclosure links configured by the operator.

### Acceptance criteria

- Modified, expired, missing, or replayed authentication data is rejected.
- The server never accepts a Telegram ID supplied separately by the client as identity proof.
- Multiple devices can be supported within configurable limits and can be revoked individually.
- Banned users cannot create new valid sessions.

## 3.2 Bootstrap, profile, and dashboard

`GET /api/v1/bootstrap` returns one versioned payload containing the authenticated user's public profile, enabled features, display-safe settings, theme tokens, currency metadata, unread-notification count, server time, and minimal navigation configuration.

Dashboard requirements:

- Greeting and Telegram profile information.
- Available balance, held balance, and lifetime earnings.
- Daily verified-task progress.
- Recommended tasks ordered by eligibility and priority.
- Mystery Box status only when enabled.
- Referral progress and active-referral count.
- Dynamic banner slider.
- Recent ledger transactions.
- Unread announcement/notification badge.
- Quick-withdraw action only when withdrawals are enabled.
- Maintenance, banned, limited, offline, empty, loading, and error states.

Profile editing is restricted to explicitly editable application fields. Telegram identity fields remain synchronized from trusted Telegram data and are not freely editable.

## 3.3 Task system

### Task configuration

Each task supports:

- Title, short description, detailed instructions, icon, category, badge, and display order.
- Server-controlled reward in minor currency units.
- Verification mode: `timer`, `provider_callback`, or `manual_review`.
- Task type: `one_time`, `daily`, or `repeatable`.
- Server-side wait time and optional repeat cooldown.
- Start/end timestamps and timezone-aware scheduling.
- Global completion cap and per-user daily/lifetime cap.
- Eligibility by user status, account age, completed-task count, referral count, country/language if legally and operationally appropriate, and feature cohort.
- Link opening mode allowed by Telegram APIs.
- Optional provider callback configuration held outside public payloads.
- Draft, scheduled, active, paused, ended, and archived lifecycle states.

### Secure completion flow

1. User selects **Start Work**.
2. The server locks/evaluates the task and user eligibility.
3. The server creates a unique attempt with `started_at`, `eligible_at`, expiry, verification mode, and immutable reward snapshot.
4. The API returns a safe public URL and attempt metadata; it never returns verification secrets.
5. The client opens the URL using the supported Telegram method and displays a cosmetic countdown based on server timestamps.
6. Claim requests include an idempotency key.
7. The server uses database/server time to check eligibility, status, limits, and required verification.
8. One database transaction creates the unique completion and balanced ledger transaction.
9. Duplicate or racing claims return the already-established result or a deterministic conflict; they never reward twice.

### Task invariants

- Client-provided reward, elapsed time, eligibility, completion status, or balance is ignored.
- A timer task proves only that server-required time elapsed; it does not prove ad engagement.
- Provider callbacks require signature validation, replay protection, allowlisted event types, and unique provider-event IDs.
- Incentivized links may be published only when the provider explicitly permits incentivized traffic.
- Unsafe, deceptive, illegal, age-restricted, malicious, or policy-breaking task destinations are prohibited.
- URL schemes are restricted to an allowlist, normally `https:` plus explicitly approved Telegram deep links.
- Task reward changes apply only to new attempts; an existing attempt retains its signed server-side reward snapshot.

## 3.4 Referral system

- Each user receives a bot referral link containing an opaque or signed referral code.
- A referral is **pending** after attribution and becomes **active** only after the referred user satisfies the configured legitimate activity threshold.
- Default activation signal is a configurable number of verified task completions; account age and device/risk checks may also be required.
- Reward can be configured for referrer, referee, both, or neither.
- Every referral reward uses a unique event key and balanced ledger transaction.
- Referral rewards are never recursively calculated from later earnings.
- Self-referral, referral loops, reused devices, high-volume shared identifiers, and abnormal activation patterns generate risk signals.
- Admins can review suspicious referrals, but cannot silently rewrite attribution history.
- A referral reward reversal, if required by policy, must be a new reversing ledger transaction with reason and audit record.

Referral API summary must distinguish:

- Total referred.
- Pending/inactive.
- Active.
- Rejected/invalid.
- Rewards earned.
- Progress toward withdrawal requirement, when such a requirement is enabled.

## 3.5 Wallet and ledger

### Authoritative model

`users.balance` will not be the source of truth. The authoritative balance is the sum of posted entries in the append-only double-entry ledger.

Required accounts include:

```text
SYSTEM_REWARD_LIABILITY
SYSTEM_PROMOTION_EXPENSE
USER_AVAILABLE:<user_id>
USER_HELD:<user_id>
PAYOUT_CLEARING
ADJUSTMENT_CLEARING
```

Account naming here describes logical account types; actual schema uses account IDs and typed ownership.

### Money rules

- All stored monetary amounts use integer minor units in signed/unsigned `BIGINT` fields as appropriate.
- `৳10.50` is stored as `1050` when the currency has two decimal places.
- JavaScript and JSON handle potentially large minor-unit values as decimal strings.
- No financial calculation uses binary floating-point.
- Percentage fees use integer basis points or an explicit decimal library, followed by one documented rounding rule.
- Currency metadata is snapshotted into financial transactions when needed for auditability.
- Every ledger transaction must balance to zero across its entries.
- Posted ledger entries are immutable. Correction uses a linked reversal plus a new correct transaction.

### Balance categories

- `available`: can be used for an eligible withdrawal request.
- `held`: reserved by a pending/held withdrawal or investigation.
- `lifetime_earned`: reporting metric derived from qualifying credits, not spendable balance.
- `pending_reward`: optional display metric; never spendable until posted.

### Idempotency

Reward, mystery-box claim, withdrawal creation, withdrawal decision, manual adjustment, and provider callbacks require stable idempotency keys. The database enforces uniqueness by operation scope and actor.

## 3.6 Withdrawal system

### Method configuration

Each withdrawal method supports:

- Name, icon, instructions, status, display order, currency, and processing mode.
- Dynamic input fields with server-side type, length, format, and required validation.
- Minimum/maximum amount.
- Fixed and/or percentage fee with optional cap.
- Daily limits, cooldown, account-age rule, verified-task rule, and active-referral rule.
- User-facing estimated processing time.
- Internal reconciliation/provider configuration not exposed to clients.

### Request flow

1. `POST /withdrawals/quote` returns a short-lived server-calculated quote.
2. User submits the quote ID and idempotency key; raw client fee calculations are ignored.
3. The server revalidates the quote, method, account status, limits, and available funds.
4. A database transaction creates the request and moves funds from available to held.
5. Authorized admin/provider processing applies an atomic status transition.
6. Approval moves held funds to payout clearing; rejection releases held funds back to available.
7. Every transition creates status history, audit data, and an outbox notification.

### State machine

```text
requested -> under_review -> approved -> processing -> paid
         \-> held ---------> approved/rejected
         \-> rejected
         \-> cancelled (only before processing, when enabled)
processing -> failed -> under_review/rejected
```

Only explicitly defined transitions are allowed. `paid` and `rejected` are terminal except for a Super-Admin-controlled reconciliation workflow that uses compensating records rather than history edits.

### Safe launch defaults

- Withdrawals are disabled until at least one method, eligibility rule, legal disclosure, and processing workflow are configured.
- Processing starts in `manual` mode.
- High-value dual approval is enabled when a threshold is configured.
- Sensitive payout field values are encrypted at rest and masked in lists/logs.
- Payout providers' age, identity, and account-ownership requirements must be followed; the app must not help a user bypass them.

## 3.7 Mystery Box

Mystery Box is a free promotional reward feature, not gambling.

- No deposit, purchase, stake, paid spin, balance wagering, or cash-for-chance mechanism is permitted.
- Access is earned only through configured legitimate activity, such as verified task completion.
- The feature is disabled by default until rewards, budget, claim frequency, and disclosure are configured.
- Reward mode can be `fixed` or `weighted_random`.
- Weighted selection uses cryptographically secure server-side randomness and immutable reward snapshots.
- Reward weights are positive integers and validated to form a usable distribution.
- Availability can be daily, weekly, lifetime, campaign-based, or cooldown-based.
- The claim operation locks eligibility, consumes the opportunity once, records the selected reward, and posts the ledger entries in one transaction.
- The client animation is decorative and never determines the result.
- Published wording must accurately describe eligibility and possible rewards; it must not promise a guaranteed amount when outcomes vary.

## 3.8 Leaderboard and history

- Leaderboards may rank verified earnings, verified task count, or active referrals for a defined period.
- Admin can select the metric and daily/weekly/monthly/all-time window.
- Users can opt out of public display; opted-out users use an anonymized label where ranking must remain visible.
- Exact Telegram IDs, phone numbers, payout identifiers, and private names are never exposed.
- Ranking snapshots/cached queries must not alter ledger truth.
- Wallet history supports filtering and cursor-based or page-based pagination with stable ordering.

## 3.9 Content, themes, and media

Admin-managed content includes:

- Banners with schedule, audience, destination, order, and active status.
- Announcements with severity, publish period, required acknowledgement, and read tracking.
- Tutorials with safe rich text, cover image, category, and order.
- Bot templates and in-app notification templates.
- Terms, Privacy, Support, Community, and other managed public links.
- Light/dark/custom theme tokens.

Media requirements:

- Uploads enter a quarantine path before validation.
- File extension, declared MIME, detected signature, dimensions, and size are checked.
- Filenames are generated; user-supplied paths are never trusted.
- Executable/server-side file types, SVG with unsafe content, and path traversal are blocked.
- Images are re-encoded where practical and served with correct content type and cache headers.
- Rich HTML is sanitized through a strict allowlist; untrusted HTML is never inserted directly.

## 3.10 Telegram Bot, notifications, and reminders

Bot commands:

- `/start`: onboarding/referral processing and Mini App button.
- `/app`: Mini App launch button.
- `/help`: safe help summary.
- `/support`: configured support route.

Bot requirements:

- Production receives updates through HTTPS webhook with a secret header.
- `update_id` is deduplicated before business effects.
- Webhook acknowledgement is fast; slow delivery is placed in an outbox/queue.
- Telegram API errors are categorized as retryable or terminal.
- Retry uses bounded exponential backoff and a dead-letter/failed-jobs record.
- Templates support escaped placeholders only; unknown placeholders fail preview validation.
- Broadcast requires audience estimate, preview, explicit confirmation, rate control, progress, cancellation before dispatch, and final report.
- Admin cannot upload a list of arbitrary Telegram IDs for unsolicited messaging.

Supported template variables in v1:

```text
{{first_name}}
{{username}}
{{balance}}
{{currency}}
{{task_count}}
{{active_referrals}}
{{withdraw_amount}}
{{withdraw_status}}
{{app_url}}
{{support_url}}
```

Reminders support timezone, days of week, local time, target segment, template, enabled state, last run, next run, retry report, and deduplication window.

## 3.11 Dynamic Admin Panel

The Admin Panel contains:

- Authentication, TOTP 2FA, recovery-code rotation, session/device view, and logout-all.
- Dashboard statistics and system-health summary.
- Users, user details, bans, sessions, referral status, activity, and internal notes.
- Tasks, categories, attempts, verification review, scheduling, and previews.
- Wallet ledger search and controlled dual-approved adjustments.
- Withdrawals, methods, status transitions, notes, exports, and reconciliation.
- Referral settings and suspicious-referral review.
- Mystery Box configuration and claim history.
- Leaderboard configuration.
- Banners, announcements, tutorials, themes, currencies, media, and managed links.
- Bot templates, reminders, broadcast preparation, delivery reports, and failed jobs.
- General, feature, maintenance, security-display, and business settings.
- Administrators, roles, permissions, active sessions, and access history.
- Fraud monitor, security events, audit logs, job status, and system health.

Every data table supports server-side pagination, validated filters, stable sorting, empty/error/loading states, and export permission where applicable.

Destructive actions use confirmation and clear impact text. Financial and security actions require a reason. Sensitive values are masked and never copied into HTML attributes or logs.

---

## 4. Configuration ownership map

The configuration system has four ownership levels. Precedence is:

```text
code invariant > deployment secret/config > validated database setting > UI default
```

An Admin setting cannot override an invariant or deployment secret.

## 4.1 Deployment-only configuration

These values belong in `.env` or deployment configuration and must never be editable from the Admin Panel.

| Key/group                  | Purpose                                      |   Required | Exposure rule                  |
| -------------------------- | -------------------------------------------- | ---------: | ------------------------------ |
| `NODE_ENV`                 | Runtime mode                                 |        Yes | Server only                    |
| `APP_ORIGIN`               | Canonical HTTPS origin                       |        Yes | Public value, deployment-owned |
| `PORT`                     | Local application port                       |        Yes | Server only                    |
| `TRUST_PROXY`              | Reverse-proxy policy                         |        Yes | Server only                    |
| `DATABASE_*`               | MySQL host, port, name, user, password, pool |        Yes | Secret/server only             |
| `REDIS_*`                  | Cache/queue connection and namespace         | Production | Secret/server only             |
| `TELEGRAM_BOT_TOKEN`       | Telegram Bot authentication                  |        Yes | Secret/server only             |
| `TELEGRAM_WEBHOOK_SECRET`  | Webhook request verification                 |        Yes | Secret/server only             |
| `TELEGRAM_BOT_USERNAME`    | Referral/deep-link construction              |        Yes | Public value, deployment-owned |
| `SESSION_SECRET`           | Session signing/key material                 |        Yes | Secret/server only             |
| `ENCRYPTION_MASTER_KEY`    | Sensitive-field encryption                   |        Yes | Secret/server only             |
| `CSRF_SECRET`              | CSRF token protection                        |        Yes | Secret/server only             |
| `APP_KEY_VERSION`          | Encryption key rotation identifier           |        Yes | Server only                    |
| `CSP_*_ORIGINS`            | Explicit trusted origins                     |        Yes | Deployment-owned allowlist     |
| `UPLOAD_ROOT`              | Storage root                                 |        Yes | Server only                    |
| `LOG_LEVEL`                | Runtime logging verbosity                    |        Yes | Server only                    |
| `SENTRY_DSN` or equivalent | Optional error monitoring                    |         No | Secret/server only             |
| `QUEUE_PREFIX`             | Job namespace                                | Production | Server only                    |
| `HEALTH_CHECK_TOKEN`       | Private detailed-health access               | Production | Secret/server only             |
| `ADMIN_BOOTSTRAP_*`        | One-time first-admin creation input          |   One-time | Removed/disabled after use     |

Phase 2 will define exact names and validation. The application must fail fast at startup when a required production value is missing, malformed, insecure, or uses an example placeholder.

## 4.2 Admin-managed settings

Settings are typed, schema-validated, versioned, cached, and audited. Unknown keys are rejected.

### General

| Setting                       | Type            | Baseline                            |
| ----------------------------- | --------------- | ----------------------------------- |
| `general.app_name`            | string          | `Telegram Task Earning` placeholder |
| `general.short_name`          | string          | `Task Earning` placeholder          |
| `general.default_language`    | enum            | `bn`                                |
| `general.supported_languages` | array           | `bn`, `en`                          |
| `general.timezone`            | IANA timezone   | `Asia/Dhaka`                        |
| `general.date_format`         | enum            | localized day-month-year            |
| `general.pagination_size`     | integer         | `20`                                |
| `general.support_url`         | HTTPS/TG URL    | Production input required           |
| `general.privacy_url`         | HTTPS URL       | Production input required           |
| `general.terms_url`           | HTTPS URL       | Production input required           |
| `general.community_url`       | HTTPS/TG URL    | Optional                            |
| `general.logo_media_id`       | media reference | Production input required           |
| `general.favicon_media_id`    | media reference | Optional                            |

### Currency

| Setting                    | Type             | Baseline         |
| -------------------------- | ---------------- | ---------------- |
| `currency.code`            | ISO-like code    | `BDT`            |
| `currency.name`            | localized string | `বাংলাদেশি টাকা` |
| `currency.symbol`          | string           | `৳`              |
| `currency.symbol_position` | enum             | `before`         |
| `currency.decimal_places`  | integer          | `2`              |
| `currency.rounding_mode`   | enum             | `half_up`        |

Currency decimal places cannot be changed after real financial entries exist without a supervised migration. Admin UI must warn and block an unsafe live change.

The first release uses one active settlement currency (`BDT`). Additional currency records may be prepared for future display/localization, but v1 performs no foreign-exchange conversion and never mixes currencies inside a ledger transaction.

### Feature flags

| Flag                       |                 Safe initial value |
| -------------------------- | ---------------------------------: |
| `features.registration`    |                                 On |
| `features.tasks`           |                                 On |
| `features.referrals`       |                                 On |
| `features.withdrawals`     |               Off until configured |
| `features.mystery_box`     |               Off until configured |
| `features.leaderboard`     |                                 On |
| `features.announcements`   |                                 On |
| `features.tutorials`       |                                 On |
| `features.reminders`       | Off until template/schedule exists |
| `features.broadcasts`      |      Off until bot delivery review |
| `features.profile_editing` |       On for app-owned fields only |

### Task defaults

- Default attempt expiry.
- Maximum server timer.
- Default daily cap.
- Maximum task reward allowed without Super Admin review.
- Allowed destination schemes and optional domain review policy.
- Provider-callback timeout and replay window.
- Whether manual verification is enabled.

No default setting can override a task's immutable reward snapshot after an attempt starts.

### Referral settings

- Feature enabled.
- Verified-task activation threshold.
- Minimum account age for activation.
- Referrer reward and referee reward in minor units.
- Active referrals required for withdrawal.
- Suspicious referral automatic-hold threshold.
- Referral link disclosure text.

Reward values default to zero until the operator intentionally configures a funded campaign.

### Withdrawal settings

- Global enabled state.
- Minimum/maximum amount.
- Daily request count and amount limit.
- Cooldown.
- Minimum account age.
- Minimum verified tasks.
- Required active referrals.
- Fixed fee and percentage fee in basis points.
- High-value dual-approval threshold.
- User cancellation policy.
- Estimated processing text.

The feature remains disabled until values and at least one method pass readiness validation.

### Mystery Box settings

- Enabled state.
- Required verified-task count.
- Claim frequency/cooldown.
- Campaign start/end.
- Fixed or weighted-random mode.
- Reward options and weights.
- Public disclosure text.
- Title, body, image, and reduced-motion animation choice.

The readiness validator blocks activation when there is no valid funded reward configuration.

### Bot and reminder settings

- Welcome, help, referral, activation, withdrawal, ban/unban, and maintenance templates.
- Mini App and support button text.
- Reminder schedules, templates, target segment, timezone, and days.
- Broadcast safety limits and confirmation requirement.
- Retry count within a hard-coded safe maximum.

### Theme and UI settings

- Brand primary/secondary/accent colors.
- Light and dark surface/text/border colors.
- Gradient choices from validated tokens.
- Logo, header style, card radius, and controlled blur level.
- Reduced-motion behavior cannot be disabled by Admin.
- Contrast validation must prevent publishing unreadable text/background combinations.

### Risk and operational settings

- Risk thresholds may be tuned by authorized security roles.
- Raw scoring algorithm, security secrets, and hard safety limits remain code/deployment-owned.
- Maintenance mode, message, estimated return text, and allowlisted admin access.
- Session/device limits inside code-enforced safe ranges.

## 4.3 Code invariants

The following are never dynamic:

- Ledger must balance and posted entries are immutable.
- Rewards are server-calculated.
- Telegram authentication validation algorithm.
- SQL parameterization and validation requirement.
- Idempotency on financial/rewarding operations.
- Defined financial state transitions.
- Admin authorization enforcement.
- Audit-log requirement for privileged mutations.
- CSRF protection for cookie-authenticated state changes.
- Webhook signature/secret verification and update deduplication.
- Secure-random requirement for weighted rewards.
- Prohibition on paid/wagered Mystery Box access.
- Secret redaction and sensitive-value masking.
- Upload safety validation.
- Production HTTPS requirement.

## 4.4 Public bootstrap allowlist

Only these setting categories may be projected to Mini App clients:

- App display name and safe branding asset URLs.
- Language, timezone, date-format, and currency-display metadata.
- Feature flags relevant to navigation.
- Public support/legal/community URLs.
- Validated theme tokens.
- Safe pagination/UI constants.
- Maintenance public message.

Database keys, bot/provider secrets, internal thresholds, payout credentials, risk rules, admin configuration, and private media paths must never enter the bootstrap payload.

---

## 5. Data and transaction invariants

1. All MySQL tables use InnoDB and explicit character set/collation suitable for Bangla and emoji.
2. Primary keys are generated server-side. Public IDs may be separate opaque values where enumeration matters.
3. Telegram IDs are exact integers in storage and strings in JavaScript/API boundaries.
4. Money is integer minor units; API money fields ending in `_minor` are decimal strings.
5. A ledger transaction contains exactly one currency; v1 has one active settlement currency and no exchange conversion.
6. Timestamps are stored in UTC with sufficient precision and displayed in configured timezone.
7. Financial/reward timestamps use database or trusted server time, never device time.
8. Foreign keys, unique constraints, and check constraints enforce important invariants in addition to application checks.
9. All reward and withdrawal operations use transactions and appropriate row-level locking.
10. Unique constraints prevent duplicate task completions, referral rewards, Mystery Box claims, provider events, and idempotency scopes.
11. Status histories and audit records are append-only.
12. Soft deletion is used where legal/audit needs require retention; anonymization is separate from silent record deletion.
13. Cached balances/statistics are treated as projections and can be rebuilt from authoritative records.
14. Background jobs use a database outbox or equivalent atomic handoff when coupled to a business transaction.
15. Migration files are ordered, immutable after production use, and recorded in a migrations table.
16. Seeders are idempotent and never overwrite operator settings silently.

---

## 6. API contract standards

### 6.1 Base rules

- Version prefix: `/api/v1`.
- Request/response encoding: UTF-8 JSON except controlled media routes.
- IDs: strings.
- Minor-unit monetary values: decimal strings.
- Timestamps: ISO 8601 UTC strings.
- Pagination: consistent metadata and stable ordering.
- State-changing routes require authentication, CSRF where applicable, validation, rate limits, and idempotency where specified.

### 6.2 Success envelope

```json
{
  "success": true,
  "data": {},
  "meta": {
    "request_id": "opaque-id",
    "server_time": "2026-09-03T12:00:00.000Z"
  }
}
```

### 6.3 Error envelope

```json
{
  "success": false,
  "error": {
    "code": "TASK_NOT_ELIGIBLE",
    "message": "এই কাজটি এখন claim করা যাবে না।",
    "details": null
  },
  "meta": {
    "request_id": "opaque-id"
  }
}
```

Production errors never expose stack traces, SQL, file paths, secrets, raw provider responses, or internal exception messages.

### 6.4 Required end-user routes

```text
POST   /api/v1/auth/telegram/exchange
POST   /api/v1/auth/logout
GET    /api/v1/bootstrap
GET    /api/v1/dashboard
GET    /api/v1/tasks
POST   /api/v1/tasks/:taskId/start
GET    /api/v1/task-attempts/:attemptId/status
POST   /api/v1/task-attempts/:attemptId/claim
GET    /api/v1/referrals
GET    /api/v1/referrals/summary
GET    /api/v1/referrals/share-link
GET    /api/v1/leaderboard
GET    /api/v1/wallet
GET    /api/v1/wallet/history
GET    /api/v1/withdrawal-methods
POST   /api/v1/withdrawals/quote
POST   /api/v1/withdrawals
GET    /api/v1/withdrawals
GET    /api/v1/mystery-box/status
POST   /api/v1/mystery-box/claim
GET    /api/v1/banners
GET    /api/v1/announcements
POST   /api/v1/announcements/:id/read
GET    /api/v1/tutorials
GET    /api/v1/profile
PATCH  /api/v1/profile
```

Admin APIs live under `/api/v1/admin/*`. Bot webhook and health routes have separate namespaces and authentication policies.

---

## 7. Security baseline

## 7.1 Authentication and sessions

- Validate Telegram `initData` server-side, including signature, freshness, required fields, and replay considerations.
- Admin passwords use Argon2id with environment-appropriate calibrated parameters.
- Admin TOTP 2FA is mandatory for Super Admin and financial/security permissions in production.
- Recovery codes are one-time, strongly generated, and stored hashed.
- Sessions are server-side, short-lived, rotated, revocable, and bound to security metadata without treating IP as a permanent identity.
- Cookies use `HttpOnly`, `Secure` in production, an appropriate `SameSite` policy, restricted path/domain, and explicit lifetime.
- Login attempts use rate limits and exponential backoff without revealing whether an account exists.

## 7.2 Request security

- Helmet-based headers plus an explicit strict CSP.
- `frame-ancestors` and trusted origins are deployment allowlists.
- CSRF tokens protect cookie-authenticated state changes.
- CORS is deny-by-default and never uses credentialed wildcard origins.
- Request body size, parameter count, upload size, and processing time are bounded.
- All input is schema-validated and unknown privileged fields are rejected.
- SQL uses parameterized queries; identifiers/order clauses come only from explicit mappings.
- Redirects and outbound URLs use scheme/domain rules and block local/private network access where server-side fetching exists.
- Output is contextually encoded; no untrusted `innerHTML`.

## 7.3 Financial and abuse security

- Row locks, unique constraints, idempotency, and deterministic status transitions protect races.
- Rate limits combine route, account, Telegram ID, session, and network signals as appropriate.
- Risk scoring can hold activity but never silently confiscates user funds.
- Admin balance adjustments are balanced ledger transactions with reason, evidence reference, and approval policy.
- Reconciliation detects ledger imbalance, negative available balances, stale holds, and payout mismatch.
- Security events include repeated auth failure, signature failure, duplicate financial attempt, unusual referral cluster, suspicious device reuse, privilege change, and secret/config failure.

## 7.4 Infrastructure boundary

Application code alone cannot guarantee DDoS protection. Production requires edge/reverse-proxy controls such as Cloudflare/WAF, TLS, connection/request limits, bot controls, caching, and origin protection. Redis-backed rate limits and queue back-pressure supplement those controls.

## 7.5 Logging and privacy

- Structured logs include timestamp, level, request ID, route, status, duration, and safe actor identifiers.
- Bot tokens, cookies, authorization headers, CSRF values, passwords, TOTP secrets, recovery codes, encryption keys, payout details, raw Telegram `initData`, and provider credentials are redacted.
- Security and admin audit logs have documented retention and restricted access.
- Data export/deletion requests follow a documented workflow without destroying required financial/audit integrity.

---

## 8. Fraud and risk model

Risk signals may include:

- Multiple accounts associated with the same device/browser signals.
- Referral loops or abnormal referral-activation velocity.
- Many accounts sharing payout identifiers.
- Repeated callback/claim replay attempts.
- Impossible request cadence or concurrent task claims.
- Rapid withdrawal after promotional credits.
- Repeated failed admin logins or new-device privileged activity.

Risk outcomes:

| Outcome   | Effect                                                        |
| --------- | ------------------------------------------------------------- |
| Observe   | Log signal; no user-visible restriction                       |
| Challenge | Require fresh authentication or additional verification       |
| Limit     | Temporarily block a specific action                           |
| Hold      | Place a withdrawal under review; funds remain in held account |
| Review    | Create an admin case with evidence references                 |
| Ban       | Block account after authorized decision and record reason     |

Risk decisions must be reviewable. The system must not expose exact detection rules to end users, but it must provide a clear, non-deceptive status and support route.

---

## 9. UI/UX requirements

### 9.1 Navigation

Bottom navigation:

1. Home
2. Tasks
3. Leaderboard
4. Refer
5. Withdraw

History, Tutorials, Notifications, and Profile are available through the header/profile area. Disabled features are removed or replaced with a clear unavailable state; dead navigation items are not shown.

### 9.2 Design system

- Premium gradient and restrained glassmorphism using CSS variables.
- Telegram light/dark theme synchronization with operator theme overrides inside safe contrast constraints.
- Mobile-first layout and Telegram safe-area handling.
- Minimum comfortable touch targets and accessible labels.
- Keyboard and screen-reader support for core flows.
- Skeleton loaders, empty states, retry states, offline notice, and non-blocking toasts.
- Haptic feedback only for meaningful supported interactions.
- Smooth transitions with `prefers-reduced-motion` and automatic reduced effects on slow devices.
- Bangla typography with local/system fallback; no critical UI dependency on an external font CDN.
- User-provided and Admin-provided content is escaped or sanitized.

### 9.3 Accessibility acceptance

- Core text and controls meet WCAG AA contrast targets.
- Status is not communicated by color alone.
- Focus order is logical and focus indicators are visible.
- Buttons have meaningful labels and disabled states.
- Countdown and animation do not prevent users from understanding server eligibility.
- Reduced-motion users receive no unnecessary spinning/flashing animation.

---

## 10. Performance, reliability, and operations

### Launch targets

- Normal cached/read API p95 target: under 750 ms at the application boundary, excluding external services.
- Critical write API p95 target: under 1.5 seconds under planned launch load.
- Initial Mini App shell should remain lightweight and usable on budget Android devices and slow mobile networks.
- Database queries used in lists and dashboards require measured indexes and bounded pagination.
- External Telegram/provider calls do not hold database transactions open.
- Workers and schedulers shut down gracefully and do not accept new work after shutdown begins.

### Reliability rules

- Health endpoints distinguish liveness from dependency readiness.
- Detailed health output is private; public health reveals minimal status.
- Jobs are retryable, deduplicated, and observable.
- Scheduler uses a distributed lock so only one instance performs a scheduled unit of work.
- Outbox delivery can resume after process restart.
- Failed jobs retain reason and safe context for operator review.
- Degraded Redis behavior is explicit: security-critical distributed functions fail closed when correctness cannot be preserved; non-critical cache reads may fall back to MySQL.

### Backup and recovery baseline

- Automated encrypted database backups.
- Separate media and configuration backup plan.
- Restore procedure tested before production launch.
- Initial target RPO: 24 hours or better; target RTO: 4 hours or better, adjusted to hosting capability.
- Ledger and audit data receive the strictest retention and restore checks.
- Backup files are not publicly web-accessible.

---

## 11. Testing requirements

### Unit tests

- Telegram authentication validation.
- Money formatting and fee rounding.
- Task eligibility and completion rules.
- Referral activation/reward rules.
- Ledger balancing and reversal behavior.
- Withdrawal quote and transition rules.
- Mystery Box eligibility and weighted selection boundaries.
- Template escaping and placeholder validation.

### Integration tests

- Authentication/session lifecycle.
- Task start, wait, claim, duplicate claim, and race behavior.
- Referral attribution, activation, and duplicate protection.
- Wallet history and computed balances.
- Withdrawal reserve, approval, rejection, and refund.
- Admin login, 2FA, permissions, and audit creation.
- Bot webhook deduplication and outbox creation.

### Security tests

- SQL injection and unsafe sorting attempts.
- Stored/reflected XSS and rich-text sanitization.
- CSRF enforcement.
- Broken object-level and function-level authorization.
- Session fixation and revoked-session reuse.
- Idempotency misuse and concurrent balance race.
- Malicious upload and path traversal.
- Webhook spoofing and replay.
- Sensitive-data leakage in logs and errors.

Release-blocking rule: any failing ledger, authorization, authentication, idempotency, withdrawal-state, or balance race test blocks production deployment.

---

## 12. Compliance and responsible operation

- Terms and Privacy pages must be available before production onboarding.
- Users receive clear descriptions of how rewards are earned, when they become available, applicable fees, withdrawal rules, and processing expectations.
- No guaranteed-income, misleading scarcity, fake countdown, or deceptive engagement claim.
- Task publishers must own/have rights to submitted content and destinations.
- Incentivized traffic is used only with explicit provider approval.
- The system must not target or facilitate prohibited, unsafe, illegal, or age-restricted offers.
- Payout-method eligibility, minimum age, identity, and account-ownership rules are enforced according to the provider and applicable requirements; no bypass workflow is provided.
- Mystery Box remains free and non-wagered.
- Before launch, the operator should confirm applicable tax, consumer, privacy, advertising, employment/gig, and payout requirements with qualified local professionals and providers.

---

## 13. Audit requirements

An audit record for a privileged mutation includes:

- Unique event ID and UTC timestamp.
- Admin actor ID, session ID, role snapshot, and request ID.
- Action and resource type/ID.
- Safe before/after diff with secrets and sensitive payout data redacted.
- Supplied reason where required.
- Result and failure code.
- Network/device metadata within the privacy policy.

Required audited actions include login/2FA events, permission/role changes, administrator changes, bans, task publishing/reward changes, setting changes, wallet adjustments, withdrawal decisions, Mystery Box configuration, broadcast approval, maintenance changes, secret-read attempts, export generation, and session revocation.

---

## 14. Phase 1 decision register

### Locked decisions

| ID    | Decision                                                                                                |
| ----- | ------------------------------------------------------------------------------------------------------- |
| D-001 | Modular monolith with separate web, worker, and scheduler entry points                                  |
| D-002 | Node.js/Express backend; exact supported runtime pinned in Phase 2 after deployment compatibility check |
| D-003 | MySQL/InnoDB authoritative datastore                                                                    |
| D-004 | Redis for distributed cache, rate limits, locks, and queue support in production                        |
| D-005 | Server-validated Telegram `initData` with server-side sessions                                          |
| D-006 | Telegram IDs and large integers are strings at JavaScript/API boundaries                                |
| D-007 | Money uses integer minor units and documented rounding                                                  |
| D-008 | Append-only double-entry ledger is the balance authority                                                |
| D-009 | Every reward/financial mutation is transactional and idempotent                                         |
| D-010 | EJS application shells plus local modular JavaScript and compiled CSS                                   |
| D-011 | Bangla-first, English-ready, `Asia/Dhaka`, BDT baseline                                                 |
| D-012 | Admin authorization uses granular database permissions                                                  |
| D-013 | TOTP 2FA is mandatory for privileged production roles                                                   |
| D-014 | Manual withdrawal processing is the safe launch mode                                                    |
| D-015 | Mystery Box is free-only, disabled by default, and never wagered                                        |
| D-016 | Provider-compliant task destinations and honest earning disclosures are mandatory                       |
| D-017 | Configuration is divided into code invariants, deployment secrets, and typed Admin settings             |
| D-018 | cPanel/Passenger remains a supported deployment target; richer infrastructure is optional               |
| D-019 | v1 uses one active settlement currency (`BDT`) and performs no currency conversion                      |

### Production values still required from the operator

These are intentional placeholders, not architecture blockers:

| ID    | Required value                                                             | Needed by                    |
| ----- | -------------------------------------------------------------------------- | ---------------------------- |
| P-001 | Final app name and short name                                              | Branding/content phase       |
| P-002 | Telegram bot username and BotFather token                                  | Environment/bot phase        |
| P-003 | Final HTTPS domain/origin                                                  | Environment/deployment phase |
| P-004 | Logo, favicon, and brand color direction                                   | Frontend/content phase       |
| P-005 | Support, Privacy, Terms, and Community URLs                                | Pre-production launch        |
| P-006 | Hosting type, Node version availability, MySQL version, Redis availability | Phase 2–5                    |
| P-007 | Initial Super Admin identity/email                                         | Admin-auth phase             |
| P-008 | Task-provider list and proof that incentivized traffic is allowed          | Task publishing/launch       |
| P-009 | Referral rewards and activation threshold                                  | Referral phase               |
| P-010 | Withdrawal methods, limits, fees, eligibility, and processing policy       | Withdrawal phase             |
| P-011 | Mystery Box rewards, weights, budget, and frequency                        | Mystery Box phase            |
| P-012 | Data retention, backup capability, and operational contacts                | Security/deployment phase    |

Until these values are supplied, development uses clearly marked non-production examples. Secrets are never committed.

---

## 15. Phase 1 completion checklist

- [x] Product purpose and boundaries defined.
- [x] End-user and administrator roles defined.
- [x] Permission naming and separation of duties defined.
- [x] Authentication and onboarding rules defined.
- [x] Dashboard, profile, task, referral, wallet, withdrawal, Mystery Box, leaderboard, content, bot, reminder, and Admin requirements defined.
- [x] Financial ledger and money invariants defined.
- [x] Configuration ownership and precedence defined.
- [x] Safe initial feature states defined.
- [x] API representation and error standards defined.
- [x] Security, fraud, privacy, audit, reliability, accessibility, and testing baselines defined.
- [x] Responsible-operation boundaries defined.
- [x] Locked decisions and operator-supplied production values separated.

**Phase 1 implementation status: COMPLETE.**

Branding, provider, payout, and hosting values remain tracked inputs. They do not require redesigning the architecture and can be supplied before their dependent phases.

---

## 16. Contract for Phase 2

Phase 2 is **Project Initialization**. It must implement only the foundation necessary for later phases, without prematurely embedding business data.

Required Phase 2 outputs:

1. Root project metadata and `package.json`.
2. Exact runtime and package version strategy compatible with the chosen hosting environment.
3. Development, production, web, worker, scheduler, lint, format, test, migration, seed, environment verification, and health-check scripts.
4. Complete approved folder skeleton without fake placeholder implementations that appear production-ready.
5. ESLint and Prettier configuration.
6. Tailwind/PostCSS or the selected compiled CSS pipeline.
7. `.gitignore`, `.editorconfig`, and a starter README.
8. Minimal entry-point stubs that fail clearly until later bootstrap phases are implemented.
9. An installation verification report.

Phase 2 must not commit `.env`, tokens, credentials, generated logs, uploads, backups, or dependency directories.

---

## 17. Change-control rule

Future changes to a locked Phase 1 decision require:

1. Decision ID or a new ID.
2. Reason for change.
3. Affected database/API/security/UI components.
4. Migration and backward-compatibility impact.
5. Updated acceptance tests.
6. Date and approval note.

This keeps every later file consistent with the product contract and prevents silent business-rule drift.
