cdp-edge 2.5.1 → 2.5.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +23 -3
- package/contracts/agent-versions.json +383 -83
- package/extracted-skill/tracking-events-generator/agents/ab-ltv-agent.md +1 -1
- package/extracted-skill/tracking-events-generator/agents/ab-testing-agent.md +1 -1
- package/extracted-skill/tracking-events-generator/agents/attribution-agent.md +18 -18
- package/extracted-skill/tracking-events-generator/agents/bidding-agent.md +1 -1
- package/extracted-skill/tracking-events-generator/agents/bing-agent.md +1 -1
- package/extracted-skill/tracking-events-generator/agents/code-guardian-agent.md +1 -1
- package/extracted-skill/tracking-events-generator/agents/compliance-agent.md +5 -5
- package/extracted-skill/tracking-events-generator/agents/crm-integration-agent.md +10 -10
- package/extracted-skill/tracking-events-generator/agents/dashboard-agent.md +3 -3
- package/extracted-skill/tracking-events-generator/agents/database-agent.md +17 -25
- package/extracted-skill/tracking-events-generator/agents/debug-agent.md +9 -9
- package/extracted-skill/tracking-events-generator/agents/devops-agent.md +18 -1
- package/extracted-skill/tracking-events-generator/agents/domain-setup-agent.md +5 -5
- package/extracted-skill/tracking-events-generator/agents/email-agent.md +3 -3
- package/extracted-skill/tracking-events-generator/agents/fingerprint-agent.md +4 -4
- package/extracted-skill/tracking-events-generator/agents/fraud-detection-agent.md +2 -0
- package/extracted-skill/tracking-events-generator/agents/google-agent.md +2 -2
- package/extracted-skill/tracking-events-generator/agents/intelligence-agent.md +23 -29
- package/extracted-skill/tracking-events-generator/agents/linkedin-agent.md +3 -3
- package/extracted-skill/tracking-events-generator/agents/localization-agent.md +1 -1
- package/extracted-skill/tracking-events-generator/agents/ltv-predictor-agent.md +1 -1
- package/extracted-skill/tracking-events-generator/agents/master-feedback-loop.md +16 -16
- package/extracted-skill/tracking-events-generator/agents/master-orchestrator.md +13 -13
- package/extracted-skill/tracking-events-generator/agents/memory-agent.md +14 -14
- package/extracted-skill/tracking-events-generator/agents/meta-agent.md +2 -2
- package/extracted-skill/tracking-events-generator/agents/ml-clustering-agent.md +9 -9
- package/extracted-skill/tracking-events-generator/agents/page-analyzer.md +1 -0
- package/extracted-skill/tracking-events-generator/agents/performance-agent.md +12 -12
- package/extracted-skill/tracking-events-generator/agents/performance-optimization-agent.md +7 -7
- package/extracted-skill/tracking-events-generator/agents/pinterest-agent.md +6 -6
- package/extracted-skill/tracking-events-generator/agents/premium-tracking-intelligence-agent.md +3 -3
- package/extracted-skill/tracking-events-generator/agents/r2-setup-agent.md +8 -8
- package/extracted-skill/tracking-events-generator/agents/reddit-agent.md +7 -7
- package/extracted-skill/tracking-events-generator/agents/security-enterprise-agent.md +21 -21
- package/extracted-skill/tracking-events-generator/agents/server-tracking.md +15 -15
- package/extracted-skill/tracking-events-generator/agents/spotify-agent.md +6 -6
- package/extracted-skill/tracking-events-generator/agents/tiktok-agent.md +3 -3
- package/extracted-skill/tracking-events-generator/agents/tracking-plan-agent.md +5 -5
- package/extracted-skill/tracking-events-generator/agents/validator-agent.md +9 -9
- package/extracted-skill/tracking-events-generator/agents/webhook-agent.md +4 -4
- package/extracted-skill/tracking-events-generator/agents/whatsapp-agent.md +1 -1
- package/extracted-skill/tracking-events-generator/agents/whatsapp-ctwa-setup-agent.md +3 -3
- package/extracted-skill/tracking-events-generator/agents/youtube-agent.md +9 -9
- package/package.json +10 -10
- package/server-edge-tracker/.client.env +5 -0
- package/server-edge-tracker/modules/dispatch/whatsapp.ts +15 -15
- package/server-edge-tracker/schema-utm.sql +5 -3
- package/server-edge-tracker/wrangler.toml +1 -1
- package/extracted-skill/tracking-events-generator/agents/intelligence-scheduling.md +0 -10
- /package/server-edge-tracker/{deploy-client.js → deploy-client.cjs} +0 -0
|
@@ -36,7 +36,7 @@ Prover **monitoramento contínuo e profissional** da performance do sistema de t
|
|
|
36
36
|
|
|
37
37
|
### 1.1 Latência do Worker
|
|
38
38
|
|
|
39
|
-
```
|
|
39
|
+
```typescript
|
|
40
40
|
// Monitorar tempo de resposta do Cloudflare Worker
|
|
41
41
|
export async function measureWorkerLatency() {
|
|
42
42
|
const sampleSize = 100;
|
|
@@ -115,7 +115,7 @@ function evaluateLatencyPerformance(latencyMetrics) {
|
|
|
115
115
|
|
|
116
116
|
### 1.2 Error Rate das APIs
|
|
117
117
|
|
|
118
|
-
```
|
|
118
|
+
```typescript
|
|
119
119
|
// Monitorar taxa de falhas em todas as APIs
|
|
120
120
|
export async function measureApiErrorRate(env, hours = 24) {
|
|
121
121
|
const platforms = ['meta', 'google', 'tiktok', 'pinterest', 'reddit'];
|
|
@@ -167,7 +167,7 @@ function evaluateErrorRate(errorRate) {
|
|
|
167
167
|
|
|
168
168
|
### 1.3 Throughput do Sistema
|
|
169
169
|
|
|
170
|
-
```
|
|
170
|
+
```typescript
|
|
171
171
|
// Monitorar eventos processados por segundo/minuto
|
|
172
172
|
export async function measureThroughput(env, hours = 24) {
|
|
173
173
|
const now = new Date();
|
|
@@ -237,7 +237,7 @@ function evaluateThroughputTrend(recent, historical) {
|
|
|
237
237
|
|
|
238
238
|
### 1.4 Performance de D1
|
|
239
239
|
|
|
240
|
-
```
|
|
240
|
+
```typescript
|
|
241
241
|
// Monitorar performance do banco de dados D1
|
|
242
242
|
export async function measureD1Performance(env, hours = 24) {
|
|
243
243
|
// Queries lentas
|
|
@@ -331,7 +331,7 @@ function evaluateD1Health(slowQueries, locks, dbSize) {
|
|
|
331
331
|
|
|
332
332
|
### 1.5 Cache Performance (KV)
|
|
333
333
|
|
|
334
|
-
```
|
|
334
|
+
```typescript
|
|
335
335
|
// Monitorar eficiência do cache KV
|
|
336
336
|
export async function measureCachePerformance(env, hours = 24) {
|
|
337
337
|
// Cache hits e misses
|
|
@@ -549,7 +549,7 @@ alerts:
|
|
|
549
549
|
|
|
550
550
|
### Implementação com Server-Sent Events (SSE)
|
|
551
551
|
|
|
552
|
-
```
|
|
552
|
+
```typescript
|
|
553
553
|
// Endpoint SSE para atualizações em tempo real do dashboard
|
|
554
554
|
export async function handleMonitoringStream(request, env) {
|
|
555
555
|
const headers = {
|
|
@@ -856,7 +856,7 @@ cpu_ms = 50 # Aumentar de 10ms para 50ms
|
|
|
856
856
|
**Problema:** Queries repetidas ao D1 degradam performance.
|
|
857
857
|
|
|
858
858
|
**Solução:**
|
|
859
|
-
```
|
|
859
|
+
```typescript
|
|
860
860
|
// Cache de métricas globais por 1 hora
|
|
861
861
|
const cacheKey = `metrics:global:${getHourBucket()}`;
|
|
862
862
|
const cached = await env.GEO_CACHE.get(cacheKey);
|
|
@@ -881,7 +881,7 @@ return metrics;
|
|
|
881
881
|
**Problema:** Processar eventos um por um é ineficiente.
|
|
882
882
|
|
|
883
883
|
**Solução:**
|
|
884
|
-
```
|
|
884
|
+
```typescript
|
|
885
885
|
// Agrupar eventos em batches de 10
|
|
886
886
|
const eventBatches = [];
|
|
887
887
|
for (let i = 0; i < events.length; i += 10) {
|
|
@@ -950,7 +950,7 @@ WHERE e.created_at > datetime('now', '-1 day')
|
|
|
950
950
|
**Problema:** Enviar eventos muito rápido causa 429 errors.
|
|
951
951
|
|
|
952
952
|
**Solução:**
|
|
953
|
-
```
|
|
953
|
+
```typescript
|
|
954
954
|
// Rate limiting com token bucket algorithm
|
|
955
955
|
const RATE_LIMITS = {
|
|
956
956
|
meta: { tokens: 200, refill_rate: 10 }, // 200 req/min, recarrega 10/min
|
|
@@ -985,7 +985,7 @@ async function consumeToken(platform, env) {
|
|
|
985
985
|
**Problema:** Perda de eventos durante rate limits.
|
|
986
986
|
|
|
987
987
|
**Solução:**
|
|
988
|
-
```
|
|
988
|
+
```typescript
|
|
989
989
|
// Cloudflare Queue para eventos bloqueados
|
|
990
990
|
export async function queueEventForRetry(event, platform, reason) {
|
|
991
991
|
await QUEUE.send('cdp-edge-events', {
|
|
@@ -1018,7 +1018,7 @@ setInterval(async () => {
|
|
|
1018
1018
|
**Problema:** TTL muito baixo causa cache misses frequentes.
|
|
1019
1019
|
|
|
1020
1020
|
**Solução:**
|
|
1021
|
-
```
|
|
1021
|
+
```typescript
|
|
1022
1022
|
// TTLs otimizados por tipo de dado
|
|
1023
1023
|
const CACHE_TTL = {
|
|
1024
1024
|
metrics_global: 3600, // 1 hora para métricas globais
|
|
@@ -1038,7 +1038,7 @@ const CACHE_TTL = {
|
|
|
1038
1038
|
**Problema:** Cache desatualizado causa dados incorretos.
|
|
1039
1039
|
|
|
1040
1040
|
**Solução:**
|
|
1041
|
-
```
|
|
1041
|
+
```typescript
|
|
1042
1042
|
// Invalidar cache quando dados mudarem
|
|
1043
1043
|
async function invalidateCacheOnChange(eventType, env) {
|
|
1044
1044
|
const patterns = {
|
|
@@ -75,7 +75,7 @@ Agente especializado em otimização de performance para o sistema CDP Edge (Clo
|
|
|
75
75
|
|
|
76
76
|
### L1: Memory Cache (Request-Scoped)
|
|
77
77
|
|
|
78
|
-
```
|
|
78
|
+
```typescript
|
|
79
79
|
/**
|
|
80
80
|
* L1 Memory Cache - In-request cache with automatic expiration
|
|
81
81
|
*/
|
|
@@ -163,7 +163,7 @@ let l1Cache = new L1Cache();
|
|
|
163
163
|
|
|
164
164
|
### L2: KV Cache (Global Edge Cache)
|
|
165
165
|
|
|
166
|
-
```
|
|
166
|
+
```typescript
|
|
167
167
|
/**
|
|
168
168
|
* L2 KV Cache - Global distributed cache with automatic invalidation
|
|
169
169
|
*/
|
|
@@ -314,7 +314,7 @@ let l2Cache = null;
|
|
|
314
314
|
|
|
315
315
|
### Cache Strategy Implementation
|
|
316
316
|
|
|
317
|
-
```
|
|
317
|
+
```typescript
|
|
318
318
|
/**
|
|
319
319
|
* Multi-Layer Cache Manager
|
|
320
320
|
* Orchestrates L1 and L2 caches with fallback logic
|
|
@@ -485,7 +485,7 @@ CREATE INDEX IF NOT EXISTS idx_channel_performance_updated
|
|
|
485
485
|
|
|
486
486
|
### Query Optimization Patterns
|
|
487
487
|
|
|
488
|
-
```
|
|
488
|
+
```typescript
|
|
489
489
|
/**
|
|
490
490
|
* Optimized Query Builder for D1
|
|
491
491
|
*/
|
|
@@ -676,7 +676,7 @@ let queryOptimizer = null;
|
|
|
676
676
|
|
|
677
677
|
### Batch Processing for Attribution
|
|
678
678
|
|
|
679
|
-
```
|
|
679
|
+
```typescript
|
|
680
680
|
/**
|
|
681
681
|
* Batch Attribution Processor
|
|
682
682
|
* Processes multiple attributions in parallel with batching
|
|
@@ -938,7 +938,7 @@ let batchProcessor = null;
|
|
|
938
938
|
|
|
939
939
|
### Performance Monitoring
|
|
940
940
|
|
|
941
|
-
```
|
|
941
|
+
```typescript
|
|
942
942
|
/**
|
|
943
943
|
* Latency Profiler
|
|
944
944
|
* Monitors and tracks performance metrics
|
|
@@ -1209,7 +1209,7 @@ let latencyProfiler = new LatencyProfiler();
|
|
|
1209
1209
|
|
|
1210
1210
|
### Worker API Endpoints
|
|
1211
1211
|
|
|
1212
|
-
```
|
|
1212
|
+
```typescript
|
|
1213
1213
|
/**
|
|
1214
1214
|
* Performance Monitoring Endpoints
|
|
1215
1215
|
*/
|
|
@@ -34,7 +34,7 @@ Buscar: "Pinterest", "pintrk", "pin_id", "Pinterest Conversions API", "PINTEREST
|
|
|
34
34
|
|
|
35
35
|
### PASSO 0 obrigatório — Ler Versões de API (api-versions.json)
|
|
36
36
|
|
|
37
|
-
```
|
|
37
|
+
```typescript
|
|
38
38
|
// Ler versões do arquivo centralizado
|
|
39
39
|
const apiVersions = await readJSON('contracts/api-versions.json');
|
|
40
40
|
const pinterestVersion = apiVersions.pinterest;
|
|
@@ -86,7 +86,7 @@ if (isDeprecated) {
|
|
|
86
86
|
|
|
87
87
|
**Ler do template:** `models/pinterest/tag-template.js`
|
|
88
88
|
|
|
89
|
-
```
|
|
89
|
+
```typescript
|
|
90
90
|
import { PINTEREST_TAG_TEMPLATE } from '../models/pinterest/tag-template.js';
|
|
91
91
|
|
|
92
92
|
// Substituir placeholders
|
|
@@ -193,7 +193,7 @@ Seu código gerado será incorporado pelo **Browser Tracking Agent** e **Server
|
|
|
193
193
|
[Função de inicialização + pintrk('load') + pintrk('page')]
|
|
194
194
|
|
|
195
195
|
### PINTEREST_CONVERSIONS_API_FUNCTION
|
|
196
|
-
[função sendPinterestApi() para o
|
|
196
|
+
[função sendPinterestApi() para o index.ts]
|
|
197
197
|
|
|
198
198
|
### PINTEREST_HEAD_TAGS
|
|
199
199
|
[tags <script> e <noscript> para inserir no <head>]
|
|
@@ -205,7 +205,7 @@ Seu código gerado será incorporado pelo **Browser Tracking Agent** e **Server
|
|
|
205
205
|
[Referência ao models/pinterest/event-mappings.json]
|
|
206
206
|
```
|
|
207
207
|
|
|
208
|
-
O Master Orchestrator usará esses blocos para injetar no `tracking.js` e `
|
|
208
|
+
O Master Orchestrator usará esses blocos para injetar no `tracking.js` e `index.ts` via Write/Edit.
|
|
209
209
|
|
|
210
210
|
---
|
|
211
211
|
|
|
@@ -254,7 +254,7 @@ wrangler secret put PINTEREST_AD_ACCOUNT_ID --name server-edge-tracker
|
|
|
254
254
|
Quando o Master Orchestrator solicitar código do Pinterest Agent:
|
|
255
255
|
|
|
256
256
|
1. **Ler versões da API:**
|
|
257
|
-
```
|
|
257
|
+
```typescript
|
|
258
258
|
const apiVersions = await readJSON('contracts/api-versions.json');
|
|
259
259
|
const pinterestVersion = apiVersions.pinterest.conversions_api.current; // "v5"
|
|
260
260
|
```
|
|
@@ -302,7 +302,7 @@ Quando o Master Orchestrator solicitar código do Pinterest Agent:
|
|
|
302
302
|
{
|
|
303
303
|
"blocos_gerados": {
|
|
304
304
|
"PINTEREST_BROWSER_SNIPPET": "pintrk('load') + pintrk('page') + eventos",
|
|
305
|
-
"PINTEREST_CONVERSIONS_API_FUNCTION": "sendPinterestApi() para
|
|
305
|
+
"PINTEREST_CONVERSIONS_API_FUNCTION": "sendPinterestApi() para index.ts",
|
|
306
306
|
"PINTEREST_HEAD_TAGS": "<script> + <noscript> para <head>",
|
|
307
307
|
"PINTEREST_CSP_DOMAINS": ["ct.pinterest.com", "log.pinterest.com"]
|
|
308
308
|
},
|
package/extracted-skill/tracking-events-generator/agents/premium-tracking-intelligence-agent.md
CHANGED
|
@@ -711,10 +711,10 @@ const browserTracking = {
|
|
|
711
711
|
};
|
|
712
712
|
```
|
|
713
713
|
|
|
714
|
-
### O que roda no Servidor (Cloudflare Worker)
|
|
714
|
+
### O que roda no Servidor (Cloudflare Worker — TypeScript)
|
|
715
715
|
|
|
716
|
-
```
|
|
717
|
-
// Server Tracking - Processamento e despacho para plataformas
|
|
716
|
+
```typescript
|
|
717
|
+
// Server Tracking - Processamento e despacho para plataformas (index.ts)
|
|
718
718
|
const serverTracking = {
|
|
719
719
|
// 1. Receber evento do browser
|
|
720
720
|
handleEvent: async (eventData, env, ctx) => {
|
|
@@ -111,13 +111,13 @@ bucket_name = "cdp-edge-logs"
|
|
|
111
111
|
|
|
112
112
|
---
|
|
113
113
|
|
|
114
|
-
## Fase 4 — Ativar saveAuditLog() no
|
|
114
|
+
## Fase 4 — Ativar saveAuditLog() no index.ts
|
|
115
115
|
|
|
116
|
-
O
|
|
116
|
+
O index.ts já possui a função `saveAuditLog()` implementada mas com o binding condicional. Após descomentar o binding, ela passa a salvar automaticamente.
|
|
117
117
|
|
|
118
|
-
### Verificar a função no
|
|
118
|
+
### Verificar a função no index.ts:
|
|
119
119
|
|
|
120
|
-
```
|
|
120
|
+
```typescript
|
|
121
121
|
// Buscar por: saveAuditLog ou AUDIT_LOGS
|
|
122
122
|
async function saveAuditLog(env, eventId, eventType, payload, platforms) {
|
|
123
123
|
if (!env.AUDIT_LOGS) return; // Skip se R2 não configurado (graceful degradation)
|
|
@@ -139,9 +139,9 @@ async function saveAuditLog(env, eventId, eventType, payload, platforms) {
|
|
|
139
139
|
}
|
|
140
140
|
```
|
|
141
141
|
|
|
142
|
-
Se a função não existir ainda, adicionar ao
|
|
142
|
+
Se a função não existir ainda, adicionar ao index.ts (seção de funções utilitárias):
|
|
143
143
|
|
|
144
|
-
```
|
|
144
|
+
```typescript
|
|
145
145
|
// ── R2 Audit Log ─────────────────────────────────────────────────────────────
|
|
146
146
|
async function saveAuditLog(env, eventId, eventType, payload, platforms) {
|
|
147
147
|
if (!env.AUDIT_LOGS) return;
|
|
@@ -161,7 +161,7 @@ async function saveAuditLog(env, eventId, eventType, payload, platforms) {
|
|
|
161
161
|
|
|
162
162
|
Adicionar ao `Promise.allSettled` no endpoint `/track` (dentro de `ctx.waitUntil`):
|
|
163
163
|
|
|
164
|
-
```
|
|
164
|
+
```typescript
|
|
165
165
|
// Adicionar como última entrada no allSettled:
|
|
166
166
|
saveAuditLog(env, eventId, eventType, payload, ['meta', 'ga4', 'tiktok']),
|
|
167
167
|
```
|
|
@@ -226,7 +226,7 @@ R2 Dashboard
|
|
|
226
226
|
[ ] R2 habilitado no Cloudflare Dashboard
|
|
227
227
|
[ ] Bucket cdp-edge-logs criado
|
|
228
228
|
[ ] wrangler.toml: [[r2_buckets]] descomentado
|
|
229
|
-
[ ]
|
|
229
|
+
[ ] index.ts: saveAuditLog() implementada
|
|
230
230
|
[ ] wrangler deploy executado sem erros
|
|
231
231
|
[ ] Evento de teste disparado
|
|
232
232
|
[ ] Objeto .json visível no R2 Dashboard
|
|
@@ -36,7 +36,7 @@ Buscar: "Reddit", "reddit pixel", "rdt", "Reddit Conversions API"
|
|
|
36
36
|
|
|
37
37
|
### PASSO 0 obrigatório — Ler Versões de API (api-versions.json)
|
|
38
38
|
|
|
39
|
-
```
|
|
39
|
+
```typescript
|
|
40
40
|
// Ler versões do arquivo centralizado
|
|
41
41
|
const apiVersions = await readJSON('contracts/api-versions.json');
|
|
42
42
|
const redditVersion = apiVersions.reddit;
|
|
@@ -86,7 +86,7 @@ if (isDeprecated) {
|
|
|
86
86
|
|
|
87
87
|
**Ler do template:** `models/reddit/pixel-template.js`
|
|
88
88
|
|
|
89
|
-
```
|
|
89
|
+
```typescript
|
|
90
90
|
import { REDDIT_PIXEL_TEMPLATE } from '../models/reddit/pixel-template.js';
|
|
91
91
|
|
|
92
92
|
// Substituir placeholders
|
|
@@ -152,7 +152,7 @@ function reinitRedditWithUserData(userData) {
|
|
|
152
152
|
|
|
153
153
|
**Ler do template:** `models/reddit/conversions-api-template.js`
|
|
154
154
|
|
|
155
|
-
```
|
|
155
|
+
```typescript
|
|
156
156
|
// Reutilizar funções do template
|
|
157
157
|
import {
|
|
158
158
|
trackRedditLead,
|
|
@@ -240,13 +240,13 @@ Seu código gerado (Reddit Pixel browser + Conversions API server) será incorpo
|
|
|
240
240
|
[rdt('init') + rdt('track', 'PageVisit') + funções de evento browser]
|
|
241
241
|
|
|
242
242
|
### REDDIT_CONVERSIONS_FUNCTION
|
|
243
|
-
[função sendRedditApi() para o
|
|
243
|
+
[função sendRedditApi() para o index.ts]
|
|
244
244
|
|
|
245
245
|
### REDDIT_HEAD_TAGS
|
|
246
246
|
[tag <script> para inserir no <head>]
|
|
247
247
|
```
|
|
248
248
|
|
|
249
|
-
O Master Orchestrator usará esses blocos para injetar no `tracking.js` e `
|
|
249
|
+
O Master Orchestrator usará esses blocos para injetar no `tracking.js` e `index.ts` via Write/Edit.
|
|
250
250
|
|
|
251
251
|
---
|
|
252
252
|
|
|
@@ -255,7 +255,7 @@ O Master Orchestrator usará esses blocos para injetar no `tracking.js` e `worke
|
|
|
255
255
|
Quando o Master Orchestrator solicitar código do Reddit Agent:
|
|
256
256
|
|
|
257
257
|
1. **Ler versões da API:**
|
|
258
|
-
```
|
|
258
|
+
```typescript
|
|
259
259
|
const apiVersions = await readJSON('contracts/api-versions.json');
|
|
260
260
|
const redditVersion = apiVersions.reddit.conversions_api.current; // "v2.0"
|
|
261
261
|
```
|
|
@@ -305,7 +305,7 @@ Quando o Master Orchestrator solicitar código do Reddit Agent:
|
|
|
305
305
|
{
|
|
306
306
|
"blocos_gerados": {
|
|
307
307
|
"REDDIT_BROWSER_SNIPPET": "rdt('init') + rdt('track', 'PageVisit') + eventos",
|
|
308
|
-
"REDDIT_CONVERSIONS_FUNCTION": "sendRedditApi() para
|
|
308
|
+
"REDDIT_CONVERSIONS_FUNCTION": "sendRedditApi() para index.ts",
|
|
309
309
|
"REDDIT_HEAD_TAGS": "<script> para <head>"
|
|
310
310
|
},
|
|
311
311
|
"versao_api": "v2.0",
|
|
@@ -43,7 +43,7 @@ Browser (Cliente) Worker (Server-Side) APIs (Meta/Google/TikT
|
|
|
43
43
|
|
|
44
44
|
### 1.1 Token Bucket Algorithm
|
|
45
45
|
|
|
46
|
-
```
|
|
46
|
+
```typescript
|
|
47
47
|
// Rate limiting com token bucket
|
|
48
48
|
const RATE_LIMIT_CONFIG = {
|
|
49
49
|
// Limites por IP
|
|
@@ -127,7 +127,7 @@ const rateLimiters = {
|
|
|
127
127
|
|
|
128
128
|
### 1.2 Rate Limiting Middleware
|
|
129
129
|
|
|
130
|
-
```
|
|
130
|
+
```typescript
|
|
131
131
|
// Middleware de rate limiting
|
|
132
132
|
export async function applyRateLimiting(request, env) {
|
|
133
133
|
const ip = request.headers.get('CF-Connecting-IP') || 'unknown';
|
|
@@ -260,7 +260,7 @@ export async function applyRateLimiting(request, env) {
|
|
|
260
260
|
|
|
261
261
|
### 1.3 Response Headers de Rate Limiting
|
|
262
262
|
|
|
263
|
-
```
|
|
263
|
+
```typescript
|
|
264
264
|
// Headers de resposta com informações de rate limiting
|
|
265
265
|
export function getRateLimitHeaders(checkResult) {
|
|
266
266
|
const headers = {
|
|
@@ -285,7 +285,7 @@ export function getRateLimitHeaders(checkResult) {
|
|
|
285
285
|
|
|
286
286
|
### 2.1 Blacklist e Whitelist de IPs
|
|
287
287
|
|
|
288
|
-
```
|
|
288
|
+
```typescript
|
|
289
289
|
// Configuração de IP blocking
|
|
290
290
|
const IP_BLOCKING_CONFIG = {
|
|
291
291
|
// Blacklist: IPs explicitamente bloqueados
|
|
@@ -396,7 +396,7 @@ CREATE INDEX IF NOT EXISTS idx_ip_violations_blocked ON ip_violations(blocked);
|
|
|
396
396
|
|
|
397
397
|
### 2.3 IP Blocking Middleware
|
|
398
398
|
|
|
399
|
-
```
|
|
399
|
+
```typescript
|
|
400
400
|
// Middleware de IP blocking
|
|
401
401
|
export async function checkIPBlocking(request, env) {
|
|
402
402
|
const ip = request.headers.get('CF-Connecting-IP') || 'unknown';
|
|
@@ -621,7 +621,7 @@ async function blockIPAutomatically(ip, reason, count, env) {
|
|
|
621
621
|
|
|
622
622
|
### 3.1 Schema Validation (Joi)
|
|
623
623
|
|
|
624
|
-
```
|
|
624
|
+
```typescript
|
|
625
625
|
// Joi schema validation (via npm package)
|
|
626
626
|
import Joi from 'joi';
|
|
627
627
|
|
|
@@ -740,7 +740,7 @@ export async function validateEvent(eventData, eventName) {
|
|
|
740
740
|
|
|
741
741
|
### 3.2 Sanitização de Dados (Anti-XSS, Anti-Injection)
|
|
742
742
|
|
|
743
|
-
```
|
|
743
|
+
```typescript
|
|
744
744
|
// Sanitização de strings (anti-XSS)
|
|
745
745
|
export function sanitizeString(input) {
|
|
746
746
|
if (!input || typeof input !== 'string') {
|
|
@@ -929,7 +929,7 @@ export function sanitizePayload(eventData, eventName) {
|
|
|
929
929
|
|
|
930
930
|
CSRF é relevante nos **endpoints de webhook** (Hotmart, Kiwify, Ticto) onde um atacante pode forjar requisições. A proteção é HMAC-SHA256 por assinatura — cada plataforma assina o payload com um secret compartilhado.
|
|
931
931
|
|
|
932
|
-
```
|
|
932
|
+
```typescript
|
|
933
933
|
/**
|
|
934
934
|
* Verificação CSRF via HMAC-SHA256 para webhooks de plataformas de pagamento.
|
|
935
935
|
* Cada plataforma tem seu próprio header e algoritmo.
|
|
@@ -1026,7 +1026,7 @@ function timingSafeEqual(a, b) {
|
|
|
1026
1026
|
|
|
1027
1027
|
### 3.4 Middleware de Validação e Sanitização
|
|
1028
1028
|
|
|
1029
|
-
```
|
|
1029
|
+
```typescript
|
|
1030
1030
|
// Middleware de segurança completo
|
|
1031
1031
|
export async function applySecurityMiddleware(request, env) {
|
|
1032
1032
|
const ip = request.headers.get('CF-Connecting-IP') || 'unknown';
|
|
@@ -1148,7 +1148,7 @@ export async function applySecurityMiddleware(request, env) {
|
|
|
1148
1148
|
|
|
1149
1149
|
### 4.1 Configuração de Encryption
|
|
1150
1150
|
|
|
1151
|
-
```
|
|
1151
|
+
```typescript
|
|
1152
1152
|
// Configuração de encryption
|
|
1153
1153
|
const ENCRYPTION_CONFIG = {
|
|
1154
1154
|
// Algoritmos de hash (para enviar às plataformas)
|
|
@@ -1186,7 +1186,7 @@ const ENCRYPTION_CONFIG = {
|
|
|
1186
1186
|
|
|
1187
1187
|
### 4.2 Hashing Functions (SHA256 - Web Crypto API)
|
|
1188
1188
|
|
|
1189
|
-
```
|
|
1189
|
+
```typescript
|
|
1190
1190
|
// Hashing de email
|
|
1191
1191
|
export async function hashEmail(email) {
|
|
1192
1192
|
if (!email) return null;
|
|
@@ -1303,7 +1303,7 @@ export async function hashCEP(cep) {
|
|
|
1303
1303
|
|
|
1304
1304
|
### 4.3 Encryption Functions (AES-256-GCM)
|
|
1305
1305
|
|
|
1306
|
-
```
|
|
1306
|
+
```typescript
|
|
1307
1307
|
// Encriptação de dados sensíveis
|
|
1308
1308
|
const encryptionKeys = new Map();
|
|
1309
1309
|
|
|
@@ -1447,7 +1447,7 @@ CREATE INDEX IF NOT EXISTS idx_audit_blocked ON audit_logs(blocked);
|
|
|
1447
1447
|
|
|
1448
1448
|
### 5.2 Tipos de Audit Log
|
|
1449
1449
|
|
|
1450
|
-
```
|
|
1450
|
+
```typescript
|
|
1451
1451
|
// Tipos de log de segurança
|
|
1452
1452
|
const AUDIT_LOG_TYPES = {
|
|
1453
1453
|
// Rate Limiting
|
|
@@ -1498,7 +1498,7 @@ const SEVERITY_LEVELS = {
|
|
|
1498
1498
|
|
|
1499
1499
|
### 5.3 Funções de Audit Logging
|
|
1500
1500
|
|
|
1501
|
-
```
|
|
1501
|
+
```typescript
|
|
1502
1502
|
// Log de evento de segurança
|
|
1503
1503
|
export async function logSecurityEvent(eventData, env) {
|
|
1504
1504
|
const {
|
|
@@ -1620,7 +1620,7 @@ export async function queryAuditLogs(filters = {}, env) {
|
|
|
1620
1620
|
|
|
1621
1621
|
### 6.1 Endpoint: `/api/security/rate-limit-status`
|
|
1622
1622
|
|
|
1623
|
-
```
|
|
1623
|
+
```typescript
|
|
1624
1624
|
export async function getRateLimitStatus(request, env) {
|
|
1625
1625
|
const ip = request.headers.get('CF-Connecting-IP') || 'unknown';
|
|
1626
1626
|
|
|
@@ -1660,7 +1660,7 @@ export async function getRateLimitStatus(request, env) {
|
|
|
1660
1660
|
|
|
1661
1661
|
### 6.2 Endpoint: `/api/security/ip-status`
|
|
1662
1662
|
|
|
1663
|
-
```
|
|
1663
|
+
```typescript
|
|
1664
1664
|
export async function getIPStatus(request, env) {
|
|
1665
1665
|
const ip = request.headers.get('CF-Connecting-IP') || 'unknown';
|
|
1666
1666
|
|
|
@@ -1696,7 +1696,7 @@ export async function getIPStatus(request, env) {
|
|
|
1696
1696
|
|
|
1697
1697
|
### 6.3 Endpoint: `/api/security/audit-logs`
|
|
1698
1698
|
|
|
1699
|
-
```
|
|
1699
|
+
```typescript
|
|
1700
1700
|
export async function getAuditLogs(request, env) {
|
|
1701
1701
|
const url = new URL(request.url);
|
|
1702
1702
|
const filters = {
|
|
@@ -1729,10 +1729,10 @@ export async function getAuditLogs(request, env) {
|
|
|
1729
1729
|
|
|
1730
1730
|
## 🎯 FORMATO DE SAÍDA
|
|
1731
1731
|
|
|
1732
|
-
### DELIVERABLE 1: `security-middleware.
|
|
1732
|
+
### DELIVERABLE 1: `modules/security-middleware.ts`
|
|
1733
1733
|
|
|
1734
|
-
```
|
|
1735
|
-
// security-middleware.
|
|
1734
|
+
```typescript
|
|
1735
|
+
// modules/security-middleware.ts - Middleware de segurança completo
|
|
1736
1736
|
export {
|
|
1737
1737
|
applyRateLimiting,
|
|
1738
1738
|
checkIPBlocking,
|
|
@@ -1765,7 +1765,7 @@ CREATE TABLE IF NOT EXISTS audit_logs (...);
|
|
|
1765
1765
|
|
|
1766
1766
|
### DELIVERABLE 3: `security-config.js`
|
|
1767
1767
|
|
|
1768
|
-
```
|
|
1768
|
+
```typescript
|
|
1769
1769
|
// security-config.js - Configuração de segurança
|
|
1770
1770
|
export const RATE_LIMIT_CONFIG = { ... };
|
|
1771
1771
|
export const IP_BLOCKING_CONFIG = { ... };
|
|
@@ -12,7 +12,7 @@ Ao ser ativado, você sempre gera os seguintes arquivos:
|
|
|
12
12
|
|---|---|
|
|
13
13
|
| `wrangler.toml` | Configuração completa do Worker com todos os bindings |
|
|
14
14
|
| `schema.sql` | Schema D1 completo: eventos, identity_graph, leads, behavioral_events |
|
|
15
|
-
| `
|
|
15
|
+
| `index.ts` | O Worker principal com lógica de processamento e engagement scoring server-side |
|
|
16
16
|
| `DEPLOY.md` | Guia passo a passo de deploy do zero ao funcionando |
|
|
17
17
|
|
|
18
18
|
---
|
|
@@ -56,7 +56,7 @@ Cloudflare Edge (Worker)
|
|
|
56
56
|
|
|
57
57
|
```toml
|
|
58
58
|
name = "cdp-edge-worker"
|
|
59
|
-
main = "
|
|
59
|
+
main = "index.ts"
|
|
60
60
|
compatibility_date = "2025-01-01"
|
|
61
61
|
compatibility_flags = ["nodejs_compat"]
|
|
62
62
|
|
|
@@ -213,7 +213,7 @@ CREATE INDEX IF NOT EXISTS idx_behavioral_events_engagement ON behavioral_events
|
|
|
213
213
|
|
|
214
214
|
## 📄 WORKER.JS (TEMPLATE COMPLETO)
|
|
215
215
|
|
|
216
|
-
```
|
|
216
|
+
```typescript
|
|
217
217
|
/**
|
|
218
218
|
* CDPEDGE CLOUDFLARE WORKER - Quantum Tier
|
|
219
219
|
*/
|
|
@@ -690,7 +690,7 @@ O engagement scoring no servidor é mais preciso que no browser porque tem acess
|
|
|
690
690
|
|
|
691
691
|
### Cálculo por Componente
|
|
692
692
|
|
|
693
|
-
```
|
|
693
|
+
```typescript
|
|
694
694
|
// 1. Visit Score (25%)
|
|
695
695
|
function calculateVisitScore(visitorContext) {
|
|
696
696
|
const visitCount = visitorContext.visit_count || 1;
|
|
@@ -757,7 +757,7 @@ const finalScore = (
|
|
|
757
757
|
### Integração com Plataformas
|
|
758
758
|
|
|
759
759
|
**Meta CAPI v22.0:**
|
|
760
|
-
```
|
|
760
|
+
```typescript
|
|
761
761
|
custom_data: {
|
|
762
762
|
engagement_score: engagementScore.server_engagement_score,
|
|
763
763
|
intention_level: engagementScore.final_intention_level,
|
|
@@ -772,7 +772,7 @@ custom_data: {
|
|
|
772
772
|
```
|
|
773
773
|
|
|
774
774
|
**Google GA4 Measurement Protocol:**
|
|
775
|
-
```
|
|
775
|
+
```typescript
|
|
776
776
|
custom_params: {
|
|
777
777
|
engagement_score: engagementScore.server_engagement_score,
|
|
778
778
|
intention_level: engagementScore.final_intention_level,
|
|
@@ -782,7 +782,7 @@ custom_params: {
|
|
|
782
782
|
```
|
|
783
783
|
|
|
784
784
|
**TikTok Events API v1.3:**
|
|
785
|
-
```
|
|
785
|
+
```typescript
|
|
786
786
|
context: {
|
|
787
787
|
user: {
|
|
788
788
|
engagement_score: engagementScore.server_engagement_score,
|
|
@@ -821,7 +821,7 @@ context: {
|
|
|
821
821
|
- SameSite=Lax para balance entre segurança e funcionalidade
|
|
822
822
|
|
|
823
823
|
**3. Response Headers Anti-Blocking:**
|
|
824
|
-
```
|
|
824
|
+
```typescript
|
|
825
825
|
const corsHeaders = {
|
|
826
826
|
'Access-Control-Allow-Origin': '*',
|
|
827
827
|
'Access-Control-Allow-Methods': 'POST, OPTIONS',
|
|
@@ -883,7 +883,7 @@ Tentativa 3 (Cloudflare Queue - 15 minutos)
|
|
|
883
883
|
|
|
884
884
|
Toda função de dispatch (Meta, Google, TikTok) DEVE ter try/catch com gravação:
|
|
885
885
|
|
|
886
|
-
```
|
|
886
|
+
```typescript
|
|
887
887
|
// Exemplo para dispatchMetaCapi com escalonamento
|
|
888
888
|
async function dispatchMetaCapi(body, env, visitor, heatScore, clientIP, userAgent, cf, retryCount = 0) {
|
|
889
889
|
if (!env.META_ACCESS_TOKEN || !body.pixel_id) {
|
|
@@ -967,7 +967,7 @@ CREATE INDEX IF NOT EXISTS idx_retry_scheduled ON retry_queue(scheduled_at, stat
|
|
|
967
967
|
|
|
968
968
|
### PASSO 3 — Funções de Log de Sucesso/Falha
|
|
969
969
|
|
|
970
|
-
```
|
|
970
|
+
```typescript
|
|
971
971
|
// Log de sucesso
|
|
972
972
|
async function logEventSuccess(DB, platform, eventId) {
|
|
973
973
|
if (!DB) return;
|
|
@@ -1033,7 +1033,7 @@ async function enqueueRetry(queue, retryData) {
|
|
|
1033
1033
|
|
|
1034
1034
|
Após 3 falhas consecutivas, disparar alerta para o administrador:
|
|
1035
1035
|
|
|
1036
|
-
```
|
|
1036
|
+
```typescript
|
|
1037
1037
|
// Função de alerta integrada com WhatsApp Agent
|
|
1038
1038
|
async function dispatchAlert(platform, eventId, errorMessage) {
|
|
1039
1039
|
const alertMessage = `
|
|
@@ -1098,9 +1098,9 @@ max_batch_timeout = 60
|
|
|
1098
1098
|
cron = "* * * * *" # A cada minuto
|
|
1099
1099
|
```
|
|
1100
1100
|
|
|
1101
|
-
E no `
|
|
1101
|
+
E no `index.ts`, adicionar handler de queue:
|
|
1102
1102
|
|
|
1103
|
-
```
|
|
1103
|
+
```typescript
|
|
1104
1104
|
// Handler de Queue (retries)
|
|
1105
1105
|
export async function queue(batch, env) {
|
|
1106
1106
|
for (const message of batch.messages) {
|
|
@@ -1150,7 +1150,7 @@ export async function queue(batch, env) {
|
|
|
1150
1150
|
|
|
1151
1151
|
- Gerar `wrangler.toml` completo com bindings D1, KV, R2, Queues e Cron Triggers
|
|
1152
1152
|
- Gerar `schema.sql` com todas as tabelas: `events_log`, `identity_graph`, `leads`, `behavioral_events`, `webhook_events`, `user_profiles`
|
|
1153
|
-
- Gerar `
|
|
1153
|
+
- Gerar `index.ts` principal com endpoint `/track` (recebe eventos do browser)
|
|
1154
1154
|
- Implementar Identity Graph sync, Engagement Scoring server-side e First-Party Cookie (`_cdp_uid`)
|
|
1155
1155
|
- Implementar Anti-Blocking: CORS same-domain, headers limpos, sem keywords bloqueáveis
|
|
1156
1156
|
- Implementar sistema de retry com Cloudflare Queues (3-Tier: imediato → 5min → 15min → 45min)
|
|
@@ -1163,7 +1163,7 @@ export async function queue(batch, env) {
|
|
|
1163
1163
|
"arquivos_gerados": [
|
|
1164
1164
|
"wrangler.toml",
|
|
1165
1165
|
"schema.sql",
|
|
1166
|
-
"
|
|
1166
|
+
"index.ts",
|
|
1167
1167
|
"DEPLOY.md"
|
|
1168
1168
|
],
|
|
1169
1169
|
"endpoints": {
|
|
@@ -35,7 +35,7 @@ Database: Cloudflare D1 (Persistência)
|
|
|
35
35
|
- Gera `event_id` para deduplicação com server-side
|
|
36
36
|
|
|
37
37
|
### 2. Server Tracking (Spotify Conversions API)
|
|
38
|
-
- `spotify
|
|
38
|
+
- `modules/dispatch/spotify.ts` — Payloads para API de conversões Spotify
|
|
39
39
|
- Envia eventos para Conversions API com deduplicação
|
|
40
40
|
- Usa `crypto.subtle.digest('SHA-256')` para PII (email, phone)
|
|
41
41
|
|
|
@@ -48,7 +48,7 @@ Database: Cloudflare D1 (Persistência)
|
|
|
48
48
|
| Arquivo | Descrição |
|
|
49
49
|
|---------|-----------|
|
|
50
50
|
| `spotify-pixel.js` | Spotify Pixel SDK (Browser) |
|
|
51
|
-
| `spotify
|
|
51
|
+
| `modules/dispatch/spotify.ts` | Spotify Conversions API Payloads (Server — TypeScript) |
|
|
52
52
|
|
|
53
53
|
---
|
|
54
54
|
|
|
@@ -219,12 +219,12 @@ Spotify Ads suporta Advanced Matching para melhorar a qualidade do sinal:
|
|
|
219
219
|
|
|
220
220
|
## 💻 O QUE VOCÊ GERA (SERVER)
|
|
221
221
|
|
|
222
|
-
### `spotify
|
|
222
|
+
### `modules/dispatch/spotify.ts`
|
|
223
223
|
|
|
224
|
-
```
|
|
224
|
+
```typescript
|
|
225
225
|
/**
|
|
226
226
|
* Spotify Conversions API - Server-Side Tracking
|
|
227
|
-
* CDP Edge Quantum Tier - Cloudflare Worker
|
|
227
|
+
* CDP Edge Quantum Tier - Cloudflare Worker (TypeScript)
|
|
228
228
|
*/
|
|
229
229
|
|
|
230
230
|
/**
|
|
@@ -349,7 +349,7 @@ Ao final, gere um relatório JSON:
|
|
|
349
349
|
"fix": "Adicionar comentário explicando integração"
|
|
350
350
|
},
|
|
351
351
|
{
|
|
352
|
-
"file": "spotify
|
|
352
|
+
"file": "modules/dispatch/spotify.ts",
|
|
353
353
|
"issue": "Descrição",
|
|
354
354
|
"fix": "Adicionar retry logic com Promise.allSettled"
|
|
355
355
|
}
|