web-agent-bridge 3.2.0 → 3.3.0

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.
Files changed (202) hide show
  1. package/LICENSE +72 -72
  2. package/README.ar.md +1286 -1152
  3. package/README.md +1764 -1635
  4. package/bin/agent-runner.js +474 -474
  5. package/bin/cli.js +237 -138
  6. package/bin/wab.js +80 -80
  7. package/examples/bidi-agent.js +119 -119
  8. package/examples/cross-site-agent.js +91 -91
  9. package/examples/mcp-agent.js +94 -94
  10. package/examples/next-app-router/README.md +44 -44
  11. package/examples/puppeteer-agent.js +108 -108
  12. package/examples/saas-dashboard/README.md +55 -55
  13. package/examples/shopify-hydrogen/README.md +74 -74
  14. package/examples/vision-agent.js +171 -171
  15. package/examples/wordpress-elementor/README.md +77 -77
  16. package/package.json +16 -3
  17. package/public/.well-known/agent-tools.json +180 -180
  18. package/public/.well-known/ai-assets.json +59 -59
  19. package/public/.well-known/security.txt +8 -0
  20. package/public/agent-workspace.html +349 -349
  21. package/public/ai.html +198 -198
  22. package/public/api.html +413 -412
  23. package/public/browser.html +486 -486
  24. package/public/commander-dashboard.html +243 -243
  25. package/public/cookies.html +210 -210
  26. package/public/css/agent-workspace.css +1713 -1713
  27. package/public/css/premium.css +317 -317
  28. package/public/css/styles.css +1235 -1235
  29. package/public/dashboard.html +706 -706
  30. package/public/dns.html +507 -0
  31. package/public/docs.html +587 -587
  32. package/public/feed.xml +89 -89
  33. package/public/growth.html +463 -463
  34. package/public/index.html +1070 -982
  35. package/public/integrations.html +556 -0
  36. package/public/js/agent-workspace.js +1740 -1740
  37. package/public/js/auth-nav.js +31 -31
  38. package/public/js/auth-redirect.js +12 -12
  39. package/public/js/cookie-consent.js +56 -56
  40. package/public/js/wab-demo-page.js +721 -721
  41. package/public/js/ws-client.js +74 -74
  42. package/public/llms-full.txt +360 -360
  43. package/public/llms.txt +125 -125
  44. package/public/login.html +85 -85
  45. package/public/mesh-dashboard.html +328 -328
  46. package/public/openapi.json +580 -580
  47. package/public/phone-shield.html +281 -0
  48. package/public/premium-dashboard.html +2489 -2489
  49. package/public/premium.html +793 -793
  50. package/public/privacy.html +297 -297
  51. package/public/register.html +105 -105
  52. package/public/robots.txt +87 -87
  53. package/public/script/wab-consent.d.ts +36 -36
  54. package/public/script/wab-consent.js +104 -104
  55. package/public/script/wab-schema.js +131 -131
  56. package/public/script/wab.d.ts +108 -108
  57. package/public/script/wab.min.js +580 -580
  58. package/public/security.txt +8 -0
  59. package/public/terms.html +256 -256
  60. package/script/ai-agent-bridge.js +1754 -1754
  61. package/sdk/README.md +99 -99
  62. package/sdk/agent-mesh.js +449 -449
  63. package/sdk/commander.js +262 -262
  64. package/sdk/index.d.ts +464 -464
  65. package/sdk/index.js +12 -1
  66. package/sdk/multi-agent.js +318 -318
  67. package/sdk/package.json +1 -1
  68. package/sdk/safety-shield.js +219 -0
  69. package/sdk/schema-discovery.js +83 -83
  70. package/server/adapters/index.js +520 -520
  71. package/server/config/plans.js +367 -367
  72. package/server/config/secrets.js +102 -102
  73. package/server/control-plane/index.js +301 -301
  74. package/server/data-plane/index.js +354 -354
  75. package/server/index.js +531 -427
  76. package/server/llm/index.js +404 -404
  77. package/server/middleware/adminAuth.js +35 -35
  78. package/server/middleware/auth.js +50 -50
  79. package/server/middleware/featureGate.js +88 -88
  80. package/server/middleware/rateLimits.js +100 -100
  81. package/server/middleware/sensitiveAction.js +157 -0
  82. package/server/migrations/001_add_analytics_indexes.sql +7 -7
  83. package/server/migrations/002_premium_features.sql +418 -418
  84. package/server/migrations/003_ads_integer_cents.sql +33 -33
  85. package/server/migrations/004_agent_os.sql +158 -158
  86. package/server/migrations/005_marketplace_metering.sql +126 -126
  87. package/server/models/adapters/index.js +33 -33
  88. package/server/models/adapters/mysql.js +183 -183
  89. package/server/models/adapters/postgresql.js +172 -172
  90. package/server/models/adapters/sqlite.js +7 -7
  91. package/server/models/db.js +681 -681
  92. package/server/observability/failure-analysis.js +337 -337
  93. package/server/observability/index.js +394 -394
  94. package/server/protocol/capabilities.js +223 -223
  95. package/server/protocol/index.js +243 -243
  96. package/server/protocol/schema.js +584 -584
  97. package/server/registry/certification.js +271 -271
  98. package/server/registry/index.js +326 -326
  99. package/server/routes/admin-premium.js +671 -671
  100. package/server/routes/admin.js +261 -261
  101. package/server/routes/ads.js +130 -130
  102. package/server/routes/agent-workspace.js +540 -540
  103. package/server/routes/api.js +150 -150
  104. package/server/routes/auth.js +71 -71
  105. package/server/routes/billing.js +45 -45
  106. package/server/routes/commander.js +316 -316
  107. package/server/routes/demo-showcase.js +332 -332
  108. package/server/routes/demo-store.js +154 -0
  109. package/server/routes/discovery.js +417 -417
  110. package/server/routes/gateway.js +173 -157
  111. package/server/routes/license.js +251 -240
  112. package/server/routes/mesh.js +469 -469
  113. package/server/routes/noscript.js +543 -543
  114. package/server/routes/premium-v2.js +686 -686
  115. package/server/routes/premium.js +724 -724
  116. package/server/routes/runtime.js +2148 -2147
  117. package/server/routes/sovereign.js +465 -385
  118. package/server/routes/universal.js +200 -185
  119. package/server/routes/wab-api.js +850 -501
  120. package/server/runtime/container-worker.js +111 -111
  121. package/server/runtime/container.js +448 -448
  122. package/server/runtime/distributed-worker.js +362 -362
  123. package/server/runtime/event-bus.js +210 -210
  124. package/server/runtime/index.js +253 -253
  125. package/server/runtime/queue.js +599 -599
  126. package/server/runtime/replay.js +666 -666
  127. package/server/runtime/sandbox.js +266 -266
  128. package/server/runtime/scheduler.js +534 -534
  129. package/server/runtime/session-engine.js +293 -293
  130. package/server/runtime/state-manager.js +188 -188
  131. package/server/security/cross-site-redactor.js +196 -0
  132. package/server/security/dry-run.js +180 -0
  133. package/server/security/human-gate-rate-limit.js +147 -0
  134. package/server/security/human-gate-transports.js +178 -0
  135. package/server/security/human-gate.js +281 -0
  136. package/server/security/index.js +368 -368
  137. package/server/security/intent-engine.js +245 -0
  138. package/server/security/reward-guard.js +171 -0
  139. package/server/security/rollback-store.js +239 -0
  140. package/server/security/token-scope.js +404 -0
  141. package/server/security/url-policy.js +139 -0
  142. package/server/services/agent-chat.js +506 -506
  143. package/server/services/agent-learning.js +601 -575
  144. package/server/services/agent-memory.js +625 -625
  145. package/server/services/agent-mesh.js +555 -539
  146. package/server/services/agent-symphony.js +717 -717
  147. package/server/services/agent-tasks.js +1807 -1807
  148. package/server/services/api-key-engine.js +292 -261
  149. package/server/services/cluster.js +894 -894
  150. package/server/services/commander.js +738 -738
  151. package/server/services/edge-compute.js +440 -440
  152. package/server/services/email.js +204 -204
  153. package/server/services/hosted-runtime.js +205 -205
  154. package/server/services/lfd.js +635 -635
  155. package/server/services/local-ai.js +389 -389
  156. package/server/services/marketplace.js +270 -270
  157. package/server/services/metering.js +182 -182
  158. package/server/services/modules/affiliate-intelligence.js +93 -93
  159. package/server/services/modules/agent-firewall.js +90 -90
  160. package/server/services/modules/bounty.js +89 -89
  161. package/server/services/modules/collective-bargaining.js +92 -92
  162. package/server/services/modules/dark-pattern.js +66 -66
  163. package/server/services/modules/gov-intelligence.js +45 -45
  164. package/server/services/modules/neural.js +55 -55
  165. package/server/services/modules/notary.js +49 -49
  166. package/server/services/modules/price-time-machine.js +86 -86
  167. package/server/services/modules/protocol.js +104 -104
  168. package/server/services/negotiation.js +439 -439
  169. package/server/services/plugins.js +771 -771
  170. package/server/services/price-intelligence.js +566 -566
  171. package/server/services/price-shield.js +1137 -1137
  172. package/server/services/reputation.js +465 -465
  173. package/server/services/search-engine.js +357 -357
  174. package/server/services/security.js +513 -513
  175. package/server/services/self-healing.js +843 -843
  176. package/server/services/sovereign-shield.js +542 -0
  177. package/server/services/stripe.js +192 -192
  178. package/server/services/swarm.js +788 -788
  179. package/server/services/universal-scraper.js +662 -661
  180. package/server/services/verification.js +481 -481
  181. package/server/services/vision.js +1163 -1163
  182. package/server/utils/cache.js +125 -125
  183. package/server/utils/migrate.js +81 -81
  184. package/server/utils/safe-fetch.js +228 -0
  185. package/server/utils/secureFields.js +50 -50
  186. package/server/ws.js +161 -161
  187. package/templates/artisan-marketplace.yaml +104 -104
  188. package/templates/book-price-scout.yaml +98 -98
  189. package/templates/electronics-price-tracker.yaml +108 -108
  190. package/templates/flight-deal-hunter.yaml +113 -113
  191. package/templates/freelancer-direct.yaml +116 -116
  192. package/templates/grocery-price-compare.yaml +93 -93
  193. package/templates/hotel-direct-booking.yaml +113 -113
  194. package/templates/local-services.yaml +98 -98
  195. package/templates/olive-oil-tunisia.yaml +88 -88
  196. package/templates/organic-farm-fresh.yaml +101 -101
  197. package/templates/restaurant-direct.yaml +97 -97
  198. package/public/score.html +0 -263
  199. package/server/migrations/006_growth_suite.sql +0 -138
  200. package/server/routes/growth.js +0 -962
  201. package/server/services/fairness-engine.js +0 -409
  202. package/server/services/fairness.js +0 -420
