StatWoX is a social platform for forms, surveys, polls, and quizzes that connects data collection directly to analysis, decision-making, and social engagement.
Most tools stop at collecting responses. Real teams struggle after that. StatWoX removes this entire gap while introducing a Trust & Identity Layer, a ZhiPu GLM-4-Flash AI Co-Pilot, a Neuromorphic UI Design System, and enterprise features including 2FA, RBAC Workspaces, Content Moderation, Billing Tiers, and 822+ Unit Tests.
- What StatWoX Does
- Architecture Diagram
- Detailed Architecture Breakdown
- Low-Level Architecture
- Terraform Infra Map
- CI/CD Pipeline
- Authentication Sequence Diagram
- Survey Creation Pipeline
- Data Flow
- Backend Internal Module Graph
- Tech Stack
- Entire DB Schema
- Local Setup Guide
- Production Deployment Terraform
- API Reference
- Contributing Guide
- Changelog
StatWoX combines Google Forms simplicity + a Neuromorphic Design System (CSS Variables, Glassmorphism, Framer Motion 12, driver.js Onboarding) + a public social feed + Identity Verification (Google/LinkedIn/DigiLocker) + RBAC Workspaces + Billing Tiers.
Core capabilities:
- Auth: JWT HS256 (jose) + Refresh Token Rotation + Google/LinkedIn/DigiLocker OAuth + Email Verify (Resend) + Password Reset (SHA-256) + 2FA TOTP (otplib + QR)
- Dashboard: Real-time Pusher notifications (4 channels, 7 events) + driver.js onboarding
- Survey Engine: 19 question types (shortText, longText, multipleChoice, checkbox, dropdown, rating, slider, date, time, email, phone, url, number, yesNo, signature, matrix, ranking, nps, fileUpload) + dnd-kit reorder + skip-logic (7 operators + circular DFS detection) + text piping (
$questionId,$respondentName,$surveyTitle) + conditional thank-you + theming + password protection + i18n + QR codes + webhooks (HMAC-SHA256 via QStash) + conversational mode - Analytics: 7 endpoints — base, sentiment (GLM-4-Flash), funnel, crosstab, NPS, significance, AI summary — Recharts 3 + d3-cloud
- Trust: Identity verification for public broadcasting. Verified badges.
collectEmaillocked behind verification - AI Co-Pilot: ZhiPu GLM-4-Flash (
glm-4-flash) — sentiment, summarization, question gen (SEC-006), follow-up suggestions - Moderation: Reporting (spam/inappropriate/misleading) with admin pipeline
- Workspaces: RBAC Owner/Editor/Viewer with workspace-scoped surveys
- Billing: FREE/PRO/ENTERPRISE, metered AI sentiment + funnel (3/month FREE)
- Delivery: Vercel CI/CD or AWS (12 Terraform
.tffiles ininfra/) - E2E Encrypted Messaging: Web Crypto API powering secure, end-to-end encrypted chat streams with Audio/Voice recording.
- Data Science Sandbox: In-browser Python environment via Pyodide WASM, Monaco Editor, Pandas, and Matplotlib.
- Guilds & Communities: Deep hierarchy of nested communities with slash-command palettes, haptic feeds, and Smart Replies.
- Generative Analytics: AI-powered natural language to Recharts generation ("Show me a pie chart of Q4").
View 6-Plane Architecture
flowchart TB
classDef core fill:#121214,stroke:#00d4ff,stroke-width:2px,color:#ffffff
classDef secondary fill:#1a1a1e,stroke:#ffffff,stroke-width:1px,color:#ffffff
subgraph Management ["ORCHESTRATION"]
GA["GitHub Actions CI/CD<br/>ci.yml + deploy.yml + ci-cd.yml"]
TF["Terraform IaC 12 .tf files"]
VAULT["Secrets Vault"]
end
subgraph Client ["USER ACCESS"]
BROWSER["Browser<br/>Next.js 16 + React 19.2.3"]
subgraph EdgeLayer ["Edge"]
R53["Route53 DNS"]
ACM["ACM SSL"]
CF["CloudFront / Vercel CDN"]
end
end
subgraph Security ["SECURITY"]
G["Edge Middleware 159 LOC<br/>JWT jose + CSRF + 6 Headers"]
H["Rate Limit 5 req/10s<br/>Redis + Memory Fallback"]
TOTP_BLK["2FA TOTP otplib + QR"]
end
subgraph Compute ["RUNTIME"]
subgraph AppCluster ["Next.js 16"]
NEXT["App Router 3 Groups 10 Pages"]
LAMBDA["AWS Lambda"]
end
subgraph Logic ["25 Lib Modules"]
AUTH_BLK["Auth + RBAC + Trust<br/>auth jwt oauth totp withAuth"]
AI_BLK["GLM-4-Flash AI 208 LOC<br/>chatCompletion generateQuestions<br/>analyzeSentiment generateSummary<br/>generateFollowUp"]
SYNC["Pusher 187 LOC<br/>4 Channels 7 Events Presence"]
VALID_BLK["Zod 4 113 LOC<br/>10 Isomorphic Schemas"]
SKIP_BLK["Skip Logic 169 LOC<br/>7 Operators + DFS Cycle Detection"]
PIPE_BLK["Text Piping 58 LOC<br/>$questionId $respondentName $surveyTitle"]
QTYPES_BLK["Question Types 294 LOC<br/>19 Runtime Types + Validators"]
SANITIZE_BLK["Sanitizer 57 LOC<br/>sanitize-html XSS"]
WEBHOOK_BLK["Webhooks 76 LOC<br/>HMAC-SHA256 + QStash"]
USAGE_BLK["Billing Meter 84 LOC<br/>3/month FREE"]
AUDIT_BLK["Audit 34 LOC<br/>9 Actions 6 Entities"]
end
end
subgraph Persistence ["DATA"]
NEON[("Neon Postgres<br/>Prisma 5.22<br/>22 Models 9 Enums")]
S3_BLK[("S3 / R2")]
QSTASH_BLK["QStash Webhooks"]
EMAIL_BLK["Resend Email"]
end
subgraph Observability ["OBSERVE"]
CW_BLK["CloudWatch"]
SENTRY_BLK["Sentry"]
AUDIT_OBS["AuditLog SQL"]
FUNNEL_OBS["PageView Funnels"]
end
TF -. Provision .-> CF
TF -. Provision .-> LAMBDA
TF -. Provision .-> NEON
GA -. Deploy .-> NEXT
BROWSER --> R53 --> CF --> G
G <--> H
G ==> NEXT <--> LAMBDA
LAMBDA --> Logic
Logic <--> NEON
LAMBDA --> S3_BLK
LAMBDA --> QSTASH_BLK
LAMBDA --> EMAIL_BLK
LAMBDA -.-> CW_BLK
NEXT -.-> SENTRY_BLK
NEON -.-> AUDIT_OBS
NEON -.-> FUNNEL_OBS
class GA,TF,VAULT,R53,ACM,CF,G,H,TOTP_BLK,AUTH_BLK,AI_BLK,SYNC,VALID_BLK,SKIP_BLK,PIPE_BLK,QTYPES_BLK,SANITIZE_BLK,WEBHOOK_BLK,USAGE_BLK,AUDIT_BLK,CW_BLK,SENTRY_BLK,AUDIT_OBS,FUNNEL_OBS,EMAIL_BLK secondary
class BROWSER,NEXT,LAMBDA,NEON,S3_BLK,QSTASH_BLK core
- React 19.2.3 + Next.js 16.1.6 App Router: 3 route groups —
(auth)(login, forgot-password, reset-password),(dashboard)(surveys, feed, community, messages, profile, api-docs),(survey)(builder, responder, analytics) - Zustand 5 (persist):
useAuthStore(session + background verify) +useSurveyStore(CRUD + notifications) - Neuromorphic Design:
design-tokens.css(62 LOC: palette #09090b/#121214/#1a1a1e, shadows, --n-cyan #00d4ff) +globals.css(821 LOC: 15 keyframes, glassmorphism, gradient borders, cyber scan, driver.js theme, status badges, OTP inputs) - Radix UI: 15 primitives (Dialog, DropdownMenu, Tabs, Toast, Tooltip, Switch, Select, Avatar, Progress, ScrollArea, Popover, Label, Slot, AlertDialog, Alert)
- 11 Component Modules: analytics(3) auth(2) builder(8) community(1) feed(3) layout(2) messages(1) profile(2) responder(4) surveys(1) ui(32)
- 3 Hooks: useToast, useDebounce, useInlineValidation
- TanStack React Query 5: Server-state caching
- Auth (14 sub-routes): register, login, logout, me, refresh, google(+cb), linkedin(+cb), digilocker(+cb), forgot-password, reset-password, verify-email(+confirm+resend), password, 2fa(setup+verify), otp
- Surveys (CRUD + 14 sub): CRUD, analytics(7: base/crosstab/funnel/nps/sentiment/significance/summary), respond, comments, like, close, draft, duplicate, export, pageview, publish, unpublish, qrcode, report, versions
- Other: ai, audit, comments, cron, docs(Swagger), feed, gdpr, health, notifications, pusher/auth, question-bank, templates, upload(presigned), users, workspaces
- Edge Middleware (159 LOC): 14 public routes + 2 optional-auth. CSRF mutations. JWT jose. 6 headers. x-request-id/x-user-id/x-user-email
- Zod 4 (113 LOC): 10 schemas with strong password rules
- Rate Limit: 5 req/10s Redis + 10K memory fallback
| Module | LOC | Purpose |
|---|---|---|
| auth.ts | 72 | bcryptjs (12 rounds), getUserFromToken, getUserFromRequest |
| jwt.ts | 37 | jose HS256 signToken(7d), verifyToken, 32-char min |
| withAuth.ts | 44 | HOF auth wrapper |
| validations.ts | 113 | 10 Zod 4 isomorphic schemas |
| oauth.ts | 136 | Google + LinkedIn + DigiLocker exchange |
| totp.ts | 41 | otplib secret gen, QR DataURI, verify |
| ai.ts | 208 | GLM-4-Flash: 5 funcs (chatCompletion, generateQuestions SEC-006, analyzeSentiment, generateSummary, generateFollowUp) |
| pusher.ts | 187 | 4 channels, 7 events, presence, subscribe/trigger |
| ratelimit.ts | 50 | Redis 5/10s + memory 10K FIFO |
| sanitize.ts | 57 | sanitize-html XSS |
| skipLogic.ts | 169 | 7 operators, DFS cycle, visible questions |
| textPiping.ts | 58 | $var interpolation, resolvePageQuestions |
| questionTypes.ts | 294 | 19 types, per-type validateAnswer |
| webhook.ts | 76 | HMAC-SHA256 + QStash, 3 events |
| usage.ts | 84 | Billing: 3/month FREE, unlimited PRO/ENT |
| email.ts | 48 | Resend verify + console stub |
| audit.ts | 34 | 9 actions, 6 entities, non-blocking |
| r2.ts | ~16 | R2/S3 client |
| redis.ts | ~12 | Upstash singleton |
| logger.ts | ~30 | Structured logging |
| motion.ts | ~44 | Framer presets |
| loading-phrases.ts | ~40 | Dynamic phrases |
| api-utils.ts | ~22 | apiResponse/apiError |
| db.ts | ~12 | Prisma singleton |
- Prisma 5.22: 22 models, 9 enums, 639 lines, fullTextSearch preview
- Enums: SurveyStatus, SurveyCategory, ShareType, FriendshipStatus, WorkspaceRole, VerificationMethod, QuestionType(16), SubscriptionPlan
View Request Lifecycle
flowchart TB
Req["HTTP Request"] --> MW["Edge Middleware 159 LOC"]
MW --> TraceID["crypto.randomUUID x-request-id"]
TraceID --> CSRFCheck{"Mutation?"}
CSRFCheck -->|Yes| CSRF["Origin + Referer check"]
CSRF -->|Fail| CSRF403["403 CSRF_FAILED"]
CSRF -->|Pass| AuthCheck
CSRFCheck -->|No| AuthCheck{"Public?"}
AuthCheck -->|Public| Headers["6 Security Headers"]
AuthCheck -->|Protected| JWTVerify["jose HS256 verify"]
JWTVerify -->|Invalid| Auth401["401"]
JWTVerify -->|Valid| Inject["x-user-id x-user-email"]
Headers --> RH["Route Handler"]
Inject --> RH
RH --> RL["ratelimit 5/10s"]
RL --> ZV["Zod Validate"]
ZV -->|Fail| R400["400"]
ZV -->|Pass| SAN["sanitize XSS"]
SAN --> AU["getUserFromRequest"]
AU --> PR["Prisma 5.22"]
PR --> NE["Neon DB"]
NE --> RH
RH --> AL["audit.ts"]
RH --> WH["webhook.ts QStash"]
RH --> PU["pusher.ts"]
RH --> RS["NextResponse.json"]
12 .tf files in infra/ for AWS.
View Terraform
flowchart TB
TF_ROOT["Terraform infra/"] --> VPC_TF["vpc.tf"]
TF_ROOT --> S3_TF["s3.tf"]
TF_ROOT --> CF_TF["cloudfront.tf"]
TF_ROOT --> APIGW_TF["apigw.tf"]
TF_ROOT --> LMD_TF["lambda.tf"]
TF_ROOT --> DB_TF["database.tf Aurora"]
TF_ROOT --> R53_TF["route53.tf"]
TF_ROOT --> ACM_TF["acm.tf SSL"]
TF_ROOT --> CW_TF["cloudwatch.tf"]
TF_ROOT --> VAR_TF["variables.tf 7 vars"]
CF_TF --> LMD_TF
R53_TF --> CF_TF
ACM_TF --> CF_TF
LMD_TF --> DB_TF
StatWoX utilizes a high-performance GitHub Actions pipeline hardened for Node.js 24.
- Elite Security Pass: Mandatory
SEC-21traceability checks. - Node.js 24 Enforced: Standardized runner environment for parity with Vercel Production.
- Lint-Staged Flexibility: Architectural placeholders (prefixed with
_) are permitted for future-proofing.
View CI/CD
flowchart TB
subgraph CI ["ci.yml 5 Jobs"]
I["Install npm ci + prisma"] --> L["Lint ESLint"]
I --> T["TypeCheck tsc"]
I --> V["Vitest 822+ tests"]
L --> B["Build"]
T --> B
V --> B
end
subgraph Deploy ["deploy.yml 4 Jobs"]
DL["Lint bun"] --> PR["Vercel Preview"]
DL --> P["Vercel Prod"]
P --> M["prisma migrate deploy"]
end
Dev("Push / PR") --> CI -->|Pass| Deploy
View Auth Flow
sequenceDiagram
participant U as User
participant F as Frontend
participant E as Edge MW
participant A as Auth API
participant P as OAuth Provider
participant R as Resend
participant D as Neon DB
Note over U, D: Registration
U->>F: Register (Zod validated)
F->>A: POST /auth/register
A->>D: Create User bcryptjs 12 rounds
A->>R: Verification email
A-->>F: 201 + JWT HS256 7d
Note over U, D: OAuth
U->>F: Sign in Google
F->>P: Redirect
P-->>A: GET /auth/google/callback
A->>P: Exchange code for userinfo
A->>D: Upsert + RefreshToken
A-->>F: JWT + Refresh
Note over U, D: Refresh Rotation
F->>A: POST /auth/refresh
A->>D: Revoke old + issue new pair
A-->>F: Rotated tokens
Note over U, D: Edge Security
F->>E: /api/protected
E->>E: CSRF + JWT + 6 headers + x-request-id
E-->>F: Pass with x-user-id
Note over U, D: 2FA TOTP
F->>A: POST /auth/2fa/setup
A->>D: otplib secret
A-->>F: QR DataURI
U->>F: 6-digit code
F->>A: POST /auth/2fa/verify
A-->>F: Session granted
Note over U, D: Trust Verify
F->>A: Make survey public
A->>D: Check isVerified
D-->>A: false
A-->>F: 403 Need verify
U->>F: Verify LinkedIn
A->>D: isVerified=true
A-->>F: Badge unlocked
Note over U, D: Password Reset
F->>A: POST /auth/forgot-password
A->>D: PasswordResetToken SHA-256
A->>R: Reset link
F->>A: POST /auth/reset-password
A->>D: Update hash
A-->>F: 200
View Builder Flow
flowchart LR
User -->|"19 types dnd-kit"| FE["Frontend"]
FE -->|"POST /surveys"| RT["Route"]
RT --> AU["x-user-id Edge"]
AU --> ZD["Zod surveyCreateSchema"]
ZD -->|Fail| R4["400"]
ZD -->|Pass| SN["sanitize"]
SN --> SK["skipLogic DFS"]
SK --> TX["Prisma Transaction"]
TX -->|"Survey+Questions+Audit"| DB["Neon"]
DB --> RT --> FE
View Analytics
flowchart TB
RES["POST respond"] --> VAL["Zod + questionTypes"]
VAL --> STO["Store Answers+PageViews"]
STO --> PU["Pusher NEW_RESPONSE"]
STO --> WH["webhook response.created HMAC"]
subgraph AN ["7 Analytics Endpoints"]
B["Base"]
SE["Sentiment GLM-4-Flash"]
FU["Funnel PageView"]
CR["Crosstab"]
NP["NPS"]
SI["Significance"]
SU["Summary AI"]
end
CH["Recharts + d3-cloud"] -->|TanStack| AN
PU -.->|Refetch| CH
View 17 API Modules
flowchart LR
subgraph FE["Frontend React 19.2.3"]
S1["useAuthStore"]
S2["Builder 19 types"]
S3["Analytics"]
S4["Feed"]
S5["Profile 2FA"]
S6["Messages Community"]
end
subgraph MW["Middleware"]
M1["middleware.ts 159 LOC"]
M2["db.ts Prisma"]
M3["validations.ts 10 Schemas"]
M4["ratelimit.ts"]
end
subgraph API["17 Modules"]
A1["/auth 14 sub"]
A2["/surveys CRUD+14"]
A3["/analytics 7"]
A4["/feed"]
A5["ai audit comments cron docs<br/>gdpr health notifications<br/>pusher question-bank templates<br/>upload users workspaces"]
end
S1 <--> A1
S2 <--> A2
S3 <--> A3
S4 <--> A4
S5 <--> A1
S6 <--> A5
A1 & A2 & A3 & A4 & A5 --> M1
A1 & A2 --> M2
A1 & A2 --> M3
A1 --> M4
| Domain | Technologies |
|---|---|
| Frontend | |
| Logic | |
| Backend | |
| Architecture | |
| Infra | |
| Data | |
| Security | |
| QA | |
| Monitoring |
StatWoX maintains a relational PostgreSQL database with 22 models and 9 enums (639 schema lines) managing core surveys (19 question types), skip-logic, social features (comments, likes, follows, friendships), RBAC workspaces, audit logs, trust identities, content moderation, billing tiers, 2FA, and OTP.
View Master ERD
erDiagram
User ||--o{ Survey : creates
User ||--o{ Response : submits
Survey ||--o{ Question : contains
Survey ||--o{ Response : tracks
Question ||--o{ Answer : receives
Response ||--o{ Answer : contains
User ||--o{ Comment : writes
User ||--o{ Like : gives
User ||--o{ Notification : receives
User ||--o{ Friendship : sends
User ||--o{ Friendship : receives
User ||--o{ Follow : following
User ||--o{ Follow : followers
Survey ||--o{ Comment : has
Survey ||--o{ Like : has
Comment ||--o{ Comment : replies
User ||--o{ QuestionBank : owns
User ||--o{ Workspace : owns
User ||--o{ WorkspaceMember : belongs_to
Survey ||--o{ SurveyVersion : versions
Survey ||--o{ ScheduledReport : triggers
Workspace ||--o{ Survey : contains
Workspace ||--o{ WorkspaceMember : has
User ||--o{ AuditLog : performs
User ||--o{ Template : authors
Survey ||--o{ PageView : tracks
Response ||--o{ PageView : drops
User ||--o{ Report : flags
Survey ||--o{ Report : flagged_in
User ||--o{ RefreshToken : signs
User {
String id PK
String email UK
String username UK
String passwordHash
String name
String image
String bio
String website
String company
String coverImage
String phone UK
Boolean isOnline
DateTime lastSeenAt
DateTime deletedAt
String googleId UK
String linkedInId UK
String digilockerId UK
Boolean isVerified
VerificationMethod verificationMethod
Boolean twoFactorEnabled
String twoFactorSecret
SubscriptionPlan plan
Int aiSentimentUsage
Int funnelViewUsage
DateTime usageResetAt
}
Survey {
String id PK
String title
String description
SurveyCategory category
SurveyStatus status
Boolean isPublic
ShareType shareType
Boolean allowAnon
Boolean collectEmail
String mediaType
String mediaUrl
String caption
Int maxResponses
DateTime closesAt
String thankYouMessage
Json thankYouLogic
String redirectUrl
Boolean showProgress
Boolean showQuestionNumbers
Boolean shuffleQuestions
Boolean conversational
String password
Json theme
String locale
Json translations
Int version
String qrCodeUrl
String webhookUrl
String webhookSecret
String customDomain
String stripeProductId
String stripePriceId
Boolean paymentRequired
Json ipAllowlist
Int responseCount
Int viewCount
Int likeCount
Int commentCount
Boolean featured
DateTime lastActivityAt
String authorId FK
String workspaceId FK
}
Question {
String id PK
String title
String description
QuestionType type
Boolean required
Json options
Int order
Int page
String placeholder
String validation
Int min
Int max
Json rows
Json columns
Json logic
Boolean fileUpload
String fileTypes
Int maxFileSize
String surveyId FK
}
Response {
String id PK
Boolean isComplete
DateTime startedAt
DateTime completedAt
String ipAddress
String userAgent
Json metadata
Int duration
Boolean flagged
String flagReason
String country
String region
String deviceType
String surveyId FK
String respondentId FK
}
Answer {
String id PK
String value
String fileUrl
String fileKey
Json matrixData
Json rankingData
String signatureUrl
Float sentimentScore
String sentimentLabel
String questionId FK
String responseId FK
}
PageView {
String id PK
Int pageNumber
Int timeSpent
String surveyId FK
String responseId FK
}
Workspace {
String id PK
String name
String slug UK
String ownerId FK
}
WorkspaceMember {
String id PK
WorkspaceRole role
String userId FK
String workspaceId FK
}
AuditLog {
String id PK
String action
String entityType
String entityId
String userId FK
Json metadata
String ipAddress
}
Report {
String id PK
String reason
String description
String status
String reporterId FK
String surveyId FK
}
RefreshToken {
String id PK
String hashedToken UK
String userId FK
Boolean revoked
DateTime expiresAt
}
VerificationToken {
String id PK
String identifier
String token UK
String type
DateTime expires
}
PasswordResetToken {
String id PK
String email
String tokenHash UK
Boolean used
DateTime expiresAt
}
OTP {
String id PK
String phone
String code
Boolean verified
DateTime expiresAt
}
QuestionBank {
String id PK
String title
String type
Json options
String userId FK
}
SurveyVersion {
String id PK
Int version
Json snapshot
String changeNote
String surveyId FK
String authorId FK
}
Template {
String id PK
String name
String category
Json snapshot
Boolean isPublic
Int usageCount
String authorId FK
}
ScheduledReport {
String id PK
String recipientEmail
String frequency
String format
DateTime nextSendAt
Boolean active
String surveyId FK
}
Comment {
String id PK
String content
String authorId FK
String surveyId FK
String parentId FK
}
Like {
String id PK
String userId FK
String surveyId FK
}
Notification {
String id PK
String type
String title
String message
Boolean read
String userId FK
}
Friendship {
String id PK
FriendshipStatus status
String requesterId FK
String receiverId FK
}
Follow {
String id PK
String followerId FK
String followingId FK
}
Click to expand
Ensure you are using node >= 20 and bun package manager. If on Windows, run inside WSL (Ubuntu).
git clone https://github.com/MrCh0p808/StatWoX.git
cd StatWoX
bun installcp .env.example .envRequired variables (see .env.example for full list of 17 variables):
DATABASE_URL="postgresql://user:pass@host/dbname?sslmode=require"
JWT_SECRET="your_32_char_secure_secret"
NEXT_PUBLIC_APP_URL="http://localhost:8000"
GOOGLE_CLIENT_ID="xxx"
GOOGLE_CLIENT_SECRET="xxx"
LINKEDIN_CLIENT_ID="xxx"
LINKEDIN_CLIENT_SECRET="xxx"
UPSTASH_REDIS_REST_URL="https://..."
UPSTASH_REDIS_REST_TOKEN="..."
PUSHER_APP_ID="xxx"
NEXT_PUBLIC_PUSHER_KEY="xxx"
PUSHER_SECRET="xxx"
NEXT_PUBLIC_PUSHER_CLUSTER="us2"
RESEND_API_KEY="re_xxx"
ZHIPU_API_KEY="xxx"bun run db:push
bun run db:generate
bun run db:seedbun run devThe app will be available at http://localhost:8000.
bun run test822+ unit tests via Vitest 4 across src/__tests__/.
Click to expand
Automated via deploy.yml GitHub Action. PRs get preview deploys, pushes to main trigger production deploy + DB migrations.
bun run deploy # manual staging
bun run deploy:prod # manual productionbun run build
cd infra
terraform init
terraform applyProvisions: VPC (vpc.tf), Aurora Serverless v2 (database.tf), Lambda (lambda.tf), API Gateway (apigw.tf), CloudFront (cloudfront.tf), S3 (s3.tf), Route53 (route53.tf), ACM (acm.tf), CloudWatch (cloudwatch.tf).
Variables required in variables.tf: aws_region, project, db_username, db_password, jwt_secret, google_client_id, domain_name (default: statwox.ttoxtech.in).
REST API with JWT Authorization: Bearer <token>. CSRF protection on mutations (POST/PUT/PATCH/DELETE). Swagger UI at /api/docs.
-
Auth (14 sub-routes):
POST /api/auth/register— Zod validated (email + password min 8 + uppercase + number + special)POST /api/auth/login— Email + passwordPOST /api/auth/logout— Invalidate sessionGET /api/auth/me— Current user profilePOST /api/auth/refresh— Rotate refresh token pairGET /api/auth/google→GET /api/auth/google/callback— Google OAuthGET /api/auth/linkedin→GET /api/auth/linkedin/callback— LinkedIn OAuthGET /api/auth/digilocker→GET /api/auth/digilocker/callback— DigiLockerPOST /api/auth/verify-email,GET /api/auth/verify-email/confirm— Email verificationPOST /api/auth/forgot-password→POST /api/auth/reset-password— Password resetPATCH /api/auth/password— Change password (authenticated)POST /api/auth/2fa/setup→POST /api/auth/2fa/verify— TOTP 2FA (otplib + QR)POST /api/auth/otp/*— Phone OTP
-
Surveys (CRUD + 14 sub-endpoints):
GET|POST /api/surveys— List / Create (ZodsurveyCreateSchema)GET|PATCH|DELETE /api/surveys/:id— Read / Update / Soft-deletePOST /api/surveys/:id/publish|unpublish|close|draft|duplicateGET /api/surveys/:id/export— CSV/JSON exportGET /api/surveys/:id/qrcode— QR code generationGET /api/surveys/:id/versions— Version historyPOST /api/surveys/:id/report— Content moderation (spam/misleading)
-
Responses:
POST /api/surveys/:id/respond— Submit (duplicate prevention, skip-logic, per-type validation, webhook trigger)POST /api/surveys/:id/pageview— Track funnel metrics
-
Social:
POST /api/surveys/:id/like— ToggleGET|POST /api/surveys/:id/comments— Threaded (parentId for replies)
-
Analytics (7 endpoints):
GET /api/surveys/:id/analytics— Base (time-series, distributions)GET .../analytics/sentiment— GLM-4-Flash scoringGET .../analytics/funnel— PageView drop-off (metered: 3/month FREE)GET .../analytics/crosstab— Cross-tabulationGET .../analytics/nps— Net Promoter ScoreGET .../analytics/significance— Statistical significanceGET .../analytics/summary— AI natural-language summary
-
Feed:
GET /api/feed— Paginated public surveys (trending algorithms) -
Other: ai, audit, cron, docs (Swagger), gdpr, health, notifications, pusher (auth), question-bank, templates, upload (presigned), users, workspaces
StatWoX is developed beneath the CoderWa Protocol. PRs should address specific isolated waves from the Master Plan.
feat/*: New featuresfix/*: Bug fixestest/*: Test coverage expansions (Aim for Vitest coverage increases)refactor/*: Code quality improvementsdocs/*: Documentation updates
Before raising a PR, ensure all 822+ Unit Tests pass natively using bun run test.
Requirements for new API routes:
- Zod validation schemas in
lib/validations.ts - Edge Middleware route classification (public/protected/optional)
- Vitest test coverage
- AuditLog entries for state-changing operations
- Input sanitization via
lib/sanitize.ts
- Design System: Neuromorphic UI —
design-tokens.css(62 lines: neon dark palette#09090b/#121214/#1a1a1e, inset/outset shadows, glow effects) +globals.css(821 lines: 15 keyframe animations, glassmorphism, gradient borders, cyber scan overlay, driver.js onboarding, status badges, chart tooltips, OTP inputs). - Framework: Next.js 16.1.6, React 19.2.3, Zustand 5, TailwindCSS 4, Zod 4, Vitest 4, Framer Motion 12.
- Auth: 14 sub-routes — register/login/logout/me/refresh, Google/LinkedIn/DigiLocker OAuth, email verification (Resend), password reset (SHA-256 tokens), 2FA (TOTP via otplib + QR), OTP.
- Edge Security: 159-LOC middleware — 14 public routes, CSRF origin/referer validation on mutations, JWT (jose HS256), 6 security headers (CSP, HSTS, X-Frame-Options, X-Content-Type-Options, Referrer-Policy, Permissions-Policy),
x-request-idtracing. - Validation: 10 isomorphic Zod 4 schemas in
lib/validations.ts(113 lines) with strong password rules. - Database: Prisma 5.22 — 22 models, 9 enums, 639 schema lines. Added OTP, PasswordResetToken, VerificationToken, Follow, Report, billing fields, fullTextSearch preview.
- Survey Engine: 19 question types (runtime
questionTypes.ts: 294 lines). Skip logic (7 operators + circular DFS detection). Text piping ($questionId,$respondentName,$surveyTitle). Webhook delivery (HMAC-SHA256 via QStash with fetch fallback, 3 events). Custom theming, password protection, i18n, QR codes, conversational mode, conditional thank-you, IP allowlisting. - Analytics: 7 endpoints — base, sentiment (GLM-4-Flash via
ai.ts: 208 lines), funnel, crosstab, NPS, significance, summary. Recharts 3 + d3-cloud. - AI: ZhiPu GLM-4-Flash (model:
glm-4-flash) — 4 functions: chatCompletion, generateQuestions (SEC-006 prompt injection guard), analyzeSentiment, generateSummary, generateFollowUp. 15s timeout. - Real-time: Pusher — 4 channels (vey-responses, notifications, messages, presence), 7 events (new-response, update, new-notif, new-msg, typing, online, offline).
- Social: Comments (threaded replies), likes, follows, friendships, notifications, public feed, verified badges, content moderation (Report model: spam/inappropriate/misleading → pending/reviewed/dismissed/actioned).
- Enterprise: RBAC Workspaces (Owner/Editor/Viewer), audit logging (9 actions, 6 entity types), question bank, survey versioning, template marketplace, scheduled reports, GDPR API.
- Billing: FREE/PRO/ENTERPRISE — metered AI sentiment + funnel views (3/month FREE limit, auto-reset monthly).
- Testing: 822+ unit tests via Vitest 4 across
src/__tests__/. - CI/CD: 3 GitHub Actions workflows —
ci.yml(5 jobs: install/lint/typecheck/test/build),deploy.yml(4 jobs: lint/preview/production/migrate),ci-cd.yml. - Infra: 12 Terraform
.tffiles ininfra/(VPC, Lambda, API Gateway, CloudFront, S3, Aurora, Route53, ACM, CloudWatch, variables, outputs, providers). Domain:statwox.ttoxtech.in. - Components: 11 modules, 32 shared UI components (Radix).
- Lib: 25 utility modules totaling ~1,800 lines.
- Core: Finalized Next.js App Router codebase conversion.
- Feature: 191+ Atomic Unit Tests deployed globally protecting APIs.
- Security: Scraped memory-leaks and hardcoded PII disclosures in HTTP Handlers.
- Feature: Upcoming Trust Identity System mapped out inside Schema.
- Core: Initial release.
- Feature: Complete Survey Builder UI.
- Infra: Full Terraform deployment suite.
Every feature StatWoX has shipped across 24 phases, organized by domain. Each entry explains what the feature is, how it works technically, and provides a Mermaid diagram showing the flow.
Desc: The monolith-to-modern migration that established the Next.js 15 App Router, PostgreSQL via Neon/Prisma, Zustand state management, and a 871-test safety net.
Tech: React 19 concurrent features, TypeScript 5 strict mode, Prisma global singleton to prevent connection exhaustion, Vitest 4 with 34 test files covering every API route and library module.
flowchart LR
subgraph Foundation ["Phase 1-3 Foundation"]
NX["Next.js 15 App Router"] --> TS["TypeScript 5 Strict"]
TS --> PR["Prisma 5.22 ORM"]
PR --> NE["Neon Serverless PG"]
NX --> ZU["Zustand 5 State"]
NX --> TW["Tailwind CSS 4"]
NX --> FM["Framer Motion 12"]
NX --> VT["Vitest 871 Tests"]
end
Desc: A multi-layer identity verification system (Google, LinkedIn, DigiLocker) that gates public broadcasting behind verified badges, plus 2FA TOTP, refresh token rotation, and edge security middleware.
Tech: OAuth 2.0 code exchange via lib/oauth.ts (136 LOC) for 3 providers. TOTP via otplib with QR DataURI generation. Edge middleware (159 LOC) validates JWT (jose HS256), enforces CSRF on mutations, and injects 6 security headers. Refresh token rotation revokes the old pair atomically in a Prisma transaction.
flowchart TB
subgraph Trust ["Phase 4-5 Identity and Auth"]
USER["User"] --> OAUTH{"OAuth Provider?"}
OAUTH -->|Google| G["Google OAuth 2.0"]
OAUTH -->|LinkedIn| L["LinkedIn OAuth"]
OAUTH -->|DigiLocker| D["DigiLocker KYC"]
G & L & D --> VERIFY["isVerified = true"]
VERIFY --> BADGE["Verified Badge Unlocked"]
USER --> TOTP["2FA Setup"]
TOTP --> SECRET["otplib Secret Gen"]
SECRET --> QR["QR DataURI"]
QR --> CODE["6-digit Code Verify"]
CODE --> SESSION["Session Granted"]
end
Desc: A powerful survey creation engine supporting 19 question types, skip-logic with cycle detection, text piping, conditional thank-you screens, webhooks, and conversational mode.
Tech: 19 runtime question types with per-type validators in questionTypes.ts (294 LOC). Skip logic engine (skipLogic.ts, 169 LOC) supports 7 comparison operators and runs DFS cycle detection to prevent infinite loops. Text piping resolves $questionId, $respondentName, $surveyTitle at display time. Webhooks use HMAC-SHA256 signatures delivered via QStash.
flowchart LR
subgraph Builder ["Phase 6 Survey Builder"]
QT["19 Question Types"] --> DND["dnd-kit Reorder"]
DND --> SKIP["Skip Logic Engine"]
SKIP --> DFS["DFS Cycle Detection"]
SKIP --> OPS["7 Operators"]
DND --> PIPE["Text Piping"]
PIPE --> VARS["dollar-questionId dollar-respondentName"]
DND --> WH["Webhook HMAC-SHA256"]
WH --> QS["QStash Delivery"]
end
Desc: Seven specialized analytics endpoints transforming raw survey responses into actionable insights - from basic distributions to AI-powered sentiment analysis and statistical significance testing.
Tech: 7 API endpoints under /api/surveys/:id/analytics/*. Sentiment analysis uses ZhiPu GLM-4-Flash with 15s timeout. Funnel tracking uses PageView records to compute drop-off rates per page. NPS calculates promoter/detractor splits. Significance uses chi-squared approximation. All visualized via Recharts 3 and d3-cloud word clouds, cached through TanStack React Query 5.
flowchart TB
subgraph Analytics ["Phase 7 Analytics Engine"]
RAW["Raw Responses"] --> BASE["Base Stats"]
RAW --> SENT["Sentiment via GLM-4-Flash"]
RAW --> FUNNEL["Funnel Drop-off"]
RAW --> CROSS["Crosstab Matrix"]
RAW --> NPS["NPS Score"]
RAW --> SIG["Statistical Significance"]
RAW --> SUMMARY["AI Summary"]
BASE & SENT & FUNNEL & CROSS & NPS & SIG & SUMMARY --> VIZ["Recharts 3 + d3-cloud"]
end
Desc: A full social layer with public feed, comments, likes, follows, friendships, profile portfolios, and a polished developer experience with design system rebrand.
Tech: Public feed with trending sort algorithm. Threaded comment system with parentId for replies, author-only edit/delete. Follow/unfollow system with counter denormalization. Rust/Taupe design rebrand touching design-tokens.css (62 vars) and globals.css (821 LOC with 15 keyframes). Driver.js onboarding flows.
flowchart TB
subgraph Social ["Phase 8-9 Social Network"]
FEED["Public Feed"] --> TREND["Trending Algorithm"]
FEED --> SEARCH["Full-Text Search"]
USER["User Profile"] --> FOLLOW["Follow/Unfollow"]
USER --> FRIENDS["Friendships"]
SURVEY["Survey"] --> COMMENTS["Threaded Comments"]
SURVEY --> LIKES["Toggle Likes"]
SURVEY --> SHARE["QR + Social Share"]
FOLLOW & FRIENDS --> NOTIF["Pusher Notifications"]
end
Desc: Production-grade deployment pipeline with 3 GitHub Actions workflows, 12 Terraform files for AWS infrastructure, and dual deployment paths (Vercel or self-hosted).
Tech: ci.yml runs 5 parallel jobs (install, lint, typecheck, 871 tests, build). deploy.yml handles Vercel preview on PR and production on merge. Terraform provisions VPC, Lambda, API Gateway, CloudFront, S3, Aurora Serverless v2, Route53, ACM, and CloudWatch.
flowchart LR
subgraph CICD ["Phase 10 CI/CD"]
PUSH["Git Push"] --> CI["ci.yml"]
CI --> LINT["ESLint"]
CI --> TSC["TypeScript Check"]
CI --> TEST["871 Vitest"]
LINT & TSC & TEST --> BUILD["Next.js Build"]
BUILD --> DEPLOY{"Deploy Target?"}
DEPLOY -->|Vercel| VCL["Vercel CDN"]
DEPLOY -->|AWS| TF["12 Terraform Files"]
TF --> VPC["VPC + Lambda + Aurora"]
end
Desc: Deep AI integration with ZhiPu GLM-4-Flash for question generation, follow-up suggestions, and survey summarization. Plus cost-aware billing meters and usage analytics.
Tech: ai.ts (208 LOC) wraps 5 GLM-4-Flash functions with SEC-006 prompt injection guards. Billing meter in usage.ts (84 LOC) tracks AI sentiment and funnel view usage with 3/month FREE limits and automatic monthly resets. Usage data exposed through API for dashboard consumption.
flowchart TB
subgraph AI ["Phase 11-12 AI + Billing"]
REQ["User Request"] --> GUARD["SEC-006 Prompt Injection Guard"]
GUARD --> GLM["ZhiPu GLM-4-Flash"]
GLM --> QGEN["Generate Questions"]
GLM --> FOLLOWUP["Follow-Up Suggestions"]
GLM --> SUMM["Survey Summarization"]
GLM --> METER["Usage Meter"]
METER --> PLAN{"Subscription Plan?"}
PLAN -->|FREE| LIMIT["3/month Cap"]
PLAN -->|PRO| UNLIMITED["Unlimited"]
end
Desc: Enterprise-grade RBAC workspaces with Owner/Editor/Viewer roles, survey versioning with snapshot diffs, template marketplace, scheduled reports, GDPR compliance API, and audit logging.
Tech: Workspace-scoped surveys with role-based access control enforced at the API level. SurveyVersion model stores JSON snapshots of entire survey state for rollback. Audit log captures 9 action types across 6 entity types. GDPR API supports data export and deletion requests.
flowchart TB
subgraph Enterprise ["Phase 13-14 Enterprise"]
WS["Workspace"] --> RBAC["RBAC Owner/Editor/Viewer"]
WS --> SURVEYS["Scoped Surveys"]
SURVEYS --> VERSIONS["Version Snapshots"]
VERSIONS --> ROLLBACK["Rollback"]
WS --> TEMPLATES["Template Marketplace"]
WS --> REPORTS["Scheduled Reports"]
WS --> GDPR["GDPR Export/Delete"]
WS --> AUDIT["Audit Log 9 Actions"]
end
Desc: A 50-item refinement backlog addressing code quality, plus a community dashboard with top creators leaderboard, trending categories, featured surveys carousel, and survey forking.
Tech: Backlog items tackled dependency upgrades, dead code removal, component extraction, and performance profiling. Community API aggregates creator stats, trending tags, and featured surveys. Fork endpoint (POST /api/surveys/:id/fork) deep-clones a survey with all questions into the forking user's account.
flowchart TB
subgraph Community ["Phase 15-16 Community"]
DASH["Community Dashboard"] --> LEADERS["Top Creators"]
DASH --> TRENDING["Trending Tags"]
DASH --> FEATURED["Featured Carousel"]
SURVEY["Survey"] --> FORK["Fork/Clone"]
FORK --> DEEP["Deep Clone Questions"]
DEEP --> OWNED["New Owner Copy"]
end
Desc: Real-time messaging with Pusher WebSocket channels, conversation management (1:1 and group), typing indicators, read receipts, and API documentation via Swagger UI.
Tech: Conversation and Message Prisma models with Pusher-driven real-time delivery across 4 channels and 7 events. Typing indicators use Pusher client events with 3s debounce. Read receipts tracked per-message. Swagger UI auto-generated from API route metadata at /api/docs.
flowchart LR
subgraph Messaging ["Phase 17-18 Comms"]
U1["User A"] --> MSG["Send Message"]
MSG --> API["POST /api/messages"]
API --> DB["Store in Neon"]
API --> PUSHER["Pusher Trigger"]
PUSHER --> U2["User B Real-time"]
U1 --> TYPING["Typing Indicator"]
TYPING --> DEBOUNCE["3s Debounce"]
DEBOUNCE --> PUSHER
end
Desc: A comprehensive quality assurance pass ensuring all features integrate correctly - API contract validation, component rendering tests, and integration smoke tests.
Tech: Cross-module integration testing verifying that auth flows, survey CRUD, analytics pipelines, and real-time events work end-to-end. Performance profiling of critical API paths. Error boundary coverage for all top-level page components.
flowchart TB
subgraph QA ["Phase 19 QA"]
UNIT["871 Unit Tests"] --> INTEG["Integration Tests"]
INTEG --> API["API Contract Checks"]
INTEG --> COMP["Component Render Tests"]
INTEG --> E2E["E2E Smoke Tests"]
API & COMP & E2E --> PASS["All Green"]
end
Desc: End-to-end encryption for messages using ECDH key exchange, encrypted key storage, biometric app locks (WebAuthn), device session management, and metadata stripping from media uploads.
Tech: ECDH P-256 key pairs generated client-side via Web Crypto API (crypto.subtle). Public keys stored in User model. Messages encrypted with AES-GCM derived from ECDH shared secret. EncryptedKeyStore model holds wrapped private keys. sharp library strips EXIF/GPS metadata from uploaded images. Device management dashboard allows revoking active sessions.
flowchart TB
subgraph E2E ["Phase 20 Zero-Trust"]
KEYGEN["ECDH P-256 Key Gen"] --> PUB["Public Key to Server"]
KEYGEN --> PRIV["Private Key Encrypted Locally"]
SENDER["Sender"] --> DERIVE["ECDH Shared Secret"]
DERIVE --> AES["AES-GCM Encrypt"]
AES --> WIRE["Encrypted Message"]
WIRE --> RECV["Receiver Decrypts"]
UPLOAD["Media Upload"] --> STRIP["EXIF/GPS Strip via sharp"]
STRIP --> CLEAN["Clean File Stored"]
end
Desc: Voice and video notes with waveform visualization, scheduled messages, offline queuing, threaded replies, message editing (15-minute window), deletion, pinned messages, slash commands (/gif, /poll, /survey), and AI smart reply suggestions.
Tech: useMediaRecorder hook captures audio/video via getUserMedia + MediaRecorder APIs. VoiceRecorder renders live waveform using Web Audio API AnalyserNode. Scheduled messages use isScheduled/sendAt fields with a cron endpoint dispatching via Pusher. useSlashCommands hook parses commands with Giphy API integration. useSmartReplies hook provides contextual suggestions via local NLP pattern matching with optional AI endpoint.
flowchart TB
subgraph RichMsg ["Phase 21 Rich Messaging"]
VOICE["Voice Note"] --> RECORDER["MediaRecorder API"]
RECORDER --> WAVE["AnalyserNode Waveform"]
RECORDER --> PLAY["AudioPlayer 1.5x/2x"]
SCHED["Scheduled Message"] --> QUEUE["status: QUEUED"]
QUEUE --> CRON["Cron Dispatch"]
CRON --> PUSHER["Pusher Deliver"]
MSG["Message"] --> REPLY["Threaded Reply"]
MSG --> EDIT["Edit 15min Window"]
MSG --> DELETE["Soft/Hard Delete"]
MSG --> PIN["Pin/Unpin"]
INPUT["Chat Input"] --> SLASH["Slash Commands"]
SLASH --> GIF["/gif Giphy Search"]
SLASH --> POLL["/poll Creator"]
SLASH --> SURVEY["/survey Embed"]
INPUT --> SMART["AI Smart Replies"]
end
Desc: Chunked file uploads supporting files up to 1GB with resume capability, automatic HEIC-to-WebP conversion, streaming video player with PiP and fullscreen, persistent background audio player, in-app image editor, embedded survey cards, document previews with OG link unfurling, syntax-highlighted code blocks, and masonry album grids.
Tech: useChunkedUpload hook slices files into 5MB chunks with 3-retry exponential backoff and abort support. mediaConvert.ts uses sharp for HEIC/PNG/JPEG to WebP conversion with standard (75% quality, max 1920px) and original (lossless) modes. StreamingVideoPlayer supports PiP via requestPictureInPicture(), playback speed cycling, and circular crop for video notes. BackgroundAudioPlayer uses zustand for cross-navigation persistence. ImageEditor is canvas-based with draw/text tools, 7-color palette, undo stack, and WebP export. CodeBlock uses built-in token regex for keyword/string/comment/number highlighting. AlbumGrid renders adaptive 2-col or 3-col masonry with overflow indicator and click-to-expand lightbox.
flowchart TB
subgraph Media ["Phase 22 Media Engine"]
FILE["Large File"] --> CHUNK["5MB Chunk Slicing"]
CHUNK --> UPLOAD["Sequential Upload + Retry"]
UPLOAD --> ASSEMBLE["Server Assembly"]
ASSEMBLE --> CONVERT["sharp HEIC to WebP"]
VIDEO["Video Message"] --> STREAM["StreamingVideoPlayer"]
STREAM --> PIP["Picture-in-Picture"]
STREAM --> SPEED["1x/1.5x/2x Speed"]
IMG["Image"] --> EDITOR["Canvas Image Editor"]
EDITOR --> DRAW["Draw + Text + Color"]
EDITOR --> EXPORT["WebP Export"]
MULTI["Multiple Images"] --> ALBUM["AlbumGrid Masonry"]
ALBUM --> LIGHTBOX["Click Lightbox"]
CODE["Code Message"] --> SYNTAX["Token Regex Highlighter"]
LINK["URL Message"] --> OG["OG Meta Unfurling"]
DOC["Document"] --> PREVIEW["File Icon + Type Badge"]
end
Desc: Discord-style guild architecture with sub-channels, hierarchical roles using bitmask permissions, approval queues for private guilds, automated toxicity filtering with auto-mute, tamper-proof moderator audit logs, slow mode rate limiting, expiring invite links, community discovery directory, and an XP/reputation leveling system.
Tech: 7 new Prisma models (Guild, Channel, ChannelMessage, GuildMember, GuildRole, ApprovalQueue, AuditLog, InviteLink). Permission system uses a 6-bit bitmask (SEND=1, DELETE=2, BAN=4, MANAGE_CHANNELS=8, MANAGE_ROLES=16, ADMIN=32) with hasPermission() utility. checkToxicity() runs regex patterns with two severity tiers - low severity blocks the message, high severity auto-mutes the user. Slow mode tracks lastMessageAt per member and returns 429 if cooldown hasn't elapsed. Invite links validate expiresAt and maxUses during join flow. XP awarded per action with logarithmic leveling curve: level = floor(sqrt(xp / 50)) + 1.
flowchart TB
subgraph Guild ["Phase 23 Guild Architecture"]
CREATE["Create Guild"] --> CHANNELS["Auto-create general + announcements"]
CREATE --> ROLES["Admin/Mod/Member Roles"]
ROLES --> BITMASK["6-bit Permission Bitmask"]
JOIN["Join Guild"] --> PUBLIC{"Public?"}
PUBLIC -->|Yes| DIRECT["Direct Join"]
PUBLIC -->|No| INVITE{"Invite Code?"}
INVITE -->|Valid| DIRECT
INVITE -->|None| APPROVAL["Approval Queue"]
MSG["Channel Message"] --> TOXIC["Toxicity Filter"]
TOXIC -->|Clean| SLOW{"Slow Mode?"}
SLOW -->|Cooldown OK| SAVE["Save + XP Award"]
SLOW -->|Too Fast| RATE["429 Wait Ns"]
TOXIC -->|High Severity| MUTE["Auto-Mute + Audit Log"]
MOD["Moderator"] --> KICK["Kick"]
MOD --> BAN["Ban"]
MOD --> AUDIT["Tamper-Proof Audit Log"]
end
Desc: Premium micro-interactions including swipe-to-reply on chat bubbles, double-tap-to-like with heart burst particles, spring-physics context menus, Dynamic Island notification toasts, odometer unread counters, trigger-word confetti effects, frosted glass input bar, parallax chat backgrounds, custom wallpapers, rich presence avatars with status dots, and zen/focus mode.
Tech: SwipeToReply uses Framer Motion drag="x" with elastic constraints and directional threshold detection. DoubleTapToLike spawns 5 SVG heart particles with random spread, rotation, and fade-out via Framer Motion. SpringContextMenu uses long-press (500ms) or right-click with spring transition (stiffness: 500, damping: 25). DynamicIslandToasts is a zustand-powered toast queue showing max 3 with spring drop-in and 5s auto-dismiss. Odometer animates per-digit with popLayout spring transitions. useConfettiTrigger fires 60 canvas particles with gravity, drag, and rotation on keywords like "congratulations". chatPreferences.ts is a persisted zustand store managing wallpapers (6 gradient presets), presence status (online/idle/dnd/invisible with PresenceDot component), and zen mode toggles.
flowchart TB
subgraph UX ["Phase 24 Hyper-Visual UX"]
BUBBLE["Chat Bubble"] --> SWIPE["Swipe-to-Reply"]
SWIPE --> DRAG["Framer Motion Drag"]
BUBBLE --> DTAP["Double-Tap to Like"]
DTAP --> HEARTS["5 Heart Burst Particles"]
BUBBLE --> LONG["Long-Press 500ms"]
LONG --> SPRING["Spring Context Menu"]
NOTIF["Incoming DM"] --> ISLAND["Dynamic Island Toast"]
ISLAND --> DROP["Spring Drop-In"]
DROP --> DISMISS["5s Auto-Dismiss"]
UNREAD["Unread Count"] --> ODO["Odometer Rolling Digits"]
TRIGGER["Congratulations"] --> CONFETTI["60 Canvas Particles"]
INPUT["Input Bar"] --> FROST["backdrop-blur-2xl"]
BG["Chat Background"] --> PARALLAX["Scroll Y Offset"]
BG --> WALLPAPER["6 Gradient Presets"]
AVATAR["User Avatar"] --> PRESENCE["Status Dot"]
PRESENCE --> ONLINE["Green Online"]
PRESENCE --> IDLE["Yellow + Moon"]
PRESENCE --> DND["Red DND"]
TOGGLE["Zen Mode"] --> HIDE["Hide Timestamps + Avatars"]
end
Click to expand
1. Requirements You will need node >= 20 and npm. If you are on Windows, run everything inside WSL (Ubuntu recommended). ### 2. Clone & Install ```bash
git clone https://github.com/MrCh0p808/StatWoX.git
cd StatWoX
npm install
### 3. Environment Variablesbash
cp .env.example .env
Required variables (see `.env.example` for full list of 17 variables):env
DATABASE_URL="postgresql://user:pass@host/dbname?sslmode=require"
JWT_SECRET="your_32_char_secure_secret"
NEXT_PUBLIC_APP_URL="http://localhost:8000"
GOOGLE_CLIENT_ID="xxx"
GOOGLE_CLIENT_SECRET="xxx"
LINKEDIN_CLIENT_ID="xxx"
LINKEDIN_CLIENT_SECRET="xxx"
UPSTASH_REDIS_REST_URL="https://..."
UPSTASH_REDIS_REST_TOKEN="..."
PUSHER_APP_ID="xxx"
NEXT_PUBLIC_PUSHER_KEY="xxx"
PUSHER_SECRET="xxx"
NEXT_PUBLIC_PUSHER_CLUSTER="us2"
RESEND_API_KEY="re_xxx"
ZHIPU_API_KEY="xxx"
### 4. Database Setupbash
npx prisma db push
npx prisma generate
npm run db:seed
### 5. Start Development Serverbash
npm run dev
The app will be available at `http://localhost:8000`. ### 6. Run Test Suitebash
npm run test
**871 unit tests** across 34 test files via Vitest 4.
</details>
---
## <span id="20-production-deployment-terraform">20. Production Deployment Terraform</span>
<details>
<summary><b>Click to expand</b></summary>
### Option A - Vercel (Recommended) Automated via `deploy.yml` GitHub Action. PRs get preview deploys, pushes to `main` trigger production deploy + DB migrations. ```bash
bun run deploy # manual staging
bun run deploy:prod # manual production
``` ### Option B - AWS Self-Hosted (12 Terraform Files) ```bash
bun run build
cd infra
terraform init
terraform apply
``` Provisions: VPC (`vpc.tf`), Aurora Serverless v2 (`database.tf`), Lambda (`lambda.tf`), API Gateway (`apigw.tf`), CloudFront (`cloudfront.tf`), S3 (`s3.tf`), Route53 (`route53.tf`), ACM (`acm.tf`), CloudWatch (`cloudwatch.tf`). Variables required in `variables.tf`: `aws_region`, `project`, `db_username`, `db_password`, `jwt_secret`, `google_client_id`, `domain_name` (default: `statwox.ttoxtech.in`).
</details>
---
## <span id="21-api-reference">21. API Reference</span>
REST API with JWT `Authorization: Bearer <token>`. CSRF protection on mutations (`POST/PUT/PATCH/DELETE`). Swagger UI at `/api/docs`. * **Auth (14 sub-routes):** * `POST /api/auth/register` - Zod validated (email + password min 8 + uppercase + number + special) * `POST /api/auth/login` - Email + password * `POST /api/auth/logout` - Invalidate session * `GET /api/auth/me` - Current user profile * `POST /api/auth/refresh` - Rotate refresh token pair * `GET /api/auth/google` - `GET /api/auth/google/callback` - Google OAuth * `GET /api/auth/linkedin` - `GET /api/auth/linkedin/callback` - LinkedIn OAuth * `GET /api/auth/digilocker` - `GET /api/auth/digilocker/callback` - DigiLocker * `POST /api/auth/verify-email`, `GET /api/auth/verify-email/confirm` - Email verification * `POST /api/auth/forgot-password` - `POST /api/auth/reset-password` - Password reset * `PATCH /api/auth/password` - Change password (authenticated) * `POST /api/auth/2fa/setup` - `POST /api/auth/2fa/verify` - TOTP 2FA (otplib + QR) * `POST /api/auth/otp/*` - Phone OTP * **Surveys (CRUD + 14 sub-endpoints):** * `GET|POST /api/surveys` - List / Create (Zod `surveyCreateSchema`) * `GET|PATCH|DELETE /api/surveys/:id` - Read / Update / Soft-delete * `POST /api/surveys/:id/publish|unpublish|close|draft|duplicate` * `GET /api/surveys/:id/export` - CSV/JSON export * `GET /api/surveys/:id/qrcode` - QR code generation * `GET /api/surveys/:id/versions` - Version history * `POST /api/surveys/:id/report` - Content moderation (spam/misleading) * **Responses:** * `POST /api/surveys/:id/respond` - Submit (duplicate prevention, skip-logic, per-type validation, webhook trigger) * `POST /api/surveys/:id/pageview` - Track funnel metrics * **Social:** * `POST /api/surveys/:id/like` - Toggle * `GET|POST /api/surveys/:id/comments` - Threaded (parentId for replies) * **Analytics (7 endpoints):** * `GET /api/surveys/:id/analytics` - Base (time-series, distributions) * `GET .../analytics/sentiment` - GLM-4-Flash scoring * `GET .../analytics/funnel` - PageView drop-off (metered: 3/month FREE) * `GET .../analytics/crosstab` - Cross-tabulation * `GET .../analytics/nps` - Net Promoter Score * `GET .../analytics/significance` - Statistical significance * `GET .../analytics/summary` - AI natural-language summary * **Messaging:** * `GET|POST /api/messages` - List / Send (with Pusher real-time delivery) * `PATCH|DELETE /api/messages/:id` - Edit (15min window) / Delete (soft/hard) * `POST /api/guilds` - Create guild (auto-generates channels + roles) * `GET /api/guilds` - Community discovery directory * `POST /api/guilds/:id/join` - Join (public, invite, or approval queue) * `POST /api/guilds/:id/moderation` - Kick/Ban/Mute/Unmute * `GET /api/guilds/:id/moderation` - Audit log viewer * `POST /api/guilds/:id/invites` - Generate expiring invite link * `POST /api/guilds/channels/messages` - Channel message with automod + XP * **Feed:** `GET /api/feed` - Paginated public surveys (trending algorithms) * **Other:** ai, audit, cron, docs (Swagger), gdpr, health, notifications, pusher (auth), question-bank, templates, upload (presigned + chunked), users, workspaces
---
## <span id="22-contributing-guide">22. Contributing Guide</span>
StatWoX is developed beneath the **CoderWa Protocol**. PRs should address specific isolated waves from the Master Plan. * `feat/*`: New features
* `fix/*`: Bug fixes
* `test/*`: Test coverage expansions (Aim for Vitest coverage increases)
* `refactor/*`: Code quality improvements
* `docs/*`: Documentation updates Before raising a PR, make sure all **871 unit tests** pass using `npm run test`. Requirements for new API routes:
1. Zod validation schemas in `lib/validations.ts`
2. Edge Middleware route classification (public/protected/optional)
3. Vitest test coverage
4. AuditLog entries for state-changing operations
5. Input sanitization via `lib/sanitize.ts`
---
## <span id="23-changelog">23. Changelog</span>
### v3.5.0-RC1 (Phase 30.5 - Vercel Launch & Elite Architecture)
* **Vercel Edge Generation**: Provisioned strict `vercel.json` routing, sanitized Next.js build constraints (removed `output: standalone`), and fully prepared `npm run vercel:deploy` integration.
* **Master DevPlan Expansion (1:1 Fidelity)**: Reconstructed the entire DevPlan timeline (Phases 1 through 30.5). Expunged summarized/fragmented architectures (`devplan1.md`, `devplan2.md`) and solidified them into a unified `MASTER_DEVPLAN_VERBATIM.md` mapped strictly via technical and Le Mans analogies.
* **Project Memory Parity**: Force-synced `STATE.md`, `WORKLOG.md`, `CODERWA_PROTOCOL.md`, and `SYSTEM_MAP.md` tracking ledgers to perfectly match the Vercel Launch state.
* **Clean Repo Policy**: Dynamically updated `.gitignore` to securely sync the isolated Master DevPlan while replacing all obsolete agent fragments with 0-byte tombstones, drastically lowering Git payload sizes.
### v4.0.0 Roadmap (DevPlan 2 - Production Hardening)
* **Phase 25 - Critical Schema & Dependency Fixes**: Removing orphaned schema fields (`stripeProductId`, `customDomain`, `ScheduledReport`). Consolidating duplicate `AuditLog` models to prevent sync crashes. Implementing true Prisma migration history (`migration.sql`) instead of force-syncs. Adding missing environment variables to templates cleanly.
* **Phase 26 - Security Hardening**: Migrating off `localStorage` tokens to pure HttpOnly Cookie-based Authentication. Setting End-to-End Encryption Web Crypto private keys as `extractable: false` to patch memory leak vulnerabilities. Securing Webhooks against SSRF (Server-Side Request Forgery) by blocking private subnets. Hardening standard Content Security Policy.
* **Phase 27 - Scalability & Backend Architecture**: Pre-computing HackerNews gravity algorithms (`trendingScore`) instead of sorting thousands of rows in RAM on every page load. Extracting massive monolithic API routes into strict Controller/Service/Repository layer abstractions. Shifting Analytics logic to join on stable UUIDs instead of volatile string option values.
* **Phase 28 - Frontend Performance & DX**: Complete structural elimination of all `any` types across 50+ files to guarantee absolute type-safety. Standardizing manual asynchronous fetch patterns entirely to TanStack React Query for aggressive caching and automatic retry logic. Lazy-loading heavy libraries (`html2canvas`, `ethers`, `Pyodide`).
* **Phase 29 - Frontend Wiring & UX**: Connecting massive decoupled API systems natively to the GUI. Launching the dedicated `/guilds` network and `/templates` library pages. Connecting the Voice Recorder to the real-time encrypted messaging socket. Triggering AI Smart Replies above keyboards on message receive. Filling "Empty States" across analytics and feeds with beautiful UX illustrations.
* **Phase 30 - Deployment & Testing**: Multi-stage `Dockerfile` standalone builds for zero-downtime AWS scaling. Creating definitive `vercel.json` Cron configurations for Redis buffer flushing and ephemeral message purging. Extensive integration testing for encrypted ECDH routing, E2E Playwright specs for authentication + survey flows, and Lighthouse 90+ Score enforcement.
* **Phase 31 - The 100 Improvements Execution**: Resolving the comprehensive Q1 2026 Codebase Audit. Immediate priorities include fixing the RDS `0.0.0.0/0` exposure, migrating Lambda credentials to AWS Secrets Manager, restricting CORS, enforcing HttpOnly cookies, and patching Web Crypto extractable keys. Long-term goals include eliminating `any` types, implementing DLT caching algorithms, pushing test coverage via CI mutators, and migrating toward complete PWA offline support.
### v3.0.0 (Phases 10-24 - Full Platform Evolution) * **Phase 10 - DevOps**: 3 GitHub Actions workflows (ci.yml, deploy.yml, ci-cd.yml). 12 Terraform files for AWS self-hosting. Dual deployment: Vercel or AWS Lambda.
* **Phase 11 - AI Agent Fusion**: GLM-4-Flash deep integration with SEC-006 prompt injection guards. 5 AI functions: chatCompletion, generateQuestions, analyzeSentiment, generateSummary, generateFollowUp.
* **Phase 12 - Data & Cost**: Billing meter (`usage.ts`, 84 LOC). 3/month FREE cap with automatic monthly resets. Pro/Enterprise unlimited.
* **Phase 13 - Enterprise UI**: RBAC Workspaces (Owner/Editor/Viewer). Survey versioning with JSON snapshots. Template marketplace. Scheduled reports.
* **Phase 14 - AI & Reliability**: GDPR compliance API (data export + deletion). Audit logging: 9 action types, 6 entity types.
* **Phase 15 - Refinement Backlog**: 50-item codebase refinement pass. Dependency upgrades, dead code removal, component extraction.
* **Phase 16 - Community Matrix**: Community dashboard with top creators leaderboard, trending tags, featured surveys carousel. Survey forking (deep clone with all questions).
* **Phase 17 - Secure Comms**: Conversation and Message models. Pusher real-time delivery (4 channels, 7 events). Typing indicators, read receipts.
* **Phase 18 - Advanced Analytics**: Swagger UI API documentation at `/api/docs`. Enhanced analytics pipeline integration.
* **Phase 19 - Build-Ready QA**: Cross-module integration testing. Performance profiling. Error boundary coverage.
* **Phase 20 - Zero-Trust Security**: ECDH P-256 key exchange for E2E encryption. AES-GCM message encryption. `EncryptedKeyStore` model. Media metadata stripping via `sharp`. WebAuthn biometric locks. Device session management.
* **Phase 21 - Rich Messaging**: Voice/video notes (`useMediaRecorder` + Web Audio API waveforms). Scheduled messages with cron dispatch. Threaded replies, edit (15min window), delete (soft/hard), pin. Slash commands (`/gif` Giphy, `/poll`, `/survey`). AI smart replies with pattern-matching fallback.
* **Phase 22 - High-Fi Media**: Chunked uploads (`useChunkedUpload`: 5MB slices, 3-retry, resume). HEIC-to-WebP (`sharp`). `StreamingVideoPlayer` with PiP/fullscreen/speed. `BackgroundAudioPlayer` (zustand, cross-navigation). `ImageEditor` (canvas draw/text/undo). `SurveyCard`, `DocumentPreview` (OG unfurling), `CodeBlock` (token highlighter), `AlbumGrid` (masonry + lightbox).
* **Phase 23 - Community Dynamics**: 7 new Prisma models (Guild, Channel, ChannelMessage, GuildMember, GuildRole, ApprovalQueue, AuditLog, InviteLink). 6-bit bitmask permission system. Automod toxicity filter with auto-mute. Slow mode enforcement. Expiring invite links. Approval queues for private guilds. XP/leveling system with logarithmic curve.
* **Phase 24 - Hyper-Visual UX**: `SwipeToReply` (Framer drag). `DoubleTapToLike` (heart burst). `SpringContextMenu` (500ms long-press, spring physics). `DynamicIslandToasts` (zustand queue, spring drop-in). `Odometer` (rolling digits). `useConfettiTrigger` (60 canvas particles). Frosted glass input bar. Parallax backgrounds. 6 wallpaper presets. `PresenceDot` (online/idle/dnd). Zen mode toggle. ### v2.1.0 (Phases 7-9 -- Social Network, Feed & DX Polish)
* **Design Rebrand**: Swept every page and component from the old blue/cyan palette to a unified Rust/Taupe identity (`#a64b29` primary, `#876654` secondary, `#c06a3a` hover). Touched 9 files: `not-found.tsx`, `forgot-password`, `reset-password`, `Builder.tsx`, `QRCodeShare.tsx`, `ShareButtons.tsx`, `verified-badge.tsx`, `loading.tsx`, `api-docs`.
* **Register Page**: Built the missing `/register` route and `RegisterClientWrapper` so the "Sign up free" link on login actually works. Form matches the login page design with the same ambient light sources and grid overlay.
* **Social Feed (Phase 8)**: Public feed with trending sort, enhanced full-text search with substring fallback, follow/unfollow system, follower/following counts on profile pages.
* **Comment System**: Threaded replies with edit/delete (author-only ownership checks, soft-delete with counter decrement). Full frontend UI with `Pencil`/`Trash2` icons.
* **Profile Portfolio**: Public profile pages showing a user's published surveys, total upvotes, survey count, and follower/following stats.
* **Repo Cleanup**: Removed 820MB of accumulated cruft (`.JugaadBKP/`, `.jugaad_venv/`, `dist/`, `infra/.terraform/`, `infra/lambda.zip`, stale lockfiles, temp test files). Working directory down from 820MB to 5.3MB.
* **TypeScript Fixes**: Resolved all `tsc` errors. Added `collectEmail` to Zod schema, `showTooltip` to `VerifiedBadgeProps`. Zero-error compilation for the first time.
* **Testing**: 871 tests across 30 files, all passing. Zero regressions throughout Phases 7-9. ### v2.0.0 (Phase 6 -- Neuromorphic UI & Full Platform)
* **Design System**: Neuromorphic UI - `design-tokens.css` (62 lines: neon dark palette `#09090b/#121214/#1a1a1e`, Rust primary `#a64b29`, Taupe secondary `#876654`) + `globals.css` (821 lines: 15 keyframe animations, glassmorphism, gradient borders, cyber scan overlay, driver.js onboarding, status badges, chart tooltips, OTP inputs).
* **Framework**: Next.js 16.1.6, React 19.2.3, Zustand 5, TailwindCSS 4, Zod 4, Vitest 4, Framer Motion 12.
* **Auth**: 14 sub-routes - register/login/logout/me/refresh, Google/LinkedIn/DigiLocker OAuth, email verification (Resend), password reset (SHA-256 tokens), 2FA (TOTP via otplib + QR), OTP.
* **Edge Security**: 159-LOC middleware - 14 public routes, CSRF origin/referer validation on mutations, JWT (jose HS256), 6 security headers (CSP, HSTS, X-Frame-Options, X-Content-Type-Options, Referrer-Policy, Permissions-Policy), `x-request-id` tracing.
* **Validation**: 10 isomorphic Zod 4 schemas in `lib/validations.ts` (113 lines) with strong password rules.
* **Database**: Prisma 5.22 - 22 models, 9 enums, 639 schema lines. Added OTP, PasswordResetToken, VerificationToken, Follow, Report, billing fields, fullTextSearch preview.
* **Survey Engine**: 19 question types (runtime `questionTypes.ts`: 294 lines). Skip logic (7 operators + circular DFS detection). Text piping (`$questionId`, `$respondentName`, `$surveyTitle`). Webhook delivery (HMAC-SHA256 via QStash with fetch fallback, 3 events). Custom theming, password protection, i18n, QR codes, conversational mode, conditional thank-you, IP allowlisting.
* **Analytics**: 7 endpoints - base, sentiment (GLM-4-Flash via `ai.ts`: 208 lines), funnel, crosstab, NPS, significance, summary. Recharts 3 + d3-cloud.
* **AI**: ZhiPu GLM-4-Flash (model: `glm-4-flash`) - 4 functions: chatCompletion, generateQuestions (SEC-006 prompt injection guard), analyzeSentiment, generateSummary, generateFollowUp. 15s timeout.
* **Real-time**: Pusher - 4 channels (vey-responses, notifications, messages, presence), 7 events (new-response, update, new-notif, new-msg, typing, online, offline).
* **Social**: Comments (threaded replies), likes, follows, friendships, notifications, public feed, verified badges, content moderation (Report model: spam/inappropriate/misleading - pending/reviewed/dismissed/actioned).
* **Enterprise**: RBAC Workspaces (Owner/Editor/Viewer), audit logging (9 actions, 6 entity types), question bank, survey versioning, template marketplace, scheduled reports, GDPR API.
* **Billing**: FREE/PRO/ENTERPRISE - metered AI sentiment + funnel views (3/month FREE limit, auto-reset monthly).
* **Testing**: 822+ unit tests via Vitest 4 across `src/__tests__/`.
* **CI/CD**: 3 GitHub Actions workflows - `ci.yml` (5 jobs: install/lint/typecheck/test/build), `deploy.yml` (4 jobs: lint/preview/production/migrate), `ci-cd.yml`.
* **Infra**: 12 Terraform `.tf` files in `infra/` (VPC, Lambda, API Gateway, CloudFront, S3, Aurora, Route53, ACM, CloudWatch, variables, outputs, providers). Domain: `statwox.ttoxtech.in`.
* **Components**: 11 modules, 32 shared UI components (Radix).
* **Lib**: 25 utility modules totaling ~1,800 lines. ### v1.1.0 (Phase 3 Execution)
* **Core**: Finalized Next.js App Router codebase conversion.
* **Feature**: 191+ Atomic Unit Tests deployed globally protecting APIs.
* **Security**: Scraped memory-leaks and hardcoded PII disclosures in HTTP Handlers.
* **Feature**: Upcoming Trust Identity System mapped out inside Schema. ### v1.0.0
* **Core**: Initial release.
* **Feature**: Complete Survey Builder UI.
* **Infra**: Full Terraform deployment suite.
