web-agent-bridge 3.0.0 → 3.2.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 (51) hide show
  1. package/LICENSE +51 -0
  2. package/README.ar.md +79 -0
  3. package/README.md +104 -4
  4. package/package.json +2 -1
  5. package/public/.well-known/ai-plugin.json +28 -0
  6. package/public/agent-workspace.html +3 -1
  7. package/public/ai.html +5 -3
  8. package/public/api.html +412 -0
  9. package/public/browser.html +4 -2
  10. package/public/cookies.html +4 -2
  11. package/public/dashboard.html +5 -3
  12. package/public/demo.html +1770 -1
  13. package/public/docs.html +6 -4
  14. package/public/growth.html +463 -0
  15. package/public/index.html +982 -738
  16. package/public/llms-full.txt +52 -1
  17. package/public/llms.txt +39 -0
  18. package/public/login.html +6 -4
  19. package/public/premium-dashboard.html +7 -5
  20. package/public/premium.html +6 -4
  21. package/public/privacy.html +4 -2
  22. package/public/register.html +6 -4
  23. package/public/score.html +263 -0
  24. package/public/terms.html +4 -2
  25. package/sdk/index.js +7 -1
  26. package/sdk/package.json +12 -1
  27. package/server/index.js +427 -375
  28. package/server/middleware/rateLimits.js +3 -3
  29. package/server/migrations/006_growth_suite.sql +138 -0
  30. package/server/routes/agent-workspace.js +162 -0
  31. package/server/routes/demo-showcase.js +332 -0
  32. package/server/routes/discovery.js +18 -7
  33. package/server/routes/gateway.js +157 -0
  34. package/server/routes/growth.js +962 -0
  35. package/server/routes/universal.js +9 -1
  36. package/server/routes/wab-api.js +16 -6
  37. package/server/services/api-key-engine.js +261 -0
  38. package/server/services/lfd.js +22 -3
  39. package/server/services/modules/affiliate-intelligence.js +93 -0
  40. package/server/services/modules/agent-firewall.js +90 -0
  41. package/server/services/modules/bounty.js +89 -0
  42. package/server/services/modules/collective-bargaining.js +92 -0
  43. package/server/services/modules/dark-pattern.js +66 -0
  44. package/server/services/modules/gov-intelligence.js +45 -0
  45. package/server/services/modules/neural.js +55 -0
  46. package/server/services/modules/notary.js +49 -0
  47. package/server/services/modules/price-time-machine.js +86 -0
  48. package/server/services/modules/protocol.js +104 -0
  49. package/server/services/premium.js +1 -1
  50. package/server/services/price-intelligence.js +2 -1
  51. package/server/services/vision.js +2 -2
@@ -11,7 +11,15 @@ const express = require('express');
11
11
  const router = express.Router();
12
12
  const scraper = require('../services/universal-scraper');
13
13
  const priceIntel = require('../services/price-intelligence');
14
- const fairness = require('../services/fairness-engine');
14
+ let fairness;
15
+ try { fairness = require('../services/fairness-engine'); } catch {
16
+ fairness = {
17
+ calculateFairnessScore: () => ({ score: 0, label: 'unrated' }),
18
+ rankWithFairness: (_items) => _items,
19
+ detectDarkPatterns: () => [],
20
+ getTopFairSites: () => []
21
+ };
22
+ }
15
23
 
16
24
  // ─── POST /api/universal/extract ─────────────────────────────────────
17
25
  // Extract prices/products from a URL (server-side fetch)
