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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Cloudflare Turnstile Integration Implementation Plan
|
| 2 |
+
|
| 3 |
+
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
| 4 |
+
|
| 5 |
+
**Goal:** Mengintegrasikan Cloudflare Turnstile anti-bot protection ke dalam WhatsApp Full Profile Picture (`ppfull`) dengan backend Go di Hugging Face Spaces dan frontend vanilla JS di Vercel.
|
| 6 |
+
|
| 7 |
+
**Architecture:** Backend menyediakan endpoint `GET /config` untuk mendistribusikan `turnstile_site_key` secara dinamis. Frontend merender widget Turnstile (Managed Mode) di atas tombol aksi, kemudian menyertakan `turnstile_token` dalam pesan inisialisasi WebSocket `{ action: "start" }`. Backend memvalidasi token ke Cloudflare Siteverify API sebelum mengalokasikan sesi WhatsApp whatsmeow.
|
| 8 |
+
|
| 9 |
+
**Tech Stack:** Go (Standard Library `net/http`, `encoding/json`), Cloudflare Turnstile REST API, Vanilla JavaScript, HTML5, CSS3, WebSocket (`github.com/coder/websocket`).
|
| 10 |
+
|
| 11 |
+
**Spec:** [docs/superpowers/specs/2026-10-07-cloudflare-turnstile-integration-design.md](file:///c:/Users/Administrator/Documents/PROJECT-GITHUB/ppfull/docs/superpowers/specs/2026-10-07-cloudflare-turnstile-integration-design.md)
|
| 12 |
+
|
| 13 |
+
## Global Constraints
|
| 14 |
+
|
| 15 |
+
- Backend server port default `7860` (Hugging Face Spaces) atau membaca variabel `PORT`.
|
| 16 |
+
- CORS aktif untuk semua origin `*` pada endpoint HTTP `/health`, `/config`, dan WebSocket `/ws`.
|
| 17 |
+
- Dev/Bypass Mode: Jika `TURNSTILE_SECRET_KEY` tidak diatur di environment, backend meloloskan verifikasi dengan peringatan log (tidak memblokir pengujian lokal).
|
| 18 |
+
- Single-use token: Token Turnstile harus segera direset di frontend setelah dikirimkan agar tidak terjadi replay attack.
|
| 19 |
+
|
| 20 |
+
## Review Focus
|
| 21 |
+
|
| 22 |
+
1. Client mengirim `turnstile_token` kosong saat backend mengaktifkan `TURNSTILE_SECRET_KEY` -> Backend menolak dengan error deskriptif dan menutup websocket.
|
| 23 |
+
2. Cloudflare API mengembalikan HTTP error atau network timeout -> Backend mengembalikan error ramah pengguna tanpa panic atau crash.
|
| 24 |
+
3. Hugging Face backend dalam keadaan sleeping / waking up -> Frontend tidak crash saat memuat widget dan menunggu backend online sebelum merender widget.
|
| 25 |
+
4. Token Turnstile kedaluwarsa sebelum user klik "Mulai Hubungkan" -> Callback `expired-callback` mereset token dan tombol kembali terkunci hingga diverifikasi ulang.
|
| 26 |
+
5. Mode dev / pengujian lokal tanpa internet ke Cloudflare -> Backend tetap dapat berjalan mulus tanpa membutuhkan API key Cloudflare.
|
| 27 |
+
|
| 28 |
+
---
|
| 29 |
+
|
| 30 |
+
### Task 1: Backend Turnstile Verification Logic & `/config` Endpoint
|
| 31 |
+
|
| 32 |
+
**Files:**
|
| 33 |
+
- Create: `turnstile_test.go`
|
| 34 |
+
- Modify: `main.go:38-75`
|
| 35 |
+
|
| 36 |
+
**Interfaces:**
|
| 37 |
+
- Produces:
|
| 38 |
+
- `type TurnstileVerifyResponse struct`
|
| 39 |
+
- `func verifyTurnstileToken(secretKey, token, remoteIP string) (bool, error)`
|
| 40 |
+
- `GET /config` handler returning JSON `{"turnstile_enabled": bool, "turnstile_site_key": string}`
|
| 41 |
+
- Updated `WSIncomingMessage` struct with `TurnstileToken string`
|
| 42 |
+
|
| 43 |
+
- [ ] **Step 1: Write failing unit tests for Turnstile verification logic**
|
| 44 |
+
|
| 45 |
+
Create `turnstile_test.go`:
|
| 46 |
+
```go
|
| 47 |
+
package main
|
| 48 |
+
|
| 49 |
+
import (
|
| 50 |
+
"encoding/json"
|
| 51 |
+
"net/http"
|
| 52 |
+
"net/http/httptest"
|
| 53 |
+
"testing"
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
func TestVerifyTurnstileToken_BypassWhenNoSecret(t *testing.T) {
|
| 57 |
+
ok, err := verifyTurnstileToken("", "some-token", "127.0.0.1")
|
| 58 |
+
if err != nil {
|
| 59 |
+
t.Fatalf("expected no error on bypass, got %v", err)
|
| 60 |
+
}
|
| 61 |
+
if !ok {
|
| 62 |
+
t.Fatalf("expected ok=true when secret is empty")
|
| 63 |
+
}
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
func TestVerifyTurnstileToken_FailsOnEmptyTokenWhenSecretSet(t *testing.T) {
|
| 67 |
+
ok, err := verifyTurnstileToken("0x4AAAAAA_secret", "", "127.0.0.1")
|
| 68 |
+
if err == nil {
|
| 69 |
+
t.Fatalf("expected error on empty token when secret is set")
|
| 70 |
+
}
|
| 71 |
+
if ok {
|
| 72 |
+
t.Fatalf("expected ok=false on empty token")
|
| 73 |
+
}
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
func TestConfigEndpoint(t *testing.T) {
|
| 77 |
+
req := httptest.NewRequest("GET", "/config", nil)
|
| 78 |
+
rec := httptest.NewRecorder()
|
| 79 |
+
|
| 80 |
+
mux := http.NewServeMux()
|
| 81 |
+
registerConfigEndpoint(mux)
|
| 82 |
+
mux.ServeHTTP(rec, req)
|
| 83 |
+
|
| 84 |
+
if rec.Code != http.StatusOK {
|
| 85 |
+
t.Fatalf("expected status 200, got %d", rec.Code)
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
var res map[string]interface{}
|
| 89 |
+
if err := json.Unmarshal(rec.Body.Bytes(), &res); err != nil {
|
| 90 |
+
t.Fatalf("invalid json: %v", err)
|
| 91 |
+
}
|
| 92 |
+
if _, exists := res["turnstile_enabled"]; !exists {
|
| 93 |
+
t.Fatalf("expected turnstile_enabled key in response")
|
| 94 |
+
}
|
| 95 |
+
}
|
| 96 |
+
```
|
| 97 |
+
|
| 98 |
+
- [ ] **Step 2: Run test to verify it fails**
|
| 99 |
+
|
| 100 |
+
Run: `go test -v -run "TestVerifyTurnstileToken|TestConfigEndpoint"`
|
| 101 |
+
Expected: FAIL (undefined `verifyTurnstileToken`, undefined `registerConfigEndpoint`).
|
| 102 |
+
|
| 103 |
+
- [ ] **Step 3: Implement `verifyTurnstileToken` and `/config` endpoint in `main.go`**
|
| 104 |
+
|
| 105 |
+
- Add `TurnstileToken` field to `WSIncomingMessage`.
|
| 106 |
+
- Implement `TurnstileVerifyResponse` struct.
|
| 107 |
+
- Implement `verifyTurnstileToken(secretKey, token, remoteIP string) (bool, error)` making a POST request with `url.Values` to `https://challenges.cloudflare.com/turnstile/v0/siteverify` with a 10s timeout client.
|
| 108 |
+
- Implement `registerConfigEndpoint(mux *http.ServeMux)` returning `{ "turnstile_enabled": isEnabled, "turnstile_site_key": siteKey }` with CORS headers enabled.
|
| 109 |
+
- Register `registerConfigEndpoint(mux)` in `main()`.
|
| 110 |
+
|
| 111 |
+
- [ ] **Step 4: Run tests to verify they pass**
|
| 112 |
+
|
| 113 |
+
Run: `go test -v -run "TestVerifyTurnstileToken|TestConfigEndpoint"`
|
| 114 |
+
Expected: PASS.
|
| 115 |
+
|
| 116 |
+
- [ ] **Step 5: Commit**
|
| 117 |
+
|
| 118 |
+
```bash
|
| 119 |
+
git add main.go turnstile_test.go
|
| 120 |
+
git commit -m "feat(backend): add turnstile verification logic and /config endpoint"
|
| 121 |
+
```
|
| 122 |
+
|
| 123 |
+
---
|
| 124 |
+
|
| 125 |
+
### Task 2: Backend WebSocket Turnstile Validation Enforcement
|
| 126 |
+
|
| 127 |
+
**Files:**
|
| 128 |
+
- Modify: `main.go:130-170`
|
| 129 |
+
- Modify: `turnstile_test.go`
|
| 130 |
+
|
| 131 |
+
**Interfaces:**
|
| 132 |
+
- Consumes: `verifyTurnstileToken()` from Task 1, `WSIncomingMessage.TurnstileToken`
|
| 133 |
+
- Produces: Enforcement in `handleWebSocket` before processing image or initializing SQLite/Whatsmeow session.
|
| 134 |
+
|
| 135 |
+
- [ ] **Step 1: Write integration test for WebSocket Turnstile token rejection**
|
| 136 |
+
|
| 137 |
+
Add `TestWebSocket_TurnstileRejection` to `turnstile_test.go` testing that a client without a token or with an invalid token gets an error message when secret key is set.
|
| 138 |
+
|
| 139 |
+
- [ ] **Step 2: Run test to verify it fails**
|
| 140 |
+
|
| 141 |
+
Run: `go test -v -run TestWebSocket_TurnstileRejection`
|
| 142 |
+
Expected: FAIL.
|
| 143 |
+
|
| 144 |
+
- [ ] **Step 3: Implement validation check in `handleWebSocket` in `main.go`**
|
| 145 |
+
|
| 146 |
+
In `handleWebSocket`, right after reading `inMsg`:
|
| 147 |
+
```go
|
| 148 |
+
secretKey := os.Getenv("TURNSTILE_SECRET_KEY")
|
| 149 |
+
if secretKey != "" {
|
| 150 |
+
clientIP := r.Header.Get("CF-Connecting-IP")
|
| 151 |
+
if clientIP == "" {
|
| 152 |
+
clientIP = r.Header.Get("X-Forwarded-For")
|
| 153 |
+
}
|
| 154 |
+
if clientIP == "" {
|
| 155 |
+
clientIP = strings.Split(r.RemoteAddr, ":")[0]
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
+
ok, err := verifyTurnstileToken(secretKey, inMsg.TurnstileToken, clientIP)
|
| 159 |
+
if !ok || err != nil {
|
| 160 |
+
log.Printf("[WS] Turnstile verification failed for %s: %v", r.RemoteAddr, err)
|
| 161 |
+
_ = wsjson.Write(ctx, c, WSOutgoingMessage{
|
| 162 |
+
Type: "error",
|
| 163 |
+
Message: "Verifikasi keamanan Turnstile gagal atau kedaluwarsa. Silakan muat ulang halaman.",
|
| 164 |
+
})
|
| 165 |
+
return
|
| 166 |
+
}
|
| 167 |
+
log.Printf("[WS] Turnstile verification succeeded for %s", r.RemoteAddr)
|
| 168 |
+
}
|
| 169 |
+
```
|
| 170 |
+
|
| 171 |
+
- [ ] **Step 4: Run tests to verify they pass**
|
| 172 |
+
|
| 173 |
+
Run: `go test -v ./...`
|
| 174 |
+
Expected: PASS.
|
| 175 |
+
|
| 176 |
+
- [ ] **Step 5: Commit**
|
| 177 |
+
|
| 178 |
+
```bash
|
| 179 |
+
git add main.go turnstile_test.go
|
| 180 |
+
git commit -m "feat(backend): enforce turnstile verification on websocket initiation"
|
| 181 |
+
```
|
| 182 |
+
|
| 183 |
+
---
|
| 184 |
+
|
| 185 |
+
### Task 3: Frontend Turnstile Widget, CSS & Dynamic Config Integration
|
| 186 |
+
|
| 187 |
+
**Files:**
|
| 188 |
+
- Modify: `frontend/index.html:14-16,160-175`
|
| 189 |
+
- Modify: `frontend/style.css`
|
| 190 |
+
- Modify: `frontend/app.js:25-50,110-150,230-245,300-360`
|
| 191 |
+
|
| 192 |
+
**Interfaces:**
|
| 193 |
+
- Consumes: `GET /config` endpoint from Task 1, Cloudflare Turnstile API JS (`window.turnstile`)
|
| 194 |
+
- Produces: Turnstile widget rendering, token state tracking, token payload transmission in `startProcess()`.
|
| 195 |
+
|
| 196 |
+
- [ ] **Step 1: Update `frontend/index.html`**
|
| 197 |
+
|
| 198 |
+
- Add Cloudflare Turnstile script tag to `<head>`:
|
| 199 |
+
`<script src="https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit" async defer></script>`
|
| 200 |
+
- Add `#turnstile-container-wrapper` inside `#view-upload` above `#btn-start-process`:
|
| 201 |
+
```html
|
| 202 |
+
<div id="turnstile-wrapper" class="turnstile-wrapper hidden">
|
| 203 |
+
<div id="turnstile-widget"></div>
|
| 204 |
+
<div id="turnstile-feedback" class="turnstile-feedback"></div>
|
| 205 |
+
</div>
|
| 206 |
+
```
|
| 207 |
+
|
| 208 |
+
- [ ] **Step 2: Add Turnstile styles in `frontend/style.css`**
|
| 209 |
+
|
| 210 |
+
- Add styles for `.turnstile-wrapper` (centered, glassmorphism border, margin, flex layout, dark-theme alignment).
|
| 211 |
+
- Add styles for `.turnstile-feedback` (subtle helper text, error indicator).
|
| 212 |
+
|
| 213 |
+
- [ ] **Step 3: Implement config fetching & Turnstile lifecycle in `frontend/app.js`**
|
| 214 |
+
|
| 215 |
+
- In `state`: add `turnstileEnabled: false`, `turnstileSiteKey: null`, `turnstileToken: null`, `turnstileWidgetId: null`.
|
| 216 |
+
- Update `updateStartButtonState()`: button is enabled if `state.currentImageBase64` exists AND (`!state.turnstileEnabled` OR `state.turnstileToken` is not null).
|
| 217 |
+
- In `fetchBackendConfig()`: fetch `${base}/config`, read `turnstile_enabled` and `turnstile_site_key`.
|
| 218 |
+
- If `turnstile_enabled` is true:
|
| 219 |
+
- Unhide `#turnstile-wrapper`.
|
| 220 |
+
- Render widget via `turnstile.render('#turnstile-widget', { sitekey, theme: 'dark', callback: (token) => { state.turnstileToken = token; updateStartButtonState(); }, 'expired-callback': () => { state.turnstileToken = null; updateStartButtonState(); turnstile.reset(state.turnstileWidgetId); }, 'error-callback': () => { ... } })`.
|
| 221 |
+
- In `startProcess()`:
|
| 222 |
+
- Add `turnstile_token: state.turnstileToken` to payload sent via WebSocket `onopen`.
|
| 223 |
+
- Reset turnstile token and widget on cancel or error or completion so token cannot be reused.
|
| 224 |
+
|
| 225 |
+
- [ ] **Step 4: Manual/Browser validation & verification**
|
| 226 |
+
|
| 227 |
+
Verify syntax and structure of `frontend/app.js`, `frontend/index.html`, and `frontend/style.css`.
|
| 228 |
+
Run local server test to verify `/config` endpoint responds and static files are served cleanly.
|
| 229 |
+
|
| 230 |
+
- [ ] **Step 5: Commit**
|
| 231 |
+
|
| 232 |
+
```bash
|
| 233 |
+
git add frontend/index.html frontend/style.css frontend/app.js
|
| 234 |
+
git commit -m "feat(frontend): integrate cloudflare turnstile widget and dynamic config"
|
| 235 |
+
```
|
| 236 |
+
|
| 237 |
+
---
|
| 238 |
+
|
| 239 |
+
### Task 4: Environment Configuration & Documentation
|
| 240 |
+
|
| 241 |
+
**Files:**
|
| 242 |
+
- Modify: `.env.example`
|
| 243 |
+
- Modify: `README.md`
|
| 244 |
+
|
| 245 |
+
- [ ] **Step 1: Update `.env.example`**
|
| 246 |
+
|
| 247 |
+
Add configuration variables:
|
| 248 |
+
```env
|
| 249 |
+
PAIRING_NUMBER="628xxxxxxxx"
|
| 250 |
+
PFP_PATH="pfp.jpg"
|
| 251 |
+
PORT="7860"
|
| 252 |
+
TURNSTILE_SITE_KEY=""
|
| 253 |
+
TURNSTILE_SECRET_KEY=""
|
| 254 |
+
```
|
| 255 |
+
|
| 256 |
+
- [ ] **Step 2: Update `README.md`**
|
| 257 |
+
|
| 258 |
+
Add a dedicated section explaining:
|
| 259 |
+
- How to get Cloudflare Turnstile keys (Free on Cloudflare Dashboard).
|
| 260 |
+
- How to set `TURNSTILE_SITE_KEY` and `TURNSTILE_SECRET_KEY` on Hugging Face Spaces (Repository Secrets/Environment Variables).
|
| 261 |
+
- How the Vercel frontend automatically detects and renders the widget without needing redeployment.
|
| 262 |
+
|
| 263 |
+
- [ ] **Step 3: Run full verification build**
|
| 264 |
+
|
| 265 |
+
Run: `go build -v .` and `go test -v ./...`
|
| 266 |
+
Expected: Successful compile and all tests passing.
|
| 267 |
+
|
| 268 |
+
- [ ] **Step 4: Commit**
|
| 269 |
+
|
| 270 |
+
```bash
|
| 271 |
+
git add .env.example README.md
|
| 272 |
+
git commit -m "docs: add cloudflare turnstile configuration guidelines"
|
| 273 |
+
```
|