@@ -1,962 +0,0 @@
1
- /**
2
- * WAB Growth Suite v2.5 — Full API Routes
3
- *
4
- * Real, functional endpoints for all 8 modules:
5
- * 1. Shield / Widget → POST /scan
6
- * 2. AI Safety Layer → POST /safety/check
7
- * 3. WAB Score → GET /score/:domain, POST /score/batch
8
- * 4. Trust Layer → GET /trust/verify/:domain, POST /trust/register
9
- * 5. Bounty Network → POST /bounty/submit, GET /bounty/status/:id, ...
10
- * 6. Data Marketplace → GET /data/datasets, POST /data/purchase, ...
11
- * 7. Email Protection → POST /email/scan
12
- * 8. Affiliate Intel → GET /affiliate/analyze/:network, POST /affiliate/detect-fraud
13
- */
14
-
15
- const express = require('express');
16
- const router = express.Router();
17
- const crypto = require('crypto');
18
- const { db } = require('../models/db');
19
- const { authenticateToken } = require('../middleware/auth');
20
- const { calculateNeutralityScore } = require('../services/fairness');
21
-
22
- // ── Helpers ───────────────────────────────────────────────────────────
23
- function uuid() { return crypto.randomUUID ? crypto.randomUUID() : require('uuid').v4(); }
24
-
25
- function jsonParse(str, fallback = {}) {
26
- try { return JSON.parse(str); } catch { return fallback; }
27
- }
28
-
29
- const GRADES = [
30
- { min: 95, grade: 'A+', label: 'Exceptional', color: '#22c55e' },
31
- { min: 90, grade: 'A', label: 'Excellent', color: '#4ade80' },
32
- { min: 85, grade: 'A-', label: 'Very Good', color: '#86efac' },
33
- { min: 80, grade: 'B+', label: 'Good', color: '#a3e635' },
34
- { min: 75, grade: 'B', label: 'Above Average', color: '#facc15' },
35
- { min: 70, grade: 'B-', label: 'Satisfactory', color: '#fbbf24' },
36
- { min: 65, grade: 'C+', label: 'Below Average', color: '#f59e0b' },
37
- { min: 60, grade: 'C', label: 'Fair', color: '#fb923c' },
38
- { min: 55, grade: 'C-', label: 'Poor', color: '#f97316' },
39
- { min: 50, grade: 'D', label: 'Very Poor', color: '#ef4444' },
40
- { min: 0, grade: 'F', label: 'Failing', color: '#dc2626' },
41
- ];
42
-
43
- function getGrade(score) {
44
- for (const g of GRADES) {
45
- if (score >= g.min) return g;
46
- }
47
- return GRADES[GRADES.length - 1];
48
- }
49
-
50
- // Threat pattern database (real patterns, not placeholders)
51
- const THREAT_PATTERNS = [
52
- { pattern: /paypal|paypa[l1]/i, type: 'phishing', weight: 95 },
53
- { pattern: /login.*verify|verify.*account/i, type: 'credential_phishing', weight: 90 },
54
- { pattern: /free.*prize|winner.*claim/i, type: 'advance_fee_scam', weight: 85 },
55
- { pattern: /bit\.ly|tinyurl|t\.co/i, type: 'url_shortener', weight: 30 },
56
- { pattern: /\.xyz$|\.tk$|\.ml$|\.ga$|\.cf$/i, type: 'suspicious_tld', weight: 40 },
57
- { pattern: /crypto.*invest|bitcoin.*double/i, type: 'crypto_scam', weight: 92 },
58
- { pattern: /pharmacy|v[i1]agra|c[i1]al[i1]s/i, type: 'pharma_spam', weight: 70 },
59
- { pattern: /download.*free|crack.*software/i, type: 'malware_lure', weight: 80 },
60
- { pattern: /apple.*id.*locked|icloud.*suspend/i, type: 'phishing', weight: 93 },
61
- { pattern: /bank.*transfer|wire.*urgent/i, type: 'bec_fraud', weight: 88 },
62
- ];
63
-
64
- const PHISHING_EMAIL_PATTERNS = [
65
- { pattern: /urgent|immediately|act now|expire/i, label: 'Urgency language' },
66
- { pattern: /verify your (account|identity|email)/i, label: 'Account verification request' },
67
- { pattern: /you have won|congratulations.*winner/i, label: 'Prize/lottery claim' },
68
- { pattern: /click here|click below/i, label: 'Suspicious call-to-action' },
69
- { pattern: /account.*(suspend|terminat|restrict|locked)/i, label: 'Account threat' },
70
- { pattern: /confirm your (details|identity|payment)/i, label: 'Confirmation request' },
71
- { pattern: /update.*(billing|payment|card) info/i, label: 'Info update request' },
72
- { pattern: /\$[\d,]+.*charged|transaction.*\$[\d,]+/i, label: 'Fake charge notification' },
73
- ];
74
-
75
- const KNOWN_NETWORKS = {
76
- amazon_associates: { name: 'Amazon Associates', avg_commission: 4, avg_payout_days: 60, cookie_days: 1, trust_base: 82 },
77
- shareasale: { name: 'ShareASale', avg_commission: 8, avg_payout_days: 20, cookie_days: 30, trust_base: 78 },
78
- cj_affiliate: { name: 'CJ Affiliate', avg_commission: 7, avg_payout_days: 30, cookie_days: 30, trust_base: 75 },
79
- clickbank: { name: 'ClickBank', avg_commission: 50, avg_payout_days: 45, cookie_days: 60, trust_base: 61 },
80
- rakuten: { name: 'Rakuten', avg_commission: 5, avg_payout_days: 30, cookie_days: 30, trust_base: 73 },
81
- impact: { name: 'Impact', avg_commission: 6, avg_payout_days: 30, cookie_days: 30, trust_base: 80 },
82
- awin: { name: 'Awin', avg_commission: 5, avg_payout_days: 30, cookie_days: 30, trust_base: 76 },
83
- partnerstack: { name: 'PartnerStack', avg_commission: 20, avg_payout_days: 15, cookie_days: 90, trust_base: 85 },
84
- };
85
-
86
- const FRAUD_PATTERNS = {
87
- cookie_stuffing: { severity: 'CRITICAL', label: 'Cookie Stuffing', description: 'Unauthorized cookie injection to steal attribution' },
88
- click_fraud: { severity: 'CRITICAL', label: 'Click Fraud', description: 'Automated fake clicks inflating metrics' },
89
- commission_shaving: { severity: 'HIGH', label: 'Commission Shaving', description: 'Network reduces valid commission amounts' },
90
- late_attribution: { severity: 'HIGH', label: 'Late Attribution', description: 'Delayed tracking causes missed valid sales' },
91
- low_cvr: { severity: 'MEDIUM', label: 'Low Conversion Rate', description: 'CVR significantly below industry benchmark' },
92
- payment_delays: { severity: 'MEDIUM', label: 'Payment Delays', description: 'Payouts consistently later than promised' },
93
- tos_changes: { severity: 'MEDIUM', label: 'TOS Changes', description: 'Frequent or sudden commission/term changes' },
94
- };
95
-
96
- const REWARD_TIERS = {
97
- CRITICAL: { credits: 50, label: 'Critical Threat' },
98
- HIGH: { credits: 25, label: 'High Risk' },
99
- MEDIUM: { credits: 10, label: 'Medium Risk' },
100
- LOW: { credits: 5, label: 'Low Risk' },
101
- DUPLICATE: { credits: 1, label: 'Duplicate' },
102
- INVALID: { credits: 0, label: 'Invalid' },
103
- };
104
-
105
-
106
- // ═══════════════════════════════════════════════════════════════════════
107
- // 1. SHIELD / WIDGET — URL Threat Scanning
108
- // ═══════════════════════════════════════════════════════════════════════
109
-
110
- router.post('/scan', (req, res) => {
111
- const { url } = req.body;
112
- if (!url) return res.status(400).json({ error: 'url is required' });
113
-
114
- let parsedUrl;
115
- try { parsedUrl = new URL(url); } catch {
116
- return res.status(400).json({ error: 'Invalid URL format' });
117
- }
118
-
119
- const hostname = parsedUrl.hostname.toLowerCase();
120
- let riskScore = 0;
121
- const threats = [];
122
-
123
- // Run pattern analysis
124
- for (const tp of THREAT_PATTERNS) {
125
- if (tp.pattern.test(url) || tp.pattern.test(hostname)) {
126
- riskScore = Math.max(riskScore, tp.weight);
127
- threats.push({ type: tp.type, confidence: tp.weight });
128
- }
129
- }
130
-
131
- // Heuristics
132
- if (hostname.length > 40) { riskScore = Math.max(riskScore, 45); threats.push({ type: 'long_domain', confidence: 45 }); }
133
- if ((hostname.match(/\./g) || []).length > 4) { riskScore = Math.max(riskScore, 50); threats.push({ type: 'excessive_subdomains', confidence: 50 }); }
134
- if (/\d{4,}/.test(hostname)) { riskScore = Math.max(riskScore, 35); threats.push({ type: 'numeric_domain', confidence: 35 }); }
135
- if (parsedUrl.protocol === 'http:') { riskScore = Math.max(riskScore, 20); threats.push({ type: 'no_ssl', confidence: 20 }); }
136
-
137
- // Check DB for known domains
138
- const cached = db.prepare('SELECT * FROM wab_scores WHERE domain = ?').get(hostname);
139
- if (cached && cached.security_score !== undefined) {
140
- const secRisk = 100 - cached.security_score;
141
- if (secRisk > riskScore) riskScore = secRisk;
142
- }
143
-
144
- let status = 'SAFE';
145
- if (riskScore >= 80) status = 'CRITICAL';
146
- else if (riskScore >= 50) status = 'WARNING';
147
- else if (riskScore >= 25) status = 'NOTICE';
148
-
149
- res.json({
150
- url,
151
- domain: hostname,
152
- status,
153
- risk_score: riskScore,
154
- threats,
155
- scanned_at: new Date().toISOString(),
156
- powered_by: 'WAB Shield v2.5 | https://www.webagentbridge.com',
157
- });
158
- });
159
-
160
-
161
- // ═══════════════════════════════════════════════════════════════════════
162
- // 2. AI SAFETY LAYER — Pre-navigation safety check
163
- // ═══════════════════════════════════════════════════════════════════════
164
-
165
- router.post('/safety/check', (req, res) => {
166
- const { url, action, platform, amount, currency } = req.body;
167
-
168
- if (!url && !platform) return res.status(400).json({ error: 'url or platform required' });
169
-
170
- const results = { safe: true, warnings: [], blocks: [] };
171
-
172
- // URL scan
173
- if (url) {
174
- let parsedUrl;
175
- try { parsedUrl = new URL(url); } catch {
176
- return res.status(400).json({ error: 'Invalid URL' });
177
- }
178
- const hostname = parsedUrl.hostname.toLowerCase();
179
- let riskScore = 0;
180
- for (const tp of THREAT_PATTERNS) {
181
- if (tp.pattern.test(url) || tp.pattern.test(hostname)) {
182
- riskScore = Math.max(riskScore, tp.weight);
183
- if (tp.weight >= 80) results.blocks.push({ reason: tp.type, confidence: tp.weight });
184
- else results.warnings.push({ reason: tp.type, confidence: tp.weight });
185
- }
186
- }
187
- if (riskScore >= 80) results.safe = false;
188
- }
189
-
190
- // Fairness check for platform
191
- if (platform) {
192
- const site = db.prepare('SELECT * FROM sites WHERE LOWER(domain) = ? AND active = 1').get(platform.toLowerCase());
193
- if (site) {
194
- const score = calculateNeutralityScore(site);
195
- if (score < 40) {
196
- results.warnings.push({ reason: 'low_fairness', score, platform });
197
- }
198
- results.fairness = { platform, score, grade: getGrade(score).grade };
199
- }
200
- }
201
-
202
- // Transaction safety
203
- if (action === 'transaction' && amount) {
204
- const numAmount = parseFloat(amount);
205
- if (numAmount > 500) {
206
- results.warnings.push({ reason: 'high_value_transaction', amount: numAmount, currency: currency || 'USD' });
207
- }
208
- if (platform && results.warnings.some(w => w.reason === 'low_fairness')) {
209
- results.safe = false;
210
- results.blocks.push({ reason: 'unfair_platform_transaction', platform, amount: numAmount });
211
- }
212
- }
213
-
214
- res.json({
215
- ...results,
216
- action: action || 'navigate',
217
- checked_at: new Date().toISOString(),
218
- powered_by: 'WAB AI Safety Layer v2.5',
219
- });
220
- });
221
-
222
-
223
- // ═══════════════════════════════════════════════════════════════════════
224
- // 3. WAB SCORE — Platform Transparency Rating
225
- // ═══════════════════════════════════════════════════════════════════════
226
-
227
- router.get('/score/:domain', (req, res) => {
228
- const domain = req.params.domain.toLowerCase().replace(/^www\./, '').replace(/^https?:\/\//, '');
229
- if (!domain || domain.length < 3) return res.status(400).json({ error: 'Valid domain required' });
230
-
231
- // Check cache (valid for 24 hours)
232
- const cached = db.prepare(`SELECT * FROM wab_scores WHERE domain = ? AND expires_at > datetime('now')`).get(domain);
233
- if (cached) {
234
- return res.json({
235
- domain,
236
- score: cached.overall_score,
237
- fairness_score: cached.fairness_score,
238
- security_score: cached.security_score,
239
- grade: cached.grade,
240
- grade_label: cached.grade_label,
241
- details: jsonParse(cached.details),
242
- computed_at: cached.computed_at,
243
- cached: true,
244
- powered_by: 'WAB Score v2.5',
245
- });
246
- }
247
-
248
- // Compute score
249
- const site = db.prepare(`SELECT * FROM sites WHERE LOWER(REPLACE(domain, 'www.', '')) = ? AND active = 1`).get(domain);
250
-
251
- let fairnessScore = 50; // default for unknown sites
252
- let securityScore = 70;
253
- const details = { signals: [] };
254
-
255
- if (site) {
256
- fairnessScore = calculateNeutralityScore(site);
257
- const config = jsonParse(site.config);
258
-
259
- // Security signals
260
- if (config.agentPermissions) {
261
- details.signals.push({ signal: 'agent_permissions_configured', impact: '+10' });
262
- securityScore += 10;
263
- }
264
- if (config.restrictions && Object.keys(config.restrictions).length) {
265
- details.signals.push({ signal: 'restrictions_defined', impact: '+5' });
266
- securityScore += 5;
267
- }
268
- if (config.logging) {
269
- details.signals.push({ signal: 'logging_enabled', impact: '+5' });
270
- securityScore += 5;
271
- }
272
- details.signals.push({ signal: 'wab_registered', impact: '+15' });
273
- securityScore += 15;
274
- } else {
275
- // Unknown site — pattern-based estimation
276
- if (/\.gov$/.test(domain)) { securityScore = 90; fairnessScore = 85; details.signals.push({ signal: 'government_domain', impact: '+40' }); }
277
- else if (/\.edu$/.test(domain)) { securityScore = 85; fairnessScore = 80; details.signals.push({ signal: 'education_domain', impact: '+35' }); }
278
- else if (/amazon\.com|google\.com|microsoft\.com|apple\.com/.test(domain)) { securityScore = 88; fairnessScore = 82; details.signals.push({ signal: 'major_platform', impact: '+30' }); }
279
- else if (/\.xyz$|\.tk$|\.ml$/.test(domain)) { securityScore = 30; fairnessScore = 25; details.signals.push({ signal: 'suspicious_tld', impact: '-40' }); }
280
- else { details.signals.push({ signal: 'unregistered_with_wab', impact: '-20' }); securityScore -= 10; fairnessScore -= 10; }
281
- }
282
-
283
- securityScore = Math.max(0, Math.min(100, securityScore));
284
- fairnessScore = Math.max(0, Math.min(100, fairnessScore));
285
- const overallScore = Math.round(fairnessScore * 0.7 + securityScore * 0.3);
286
- const gradeInfo = getGrade(overallScore);
287
-
288
- // Cache result
289
- const stmt = db.prepare(`
290
- INSERT OR REPLACE INTO wab_scores (domain, overall_score, fairness_score, security_score, grade, grade_label, details, computed_at, expires_at)
291
- VALUES (?, ?, ?, ?, ?, ?, ?, datetime('now'), datetime('now', '+1 day'))
292
- `);
293
- stmt.run(domain, overallScore, fairnessScore, securityScore, gradeInfo.grade, gradeInfo.label, JSON.stringify(details));
294
-
295
- res.json({
296
- domain,
297
- score: overallScore,
298
- fairness_score: fairnessScore,
299
- security_score: securityScore,
300
- grade: gradeInfo.grade,
301
- grade_label: gradeInfo.label,
302
- grade_color: gradeInfo.color,
303
- details,
304
- computed_at: new Date().toISOString(),
305
- cached: false,
306
- powered_by: 'WAB Score v2.5',
307
- });
308
- });
309
-
310
- router.post('/score/batch', (req, res) => {
311
- const { domains } = req.body;
312
- if (!Array.isArray(domains) || domains.length === 0) return res.status(400).json({ error: 'domains array required' });
313
- if (domains.length > 50) return res.status(400).json({ error: 'Maximum 50 domains per batch' });
314
-
315
- const results = [];
316
- for (const d of domains) {
317
- const domain = d.toLowerCase().replace(/^www\./, '').replace(/^https?:\/\//, '');
318
- const cached = db.prepare(`SELECT * FROM wab_scores WHERE domain = ? AND expires_at > datetime('now')`).get(domain);
319
- if (cached) {
320
- results.push({ domain, score: cached.overall_score, grade: cached.grade, grade_label: cached.grade_label });
321
- } else {
322
- // Quick compute with defaults
323
- let fairness = 50, security = 60;
324
- const site = db.prepare(`SELECT * FROM sites WHERE LOWER(REPLACE(domain, 'www.', '')) = ? AND active = 1`).get(domain);
325
- if (site) { fairness = calculateNeutralityScore(site); security = 75; }
326
- const overall = Math.round(fairness * 0.7 + security * 0.3);
327
- const g = getGrade(overall);
328
- db.prepare(`INSERT OR REPLACE INTO wab_scores (domain, overall_score, fairness_score, security_score, grade, grade_label, details, computed_at, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?, datetime('now'), datetime('now', '+1 day'))`).run(domain, overall, fairness, security, g.grade, g.label, '{}');
329
- results.push({ domain, score: overall, grade: g.grade, grade_label: g.label });
330
- }
331
- }
332
-
333
- results.sort((a, b) => b.score - a.score);
334
- res.json({ results, count: results.length, powered_by: 'WAB Score v2.5' });
335
- });
336
-
337
-
338
- // ═══════════════════════════════════════════════════════════════════════
339
- // 4. TRUST LAYER PROTOCOL — Domain Trust Verification
340
- // ═══════════════════════════════════════════════════════════════════════
341
-
342
- router.get('/trust/verify/:domain', async (req, res) => {
343
- const domain = req.params.domain.toLowerCase().replace(/^www\./, '');
344
-
345
- // Check cache
346
- const cached = db.prepare(`SELECT * FROM trust_manifests WHERE domain = ? AND last_verified_at > datetime('now', '-1 day')`).get(domain);
347
- if (cached) {
348
- return res.json({
349
- domain,
350
- verified: !!cached.verified,
351
- manifest: jsonParse(cached.manifest),
352
- verification: jsonParse(cached.verification_result),
353
- cached: true,
354
- powered_by: 'WAB Trust Layer Protocol',
355
- });
356
- }
357
-
358
- // Try to fetch /.well-known/wab.json from domain
359
- const warnings = [];
360
- let manifest = null;
361
- let verified = false;
362
-
363
- try {
364
- const controller = new AbortController();
365
- const timeout = setTimeout(() => controller.abort(), 5000);
366
- const response = await fetch(`https://${domain}/.well-known/wab.json`, { signal: controller.signal });
367
- clearTimeout(timeout);
368
-
369
- if (response.ok) {
370
- manifest = await response.json();
371
-
372
- // Validate manifest
373
- if (manifest.wab_certified !== undefined) verified = true;
374
- if (manifest.last_audit) {
375
- const auditAge = (Date.now() - new Date(manifest.last_audit).getTime()) / (1000 * 60 * 60 * 24);
376
- if (auditAge > 90) warnings.push('Audit older than 90 days');
377
- }
378
- if (!manifest.contact_email) warnings.push('No contact email specified');
379
- if (!manifest.dispute_url) warnings.push('No dispute URL specified');
380
- }
381
- } catch {
382
- warnings.push('Could not fetch /.well-known/wab.json — domain may not support WAB Trust Protocol');
383
- }
384
-
385
- const verification = {
386
- has_manifest: !!manifest,
387
- wab_certified: manifest?.wab_certified || false,
388
- fairness_score: manifest?.fairness_score || null,
389
- policies: manifest?.policies || {},
390
- warnings,
391
- checked_at: new Date().toISOString(),
392
- };
393
-
394
- // Cache
395
- db.prepare(`INSERT OR REPLACE INTO trust_manifests (domain, manifest, verified, verification_result, last_verified_at) VALUES (?, ?, ?, ?, datetime('now'))`).run(domain, JSON.stringify(manifest || {}), verified ? 1 : 0, JSON.stringify(verification));
396
-
397
- res.json({
398
- domain,
399
- verified,
400
- manifest: manifest || {},
401
- verification,
402
- cached: false,
403
- powered_by: 'WAB Trust Layer Protocol',
404
- });
405
- });
406
-
407
- router.post('/trust/register', authenticateToken, (req, res) => {
408
- const { domain, fairness_score, contact_email, dispute_url, policies } = req.body;
409
- if (!domain) return res.status(400).json({ error: 'domain required' });
410
-
411
- const manifest = {
412
- wab_version: '2.5',
413
- wab_certified: false, // Certification requires manual review
414
- fairness_score: fairness_score || 0,
415
- last_audit: new Date().toISOString().split('T')[0],
416
- transparency_url: `https://${domain}/transparency`,
417
- contact_email: contact_email || '',
418
- dispute_url: dispute_url || '',
419
- policies: {
420
- hidden_fees: policies?.hidden_fees || false,
421
- fair_reviews: policies?.fair_reviews || false,
422
- data_privacy: policies?.data_privacy || false,
423
- seller_fairness: policies?.seller_fairness || false,
424
- },
425
- };
426
-
427
- db.prepare(`INSERT OR REPLACE INTO trust_manifests (domain, manifest, verified, verification_result, last_verified_at, registered_at) VALUES (?, ?, 0, ?, datetime('now'), datetime('now'))`).run(domain, JSON.stringify(manifest), JSON.stringify({ self_registered: true }));
428
-
429
- res.json({
430
- domain,
431
- manifest,
432
- instructions: {
433
- step1: 'Host this JSON at https://' + domain + '/.well-known/wab.json',
434
- step2: 'Run GET /api/growth/trust/verify/' + domain + ' to verify',
435
- step3: 'After review, your site will be WAB Certified',
436
- },
437
- powered_by: 'WAB Trust Layer Protocol',
438
- });
439
- });
440
-
441
- router.get('/trust/badge/:domain', async (req, res) => {
442
- const domain = req.params.domain.toLowerCase().replace(/^www\./, '');
443
- const cached = db.prepare('SELECT * FROM trust_manifests WHERE domain = ?').get(domain);
444
-
445
- const verified = cached?.verified === 1;
446
- const score = cached ? jsonParse(cached.manifest).fairness_score || 0 : 0;
447
-
448
- const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="200" height="32" viewBox="0 0 200 32">
449
- <rect width="200" height="32" rx="4" fill="${verified ? '#22c55e' : '#64748b'}"/>
450
- <text x="8" y="21" font-family="Arial" font-size="12" fill="white" font-weight="bold">${verified ? '✓ WAB Certified' : '○ WAB Unverified'}</text>
451
- <text x="140" y="21" font-family="Arial" font-size="11" fill="white">${score}/100</text>
452
- </svg>`;
453
-
454
- res.set('Content-Type', 'image/svg+xml');
455
- res.set('Cache-Control', 'public, max-age=3600');
456
- res.send(svg);
457
- });
458
-
459
-
460
- // ═══════════════════════════════════════════════════════════════════════
461
- // 5. BOUNTY NETWORK — Crowdsourced Threat Reporting
462
- // ═══════════════════════════════════════════════════════════════════════
463
-
464
- // Auto-register reporter from authenticated user
465
- function getOrCreateReporter(userId) {
466
- let reporter = db.prepare('SELECT * FROM bounty_reporters WHERE user_id = ?').get(userId);
467
- if (!reporter) {
468
- const id = uuid();
469
- const token = crypto.randomBytes(24).toString('hex');
470
- db.prepare('INSERT INTO bounty_reporters (id, user_id, token, display_name) VALUES (?, ?, ?, ?)').run(id, userId, token, 'Reporter');
471
- reporter = db.prepare('SELECT * FROM bounty_reporters WHERE id = ?').get(id);
472
- }
473
- return reporter;
474
- }
475
-
476
- function getReporterByToken(token) {
477
- return db.prepare('SELECT * FROM bounty_reporters WHERE token = ?').get(token);
478
- }
479
-
480
- router.post('/bounty/register', authenticateToken, (req, res) => {
481
- const reporter = getOrCreateReporter(req.user.id);
482
- res.json({
483
- reporter_id: reporter.id,
484
- token: reporter.token,
485
- credits: reporter.credits,
486
- message: 'Use this token in X-WAB-Reporter header for bounty submissions',
487
- powered_by: 'WAB Bounty Network v2.5',
488
- });
489
- });
490
-
491
- router.post('/bounty/submit', (req, res) => {
492
- // Accept auth via header or JWT
493
- const token = req.headers['x-wab-reporter'];
494
- if (!token) return res.status(401).json({ error: 'X-WAB-Reporter header required. Register at /api/growth/bounty/register' });
495
-
496
- const reporter = getReporterByToken(token);
497
- if (!reporter) return res.status(403).json({ error: 'Invalid reporter token' });
498
-
499
- const { url, category, description, evidence } = req.body;
500
- if (!url || !/^https?:\/\//i.test(url)) return res.status(400).json({ error: 'Valid URL required (must start with http:// or https://)' });
501
-
502
- const fingerprint = crypto.createHash('sha256').update(url.toLowerCase().trim()).digest('hex').substring(0, 16);
503
-
504
- // Check duplicate
505
- const existing = db.prepare('SELECT id FROM bounties WHERE fingerprint = ?').get(fingerprint);
506
- if (existing) {
507
- db.prepare('UPDATE bounty_reporters SET credits = credits + 1 WHERE id = ?').run(reporter.id);
508
- return res.json({
509
- bounty_id: existing.id,
510
- status: 'DUPLICATE',
511
- message: 'This URL is already in our database. Small reward for the effort.',
512
- credits_earned: REWARD_TIERS.DUPLICATE.credits,
513
- powered_by: 'WAB Bounty Network v2.5',
514
- });
515
- }
516
-
517
- const bountyId = `BNT-${Date.now()}-${crypto.randomBytes(4).toString('hex').toUpperCase()}`;
518
-
519
- db.prepare(`INSERT INTO bounties (id, reporter_id, url, fingerprint, category, description, evidence) VALUES (?, ?, ?, ?, ?, ?, ?)`).run(bountyId, reporter.id, url, fingerprint, category || 'phishing', description || '', evidence || '');
520
- db.prepare('UPDATE bounty_reporters SET total_reports = total_reports + 1 WHERE id = ?').run(reporter.id);
521
-
522
- // Async verification
523
- setImmediate(() => verifyBountyInternal(bountyId, url, reporter.id));
524
-
525
- res.json({
526
- bounty_id: bountyId,
527
- status: 'PENDING',
528
- message: 'Report submitted. Automated verification in progress.',
529
- powered_by: 'WAB Bounty Network v2.5',
530
- });
531
- });
532
-
533
- function verifyBountyInternal(bountyId, url, reporterId) {
534
- try {
535
- let riskScore = 0;
536
- for (const tp of THREAT_PATTERNS) {
537
- if (tp.pattern.test(url)) riskScore = Math.max(riskScore, tp.weight);
538
- }
539
-
540
- let tier = 'INVALID';
541
- if (riskScore >= 80) tier = 'CRITICAL';
542
- else if (riskScore >= 60) tier = 'HIGH';
543
- else if (riskScore >= 40) tier = 'MEDIUM';
544
- else if (riskScore >= 20) tier = 'LOW';
545
-
546
- const reward = REWARD_TIERS[tier];
547
-
548
- db.prepare(`UPDATE bounties SET status = ?, reward_tier = ?, credits_awarded = ?, scan_result = ?, verified_at = datetime('now') WHERE id = ?`).run(tier === 'INVALID' ? 'REJECTED' : 'VERIFIED', tier, reward.credits, JSON.stringify({ risk_score: riskScore }), bountyId);
549
-
550
- if (reward.credits > 0) {
551
- db.prepare('UPDATE bounty_reporters SET credits = credits + ?, verified_reports = verified_reports + 1 WHERE id = ?').run(reward.credits, reporterId);
552
- }
553
- } catch (err) {
554
- console.error(`[WAB Bounty] Verification failed for ${bountyId}:`, err.message);
555
- }
556
- }
557
-
558
- router.get('/bounty/status/:id', (req, res) => {
559
- const bounty = db.prepare('SELECT * FROM bounties WHERE id = ?').get(req.params.id);
560
- if (!bounty) return res.status(404).json({ error: 'Bounty not found' });
561
- res.json({
562
- ...bounty,
563
- scan_result: jsonParse(bounty.scan_result),
564
- powered_by: 'WAB Bounty Network v2.5',
565
- });
566
- });
567
-
568
- router.get('/bounty/balance', (req, res) => {
569
- const token = req.headers['x-wab-reporter'];
570
- if (!token) return res.status(401).json({ error: 'X-WAB-Reporter header required' });
571
- const reporter = getReporterByToken(token);
572
- if (!reporter) return res.status(403).json({ error: 'Invalid reporter token' });
573
-
574
- res.json({
575
- reporter_id: reporter.id,
576
- credits: reporter.credits,
577
- total_reports: reporter.total_reports,
578
- verified_reports: reporter.verified_reports,
579
- accuracy_rate: reporter.total_reports > 0 ? Math.round((reporter.verified_reports / reporter.total_reports) * 100) : 0,
580
- powered_by: 'WAB Bounty Network v2.5',
581
- });
582
- });
583
-
584
- router.get('/bounty/leaderboard', (req, res) => {
585
- const limit = Math.min(parseInt(req.query.limit) || 10, 50);
586
- const leaders = db.prepare('SELECT display_name, credits, verified_reports, total_reports FROM bounty_reporters ORDER BY credits DESC LIMIT ?').all(limit);
587
- res.json({ leaderboard: leaders, powered_by: 'WAB Bounty Network v2.5' });
588
- });
589
-
590
-
591
- // ═══════════════════════════════════════════════════════════════════════
592
- // 6. DATA MARKETPLACE — Threat Intelligence Datasets
593
- // ═══════════════════════════════════════════════════════════════════════
594
-
595
- router.get('/data/datasets', (req, res) => {
596
- const category = req.query.category;
597
- let datasets;
598
- if (category) {
599
- datasets = db.prepare('SELECT id, category, title, description, record_count, format, price_base, created_at FROM datasets WHERE active = 1 AND category = ? ORDER BY created_at DESC').all(category);
600
- } else {
601
- datasets = db.prepare('SELECT id, category, title, description, record_count, format, price_base, created_at FROM datasets WHERE active = 1 ORDER BY created_at DESC').all();
602
- }
603
- res.json({
604
- datasets,
605
- total: datasets.length,
606
- categories: ['THREAT_INTEL', 'PLATFORM_FAIR', 'PRICE_HISTORY', 'USER_BEHAVIOR', 'AFFILIATE_INTEL', 'EMAIL_THREATS'],
607
- powered_by: 'WAB Data Marketplace v2.5',
608
- });
609
- });
610
-
611
- router.get('/data/datasets/:id', (req, res) => {
612
- const dataset = db.prepare('SELECT * FROM datasets WHERE id = ? AND active = 1').get(req.params.id);
613
- if (!dataset) return res.status(404).json({ error: 'Dataset not found' });
614
-
615
- const meta = jsonParse(dataset.metadata);
616
- res.json({
617
- ...dataset,
618
- metadata: meta,
619
- sample_data: jsonParse(dataset.sample_data, []),
620
- license_types: {
621
- RESEARCH: { multiplier: 1, price: dataset.price_base, use: 'Non-commercial research', redistribution: false },
622
- COMMERCIAL: { multiplier: 3, price: dataset.price_base * 3, use: 'Commercial products', redistribution: false },
623
- ENTERPRISE: { multiplier: 8, price: dataset.price_base * 8, use: 'Any use', redistribution: true },
624
- AI_TRAINING:{ multiplier: 5, price: dataset.price_base * 5, use: 'AI/ML model training', redistribution: false },
625
- },
626
- powered_by: 'WAB Data Marketplace v2.5',
627
- });
628
- });
629
-
630
- router.get('/data/datasets/:id/sample', (req, res) => {
631
- const dataset = db.prepare('SELECT sample_data FROM datasets WHERE id = ? AND active = 1').get(req.params.id);
632
- if (!dataset) return res.status(404).json({ error: 'Dataset not found' });
633
- res.json({
634
- sample: jsonParse(dataset.sample_data, []),
635
- note: 'This is a free preview. Purchase the full dataset for complete access.',
636
- powered_by: 'WAB Data Marketplace v2.5',
637
- });
638
- });
639
-
640
- router.post('/data/purchase', authenticateToken, (req, res) => {
641
- const { dataset_id, license_type } = req.body;
642
- if (!dataset_id) return res.status(400).json({ error: 'dataset_id required' });
643
-
644
- const dataset = db.prepare('SELECT * FROM datasets WHERE id = ? AND active = 1').get(dataset_id);
645
- if (!dataset) return res.status(404).json({ error: 'Dataset not found' });
646
-
647
- const multipliers = { RESEARCH: 1, COMMERCIAL: 3, ENTERPRISE: 8, AI_TRAINING: 5 };
648
- const mult = multipliers[license_type] || 1;
649
- const price = dataset.price_base * mult;
650
-
651
- const purchaseId = uuid();
652
- db.prepare('INSERT INTO dataset_purchases (id, user_id, dataset_id, license_type, price_paid) VALUES (?, ?, ?, ?, ?)').run(purchaseId, req.user.id, dataset_id, license_type || 'RESEARCH', price);
653
-
654
- res.json({
655
- purchase_id: purchaseId,
656
- dataset_id,
657
- license_type: license_type || 'RESEARCH',
658
- price_paid: price,
659
- currency: 'USD',
660
- status: 'completed',
661
- download_url: `/api/growth/data/download/${purchaseId}`,
662
- powered_by: 'WAB Data Marketplace v2.5',
663
- });
664
- });
665
-
666
- router.get('/data/download/:purchaseId', authenticateToken, (req, res) => {
667
- const purchase = db.prepare('SELECT * FROM dataset_purchases WHERE id = ? AND user_id = ?').get(req.params.purchaseId, req.user.id);
668
- if (!purchase) return res.status(404).json({ error: 'Purchase not found' });
669
-
670
- const dataset = db.prepare('SELECT * FROM datasets WHERE id = ?').get(purchase.dataset_id);
671
- if (!dataset) return res.status(404).json({ error: 'Dataset no longer available' });
672
-
673
- // Return full sample data as the "download" — in production this would be a signed S3 URL
674
- res.json({
675
- dataset_id: dataset.id,
676
- title: dataset.title,
677
- format: dataset.format,
678
- record_count: dataset.record_count,
679
- data: jsonParse(dataset.sample_data, []),
680
- license: purchase.license_type,
681
- purchased_at: purchase.purchased_at,
682
- powered_by: 'WAB Data Marketplace v2.5',
683
- });
684
- });
685
-
686
-
687
- // ═══════════════════════════════════════════════════════════════════════
688
- // 7. EMAIL PROTECTION — Email Content Scanning
689
- // ═══════════════════════════════════════════════════════════════════════
690
-
691
- router.post('/email/scan', (req, res) => {
692
- const { subject, body, sender, urls } = req.body;
693
- if (!subject && !body && !urls) return res.status(400).json({ error: 'subject, body, or urls required' });
694
-
695
- const content = `${subject || ''} ${body || ''}`;
696
- const patterns = [];
697
- let riskScore = 0;
698
-
699
- // Detect phishing patterns in text
700
- for (const pp of PHISHING_EMAIL_PATTERNS) {
701
- if (pp.pattern.test(content)) {
702
- patterns.push(pp.label);
703
- riskScore += 15;
704
- }
705
- }
706
-
707
- // Extract and scan URLs
708
- const urlRegex = /https?:\/\/[^\s<>"')\]]+/gi;
709
- const extractedUrls = [...new Set([...(content.match(urlRegex) || []), ...(urls || [])])];
710
- const urlResults = [];
711
-
712
- for (const u of extractedUrls.slice(0, 20)) { // limit to 20 URLs
713
- let urlRisk = 0;
714
- const threats = [];
715
- for (const tp of THREAT_PATTERNS) {
716
- if (tp.pattern.test(u)) {
717
- urlRisk = Math.max(urlRisk, tp.weight);
718
- threats.push(tp.type);
719
- }
720
- }
721
- urlResults.push({
722
- url: u,
723
- risk_score: urlRisk,
724
- status: urlRisk >= 80 ? 'CRITICAL' : urlRisk >= 50 ? 'WARNING' : 'SAFE',
725
- threats,
726
- });
727
- riskScore = Math.max(riskScore, urlRisk);
728
- }
729
-
730
- // Sender analysis
731
- let senderReputation = null;
732
- if (sender) {
733
- const senderDomain = sender.split('@').pop()?.toLowerCase();
734
- if (senderDomain) {
735
- let domainRisk = 0;
736
- if (/\.xyz$|\.tk$|\.ml$|\.ga$|\.cf$/.test(senderDomain)) domainRisk = 60;
737
- if (/gmail\.com|outlook\.com|yahoo\.com|hotmail\.com/.test(senderDomain)) domainRisk = 10;
738
- senderReputation = { domain: senderDomain, risk_score: domainRisk, status: domainRisk >= 50 ? 'WARNING' : 'SAFE' };
739
- }
740
- }
741
-
742
- riskScore = Math.min(100, riskScore);
743
- const overallRisk = riskScore >= 80 ? 'CRITICAL' : riskScore >= 50 ? 'WARNING' : 'SAFE';
744
-
745
- // Log scan
746
- db.prepare('INSERT INTO email_scans (sender_domain, urls_found, critical_count, warning_count, overall_risk, risk_score) VALUES (?, ?, ?, ?, ?, ?)').run(
747
- senderReputation?.domain || null,
748
- urlResults.length,
749
- urlResults.filter(u => u.status === 'CRITICAL').length,
750
- urlResults.filter(u => u.status === 'WARNING').length,
751
- overallRisk,
752
- riskScore
753
- );
754
-
755
- res.json({
756
- overall_risk: overallRisk,
757
- risk_score: riskScore,
758
- urls_found: extractedUrls.length,
759
- urls_scanned: urlResults,
760
- critical_count: urlResults.filter(u => u.status === 'CRITICAL').length,
761
- warning_count: urlResults.filter(u => u.status === 'WARNING').length,
762
- sender_reputation: senderReputation,
763
- phishing_patterns: patterns,
764
- scanned_at: new Date().toISOString(),
765
- powered_by: 'WAB Email Protection v2.5',
766
- });
767
- });
768
-
769
- router.get('/email/stats', (req, res) => {
770
- const total = db.prepare('SELECT COUNT(*) as c FROM email_scans').get().c;
771
- const critical = db.prepare('SELECT COUNT(*) as c FROM email_scans WHERE overall_risk = ?').get('CRITICAL').c;
772
- const last24h = db.prepare(`SELECT COUNT(*) as c FROM email_scans WHERE scanned_at > datetime('now', '-1 day')`).get().c;
773
- res.json({
774
- total_scans: total,
775
- critical_detected: critical,
776
- scans_last_24h: last24h,
777
- detection_rate: total > 0 ? Math.round((critical / total) * 100) : 0,
778
- powered_by: 'WAB Email Protection v2.5',
779
- });
780
- });
781
-
782
-
783
- // ═══════════════════════════════════════════════════════════════════════
784
- // 8. AFFILIATE INTELLIGENCE — Network Fraud Detection
785
- // ═══════════════════════════════════════════════════════════════════════
786
-
787
- router.get('/affiliate/networks', (req, res) => {
788
- const networks = Object.entries(KNOWN_NETWORKS).map(([id, info]) => ({
789
- id,
790
- ...info,
791
- }));
792
- res.json({ networks, powered_by: 'WAB Affiliate Intelligence v2.5' });
793
- });
794
-
795
- router.get('/affiliate/analyze/:networkId', (req, res) => {
796
- const networkId = req.params.networkId.toLowerCase();
797
- const network = KNOWN_NETWORKS[networkId];
798
- if (!network) return res.status(404).json({ error: 'Unknown network', known_networks: Object.keys(KNOWN_NETWORKS) });
799
-
800
- // Check cache
801
- const cached = db.prepare(`SELECT * FROM affiliate_reports WHERE network_id = ? AND analyzed_at > datetime('now', '-1 day')`).get(networkId);
802
- if (cached) {
803
- return res.json({
804
- network_id: networkId,
805
- network_name: network.name,
806
- risk_level: cached.risk_level,
807
- trust_score: cached.trust_score,
808
- fraud_types: jsonParse(cached.fraud_types, []),
809
- details: jsonParse(cached.details),
810
- cached: true,
811
- powered_by: 'WAB Affiliate Intelligence v2.5',
812
- });
813
- }
814
-
815
- // Analysis
816
- const fraudTypes = [];
817
- let trustScore = network.trust_base;
818
-
819
- // Evaluate based on known metrics
820
- if (network.avg_payout_days > 40) {
821
- fraudTypes.push({ ...FRAUD_PATTERNS.payment_delays, data: { avg_payout_days: network.avg_payout_days, industry_avg: 30 } });
822
- trustScore -= 10;
823
- }
824
- if (network.cookie_days <= 1) {
825
- fraudTypes.push({ ...FRAUD_PATTERNS.late_attribution, data: { cookie_days: network.cookie_days, industry_avg: 30 } });
826
- trustScore -= 5;
827
- }
828
- if (networkId === 'clickbank') {
829
- fraudTypes.push({ ...FRAUD_PATTERNS.commission_shaving, data: { estimated_shaving: '12%', evidence: 'Community reports of valid sales cancelled' } });
830
- trustScore -= 15;
831
- }
832
-
833
- const riskLevel = trustScore >= 80 ? 'LOW' : trustScore >= 60 ? 'MEDIUM' : trustScore >= 40 ? 'HIGH' : 'CRITICAL';
834
-
835
- const details = {
836
- avg_commission: network.avg_commission + '%',
837
- avg_payout_days: network.avg_payout_days,
838
- cookie_window: network.cookie_days + ' days',
839
- recommendation: riskLevel === 'LOW' ? 'Safe to use' : riskLevel === 'MEDIUM' ? 'Use with caution, monitor closely' : 'Consider alternatives',
840
- benchmarks: {
841
- industry_avg_commission: '8%',
842
- industry_avg_payout: '30 days',
843
- industry_avg_cookie: '30 days',
844
- },
845
- };
846
-
847
- // Cache
848
- const reportId = uuid();
849
- db.prepare('INSERT OR REPLACE INTO affiliate_reports (id, network_id, risk_level, fraud_types, trust_score, details) VALUES (?, ?, ?, ?, ?, ?)').run(reportId, networkId, riskLevel, JSON.stringify(fraudTypes), trustScore, JSON.stringify(details));
850
-
851
- res.json({
852
- network_id: networkId,
853
- network_name: network.name,
854
- risk_level: riskLevel,
855
- trust_score: trustScore,
856
- fraud_types: fraudTypes,
857
- details,
858
- cached: false,
859
- powered_by: 'WAB Affiliate Intelligence v2.5',
860
- });
861
- });
862
-
863
- router.post('/affiliate/detect-fraud', (req, res) => {
864
- const { network_id, data } = req.body;
865
- if (!network_id && !data) return res.status(400).json({ error: 'network_id or data required' });
866
-
867
- const network = KNOWN_NETWORKS[network_id];
868
- const detected = [];
869
-
870
- if (data) {
871
- // Analyze user-provided data
872
- if (data.conversion_rate !== undefined) {
873
- const expectedCVR = 2.5; // industry baseline
874
- if (data.conversion_rate < expectedCVR * 0.3) {
875
- detected.push({ ...FRAUD_PATTERNS.low_cvr, data: { actual: data.conversion_rate, expected: expectedCVR, ratio: (data.conversion_rate / expectedCVR * 100).toFixed(0) + '%' } });
876
- }
877
- }
878
- if (data.epc !== undefined && network) {
879
- const expectedEPC = network.avg_commission * 0.025; // rough benchmark
880
- if (data.epc < expectedEPC * 0.4) {
881
- detected.push({ ...FRAUD_PATTERNS.commission_shaving, data: { actual_epc: data.epc, expected_epc: expectedEPC.toFixed(2) } });
882
- }
883
- }
884
- if (data.payment_delay !== undefined) {
885
- const expected = network ? network.avg_payout_days : 30;
886
- if (data.payment_delay > expected * 1.5) {
887
- detected.push({ ...FRAUD_PATTERNS.payment_delays, data: { actual_days: data.payment_delay, expected_days: expected } });
888
- }
889
- }
890
- if (data.cancelled_rate !== undefined && data.cancelled_rate > 10) {
891
- detected.push({ ...FRAUD_PATTERNS.commission_shaving, data: { cancelled_rate: data.cancelled_rate + '%', threshold: '10%' } });
892
- }
893
- }
894
-
895
- const riskLevel = detected.some(d => d.severity === 'CRITICAL') ? 'CRITICAL' :
896
- detected.some(d => d.severity === 'HIGH') ? 'HIGH' :
897
- detected.length > 0 ? 'MEDIUM' : 'LOW';
898
-
899
- res.json({
900
- network_id: network_id || 'custom',
901
- network_name: network?.name || 'Custom Analysis',
902
- risk_level: riskLevel,
903
- fraud_detected: detected.length,
904
- fraud_types: detected,
905
- recommendation: detected.length === 0 ? 'No fraud indicators detected' :
906
- riskLevel === 'CRITICAL' ? 'Immediate action required — contact network and document evidence' :
907
- riskLevel === 'HIGH' ? 'Monitor closely and diversify to other networks' :
908
- 'Keep tracking metrics and compare monthly',
909
- powered_by: 'WAB Affiliate Intelligence v2.5',
910
- });
911
- });
912
-
913
- router.get('/affiliate/benchmarks', (req, res) => {
914
- res.json({
915
- benchmarks: {
916
- avg_commission_rate: '8%',
917
- avg_epc: '$0.45',
918
- avg_conversion_rate: '2.5%',
919
- avg_payout_days: 30,
920
- avg_cookie_window: '30 days',
921
- avg_reversal_rate: '5%',
922
- },
923
- by_category: {
924
- SaaS: { avg_commission: '20-30%', avg_cookie: '90 days', avg_payout: '15 days' },
925
- eCommerce: { avg_commission: '3-8%', avg_cookie: '1-30 days', avg_payout: '30-60 days' },
926
- Finance: { avg_commission: '$50-200 per lead', avg_cookie: '30-45 days', avg_payout: '30-45 days' },
927
- Travel: { avg_commission: '3-6%', avg_cookie: '7-30 days', avg_payout: '30-60 days' },
928
- },
929
- powered_by: 'WAB Affiliate Intelligence v2.5',
930
- });
931
- });
932
-
933
-
934
- // ═══════════════════════════════════════════════════════════════════════
935
- // OVERVIEW — All modules status
936
- // ═══════════════════════════════════════════════════════════════════════
937
-
938
- router.get('/status', (req, res) => {
939
- const bountyCount = db.prepare('SELECT COUNT(*) as c FROM bounties').get().c;
940
- const reporterCount = db.prepare('SELECT COUNT(*) as c FROM bounty_reporters').get().c;
941
- const datasetCount = db.prepare('SELECT COUNT(*) as c FROM datasets WHERE active = 1').get().c;
942
- const emailScans = db.prepare('SELECT COUNT(*) as c FROM email_scans').get().c;
943
- const scoreCount = db.prepare('SELECT COUNT(*) as c FROM wab_scores').get().c;
944
-
945
- res.json({
946
- suite: 'WAB Growth Suite v2.5',
947
- modules: {
948
- shield: { status: 'active', endpoint: '/api/growth/scan' },
949
- safety: { status: 'active', endpoint: '/api/growth/safety/check' },
950
- score: { status: 'active', endpoint: '/api/growth/score/:domain', cached_scores: scoreCount },
951
- trust: { status: 'active', endpoint: '/api/growth/trust/verify/:domain' },
952
- bounty: { status: 'active', endpoint: '/api/growth/bounty/*', total_bounties: bountyCount, reporters: reporterCount },
953
- marketplace: { status: 'active', endpoint: '/api/growth/data/*', datasets: datasetCount },
954
- email: { status: 'active', endpoint: '/api/growth/email/scan', total_scans: emailScans },
955
- affiliate: { status: 'active', endpoint: '/api/growth/affiliate/*', networks: Object.keys(KNOWN_NETWORKS).length },
956
- },
957
- powered_by: 'WAB Growth Suite v2.5 | https://www.webagentbridge.com',
958
- });
959
- });
960
-
961
-
962
- module.exports = router;