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,501 +1,850 @@
1
- /**
2
- * WAB Protocol HTTP Transport โ€” RESTful endpoints that implement the
3
- * WAB command protocol over HTTP for remote agents and the MCP adapter.
4
- *
5
- * Every command from the WAB spec (docs/SPEC.md ยง5) is accessible here
6
- * so agents that cannot run JavaScript in a browser can still interact
7
- * with WAB-enabled sites via standard HTTP requests.
8
- */
9
-
10
- const express = require('express');
11
- const router = express.Router();
12
- const crypto = require('crypto');
13
- const { findSiteById, findSiteByLicense, recordAnalytic, db } = require('../models/db');
14
- const { broadcastAnalytic } = require('../ws');
15
- const { wabAuthenticateLimiter, wabActionLimiter, searchLimiter } = require('../middleware/rateLimits');
16
- const { auditLog } = require('../services/security');
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
- }
33
-
34
- const WAB_VERSION = '1.2.0';
35
- const PROTOCOL_VERSION = '1.0';
36
-
37
- // โ”€โ”€โ”€ Session management โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
38
- const sessions = new Map();
39
- const SESSION_TTL = 3600_000;
40
-
41
- setInterval(() => {
42
- const now = Date.now();
43
- for (const [token, data] of sessions) {
44
- if (now > data.expiresAt) sessions.delete(token);
45
- }
46
- }, 300_000);
47
-
48
- function generateSessionToken() {
49
- const bytes = require('crypto').randomBytes(32);
50
- return bytes.toString('hex');
51
- }
52
-
53
- function requireSession(req, res, next) {
54
- const auth = req.get('Authorization');
55
- if (!auth || !auth.startsWith('Bearer ')) {
56
- return res.status(401).json({
57
- type: 'error',
58
- error: { code: 'auth_required', message: 'Bearer token required in Authorization header' }
59
- });
60
- }
61
- const token = auth.slice(7);
62
- const session = sessions.get(token);
63
- if (!session || Date.now() > session.expiresAt) {
64
- sessions.delete(token);
65
- return res.status(401).json({
66
- type: 'error',
67
- error: { code: 'session_expired', message: 'Session expired or invalid' }
68
- });
69
- }
70
- req.wabSession = session;
71
- next();
72
- }
73
-
74
- // โ”€โ”€โ”€ Helper: resolve site from request โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
75
- function resolveSite(req) {
76
- if (req.wabSession) return findSiteById.get(req.wabSession.siteId);
77
- const siteId = req.query.siteId || req.body?.siteId;
78
- if (siteId) return findSiteById.get(siteId);
79
- return null;
80
- }
81
-
82
- function parseSiteConfig(site) {
83
- try { return JSON.parse(site.config || '{}'); } catch (_) { return {}; }
84
- }
85
-
86
- function buildCommandResponse(id, result) {
87
- return { id: id || null, type: 'success', protocol: PROTOCOL_VERSION, result };
88
- }
89
-
90
- function buildErrorResponse(id, code, message) {
91
- return { id: id || null, type: 'error', protocol: PROTOCOL_VERSION, error: { code, message } };
92
- }
93
-
94
- // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
95
- // POST /api/wab/authenticate โ€” session token exchange
96
- // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
97
-
98
- router.post('/authenticate', wabAuthenticateLimiter, (req, res) => {
99
- try {
100
- const { siteId, apiKey, meta } = req.body;
101
- if (!siteId && !apiKey) {
102
- return res.status(400).json(buildErrorResponse(null, 'invalid_argument', 'siteId or apiKey required'));
103
- }
104
-
105
- let site;
106
- if (apiKey) {
107
- // Timing-safe API key lookup: hash the provided key and compare against stored hashes
108
- // to prevent timing attacks on the raw key comparison
109
- const allActive = db.prepare('SELECT * FROM sites WHERE active = 1 AND api_key IS NOT NULL').all();
110
- site = allActive.find(s => {
111
- if (!s.api_key) return false;
112
- const a = Buffer.from(s.api_key);
113
- const b = Buffer.from(apiKey);
114
- if (a.length !== b.length) return false;
115
- return crypto.timingSafeEqual(a, b);
116
- }) || null;
117
- } else {
118
- site = findSiteById.get(siteId);
119
- }
120
-
121
- if (!site) {
122
- auditLog({ actorType: 'agent', action: 'wab_auth_failed', details: { siteId }, ip: req.ip, outcome: 'denied', severity: 'warning' });
123
- return res.status(404).json(buildErrorResponse(null, 'not_found', 'Site not found or invalid credentials'));
124
- }
125
-
126
- const origin = req.get('origin') || '';
127
- if (origin) {
128
- try {
129
- const reqDomain = new URL(origin).hostname.replace(/^www\./, '');
130
- const siteDomain = site.domain.replace(/^www\./, '');
131
- const isProduction = process.env.NODE_ENV === 'production';
132
- const isLocalhost = reqDomain === 'localhost' || reqDomain === '127.0.0.1';
133
- if (reqDomain !== siteDomain && !(isLocalhost && !isProduction)) {
134
- return res.status(403).json(buildErrorResponse(null, 'origin_mismatch', 'Origin does not match site domain'));
135
- }
136
- } catch (_) {}
137
- }
138
-
139
- const token = generateSessionToken();
140
- sessions.set(token, {
141
- siteId: site.id,
142
- tier: site.tier,
143
- domain: site.domain,
144
- agentMeta: meta || {},
145
- createdAt: Date.now(),
146
- expiresAt: Date.now() + SESSION_TTL
147
- });
148
-
149
- res.json(buildCommandResponse(null, {
150
- authenticated: true,
151
- token,
152
- siteId: site.id,
153
- tier: site.tier,
154
- expiresIn: SESSION_TTL / 1000,
155
- permissions: parseSiteConfig(site).agentPermissions || {}
156
- }));
157
- } catch (err) {
158
- res.status(500).json(buildErrorResponse(null, 'internal', 'Authentication failed'));
159
- }
160
- });
161
-
162
- // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
163
- // GET /api/wab/discover โ€” full discovery document
164
- // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
165
-
166
- router.get('/discover', (req, res) => {
167
- try {
168
- const site = resolveSite(req);
169
- if (!site || !site.active) {
170
- const domain = (req.get('origin') ? new URL(req.get('origin')).hostname : req.get('host')?.split(':')[0]) || '';
171
- const byDomain = db.prepare(
172
- 'SELECT * FROM sites WHERE LOWER(REPLACE(domain, "www.", "")) = ? AND active = 1 LIMIT 1'
173
- ).get(domain.toLowerCase().replace(/^www\./, ''));
174
-
175
- if (!byDomain) {
176
- return res.status(404).json(buildErrorResponse(null, 'not_found', 'No WAB site found'));
177
- }
178
- return res.json(buildCommandResponse(null, buildDiscovery(byDomain)));
179
- }
180
- res.json(buildCommandResponse(null, buildDiscovery(site)));
181
- } catch (err) {
182
- res.status(500).json(buildErrorResponse(null, 'internal', 'Discovery failed'));
183
- }
184
- });
185
-
186
- // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
187
- // GET /api/wab/actions โ€” list actions
188
- // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
189
-
190
- router.get('/actions', (req, res) => {
191
- try {
192
- const site = resolveSite(req);
193
- if (!site) return res.status(400).json(buildErrorResponse(null, 'invalid_argument', 'siteId required'));
194
-
195
- const config = parseSiteConfig(site);
196
- const perms = config.agentPermissions || {};
197
- const category = req.query.category;
198
-
199
- const actions = Object.entries(perms)
200
- .filter(([, v]) => v)
201
- .map(([name]) => ({
202
- name,
203
- description: `Permission: ${name}`,
204
- trigger: name === 'click' ? 'click' : name === 'fillForms' ? 'fill_and_submit' : name === 'scroll' ? 'scroll' : 'api',
205
- category: name === 'navigate' ? 'navigation' : 'general',
206
- requiresAuth: ['apiAccess', 'automatedLogin', 'extractData'].includes(name)
207
- }));
208
-
209
- const filtered = category ? actions.filter(a => a.category === category) : actions;
210
-
211
- res.json(buildCommandResponse(req.query.id || null, { actions: filtered, total: filtered.length }));
212
- } catch (err) {
213
- res.status(500).json(buildErrorResponse(null, 'internal', 'Failed to list actions'));
214
- }
215
- });
216
-
217
- // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
218
- // POST /api/wab/actions/:name โ€” execute action (with tracking)
219
- // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
220
-
221
- router.post('/actions/:name', requireSession, wabActionLimiter, (req, res) => {
222
- try {
223
- const actionName = req.params.name;
224
- const site = findSiteById.get(req.wabSession.siteId);
225
- if (!site) return res.status(404).json(buildErrorResponse(req.body?.id, 'not_found', 'Site not found'));
226
-
227
- const config = parseSiteConfig(site);
228
- const perms = config.agentPermissions || {};
229
-
230
- const permMap = {
231
- click: 'click', fill_and_submit: 'fillForms', scroll: 'scroll',
232
- navigate: 'navigate', api: 'apiAccess', read: 'readContent', extract: 'extractData'
233
- };
234
- const requiredPerm = permMap[actionName] || actionName;
235
-
236
- if (!perms[requiredPerm] && !perms[actionName]) {
237
- return res.status(403).json(buildErrorResponse(req.body?.id, 'permission_denied',
238
- `Action "${actionName}" is not permitted by site configuration`));
239
- }
240
-
241
- recordAnalytic({
242
- siteId: site.id,
243
- actionName,
244
- agentId: req.wabSession.agentMeta?.name || 'mcp-agent',
245
- triggerType: 'wab_api',
246
- success: true,
247
- metadata: { params: req.body?.params || {}, transport: 'http' }
248
- });
249
-
250
- broadcastAnalytic(site.id, {
251
- actionName,
252
- agentId: req.wabSession.agentMeta?.name || 'mcp-agent',
253
- triggerType: 'wab_api',
254
- success: true
255
- });
256
-
257
- res.json(buildCommandResponse(req.body?.id, {
258
- success: true,
259
- action: actionName,
260
- siteId: site.id,
261
- executed_at: new Date().toISOString(),
262
- note: 'Server-side action recorded. For DOM interactions, use the bridge script in-browser.'
263
- }));
264
- } catch (err) {
265
- res.status(500).json(buildErrorResponse(req.body?.id, 'internal', 'Action execution failed'));
266
- }
267
- });
268
-
269
- // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
270
- // POST /api/wab/read โ€” read content (selector-based, requires in-browser)
271
- // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
272
-
273
- router.post('/read', requireSession, (req, res) => {
274
- try {
275
- const { selector, id } = req.body;
276
- if (!selector) {
277
- return res.status(400).json(buildErrorResponse(id, 'invalid_argument', 'selector is required'));
278
- }
279
-
280
- const site = findSiteById.get(req.wabSession.siteId);
281
- if (!site) return res.status(404).json(buildErrorResponse(id, 'not_found', 'Site not found'));
282
-
283
- const config = parseSiteConfig(site);
284
- if (!config.agentPermissions?.readContent) {
285
- return res.status(403).json(buildErrorResponse(id, 'permission_denied', 'readContent not enabled'));
286
- }
287
-
288
- recordAnalytic({
289
- siteId: site.id,
290
- actionName: 'readContent',
291
- agentId: req.wabSession.agentMeta?.name || 'mcp-agent',
292
- triggerType: 'wab_api',
293
- success: true,
294
- metadata: { selector, transport: 'http' }
295
- });
296
-
297
- res.json(buildCommandResponse(id, {
298
- success: true,
299
- selector,
300
- note: 'Content reading via HTTP returns metadata only. Use the bridge script in-browser or the noscript bridge for rendered content.',
301
- bridge_page: `/api/noscript/bridge/${site.id}`,
302
- noscript_endpoints: {
303
- pixel: `/api/noscript/pixel/${site.id}`,
304
- css: `/api/noscript/css/${site.id}`,
305
- bridge: `/api/noscript/bridge/${site.id}`
306
- }
307
- }));
308
- } catch (err) {
309
- res.status(500).json(buildErrorResponse(null, 'internal', 'Read failed'));
310
- }
311
- });
312
-
313
- // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
314
- // GET /api/wab/page-info โ€” get page/site metadata
315
- // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
316
-
317
- router.get('/page-info', (req, res) => {
318
- try {
319
- const site = resolveSite(req);
320
- if (!site) return res.status(400).json(buildErrorResponse(null, 'invalid_argument', 'siteId required'));
321
-
322
- const config = parseSiteConfig(site);
323
- const neutralityScore = calculateNeutralityScore(site);
324
-
325
- res.json(buildCommandResponse(req.query.id || null, {
326
- title: site.name,
327
- domain: site.domain,
328
- url: `https://${site.domain}`,
329
- tier: site.tier,
330
- bridgeVersion: WAB_VERSION,
331
- protocol: PROTOCOL_VERSION,
332
- permissions: config.agentPermissions || {},
333
- restrictions: config.restrictions || {},
334
- security: {
335
- sandboxActive: true,
336
- sessionRequired: true,
337
- originValidation: true,
338
- rateLimit: config.restrictions?.rateLimit?.maxCallsPerMinute || 60
339
- },
340
- fairness: {
341
- neutralityScore,
342
- isIndependent: false
343
- },
344
- endpoints: {
345
- discover: `/api/wab/discover?siteId=${site.id}`,
346
- actions: `/api/wab/actions?siteId=${site.id}`,
347
- authenticate: '/api/wab/authenticate',
348
- bridge: `/api/noscript/bridge/${site.id}`,
349
- discovery: `/api/discovery/${site.id}`
350
- }
351
- }));
352
- } catch (err) {
353
- res.status(500).json(buildErrorResponse(null, 'internal', 'Failed to get page info'));
354
- }
355
- });
356
-
357
- // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
358
- // GET /api/wab/search โ€” fairness-weighted search (MCP adapter uses this)
359
- // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
360
-
361
- router.get('/search', searchLimiter, (req, res) => {
362
- try {
363
- const query = req.query.q || '';
364
- const category = req.query.category || null;
365
- const limit = Math.min(parseInt(req.query.limit) || 10, 100);
366
-
367
- let sql = `
368
- SELECT s.*, d.category, d.tags, d.is_independent, d.commission_rate,
369
- d.direct_benefit, d.neutrality_score, d.trust_signature
370
- FROM wab_directory d
371
- JOIN sites s ON d.site_id = s.id AND s.active = 1
372
- WHERE d.listed = 1
373
- `;
374
- const params = [];
375
-
376
- if (category) {
377
- sql += ' AND d.category = ?';
378
- params.push(category);
379
- }
380
-
381
- sql += ' ORDER BY d.neutrality_score DESC LIMIT ?';
382
- params.push(limit * 3);
383
-
384
- const candidates = db.prepare(sql).all(...params);
385
- const results = fairnessWeightedSearch(query, candidates).slice(0, limit);
386
-
387
- res.json(buildCommandResponse(req.query.id || null, {
388
- query,
389
- total: results.length,
390
- fairness_applied: true,
391
- results: results.map(r => ({
392
- siteId: r.id,
393
- name: r.name,
394
- domain: r.domain,
395
- description: r.description || '',
396
- category: r.category || 'general',
397
- tier: r.tier,
398
- neutrality_score: r._neutralityScore,
399
- is_independent: r._isIndependent,
400
- relevance_score: r._relevance,
401
- fairness_boost: r._fairnessBoost,
402
- final_score: r._finalScore,
403
- endpoints: {
404
- discover: `/api/wab/discover?siteId=${r.id}`,
405
- actions: `/api/wab/actions?siteId=${r.id}`,
406
- bridge: `/api/noscript/bridge/${r.id}`
407
- }
408
- }))
409
- }));
410
- } catch (err) {
411
- res.status(500).json(buildErrorResponse(null, 'internal', 'Search failed'));
412
- }
413
- });
414
-
415
- // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
416
- // GET /api/wab/ping โ€” health check
417
- // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
418
-
419
- router.get('/ping', (_req, res) => {
420
- res.json(buildCommandResponse(null, {
421
- pong: true,
422
- version: WAB_VERSION,
423
- protocol: PROTOCOL_VERSION,
424
- timestamp: Date.now(),
425
- status: 'healthy'
426
- }));
427
- });
428
-
429
- // โ”€โ”€โ”€ Discovery document builder โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
430
-
431
- function buildDiscovery(site) {
432
- const config = parseSiteConfig(site);
433
- const perms = config.agentPermissions || {};
434
- const features = config.features || {};
435
-
436
- const commands = Object.entries(perms)
437
- .filter(([, v]) => v)
438
- .map(([name]) => ({
439
- name,
440
- trigger: name === 'click' ? 'click' : name === 'fillForms' ? 'fill_and_submit' : name === 'scroll' ? 'scroll' : 'api',
441
- requiresAuth: ['apiAccess', 'automatedLogin', 'extractData'].includes(name)
442
- }));
443
-
444
- const featureList = ['auto_discovery', 'noscript_fallback', 'wab_protocol_api'];
445
- if (features.advancedAnalytics) featureList.push('advanced_analytics');
446
- if (features.realTimeUpdates) featureList.push('real_time_updates');
447
-
448
- const dirEntry = db.prepare('SELECT * FROM wab_directory WHERE site_id = ?').get(site.id);
449
-
450
- return {
451
- wab_version: WAB_VERSION,
452
- protocol: PROTOCOL_VERSION,
453
- generated_at: new Date().toISOString(),
454
- provider: {
455
- name: site.name,
456
- domain: site.domain,
457
- category: dirEntry?.category || 'general',
458
- description: site.description || ''
459
- },
460
- capabilities: {
461
- commands,
462
- permissions: perms,
463
- tier: site.tier,
464
- transport: ['js_global', 'http', 'websocket'],
465
- features: featureList
466
- },
467
- agent_access: {
468
- bridge_script: '/script/ai-agent-bridge.js',
469
- api_base: '/api/wab',
470
- websocket: '/ws/analytics',
471
- noscript: `/api/noscript/bridge/${site.id}`,
472
- discovery: `/api/discovery/${site.id}`
473
- },
474
- fairness: {
475
- is_independent: dirEntry ? !!dirEntry.is_independent : false,
476
- commission_rate: dirEntry ? dirEntry.commission_rate : 0,
477
- direct_benefit: dirEntry ? (dirEntry.direct_benefit || '') : '',
478
- neutrality_score: calculateNeutralityScore(site)
479
- },
480
- security: {
481
- session_required: true,
482
- origin_validation: true,
483
- rate_limit: config.restrictions?.rateLimit?.maxCallsPerMinute || 60,
484
- sandbox: true
485
- },
486
- endpoints: {
487
- authenticate: '/api/wab/authenticate',
488
- discover: `/api/wab/discover?siteId=${site.id}`,
489
- actions: `/api/wab/actions?siteId=${site.id}`,
490
- execute: '/api/wab/actions/{actionName}',
491
- read: '/api/wab/read',
492
- page_info: `/api/wab/page-info?siteId=${site.id}`,
493
- search: '/api/wab/search',
494
- ping: '/api/wab/ping',
495
- token_exchange: '/api/license/token',
496
- bridge_page: `/api/noscript/bridge/${site.id}`
497
- }
498
- };
499
- }
500
-
501
- module.exports = router;
1
+ /**
2
+ * WAB Protocol HTTP Transport โ€” RESTful endpoints that implement the
3
+ * WAB command protocol over HTTP for remote agents and the MCP adapter.
4
+ *
5
+ * Every command from the WAB spec (docs/SPEC.md ยง5) is accessible here
6
+ * so agents that cannot run JavaScript in a browser can still interact
7
+ * with WAB-enabled sites via standard HTTP requests.
8
+ */
9
+
10
+ const express = require('express');
11
+ const router = express.Router();
12
+ const crypto = require('crypto');
13
+ const { findSiteById, findSiteByLicense, recordAnalytic, db } = require('../models/db');
14
+ const { broadcastAnalytic } = require('../ws');
15
+ const { wabAuthenticateLimiter, wabActionLimiter, searchLimiter } = require('../middleware/rateLimits');
16
+ const { auditLog } = require('../services/security');
17
+ const tokenScope = require('../security/token-scope');
18
+ const dryRun = require('../security/dry-run');
19
+ const humanGate = require('../security/human-gate');
20
+ const humanGateTransports = require('../security/human-gate-transports');
21
+ const humanGateRateLimit = require('../security/human-gate-rate-limit');
22
+ const intentEngine = require('../security/intent-engine');
23
+ const rollback = require('../security/rollback-store');
24
+
25
+ // Register built-in transports (webhook/email/console). Sites pick one
26
+ // via siteConfig.humanGate.transport โˆˆ {null, webhook, email, console}.
27
+ humanGateTransports.registerAll(humanGate);
28
+
29
+ // Fairness module is proprietary โ€” provide stubs when not available
30
+ let calculateNeutralityScore, fairnessWeightedSearch, getDirectoryListings, generateFairnessReport;
31
+ try {
32
+ ({
33
+ calculateNeutralityScore,
34
+ fairnessWeightedSearch,
35
+ getDirectoryListings,
36
+ generateFairnessReport
37
+ } = require('../services/fairness'));
38
+ } catch {
39
+ calculateNeutralityScore = () => ({ score: 0, label: 'unrated' });
40
+ fairnessWeightedSearch = (_q, candidates) => candidates;
41
+ getDirectoryListings = () => [];
42
+ generateFairnessReport = () => ({ status: 'unavailable' });
43
+ }
44
+
45
+ const WAB_VERSION = '1.2.0';
46
+ const PROTOCOL_VERSION = '1.0';
47
+
48
+ // โ”€โ”€โ”€ Session management โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
49
+ const sessions = new Map();
50
+ const SESSION_TTL = 3600_000;
51
+
52
+ setInterval(() => {
53
+ const now = Date.now();
54
+ for (const [token, data] of sessions) {
55
+ if (now > data.expiresAt) sessions.delete(token);
56
+ }
57
+ }, 300_000);
58
+
59
+ function generateSessionToken() {
60
+ const bytes = require('crypto').randomBytes(32);
61
+ return bytes.toString('hex');
62
+ }
63
+
64
+ function requireSession(req, res, next) {
65
+ const auth = req.get('Authorization');
66
+ if (!auth || !auth.startsWith('Bearer ')) {
67
+ return res.status(401).json({
68
+ type: 'error',
69
+ error: { code: 'auth_required', message: 'Bearer token required in Authorization header' }
70
+ });
71
+ }
72
+ const token = auth.slice(7);
73
+ const session = sessions.get(token);
74
+ if (!session || Date.now() > session.expiresAt) {
75
+ sessions.delete(token);
76
+ return res.status(401).json({
77
+ type: 'error',
78
+ error: { code: 'session_expired', message: 'Session expired or invalid' }
79
+ });
80
+ }
81
+ req.wabSession = session;
82
+ next();
83
+ }
84
+
85
+ // โ”€โ”€โ”€ Helper: resolve site from request โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
86
+ function resolveSite(req) {
87
+ if (req.wabSession) return findSiteById.get(req.wabSession.siteId);
88
+ const siteId = req.query.siteId || req.body?.siteId;
89
+ if (siteId) return findSiteById.get(siteId);
90
+ return null;
91
+ }
92
+
93
+ function parseSiteConfig(site) {
94
+ try { return JSON.parse(site.config || '{}'); } catch (_) { return {}; }
95
+ }
96
+
97
+ function buildCommandResponse(id, result) {
98
+ return { id: id || null, type: 'success', protocol: PROTOCOL_VERSION, result };
99
+ }
100
+
101
+ function buildErrorResponse(id, code, message, extra) {
102
+ const error = { code, message };
103
+ if (extra && typeof extra === 'object') Object.assign(error, extra);
104
+ return { id: id || null, type: 'error', protocol: PROTOCOL_VERSION, error };
105
+ }
106
+
107
+ // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
108
+ // POST /api/wab/authenticate โ€” session token exchange
109
+ // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
110
+
111
+ router.post('/authenticate', wabAuthenticateLimiter, (req, res) => {
112
+ try {
113
+ const { siteId, apiKey, meta, scope: requestedScope } = req.body;
114
+ if (!siteId && !apiKey) {
115
+ return res.status(400).json(buildErrorResponse(null, 'invalid_argument', 'siteId or apiKey required'));
116
+ }
117
+
118
+ // SPEC ยง8.7 โ€” parse caller-requested scope. Absent = legacy unscoped (admin/*).
119
+ let scope;
120
+ try {
121
+ scope = tokenScope.parseScope(requestedScope);
122
+ } catch (e) {
123
+ return res.status(400).json(buildErrorResponse(null, 'invalid_scope', e.message));
124
+ }
125
+
126
+ let site;
127
+ if (apiKey) {
128
+ // Timing-safe API key lookup: hash the provided key and compare against stored hashes
129
+ // to prevent timing attacks on the raw key comparison
130
+ const allActive = db.prepare('SELECT * FROM sites WHERE active = 1 AND api_key IS NOT NULL').all();
131
+ site = allActive.find(s => {
132
+ if (!s.api_key) return false;
133
+ const a = Buffer.from(s.api_key);
134
+ const b = Buffer.from(apiKey);
135
+ if (a.length !== b.length) return false;
136
+ return crypto.timingSafeEqual(a, b);
137
+ }) || null;
138
+ } else {
139
+ site = findSiteById.get(siteId);
140
+ }
141
+
142
+ if (!site) {
143
+ auditLog({ actorType: 'agent', action: 'wab_auth_failed', details: { siteId }, ip: req.ip, outcome: 'denied', severity: 'warning' });
144
+ return res.status(404).json(buildErrorResponse(null, 'not_found', 'Site not found or invalid credentials'));
145
+ }
146
+
147
+ const origin = req.get('origin') || '';
148
+ if (origin) {
149
+ try {
150
+ const reqDomain = new URL(origin).hostname.replace(/^www\./, '');
151
+ const siteDomain = site.domain.replace(/^www\./, '');
152
+ const isProduction = process.env.NODE_ENV === 'production';
153
+ const isLocalhost = reqDomain === 'localhost' || reqDomain === '127.0.0.1';
154
+ if (reqDomain !== siteDomain && !(isLocalhost && !isProduction)) {
155
+ return res.status(403).json(buildErrorResponse(null, 'origin_mismatch', 'Origin does not match site domain'));
156
+ }
157
+ } catch (_) {}
158
+ }
159
+
160
+ const token = generateSessionToken();
161
+ sessions.set(token, {
162
+ siteId: site.id,
163
+ tier: site.tier,
164
+ domain: site.domain,
165
+ agentMeta: meta || {},
166
+ scope,
167
+ createdAt: Date.now(),
168
+ expiresAt: Date.now() + SESSION_TTL
169
+ });
170
+
171
+ res.json(buildCommandResponse(null, {
172
+ authenticated: true,
173
+ token,
174
+ siteId: site.id,
175
+ tier: site.tier,
176
+ expiresIn: SESSION_TTL / 1000,
177
+ permissions: parseSiteConfig(site).agentPermissions || {},
178
+ scope: tokenScope.formatScope(scope)
179
+ }));
180
+ } catch (err) {
181
+ res.status(500).json(buildErrorResponse(null, 'internal', 'Authentication failed'));
182
+ }
183
+ });
184
+
185
+ // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
186
+ // GET /api/wab/discover โ€” full discovery document
187
+ // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
188
+
189
+ router.get('/discover', (req, res) => {
190
+ try {
191
+ const site = resolveSite(req);
192
+ if (!site || !site.active) {
193
+ const domain = (req.get('origin') ? new URL(req.get('origin')).hostname : req.get('host')?.split(':')[0]) || '';
194
+ const byDomain = db.prepare(
195
+ 'SELECT * FROM sites WHERE LOWER(REPLACE(domain, "www.", "")) = ? AND active = 1 LIMIT 1'
196
+ ).get(domain.toLowerCase().replace(/^www\./, ''));
197
+
198
+ if (!byDomain) {
199
+ return res.status(404).json(buildErrorResponse(null, 'not_found', 'No WAB site found'));
200
+ }
201
+ return res.json(buildCommandResponse(null, buildDiscovery(byDomain)));
202
+ }
203
+ res.json(buildCommandResponse(null, buildDiscovery(site)));
204
+ } catch (err) {
205
+ res.status(500).json(buildErrorResponse(null, 'internal', 'Discovery failed'));
206
+ }
207
+ });
208
+
209
+ // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
210
+ // GET /api/wab/actions โ€” list actions
211
+ // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
212
+
213
+ router.get('/actions', (req, res) => {
214
+ try {
215
+ const site = resolveSite(req);
216
+ if (!site) return res.status(400).json(buildErrorResponse(null, 'invalid_argument', 'siteId required'));
217
+
218
+ const config = parseSiteConfig(site);
219
+ const perms = config.agentPermissions || {};
220
+ const category = req.query.category;
221
+
222
+ const actions = Object.entries(perms)
223
+ .filter(([, v]) => v)
224
+ .map(([name]) => ({
225
+ name,
226
+ description: `Permission: ${name}`,
227
+ trigger: name === 'click' ? 'click' : name === 'fillForms' ? 'fill_and_submit' : name === 'scroll' ? 'scroll' : 'api',
228
+ category: name === 'navigate' ? 'navigation' : 'general',
229
+ requiresAuth: ['apiAccess', 'automatedLogin', 'extractData'].includes(name)
230
+ }));
231
+
232
+ const filtered = category ? actions.filter(a => a.category === category) : actions;
233
+
234
+ res.json(buildCommandResponse(req.query.id || null, { actions: filtered, total: filtered.length }));
235
+ } catch (err) {
236
+ res.status(500).json(buildErrorResponse(null, 'internal', 'Failed to list actions'));
237
+ }
238
+ });
239
+
240
+ // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
241
+ // POST /api/wab/actions/:name โ€” execute action (with tracking)
242
+ // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
243
+
244
+ router.post('/actions/:name', requireSession, wabActionLimiter, async (req, res) => {
245
+ try {
246
+ const actionName = req.params.name;
247
+ const site = findSiteById.get(req.wabSession.siteId);
248
+ if (!site) return res.status(404).json(buildErrorResponse(req.body?.id, 'not_found', 'Site not found'));
249
+
250
+ const config = parseSiteConfig(site);
251
+ const perms = config.agentPermissions || {};
252
+
253
+ // SPEC ยง8.7 โ€” token scope gate. Site config may declare
254
+ // `environment` ("production" by default), `destructiveActions[]`,
255
+ // and `nonDestructiveActions[]` to extend the default policy.
256
+ const sessionScope = req.wabSession.scope;
257
+ if (sessionScope) {
258
+ const decision = tokenScope.authorize(sessionScope, {
259
+ name: actionName,
260
+ env: config.environment || 'production',
261
+ resource: req.body?.resource,
262
+ action_kind: req.body?.action_kind,
263
+ }, config);
264
+ if (!decision.allowed) {
265
+ auditLog({
266
+ actorType: 'agent',
267
+ action: 'scope_denied',
268
+ details: { actionName, code: decision.code, reason: decision.reason, siteId: site.id },
269
+ ip: req.ip,
270
+ outcome: 'denied',
271
+ severity: 'warning',
272
+ });
273
+ return res.status(403).json(buildErrorResponse(
274
+ req.body?.id,
275
+ decision.code,
276
+ decision.reason
277
+ ));
278
+ }
279
+ }
280
+
281
+ const permMap = {
282
+ click: 'click', fill_and_submit: 'fillForms', scroll: 'scroll',
283
+ navigate: 'navigate', api: 'apiAccess', read: 'readContent', extract: 'extractData'
284
+ };
285
+ const requiredPerm = permMap[actionName] || actionName;
286
+
287
+ if (!perms[requiredPerm] && !perms[actionName]) {
288
+ return res.status(403).json(buildErrorResponse(req.body?.id, 'permission_denied',
289
+ `Action "${actionName}" is not permitted by site configuration`));
290
+ }
291
+
292
+ // SPEC ยง8.12 โ€” Intent Analysis Engine (Premium+ or opt-in).
293
+ const intentCfg = config.intentEngine || {};
294
+ const intentEnabled = intentCfg.enabled === false
295
+ ? false
296
+ : (intentCfg.enabled === true || ['premium', 'enterprise'].includes(String(site.tier || '').toLowerCase()));
297
+ let intentVerdict = null;
298
+ if (intentEnabled) {
299
+ intentVerdict = intentEngine.score({
300
+ actorId: req.wabSession?.agentMeta?.name || null,
301
+ sessionToken: req.get('Authorization')?.slice(7),
302
+ siteId: site.id,
303
+ actionName,
304
+ params: req.body?.params || {},
305
+ env: config.environment || 'production',
306
+ tier: site.tier,
307
+ }, config);
308
+ if (intentVerdict.required_gate === 'block') {
309
+ auditLog({
310
+ actorType: 'agent', action: 'intent_blocked',
311
+ details: { actionName, score: intentVerdict.score, reasons: intentVerdict.reasons, siteId: site.id },
312
+ ip: req.ip, outcome: 'blocked', severity: 'critical',
313
+ });
314
+ return res.status(403).json(buildErrorResponse(req.body?.id, 'INTENT_BLOCKED',
315
+ `Request blocked by intent analysis (score=${intentVerdict.score}, level=${intentVerdict.level}). Reasons: ${intentVerdict.reasons.join('; ')}`,
316
+ { intent: intentVerdict }));
317
+ }
318
+ }
319
+
320
+ // SPEC ยง8.10 โ€” Mandatory Dry-Run for destructive actions.
321
+ const intentForcesDryRun = intentVerdict && intentVerdict.required_gate === 'dry_run';
322
+ if (dryRun.requiresDryRun(actionName, config) || intentForcesDryRun) {
323
+ const dryFlag = req.body?.dry_run;
324
+ const planId = req.body?.plan_id;
325
+ const ctx = {
326
+ sessionToken: req.get('Authorization')?.slice(7),
327
+ siteId: site.id,
328
+ actionName,
329
+ params: req.body?.params || {},
330
+ };
331
+
332
+ if (dryFlag === true) {
333
+ // Generate a plan. The default simulator is conservative โ€” it
334
+ // surfaces what we know (action, params, target site) and marks
335
+ // reversible=false. Sites integrating with their own backend MAY
336
+ // override this via a server-side adapter.
337
+ const sim = {
338
+ would_affect: [`site:${site.id}`, `action:${actionName}`],
339
+ side_effects: [actionName],
340
+ reversible: false,
341
+ summary: `Would execute "${actionName}" on site ${site.domain} with the given params. ` +
342
+ 'No actual changes have been made. Confirm with dry_run:false + plan_id to proceed.',
343
+ };
344
+ const envelope = dryRun.createPlan(ctx, sim);
345
+ auditLog({
346
+ actorType: 'agent', action: 'dry_run_plan_created',
347
+ details: { actionName, planId: envelope.plan_id, siteId: site.id },
348
+ ip: req.ip, outcome: 'success', severity: 'info',
349
+ });
350
+ return res.json(buildCommandResponse(req.body?.id, envelope));
351
+ }
352
+
353
+ // dryFlag === false (or undefined) โ€” must consume a valid plan.
354
+ const consume = dryRun.consumePlan(planId, ctx);
355
+ if (!consume.ok) {
356
+ auditLog({
357
+ actorType: 'agent', action: 'dry_run_violation',
358
+ details: { actionName, code: consume.code, siteId: site.id },
359
+ ip: req.ip, outcome: 'denied', severity: 'warning',
360
+ });
361
+ return res.status(412).json(buildErrorResponse(req.body?.id, consume.code, consume.message));
362
+ }
363
+ }
364
+
365
+ // SPEC ยง8.11 โ€” Out-of-Band Human Gate (Pro+).
366
+ const intentForcesHumanGate = intentVerdict && intentVerdict.required_gate === 'human_gate';
367
+ if (humanGate.requiresHumanGate(actionName, config, site.tier) || intentForcesHumanGate) {
368
+ const hgCtx = {
369
+ sessionToken: req.get('Authorization')?.slice(7),
370
+ siteId: site.id,
371
+ actorId: req.wabSession?.agentMeta?.name || null,
372
+ actionName,
373
+ params: req.body?.params || {},
374
+ };
375
+ const confirmationId = req.body?.confirmation_id;
376
+ if (!confirmationId) {
377
+ const challenge = await humanGate.issueChallenge(hgCtx, { siteConfig: config });
378
+ auditLog({
379
+ actorType: 'agent', action: 'human_gate_issued',
380
+ details: { actionName, challenge_id: challenge.challenge_id, siteId: site.id, dispatched_to: challenge.dispatched_to },
381
+ ip: req.ip, outcome: 'success', severity: 'info',
382
+ });
383
+ return res.status(202).json(buildErrorResponse(req.body?.id, 'HUMAN_GATE_REQUIRED',
384
+ 'Out-of-band human approval required. Retry with confirmation_id once approved.', {
385
+ challenge_id: challenge.challenge_id,
386
+ expires_at: challenge.expires_at,
387
+ dispatched_to: challenge.dispatched_to,
388
+ }));
389
+ }
390
+ const hg = humanGate.consumeApproved(confirmationId, hgCtx);
391
+ if (!hg.ok) {
392
+ auditLog({
393
+ actorType: 'agent', action: 'human_gate_violation',
394
+ details: { actionName, code: hg.code, challenge_id: confirmationId, siteId: site.id },
395
+ ip: req.ip, outcome: 'denied', severity: 'warning',
396
+ });
397
+ const status = hg.code === 'HUMAN_GATE_PENDING' ? 425 : 403;
398
+ return res.status(status).json(buildErrorResponse(req.body?.id, hg.code, hg.message || hg.code));
399
+ }
400
+ }
401
+
402
+ // SPEC ยง8.13 โ€” Snapshot before execution (Enterprise or opt-in).
403
+ let snapshotId = null;
404
+ const snapshotsEnabled = (config.snapshots && config.snapshots.enabled === true) ||
405
+ String(site.tier || '').toLowerCase() === 'enterprise';
406
+ const isDestructiveExec = tokenScope.isDestructiveAction(actionName, config) ||
407
+ (intentVerdict && intentVerdict.verb_class === 'destructive');
408
+ if (snapshotsEnabled && isDestructiveExec) {
409
+ try {
410
+ const snap = rollback.recordSnapshot({
411
+ siteId: site.id,
412
+ actionName,
413
+ actorId: req.wabSession?.agentMeta?.name || null,
414
+ sessionToken: req.get('Authorization')?.slice(7),
415
+ params: req.body?.params || {},
416
+ }, {
417
+ // The default snapshot payload is metadata-only; site adapters
418
+ // override via their own pre-execution hook.
419
+ snapshot: { actionName, params: req.body?.params || {}, captured_at: new Date().toISOString() },
420
+ meta: { intent_score: intentVerdict?.score || null },
421
+ reversible: true,
422
+ });
423
+ snapshotId = snap.snapshot_id;
424
+ auditLog({
425
+ actorType: 'agent', action: 'snapshot_recorded',
426
+ details: { actionName, snapshot_id: snapshotId, siteId: site.id },
427
+ ip: req.ip, outcome: 'success', severity: 'info',
428
+ });
429
+ } catch (e) {
430
+ // Snapshot failure must NOT silently allow destructive actions.
431
+ auditLog({
432
+ actorType: 'agent', action: 'snapshot_failed',
433
+ details: { actionName, error: e.message, siteId: site.id },
434
+ ip: req.ip, outcome: 'error', severity: 'critical',
435
+ });
436
+ return res.status(500).json(buildErrorResponse(req.body?.id, 'SNAPSHOT_FAILED',
437
+ 'Could not record pre-action snapshot โ€” destructive action aborted for safety.'));
438
+ }
439
+ }
440
+
441
+ recordAnalytic({
442
+ siteId: site.id,
443
+ actionName,
444
+ agentId: req.wabSession.agentMeta?.name || 'mcp-agent',
445
+ triggerType: 'wab_api',
446
+ success: true,
447
+ metadata: { params: req.body?.params || {}, transport: 'http' }
448
+ });
449
+
450
+ broadcastAnalytic(site.id, {
451
+ actionName,
452
+ agentId: req.wabSession.agentMeta?.name || 'mcp-agent',
453
+ triggerType: 'wab_api',
454
+ success: true
455
+ });
456
+
457
+ res.json(buildCommandResponse(req.body?.id, {
458
+ success: true,
459
+ action: actionName,
460
+ siteId: site.id,
461
+ executed_at: new Date().toISOString(),
462
+ snapshot_id: snapshotId,
463
+ note: 'Server-side action recorded. For DOM interactions, use the bridge script in-browser.'
464
+ }));
465
+ } catch (err) {
466
+
467
+ res.status(500).json(buildErrorResponse(req.body?.id, 'internal', 'Action execution failed'));
468
+ }
469
+ });
470
+
471
+ // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
472
+ // POST /api/wab/read โ€” read content (selector-based, requires in-browser)
473
+ // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
474
+
475
+ router.post('/read', requireSession, (req, res) => {
476
+ try {
477
+ const { selector, id } = req.body;
478
+ if (!selector) {
479
+ return res.status(400).json(buildErrorResponse(id, 'invalid_argument', 'selector is required'));
480
+ }
481
+
482
+ const site = findSiteById.get(req.wabSession.siteId);
483
+ if (!site) return res.status(404).json(buildErrorResponse(id, 'not_found', 'Site not found'));
484
+
485
+ const config = parseSiteConfig(site);
486
+ if (!config.agentPermissions?.readContent) {
487
+ return res.status(403).json(buildErrorResponse(id, 'permission_denied', 'readContent not enabled'));
488
+ }
489
+
490
+ recordAnalytic({
491
+ siteId: site.id,
492
+ actionName: 'readContent',
493
+ agentId: req.wabSession.agentMeta?.name || 'mcp-agent',
494
+ triggerType: 'wab_api',
495
+ success: true,
496
+ metadata: { selector, transport: 'http' }
497
+ });
498
+
499
+ res.json(buildCommandResponse(id, {
500
+ success: true,
501
+ selector,
502
+ note: 'Content reading via HTTP returns metadata only. Use the bridge script in-browser or the noscript bridge for rendered content.',
503
+ bridge_page: `/api/noscript/bridge/${site.id}`,
504
+ noscript_endpoints: {
505
+ pixel: `/api/noscript/pixel/${site.id}`,
506
+ css: `/api/noscript/css/${site.id}`,
507
+ bridge: `/api/noscript/bridge/${site.id}`
508
+ }
509
+ }));
510
+ } catch (err) {
511
+ res.status(500).json(buildErrorResponse(null, 'internal', 'Read failed'));
512
+ }
513
+ });
514
+
515
+ // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
516
+ // GET /api/wab/page-info โ€” get page/site metadata
517
+ // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
518
+
519
+ router.get('/page-info', (req, res) => {
520
+ try {
521
+ const site = resolveSite(req);
522
+ if (!site) return res.status(400).json(buildErrorResponse(null, 'invalid_argument', 'siteId required'));
523
+
524
+ const config = parseSiteConfig(site);
525
+ const neutralityScore = calculateNeutralityScore(site);
526
+
527
+ res.json(buildCommandResponse(req.query.id || null, {
528
+ title: site.name,
529
+ domain: site.domain,
530
+ url: `https://${site.domain}`,
531
+ tier: site.tier,
532
+ bridgeVersion: WAB_VERSION,
533
+ protocol: PROTOCOL_VERSION,
534
+ permissions: config.agentPermissions || {},
535
+ restrictions: config.restrictions || {},
536
+ security: {
537
+ sandboxActive: true,
538
+ sessionRequired: true,
539
+ originValidation: true,
540
+ rateLimit: config.restrictions?.rateLimit?.maxCallsPerMinute || 60
541
+ },
542
+ fairness: {
543
+ neutralityScore,
544
+ isIndependent: false
545
+ },
546
+ endpoints: {
547
+ discover: `/api/wab/discover?siteId=${site.id}`,
548
+ actions: `/api/wab/actions?siteId=${site.id}`,
549
+ authenticate: '/api/wab/authenticate',
550
+ bridge: `/api/noscript/bridge/${site.id}`,
551
+ discovery: `/api/discovery/${site.id}`
552
+ }
553
+ }));
554
+ } catch (err) {
555
+ res.status(500).json(buildErrorResponse(null, 'internal', 'Failed to get page info'));
556
+ }
557
+ });
558
+
559
+ // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
560
+ // GET /api/wab/search โ€” fairness-weighted search (MCP adapter uses this)
561
+ // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
562
+
563
+ router.get('/search', searchLimiter, (req, res) => {
564
+ try {
565
+ const query = req.query.q || '';
566
+ const category = req.query.category || null;
567
+ const limit = Math.min(parseInt(req.query.limit) || 10, 100);
568
+
569
+ let sql = `
570
+ SELECT s.*, d.category, d.tags, d.is_independent, d.commission_rate,
571
+ d.direct_benefit, d.neutrality_score, d.trust_signature
572
+ FROM wab_directory d
573
+ JOIN sites s ON d.site_id = s.id AND s.active = 1
574
+ WHERE d.listed = 1
575
+ `;
576
+ const params = [];
577
+
578
+ if (category) {
579
+ sql += ' AND d.category = ?';
580
+ params.push(category);
581
+ }
582
+
583
+ sql += ' ORDER BY d.neutrality_score DESC LIMIT ?';
584
+ params.push(limit * 3);
585
+
586
+ const candidates = db.prepare(sql).all(...params);
587
+ const results = fairnessWeightedSearch(query, candidates).slice(0, limit);
588
+
589
+ res.json(buildCommandResponse(req.query.id || null, {
590
+ query,
591
+ total: results.length,
592
+ fairness_applied: true,
593
+ results: results.map(r => ({
594
+ siteId: r.id,
595
+ name: r.name,
596
+ domain: r.domain,
597
+ description: r.description || '',
598
+ category: r.category || 'general',
599
+ tier: r.tier,
600
+ neutrality_score: r._neutralityScore,
601
+ is_independent: r._isIndependent,
602
+ relevance_score: r._relevance,
603
+ fairness_boost: r._fairnessBoost,
604
+ final_score: r._finalScore,
605
+ endpoints: {
606
+ discover: `/api/wab/discover?siteId=${r.id}`,
607
+ actions: `/api/wab/actions?siteId=${r.id}`,
608
+ bridge: `/api/noscript/bridge/${r.id}`
609
+ }
610
+ }))
611
+ }));
612
+ } catch (err) {
613
+ res.status(500).json(buildErrorResponse(null, 'internal', 'Search failed'));
614
+ }
615
+ });
616
+
617
+ // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
618
+ // GET /api/wab/ping โ€” health check
619
+ // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
620
+
621
+ router.get('/ping', (_req, res) => {
622
+ res.json(buildCommandResponse(null, {
623
+ pong: true,
624
+ version: WAB_VERSION,
625
+ protocol: PROTOCOL_VERSION,
626
+ timestamp: Date.now(),
627
+ status: 'healthy'
628
+ }));
629
+ });
630
+
631
+ // โ”€โ”€โ”€ Discovery document builder โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
632
+
633
+ function buildDiscovery(site) {
634
+ const config = parseSiteConfig(site);
635
+ const perms = config.agentPermissions || {};
636
+ const features = config.features || {};
637
+
638
+ const commands = Object.entries(perms)
639
+ .filter(([, v]) => v)
640
+ .map(([name]) => ({
641
+ name,
642
+ trigger: name === 'click' ? 'click' : name === 'fillForms' ? 'fill_and_submit' : name === 'scroll' ? 'scroll' : 'api',
643
+ requiresAuth: ['apiAccess', 'automatedLogin', 'extractData'].includes(name)
644
+ }));
645
+
646
+ const featureList = ['auto_discovery', 'noscript_fallback', 'wab_protocol_api'];
647
+ if (features.advancedAnalytics) featureList.push('advanced_analytics');
648
+ if (features.realTimeUpdates) featureList.push('real_time_updates');
649
+
650
+ const dirEntry = db.prepare('SELECT * FROM wab_directory WHERE site_id = ?').get(site.id);
651
+
652
+ return {
653
+ wab_version: WAB_VERSION,
654
+ protocol: PROTOCOL_VERSION,
655
+ generated_at: new Date().toISOString(),
656
+ provider: {
657
+ name: site.name,
658
+ domain: site.domain,
659
+ category: dirEntry?.category || 'general',
660
+ description: site.description || ''
661
+ },
662
+ capabilities: {
663
+ commands,
664
+ permissions: perms,
665
+ tier: site.tier,
666
+ transport: ['js_global', 'http', 'websocket'],
667
+ features: featureList
668
+ },
669
+ agent_access: {
670
+ bridge_script: '/script/ai-agent-bridge.js',
671
+ api_base: '/api/wab',
672
+ websocket: '/ws/analytics',
673
+ noscript: `/api/noscript/bridge/${site.id}`,
674
+ discovery: `/api/discovery/${site.id}`
675
+ },
676
+ fairness: {
677
+ is_independent: dirEntry ? !!dirEntry.is_independent : false,
678
+ commission_rate: dirEntry ? dirEntry.commission_rate : 0,
679
+ direct_benefit: dirEntry ? (dirEntry.direct_benefit || '') : '',
680
+ neutrality_score: calculateNeutralityScore(site)
681
+ },
682
+ security: {
683
+ session_required: true,
684
+ origin_validation: true,
685
+ rate_limit: config.restrictions?.rateLimit?.maxCallsPerMinute || 60,
686
+ sandbox: true
687
+ },
688
+ endpoints: {
689
+ authenticate: '/api/wab/authenticate',
690
+ discover: `/api/wab/discover?siteId=${site.id}`,
691
+ actions: `/api/wab/actions?siteId=${site.id}`,
692
+ execute: '/api/wab/actions/{actionName}',
693
+ read: '/api/wab/read',
694
+ page_info: `/api/wab/page-info?siteId=${site.id}`,
695
+ search: '/api/wab/search',
696
+ ping: '/api/wab/ping',
697
+ token_exchange: '/api/license/token',
698
+ bridge_page: `/api/noscript/bridge/${site.id}`
699
+ }
700
+ };
701
+ }
702
+
703
+ // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
704
+ // SPEC ยง8.11 โ€” Out-of-Band Human Gate endpoints
705
+ // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
706
+
707
+ // Public-ish: anyone holding a valid challenge_id + 6-digit code can
708
+ // approve/reject. Rate-limit applies to brute-force the code (5 attempts
709
+ // per challenge enforced by the module).
710
+ router.post('/human-gate/approve', wabActionLimiter, (req, res) => {
711
+ try {
712
+ const { challenge_id, code } = req.body || {};
713
+ if (!challenge_id || !code) {
714
+ return res.status(400).json(buildErrorResponse(null, 'invalid_argument', 'challenge_id and code required'));
715
+ }
716
+ // SPEC ยง8.11 โ€” IP-level brute-force limiter (sliding window).
717
+ // Per-challenge 5-attempt lockout still applies inside humanGate.
718
+ const ipCheck = humanGateRateLimit.checkBeforeAttempt(req.ip);
719
+ if (!ipCheck.allowed) {
720
+ try {
721
+ auditLog({
722
+ actorType: 'user', action: 'human_gate_rate_limited',
723
+ details: { challenge_id, code: ipCheck.code, retry_after_ms: ipCheck.retry_after_ms },
724
+ ip: req.ip, outcome: 'denied', severity: 'warning',
725
+ });
726
+ } catch { /* audit failures must not block */ }
727
+ res.set('Retry-After', String(Math.ceil((ipCheck.retry_after_ms || 0) / 1000)));
728
+ return res.status(429).json(buildErrorResponse(null, ipCheck.code,
729
+ 'too many approval attempts from this IP; slow down', { retry_after_ms: ipCheck.retry_after_ms }));
730
+ }
731
+ const result = humanGate.approveChallenge(challenge_id, code);
732
+ humanGateRateLimit.recordAttempt(req.ip, !!result.ok);
733
+ try {
734
+ auditLog({
735
+ actorType: 'user', action: 'human_gate_approve_attempt',
736
+ details: { challenge_id, ok: result.ok, code: result.code },
737
+ ip: req.ip, outcome: result.ok ? 'success' : 'denied',
738
+ severity: result.ok ? 'info' : 'warning',
739
+ });
740
+ } catch (e) { /* audit failures must not block the security gate */ }
741
+ if (!result.ok) {
742
+ const status = result.code === 'HUMAN_GATE_NOT_FOUND' ? 404
743
+ : result.code === 'HUMAN_GATE_LOCKED' ? 429
744
+ : result.code === 'HUMAN_GATE_BAD_CODE' ? 401
745
+ : 400;
746
+ return res.status(status).json(buildErrorResponse(null, result.code, result.message || result.code));
747
+ }
748
+ return res.json({ type: 'success', protocol: PROTOCOL_VERSION, result: { status: result.status } });
749
+ } catch (err) {
750
+ return res.status(500).json(buildErrorResponse(null, 'internal', err.message));
751
+ }
752
+ });
753
+
754
+ router.post('/human-gate/reject', wabActionLimiter, (req, res) => {
755
+ const { challenge_id, reason } = req.body || {};
756
+ if (!challenge_id) {
757
+ return res.status(400).json(buildErrorResponse(null, 'invalid_argument', 'challenge_id required'));
758
+ }
759
+ const result = humanGate.rejectChallenge(challenge_id, reason);
760
+ auditLog({
761
+ actorType: 'user', action: 'human_gate_reject',
762
+ details: { challenge_id, ok: result.ok, code: result.code },
763
+ ip: req.ip, outcome: result.ok ? 'success' : 'denied', severity: 'info',
764
+ });
765
+ if (!result.ok) {
766
+ return res.status(result.code === 'HUMAN_GATE_NOT_FOUND' ? 404 : 400)
767
+ .json(buildErrorResponse(null, result.code, result.code));
768
+ }
769
+ return res.json({ type: 'success', protocol: PROTOCOL_VERSION, result: { status: result.status } });
770
+ });
771
+
772
+ router.get('/human-gate/:id/status', (req, res) => {
773
+ const status = humanGate.getStatus(req.params.id);
774
+ if (!status) {
775
+ return res.status(404).json(buildErrorResponse(null, 'HUMAN_GATE_NOT_FOUND', 'challenge not found'));
776
+ }
777
+ return res.json({ type: 'success', protocol: PROTOCOL_VERSION, result: status });
778
+ });
779
+
780
+ // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
781
+ // SPEC ยง8.13 โ€” Snapshot & Rollback admin endpoints
782
+ // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
783
+ //
784
+ // Auth: site owner authenticates with the site's apiKey via
785
+ // X-WAB-Site-Id + X-WAB-Api-Key headers (same secret used to issue
786
+ // bridge tokens). This is the operator's break-glass.
787
+ function _adminAuth(req, res) {
788
+ const siteId = req.get('X-WAB-Site-Id');
789
+ const apiKey = req.get('X-WAB-Api-Key');
790
+ if (!siteId || !apiKey) {
791
+ res.status(401).json(buildErrorResponse(null, 'auth_required', 'X-WAB-Site-Id and X-WAB-Api-Key required'));
792
+ return null;
793
+ }
794
+ const site = findSiteById.get(siteId);
795
+ if (!site || site.api_key !== apiKey) {
796
+ res.status(403).json(buildErrorResponse(null, 'forbidden', 'invalid site or api key'));
797
+ return null;
798
+ }
799
+ return site;
800
+ }
801
+
802
+ router.get('/admin/snapshots', (req, res) => {
803
+ const site = _adminAuth(req, res); if (!site) return;
804
+ try {
805
+ const list = rollback.listSnapshots(site.id, {
806
+ limit: parseInt(req.query.limit, 10) || 50,
807
+ status: req.query.status || undefined,
808
+ });
809
+ res.json({ type: 'success', protocol: PROTOCOL_VERSION, result: { snapshots: list } });
810
+ } catch (err) {
811
+ res.status(500).json(buildErrorResponse(null, 'internal', err.message));
812
+ }
813
+ });
814
+
815
+ router.get('/admin/snapshots/:id', (req, res) => {
816
+ const site = _adminAuth(req, res); if (!site) return;
817
+ const snap = rollback.getSnapshot(req.params.id);
818
+ if (!snap || snap.site_id !== site.id) {
819
+ return res.status(404).json(buildErrorResponse(null, 'SNAPSHOT_NOT_FOUND', 'snapshot not found'));
820
+ }
821
+ res.json({ type: 'success', protocol: PROTOCOL_VERSION, result: snap });
822
+ });
823
+
824
+ router.post('/admin/rollback/:id', async (req, res) => {
825
+ const site = _adminAuth(req, res); if (!site) return;
826
+ const snap = rollback.getSnapshot(req.params.id);
827
+ if (!snap || snap.site_id !== site.id) {
828
+ return res.status(404).json(buildErrorResponse(null, 'SNAPSHOT_NOT_FOUND', 'snapshot not found'));
829
+ }
830
+ try {
831
+ const result = await rollback.restoreSnapshot(req.params.id);
832
+ auditLog({
833
+ actorType: 'admin', action: 'snapshot_rollback_attempt',
834
+ details: { snapshot_id: req.params.id, site_id: site.id, ok: result.ok, code: result.code },
835
+ ip: req.ip, outcome: result.ok ? 'success' : 'denied',
836
+ severity: result.ok ? 'warning' : 'critical',
837
+ });
838
+ if (!result.ok) {
839
+ const status = result.code === 'SNAPSHOT_NOT_FOUND' ? 404
840
+ : result.code === 'NO_RESTORER' ? 503
841
+ : 409;
842
+ return res.status(status).json(buildErrorResponse(null, result.code, result.message || result.code));
843
+ }
844
+ res.json({ type: 'success', protocol: PROTOCOL_VERSION, result: { restored: true, snapshot_id: req.params.id } });
845
+ } catch (err) {
846
+ res.status(500).json(buildErrorResponse(null, 'internal', err.message));
847
+ }
848
+ });
849
+
850
+ module.exports = router;