@@ -14,12 +14,22 @@ const { findSiteById, findSiteByLicense, recordAnalytic, db } = require('../mode
14
14
  const { broadcastAnalytic } = require('../ws');
15
15
  const { wabAuthenticateLimiter, wabActionLimiter, searchLimiter } = require('../middleware/rateLimits');
16
16
  const { auditLog } = require('../services/security');
17
- const {
18
- calculateNeutralityScore,
19
- fairnessWeightedSearch,
20
- getDirectoryListings,
21
- generateFairnessReport
22
- } = require('../services/fairness');
17
+
18
+ // Fairness module is proprietary — provide stubs when not available
19
+ let calculateNeutralityScore, fairnessWeightedSearch, getDirectoryListings, generateFairnessReport;
20
+ try {
21
+ ({
22
+ calculateNeutralityScore,
23
+ fairnessWeightedSearch,
24
+ getDirectoryListings,
25
+ generateFairnessReport
26
+ } = require('../services/fairness'));
27
+ } catch {
28
+ calculateNeutralityScore = () => ({ score: 0, label: 'unrated' });
29
+ fairnessWeightedSearch = (_q, candidates) => candidates;
30
+ getDirectoryListings = () => [];
31
+ generateFairnessReport = () => ({ status: 'unavailable' });
32
+ }
23
33
 
24
34
  const WAB_VERSION = '1.2.0';
25
35
  const PROTOCOL_VERSION = '1.0';
@@ -0,0 +1,261 @@
1
+ /**
2
+ * WAB API Key Engine
3
+ * Authentication, authorization, rate limiting, and quota management
4
+ * for all WAB advanced modules.
5
+ *
6
+ * Powered by WAB — Web Agent Bridge
7
+ * https://www.webagentbridge.com
8
+ */
9
+
10
+ 'use strict';
11
+
12
+ const crypto = require('crypto');
13
+
14
+ // ─── Plan Definitions ─────────────────────────────────────────────────────────
15
+ const PLANS = {
16
+ FREE: {
17
+ name: 'Free',
18
+ price_usd: 0,
19
+ requests_per_day: 100,
20
+ requests_per_minute: 10,
21
+ modules_allowed: ['dark-pattern', 'price', 'protocol', 'bounty'],
22
+ features: {
23
+ agent_firewall: false, notary: false, dark_pattern: true,
24
+ collective_bargaining: false, gov_intelligence: false,
25
+ price_time_machine: true, neural: false, protocol: true,
26
+ bounty: true, affiliate: false,
27
+ },
28
+ support: 'community',
29
+ data_retention_days: 7,
30
+ },
31
+ PRO: {
32
+ name: 'Pro',
33
+ price_usd: 29,
34
+ requests_per_day: 10000,
35
+ requests_per_minute: 100,
36
+ modules_allowed: ['agent-firewall', 'dark-pattern', 'neural', 'bounty', 'affiliate', 'protocol', 'price', 'bargaining'],
37
+ features: {
38
+ agent_firewall: true, notary: false, dark_pattern: true,
39
+ collective_bargaining: true, gov_intelligence: false,
40
+ price_time_machine: true, neural: true, protocol: true,
41
+ bounty: true, affiliate: true,
42
+ },
43
+ support: 'email',
44
+ data_retention_days: 90,
45
+ },
46
+ BUSINESS: {
47
+ name: 'Business',
48
+ price_usd: 149,
49
+ requests_per_day: 100000,
50
+ requests_per_minute: 500,
51
+ modules_allowed: ['all'],
52
+ features: {
53
+ agent_firewall: true, notary: true, dark_pattern: true,
54
+ collective_bargaining: true, gov_intelligence: true,
55
+ price_time_machine: true, neural: true, protocol: true,
56
+ bounty: true, affiliate: true,
57
+ },
58
+ support: 'priority',
59
+ data_retention_days: 365,
60
+ },
61
+ ENTERPRISE: {
62
+ name: 'Enterprise',
63
+ price_usd: null,
64
+ requests_per_day: Infinity,
65
+ requests_per_minute: Infinity,
66
+ modules_allowed: ['all'],
67
+ features: {
68
+ agent_firewall: true, notary: true, dark_pattern: true,
69
+ collective_bargaining: true, gov_intelligence: true,
70
+ price_time_machine: true, neural: true, protocol: true,
71
+ bounty: true, affiliate: true,
72
+ },
73
+ support: 'dedicated',
74
+ data_retention_days: Infinity,
75
+ custom_sla: true,
76
+ on_premise: true,
77
+ },
78
+ INTERNAL: {
79
+ name: 'Internal',
80
+ price_usd: 0,
81
+ requests_per_day: Infinity,
82
+ requests_per_minute: Infinity,
83
+ modules_allowed: ['all'],
84
+ features: Object.fromEntries(
85
+ ['agent_firewall','notary','dark_pattern','collective_bargaining','gov_intelligence',
86
+ 'price_time_machine','neural','protocol','bounty','affiliate'].map(k => [k, true])
87
+ ),
88
+ support: 'internal',
89
+ data_retention_days: Infinity,
90
+ },
91
+ };
92
+
93
+ const keyStore = new Map();
94
+ const usageStore = new Map();
95
+ const rateLimitStore = new Map();
96
+
97
+ class WABKeyEngine {
98
+ constructor() {
99
+ this.internalKey = this._seedInternalKeys();
100
+ }
101
+
102
+ _seedInternalKeys() {
103
+ const internalKey = 'wab_internal_' + crypto.randomBytes(16).toString('hex');
104
+ keyStore.set(internalKey, {
105
+ key: internalKey, key_id: 'kid_internal_001', plan: 'INTERNAL',
106
+ owner: 'WAB Core Team', email: 'dev@webagentbridge.com',
107
+ environment: 'internal', created_at: new Date().toISOString(),
108
+ last_used: null, active: true, scopes: ['*'],
109
+ });
110
+ return internalKey;
111
+ }
112
+
113
+ generateKey(options = {}) {
114
+ const { plan = 'FREE', owner, email, environment = 'live', scopes = [], metadata = {} } = options;
115
+ if (!PLANS[plan]) throw new Error(`Invalid plan: ${plan}`);
116
+ if (!owner) throw new Error('owner is required');
117
+ if (!email) throw new Error('email is required');
118
+
119
+ const planPrefix = plan.toLowerCase().substring(0, 3);
120
+ const randomPart = crypto.randomBytes(20).toString('hex');
121
+ const apiKey = `wab_${environment}_${planPrefix}_${randomPart}`;
122
+ const keyId = 'kid_' + crypto.randomBytes(8).toString('hex');
123
+ const webhookSecret = 'whsec_' + crypto.randomBytes(24).toString('hex');
124
+
125
+ const keyRecord = {
126
+ key: apiKey, key_id: keyId, plan, plan_details: PLANS[plan],
127
+ owner, email, environment,
128
+ created_at: new Date().toISOString(),
129
+ expires_at: plan === 'FREE' ? new Date(Date.now() + 365 * 86400000).toISOString() : null,
130
+ last_used: null, active: true,
131
+ scopes: scopes.length > 0 ? scopes : this._defaultScopes(plan),
132
+ webhook_secret: webhookSecret, metadata, total_requests: 0,
133
+ };
134
+
135
+ keyStore.set(apiKey, keyRecord);
136
+ usageStore.set(apiKey, { today: 0, this_month: 0, total: 0, by_module: {}, by_day: {}, last_reset: new Date().toDateString() });
137
+
138
+ return {
139
+ api_key: apiKey, key_id: keyId, webhook_secret: webhookSecret, plan,
140
+ plan_details: { name: PLANS[plan].name, requests_per_day: PLANS[plan].requests_per_day, requests_per_minute: PLANS[plan].requests_per_minute, modules_allowed: PLANS[plan].modules_allowed },
141
+ created_at: keyRecord.created_at, expires_at: keyRecord.expires_at,
142
+ };
143
+ }
144
+
145
+ validate(apiKey, module = null) {
146
+ if (!apiKey) return { valid: false, error: 'API key is required', code: 'MISSING_KEY' };
147
+ const record = keyStore.get(apiKey);
148
+ if (!record) return { valid: false, error: 'Invalid API key', code: 'INVALID_KEY' };
149
+ if (!record.active) return { valid: false, error: 'API key has been revoked', code: 'REVOKED_KEY' };
150
+ if (record.expires_at && new Date(record.expires_at) < new Date()) {
151
+ return { valid: false, error: 'API key has expired', code: 'EXPIRED_KEY' };
152
+ }
153
+
154
+ if (module) {
155
+ const plan = PLANS[record.plan];
156
+ const hasAccess = plan.modules_allowed.includes('all') || plan.modules_allowed.includes(module);
157
+ if (!hasAccess) {
158
+ return { valid: false, error: `Module '${module}' not available on ${plan.name} plan`, code: 'INSUFFICIENT_PLAN',
159
+ upgrade_url: 'https://www.webagentbridge.com/#pricing', current_plan: plan.name, required_plan: this._getMinPlanForModule(module) };
160
+ }
161
+ }
162
+
163
+ const rateCheck = this._checkRateLimit(apiKey, record.plan);
164
+ if (!rateCheck.allowed) {
165
+ return { valid: false, error: 'Rate limit exceeded', code: 'RATE_LIMIT_EXCEEDED', retry_after_seconds: rateCheck.retry_after, limit: rateCheck.limit };
166
+ }
167
+
168
+ const usage = usageStore.get(apiKey);
169
+ this._resetDailyIfNeeded(apiKey, usage);
170
+ const plan = PLANS[record.plan];
171
+ if (usage.today >= plan.requests_per_day) {
172
+ return { valid: false, error: 'Daily quota exceeded', code: 'QUOTA_EXCEEDED', used: usage.today, limit: plan.requests_per_day, upgrade_url: 'https://www.webagentbridge.com/#pricing' };
173
+ }
174
+
175
+ this._recordUsage(apiKey, module);
176
+ return { valid: true, key_id: record.key_id, plan: record.plan, plan_name: plan.name, owner: record.owner, environment: record.environment, features: plan.features,
177
+ usage: { today: usage.today + 1, limit_today: plan.requests_per_day, remaining_today: plan.requests_per_day - usage.today - 1 } };
178
+ }
179
+
180
+ revoke(apiKey, reason = 'user_request') {
181
+ const record = keyStore.get(apiKey);
182
+ if (!record) return { success: false, error: 'Key not found' };
183
+ record.active = false; record.revoked_at = new Date().toISOString(); record.revoke_reason = reason;
184
+ return { success: true, message: 'Key revoked', revoked_at: record.revoked_at };
185
+ }
186
+
187
+ rotate(oldKey) {
188
+ const record = keyStore.get(oldKey);
189
+ if (!record) return { success: false, error: 'Key not found' };
190
+ this.revoke(oldKey, 'rotation');
191
+ return { success: true, ...this.generateKey({ plan: record.plan, owner: record.owner, email: record.email, environment: record.environment, metadata: { ...record.metadata, rotated_from: record.key_id } }) };
192
+ }
193
+
194
+ getUsage(apiKey) {
195
+ const record = keyStore.get(apiKey);
196
+ if (!record) return { error: 'Key not found' };
197
+ const usage = usageStore.get(apiKey) || {};
198
+ this._resetDailyIfNeeded(apiKey, usage);
199
+ const plan = PLANS[record.plan];
200
+ return { key_id: record.key_id, plan: record.plan, plan_name: plan.name, today: usage.today, this_month: usage.this_month, total: usage.total,
201
+ limit_per_day: plan.requests_per_day, limit_per_minute: plan.requests_per_minute, remaining_today: Math.max(0, plan.requests_per_day - usage.today),
202
+ by_module: usage.by_module, last_used: record.last_used, created_at: record.created_at };
203
+ }
204
+
205
+ listKeys(adminKey) {
206
+ const adminRecord = keyStore.get(adminKey);
207
+ if (!adminRecord || adminRecord.plan !== 'INTERNAL') return { error: 'Admin access required' };
208
+ return { total: keyStore.size, keys: Array.from(keyStore.values()).map(r => ({
209
+ key_id: r.key_id, plan: r.plan, owner: r.owner, email: r.email, environment: r.environment, active: r.active,
210
+ created_at: r.created_at, last_used: r.last_used, total_requests: r.total_requests || 0 })) };
211
+ }
212
+
213
+ getPlans() {
214
+ return Object.entries(PLANS).filter(([k]) => k !== 'INTERNAL').map(([key, plan]) => ({
215
+ id: key, name: plan.name, price_usd: plan.price_usd, requests_per_day: plan.requests_per_day,
216
+ requests_per_minute: plan.requests_per_minute, features: plan.features, support: plan.support }));
217
+ }
218
+
219
+ _checkRateLimit(apiKey, plan) {
220
+ const limit = PLANS[plan].requests_per_minute;
221
+ if (limit === Infinity) return { allowed: true };
222
+ const now = Date.now(); const window = 60000;
223
+ const rl = rateLimitStore.get(apiKey) || { count: 0, windowStart: now };
224
+ if (now - rl.windowStart > window) { rl.count = 0; rl.windowStart = now; }
225
+ if (rl.count >= limit) { return { allowed: false, retry_after: Math.ceil((rl.windowStart + window - now) / 1000), limit }; }
226
+ rl.count++; rateLimitStore.set(apiKey, rl);
227
+ return { allowed: true };
228
+ }
229
+
230
+ _recordUsage(apiKey, module) {
231
+ const record = keyStore.get(apiKey); const usage = usageStore.get(apiKey);
232
+ const today = new Date().toISOString().split('T')[0];
233
+ usage.today++; usage.this_month++; usage.total++;
234
+ if (module) usage.by_module[module] = (usage.by_module[module] || 0) + 1;
235
+ usage.by_day[today] = (usage.by_day[today] || 0) + 1;
236
+ record.last_used = new Date().toISOString();
237
+ record.total_requests = (record.total_requests || 0) + 1;
238
+ }
239
+
240
+ _resetDailyIfNeeded(apiKey, usage) {
241
+ const today = new Date().toDateString();
242
+ if (usage.last_reset !== today) { usage.today = 0; usage.last_reset = today; usageStore.set(apiKey, usage); }
243
+ }
244
+
245
+ _defaultScopes(plan) {
246
+ if (plan === 'FREE') return ['read'];
247
+ if (plan === 'PRO') return ['read', 'write'];
248
+ return ['read', 'write', 'admin'];
249
+ }
250
+
251
+ _getMinPlanForModule(module) {
252
+ const map = { 'agent-firewall': 'PRO', 'notary': 'BUSINESS', 'dark-pattern': 'FREE', 'bargaining': 'PRO', 'gov': 'BUSINESS', 'price': 'FREE', 'neural': 'PRO', 'protocol': 'FREE', 'bounty': 'FREE', 'affiliate': 'PRO' };
253
+ return map[module] || 'PRO';
254
+ }
255
+
256
+ _nextMidnight() {
257
+ const d = new Date(); d.setDate(d.getDate() + 1); d.setHours(0, 0, 0, 0); return d.toISOString();
258
+ }
259
+ }
260
+
261
+ module.exports = { WABKeyEngine, PLANS };
@@ -277,11 +277,10 @@ class RecipeExecutor {
277
277
  errors: [],
278
278
  };
279
279
 
280
- // Variable substitution in steps
280
+ // Variable substitution in steps — substitute in all string fields
281
281
  if (Object.keys(execution.variables).length > 0) {
282
282
  for (const step of execution.steps) {
283
- if (step.value) step.value = this._substituteVars(step.value, execution.variables);
284
- if (step.url) step.url = this._substituteVars(step.url, execution.variables);
283
+ this._substituteStepVars(step, execution.variables);
285
284
  }
286
285
  }
287
286
 
@@ -379,6 +378,23 @@ class RecipeExecutor {
379
378
  return str.replace(/\{\{(\w+)\}\}/g, (_, key) => vars[key] !== undefined ? String(vars[key]) : `{{${key}}}`);
380
379
  }
381
380
 
381
+ _substituteStepVars(step, vars) {
382
+ if (step.value) step.value = this._substituteVars(step.value, vars);
383
+ if (step.url) step.url = this._substituteVars(step.url, vars);
384
+ if (step.selector) step.selector = this._substituteVars(step.selector, vars);
385
+ if (step.description) step.description = this._substituteVars(step.description, vars);
386
+ if (step.fallback) {
387
+ if (step.fallback.text) step.fallback.text = this._substituteVars(step.fallback.text, vars);
388
+ if (step.fallback.xpath) step.fallback.xpath = this._substituteVars(step.fallback.xpath, vars);
389
+ if (step.fallback.ariaLabel) step.fallback.ariaLabel = this._substituteVars(step.fallback.ariaLabel, vars);
390
+ }
391
+ if (step.options && typeof step.options === 'object') {
392
+ for (const k of Object.keys(step.options)) {
393
+ if (typeof step.options[k] === 'string') step.options[k] = this._substituteVars(step.options[k], vars);
394
+ }
395
+ }
396
+ }
397
+
382
398
  getStats() {
383
399
  const execs = [...this.executions.values()];
384
400
  return {
@@ -447,6 +463,9 @@ class LfdEngine {
447
463
  stopRecording(sessionId) {
448
464
  const session = this.sessions.get(sessionId);
449
465
  if (!session) throw new Error('Recording session not found');
466
+ if (session.status !== 'recording' && session.status !== 'paused') {
467
+ throw new Error(`Cannot stop recording in state: ${session.status}`);
468
+ }
450
469
  session.complete();
451
470
 
452
471
  // Auto-convert to recipe
@@ -0,0 +1,93 @@
1
+ /**
2
+ * WAB Affiliate Intelligence (10-affiliate-intelligence) — PUBLIC API, PRIVATE DB
3
+ * Detects affiliate link manipulation and cookie stuffing.
4
+ * API is open, detection database is closed.
5
+ *
6
+ * Powered by WAB — Web Agent Bridge
7
+ * https://www.webagentbridge.com
8
+ */
9
+
10
+ 'use strict';
11
+
12
+ const crypto = require('crypto');
13
+ const url = require('url');
14
+
15
+ const scanStore = new Map();
16
+
17
+ let affiliateDb;
18
+ try { affiliateDb = require('./affiliate-db'); } catch { affiliateDb = null; }
19
+
20
+ const KNOWN_AFFILIATE_PARAMS = ['ref', 'aff', 'affiliate', 'partner', 'utm_source', 'tag', 'associate', 'clickid', 'subid', 'irclickid', 'gclid', 'fbclid'];
21
+ const COOKIE_STUFFING_INDICATORS = ['iframe[style*="display:none"]', 'iframe[width="0"]', 'img[src*="click"]', 'img[width="1"][height="1"]'];
22
+
23
+ function createRouter(express) {
24
+ const router = express.Router();
25
+
26
+ router.post('/scan-url', (req, res) => {
27
+ const { target_url } = req.body;
28
+ if (!target_url) return res.status(400).json({ error: 'target_url required' });
29
+
30
+ try {
31
+ const parsed = new URL(target_url);
32
+ const affiliateParams = [];
33
+ for (const [key, value] of parsed.searchParams) {
34
+ if (KNOWN_AFFILIATE_PARAMS.includes(key.toLowerCase())) {
35
+ affiliateParams.push({ param: key, value, type: 'affiliate_tracking' });
36
+ }
37
+ }
38
+
39
+ const hasRedirect = /\/(click|go|redirect|track|aff|out)\//i.test(parsed.pathname);
40
+ let manipulation = null;
41
+ if (affiliateDb) {
42
+ manipulation = affiliateDb.checkManipulation(target_url, affiliateParams);
43
+ }
44
+
45
+ const scanId = 'ASCAN-' + crypto.randomBytes(6).toString('hex').toUpperCase();
46
+ const result = {
47
+ scan_id: scanId, url: target_url, hostname: parsed.hostname,
48
+ affiliate_params: affiliateParams, has_affiliate: affiliateParams.length > 0,
49
+ has_redirect_chain: hasRedirect, manipulation_detected: manipulation,
50
+ risk_level: affiliateParams.length > 2 ? 'HIGH' : affiliateParams.length > 0 ? 'MEDIUM' : 'LOW',
51
+ scanned_at: new Date().toISOString(),
52
+ };
53
+ scanStore.set(scanId, result);
54
+ res.json(result);
55
+ } catch (e) {
56
+ res.status(400).json({ error: 'Invalid URL: ' + e.message });
57
+ }
58
+ });
59
+
60
+ router.post('/scan-html', (req, res) => {
61
+ const { html, page_url } = req.body;
62
+ if (!html) return res.status(400).json({ error: 'html content required' });
63
+
64
+ const findings = [];
65
+ for (const indicator of COOKIE_STUFFING_INDICATORS) {
66
+ const tag = indicator.split('[')[0];
67
+ const attrMatch = indicator.match(/\[([^\]]+)\]/g) || [];
68
+ if (new RegExp(`<${tag}[^>]*${attrMatch.map(a => a.slice(1, -1).replace('*', '.*')).join('[^>]*')}`, 'gi').test(html)) {
69
+ findings.push({ type: 'COOKIE_STUFFING', indicator, severity: 'HIGH' });
70
+ }
71
+ }
72
+
73
+ const hiddenIframes = (html.match(/<iframe[^>]*(?:display\s*:\s*none|width\s*=\s*["']?0|height\s*=\s*["']?0)[^>]*>/gi) || []).length;
74
+ const trackingPixels = (html.match(/<img[^>]*(?:width\s*=\s*["']?1["']?\s+height\s*=\s*["']?1|height\s*=\s*["']?1["']?\s+width\s*=\s*["']?1)[^>]*>/gi) || []).length;
75
+
76
+ res.json({
77
+ page_url: page_url || 'unknown', cookie_stuffing_indicators: findings,
78
+ hidden_iframes: hiddenIframes, tracking_pixels: trackingPixels,
79
+ risk_level: findings.length > 0 || hiddenIframes > 2 ? 'HIGH' : trackingPixels > 5 ? 'MEDIUM' : 'LOW',
80
+ scanned_at: new Date().toISOString(),
81
+ });
82
+ });
83
+
84
+ router.get('/stats', (req, res) => {
85
+ let high = 0, manipulations = 0;
86
+ for (const s of scanStore.values()) { if (s.risk_level === 'HIGH') high++; if (s.manipulation_detected) manipulations++; }
87
+ res.json({ total_scans: scanStore.size, high_risk: high, manipulations_detected: manipulations });
88
+ });
89
+
90
+ return router;
91
+ }
92
+
93
+ module.exports = { createRouter };
@@ -0,0 +1,90 @@
1
+ /**
2
+ * WAB Agent Firewall (01-agent-firewall) — PUBLIC API, PRIVATE DETECTION LOGIC
3
+ * Scans URLs and content for prompt injections, phishing, and dark patterns.
4
+ * API is open, deep detection rules are closed.
5
+ *
6
+ * Powered by WAB — Web Agent Bridge
7
+ * https://www.webagentbridge.com
8
+ */
9
+
10
+ 'use strict';
11
+
12
+ const crypto = require('crypto');
13
+
14
+ const BASIC_THREATS = [
15
+ /ignore\s+(all\s+)?previous\s+instructions/gi,
16
+ /you\s+are\s+now\s+in\s+developer\s+mode/gi,
17
+ /disregard\s+(your\s+)?(prior\s+|previous\s+)?instructions/gi,
18
+ /<\s*script[^>]*>.*?<\/\s*script\s*>/gis,
19
+ /transfer\s+\$?\d+.*?to\s+(?:wallet|account|address)/gi,
20
+ /data:text\/html.*base64/gi,
21
+ /javascript:void/gi,
22
+ ];
23
+
24
+ const MALICIOUS_DOMAINS = new Set([
25
+ 'paypa1.com', 'amaz0n.com', 'g00gle.com', 'faceb00k.com',
26
+ 'secure-paypal-login.com', 'amazon-security-alert.com',
27
+ ]);
28
+
29
+ let deepDetection;
30
+ try { deepDetection = require('./firewall-engine'); } catch { deepDetection = null; }
31
+
32
+ const scanLog = [];
33
+
34
+ function createRouter(express) {
35
+ const router = express.Router();
36
+
37
+ router.post('/scan', (req, res) => {
38
+ const { url: targetUrl, content, agent_id } = req.body;
39
+ const startTime = Date.now();
40
+
41
+ const urlThreats = [];
42
+ const contentThreats = [];
43
+ let riskScore = 0;
44
+
45
+ if (targetUrl) {
46
+ try {
47
+ const parsed = new URL(targetUrl);
48
+ const hostname = parsed.hostname.toLowerCase();
49
+ if (MALICIOUS_DOMAINS.has(hostname)) { urlThreats.push({ type: 'MALICIOUS_DOMAIN', severity: 'CRITICAL', detail: hostname }); riskScore += 40; }
50
+ if (/[^\x00-\x7F]/.test(hostname)) { urlThreats.push({ type: 'HOMOGRAPH_ATTACK', severity: 'HIGH', detail: hostname }); riskScore += 25; }
51
+ if (/(?:password|token|apikey|secret)=/i.test(targetUrl)) { urlThreats.push({ type: 'DATA_EXFILTRATION', severity: 'HIGH', detail: 'Sensitive params in URL' }); riskScore += 25; }
52
+ } catch { urlThreats.push({ type: 'INVALID_URL', severity: 'LOW' }); }
53
+ }
54
+
55
+ if (content && typeof content === 'string') {
56
+ for (const pattern of BASIC_THREATS) {
57
+ const matches = content.match(pattern);
58
+ if (matches) { contentThreats.push({ type: 'PROMPT_INJECTION', matches: matches.slice(0, 3), count: matches.length }); riskScore += 30; }
59
+ }
60
+ if (deepDetection) {
61
+ const deep = deepDetection.analyze(content, targetUrl);
62
+ contentThreats.push(...(deep.threats || []));
63
+ riskScore += deep.score || 0;
64
+ }
65
+ }
66
+
67
+ riskScore = Math.min(100, riskScore);
68
+ const verdict = riskScore === 0 ? 'CLEAN' : riskScore > 50 ? 'BLOCKED' : 'WARNING';
69
+ const scanId = crypto.randomBytes(8).toString('hex');
70
+
71
+ scanLog.push({ scan_id: scanId, url: targetUrl, verdict, risk_score: riskScore, timestamp: new Date().toISOString() });
72
+ if (scanLog.length > 5000) scanLog.splice(0, scanLog.length - 5000);
73
+
74
+ res.json({
75
+ scan_id: scanId, verdict, risk_score: riskScore,
76
+ url_threats: urlThreats, content_threats: contentThreats,
77
+ processing_time_ms: Date.now() - startTime, scanned_at: new Date().toISOString(),
78
+ });
79
+ });
80
+
81
+ router.get('/stats', (req, res) => {
82
+ let blocked = 0, warnings = 0;
83
+ for (const s of scanLog) { if (s.verdict === 'BLOCKED') blocked++; if (s.verdict === 'WARNING') warnings++; }
84
+ res.json({ total_scans: scanLog.length, blocked, warnings, clean: scanLog.length - blocked - warnings });
85
+ });
86
+
87
+ return router;
88
+ }
89
+
90
+ module.exports = { createRouter };
@@ -0,0 +1,89 @@
1
+ /**
2
+ * WAB Bounty Network (09-bounty-network) — PUBLIC API, PRIVATE VERIFICATION RULES
3
+ * Bug bounty and threat reporting network.
4
+ * Report interface is open, verification rules are closed.
5
+ *
6
+ * Powered by WAB — Web Agent Bridge
7
+ * https://www.webagentbridge.com
8
+ */
9
+
10
+ 'use strict';
11
+
12
+ const crypto = require('crypto');
13
+
14
+ const reportStore = new Map();
15
+ const rewardStore = new Map();
16
+
17
+ const CATEGORIES = ['dark_pattern', 'price_manipulation', 'fake_reviews', 'hidden_fees', 'data_harvesting', 'accessibility_violation', 'misleading_ads', 'forced_subscription'];
18
+ const SEVERITY_REWARDS = { LOW: 10, MEDIUM: 50, HIGH: 200, CRITICAL: 500 };
19
+
20
+ let verifyReport;
21
+ try { verifyReport = require('./bounty-verification'); } catch { verifyReport = null; }
22
+
23
+ function createRouter(express) {
24
+ const router = express.Router();
25
+
26
+ router.post('/report', (req, res) => {
27
+ const { platform, url: targetUrl, category, description, evidence_html, reporter_token } = req.body;
28
+ if (!platform || !targetUrl || !category || !description) {
29
+ return res.status(400).json({ error: 'platform, url, category, and description required' });
30
+ }
31
+ if (!CATEGORIES.includes(category)) {
32
+ return res.status(400).json({ error: `Invalid category. Valid: ${CATEGORIES.join(', ')}` });
33
+ }
34
+
35
+ const reportId = 'RPT-' + crypto.randomBytes(8).toString('hex').toUpperCase();
36
+ const reporterHash = crypto.createHmac('sha256', process.env.WAB_SECRET || 'wab-bounty-salt')
37
+ .update(reporter_token || crypto.randomBytes(16).toString('hex')).digest('hex').substring(0, 16);
38
+
39
+ const report = {
40
+ report_id: reportId, platform, url: targetUrl, category, description,
41
+ reporter_hash: reporterHash, severity: null, reward_usd: 0,
42
+ status: 'SUBMITTED', submitted_at: new Date().toISOString(),
43
+ verified: false, verification_notes: null,
44
+ };
45
+
46
+ if (verifyReport) {
47
+ const verification = verifyReport(report, evidence_html);
48
+ report.severity = verification.severity;
49
+ report.verified = verification.verified;
50
+ report.reward_usd = verification.verified ? (SEVERITY_REWARDS[verification.severity] || 0) : 0;
51
+ report.status = verification.verified ? 'VERIFIED' : 'PENDING_REVIEW';
52
+ } else {
53
+ report.status = 'PENDING_REVIEW';
54
+ }
55
+
56
+ reportStore.set(reportId, report);
57
+ res.status(201).json(report);
58
+ });
59
+
60
+ router.get('/report/:id', (req, res) => {
61
+ const report = reportStore.get(req.params.id);
62
+ if (!report) return res.status(404).json({ error: 'Report not found' });
63
+ res.json(report);
64
+ });
65
+
66
+ router.get('/categories', (req, res) => {
67
+ res.json({ categories: CATEGORIES, severity_rewards_usd: SEVERITY_REWARDS });
68
+ });
69
+
70
+ router.get('/leaderboard', (req, res) => {
71
+ const reporters = {};
72
+ for (const r of reportStore.values()) {
73
+ if (r.verified) { reporters[r.reporter_hash] = (reporters[r.reporter_hash] || 0) + r.reward_usd; }
74
+ }
75
+ const leaderboard = Object.entries(reporters).map(([hash, total]) => ({ reporter_hash: hash, total_rewards_usd: total }))
76
+ .sort((a, b) => b.total_rewards_usd - a.total_rewards_usd).slice(0, 20);
77
+ res.json({ leaderboard });
78
+ });
79
+
80
+ router.get('/stats', (req, res) => {
81
+ let verified = 0, totalReward = 0;
82
+ for (const r of reportStore.values()) { if (r.verified) { verified++; totalReward += r.reward_usd; } }
83
+ res.json({ total_reports: reportStore.size, verified_reports: verified, total_rewards_usd: totalReward, categories: CATEGORIES.length });
84
+ });
85
+
86
+ return router;
87
+ }
88
+
89
+ module.exports = { createRouter };