Merge remote-tracking branch 'origin/main'
This commit is contained in:
27
.taskmaster/README.md
Normal file
27
.taskmaster/README.md
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
# Taskmaster workspace for Amanat PRDs
|
||||||
|
|
||||||
|
This docs-side Taskmaster setup tracks the product/security PRDs from the documentation vault.
|
||||||
|
|
||||||
|
## Source PRDs
|
||||||
|
|
||||||
|
- `prd-mermaid-diagram-rendering-stabilization.md`
|
||||||
|
- `prd-platform-audit-remediation-plan-2026-05-24.md`
|
||||||
|
- `prd-request-network-migration-and-funds-management.md`
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
From `nick-doc`, developers can use Taskmaster-compatible tooling against `.taskmaster/tasks/tasks.json`.
|
||||||
|
|
||||||
|
Common commands, once `task-master-ai` is installed/configured:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
task-master list
|
||||||
|
task-master show 2
|
||||||
|
task-master show 3.4
|
||||||
|
task-master next
|
||||||
|
task-master set-status --id=2.1 --status=in-progress
|
||||||
|
```
|
||||||
|
|
||||||
|
The Mermaid PRD is already marked `done` because its source PRD records the full parser sweep as passing. The security and migration PRDs are pending implementation.
|
||||||
|
|
||||||
|
No API keys are committed here. Configure API keys locally or in MCP/editor config if AI-assisted Taskmaster commands are needed.
|
||||||
40
.taskmaster/config.json
Normal file
40
.taskmaster/config.json
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
{
|
||||||
|
"models": {
|
||||||
|
"main": {
|
||||||
|
"provider": "anthropic",
|
||||||
|
"modelId": "claude-sonnet-4-20250514",
|
||||||
|
"maxTokens": 64000,
|
||||||
|
"temperature": 0.2
|
||||||
|
},
|
||||||
|
"research": {
|
||||||
|
"provider": "perplexity",
|
||||||
|
"modelId": "sonar",
|
||||||
|
"maxTokens": 8700,
|
||||||
|
"temperature": 0.1
|
||||||
|
},
|
||||||
|
"fallback": {
|
||||||
|
"provider": "anthropic",
|
||||||
|
"modelId": "claude-3-7-sonnet-20250219",
|
||||||
|
"maxTokens": 120000,
|
||||||
|
"temperature": 0.2
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"global": {
|
||||||
|
"logLevel": "info",
|
||||||
|
"debug": false,
|
||||||
|
"defaultNumTasks": 10,
|
||||||
|
"defaultSubtasks": 5,
|
||||||
|
"defaultPriority": "medium",
|
||||||
|
"projectName": "Amanat Documentation PRDs",
|
||||||
|
"defaultTag": "master",
|
||||||
|
"ollamaBaseURL": "http://localhost:11434/api",
|
||||||
|
"bedrockBaseURL": "https://bedrock.us-east-1.amazonaws.com",
|
||||||
|
"responseLanguage": "English",
|
||||||
|
"enableCodebaseAnalysis": true,
|
||||||
|
"enableProxy": false,
|
||||||
|
"anonymousTelemetry": false
|
||||||
|
},
|
||||||
|
"storage": {
|
||||||
|
"type": "file"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,560 @@
|
|||||||
|
---
|
||||||
|
title: Backend Stack Security and Refactor Assessment
|
||||||
|
tags: [audit, security, backend, architecture, payments, refactor]
|
||||||
|
created: 2026-05-24
|
||||||
|
status: advisory
|
||||||
|
---
|
||||||
|
|
||||||
|
# Backend Stack Security and Refactor Assessment
|
||||||
|
|
||||||
|
## Purpose
|
||||||
|
|
||||||
|
This document records an advisory assessment of whether Amanat should keep the current Node/Express backend, harden it in place, or migrate at least the security-critical backend surface to another technology stack.
|
||||||
|
|
||||||
|
The conclusion is intentionally strategic rather than implementation-heavy. It should be used as input for architecture review, security planning, and refactor scoping.
|
||||||
|
|
||||||
|
## Executive summary
|
||||||
|
|
||||||
|
Amanat is not a normal CRUD marketplace. It is a financial escrow platform with authentication, realtime communication, crypto payment intake, payout/release flows, provider webhooks, and dispute-sensitive fund movement.
|
||||||
|
|
||||||
|
The main security risk is not simply "Node is insecure." The larger issue is that the current backend mixes high-risk financial state transitions, webhook handling, realtime room membership, admin operations, test/demo endpoints, and ordinary marketplace APIs in one Express application.
|
||||||
|
|
||||||
|
Moving away from Node/Express may reduce npm supply-chain exposure and improve long-term auditability, but it will not automatically fix the most important risks. The immediate priority should be to define and enforce the correct security architecture:
|
||||||
|
|
||||||
|
- A canonical funds ledger.
|
||||||
|
- A strict escrow/payment/dispute state machine.
|
||||||
|
- Centralized authorization and ownership checks.
|
||||||
|
- Signed webhook handling with idempotency.
|
||||||
|
- Server-derived realtime authorization.
|
||||||
|
- Secure session handling.
|
||||||
|
- A provider-neutral payment abstraction.
|
||||||
|
|
||||||
|
Recommended approach:
|
||||||
|
|
||||||
|
1. Harden the existing backend immediately.
|
||||||
|
2. Define the target payment, ledger, and auth architecture in documentation.
|
||||||
|
3. Extract or rewrite only the security-critical backend core if the team can support the new stack.
|
||||||
|
4. Keep lower-risk marketplace, chat, notification, and dashboard APIs in TypeScript until the core is stable.
|
||||||
|
|
||||||
|
Default recommendation: do not rewrite the entire backend at once. If a rewrite is chosen, start with payment/auth/escrow core services, preferably in Go or Kotlin/Java, while preserving current product behavior behind stable API contracts.
|
||||||
|
|
||||||
|
## Current system profile
|
||||||
|
|
||||||
|
Observed architecture:
|
||||||
|
|
||||||
|
- Frontend: Next.js, React, MUI, Web3, Socket.IO client.
|
||||||
|
- Backend: Express 5, TypeScript, Mongoose, Socket.IO, SHKeeper, Web3 transaction verification, SMTP, OpenAI integration.
|
||||||
|
- Storage: MongoDB and Redis, though Redis is not consistently used as a shared state authority for all security-sensitive flows.
|
||||||
|
- Realtime: Socket.IO rooms for user, buyer, seller, chat, and purchase-request updates.
|
||||||
|
- Payments: SHKeeper pay-in, SHKeeper payout, decentralized/Web3 payment verification, manual/admin payout paths.
|
||||||
|
- Docs: existing logical audit and remediation documents already identify several critical flaws.
|
||||||
|
|
||||||
|
The backend currently acts as:
|
||||||
|
|
||||||
|
- API server.
|
||||||
|
- Realtime server.
|
||||||
|
- Payment orchestrator.
|
||||||
|
- Webhook processor.
|
||||||
|
- Background-job runner.
|
||||||
|
- File upload server.
|
||||||
|
- Auth/session issuer.
|
||||||
|
- Admin operations surface.
|
||||||
|
|
||||||
|
That is too much responsibility in one process for a financial platform unless the architecture is very tightly controlled.
|
||||||
|
|
||||||
|
## Code-backed security observations
|
||||||
|
|
||||||
|
These findings are consistent with the existing audit docs and representative source review.
|
||||||
|
|
||||||
|
### Payment and funds risks
|
||||||
|
|
||||||
|
- Payment state is largely represented by mutable `Payment.status` and `escrowState` fields rather than an immutable funds ledger.
|
||||||
|
- Pay-in, manual confirmation, wallet monitoring, webhook handling, and payout flows can converge on the same records through different paths.
|
||||||
|
- Release/refund eligibility is not fully centralized around ledger invariants.
|
||||||
|
- The existing docs identify a dispute/escrow race: disputes do not reliably create an enforceable hold before release.
|
||||||
|
- `Payment` uses mixed/string-compatible references for some core links, reducing referential integrity and query safety.
|
||||||
|
- Some payment mutation/history routes were exposed without sufficient authentication or ownership enforcement.
|
||||||
|
- Web3 verification has been documented as relying primarily on transaction receipt success rather than strict token, recipient, and amount verification.
|
||||||
|
|
||||||
|
Security implication: a backend stack change alone will not fix this. The platform needs a funds ledger and state machine first.
|
||||||
|
|
||||||
|
### Authentication and session risks
|
||||||
|
|
||||||
|
- Browser tokens are stored in `localStorage`, increasing impact from XSS.
|
||||||
|
- Passkey/WebAuthn behavior is described in the audit docs as stubbed/incomplete and challenge storage is process-local.
|
||||||
|
- Refresh-token behavior differs between auth paths.
|
||||||
|
- Admin-sensitive routes need explicit role enforcement, not just authentication.
|
||||||
|
|
||||||
|
Security implication: migration should include a session architecture decision, not just a framework change.
|
||||||
|
|
||||||
|
### Realtime risks
|
||||||
|
|
||||||
|
- Socket.IO room joins are client-driven by IDs such as `join-user-room`, `join-buyer-room`, and `join-seller-room`.
|
||||||
|
- The server should derive room membership from authenticated socket identity, not trust client-supplied user IDs.
|
||||||
|
|
||||||
|
Security implication: realtime authorization needs to be treated like API authorization.
|
||||||
|
|
||||||
|
### Rate limiting and abuse controls
|
||||||
|
|
||||||
|
- Global rate limiting is explicitly disabled in the Express app.
|
||||||
|
- Sensitive paths need tiered limits: auth, verification, file upload, AI, payment, webhook, chat.
|
||||||
|
- AI endpoints and email endpoints can create cost or abuse exposure if not authenticated and rate-limited.
|
||||||
|
|
||||||
|
Security implication: this is an immediate hardening task regardless of backend stack.
|
||||||
|
|
||||||
|
### Webhook and provider risks
|
||||||
|
|
||||||
|
- Webhooks must be verified using raw-body signatures, not reconstructed JSON when signatures depend on raw bytes.
|
||||||
|
- Webhook delivery must be idempotent.
|
||||||
|
- Unknown, duplicate, malformed, and failed webhooks should be visible in structured records or dead-letter storage.
|
||||||
|
- Provider callbacks should create reconciliation events, not directly release funds.
|
||||||
|
|
||||||
|
Security implication: payment provider integration should be isolated behind a provider-neutral service contract.
|
||||||
|
|
||||||
|
### Supply-chain risks
|
||||||
|
|
||||||
|
The Node/npm ecosystem has real and recurring supply-chain risk. For this codebase, that risk matters because both frontend and backend depend heavily on npm packages.
|
||||||
|
|
||||||
|
Relevant 2026 context:
|
||||||
|
|
||||||
|
- Express published February 2026 security releases, including high-severity Multer issues affecting versions before 2.1.0. The backend manifest currently specifies `multer: ^2.0.2`, so the resolved lockfile version should be reviewed and updated if necessary.
|
||||||
|
- Node.js published March 2026 security releases across active release lines.
|
||||||
|
- Microsoft reported an Axios npm supply-chain compromise in March 2026. This project uses Axios on frontend and backend.
|
||||||
|
- TanStack published a May 2026 npm compromise postmortem. This project uses `@tanstack/react-query`.
|
||||||
|
|
||||||
|
References:
|
||||||
|
|
||||||
|
- Express security release, 2026-02-27: https://expressjs.com/2026/02/27/security-releases.html
|
||||||
|
- Node.js March 2026 security releases: https://nodejs.org/en/blog/vulnerability/march-2026-security-releases
|
||||||
|
- Microsoft on Axios npm supply-chain compromise: https://www.microsoft.com/en-us/security/blog/2026/04/01/mitigating-the-axios-npm-supply-chain-compromise/
|
||||||
|
- TanStack npm supply-chain compromise postmortem: https://tanstack.com/blog/npm-supply-chain-compromise-postmortem
|
||||||
|
|
||||||
|
Security implication: npm supply-chain controls are required even if the backend is rewritten, because the frontend remains npm-based.
|
||||||
|
|
||||||
|
## Should the backend move away from Node/Express?
|
||||||
|
|
||||||
|
### Reasons to keep and harden first
|
||||||
|
|
||||||
|
- The product already exists and has working business flows.
|
||||||
|
- A full rewrite risks reintroducing escrow/payment bugs.
|
||||||
|
- The most dangerous issues are domain/state/authorization issues, not syntax or framework issues.
|
||||||
|
- Hardening can reduce immediate exposure faster than a rewrite.
|
||||||
|
- The team may currently be more productive in TypeScript.
|
||||||
|
|
||||||
|
### Reasons to migrate at least the backend core
|
||||||
|
|
||||||
|
- Financial backend code benefits from a smaller, stricter dependency footprint.
|
||||||
|
- Payment, ledger, webhook, and payout flows need strong invariants and auditability.
|
||||||
|
- Express makes it easy to accumulate route-level exceptions, test endpoints, and inconsistent middleware.
|
||||||
|
- Node/npm supply-chain exposure is material and recurring.
|
||||||
|
- TypeScript runtime enforcement is limited unless paired with strict schema validation everywhere.
|
||||||
|
- A separate payment core can be more easily audited, threat-modeled, tested, and locked down.
|
||||||
|
|
||||||
|
### Balanced conclusion
|
||||||
|
|
||||||
|
It is security-wise reasonable to move the highest-risk backend core away from Node/Express, but only after the target security model is specified.
|
||||||
|
|
||||||
|
Do not begin with a full product rewrite. Begin with a security-critical core extraction:
|
||||||
|
|
||||||
|
- Auth/session/token authority.
|
||||||
|
- Payment intent creation.
|
||||||
|
- Provider webhook processing.
|
||||||
|
- Funds ledger and reconciliation.
|
||||||
|
- Release/refund/dispute-hold enforcement.
|
||||||
|
- Admin payout approval and audit logging.
|
||||||
|
|
||||||
|
Keep lower-risk modules in the current stack until the core is stable:
|
||||||
|
|
||||||
|
- Marketplace browsing/listing.
|
||||||
|
- Request templates.
|
||||||
|
- Chat and notifications, after socket authorization fixes.
|
||||||
|
- Admin dashboard reads.
|
||||||
|
- File upload, after hardening or moving to object storage.
|
||||||
|
|
||||||
|
## Stack options
|
||||||
|
|
||||||
|
### Go
|
||||||
|
|
||||||
|
Best fit if the team wants a smaller, operationally simple, security-focused payment core.
|
||||||
|
|
||||||
|
Strengths:
|
||||||
|
|
||||||
|
- Small binaries and deployment footprint.
|
||||||
|
- Lower dependency surface than typical Node services.
|
||||||
|
- Strong standard library for HTTP, crypto, JSON, and concurrency.
|
||||||
|
- Good fit for webhook receivers, ledger services, workers, and reconciliation jobs.
|
||||||
|
- Easy to run static analysis and produce reproducible builds.
|
||||||
|
|
||||||
|
Weaknesses:
|
||||||
|
|
||||||
|
- Less ergonomic than TypeScript for rapid product iteration.
|
||||||
|
- Requires team comfort with Go idioms.
|
||||||
|
- API/schema generation must be designed deliberately.
|
||||||
|
|
||||||
|
Assessment: recommended first choice for a payment/ledger/auth core if the team can maintain Go.
|
||||||
|
|
||||||
|
### Kotlin/Java with Spring Boot
|
||||||
|
|
||||||
|
Best fit if the team wants enterprise-grade structure, mature auth patterns, and strong ecosystem support.
|
||||||
|
|
||||||
|
Strengths:
|
||||||
|
|
||||||
|
- Mature security and validation ecosystem.
|
||||||
|
- Strong typing and tooling.
|
||||||
|
- Good for complex domain services and audit-heavy systems.
|
||||||
|
- Well-understood operational patterns.
|
||||||
|
|
||||||
|
Weaknesses:
|
||||||
|
|
||||||
|
- Heavier runtime and framework footprint.
|
||||||
|
- More ceremony.
|
||||||
|
- Slower iteration for a small team.
|
||||||
|
|
||||||
|
Assessment: strong choice for a larger engineering team or enterprise-style compliance needs.
|
||||||
|
|
||||||
|
### Rust
|
||||||
|
|
||||||
|
Best fit if maximum memory safety and correctness are worth slower delivery.
|
||||||
|
|
||||||
|
Strengths:
|
||||||
|
|
||||||
|
- Strong compile-time safety.
|
||||||
|
- Good for cryptographic and high-assurance components.
|
||||||
|
- Very low runtime footprint.
|
||||||
|
|
||||||
|
Weaknesses:
|
||||||
|
|
||||||
|
- Higher implementation cost.
|
||||||
|
- Smaller hiring pool.
|
||||||
|
- Web API development may be slower.
|
||||||
|
|
||||||
|
Assessment: attractive for narrow cryptographic or transaction-verification components, but probably too costly for the whole backend unless the team is already strong in Rust.
|
||||||
|
|
||||||
|
### Python/FastAPI
|
||||||
|
|
||||||
|
Best fit if rapid backend development and clean API typing are more important than strict compile-time guarantees.
|
||||||
|
|
||||||
|
Strengths:
|
||||||
|
|
||||||
|
- Fast development.
|
||||||
|
- Good validation with Pydantic.
|
||||||
|
- Good for admin tools and internal services.
|
||||||
|
|
||||||
|
Weaknesses:
|
||||||
|
|
||||||
|
- Supply-chain risk remains.
|
||||||
|
- Runtime typing and async behavior require discipline.
|
||||||
|
- Less compelling than Go/Kotlin for a financial core.
|
||||||
|
|
||||||
|
Assessment: acceptable for internal services, not the preferred payment-core target.
|
||||||
|
|
||||||
|
### Continue TypeScript/Node with stronger architecture
|
||||||
|
|
||||||
|
Best fit if team capacity cannot support another backend language yet.
|
||||||
|
|
||||||
|
Required conditions:
|
||||||
|
|
||||||
|
- Strict route registration policy.
|
||||||
|
- Runtime validation on every boundary.
|
||||||
|
- No test/demo routes in production builds.
|
||||||
|
- Full lockfile and package provenance controls.
|
||||||
|
- Centralized auth, ownership, and role guards.
|
||||||
|
- Ledger-first payment architecture.
|
||||||
|
- Secure cookies or a documented token-storage risk acceptance.
|
||||||
|
- Socket auth middleware.
|
||||||
|
- Redis-backed challenge/idempotency/rate-limit storage.
|
||||||
|
|
||||||
|
Assessment: viable short term, but the security bar must be raised significantly.
|
||||||
|
|
||||||
|
## Recommended target architecture
|
||||||
|
|
||||||
|
### Phase 0: Immediate containment
|
||||||
|
|
||||||
|
Goal: reduce current high-risk exposure without broad redesign.
|
||||||
|
|
||||||
|
Actions:
|
||||||
|
|
||||||
|
- Disable or protect test/demo payment and email endpoints in production.
|
||||||
|
- Require authentication and ownership checks on all payment, notification, AI, and file routes.
|
||||||
|
- Re-enable rate limiting with stricter limits on auth, payment, AI, file upload, and webhook paths.
|
||||||
|
- Add admin role checks to admin routes.
|
||||||
|
- Stop accepting arbitrary `userId` from clients for private data.
|
||||||
|
- Validate all payment mutations through centralized service methods.
|
||||||
|
- Lock Socket.IO room membership to server-verified identity.
|
||||||
|
- Review and update lockfiles for known vulnerable packages.
|
||||||
|
- Rotate any committed or publicly visible secrets.
|
||||||
|
|
||||||
|
### Phase 1: Architecture specification
|
||||||
|
|
||||||
|
Goal: define the new security model before implementation.
|
||||||
|
|
||||||
|
Documents to produce are listed in the "Required documentation" section below.
|
||||||
|
|
||||||
|
### Phase 2: Payment and ledger extraction
|
||||||
|
|
||||||
|
Goal: move funds logic behind a provider-neutral service.
|
||||||
|
|
||||||
|
Introduce:
|
||||||
|
|
||||||
|
- `FundsAccount`
|
||||||
|
- `LedgerEntry`
|
||||||
|
- `FundsBalance`
|
||||||
|
- `PaymentIntent`
|
||||||
|
- `PaymentProviderEvent`
|
||||||
|
- `ReleaseInstruction`
|
||||||
|
- `RefundInstruction`
|
||||||
|
- `DisputeHold`
|
||||||
|
|
||||||
|
Key rule: provider webhooks do not directly release funds. They create verified events and ledger entries.
|
||||||
|
|
||||||
|
### Phase 3: Backend-core rewrite or service split
|
||||||
|
|
||||||
|
Goal: decide whether the extracted core remains TypeScript or moves to Go/Kotlin.
|
||||||
|
|
||||||
|
Recommended split:
|
||||||
|
|
||||||
|
- `core-payments`: payment intent, webhook, ledger, release/refund, reconciliation.
|
||||||
|
- `core-auth`: sessions, passkeys, OAuth, token issuance, session revocation.
|
||||||
|
- `marketplace-api`: purchase requests, offers, categories, templates.
|
||||||
|
- `realtime-api`: chat, notifications, socket rooms.
|
||||||
|
|
||||||
|
The split can be logical first, physical later.
|
||||||
|
|
||||||
|
### Phase 4: Full migration only if justified
|
||||||
|
|
||||||
|
Goal: avoid rewriting stable lower-risk product surfaces prematurely.
|
||||||
|
|
||||||
|
Only consider full backend migration after:
|
||||||
|
|
||||||
|
- Payment core is stable.
|
||||||
|
- Auth/session model is stable.
|
||||||
|
- API contracts are documented and tested.
|
||||||
|
- Legacy payment records are migrated or safely read-only.
|
||||||
|
- Team has demonstrated production maintenance ability in the new stack.
|
||||||
|
|
||||||
|
## Required documentation before refactor
|
||||||
|
|
||||||
|
### 1. Threat Model
|
||||||
|
|
||||||
|
Purpose: identify what must be protected and how it can be attacked.
|
||||||
|
|
||||||
|
Should include:
|
||||||
|
|
||||||
|
- Assets: user accounts, admin accounts, wallet addresses, payment records, funds, webhook secrets, API keys, private notifications.
|
||||||
|
- Actors: buyer, seller, admin, support, unauthenticated attacker, compromised user, compromised admin, provider, malicious webhook sender.
|
||||||
|
- Trust boundaries: browser, backend, database, Redis, provider APIs, wallet/RPC, admin UI, Socket.IO.
|
||||||
|
- Abuse cases: fake payment proof, replayed webhook, arbitrary room join, stolen token, double payout, dispute bypass, email/AI abuse.
|
||||||
|
|
||||||
|
### 2. Funds Ledger Specification
|
||||||
|
|
||||||
|
Purpose: make money movement auditable and provider-independent.
|
||||||
|
|
||||||
|
Should define:
|
||||||
|
|
||||||
|
- Account model per purchase request/order.
|
||||||
|
- Immutable ledger entry types.
|
||||||
|
- Derived balance model.
|
||||||
|
- Gross amount, provider fees, platform fees, held amount, disputed amount, releasable amount, released amount, refunded amount.
|
||||||
|
- Idempotency keys.
|
||||||
|
- Reconciliation behavior.
|
||||||
|
|
||||||
|
### 3. Escrow State Machine
|
||||||
|
|
||||||
|
Purpose: define legal transitions once.
|
||||||
|
|
||||||
|
Should include:
|
||||||
|
|
||||||
|
- Purchase request states.
|
||||||
|
- Payment states.
|
||||||
|
- Escrow/funds states.
|
||||||
|
- Dispute states.
|
||||||
|
- Valid transitions and forbidden transitions.
|
||||||
|
- Who or what can trigger each transition.
|
||||||
|
- Required preconditions for release, refund, cancellation, dispute hold, and admin override.
|
||||||
|
|
||||||
|
### 4. Authorization Matrix
|
||||||
|
|
||||||
|
Purpose: remove route-by-route ambiguity.
|
||||||
|
|
||||||
|
Should map every endpoint and socket event to:
|
||||||
|
|
||||||
|
- Public, authenticated, owner, seller, buyer, admin, support, or service role.
|
||||||
|
- Required ownership checks.
|
||||||
|
- Required object state.
|
||||||
|
- Rate-limit tier.
|
||||||
|
- Audit-log requirement.
|
||||||
|
|
||||||
|
### 5. Payment Provider Adapter Spec
|
||||||
|
|
||||||
|
Purpose: decouple business logic from SHKeeper, Request Network, manual wallet flow, and future providers.
|
||||||
|
|
||||||
|
Should define:
|
||||||
|
|
||||||
|
- `createPayInIntent`
|
||||||
|
- `getPayInStatus`
|
||||||
|
- `handleProviderWebhook`
|
||||||
|
- `createHostedPaymentLink`
|
||||||
|
- `createReleaseInstruction`
|
||||||
|
- `createRefundInstruction`
|
||||||
|
- `getPayoutStatus`
|
||||||
|
- `searchProviderPayments`
|
||||||
|
|
||||||
|
Provider-specific metadata should be namespaced and never become the canonical funds state.
|
||||||
|
|
||||||
|
### 6. Webhook Security Spec
|
||||||
|
|
||||||
|
Purpose: prevent forged, replayed, or silently failed provider events.
|
||||||
|
|
||||||
|
Should define:
|
||||||
|
|
||||||
|
- Raw-body signature verification.
|
||||||
|
- Accepted headers and algorithms.
|
||||||
|
- Replay prevention.
|
||||||
|
- Delivery ID/idempotency handling.
|
||||||
|
- Unknown payment behavior.
|
||||||
|
- Duplicate event behavior.
|
||||||
|
- Retry semantics.
|
||||||
|
- Dead-letter/replay storage.
|
||||||
|
- Alerting thresholds.
|
||||||
|
|
||||||
|
### 7. Session and Auth Architecture
|
||||||
|
|
||||||
|
Purpose: decide how browser sessions should work for a financial platform.
|
||||||
|
|
||||||
|
Should define:
|
||||||
|
|
||||||
|
- Access token lifetime.
|
||||||
|
- Refresh token lifetime and rotation.
|
||||||
|
- Whether tokens move from `localStorage` to `httpOnly` cookies.
|
||||||
|
- CSRF strategy if cookies are used.
|
||||||
|
- Passkey/WebAuthn implementation requirements.
|
||||||
|
- OAuth requirements.
|
||||||
|
- Device/session revocation.
|
||||||
|
- Admin step-up authentication for payouts or role changes.
|
||||||
|
|
||||||
|
### 8. Realtime Authorization Spec
|
||||||
|
|
||||||
|
Purpose: make Socket.IO events subject to the same security model as REST.
|
||||||
|
|
||||||
|
Should define:
|
||||||
|
|
||||||
|
- Socket handshake authentication.
|
||||||
|
- Server-derived room membership.
|
||||||
|
- Which rooms exist.
|
||||||
|
- Who may join each room.
|
||||||
|
- Whether room membership changes with request/payment/dispute state.
|
||||||
|
- Event payload privacy rules.
|
||||||
|
|
||||||
|
### 9. Migration Plan
|
||||||
|
|
||||||
|
Purpose: avoid breaking current payments and historical records.
|
||||||
|
|
||||||
|
Should include:
|
||||||
|
|
||||||
|
- SHKeeper legacy read path.
|
||||||
|
- New provider feature flag.
|
||||||
|
- Ledger backfill strategy.
|
||||||
|
- Data validation report before enforcement.
|
||||||
|
- Rollback criteria.
|
||||||
|
- Cutover date for old webhook routes.
|
||||||
|
- Operator manual reconciliation workflow.
|
||||||
|
|
||||||
|
### 10. Secure Build and Supply-Chain Policy
|
||||||
|
|
||||||
|
Purpose: reduce npm and dependency compromise risk.
|
||||||
|
|
||||||
|
Should define:
|
||||||
|
|
||||||
|
- Package manager and lockfile policy.
|
||||||
|
- CI install mode.
|
||||||
|
- Dependency update cadence.
|
||||||
|
- Security advisory monitoring.
|
||||||
|
- npm provenance/signature policy where available.
|
||||||
|
- Secrets handling.
|
||||||
|
- Production build reproducibility.
|
||||||
|
- Separation of frontend npm risk from backend core risk.
|
||||||
|
|
||||||
|
### 11. Operational Runbooks
|
||||||
|
|
||||||
|
Purpose: make security incidents and payment failures survivable.
|
||||||
|
|
||||||
|
Should include:
|
||||||
|
|
||||||
|
- Failed webhook.
|
||||||
|
- Duplicate payment.
|
||||||
|
- Missing payment.
|
||||||
|
- Stuck release.
|
||||||
|
- Disputed release attempt.
|
||||||
|
- Compromised admin.
|
||||||
|
- Leaked API key.
|
||||||
|
- Provider outage.
|
||||||
|
- Chain/RPC outage.
|
||||||
|
- Suspicious payment proof.
|
||||||
|
- npm/package compromise.
|
||||||
|
|
||||||
|
## Decision framework
|
||||||
|
|
||||||
|
Use the following questions before choosing a rewrite:
|
||||||
|
|
||||||
|
- Is the current goal safe launch, or long-term platform rebuild?
|
||||||
|
- Is the team willing to delay feature work for a payment-core redesign?
|
||||||
|
- Can the team maintain Go/Kotlin/Rust in production?
|
||||||
|
- Is the biggest current risk supply chain, or incorrect money movement?
|
||||||
|
- Are admin actions trusted, or should high-risk actions require step-up approval?
|
||||||
|
- Should Amanat custody funds, or should the provider/payment network hold or route them?
|
||||||
|
- Are disputes central to the product, or rare manual exceptions?
|
||||||
|
- Is auditability a regulatory/business requirement or only an internal safety goal?
|
||||||
|
|
||||||
|
## Recommended decision
|
||||||
|
|
||||||
|
Near term:
|
||||||
|
|
||||||
|
- Harden the current Express backend.
|
||||||
|
- Disable unsafe production routes.
|
||||||
|
- Add centralized authorization and rate limiting.
|
||||||
|
- Fix Web3 verification.
|
||||||
|
- Fix Socket.IO authorization.
|
||||||
|
- Disable passkeys unless implemented with real WebAuthn.
|
||||||
|
- Begin ledger/state-machine documentation immediately.
|
||||||
|
|
||||||
|
Medium term:
|
||||||
|
|
||||||
|
- Build a provider-neutral payment and funds layer.
|
||||||
|
- Add immutable ledger entries.
|
||||||
|
- Move release/refund/dispute-hold checks into the central payment/funds service.
|
||||||
|
- Keep SHKeeper compatibility read-only for legacy records.
|
||||||
|
- Add Request Network or another provider behind the adapter if desired.
|
||||||
|
|
||||||
|
Long term:
|
||||||
|
|
||||||
|
- Rewrite the payment/auth/escrow core in Go or Kotlin/Java if the team can support it.
|
||||||
|
- Do not rewrite the entire backend until the core is proven.
|
||||||
|
- Keep lower-risk modules in TypeScript until there is a business or operational reason to migrate them.
|
||||||
|
|
||||||
|
## Open questions for leadership and engineering
|
||||||
|
|
||||||
|
1. Is launch timeline more important than a full payment/funds redesign?
|
||||||
|
2. Should passkeys be removed from launch scope until production-grade WebAuthn is implemented?
|
||||||
|
3. Should browser auth move to `httpOnly` cookies even if that requires CSRF work and frontend changes?
|
||||||
|
4. Should every payout require admin step-up authentication or two-person approval?
|
||||||
|
5. Should Amanat keep funds in a platform-controlled escrow wallet, or should provider-mediated payment pages become the default?
|
||||||
|
6. Is Request Network a desired provider migration, or just one option being explored?
|
||||||
|
7. What new backend stack can the team realistically operate for the next two years?
|
||||||
|
8. What is the acceptable level of temporary dual-stack complexity during migration?
|
||||||
|
9. Do we need formal external penetration testing before public launch?
|
||||||
|
10. Who owns security decisions: product, backend, DevOps, or a dedicated security owner?
|
||||||
|
|
||||||
|
## Relationship to existing docs
|
||||||
|
|
||||||
|
This assessment complements:
|
||||||
|
|
||||||
|
- [[Platform Logical Audit - 2026-05-24]]
|
||||||
|
- [[PRD - Platform Audit Remediation Plan (2026-05-24)]]
|
||||||
|
- [[PRD - Request Network Migration and Funds Management]]
|
||||||
|
- [[Security Architecture]]
|
||||||
|
- [[Payment Flow - SHKeeper]]
|
||||||
|
- [[Payment Flow - DePay & Web3]]
|
||||||
|
- [[Escrow Flow]]
|
||||||
|
- [[Dispute Flow]]
|
||||||
|
|
||||||
|
The existing remediation PRD is the tactical hardening plan. This document is the strategic backend-stack and refactor assessment.
|
||||||
118
.taskmaster/docs/prd-mermaid-diagram-rendering-stabilization.md
Normal file
118
.taskmaster/docs/prd-mermaid-diagram-rendering-stabilization.md
Normal file
@@ -0,0 +1,118 @@
|
|||||||
|
# PRD: Mermaid Diagram Rendering Stabilization
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
- Scope: Documentation Mermaid diagrams in this vault.
|
||||||
|
- Discovery date: 2026-05-24.
|
||||||
|
- Total Mermaid blocks checked: `57`.
|
||||||
|
- Total failing blocks: `11`.
|
||||||
|
- Tooling used: `@mermaid-js/mermaid-cli` parse validation for each extracted block.
|
||||||
|
|
||||||
|
## Goal
|
||||||
|
Create a pass-ready task queue of Mermaid syntax/render issues so each diagram can be corrected one-by-one without guessing.
|
||||||
|
|
||||||
|
## Acceptance Criteria
|
||||||
|
- Every Mermaid block parses successfully with the same mmdc-based syntax validation.
|
||||||
|
- Diagrams render in Obsidian/markdown previews without parser errors.
|
||||||
|
- Each corrected block retains the same intent and participant names where possible.
|
||||||
|
|
||||||
|
## Task 1 - Security Architecture: Email + password sequence
|
||||||
|
- **File:** `01 - Architecture/Security Architecture.md`
|
||||||
|
- **Diagram range:** `38-57` (Authentication layers / 2.1)
|
||||||
|
- **Error:** Parse error line 12: `...nAttempts; lock at N BE-->>FE: 4`
|
||||||
|
- **Likely issue:** Sequence parser is choking around a message containing inline punctuation and line continuation (`;` and `...`), likely interpreted as malformed sequence text.
|
||||||
|
- **Fix:** Keep the message text parser-safe (single simple `:` message per line; avoid special separators like unescaped semicolons) and rerun parser.
|
||||||
|
|
||||||
|
## Task 2 - Authentication Flow: Login sequence
|
||||||
|
- **File:** `04 - Flows/Authentication Flow.md`
|
||||||
|
- **Diagram range:** `57-90` (`## Sequence diagram`)
|
||||||
|
- **Error:** Parse error line 48: `...Tokens.push(refresh) BE->>BE: ge`
|
||||||
|
- **Likely issue:** Line includes inline method-like token with parentheses-like/space patterns and tokenization ambiguity.
|
||||||
|
- **Fix:** Replace the problematic statement with plain text in message, e.g. `BE->>DB: User.refreshTokens.push(refreshToken)` as one line.
|
||||||
|
|
||||||
|
## Task 3 - Authentication Flow: Refresh token flow
|
||||||
|
- **File:** `04 - Flows/Authentication Flow.md`
|
||||||
|
- **Diagram range:** `127-143` (`## Refresh flow`)
|
||||||
|
- **Error:** Parse error line 11: `... is in user.refreshTokens BE->>BE: Genera`
|
||||||
|
- **Likely issue:** Special math-style characters and expression-like message text interrupting parser tokenization.
|
||||||
|
- **Fix:** Replace special symbols in message text with plain ASCII and split to simple message line(s).
|
||||||
|
|
||||||
|
## Task 4 - Chat Flow: typing/chat notification sequence
|
||||||
|
- **File:** `04 - Flows/Chat Flow.md`
|
||||||
|
- **Diagram range:** `91-125` (`## Sequence diagram`)
|
||||||
|
- **Error:** Parse error line 20: `...ata.lastActivity=now BE->>IO: emit c`
|
||||||
|
- **Likely issue:** Assignment-style text (`...=now`) in message and possible bare punctuation in one-line payload.
|
||||||
|
- **Fix:** Simplify message bodies around state updates to readable text only.
|
||||||
|
|
||||||
|
## Task 5 - Delivery Confirmation Flow: code verification sequence
|
||||||
|
- **File:** `04 - Flows/Delivery Confirmation Flow.md`
|
||||||
|
- **Diagram range:** `45-71` (`## Sequence diagram`)
|
||||||
|
- **Error:** Parse error line 22: `...; status="delivered" BE->>IO: emit r`
|
||||||
|
- **Likely issue:** Double status expression in message (`deliveryCodeUsed=true; status="delivered"`).
|
||||||
|
- **Fix:** Split into two explicit sequence lines or rephrase with punctuation-safe text.
|
||||||
|
|
||||||
|
## Task 6 - Dispute Flow: admin resolve sequence
|
||||||
|
- **File:** `04 - Flows/Dispute Flow.md`
|
||||||
|
- **Diagram range:** `90-134` (`## Sequence diagram`)
|
||||||
|
- **Error:** Parse error line 18: `... is dispute } FE-->>B,S: chat opens (real`
|
||||||
|
- **Likely issue:** Invalid multi-recipient send syntax `B,S` on one arrow line.
|
||||||
|
- **Fix:** Either split into two lines (`FE-->>B:` and `FE-->>S:`) or route via a shared frontend/chat intermediary.
|
||||||
|
|
||||||
|
## Task 7 - Google OAuth Flow: completion sequence
|
||||||
|
- **File:** `04 - Flows/Google OAuth Flow.md`
|
||||||
|
- **Diagram range:** `56-96` (`## Sequence diagram`)
|
||||||
|
- **Error:** Parse error line 34: `...fill avatar if blank end BE->>BE`
|
||||||
|
- **Likely issue:** `end`/branch block combined with following arrow in parser context likely due missing separation in message-heavy block.
|
||||||
|
- **Fix:** Ensure `opt ... end` block boundaries and arrows are on clean, standalone lines.
|
||||||
|
|
||||||
|
## Task 8 - Purchase Request Flow: publish sequence
|
||||||
|
- **File:** `04 - Flows/Purchase Request Flow.md`
|
||||||
|
- **Diagram range:** `94-129` (`## Sequence diagram`)
|
||||||
|
- **Error:** Parse error line 27: `...ds; compute isPublic BE->>DB: Purcha`
|
||||||
|
- **Likely issue:** Message text includes expressions (`compute isPublic`) and punctuation (`;`) that are breaking the sequence parser.
|
||||||
|
- **Fix:** Rephrase backend processing lines into simple text without `;`/embedded expressions.
|
||||||
|
|
||||||
|
## Task 9 - Referral Flow: conversion and payout sequence
|
||||||
|
- **File:** `04 - Flows/Referral Flow.md`
|
||||||
|
- **Diagram range:** `70-99` (`## Sequence diagram`)
|
||||||
|
- **Error:** Parse error line 26: `...Transaction.create; update`
|
||||||
|
- **Likely issue:** Message text around chained commands (`updateUserLevel`) appears parser-conflicting.
|
||||||
|
- **Fix:** Break chained method-like messages into one action-per-line statements.
|
||||||
|
|
||||||
|
## Task 10 - Registration Flow: email verification sequence
|
||||||
|
- **File:** `04 - Flows/Registration Flow.md`
|
||||||
|
- **Diagram range:** `87-127` (`## Sequence diagram`)
|
||||||
|
- **Error:** Parse error line 36: `...tokens.push(refresh) BE->>BE: 200`
|
||||||
|
- **Likely issue:** Message line includes token-manipulation call style in plain text causing parser confusion.
|
||||||
|
- **Fix:** Reword to plain textual action; keep method calls minimal.
|
||||||
|
|
||||||
|
## Task 11 - Seller Offer Flow: submit offer sequence
|
||||||
|
- **File:** `04 - Flows/Seller Offer Flow.md`
|
||||||
|
- **Diagram range:** `97-134` (`## Sequence diagram`)
|
||||||
|
- **Error:** Parse error line 16: `...ETA, notes; submit FE_S->>BE: POST`
|
||||||
|
- **Likely issue:** Message with `; submit` and inline comma-separated action text.
|
||||||
|
- **Fix:** Split into cleaner action lines before POST step.
|
||||||
|
|
||||||
|
## Execution Order
|
||||||
|
1. Address Task 6 first (obvious syntax violation) to quickly cut down parse noise.
|
||||||
|
2. Tackle Tasks 2, 3, 5, 8, 9, 10, 11 (message-format cleanup).
|
||||||
|
3. Validate with a full parser sweep after each batch.
|
||||||
|
4. Final sweep: re-run mmdc parse validation across all `57` Mermaid blocks and close this PRD once no errors remain.
|
||||||
|
|
||||||
|
## Current Run Status
|
||||||
|
- Execution date: 2026-05-24
|
||||||
|
- Parallel passes launched: 3
|
||||||
|
- Result: All targeted task files pass `@mermaid-js/mermaid-cli` parsing.
|
||||||
|
- Full vault sweep (all markdown Mermaid blocks): **pass**.
|
||||||
|
|
||||||
|
### Task Completion
|
||||||
|
- Task 1: Complete (Security Architecture sequence lines simplified)
|
||||||
|
- Task 2: Complete (Authentication login refresh token line split/rephrased)
|
||||||
|
- Task 3: Complete (Authentication refresh-flow syntax normalized)
|
||||||
|
- Task 4: Complete (Chat flow update-message line rewritten)
|
||||||
|
- Task 5: Complete (Delivery confirmation message split into safe lines)
|
||||||
|
- Task 6: Complete (Dispute flow multi-recipient send split into separate arrows)
|
||||||
|
- Task 7: Complete (Google OAuth flow statement ordering fixed)
|
||||||
|
- Task 8: Complete (Purchase Request preference/public logic split into separate action lines)
|
||||||
|
- Task 9: Complete (Referral flow user-points action split)
|
||||||
|
- Task 10: Complete (Registration token update line split)
|
||||||
|
- Task 11: Complete (Seller Offer flow rewritten into parser-safe sequence diagram)
|
||||||
@@ -0,0 +1,232 @@
|
|||||||
|
# PRD: Platform Audit Remediation Plan (2026-05-24)
|
||||||
|
|
||||||
|
## Scope
|
||||||
|
- Source audit: `09 - Audits/Platform Logical Audit - 2026-05-24.md`
|
||||||
|
- Target: backend hardening and consistency fixes first, then doc/runtime alignment.
|
||||||
|
- Assessed date: 2026-05-24
|
||||||
|
|
||||||
|
## Audit validity check (code-backed vs docs-only)
|
||||||
|
|
||||||
|
- **Code-confirmed valid findings**:
|
||||||
|
- Unauthenticated financial/auth-sensitive routes are exposed (`/api/payment/*`, `/api/ai/*`, legacy notification routes).
|
||||||
|
- Passkey flow uses stubbed credential handling and in-memory challenge storage.
|
||||||
|
- `PaymentCoordinator` does not currently enforce dispute holds.
|
||||||
|
- Web3 verifier relies primarily on `receipt.status`.
|
||||||
|
- Socket.IO user-room joins are client-controlled.
|
||||||
|
- Rate limiting is explicitly disabled in `backend/src/app.ts`.
|
||||||
|
|
||||||
|
- **Partially validated / inconsistent findings**:
|
||||||
|
- Dispute module appears absent in the checked backend tree (`backend/src` does not contain `services/dispute`/`routes/disputeRoutes`/`controllers/disputeController`), so many dispute-specific audit checks cannot be confirmed against code but indicate a documentation-runtime mismatch.
|
||||||
|
- The REST/API/flow docs mention endpoints that differ from available implementation in some places; these should be normalized as part of a separate alignment pass.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## PRD 1: Secure unauthenticated endpoints and data-owner enforcement (P0)
|
||||||
|
|
||||||
|
### Problem
|
||||||
|
- `backend/src/services/payment/decentralizedPaymentRoutes.ts` exposes mutation endpoints (`/save`, `/update`, `/verify`, `/verify-all-pending`) without auth.
|
||||||
|
- `backend/src/services/ai/aiRoutes.ts` has public generation endpoints (`/generate`, `/analyze`, `/translate`, `/assist`) with no auth.
|
||||||
|
- `backend/src/services/notification/routes.ts` lets clients specify `userId` and mutate/read without ownership checks, and routes are mounted publicly via `app.use("/api", notificationRoutes)` in `backend/src/app.ts`.
|
||||||
|
|
||||||
|
### Acceptance criteria
|
||||||
|
- Every endpoint in `decentralizedPaymentRoutes.ts`, `aiRoutes.ts`, and legacy `notificationRoutes.ts` requires:
|
||||||
|
- `authenticateToken`
|
||||||
|
- owner/admin role check where applicable
|
||||||
|
- Notification endpoints do not accept arbitrary `userId`; derive `userId` from authenticated principal.
|
||||||
|
- Payment history and mutation endpoints enforce requestor ownership or admin/authorized role.
|
||||||
|
|
||||||
|
### Risk assessment
|
||||||
|
- **Threat**: Financial/private data tampering or privacy breach by unauthenticated callers.
|
||||||
|
- **Likelihood**: High.
|
||||||
|
- **Impact**: Critical (funding fraud, PII leakage, cost abuse).
|
||||||
|
- **Mitigation**: Introduce router-level middleware and standardized auth helper.
|
||||||
|
- **Residual risk**: Medium if any integration jobs call these endpoints (document required with service tokens or service role).
|
||||||
|
|
||||||
|
### Delivery plan
|
||||||
|
1. Add route-level `authenticateToken` to all routes in files above.
|
||||||
|
2. Introduce ownership guard utilities for:
|
||||||
|
- `history/:userId` and payment listing/history filters
|
||||||
|
- notification queries/updates
|
||||||
|
3. Restrict AI calls to authenticated users with per-user rate budget.
|
||||||
|
4. Add audit logs for denied access and suspicious payloads.
|
||||||
|
5. Update API docs for auth requirements.
|
||||||
|
|
||||||
|
### Owner / dependencies
|
||||||
|
- Owner: Backend security + payments teams.
|
||||||
|
- Depends on: token standards in `backend/src/shared/middleware/auth`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## PRD 2: Production-grade Passkey/WebAuthn flow (P0)
|
||||||
|
|
||||||
|
### Problem
|
||||||
|
- `backend/src/services/auth/passkeyService.ts` stores passkey challenge data in an in-memory `Map` and inserts `'simulated-public-key'` during registration.
|
||||||
|
- Refresh token is generated on authentication but never persisted to `user.refreshTokens[]`, making token rotation behavior inconsistent with the rest of auth flows.
|
||||||
|
|
||||||
|
### Acceptance criteria
|
||||||
|
- Replace stubbed registration/verification with real WebAuthn verification.
|
||||||
|
- Back challenges by shared storage (Redis or equivalent), not in-process memory.
|
||||||
|
- Persist verified refresh tokens and rotate according to normal auth policy.
|
||||||
|
- Reject reused/expired challenges and malformed assertions with deterministic errors.
|
||||||
|
|
||||||
|
### Risk assessment
|
||||||
|
- **Threat**: Credential spoofing, replay attacks, and broken session continuity.
|
||||||
|
- **Likelihood**: High.
|
||||||
|
- **Impact**: Critical (account takeover / authentication bypass).
|
||||||
|
- **Mitigation**: Add `@simplewebauthn/server` (or equivalent) + Redis-backed nonce store + strict verification.
|
||||||
|
- **Residual risk**: Medium (device/browser compatibility edge-cases).
|
||||||
|
|
||||||
|
### Delivery plan
|
||||||
|
1. Replace `verifyRegistration` and `verifyAuthentication` with attestation/assertion verification.
|
||||||
|
2. Swap `storedChallenges` map for distributed storage with TTL.
|
||||||
|
3. Add persistent refresh token append in passkey login flow.
|
||||||
|
4. Add regression tests for sign-in/sign-up and challenge expiry.
|
||||||
|
|
||||||
|
### Owner / dependencies
|
||||||
|
- Owner: Auth team.
|
||||||
|
- Depends on: Redis infra, passkey frontend challenge handling.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## PRD 3: Enforce dispute hold before payout/release operations (P1)
|
||||||
|
|
||||||
|
### Problem
|
||||||
|
- No dispute implementation files are present in the checked backend for enforcement paths, yet escrow release can still proceed in payment logic without a blocking hold.
|
||||||
|
- `backend/src/services/marketplace/routes.ts` release endpoint (`/purchase-requests/:id/release-payment`) executes without a dispute gate.
|
||||||
|
- `backend/src/services/payment/paymentCoordinator.ts` applies sequencing and dedupe logic but has no dispute state guard.
|
||||||
|
|
||||||
|
### Acceptance criteria
|
||||||
|
- Introduce explicit hold mechanism on `Payment` (or new `disputeStatus`/`holdReason` field).
|
||||||
|
- All release/refund flows check hold state before state mutation.
|
||||||
|
- Release endpoint returns clear 409/423 response when disputed.
|
||||||
|
- Backfill/reporting distinguishes dispute-blocked payments.
|
||||||
|
|
||||||
|
### Risk assessment
|
||||||
|
- **Threat**: Funds released before dispute resolution.
|
||||||
|
- **Likelihood**: Medium (documented behavior gap).
|
||||||
|
- **Impact**: Critical (financial loss / trust erosion).
|
||||||
|
- **Mitigation**: Centralize payout/refund state checks in coordinator and services, not UI-only logic.
|
||||||
|
- **Residual risk**: Medium (existing open disputes may need manual reconciliation).
|
||||||
|
|
||||||
|
### Delivery plan
|
||||||
|
1. Add `disputed`/`disputeHoldReason` fields (and migration plan) to `Payment`.
|
||||||
|
2. Add hold checks in:
|
||||||
|
- `backend/src/services/marketplace/routes.ts` admin release flow
|
||||||
|
- `backend/src/services/payment/shkeeper/shkeeperService.ts` and payout flows
|
||||||
|
- `backend/src/services/payment/paymentCoordinator.ts` before completion transitions.
|
||||||
|
3. Create an internal service contract for setting/releasing hold after dispute open/resolve.
|
||||||
|
4. Add guard tests for blocked release and allowed release post-override.
|
||||||
|
|
||||||
|
### Owner / dependencies
|
||||||
|
- Owner: Escrow/payment platform team.
|
||||||
|
- Depends on: dispute subsystem availability / status source-of-truth.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## PRD 4: Strengthen DePay/Web3 verification semantics (P1)
|
||||||
|
|
||||||
|
### Problem
|
||||||
|
- `backend/src/services/payment/decentralizedPaymentService.ts` verifies only `receipt.status === '0x1'`, without validating destination token, recipient, and amount mapping.
|
||||||
|
|
||||||
|
### Acceptance criteria
|
||||||
|
- Verification loads the transaction receipt + logs + token-decoding and validates:
|
||||||
|
- correct recipient address (`toAddress`)
|
||||||
|
- expected token contract (`token`)
|
||||||
|
- minimum amount with decimals.
|
||||||
|
- Reject/flag ambiguous payloads and store verifier evidence in `Payment.metadata`.
|
||||||
|
- Add idempotency/duplicate handling for repeated verification requests.
|
||||||
|
|
||||||
|
### Risk assessment
|
||||||
|
- **Threat**: Fraudulent transaction proofing and false-positive confirmations.
|
||||||
|
- **Likelihood**: Medium.
|
||||||
|
- **Impact**: High (unauthorized balance movement/false completion).
|
||||||
|
- **Mitigation**: Strict recipient/token/amount checks + explicit failure reason mapping.
|
||||||
|
- **Residual risk**: Medium (chain/protocol variance).
|
||||||
|
|
||||||
|
### Delivery plan
|
||||||
|
1. Extend verifier schema for expected transfer contract/address/decimals.
|
||||||
|
2. Decode ERC-20 `Transfer` event and compare against expected values.
|
||||||
|
3. Mark and persist `verificationFingerprint` to prevent replay/double-processing.
|
||||||
|
4. Return canonical failure reasons for observability.
|
||||||
|
|
||||||
|
### Owner / dependencies
|
||||||
|
- Owner: Payments + blockchain service team.
|
||||||
|
- Depends on: RPC/provider reliability and token ABI metadata.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## PRD 5: Lock Socket.IO user room joins to authenticated context (P2)
|
||||||
|
|
||||||
|
### Problem
|
||||||
|
- `backend/src/app.ts` allows `join-user-room`, `join-buyer-room`, and `join-seller-room` events from arbitrary input IDs with no identity binding.
|
||||||
|
|
||||||
|
### Acceptance criteria
|
||||||
|
- Server derives room membership from validated `socket` identity after token handshake.
|
||||||
|
- Reject mismatched room join attempts with server-side authorization checks.
|
||||||
|
- Preserve real-time event behavior for legitimate users.
|
||||||
|
|
||||||
|
### Risk assessment
|
||||||
|
- **Threat**: Event channel interception and privacy leakage.
|
||||||
|
- **Likelihood**: Medium.
|
||||||
|
- **Impact**: High (notifications/messages for wrong user).
|
||||||
|
- **Mitigation**: Server-authorized socket-to-user mapping and middleware verification.
|
||||||
|
- **Residual risk**: Low (requires active socket auth and client migration).
|
||||||
|
|
||||||
|
### Delivery plan
|
||||||
|
1. Add token validation middleware on socket connection.
|
||||||
|
2. Replace client-sent ID room joins with authenticated identity joins.
|
||||||
|
3. Add per-room join/emit checks in critical publishers.
|
||||||
|
4. Add monitoring for room-join failures and suspicious activity.
|
||||||
|
|
||||||
|
### Owner / dependencies
|
||||||
|
- Owner: Real-time platform team.
|
||||||
|
- Depends on: frontend socket auth handshake updates.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## PRD 6: Re-enable and scope rate limiting for public-sensitive paths (P2)
|
||||||
|
|
||||||
|
### Problem
|
||||||
|
- `backend/src/app.ts` has comments and code indicating rate limiting is disabled globally.
|
||||||
|
|
||||||
|
### Acceptance criteria
|
||||||
|
- Re-enable limiter at edge level with sensible defaults.
|
||||||
|
- Use stricter quotas for auth/financial/AI endpoints.
|
||||||
|
- Keep lightweight paths (public listings, static read APIs) at higher budgets.
|
||||||
|
|
||||||
|
### Risk assessment
|
||||||
|
- **Threat**: Brute-force/log abuse, AI cost exhaustion, webhook abuse.
|
||||||
|
- **Likelihood**: High.
|
||||||
|
- **Impact**: Medium-High (operational availability and cost).
|
||||||
|
- **Mitigation**: Endpoint-tiered limiter with trusted network exceptions and observability.
|
||||||
|
- **Residual risk**: Medium (false positives on legitimate spikes).
|
||||||
|
|
||||||
|
### Delivery plan
|
||||||
|
1. Restore global limiter with default relaxed values.
|
||||||
|
2. Add stricter route-level windows for `/api/auth/*`, `/api/payment/*`, `/api/ai/*`.
|
||||||
|
3. Add alerts on repeated 429s and limit misconfigurations.
|
||||||
|
|
||||||
|
### Owner / dependencies
|
||||||
|
- Owner: Platform infrastructure/security team.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Documentation and API alignment follow-up (P2)
|
||||||
|
|
||||||
|
- Where docs refer to `backend/src/services/dispute/*` and `backend/src/services/dispute/disputeRoutes.ts`, either implement that module or update architecture/API/docs to current repository reality.
|
||||||
|
- Normalize enum/action naming across:
|
||||||
|
- `02 - Data Models/*`
|
||||||
|
- `03 - API Reference/*`
|
||||||
|
- `04 - Flows/*`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Delivery sequencing suggestion
|
||||||
|
1. PRD 1 (security/auth)
|
||||||
|
2. PRD 6 (rate limiting)
|
||||||
|
3. PRD 2 (passkeys)
|
||||||
|
4. PRD 4 (verification trust)
|
||||||
|
5. PRD 5 (socket hardening)
|
||||||
|
6. PRD 3 (dispute hold controls)
|
||||||
|
7. Documentation/API alignment
|
||||||
|
|
||||||
@@ -0,0 +1,333 @@
|
|||||||
|
# PRD - Request Network Migration and Funds Management
|
||||||
|
|
||||||
|
Date: 2026-05-24
|
||||||
|
Status: Draft for architecture review
|
||||||
|
Owner: Platform / Payments
|
||||||
|
Codebase reviewed: `/Users/manwe/CascadeProjects/escrow`
|
||||||
|
|
||||||
|
## Executive Summary
|
||||||
|
|
||||||
|
Replacing SHKeeper with Request Network is not a provider swap. SHKeeper currently acts like a deposit-wallet and payout-task provider: the backend creates a payment intent, receives a generated wallet address, watches SHKeeper webhooks and BSC wallet balances, then optionally creates an outgoing payout task.
|
||||||
|
|
||||||
|
Request Network is request/payment-reference based. The platform creates a Request Network payment request or secure payment page, the payer pays through Request Network contracts or hosted flow, and reconciliation happens through Request Network payment events. Payouts are API-created payment requests/calldata that still require wallet execution. This means Amanat needs a first-class funds ledger and a release/refund orchestration layer, not just renamed `/payment/shkeeper/*` endpoints.
|
||||||
|
|
||||||
|
Primary recommendation: run a phased migration behind a provider adapter. Introduce Request Network for new pay-ins first using Secure Payment Pages, keep SHKeeper read-only for existing payments, then add funds ledger, release/refund gates, and Request Network payout flows.
|
||||||
|
|
||||||
|
## Source Findings
|
||||||
|
|
||||||
|
Current code:
|
||||||
|
|
||||||
|
- Backend mounts SHKeeper at `/api/payment/shkeeper` through `backend/src/services/payment/shkeeper/shkeeperRoutes.ts` and `shkeeperPayoutRoutes.ts`.
|
||||||
|
- Frontend calls SHKeeper through `frontend/src/actions/payment.ts`, `frontend/src/web3/components/shkeeper-payment.tsx`, `shkeeper-widget.tsx`, and `shkeeper-payout.tsx`.
|
||||||
|
- `Payment.provider` only allows `shkeeper` or `other`; SHKeeper-specific fields live directly under `Payment.metadata`.
|
||||||
|
- Pay-in completion is accepted from SHKeeper webhook, manual confirmation, or wallet monitor, all coordinated through `PaymentCoordinator`.
|
||||||
|
- Current payout paths mix SHKeeper payout tasks, simulated marketplace release, and direct admin wallet payout.
|
||||||
|
- There is no durable internal funds ledger that tracks available, held, releasable, disputed, released, refunded, and fee amounts per purchase request.
|
||||||
|
|
||||||
|
Request Network documentation checked:
|
||||||
|
|
||||||
|
- API v2 supports programmatic request creation, secure payment pages, payouts, webhooks, payment search, platform fees, and payee destinations: <https://docs.request.network/llms.txt>
|
||||||
|
- Secure Payment Pages are hosted payment URLs returned by `POST /v2/secure-payments`, returning `requestIds`, `token`, and `securePaymentUrl`: <https://beta.docs.request.network/api-features/secure-payment-pages>
|
||||||
|
- Secure Payment Pages validate official Request Network contracts before payer signing: <https://beta.docs.request.network/api-features/secure-payment-pages>
|
||||||
|
- Webhooks are scoped by Client ID and include `x-request-network-signature`, delivery ID, retry count, and optional test header: <https://requestnetwork.mintlify.app/api-reference/webhooks>
|
||||||
|
- Request Network webhooks retry failed deliveries up to 3 retries with short backoff windows: <https://requestnetwork.mintlify.app/api-reference/webhooks>
|
||||||
|
- Payout endpoints return unsigned transaction data that the platform/wallet must execute: <https://docs.request.network/request-network-api/recurring-payments>
|
||||||
|
- Batch payouts can return approval and batch payment transactions; the application sends those wallet transactions: <https://docs.request.network/request-network-api/batch-payments>
|
||||||
|
- Request Network protocol fee is 5 bps with stablecoin caps, and platform fees can be included through `feePercentage` and `feeAddress`: <https://docs.request.network/request-network-api/fees>
|
||||||
|
- Payment networks use payment references for detection, rather than unique deposit wallets per invoice: <https://docs.request.network/advanced/protocol-overview/how-payment-networks-work>
|
||||||
|
|
||||||
|
## Target Architecture
|
||||||
|
|
||||||
|
### Payment Provider Adapter
|
||||||
|
|
||||||
|
Create a provider-neutral payment interface:
|
||||||
|
|
||||||
|
- `createPayInIntent`
|
||||||
|
- `getPayInStatus`
|
||||||
|
- `handleProviderWebhook`
|
||||||
|
- `createHostedPaymentLink`
|
||||||
|
- `createReleaseInstruction`
|
||||||
|
- `createRefundInstruction`
|
||||||
|
- `getPayoutStatus`
|
||||||
|
- `searchProviderPayments`
|
||||||
|
|
||||||
|
Implement:
|
||||||
|
|
||||||
|
- `ShkeeperProvider` for legacy compatibility.
|
||||||
|
- `RequestNetworkProvider` for new flows.
|
||||||
|
|
||||||
|
### Funds Ledger
|
||||||
|
|
||||||
|
Add an internal ledger separate from provider metadata:
|
||||||
|
|
||||||
|
- `fundsAccount`: one per purchase request or order.
|
||||||
|
- `ledgerEntry`: immutable entries for authorization, payment detected, platform fee, provider fee, hold, release, refund, chargeback/dispute hold, adjustment.
|
||||||
|
- `fundsBalance`: derived or cached view containing `expected`, `paid`, `held`, `releasable`, `released`, `refunded`, `disputed`, `fees`, and `available`.
|
||||||
|
|
||||||
|
Ledger invariants:
|
||||||
|
|
||||||
|
- Seller payout cannot exceed paid amount minus refunds, fees, and active dispute holds.
|
||||||
|
- Release requires payment status `completed`, escrow state `releasable`, no open dispute, and a verified seller destination.
|
||||||
|
- Refund requires available held balance and must mark the purchase request/payment state consistently.
|
||||||
|
- Provider webhooks never directly mark funds as released; they create/reconcile ledger entries.
|
||||||
|
|
||||||
|
### Payment Flow
|
||||||
|
|
||||||
|
Pay-in:
|
||||||
|
|
||||||
|
1. Buyer accepts seller offer.
|
||||||
|
2. Backend creates internal payment + funds account.
|
||||||
|
3. Backend calls Request Network `POST /v2/secure-payments` or `POST /v2/request`.
|
||||||
|
4. Frontend redirects to `securePaymentUrl` or executes returned calldata in wallet.
|
||||||
|
5. Request Network webhook confirms payment.
|
||||||
|
6. Backend verifies signature, idempotency, amount, request ID, payment reference, currency, and merchant reference.
|
||||||
|
7. Ledger moves from `expected` to `held`.
|
||||||
|
8. Purchase request enters `payment` or `processing`.
|
||||||
|
|
||||||
|
Release:
|
||||||
|
|
||||||
|
1. Buyer delivery confirmation or admin release marks funds `releasable`.
|
||||||
|
2. Backend creates Request Network payout/release instruction, or admin wallet transaction instruction.
|
||||||
|
3. Admin/operator wallet signs and broadcasts transaction.
|
||||||
|
4. Backend records transaction hash as `release_pending`.
|
||||||
|
5. Webhook/search confirms settlement.
|
||||||
|
6. Ledger moves `held -> released`.
|
||||||
|
|
||||||
|
Refund:
|
||||||
|
|
||||||
|
1. Refund request validates available held balance.
|
||||||
|
2. Backend creates refund transaction instruction.
|
||||||
|
3. Admin/operator wallet executes.
|
||||||
|
4. Confirmation updates ledger `held -> refunded`.
|
||||||
|
|
||||||
|
## PRD 1 - Provider-Neutral Payment Adapter
|
||||||
|
|
||||||
|
Priority: P0
|
||||||
|
|
||||||
|
Goal: decouple checkout, webhook, and payout flows from SHKeeper-specific routes and metadata.
|
||||||
|
|
||||||
|
Scope:
|
||||||
|
|
||||||
|
- Add `paymentProvider` abstraction in backend.
|
||||||
|
- Add `provider: 'shkeeper' | 'request_network' | 'manual' | 'admin_wallet'` to payment model.
|
||||||
|
- Keep `/api/payment/shkeeper/*` operational for legacy records.
|
||||||
|
- Add `/api/payment/providers/request-network/*` or `/api/payment/request-network/*` for new Request Network flows.
|
||||||
|
- Add a feature flag: `PAYMENT_PROVIDER=request_network|shkeeper`.
|
||||||
|
|
||||||
|
Acceptance Criteria:
|
||||||
|
|
||||||
|
- New checkout can create a Request Network payment link without touching SHKeeper service code.
|
||||||
|
- Existing SHKeeper payments remain readable and can still process late webhooks.
|
||||||
|
- Frontend does not import provider-specific action names outside provider-specific components.
|
||||||
|
- Provider metadata is namespaced under `metadata.providers.requestNetwork` or a dedicated provider table.
|
||||||
|
|
||||||
|
Risk Assessment:
|
||||||
|
|
||||||
|
- Impact: High. Payment creation is core revenue flow.
|
||||||
|
- Likelihood: Medium. Existing code has many direct `shkeeper` references.
|
||||||
|
- Main risks: broken checkout, duplicate payment records, orphaned webhooks, mixed provider states.
|
||||||
|
- Mitigation: use provider feature flag, preserve SHKeeper routes, add idempotency keys, run Request Network only for new payments during rollout.
|
||||||
|
- Rollback: set `PAYMENT_PROVIDER=shkeeper`; keep Request Network records read-only.
|
||||||
|
|
||||||
|
## PRD 2 - Request Network Pay-In Integration
|
||||||
|
|
||||||
|
Priority: P0
|
||||||
|
|
||||||
|
Goal: replace generated SHKeeper wallet addresses with Request Network request/payment-reference based payment collection.
|
||||||
|
|
||||||
|
Scope:
|
||||||
|
|
||||||
|
- Store Request Network `requestId`, `paymentReference`, `securePaymentUrl`, `token`, `merchantReference`, `network`, `invoiceCurrency`, and `paymentCurrency`.
|
||||||
|
- Use Secure Payment Pages for first launch to reduce frontend wallet/calldata complexity.
|
||||||
|
- Include Amanat purchase request ID and payment ID as merchant reference or metadata.
|
||||||
|
- Validate supported networks/currencies before creating payment links.
|
||||||
|
- Remove frontend dependence on SHKeeper-generated `walletAddress` for new provider flow.
|
||||||
|
|
||||||
|
Acceptance Criteria:
|
||||||
|
|
||||||
|
- Buyer can start payment and receive a Request Network hosted payment URL.
|
||||||
|
- Backend records internal payment as `pending` with Request Network identifiers.
|
||||||
|
- Webhook `payment.confirmed` reconciles only the matching internal payment.
|
||||||
|
- Amount, currency, provider request ID, and merchant reference are verified before setting `escrowState='funded'`.
|
||||||
|
- Late or duplicate webhook deliveries are idempotent.
|
||||||
|
|
||||||
|
Risk Assessment:
|
||||||
|
|
||||||
|
- Impact: High.
|
||||||
|
- Likelihood: Medium.
|
||||||
|
- Main risks: currency/network mismatch, hosted redirect UX breakage, buyer pays wrong amount, missing webhook.
|
||||||
|
- Mitigation: backend-only creation, strict metadata correlation, periodic fallback reconciliation using Request Network payment search, idempotency by delivery ID and request ID.
|
||||||
|
- Rollback: disable Request Network provider for new payments; keep pending Request Network payments visible with manual support workflow.
|
||||||
|
|
||||||
|
## PRD 3 - Funds Ledger and Escrow State Machine
|
||||||
|
|
||||||
|
Priority: P0
|
||||||
|
|
||||||
|
Goal: introduce internal funds management so payment, hold, release, refund, dispute, and fee states are auditable and provider-independent.
|
||||||
|
|
||||||
|
Scope:
|
||||||
|
|
||||||
|
- Add `FundsAccount` model keyed by purchase request/payment.
|
||||||
|
- Add immutable `LedgerEntry` model with provider references and actor/source.
|
||||||
|
- Add derived `FundsBalance` query/service.
|
||||||
|
- Define state transitions: `expected -> held -> releasable -> releasing -> released`, plus `refunded`, `partially_refunded`, `disputed`, `failed`.
|
||||||
|
- Prevent release/refund from reading raw `Payment.status` alone.
|
||||||
|
|
||||||
|
Acceptance Criteria:
|
||||||
|
|
||||||
|
- Every successful pay-in creates a ledger entry for gross paid amount.
|
||||||
|
- Platform fee, Request Network protocol fee, and net seller amount are represented explicitly.
|
||||||
|
- Release API checks ledger invariants before creating payout/refund instructions.
|
||||||
|
- Dispute hold blocks payout until resolved.
|
||||||
|
- Admin UI/payment detail view can show gross paid, fees, held, releasable, released, refunded.
|
||||||
|
|
||||||
|
Risk Assessment:
|
||||||
|
|
||||||
|
- Impact: Very High.
|
||||||
|
- Likelihood: Medium.
|
||||||
|
- Main risks: double-release, incorrect fee accounting, drift between Payment and ledger state.
|
||||||
|
- Mitigation: immutable entries, unique idempotency keys, transaction/session writes where Mongo supports them, reconciliation job, read-only migration report before enforcing ledger.
|
||||||
|
- Rollback: keep old payment fields as source of truth until ledger backfill passes; feature flag release enforcement.
|
||||||
|
|
||||||
|
## PRD 4 - Request Network Webhook and Reconciliation Service
|
||||||
|
|
||||||
|
Priority: P1
|
||||||
|
|
||||||
|
Goal: replace SHKeeper webhook and wallet monitor semantics with signed Request Network event processing and periodic reconciliation.
|
||||||
|
|
||||||
|
Scope:
|
||||||
|
|
||||||
|
- Add `/api/payment/request-network/webhook`.
|
||||||
|
- Verify raw body using `x-request-network-signature`.
|
||||||
|
- Store delivery ID, retry count, event type, request ID, payment reference, payload hash, and processed status.
|
||||||
|
- Support test webhooks via `x-request-network-test`.
|
||||||
|
- Add scheduled reconciliation using Request Network payment search/status APIs.
|
||||||
|
- Retire SHKeeper wallet monitor for new Request Network payments.
|
||||||
|
|
||||||
|
Acceptance Criteria:
|
||||||
|
|
||||||
|
- Invalid signatures are rejected in all environments except explicit local test mode.
|
||||||
|
- Duplicate delivery IDs are acknowledged without duplicating ledger entries.
|
||||||
|
- `payment.confirmed` and partial/over/failed states map to internal status consistently.
|
||||||
|
- Reconciliation job can repair missed webhook state without relying on buyer/frontend callbacks.
|
||||||
|
|
||||||
|
Risk Assessment:
|
||||||
|
|
||||||
|
- Impact: High.
|
||||||
|
- Likelihood: Medium.
|
||||||
|
- Main risks: raw body parsing mismatch, webhook downtime, event mapping mistakes.
|
||||||
|
- Mitigation: raw-body middleware scoped to webhook route, event fixture tests, dead-letter queue/table, operator replay endpoint.
|
||||||
|
- Rollback: pause webhook processor and rely on manual/admin reconciliation for Request Network records.
|
||||||
|
|
||||||
|
## PRD 5 - Release, Refund, and Payout Orchestration
|
||||||
|
|
||||||
|
Priority: P1
|
||||||
|
|
||||||
|
Goal: replace SHKeeper payout tasks and simulated marketplace release with auditable transaction instruction and confirmation flows.
|
||||||
|
|
||||||
|
Scope:
|
||||||
|
|
||||||
|
- Define release/refund service that consumes ledger balances, not raw request status.
|
||||||
|
- Generate Request Network payout instructions or direct admin wallet transaction instructions.
|
||||||
|
- Store unsigned transaction payloads, signer, submitted tx hash, confirmation status, and provider status.
|
||||||
|
- Add batch payout support as a later optimization after single release is stable.
|
||||||
|
- Require admin/operator authorization and dispute checks before instruction creation.
|
||||||
|
|
||||||
|
Acceptance Criteria:
|
||||||
|
|
||||||
|
- Seller payout requires verified seller wallet/payee destination.
|
||||||
|
- Release cannot occur if funds are unpaid, already released, refunded, or disputed.
|
||||||
|
- Transaction hash confirmation updates ledger only once.
|
||||||
|
- Admin can see pending release instructions and retry/cancel safely.
|
||||||
|
- Existing `/purchase-requests/:id/release-payment` simulated path is removed or hidden behind dev-only mode.
|
||||||
|
|
||||||
|
Risk Assessment:
|
||||||
|
|
||||||
|
- Impact: Very High.
|
||||||
|
- Likelihood: High.
|
||||||
|
- Main risks: Request Network payouts are not custodial magic; operator wallet still signs transactions, so process failure can leave funds pending.
|
||||||
|
- Mitigation: explicit release queue, two-step admin approval, signer audit trail, reconciliation against tx hash/provider status.
|
||||||
|
- Rollback: keep direct admin wallet payout as emergency fallback with mandatory ledger entry and reason code.
|
||||||
|
|
||||||
|
## PRD 6 - Frontend Checkout and Admin Migration
|
||||||
|
|
||||||
|
Priority: P1
|
||||||
|
|
||||||
|
Goal: update buyer payment, admin release, seller payout, and payment details UI for Request Network flows.
|
||||||
|
|
||||||
|
Scope:
|
||||||
|
|
||||||
|
- Replace `ShkeeperPayment` with provider-neutral `CryptoPayment`.
|
||||||
|
- Add `RequestNetworkPayment` redirect flow for secure payment pages.
|
||||||
|
- Keep `ShkeeperPayment` available only for legacy/unpaid SHKeeper records if needed.
|
||||||
|
- Replace `ShkeeperPayout` with release queue/admin payout UI.
|
||||||
|
- Payment detail page shows provider, request ID, payment reference, hosted link, transaction hashes, ledger balances, webhook/reconciliation status.
|
||||||
|
|
||||||
|
Acceptance Criteria:
|
||||||
|
|
||||||
|
- Buyer checkout no longer expects provider-generated `walletAddress` for Request Network payments.
|
||||||
|
- Admin release UI displays available/releasable funds and blocks unsafe release states.
|
||||||
|
- Seller payout status comes from internal release instruction/ledger, not SHKeeper task polling.
|
||||||
|
- Legacy SHKeeper labels are not shown for Request Network payments.
|
||||||
|
|
||||||
|
Risk Assessment:
|
||||||
|
|
||||||
|
- Impact: Medium-High.
|
||||||
|
- Likelihood: Medium.
|
||||||
|
- Main risks: confusing redirect UX, old Persian labels referencing SHKeeper, admin accidentally using old payout button.
|
||||||
|
- Mitigation: provider-specific copy, feature flag UI sections, legacy badge, clear payment detail diagnostics.
|
||||||
|
- Rollback: route checkout back to SHKeeper component via provider flag.
|
||||||
|
|
||||||
|
## PRD 7 - Data Migration and Legacy Decommission
|
||||||
|
|
||||||
|
Priority: P2
|
||||||
|
|
||||||
|
Goal: safely migrate historical SHKeeper payment records and phase out provider-specific code.
|
||||||
|
|
||||||
|
Scope:
|
||||||
|
|
||||||
|
- Backfill provider metadata namespace for existing SHKeeper payments.
|
||||||
|
- Create ledger entries for completed SHKeeper payments from trusted records.
|
||||||
|
- Mark historical records as `legacyProvider='shkeeper'`.
|
||||||
|
- Keep SHKeeper webhook active during webhook tail period.
|
||||||
|
- Remove SHKeeper wallet monitor, simple auto webhook, test callback routes, and payout routes after cutoff.
|
||||||
|
|
||||||
|
Acceptance Criteria:
|
||||||
|
|
||||||
|
- Migration produces counts for total, migrated, skipped, ambiguous, and failed records.
|
||||||
|
- No historical completed payment loses transaction hash/provider invoice/task metadata.
|
||||||
|
- Legacy SHKeeper webhook can still reconcile existing pending records until cutoff date.
|
||||||
|
- Decommission checklist includes env vars, docs, frontend labels, backend routes, and runbooks.
|
||||||
|
|
||||||
|
Risk Assessment:
|
||||||
|
|
||||||
|
- Impact: Medium.
|
||||||
|
- Likelihood: Medium.
|
||||||
|
- Main risks: ambiguous historical records, template checkout string IDs, mixed status meanings.
|
||||||
|
- Mitigation: dry-run migration, manual review bucket, no destructive migration, keep original metadata.
|
||||||
|
- Rollback: ledger backfill is additive; old records remain intact.
|
||||||
|
|
||||||
|
## Implementation Sequence
|
||||||
|
|
||||||
|
1. Add provider adapter and Request Network config without changing default provider.
|
||||||
|
2. Add funds ledger models/services and dry-run backfill report.
|
||||||
|
3. Implement Request Network secure pay-in flow behind feature flag.
|
||||||
|
4. Implement signed webhook receiver and reconciliation job.
|
||||||
|
5. Enable Request Network for limited new checkout cohort.
|
||||||
|
6. Add release/refund orchestration using ledger gates.
|
||||||
|
7. Migrate admin/frontend views.
|
||||||
|
8. Backfill legacy records.
|
||||||
|
9. Decommission SHKeeper once no active records depend on it.
|
||||||
|
|
||||||
|
## Open Decisions
|
||||||
|
|
||||||
|
- Use Request Network Secure Payment Pages first, or execute Request Network calldata directly in the existing wallet modal?
|
||||||
|
- Keep funds in a platform-controlled escrow wallet, pay sellers via admin/operator release, or route pay-ins directly to seller with only platform fee collection?
|
||||||
|
- Which chains/currencies are required for launch: BSC USDT parity with today, or Request Network supported stablecoin routes first?
|
||||||
|
- Should platform fee be paid by buyer, seller, or absorbed by Amanat?
|
||||||
|
- Does Amanat need crypto-to-fiat/offramp later, which adds KYC/payment detail requirements?
|
||||||
|
|
||||||
|
## Recommendation
|
||||||
|
|
||||||
|
Start with Secure Payment Pages and a platform escrow/payee destination controlled by Amanat. This best matches the current escrow mental model while reducing frontend transaction-building risk. Do not route pay-ins directly to sellers until dispute handling, refund logic, and service fee economics are fully redesigned.
|
||||||
|
|
||||||
5
.taskmaster/state.json
Normal file
5
.taskmaster/state.json
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
{
|
||||||
|
"currentTag": "master",
|
||||||
|
"lastSwitched": "2026-05-24T00:00:00.000Z",
|
||||||
|
"migrationNoticeShown": true
|
||||||
|
}
|
||||||
9
.taskmaster/tasks/task-1.md
Normal file
9
.taskmaster/tasks/task-1.md
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
# Task 1: Stabilize Mermaid diagram rendering across documentation vault
|
||||||
|
|
||||||
|
Status: done
|
||||||
|
Priority: medium
|
||||||
|
Source PRD: `.taskmaster/docs/prd-mermaid-diagram-rendering-stabilization.md`
|
||||||
|
|
||||||
|
Correct Mermaid syntax/rendering issues across the documentation vault and validate all Mermaid blocks.
|
||||||
|
|
||||||
|
The source PRD records that all targeted task files pass `@mermaid-js/mermaid-cli` parsing and the full vault sweep passes.
|
||||||
17
.taskmaster/tasks/task-2.md
Normal file
17
.taskmaster/tasks/task-2.md
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
# Task 2: Implement platform audit remediation plan
|
||||||
|
|
||||||
|
Status: pending
|
||||||
|
Priority: high
|
||||||
|
Source PRD: `.taskmaster/docs/prd-platform-audit-remediation-plan-2026-05-24.md`
|
||||||
|
|
||||||
|
Address the code-backed security and consistency issues identified in the 2026-05-24 platform audit remediation PRD.
|
||||||
|
|
||||||
|
Subtasks:
|
||||||
|
|
||||||
|
1. Secure unauthenticated endpoints and owner enforcement.
|
||||||
|
2. Re-enable and scope rate limiting.
|
||||||
|
3. Replace stubbed passkey/WebAuthn flow.
|
||||||
|
4. Strengthen DePay/Web3 payment verification.
|
||||||
|
5. Lock Socket.IO room joins to authenticated context.
|
||||||
|
6. Enforce dispute hold before payout and release operations.
|
||||||
|
7. Align documentation, API references, and runtime enums.
|
||||||
18
.taskmaster/tasks/task-3.md
Normal file
18
.taskmaster/tasks/task-3.md
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
# Task 3: Migrate payment architecture toward Request Network and internal funds management
|
||||||
|
|
||||||
|
Status: pending
|
||||||
|
Priority: high
|
||||||
|
Depends on: Task 2
|
||||||
|
Source PRD: `.taskmaster/docs/prd-request-network-migration-and-funds-management.md`
|
||||||
|
|
||||||
|
Plan and implement provider-neutral payment flows, Request Network pay-in support, funds ledger, webhook reconciliation, release/refund orchestration, UI migration, and SHKeeper decommissioning.
|
||||||
|
|
||||||
|
Subtasks:
|
||||||
|
|
||||||
|
1. Introduce provider-neutral payment adapter.
|
||||||
|
2. Implement Request Network pay-in integration.
|
||||||
|
3. Add funds ledger and escrow state machine.
|
||||||
|
4. Build Request Network webhook and reconciliation service.
|
||||||
|
5. Implement release, refund, and payout orchestration.
|
||||||
|
6. Migrate frontend checkout and admin payment UI.
|
||||||
|
7. Backfill legacy SHKeeper records and decommission provider-specific code.
|
||||||
21
.taskmaster/tasks/task-4.md
Normal file
21
.taskmaster/tasks/task-4.md
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
# Task 4: Define backend security and refactor strategy from latest audit
|
||||||
|
|
||||||
|
Status: pending
|
||||||
|
Priority: high
|
||||||
|
Source audit: `.taskmaster/docs/audit-backend-stack-security-and-refactor-assessment-2026-05-24.md`
|
||||||
|
|
||||||
|
Convert the backend stack security/refactor assessment into concrete architecture decisions, documentation deliverables, and developer handoff criteria.
|
||||||
|
|
||||||
|
This is an advisory/architecture task. It should run in parallel with immediate backend hardening rather than block urgent remediation.
|
||||||
|
|
||||||
|
Subtasks:
|
||||||
|
|
||||||
|
1. Assign security ownership and launch decision criteria.
|
||||||
|
2. Produce threat model for escrow platform.
|
||||||
|
3. Specify funds ledger and escrow state machine.
|
||||||
|
4. Create authorization matrix for REST and Socket.IO.
|
||||||
|
5. Decide session, passkey, and admin step-up architecture.
|
||||||
|
6. Specify webhook security and provider adapter contracts.
|
||||||
|
7. Define secure build and supply-chain policy.
|
||||||
|
8. Make backend-core stack decision.
|
||||||
|
9. Create migration and operational runbooks.
|
||||||
386
.taskmaster/tasks/tasks.json
Normal file
386
.taskmaster/tasks/tasks.json
Normal file
@@ -0,0 +1,386 @@
|
|||||||
|
{
|
||||||
|
"master": {
|
||||||
|
"metadata": {
|
||||||
|
"projectName": "Amanat Documentation PRDs",
|
||||||
|
"created": "2026-05-24T00:00:00.000Z",
|
||||||
|
"updated": "2026-05-24T00:00:00.000Z",
|
||||||
|
"description": "Taskmaster task queue generated from docs-side PRDs for developer sharing.",
|
||||||
|
"sourcePrds": [
|
||||||
|
".taskmaster/docs/prd-mermaid-diagram-rendering-stabilization.md",
|
||||||
|
".taskmaster/docs/prd-platform-audit-remediation-plan-2026-05-24.md",
|
||||||
|
".taskmaster/docs/prd-request-network-migration-and-funds-management.md",
|
||||||
|
".taskmaster/docs/audit-backend-stack-security-and-refactor-assessment-2026-05-24.md"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"tasks": [
|
||||||
|
{
|
||||||
|
"id": 1,
|
||||||
|
"title": "Stabilize Mermaid diagram rendering across documentation vault",
|
||||||
|
"description": "Correct Mermaid syntax/rendering issues across the documentation vault and validate all Mermaid blocks.",
|
||||||
|
"details": "Source PRD: .taskmaster/docs/prd-mermaid-diagram-rendering-stabilization.md. Scope covered 57 Mermaid blocks and 11 failing blocks. The source PRD records that all targeted files now pass mmdc parse validation and the full vault sweep passes.",
|
||||||
|
"testStrategy": "Run the same mmdc-based syntax validation across all Markdown Mermaid blocks and confirm zero parser failures in Obsidian/markdown previews.",
|
||||||
|
"priority": "medium",
|
||||||
|
"status": "done",
|
||||||
|
"dependencies": [],
|
||||||
|
"subtasks": [
|
||||||
|
{
|
||||||
|
"id": 1,
|
||||||
|
"title": "Fix Security Architecture email/password sequence",
|
||||||
|
"description": "Normalize parser-sensitive sequence text in 01 - Architecture/Security Architecture.md.",
|
||||||
|
"details": "Avoid semicolons and ambiguous inline punctuation in sequence messages.",
|
||||||
|
"status": "done",
|
||||||
|
"priority": "medium",
|
||||||
|
"dependencies": [],
|
||||||
|
"testStrategy": "mmdc parse for the specific block."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 2,
|
||||||
|
"title": "Fix authentication login and refresh diagrams",
|
||||||
|
"description": "Normalize parser-sensitive token and refresh-token sequence text in Authentication Flow.",
|
||||||
|
"details": "Split method-like or expression-like message text into parser-safe plain text lines.",
|
||||||
|
"status": "done",
|
||||||
|
"priority": "medium",
|
||||||
|
"dependencies": [],
|
||||||
|
"testStrategy": "mmdc parse for both Authentication Flow blocks."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 3,
|
||||||
|
"title": "Fix chat, delivery, dispute, OAuth, purchase request, referral, registration, and seller-offer diagrams",
|
||||||
|
"description": "Clean the remaining Mermaid sequence diagrams with invalid or ambiguous syntax.",
|
||||||
|
"details": "Split multi-recipient arrows, remove parser-conflicting semicolon/expression text, and keep intent unchanged.",
|
||||||
|
"status": "done",
|
||||||
|
"priority": "medium",
|
||||||
|
"dependencies": [],
|
||||||
|
"testStrategy": "Full vault mmdc parser sweep across all Mermaid blocks."
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 2,
|
||||||
|
"title": "Implement platform audit remediation plan",
|
||||||
|
"description": "Address the code-backed security and consistency issues identified in the 2026-05-24 platform audit remediation PRD.",
|
||||||
|
"details": "Source PRD: .taskmaster/docs/prd-platform-audit-remediation-plan-2026-05-24.md. Target backend hardening first, then documentation/runtime alignment. Delivery order suggested by PRD: security/auth, rate limiting, passkeys, Web3 verification, socket hardening, dispute hold controls, docs/API alignment.",
|
||||||
|
"testStrategy": "Add focused regression tests for route auth/ownership, passkey challenge/verification, Web3 verification semantics, socket authorization, rate limiting tiers, and payout/release dispute holds. Update API docs after behavior is implemented.",
|
||||||
|
"priority": "high",
|
||||||
|
"status": "pending",
|
||||||
|
"dependencies": [],
|
||||||
|
"subtasks": [
|
||||||
|
{
|
||||||
|
"id": 1,
|
||||||
|
"title": "Secure unauthenticated endpoints and owner enforcement",
|
||||||
|
"description": "Require authenticateToken and owner/admin checks on exposed payment, AI, and legacy notification routes.",
|
||||||
|
"details": "Derive notification userId from authenticated principal. Protect payment history and mutation endpoints. Restrict AI calls to authenticated users with per-user budgets. Add denied-access audit logs.",
|
||||||
|
"status": "pending",
|
||||||
|
"priority": "high",
|
||||||
|
"dependencies": [],
|
||||||
|
"testStrategy": "Unauthorized callers receive 401/403; users cannot access or mutate other users' payments/notifications; admins retain authorized access."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 2,
|
||||||
|
"title": "Re-enable and scope rate limiting",
|
||||||
|
"description": "Restore global and route-tiered rate limits for public-sensitive paths.",
|
||||||
|
"details": "Use stricter limits for auth, financial, AI, file upload, and verification paths. Keep public reads at relaxed limits. Add observability for 429 spikes.",
|
||||||
|
"status": "pending",
|
||||||
|
"priority": "high",
|
||||||
|
"dependencies": [
|
||||||
|
1
|
||||||
|
],
|
||||||
|
"testStrategy": "Exercise configured limits per tier and confirm expected 429 responses without blocking ordinary reads."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 3,
|
||||||
|
"title": "Replace stubbed passkey/WebAuthn flow",
|
||||||
|
"description": "Implement production-grade WebAuthn registration/authentication and shared challenge storage.",
|
||||||
|
"details": "Use real attestation/assertion verification, Redis-backed TTL challenges, refresh-token persistence/rotation, and deterministic malformed/reused/expired challenge errors.",
|
||||||
|
"status": "pending",
|
||||||
|
"priority": "high",
|
||||||
|
"dependencies": [
|
||||||
|
1
|
||||||
|
],
|
||||||
|
"testStrategy": "Registration, login, replay, expired challenge, and refresh-token continuity tests pass."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 4,
|
||||||
|
"title": "Strengthen DePay/Web3 payment verification",
|
||||||
|
"description": "Verify transaction recipient, token contract, and amount, not only receipt success.",
|
||||||
|
"details": "Decode ERC-20 Transfer logs, compare recipient against escrow address, validate token contract and decimals-adjusted minimum amount, store verifier evidence and idempotency fingerprint.",
|
||||||
|
"status": "pending",
|
||||||
|
"priority": "high",
|
||||||
|
"dependencies": [
|
||||||
|
1
|
||||||
|
],
|
||||||
|
"testStrategy": "Reject successful but wrong-recipient/wrong-token/underpaid tx hashes; accept only matching transfers."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 5,
|
||||||
|
"title": "Lock Socket.IO room joins to authenticated context",
|
||||||
|
"description": "Remove trust in client-supplied user/buyer/seller room IDs.",
|
||||||
|
"details": "Validate socket handshake token, derive server-side room membership, reject mismatched joins, and monitor suspicious join attempts.",
|
||||||
|
"status": "pending",
|
||||||
|
"priority": "medium",
|
||||||
|
"dependencies": [
|
||||||
|
1
|
||||||
|
],
|
||||||
|
"testStrategy": "A user cannot subscribe to another user's rooms; legitimate realtime notifications still arrive."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 6,
|
||||||
|
"title": "Enforce dispute hold before payout and release operations",
|
||||||
|
"description": "Add payment hold state and central release/refund guards that block disputed funds.",
|
||||||
|
"details": "Introduce explicit dispute hold fields or state, enforce in PaymentCoordinator and payout/release services, return clear 409/423 responses, and backfill/report blocked payments.",
|
||||||
|
"status": "pending",
|
||||||
|
"priority": "medium",
|
||||||
|
"dependencies": [
|
||||||
|
1,
|
||||||
|
4
|
||||||
|
],
|
||||||
|
"testStrategy": "Open dispute blocks release/refund until resolved or explicitly overridden through authorized path."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 7,
|
||||||
|
"title": "Align documentation, API references, and runtime enums",
|
||||||
|
"description": "Normalize disputed/payment/request status docs and implementation references after security behavior changes.",
|
||||||
|
"details": "Resolve mismatch around absent dispute module, endpoint names, status enums, and action names across Data Models, API Reference, and Flows.",
|
||||||
|
"status": "pending",
|
||||||
|
"priority": "medium",
|
||||||
|
"dependencies": [
|
||||||
|
1,
|
||||||
|
2,
|
||||||
|
3,
|
||||||
|
4,
|
||||||
|
5,
|
||||||
|
6
|
||||||
|
],
|
||||||
|
"testStrategy": "Docs match implemented routes, models, enum values, and state transitions."
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 3,
|
||||||
|
"title": "Migrate payment architecture toward Request Network and internal funds management",
|
||||||
|
"description": "Plan and implement provider-neutral payment flows, Request Network pay-in support, funds ledger, webhook reconciliation, release/refund orchestration, UI migration, and SHKeeper decommissioning.",
|
||||||
|
"details": "Source PRD: .taskmaster/docs/prd-request-network-migration-and-funds-management.md. The PRD recommends phased migration behind a provider adapter, Secure Payment Pages first, platform-controlled escrow/payee destination, and a first-class internal funds ledger before release/refund enforcement.",
|
||||||
|
"testStrategy": "Use feature flags, provider fixture tests, webhook signature/idempotency tests, ledger invariant tests, migration dry-run reports, and limited cohort rollout before default provider switch.",
|
||||||
|
"priority": "high",
|
||||||
|
"status": "pending",
|
||||||
|
"dependencies": [
|
||||||
|
2
|
||||||
|
],
|
||||||
|
"subtasks": [
|
||||||
|
{
|
||||||
|
"id": 1,
|
||||||
|
"title": "Introduce provider-neutral payment adapter",
|
||||||
|
"description": "Decouple checkout, webhook, and payout flows from SHKeeper-specific routes and metadata.",
|
||||||
|
"details": "Define createPayInIntent, getPayInStatus, handleProviderWebhook, createHostedPaymentLink, createReleaseInstruction, createRefundInstruction, getPayoutStatus, and searchProviderPayments. Add provider values shkeeper, request_network, manual, admin_wallet and PAYMENT_PROVIDER feature flag.",
|
||||||
|
"status": "pending",
|
||||||
|
"priority": "high",
|
||||||
|
"dependencies": [],
|
||||||
|
"testStrategy": "New provider can be selected by feature flag while existing SHKeeper payments remain readable and process late webhooks."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 2,
|
||||||
|
"title": "Implement Request Network pay-in integration",
|
||||||
|
"description": "Create Request Network payment requests or Secure Payment Pages for new checkout flows.",
|
||||||
|
"details": "Store requestId, paymentReference, securePaymentUrl, token, merchantReference, network, invoiceCurrency, and paymentCurrency. Validate supported networks/currencies before creating links.",
|
||||||
|
"status": "pending",
|
||||||
|
"priority": "high",
|
||||||
|
"dependencies": [
|
||||||
|
1
|
||||||
|
],
|
||||||
|
"testStrategy": "Buyer receives hosted payment URL; webhook reconciles matching internal payment only after amount/currency/reference validation."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 3,
|
||||||
|
"title": "Add funds ledger and escrow state machine",
|
||||||
|
"description": "Introduce internal funds accounting independent from provider metadata.",
|
||||||
|
"details": "Add FundsAccount, LedgerEntry, derived FundsBalance, expected/held/releasable/releasing/released/refunded/disputed/failed states, fee representation, and release/refund invariant checks.",
|
||||||
|
"status": "pending",
|
||||||
|
"priority": "high",
|
||||||
|
"dependencies": [
|
||||||
|
1
|
||||||
|
],
|
||||||
|
"testStrategy": "Every pay-in creates immutable ledger entries and payout/refund cannot exceed available held funds or bypass dispute holds."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 4,
|
||||||
|
"title": "Build Request Network webhook and reconciliation service",
|
||||||
|
"description": "Process signed Request Network events and repair missed webhook state through reconciliation.",
|
||||||
|
"details": "Add /api/payment/request-network/webhook, verify raw-body x-request-network-signature, store delivery ID/retry/event/request/payment reference/payload hash, support test webhooks, and add scheduled payment search/status reconciliation.",
|
||||||
|
"status": "pending",
|
||||||
|
"priority": "high",
|
||||||
|
"dependencies": [
|
||||||
|
2,
|
||||||
|
3
|
||||||
|
],
|
||||||
|
"testStrategy": "Invalid signatures reject; duplicate delivery IDs acknowledge without duplicate ledger entries; reconciliation repairs missed state."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 5,
|
||||||
|
"title": "Implement release, refund, and payout orchestration",
|
||||||
|
"description": "Replace SHKeeper payout tasks and simulated release with auditable transaction instruction and confirmation flows.",
|
||||||
|
"details": "Create release/refund service consuming ledger balances, generate Request Network payout or direct admin wallet instructions, store unsigned tx payloads, signer, submitted hash, confirmation status, provider status, and require admin/operator authorization plus dispute checks.",
|
||||||
|
"status": "pending",
|
||||||
|
"priority": "high",
|
||||||
|
"dependencies": [
|
||||||
|
3,
|
||||||
|
4
|
||||||
|
],
|
||||||
|
"testStrategy": "Release cannot occur if unpaid, already released, refunded, or disputed; tx hash confirmation updates ledger once; admin can retry/cancel safely."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 6,
|
||||||
|
"title": "Migrate frontend checkout and admin payment UI",
|
||||||
|
"description": "Update buyer checkout, admin release, seller payout, and payment details for provider-neutral Request Network flows.",
|
||||||
|
"details": "Replace ShkeeperPayment with CryptoPayment/RequestNetworkPayment redirect flow, keep legacy SHKeeper only for legacy records, replace ShkeeperPayout with release queue/admin payout UI, and show provider IDs, payment references, hosted links, ledger balances, webhook/reconciliation status.",
|
||||||
|
"status": "pending",
|
||||||
|
"priority": "medium",
|
||||||
|
"dependencies": [
|
||||||
|
2,
|
||||||
|
3,
|
||||||
|
5
|
||||||
|
],
|
||||||
|
"testStrategy": "Request Network checkout does not expect walletAddress; admin UI blocks unsafe release; legacy labels are hidden for Request Network records."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 7,
|
||||||
|
"title": "Backfill legacy SHKeeper records and decommission provider-specific code",
|
||||||
|
"description": "Migrate historical SHKeeper payment metadata and safely remove legacy wallet monitor/webhook/payout paths after cutoff.",
|
||||||
|
"details": "Backfill provider namespace, create ledger entries for trusted completed SHKeeper payments, mark legacyProvider, keep webhook tail period, and produce decommission checklist for env vars, docs, labels, routes, and runbooks.",
|
||||||
|
"status": "pending",
|
||||||
|
"priority": "medium",
|
||||||
|
"dependencies": [
|
||||||
|
3,
|
||||||
|
4,
|
||||||
|
5,
|
||||||
|
6
|
||||||
|
],
|
||||||
|
"testStrategy": "Dry-run report includes total, migrated, skipped, ambiguous, failed; no historical transaction hash/invoice/task metadata is lost."
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 4,
|
||||||
|
"title": "Define backend security and refactor strategy from latest audit",
|
||||||
|
"description": "Convert the backend stack security/refactor assessment into concrete architecture decisions, documentation deliverables, and developer handoff criteria.",
|
||||||
|
"details": "Source audit: .taskmaster/docs/audit-backend-stack-security-and-refactor-assessment-2026-05-24.md. This task is advisory/architecture-focused and should run in parallel with immediate hardening. It should produce the decision artifacts needed before any backend-core rewrite or provider migration is started.",
|
||||||
|
"testStrategy": "Review and sign off each architecture document with backend, payments, frontend, and operations stakeholders. Confirm every open question has an owner or explicit deferred decision before implementation work begins.",
|
||||||
|
"priority": "high",
|
||||||
|
"status": "pending",
|
||||||
|
"dependencies": [],
|
||||||
|
"subtasks": [
|
||||||
|
{
|
||||||
|
"id": 1,
|
||||||
|
"title": "Assign security ownership and launch decision criteria",
|
||||||
|
"description": "Define who owns security decisions and what must be true before public launch or migration work proceeds.",
|
||||||
|
"details": "Answer ownership questions from the audit: security owner, launch safety bar, whether launch prioritizes hardening or redesign, and whether external penetration testing is required.",
|
||||||
|
"status": "pending",
|
||||||
|
"priority": "high",
|
||||||
|
"dependencies": [],
|
||||||
|
"testStrategy": "Written owner/RACI and launch gate checklist are accepted by leadership and engineering."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 2,
|
||||||
|
"title": "Produce threat model for escrow platform",
|
||||||
|
"description": "Document protected assets, actors, trust boundaries, and abuse cases for the financial marketplace.",
|
||||||
|
"details": "Include buyer, seller, admin, support, unauthenticated attacker, compromised user/admin, provider, malicious webhook sender, browser/backend/database/Redis/provider/wallet/Socket.IO trust boundaries, and abuse cases such as fake payment proof, replayed webhook, arbitrary room join, stolen token, double payout, dispute bypass, email abuse, and AI abuse.",
|
||||||
|
"status": "pending",
|
||||||
|
"priority": "high",
|
||||||
|
"dependencies": [
|
||||||
|
1
|
||||||
|
],
|
||||||
|
"testStrategy": "Threat model maps each high-risk finding to at least one mitigation task or accepted risk."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 3,
|
||||||
|
"title": "Specify funds ledger and escrow state machine",
|
||||||
|
"description": "Define canonical money movement and legal state transitions before refactor or provider migration.",
|
||||||
|
"details": "Create specs for FundsAccount, LedgerEntry, FundsBalance, gross paid, provider fees, platform fees, held, disputed, releasable, released, refunded, idempotency keys, reconciliation behavior, purchase request states, payment states, escrow/funds states, dispute states, valid transitions, forbidden transitions, and release/refund/admin override preconditions.",
|
||||||
|
"status": "pending",
|
||||||
|
"priority": "high",
|
||||||
|
"dependencies": [
|
||||||
|
2
|
||||||
|
],
|
||||||
|
"testStrategy": "Spec can be used to reject double-release, release-during-dispute, underfunded payout, and ambiguous provider-event scenarios."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 4,
|
||||||
|
"title": "Create authorization matrix for REST and Socket.IO",
|
||||||
|
"description": "Map every endpoint and realtime event to access level, ownership checks, state preconditions, rate-limit tier, and audit-log requirement.",
|
||||||
|
"details": "Include public/authenticated/owner/buyer/seller/admin/support/service-role classifications. Socket.IO rooms must be server-derived from authenticated identity, not client-supplied user IDs.",
|
||||||
|
"status": "pending",
|
||||||
|
"priority": "high",
|
||||||
|
"dependencies": [
|
||||||
|
2
|
||||||
|
],
|
||||||
|
"testStrategy": "No route or socket event remains unmapped; implementation tasks can reference matrix rows directly."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 5,
|
||||||
|
"title": "Decide session, passkey, and admin step-up architecture",
|
||||||
|
"description": "Choose browser session model and high-risk admin authentication requirements.",
|
||||||
|
"details": "Decide localStorage versus httpOnly cookies, access/refresh token lifetimes, CSRF strategy, refresh rotation, WebAuthn requirements, OAuth requirements, device/session revocation, and whether payouts/role changes require step-up authentication or two-person approval.",
|
||||||
|
"status": "pending",
|
||||||
|
"priority": "high",
|
||||||
|
"dependencies": [
|
||||||
|
2
|
||||||
|
],
|
||||||
|
"testStrategy": "Decision record lists chosen model, rejected alternatives, migration cost, and required implementation tasks."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 6,
|
||||||
|
"title": "Specify webhook security and provider adapter contracts",
|
||||||
|
"description": "Define provider-neutral payment interface and signed webhook processing rules.",
|
||||||
|
"details": "Document createPayInIntent, getPayInStatus, handleProviderWebhook, createHostedPaymentLink, createReleaseInstruction, createRefundInstruction, getPayoutStatus, searchProviderPayments, raw-body signature verification, replay prevention, delivery ID idempotency, duplicate/unknown event behavior, retry semantics, dead-letter/replay storage, and alert thresholds.",
|
||||||
|
"status": "pending",
|
||||||
|
"priority": "high",
|
||||||
|
"dependencies": [
|
||||||
|
3
|
||||||
|
],
|
||||||
|
"testStrategy": "Contracts cover SHKeeper legacy, Request Network, manual/admin wallet, invalid signatures, duplicate deliveries, and missed webhook reconciliation."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 7,
|
||||||
|
"title": "Define secure build and supply-chain policy",
|
||||||
|
"description": "Reduce npm/dependency compromise risk across frontend and any remaining Node services.",
|
||||||
|
"details": "Specify package manager and lockfile policy, CI install mode, dependency update cadence, advisory monitoring, npm provenance/signature policy where available, secrets handling, reproducible production builds, and separation between frontend npm risk and backend-core risk.",
|
||||||
|
"status": "pending",
|
||||||
|
"priority": "medium",
|
||||||
|
"dependencies": [
|
||||||
|
1
|
||||||
|
],
|
||||||
|
"testStrategy": "Policy is actionable in CI and includes response steps for compromised package, leaked token, and vulnerable dependency alerts."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 8,
|
||||||
|
"title": "Make backend-core stack decision",
|
||||||
|
"description": "Choose whether the security-critical backend core remains TypeScript or moves to Go/Kotlin/Rust/Python.",
|
||||||
|
"details": "Evaluate team capability, two-year maintainability, operational footprint, rewrite cost, dual-stack complexity, auditability, supply-chain exposure, and which modules belong in a payment/auth/escrow core versus the existing marketplace/chat API.",
|
||||||
|
"status": "pending",
|
||||||
|
"priority": "medium",
|
||||||
|
"dependencies": [
|
||||||
|
2,
|
||||||
|
3,
|
||||||
|
4,
|
||||||
|
5,
|
||||||
|
6,
|
||||||
|
7
|
||||||
|
],
|
||||||
|
"testStrategy": "Architecture decision record states chosen stack, scope of extraction, non-goals, migration phases, rollback criteria, and owners."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 9,
|
||||||
|
"title": "Create migration and operational runbooks",
|
||||||
|
"description": "Document rollout, rollback, and incident response for the selected backend/funds architecture.",
|
||||||
|
"details": "Include SHKeeper legacy read path, provider feature flag, ledger backfill, validation report before enforcement, rollback criteria, webhook cutoff, manual reconciliation, failed webhook, duplicate/missing payment, stuck release, disputed release attempt, compromised admin, leaked API key, provider outage, chain/RPC outage, suspicious payment proof, and npm/package compromise.",
|
||||||
|
"status": "pending",
|
||||||
|
"priority": "medium",
|
||||||
|
"dependencies": [
|
||||||
|
8
|
||||||
|
],
|
||||||
|
"testStrategy": "Runbooks identify owner, trigger, detection signal, immediate action, recovery action, and post-incident documentation for each scenario."
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -153,6 +153,7 @@ For engineers / SREs running the system in production.
|
|||||||
| **Payments** | [[Payment Flow - SHKeeper]] → [[Payment API]] → [[Payment]] → [[Payout Flow]] |
|
| **Payments** | [[Payment Flow - SHKeeper]] → [[Payment API]] → [[Payment]] → [[Payout Flow]] |
|
||||||
| **Auth** | [[Authentication Flow]] → [[Authentication API]] → [[Security Architecture]] |
|
| **Auth** | [[Authentication Flow]] → [[Authentication API]] → [[Security Architecture]] |
|
||||||
| **Backend security / refactor** | [[Backend Stack Security and Refactor Assessment - 2026-05-24]] → [[Platform Logical Audit - 2026-05-24]] → [[PRD - Platform Audit Remediation Plan (2026-05-24)]] |
|
| **Backend security / refactor** | [[Backend Stack Security and Refactor Assessment - 2026-05-24]] → [[Platform Logical Audit - 2026-05-24]] → [[PRD - Platform Audit Remediation Plan (2026-05-24)]] |
|
||||||
|
| **Developer task queue** | `.taskmaster/README.md` → `.taskmaster/tasks/tasks.json` → root `PRD - *.md` files |
|
||||||
| **Real-time** | [[Real-time Layer]] → [[Socket Events]] → [[Chat Flow]] / [[Notification Flow]] |
|
| **Real-time** | [[Real-time Layer]] → [[Socket Events]] → [[Chat Flow]] / [[Notification Flow]] |
|
||||||
| **Disputes** | [[Dispute Flow]] → [[Dispute API]] → [[Dispute]] → [[Admin Guide]] §5 |
|
| **Disputes** | [[Dispute Flow]] → [[Dispute API]] → [[Dispute]] → [[Admin Guide]] §5 |
|
||||||
| **Web3** | [[Payment Flow - DePay & Web3]] → [[Frontend Architecture]] §9 |
|
| **Web3** | [[Payment Flow - DePay & Web3]] → [[Frontend Architecture]] §9 |
|
||||||
|
|||||||
Reference in New Issue
Block a user