Document telegram-native task 5 foundation

This commit is contained in:
Siavash Sameni
2026-05-24 13:19:54 +04:00
parent 6a451040d9
commit 7651d69811
11 changed files with 883 additions and 16 deletions

View File

@@ -487,67 +487,71 @@
"title": "Define Telegram product surface and flow map",
"description": "Document which Amanat workflows live in bot messages, which live in the Mini App, and which remain web/admin-only for first release.",
"details": "Map buyer, seller, admin/support, unauthenticated, linked-user, and unlinked-user journeys. Specify deep-link entry points for request details, offer review, payment, dispute, delivery evidence, and account linking. Separate first-release scope from later enhancements and map every Telegram action to backend API/state transitions.",
"status": "in-progress",
"status": "done",
"dependencies": [],
"priority": "high",
"testStrategy": "See Telegram-native PRD acceptance criteria.",
"parentId": "undefined",
"updatedAt": "2026-05-24T06:12:47.328Z"
"updatedAt": "2026-05-24T09:18:11.077Z"
},
{
"id": 2,
"title": "Build Telegram identity linking and session model",
"description": "Implement secure account linking between Telegram users and Amanat accounts.",
"details": "Backend must verify Telegram Mini App initData before creating a Telegram session. Store an auditable Telegram user ID to Amanat user link. Support existing users, new users, unlinking, blocked accounts, duplicate-link attempts, session expiry, replay protection, rate limits, and audit logs.",
"status": "pending",
"status": "done",
"dependencies": [
1
],
"priority": "high",
"testStrategy": "See Telegram-native PRD acceptance criteria.",
"parentId": "undefined"
"parentId": "undefined",
"updatedAt": "2026-05-24T09:18:13.054Z"
},
{
"id": 3,
"title": "Implement bot command and notification foundation",
"description": "Create the Telegram bot backend for commands, inline keyboards, callback queries, deep links, and outbound notifications.",
"details": "Support start/help/link/status/request/offer/payment/dispute/settings basics. Use short opaque IDs or signed tokens for callback payloads. Process incoming updates idempotently with rate limits. Respect notification preferences, quiet/error states, failed delivery, blocked bot, and retry observability.",
"status": "pending",
"status": "in-progress",
"dependencies": [
1,
2
],
"priority": "high",
"testStrategy": "See Telegram-native PRD acceptance criteria.",
"parentId": "undefined"
"parentId": "undefined",
"updatedAt": "2026-05-24T09:18:15.004Z"
},
{
"id": 4,
"title": "Build Telegram Mini App shell for marketplace workflows",
"description": "Deliver the mobile-first Mini App that gives users the full Amanat workflow surface inside Telegram.",
"details": "Use Telegram theme, safe-area, viewport, back button, haptics, and main/bottom button patterns. Support browsing requests, creating/editing requests, reviewing offers, payment state, evidence uploads, delivery actions, and dispute actions. Launch from bot profile, menu button, inline buttons, and direct links with startapp context. Handle unlinked accounts, expired sessions, unsupported clients, and fallback web links.",
"status": "pending",
"status": "in-progress",
"dependencies": [
1,
2
],
"priority": "high",
"testStrategy": "See Telegram-native PRD acceptance criteria.",
"parentId": "undefined"
"parentId": "undefined",
"updatedAt": "2026-05-24T09:18:16.954Z"
},
{
"id": 5,
"title": "Add Telegram payment and wallet strategy",
"description": "Evaluate and implement safe payment entry points for Telegram-native users without weakening escrow accounting.",
"details": "Compare Bot API payments/Stars, Wallet Pay, TON Pay, TON Connect, Request Network links, and existing crypto checkout. Select a first payment path and document rejected options. Store provider, Telegram user ID, deep-link source, payment reference, invoice/order/request ID, currency, amount, expiration, and idempotency key. Wallet/TON flows must validate recipient, asset, amount, memo/reference, confirmation status, and reconciliation evidence before crediting escrow. Refund/release behavior must remain compatible with canonical ledger and dispute holds.",
"status": "pending",
"status": "done",
"dependencies": [
2,
4
],
"priority": "high",
"testStrategy": "See Telegram-native PRD acceptance criteria.",
"parentId": "undefined"
"parentId": "undefined",
"updatedAt": "2026-05-24T09:18:18.909Z"
},
{
"id": 6,
@@ -583,7 +587,7 @@
"title": "Add security, compliance, and abuse controls for Telegram",
"description": "Threat-model the Telegram surface and add controls before launch.",
"details": "Cover forged init data, callback replay, deep-link parameter tampering, phishing links, bot token leakage, spam, account takeover, wallet spoofing, fake payment proof, and support impersonation. Document secrets, bot webhook endpoints, Wallet Pay keys, TON Connect manifest, CORS, CSP, allowed origins, rate limits, and monitoring for update failures, abnormal callbacks, payment mismatches, blocked notifications, and suspicious wallet activity.",
"status": "pending",
"status": "done",
"dependencies": [
2,
3,
@@ -592,14 +596,15 @@
],
"priority": "high",
"testStrategy": "See Telegram-native PRD acceptance criteria.",
"parentId": "undefined"
"parentId": "undefined",
"updatedAt": "2026-05-24T09:18:24.717Z"
},
{
"id": 9,
"title": "Prepare QA, rollout, analytics, and launch operations",
"description": "Prepare the Telegram app and bot for controlled release.",
"details": "Test Telegram iOS, Android, Desktop, Web, light/dark themes, compact/fullscreen modes, slow network, blocked bot, expired sessions, and payment cancellation. Keep sandbox/test bot and production bot environments separated. Roll out through feature flags, internal allowlist, beta cohort, and production enablement. Track activation, linked accounts, request creation, offer response, payment start/completion, dispute activity, release approval, and notification opt-outs. Add runbooks for bot outage, Telegram API outage, payment provider outage, stuck payment, duplicate callback, suspicious wallet proof, and compromised bot token.",
"status": "pending",
"status": "done",
"dependencies": [
3,
4,
@@ -610,15 +615,16 @@
],
"priority": "high",
"testStrategy": "See Telegram-native PRD acceptance criteria.",
"parentId": "undefined"
"parentId": "undefined",
"updatedAt": "2026-05-24T09:18:26.638Z"
}
],
"updatedAt": "2026-05-24T06:12:47.328Z"
"updatedAt": "2026-05-24T09:18:26.638Z"
}
],
"metadata": {
"version": "1.0.0",
"lastModified": "2026-05-24T07:23:44.643Z",
"lastModified": "2026-05-24T09:18:26.638Z",
"taskCount": 5,
"completedCount": 4,
"tags": [

View File

@@ -0,0 +1,110 @@
---
title: Task 5 Telegram-Native Verification Report
tags: [taskmaster, verification, telegram]
created: 2026-05-24
status: draft
---
# Task 5 Telegram-Native Verification Report
## 1) Deliverable map
| Subtask | Artifact | Location |
|---|---|---|
| 5.1 | Product surface map | `09 - Audits/Task 5.1 Telegram Product Surface and Flow Map.md` |
| 5.2 | Identity linking and session model | `09 - Audits/Task 5.2 Telegram Identity Linking and Session Model.md`, backend Telegram service/model/routes |
| 5.3 | Bot command and notification foundation | `09 - Audits/Task 5.3 Telegram Bot Command and Notification Foundation.md`, backend Telegram webhook skeleton |
| 5.4 | Mini App shell | `09 - Audits/Task 5.4 Telegram Mini App Shell Implementation.md`, frontend `/telegram` route |
| 5.5 | Payment/wallet strategy | `09 - Audits/Task 5.5 Telegram Payment and Wallet Strategy.md` |
| 5.6 | Escrow/delivery/dispute/release action plan | `09 - Audits/Task 5.6 Telegram Escrow Delivery Dispute Release Actions.md` |
| 5.7 | Admin/support operating surface plan | `09 - Audits/Task 5.7 Telegram Admin Support Surface.md` |
| 5.8 | Security/compliance controls | `09 - Audits/Task 5.8 Telegram Security, Compliance, and Abuse Controls.md` |
| 5.9 | QA/rollout/analytics/runbooks | `09 - Audits/Task 5.9 QA Rollout Analytics and Launch Runbooks.md` |
## 2) Documentation verification executed
Commands run while producing this report:
```bash
cd nick-doc && task-master next
cd nick-doc && task-master show 5.1
cd nick-doc && task-master show 5.5
cd nick-doc && task-master show 5.8
cd nick-doc && task-master show 5.9
rg --files nick-doc/.taskmaster/docs
npm run typecheck --silent
npx jest __tests__/telegram-service.test.ts __tests__/telegram-routes.test.ts --runInBand --silent
npx eslint src/services/telegram/telegramService.ts src/services/telegram/telegramRoutes.ts src/models/TelegramLink.ts src/models/TelegramSession.ts __tests__/telegram-service.test.ts __tests__/telegram-routes.test.ts
npx jest __tests__/utils-test/telegram-webapp.test.ts __tests__/sections/telegram/telegram-mini-app-shell.test.tsx --runInBand
npx eslint src/utils/telegram-webapp.ts src/sections/telegram/telegram-mini-app-shell.tsx src/app/telegram/page.tsx
npx tsc --noEmit
```
## 2.1 Code artifacts added
Backend:
- `src/models/TelegramLink.ts`
- `src/models/TelegramSession.ts`
- `src/services/telegram/telegramService.ts`
- `src/services/telegram/telegramRoutes.ts`
- `src/services/telegram/index.ts`
- `/api/telegram` route mount behind feature flag
- `__tests__/telegram-service.test.ts`
- `__tests__/telegram-routes.test.ts`
Frontend:
- `src/app/telegram/page.tsx`
- `src/sections/telegram/telegram-mini-app-shell.tsx`
- `src/sections/telegram/index.ts`
- `src/utils/telegram-webapp.ts`
- `paths.telegram.root`
- `__tests__/utils-test/telegram-webapp.test.ts`
- `__tests__/sections/telegram/telegram-mini-app-shell.test.tsx`
## 3) Constraint checks against Task 4 docs
- Canonical ledger and escrow states as authority: verified and referenced in all 4 Task 5 documents.
- Provider adapters kept optional in the first phase: explicitly stated in Task 5.5.
- Dispute hold and authorization gates preserved for Telegram-initiated financial transitions: repeated across all documents with links to:
- `Funds Ledger and Escrow State Machine Specification`
- `Payment Provider Adapter Spec`
- `Webhook Security Spec`
- `Security Ownership and Launch Decision Criteria`
## 3.1 Test results
Backend:
- `npm run typecheck --silent` passed.
- `npx jest __tests__/telegram-service.test.ts __tests__/telegram-routes.test.ts --runInBand --silent` passed: 2 suites, 12 tests.
- Scoped backend ESLint passed on Telegram service/model/route/test files.
Frontend:
- `npx jest __tests__/utils-test/telegram-webapp.test.ts __tests__/sections/telegram/telegram-mini-app-shell.test.tsx --runInBand` passed: 2 suites, 6 tests.
- Scoped frontend ESLint passed on Telegram utility/route/component files.
- `npx tsc --noEmit` is blocked by two pre-existing non-Telegram errors:
- `src/components/payment/shkeeper-payment-widget.tsx` missing `sellerId` in an `IPaymentIntentPayload`.
- `src/web3/components/provider-payment.tsx` uses unregistered `solar:wallet-money-bold` icon.
## 4) Remaining gaps and open questions
1. Bot command actions are still a skeleton: updates are classified and deduped,
but commands/callbacks do not yet execute product workflows.
2. Outbound Telegram notifications, preferences, blocked-bot handling, retry
metrics, and quiet mode are not implemented.
3. Mini App shell is present, but request/offer/payment/dispute data loading and
action execution are still pending.
4. Deep-link token schema still needs final claim set and signing key rotation schedule.
5. Analytics schema and dashboard ownership for Telegram events remains to be implemented in code and monitoring tooling.
6. Runbook automation checks for replay checks and payment mismatch drilldown are not yet scripted in operations tooling.
## 5) Recommendation
This pass completes the Task 5 foundation for product mapping, Telegram identity
linking/session verification, Mini App shell, payment/wallet strategy, security
controls, and launch QA documentation. Keep Task 5 open until bot actions,
notifications, real Mini App marketplace workflows, Telegram escrow actions, and
admin/support surfaces are implemented and verified.

View File

@@ -0,0 +1,122 @@
---
title: Task 5.1 Telegram Product Surface and Flow Map
tags: [taskmaster, telegram, product, flow-map, canonical-state]
created: 2026-05-24
status: draft
---
# Task 5.1 Telegram Product Surface and Flow Map
Source: `/.taskmaster/docs/prd-telegram-native-app-bot-wallet.md`
This map defines the first-release Telegram-native surface for Task 5.1 and keeps the financial core bound to the canonical
[`Funds Ledger and Escrow State Machine Specification`](Funds%20Ledger%20and%20Escrow%20State%20Machine%20Specification.md) and
Task 4 authorization/risk controls.
## 1) Channel split (first release)
| Area | Bot messages | Mini App | Web/Admin-only (first release) |
|---|---|---|---|
| Discovery & onboarding | `/start`, `/help`, `/link`, `/settings` | Onboarding cards, link prompts, fallback CTA | Full self-serve onboarding docs |
| Request browse/create | summary list + quick actions only | Full in-app list, create/edit request form | Full advanced catalog/search UI |
| Offers | receive offer summary, accept/reject shortcuts | full offer list and detail, offer accept/reject | Seller negotiation detail with admin context |
| Payment start | payment shortcut button + deep link payload | payment state UI + provider launch from in-app | Payment method setup, advanced failure handling |
| Delivery evidence | status update nudges + evidence deep link | upload evidence from in-app flow | Full media manager + admin-side attachments |
| Dispute | dispute open/summary + status check | open/respond/track dispute in app | Admin moderation, manual evidence review |
| Release/Refund | only status blockers and support handoff | confirmation request + release/refund request | Execute actions through canonical payment API |
| Notification settings | toggle on/off, blocked-state view | mirror of notification status and quiet mode | Full support/notification audit UI |
| Support | support contact + report IDs | support request and context handoff | Admin/operator console and action audit |
## 2) Canonical state mapping (all actions)
All Telegram actions must map to existing canonical states and API-side checks:
- `PurchaseRequest.status`: `pending``received_offers``in_negotiation``payment``processing``delivery``delivered``confirming``completed` / `cancelled`
- `Payment.escrowState`: `FUNDED` / `PARTIALLY_FUNDED` / `RELEASABLE` / `DISPUTED` / `RELEASING` / `RELEASED` / `REFUNDING` / `REFUNDED` / `FAILED` / `CANCELLED`
- `Dispute.status`: `OPEN` / `UNDER_REVIEW` / `RESOLVED_*` / `CLOSED` as appropriate
The only transitions that may modify funds, release eligibility, or dispute holds are those enforced by the canonical service
layer from the
[`Funds Ledger and Escrow State Machine Specification`](Funds%20Ledger%20and%20Escrow%20State%20Machine%20Specification.md).
## 3) Journey mapping by persona
### 3.1 Unauthenticated user
- See bot start/help and public support command.
- Any authenticated action routes to account-link flow.
- No request write actions without auth link.
### 3.2 Unlinked Telegram user
1. Start in bot or Mini App.
2. Prompt account linking (`/link` equivalent) using signed callback token.
3. Complete account link or return to web flow.
4. After link success, deep link returns user to prior action context (request, offer, payment, or dispute).
### 3.3 Linked buyer
- Browse/create requests, send offer review decision, start payment, upload delivery evidence, open disputes, monitor request state, request release/refund.
- No direct fund release path: Telegram actions read state and submit intent only.
### 3.4 Linked seller
- Receive offer and request notifications, update offer availability, review buyer disputes, upload shipping/proof artifacts.
- No direct payout mutation from Telegram; actions remain canonical requests to existing payment/dispute endpoints.
### 3.5 Admin/support
- Dedicated support context in admin view only (first release).
- Telegram-origin IDs and linked wallet/payment provenance shown in existing admin interfaces.
- Any manual override for Telegram-originated cases follows the same step-up/two-person policy as web flows when configured in
[`Security Ownership and Launch Decision Criteria`](Security%20Ownership%20and%20Launch%20Decision%20Criteria.md).
## 4) Deep-link and context contract
Deep-link entry points in order of priority:
1. `request` detail
2. `offer-review` (accept/reject)
3. `payment-start`
4. `dispute-open` / `dispute-track`
5. `delivery-evidence`
6. `account-link`
Rules:
- No raw IDs in clear URLs when not needed.
- Use short opaque or signed context IDs.
- Expire context tokens and bind to Telegram user + wallet/session.
- Every context hit verifies canonical ownership/state before rendering any action.
### Example startapp routes (illustrative)
- `.../startapp=request&rid=<opaque>`
- `.../startapp=offer&oid=<opaque>`
- `.../startapp=payment&pid=<opaque>`
- `.../startapp=dispute&did=<opaque>`
- `.../startapp=verify`
## 5) Release phasing
| Phase | Telegram surface | Backend dependency |
|---|---|---|
| Phase 0 (MVP) | bot + limited Mini App for state-safe buyer/seller actions; no Telegram-only financial mutations | Payment and ledger gates already enforced |
| Phase 1 | richer navigation, richer filters, deeper support surfaces | Identity linking + event fanout |
| Phase 2 | admin operator actions in Telegram | Additional ops hardening and audit scope |
## 6) Acceptance traceability
Directly mapped to PRD section "Task 1":
- Buyer/seller/admin/support journeys and entry contexts documented: **yes**
- Deep links and entry points defined with phase split: **yes**
- Canonical API/state mapping in table + journey sections: **yes**
- Non-native and admin surfaces identified: **yes**
- Backward compatibility with existing web flows retained: **yes**
## 7) Open items for implementation
1. Finalize concrete deep-link payload schema (opaque token claim set).
2. Finalize Mini App navigation IDs and route-to-state matrix in frontend routing.
3. Confirm unsupported actions for `DISPUTED`/`FAILED` states at Telegram action layer.

View File

@@ -0,0 +1,62 @@
---
title: Task 5.2 Telegram Identity Linking and Session Model
tags: [taskmaster, telegram, identity, session]
created: 2026-05-24
status: implemented-foundation
---
# Task 5.2 Telegram Identity Linking and Session Model
This document captures the first backend implementation pass for Task 5.2.
## Implemented foundation
- `TelegramLink` model maps one active Telegram user ID to one Amanat user.
- `TelegramSession` model stores Mini App session tokens, Telegram user ID,
optional Amanat user ID, initData fingerprint, auth date, source, expiry, and
active state.
- `/api/telegram/miniapp/verify` validates Telegram Mini App `initData` without
creating an Amanat session.
- `/api/telegram/miniapp/session` creates a Telegram session after verified
`initData`.
- `/api/telegram/link` lets an authenticated Amanat user link, read, or unlink a
Telegram account.
## Security model
- Backend verifies Mini App `initData` with Telegram's server-side signature
scheme before trusting Telegram identity.
- `initDataUnsafe` remains client-only display context and is not trusted for
backend authorization.
- Bot accounts are rejected.
- Stale `auth_date` values are rejected by configured TTL.
- Replayed Mini App payloads are rejected inside the configured replay window.
- Duplicate active Telegram-to-Amanat links are rejected.
## Configuration
| Variable | Purpose |
|---|---|
| `TELEGRAM_FEATURE_ENABLED` | Master feature flag |
| `TELEGRAM_MINIAPP_ENABLED` | Mini App session/linking flag |
| `TELEGRAM_BOT_TOKEN` | Server-side token used to verify Mini App signatures |
| `TELEGRAM_INITDATA_MAX_AGE_SEC` | Maximum accepted `auth_date` age |
| `TELEGRAM_INITDATA_REPLAY_WINDOW_MS` | Replay window for duplicate Mini App submissions |
| `TELEGRAM_SESSION_TTL_SEC` | Telegram session lifetime |
## Tests
- `backend/__tests__/telegram-service.test.ts`
- `backend/__tests__/telegram-routes.test.ts`
Coverage includes valid/invalid signature, expired initData, replay detection,
session persistence, link/unlink behavior, duplicate link rejection, route-level
Mini App validation, and secret non-leakage.
## Remaining work
- Move replay protection from in-memory maps to Redis or another shared store for
multi-instance deployments.
- Bind Telegram session tokens to first-party web session controls once the
final session architecture is implemented.
- Add admin/support controls for revoking or blocking Telegram links.

View File

@@ -0,0 +1,48 @@
---
title: Task 5.3 Telegram Bot Command and Notification Foundation
tags: [taskmaster, telegram, bot, notifications]
created: 2026-05-24
status: partial-foundation
---
# Task 5.3 Telegram Bot Command and Notification Foundation
This document captures the first backend bot foundation pass.
## Implemented foundation
- `/api/telegram/status` reports feature and webhook readiness without leaking
bot or webhook secrets.
- `/api/telegram/webhook` is mounted only when Telegram features are enabled.
- Webhook requests require `x-telegram-bot-api-secret-token` to match
`TELEGRAM_WEBHOOK_SECRET_TOKEN`.
- Webhook update handling dedupes by `update_id` or callback ID.
- Webhook handler classifies updates as:
- `command`
- `callback`
- `noop`
- `duplicate`
## Configuration
| Variable | Purpose |
|---|---|
| `TELEGRAM_WEBHOOK_ENABLED` | Enables webhook route |
| `TELEGRAM_WEBHOOK_SECRET_TOKEN` | Telegram webhook secret token |
| `TELEGRAM_WEBHOOK_REPLAY_WINDOW_MS` | Duplicate update replay window |
## Tests
- Service-level tests cover command/callback/noop classification and duplicate
handling.
- Route-level tests cover secret-token rejection and accepted command webhook
processing.
## Remaining work
- Implement actual command actions for `/start`, `/help`, `/link`, `/status`,
`/request`, `/offer`, `/payment`, `/dispute`, and `/settings`.
- Add signed opaque callback payload issuance and resolution.
- Add outbound notification delivery, blocked-bot detection, retry metrics, and
notification preferences.
- Persist webhook dedupe keys in shared storage instead of process memory.

View File

@@ -0,0 +1,42 @@
---
title: Task 5.4 Telegram Mini App Shell Implementation
tags: [taskmaster, telegram, mini-app, frontend]
created: 2026-05-24
status: partial-foundation
---
# Task 5.4 Telegram Mini App Shell Implementation
This document captures the first frontend implementation pass for the Telegram
Mini App surface.
## Implemented foundation
- Added `/telegram` route.
- Added `src/utils/telegram-webapp.ts` for safe Telegram WebApp context parsing.
- Added `TelegramMiniAppShell` with three first-pass states:
- unsupported browser context,
- Telegram detected but unlinked,
- Telegram detected and authenticated web user present.
- Added basic marketplace/escrow action cards for requests, request creation,
payment/escrow, chat, and account.
- Added Telegram chrome attachment helper for MainButton, BackButton, and haptic
feedback when available.
- Added safe-area and Telegram theme helpers.
## Tests
- `frontend/__tests__/utils-test/telegram-webapp.test.ts`
- `frontend/__tests__/sections/telegram/telegram-mini-app-shell.test.tsx`
Coverage includes standard browser fallback, Telegram context parsing,
safe-area/theme fallback, start parameter parsing, unsupported state, unlinked
state, and linked state rendering.
## Remaining work
- Wire Mini App shell to backend Telegram session endpoints.
- Add request/offer/payment/dispute data loading inside the Mini App route.
- Add upload and dispute action surfaces that call canonical backend APIs.
- Add Telegram BackButton routing behavior once final navigation stack is known.
- Add client matrix QA across iOS, Android, Desktop, and Web Telegram clients.

View File

@@ -0,0 +1,105 @@
---
title: Task 5.5 Telegram Payment and Wallet Strategy
tags: [taskmaster, telegram, payment, wallet, provider-adapter]
created: 2026-05-24
status: draft
---
# Task 5.5 Telegram Payment and Wallet Strategy
Source: `/.taskmaster/docs/prd-telegram-native-app-bot-wallet.md`
## 1) Strategy principle for this track
For first release, Telegram-native payment initiation must feed the existing canonical payment system and must **not** bypass
ledger-led state transitions. This means:
- payment proof and funds movement remain authorized by
[`Funds Ledger and Escrow State Machine Specification`](Funds%20Ledger%20and%20Escrow%20State%20Machine%20Specification.md),
- release/refund actions remain governed by service-layer guards and dispute holds,
- Telegram provider adapters are optional extensions, not a hard dependency.
In practice: Telegram can open payment flows through one canonical path first, and optional providers are layered later.
## 2) Option comparison
| Option | Fit for Telegram UX | Funds correctness risk | Regulatory / abuse risk | Complexity | Decision |
|---|---|---|---|---|---|
| Bot API Payments / Telegram Stars | Moderate | High (revenue and settlement mapping differs from existing ledger assumptions) | Medium | Medium | Deferred |
| Wallet Pay | Moderate | Medium-High (token-specific proof path) | High | High | Deferred |
| TON Pay | Medium | Medium-High (provider proof consistency + chain mapping) | High | High | Deferred |
| TON Connect + direct wallet pay | Medium | Medium if proven; requires strict recipient+amount+memo checks | High | High | Deferred |
| Request Network links | High (already introduced) | Low-Medium (existing adapter/service contract) | Medium | Low | **Primary for phase 1** |
| Existing Web3/crypto checkout path | High | Medium (requires recipient/amount/network proof hardening) | High | Medium | Keep as fallback only |
## 3) Selected phase-1 path
### Primary phase-1 strategy
- Telegram bot/Mini App starts the payment by invoking the same canonical payment intent creation API used for web flows.
- Payment provider is written as metadata; provider-neutral adapter remains optional and feature-flagged.
- Telegram identity metadata is persisted with the intent:
- `provider` (e.g., `request_network` or `shkeeper`)
- `telegramUserId`
- `telegramChatId` (if available)
- `launchSource` (`bot`, `mini_app`, `web_fallback`)
- `paymentReference`
- `invoiceId` / `orderId` / `requestId`
- `currency`, `amount`, `expiresAt`
- idempotency key (request-scoped)
### Optional providers
- Wallet Pay / TON Pay / TON Connect paths are documented as optional and must be implemented behind explicit
feature flags and dedicated adapter configuration only when:
- replay-safe proofs are standardized,
- canonical refund/release reconciliation supports provider-native evidence,
- monitoring/reporting has parity with existing paths.
- Until that date, these options are not required to merge for Task 5.1-5.9 handoff.
## 4) Data integrity requirements for any Telegram payment/Wallet path
Before any pay-in is accepted into escrow, enforce:
1. recipient validation (exact canonical recipient for the active escrow policy),
2. asset validation (supported chain + token),
3. amount validation against payment intent and currency precision,
4. memo/reference validation (idempotent and tamper-evident),
5. confirmation proof validation (`confirmed`, `on-chain`, or provider webhook),
6. canonical reconciliation step before mark-complete,
7. invariant re-check with ledger balances before release/refund operations.
These map directly to:
- [`Webhook Security Spec`](Webhook%20Security%20Spec.md)
- [`Payment Provider Adapter Spec`](Payment%20Provider%20Adapter%20Spec.md) (if optional provider is enabled)
- [`Funds Ledger and Escrow State Machine Specification`](Funds%20Ledger%20and%20Escrow%20State%20Machine%20Specification.md) (all financial state transitions).
## 5) Anti-divergence record model
Every Telegram payment intent should write a small canonical trace record with:
- canonical `paymentId`
- `canonicalSourceChannel = telegram`
- `telegramContext` payload hash
- `provider` and `providerReference`
- `idempotencyKey`
- `createdFrom` deep-link/command/callback identifier
- reconciliation status (`created`, `started`, `confirmed`, `failed`, `reconciled`)
This avoids duplicate checkout creation and makes Telegram callback replay and callback mismatch explainable in operations.
## 6) Refund/release compatibility
Refund/release logic remains unchanged from the canonical engine:
- cannot release funds not in releasable state,
- no release/release-amount mutation from Telegram without canonical precondition checks,
- disputed states block direct payout operations,
- release/refund events are only reflected after ledger updates succeed.
## 7) Open follow-up decisions
1. Decide whether to onboard `Wallet Pay` as phase-2 provider once adapter-level proof validation and reconciliation parity are met.
2. Decide whether to expose optional "wallet direct top-up" button in Mini App from day one or keep explicit link-first flow.
3. Finalize provider timeout and retry policy for Telegram-triggered intents under slow-network conditions.

View File

@@ -0,0 +1,38 @@
---
title: Task 5.6 Telegram Escrow Delivery Dispute Release Actions
tags: [taskmaster, telegram, escrow, disputes, release]
created: 2026-05-24
status: planned
---
# Task 5.6 Telegram Escrow Delivery Dispute Release Actions
Task 5.6 is not complete in this first Task 5 pass. This document defines the
implementation boundary required before Telegram shortcuts can affect escrow
state.
## Required behavior
- Telegram users can view current escrow state and next allowed actions.
- Delivery confirmation, evidence upload, refund request, dispute open/respond,
and release approval route through existing backend precondition checks.
- High-risk actions require fresh confirmation and audit logging with Telegram
context.
- Disputed or held funds cannot be released through Telegram shortcuts.
## Required backend constraints
- Use canonical purchase request, payment, dispute, and ledger state.
- Reject release/refund actions unless the funds state machine says the action is
allowed.
- Apply the same step-up and two-person policy as web/admin flows.
- Record Telegram user ID, chat/update ID, deep-link source, and callback token
ID in audit metadata.
## Required tests
- Buyer cannot confirm delivery before delivery state.
- Disputed funds cannot be released.
- Replayed Telegram callback cannot create a second action.
- Stale callback token is rejected.
- Telegram release/refund action emits the same audit fields as web release.

View File

@@ -0,0 +1,40 @@
---
title: Task 5.7 Telegram Admin Support Surface
tags: [taskmaster, telegram, admin, support]
created: 2026-05-24
status: planned
---
# Task 5.7 Telegram Admin Support Surface
Task 5.7 is not complete in this first Task 5 pass. This document defines the
admin/support scope required for Telegram-originated cases.
## Required admin/support visibility
- Telegram linked identity on user profile.
- Bot notification status and blocked-bot state.
- Mini App launch source and latest Telegram session metadata.
- Payment provider and wallet/payment references for Telegram-originated intents.
- Telegram webhook/callback event history for support investigation.
## Required admin/support actions
- Resend link prompt.
- Revoke Telegram link.
- Block Telegram bot access for a user.
- Inspect Telegram-originated event history.
- Escalate payment/dispute issues to canonical admin workflows.
## Security requirements
- Admin overrides remain gated by Task 4 step-up/two-person controls.
- Support can inspect Telegram context but cannot mutate funds state.
- Every support/admin action writes structured audit metadata.
## Required tests
- Support can read Telegram link metadata but cannot release/refund funds.
- Admin link revocation invalidates active Telegram link.
- Blocked Telegram user cannot create a new Mini App session.
- Admin override paths still require step-up when configured.

View File

@@ -0,0 +1,138 @@
---
title: Task 5.8 Telegram Security, Compliance, and Abuse Controls
tags: [taskmaster, telegram, security, compliance, abuse]
created: 2026-05-24
status: draft
---
# Task 5.8 Telegram Security, Compliance, and Abuse Controls
Source: `/.taskmaster/docs/prd-telegram-native-app-bot-wallet.md`
## 1) Threat model alignment
Threats are prioritized by impact to funds and identity:
- forged `initData`
- callback/replay abuse
- deep-link tampering
- phishing / link substitution
- bot token leakage
- spam / command flood
- account takeover
- wallet spoofing
- fake payment proof
- support impersonation
These correspond to existing concerns in
[`Threat Model - Amanat Escrow Platform`](Threat%20Model%20-%20Amanat%20Escrow%20Platform.md), especially **T16** (Telegram deep-link tampering).
## 2) Channel-specific controls
### 2.1 Telegram Web App identity
- Validate every Mini App session using Telegram `initData` with server-side signature verification.
- Never trust raw Telegram identifiers from client payload.
- Reject `initData` outside active bot context.
- Enforce short TTL and replay window for session and deep-link context tokens.
### 2.2 Bot callback and command surface
- Signed opaque callback payloads only; no mutable business state in query strings.
- Update callback handling is idempotent with dedupe key `(callbackId, telegramUpdateId, telegramUserId)`.
- Unknown callback payloads are rejected with audit logging and zero state mutation.
- Hard rate limits on `/api/telegram/webhook` per IP and per Telegram user.
### 2.3 Deep-link and redirect controls
- Signed link payloads with short expiry and bound context.
- Reject tampered/deprecated deep links by schema/nonce/version checks.
- No direct redirect to non-whitelisted hosts.
- Re-validate request ownership after deep-link state resolution.
### 2.4 Wallet and payment evidence controls
- Recipient, token, amount, and network checks must run before trust decisions.
- Payment proof replay rejected when payload hash differs from signed first-seen proof.
- Require provider-normalized reconciliation confirmation before marking funds complete.
### 2.5 Bot token and secrets
Secrets must never be in client-side code and must not be logged:
- `TELEGRAM_BOT_TOKEN`
- `TELEGRAM_WEBHOOK_SECRET`
- `TELEGRAM_WALLET_PAY_TOKEN` (if Wallet Pay enabled)
- `TON_CONNECT_MANIFEST_URL` / TON secret artifacts
- provider API secrets and webhook keys for request-network/SHKeeper paths
Apply Task 4 secret principles:
- separate sandbox and production tokens/environments,
- short rotation cadence,
- strict allowlist for secret-bearing hosts.
## 3) Compliance and secure configuration
### 3.1 CORS / CSP / framing
- Restrict Telegram endpoints to required app origins only.
- CSP in Telegram surfaces should avoid wildcard connect/script allowances.
- Add explicit `frame-ancestors` constraints for web entry surfaces that can be embedded.
### 3.2 Access and authorization
- Apply existing ownership rules from
[`Authorization Matrix - REST and Socket.IO`](Authorization%20Matrix%20-%20REST%20and%20Socket.IO.md).
- Telegram-originated actions use the same actor checks as web actions, including admin step-up and two-person control for high-value override actions.
- Dispute hold checks remain blocking for release/refund.
## 4) Abuse controls
1. **Spam / abuse**
- per-user command/chat throttle,
- per-IP flood detection on webhook.
2. **Account takeover**
- suspicious Telegram session behavior triggers notification disable and forced re-link.
3. **Wallet spoofing**
- signed wallet ownership checks + reconciliation proof checks.
4. **Fake proof**
- malformed proofs logged; never auto-complete payment with unverifiable proof.
5. **Support impersonation**
- support tools require signed admin context, with explicit role and actor logs.
## 5) Monitoring and alerting
Signals (and baseline targets):
- `telegram_update_failures_total` (high if sustained >0.5%)
- `telegram_initdata_invalid_total`
- `telegram_callback_replay_total`
- `telegram_payment_proof_mismatch_total`
- `telegram_notification_blocked_total`
- `telegram_payment_abnormal_status_jump_total`
Alert rules (initial):
- warning after 10 minutes, critical after 30 minutes or sustained spike above baseline.
- any sudden increase in payment mismatch ratio requires incident triage.
Where to emit:
- Sentry for exception/error trending,
- backend logs for structured events,
- existing dashboard metrics hooks and runbook scripts where available.
## 6) Operational controls required before launch
- Secrets rotation checklist completed (bot token and payment/provider keys).
- CORS/CSP reviewed and restricted to Telegram and known frontend origin.
- webhook secrets configured separately for sandbox and production.
- callback replay suppression validated in QA scenarios.
- support impersonation checks and audit trails validated.
## 7) Outstanding controls not yet implemented in this task layer
- Two-way admin alerting channel for Telegram-specific abuse currently depends on operations integration.
- Formal cryptographic replay store for deep-link one-time tokens (recommended before general rollout).
- Telegram payment-specific policy page and end-user risk consent copy.

View File

@@ -0,0 +1,156 @@
---
title: Task 5.9 QA, Rollout, Analytics, and Launch Runbooks
tags: [taskmaster, telegram, qa, rollout, analytics, runbook]
created: 2026-05-24
status: draft
---
# Task 5.9 QA, Rollout, Analytics, and Launch Runbooks
Source: `/.taskmaster/docs/prd-telegram-native-app-bot-wallet.md`
## 1) QA scope for launch readiness
### 1.1 Client matrix (required)
- Telegram iOS
- Telegram Android
- Telegram Desktop
- Telegram Web
- Light / dark themes
- Compact / fullscreen modes
- Normal and slow network
- Blocked bot scenario
- Expired / stale session scenario
- Payment cancellation and abort
- Unlinked user and re-link path
### 1.2 Functional QA checklist
1. Identity and linking
2. Request listing/detail in both bot and Mini App
3. Offer review flow
4. Payment initiation and cancel path
5. Delivery evidence upload
6. Dispute open/respond and status progression
7. Notification quiet/error state
8. Error and blocked-bot behavior
9. Support escalation handoff
### 1.3 Security/abuse QA
- forged/invalid `initData` rejection
- callback replay replayed twice: one success one no-op
- deep-link tampering
- wallet proof mismatch
- callback processing under invalid provider secrets
- admin override behavior and audit event capture
## 2) Environments and rollout
### 2.1 Environment separation
- `telegram-dev-bot` and `telegram-prod-bot` tokens and webhook endpoints must be distinct.
- No shared webhook secret between environments.
- QA and production payment fixtures remain isolated.
### 2.2 Feature flag sequence
1. **Development flag off**: no surface exposed
2. **Internal allowlist**: selected users only (buyer/seller/admin)
3. **Beta cohort**: controlled percentage and fixed org list
4. **Production enablement**: after runbook and KPI thresholds pass
### 2.3 Deployment safety
- If new surface increases payment mismatch or callback failure, immediately pause `TELEGRAM_SURFACE_ENABLED` and keep providers in read-only mode.
- Use existing rollback flow from incident operations and deployment runbooks.
## 3) Analytics and launch KPIs
Track these metrics daily for 14 days after stage advancement:
- activation rate (`activatedTelegramUsers / startedTelegramUsers`)
- link completion rate (`linkedUsers / startedLink`)
- request creation from Telegram (`telegramRequestsCreated`)
- offer response completion (`offerResponses / offersOpened`)
- payment started / payment completed (`telegramPaymentStart`, `telegramPaymentComplete`, `telegramPaymentFail`)
- dispute activity (`disputesOpened`, `disputesResolvedInTelegram`)
- release approvals from Telegram context (`telegramReleaseApprovals`)
- notification opt-outs (`notificationsOptOutRate`)
- callback duplicate ratio (`callbackReplay / callbackTotal`)
- average context resume latency (min and p95)
### Reporting destinations
- Sentry for exception and failure spikes
- application logs for workflow events
- existing monitoring dashboards for rate/latency anomalies
## 4) Launch runbooks
All runbooks are mandatory for Stage-1 rollout and post-launch incidents.
### 4.1 Bot outage
1. Validate webhook endpoint response health.
2. Switch status to notification-only mode where possible.
3. Confirm bot token and webhook URL.
4. Re-route urgent flows to web fallback.
5. Restore Telegram webhook + replay backlog after recovery.
### 4.2 Telegram API outage
1. Confirm external Telegram API status.
2. Temporarily disable deep-link / in-app actions that require Telegram callbacks.
3. Notify users of delayed updates.
4. Keep pending payment states in read-only mode until callback channel is restored.
### 4.3 Payment provider outage
1. Identify affected provider via provider mode and provider health flags.
2. Switch to read-only or alternative provider mode where configured.
3. Run reconciliation before re-enabling full writes.
4. Track stale pending payment age and contact support workflow.
### 4.4 Stuck payment
1. Check payment reconciliation queue and provider status.
2. Verify callback proof and on-chain confirmation.
3. Manually reconcile if allowed by protocol and policy.
4. Escalate if stale > 24h in funded or processing state.
### 4.5 Duplicate callback
1. Validate idempotency path executed correctly.
2. Confirm callback dedupe key retention window.
3. Compare event fingerprint for payload divergence.
4. Mark one path as duplicate no-op and keep audit trail.
### 4.6 Suspicious wallet proof
1. Block automated release/refund for the request.
2. Flag payment and mark for manual ops review.
3. Verify recipient, amount, and tx hash against chain/provider data.
4. Resume only after explicit approval.
### 4.7 Compromised bot token
1. Rotate bot token immediately.
2. Disable bot endpoints and clear webhook secret for 1 hour.
3. Validate callback signatures with new secret.
4. Resume in staged rollout mode with monitoring for 24h.
## 5) Stage exit criteria
- All required QA scenarios pass on iOS/Android/desktop/web.
- No critical webhook/payload mismatch regressions in 24h observation window.
- No unresolved payment stuck items > 24h after manual triage.
- Incident owners can execute all seven runbooks.
- Rollout metrics show non-degrading trend for the first two days.
## 6) Known rollout gaps
1. Fine-grained feature toggles for Telegram in existing observability dashboards are pending.
2. Admin analytics for Telegram-originated releases are schema-dependent and need implementation wiring.
3. Deep-link recovery behavior after prolonged Telegram link expiry still needs UX polishing.