web-agent-bridge 3.0.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 -21
  2. package/README.ar.md +1286 -1073
  3. package/README.md +1764 -1535
  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 +17 -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/ai-plugin.json +28 -0
  20. package/public/.well-known/security.txt +8 -0
  21. package/public/agent-workspace.html +349 -347
  22. package/public/ai.html +198 -196
  23. package/public/api.html +413 -0
  24. package/public/browser.html +486 -484
  25. package/public/commander-dashboard.html +243 -243
  26. package/public/cookies.html +210 -208
  27. package/public/css/agent-workspace.css +1713 -1713
  28. package/public/css/premium.css +317 -317
  29. package/public/css/styles.css +1235 -1235
  30. package/public/dashboard.html +706 -704
  31. package/public/demo.html +1770 -1
  32. package/public/dns.html +507 -0
  33. package/public/docs.html +587 -585
  34. package/public/feed.xml +89 -89
  35. package/public/growth.html +463 -0
  36. package/public/index.html +341 -9
  37. package/public/integrations.html +556 -0
  38. package/public/js/agent-workspace.js +1740 -1740
  39. package/public/js/auth-nav.js +31 -31
  40. package/public/js/auth-redirect.js +12 -12
  41. package/public/js/cookie-consent.js +56 -56
  42. package/public/js/wab-demo-page.js +721 -721
  43. package/public/js/ws-client.js +74 -74
  44. package/public/llms-full.txt +360 -309
  45. package/public/llms.txt +125 -86
  46. package/public/login.html +85 -83
  47. package/public/mesh-dashboard.html +328 -328
  48. package/public/openapi.json +580 -580
  49. package/public/phone-shield.html +281 -0
  50. package/public/premium-dashboard.html +2489 -2487
  51. package/public/premium.html +793 -791
  52. package/public/privacy.html +297 -295
  53. package/public/register.html +105 -103
  54. package/public/robots.txt +87 -87
  55. package/public/script/wab-consent.d.ts +36 -36
  56. package/public/script/wab-consent.js +104 -104
  57. package/public/script/wab-schema.js +131 -131
  58. package/public/script/wab.d.ts +108 -108
  59. package/public/script/wab.min.js +580 -580
  60. package/public/security.txt +8 -0
  61. package/public/terms.html +256 -254
  62. package/script/ai-agent-bridge.js +1754 -1754
  63. package/sdk/README.md +99 -99
  64. package/sdk/agent-mesh.js +449 -449
  65. package/sdk/commander.js +262 -262
  66. package/sdk/index.d.ts +464 -464
  67. package/sdk/index.js +18 -1
  68. package/sdk/multi-agent.js +318 -318
  69. package/sdk/package.json +12 -1
  70. package/sdk/safety-shield.js +219 -0
  71. package/sdk/schema-discovery.js +83 -83
  72. package/server/adapters/index.js +520 -520
  73. package/server/config/plans.js +367 -367
  74. package/server/config/secrets.js +102 -102
  75. package/server/control-plane/index.js +301 -301
  76. package/server/data-plane/index.js +354 -354
  77. package/server/index.js +175 -19
  78. package/server/llm/index.js +404 -404
  79. package/server/middleware/adminAuth.js +35 -35
  80. package/server/middleware/auth.js +50 -50
  81. package/server/middleware/featureGate.js +88 -88
  82. package/server/middleware/rateLimits.js +100 -100
  83. package/server/middleware/sensitiveAction.js +157 -0
  84. package/server/migrations/001_add_analytics_indexes.sql +7 -7
  85. package/server/migrations/002_premium_features.sql +418 -418
  86. package/server/migrations/003_ads_integer_cents.sql +33 -33
  87. package/server/migrations/004_agent_os.sql +158 -158
  88. package/server/migrations/005_marketplace_metering.sql +126 -126
  89. package/server/models/adapters/index.js +33 -33
  90. package/server/models/adapters/mysql.js +183 -183
  91. package/server/models/adapters/postgresql.js +172 -172
  92. package/server/models/adapters/sqlite.js +7 -7
  93. package/server/models/db.js +681 -681
  94. package/server/observability/failure-analysis.js +337 -337
  95. package/server/observability/index.js +394 -394
  96. package/server/protocol/capabilities.js +223 -223
  97. package/server/protocol/index.js +243 -243
  98. package/server/protocol/schema.js +584 -584
  99. package/server/registry/certification.js +271 -271
  100. package/server/registry/index.js +326 -326
  101. package/server/routes/admin-premium.js +671 -671
  102. package/server/routes/admin.js +261 -261
  103. package/server/routes/ads.js +130 -130
  104. package/server/routes/agent-workspace.js +540 -378
  105. package/server/routes/api.js +150 -150
  106. package/server/routes/auth.js +71 -71
  107. package/server/routes/billing.js +45 -45
  108. package/server/routes/commander.js +316 -316
  109. package/server/routes/demo-showcase.js +332 -0
  110. package/server/routes/demo-store.js +154 -0
  111. package/server/routes/discovery.js +417 -406
  112. package/server/routes/gateway.js +173 -0
  113. package/server/routes/license.js +251 -240
  114. package/server/routes/mesh.js +469 -469
  115. package/server/routes/noscript.js +543 -543
  116. package/server/routes/premium-v2.js +686 -686
  117. package/server/routes/premium.js +724 -724
  118. package/server/routes/runtime.js +2148 -2147
  119. package/server/routes/sovereign.js +465 -385
  120. package/server/routes/universal.js +200 -177
  121. package/server/routes/wab-api.js +850 -491
  122. package/server/runtime/container-worker.js +111 -111
  123. package/server/runtime/container.js +448 -448
  124. package/server/runtime/distributed-worker.js +362 -362
  125. package/server/runtime/event-bus.js +210 -210
  126. package/server/runtime/index.js +253 -253
  127. package/server/runtime/queue.js +599 -599
  128. package/server/runtime/replay.js +666 -666
  129. package/server/runtime/sandbox.js +266 -266
  130. package/server/runtime/scheduler.js +534 -534
  131. package/server/runtime/session-engine.js +293 -293
  132. package/server/runtime/state-manager.js +188 -188
  133. package/server/security/cross-site-redactor.js +196 -0
  134. package/server/security/dry-run.js +180 -0
  135. package/server/security/human-gate-rate-limit.js +147 -0
  136. package/server/security/human-gate-transports.js +178 -0
  137. package/server/security/human-gate.js +281 -0
  138. package/server/security/index.js +368 -368
  139. package/server/security/intent-engine.js +245 -0
  140. package/server/security/reward-guard.js +171 -0
  141. package/server/security/rollback-store.js +239 -0
  142. package/server/security/token-scope.js +404 -0
  143. package/server/security/url-policy.js +139 -0
  144. package/server/services/agent-chat.js +506 -506
  145. package/server/services/agent-learning.js +601 -575
  146. package/server/services/agent-memory.js +625 -625
  147. package/server/services/agent-mesh.js +555 -539
  148. package/server/services/agent-symphony.js +717 -717
  149. package/server/services/agent-tasks.js +1807 -1807
  150. package/server/services/api-key-engine.js +292 -0
  151. package/server/services/cluster.js +894 -894
  152. package/server/services/commander.js +738 -738
  153. package/server/services/edge-compute.js +440 -440
  154. package/server/services/email.js +204 -204
  155. package/server/services/hosted-runtime.js +205 -205
  156. package/server/services/lfd.js +635 -616
  157. package/server/services/local-ai.js +389 -389
  158. package/server/services/marketplace.js +270 -270
  159. package/server/services/metering.js +182 -182
  160. package/server/services/modules/affiliate-intelligence.js +93 -0
  161. package/server/services/modules/agent-firewall.js +90 -0
  162. package/server/services/modules/bounty.js +89 -0
  163. package/server/services/modules/collective-bargaining.js +92 -0
  164. package/server/services/modules/dark-pattern.js +66 -0
  165. package/server/services/modules/gov-intelligence.js +45 -0
  166. package/server/services/modules/neural.js +55 -0
  167. package/server/services/modules/notary.js +49 -0
  168. package/server/services/modules/price-time-machine.js +86 -0
  169. package/server/services/modules/protocol.js +104 -0
  170. package/server/services/negotiation.js +439 -439
  171. package/server/services/plugins.js +771 -771
  172. package/server/services/premium.js +1 -1
  173. package/server/services/price-intelligence.js +566 -565
  174. package/server/services/price-shield.js +1137 -1137
  175. package/server/services/reputation.js +465 -465
  176. package/server/services/search-engine.js +357 -357
  177. package/server/services/security.js +513 -513
  178. package/server/services/self-healing.js +843 -843
  179. package/server/services/sovereign-shield.js +542 -0
  180. package/server/services/stripe.js +192 -192
  181. package/server/services/swarm.js +788 -788
  182. package/server/services/universal-scraper.js +662 -661
  183. package/server/services/verification.js +481 -481
  184. package/server/services/vision.js +1163 -1163
  185. package/server/utils/cache.js +125 -125
  186. package/server/utils/migrate.js +81 -81
  187. package/server/utils/safe-fetch.js +228 -0
  188. package/server/utils/secureFields.js +50 -50
  189. package/server/ws.js +161 -161
  190. package/templates/artisan-marketplace.yaml +104 -104
  191. package/templates/book-price-scout.yaml +98 -98
  192. package/templates/electronics-price-tracker.yaml +108 -108
  193. package/templates/flight-deal-hunter.yaml +113 -113
  194. package/templates/freelancer-direct.yaml +116 -116
  195. package/templates/grocery-price-compare.yaml +93 -93
  196. package/templates/hotel-direct-booking.yaml +113 -113
  197. package/templates/local-services.yaml +98 -98
  198. package/templates/olive-oil-tunisia.yaml +88 -88
  199. package/templates/organic-farm-fresh.yaml +101 -101
  200. package/templates/restaurant-direct.yaml +97 -97
  201. package/server/services/fairness-engine.js +0 -409
  202. package/server/services/fairness.js +0 -420
@@ -1,491 +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
- const {
18
- calculateNeutralityScore,
19
- fairnessWeightedSearch,
20
- getDirectoryListings,
21
- generateFairnessReport
22
- } = require('../services/fairness');
23
-
24
- const WAB_VERSION = '1.2.0';
25
- const PROTOCOL_VERSION = '1.0';
26
-
27
- // โ”€โ”€โ”€ Session management โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
28
- const sessions = new Map();
29
- const SESSION_TTL = 3600_000;
30
-
31
- setInterval(() => {
32
- const now = Date.now();
33
- for (const [token, data] of sessions) {
34
- if (now > data.expiresAt) sessions.delete(token);
35
- }
36
- }, 300_000);
37
-
38
- function generateSessionToken() {
39
- const bytes = require('crypto').randomBytes(32);
40
- return bytes.toString('hex');
41
- }
42
-
43
- function requireSession(req, res, next) {
44
- const auth = req.get('Authorization');
45
- if (!auth || !auth.startsWith('Bearer ')) {
46
- return res.status(401).json({
47
- type: 'error',
48
- error: { code: 'auth_required', message: 'Bearer token required in Authorization header' }
49
- });
50
- }
51
- const token = auth.slice(7);
52
- const session = sessions.get(token);
53
- if (!session || Date.now() > session.expiresAt) {
54
- sessions.delete(token);
55
- return res.status(401).json({
56
- type: 'error',
57
- error: { code: 'session_expired', message: 'Session expired or invalid' }
58
- });
59
- }
60
- req.wabSession = session;
61
- next();
62
- }
63
-
64
- // โ”€โ”€โ”€ Helper: resolve site from request โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
65
- function resolveSite(req) {
66
- if (req.wabSession) return findSiteById.get(req.wabSession.siteId);
67
- const siteId = req.query.siteId || req.body?.siteId;
68
- if (siteId) return findSiteById.get(siteId);
69
- return null;
70
- }
71
-
72
- function parseSiteConfig(site) {
73
- try { return JSON.parse(site.config || '{}'); } catch (_) { return {}; }
74
- }
75
-
76
- function buildCommandResponse(id, result) {
77
- return { id: id || null, type: 'success', protocol: PROTOCOL_VERSION, result };
78
- }
79
-
80
- function buildErrorResponse(id, code, message) {
81
- return { id: id || null, type: 'error', protocol: PROTOCOL_VERSION, error: { code, message } };
82
- }
83
-
84
- // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
85
- // POST /api/wab/authenticate โ€” session token exchange
86
- // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
87
-
88
- router.post('/authenticate', wabAuthenticateLimiter, (req, res) => {
89
- try {
90
- const { siteId, apiKey, meta } = req.body;
91
- if (!siteId && !apiKey) {
92
- return res.status(400).json(buildErrorResponse(null, 'invalid_argument', 'siteId or apiKey required'));
93
- }
94
-
95
- let site;
96
- if (apiKey) {
97
- // Timing-safe API key lookup: hash the provided key and compare against stored hashes
98
- // to prevent timing attacks on the raw key comparison
99
- const allActive = db.prepare('SELECT * FROM sites WHERE active = 1 AND api_key IS NOT NULL').all();
100
- site = allActive.find(s => {
101
- if (!s.api_key) return false;
102
- const a = Buffer.from(s.api_key);
103
- const b = Buffer.from(apiKey);
104
- if (a.length !== b.length) return false;
105
- return crypto.timingSafeEqual(a, b);
106
- }) || null;
107
- } else {
108
- site = findSiteById.get(siteId);
109
- }
110
-
111
- if (!site) {
112
- auditLog({ actorType: 'agent', action: 'wab_auth_failed', details: { siteId }, ip: req.ip, outcome: 'denied', severity: 'warning' });
113
- return res.status(404).json(buildErrorResponse(null, 'not_found', 'Site not found or invalid credentials'));
114
- }
115
-
116
- const origin = req.get('origin') || '';
117
- if (origin) {
118
- try {
119
- const reqDomain = new URL(origin).hostname.replace(/^www\./, '');
120
- const siteDomain = site.domain.replace(/^www\./, '');
121
- const isProduction = process.env.NODE_ENV === 'production';
122
- const isLocalhost = reqDomain === 'localhost' || reqDomain === '127.0.0.1';
123
- if (reqDomain !== siteDomain && !(isLocalhost && !isProduction)) {
124
- return res.status(403).json(buildErrorResponse(null, 'origin_mismatch', 'Origin does not match site domain'));
125
- }
126
- } catch (_) {}
127
- }
128
-
129
- const token = generateSessionToken();
130
- sessions.set(token, {
131
- siteId: site.id,
132
- tier: site.tier,
133
- domain: site.domain,
134
- agentMeta: meta || {},
135
- createdAt: Date.now(),
136
- expiresAt: Date.now() + SESSION_TTL
137
- });
138
-
139
- res.json(buildCommandResponse(null, {
140
- authenticated: true,
141
- token,
142
- siteId: site.id,
143
- tier: site.tier,
144
- expiresIn: SESSION_TTL / 1000,
145
- permissions: parseSiteConfig(site).agentPermissions || {}
146
- }));
147
- } catch (err) {
148
- res.status(500).json(buildErrorResponse(null, 'internal', 'Authentication failed'));
149
- }
150
- });
151
-
152
- // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
153
- // GET /api/wab/discover โ€” full discovery document
154
- // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
155
-
156
- router.get('/discover', (req, res) => {
157
- try {
158
- const site = resolveSite(req);
159
- if (!site || !site.active) {
160
- const domain = (req.get('origin') ? new URL(req.get('origin')).hostname : req.get('host')?.split(':')[0]) || '';
161
- const byDomain = db.prepare(
162
- 'SELECT * FROM sites WHERE LOWER(REPLACE(domain, "www.", "")) = ? AND active = 1 LIMIT 1'
163
- ).get(domain.toLowerCase().replace(/^www\./, ''));
164
-
165
- if (!byDomain) {
166
- return res.status(404).json(buildErrorResponse(null, 'not_found', 'No WAB site found'));
167
- }
168
- return res.json(buildCommandResponse(null, buildDiscovery(byDomain)));
169
- }
170
- res.json(buildCommandResponse(null, buildDiscovery(site)));
171
- } catch (err) {
172
- res.status(500).json(buildErrorResponse(null, 'internal', 'Discovery failed'));
173
- }
174
- });
175
-
176
- // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
177
- // GET /api/wab/actions โ€” list actions
178
- // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
179
-
180
- router.get('/actions', (req, res) => {
181
- try {
182
- const site = resolveSite(req);
183
- if (!site) return res.status(400).json(buildErrorResponse(null, 'invalid_argument', 'siteId required'));
184
-
185
- const config = parseSiteConfig(site);
186
- const perms = config.agentPermissions || {};
187
- const category = req.query.category;
188
-
189
- const actions = Object.entries(perms)
190
- .filter(([, v]) => v)
191
- .map(([name]) => ({
192
- name,
193
- description: `Permission: ${name}`,
194
- trigger: name === 'click' ? 'click' : name === 'fillForms' ? 'fill_and_submit' : name === 'scroll' ? 'scroll' : 'api',
195
- category: name === 'navigate' ? 'navigation' : 'general',
196
- requiresAuth: ['apiAccess', 'automatedLogin', 'extractData'].includes(name)
197
- }));
198
-
199
- const filtered = category ? actions.filter(a => a.category === category) : actions;
200
-
201
- res.json(buildCommandResponse(req.query.id || null, { actions: filtered, total: filtered.length }));
202
- } catch (err) {
203
- res.status(500).json(buildErrorResponse(null, 'internal', 'Failed to list actions'));
204
- }
205
- });
206
-
207
- // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
208
- // POST /api/wab/actions/:name โ€” execute action (with tracking)
209
- // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
210
-
211
- router.post('/actions/:name', requireSession, wabActionLimiter, (req, res) => {
212
- try {
213
- const actionName = req.params.name;
214
- const site = findSiteById.get(req.wabSession.siteId);
215
- if (!site) return res.status(404).json(buildErrorResponse(req.body?.id, 'not_found', 'Site not found'));
216
-
217
- const config = parseSiteConfig(site);
218
- const perms = config.agentPermissions || {};
219
-
220
- const permMap = {
221
- click: 'click', fill_and_submit: 'fillForms', scroll: 'scroll',
222
- navigate: 'navigate', api: 'apiAccess', read: 'readContent', extract: 'extractData'
223
- };
224
- const requiredPerm = permMap[actionName] || actionName;
225
-
226
- if (!perms[requiredPerm] && !perms[actionName]) {
227
- return res.status(403).json(buildErrorResponse(req.body?.id, 'permission_denied',
228
- `Action "${actionName}" is not permitted by site configuration`));
229
- }
230
-
231
- recordAnalytic({
232
- siteId: site.id,
233
- actionName,
234
- agentId: req.wabSession.agentMeta?.name || 'mcp-agent',
235
- triggerType: 'wab_api',
236
- success: true,
237
- metadata: { params: req.body?.params || {}, transport: 'http' }
238
- });
239
-
240
- broadcastAnalytic(site.id, {
241
- actionName,
242
- agentId: req.wabSession.agentMeta?.name || 'mcp-agent',
243
- triggerType: 'wab_api',
244
- success: true
245
- });
246
-
247
- res.json(buildCommandResponse(req.body?.id, {
248
- success: true,
249
- action: actionName,
250
- siteId: site.id,
251
- executed_at: new Date().toISOString(),
252
- note: 'Server-side action recorded. For DOM interactions, use the bridge script in-browser.'
253
- }));
254
- } catch (err) {
255
- res.status(500).json(buildErrorResponse(req.body?.id, 'internal', 'Action execution failed'));
256
- }
257
- });
258
-
259
- // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
260
- // POST /api/wab/read โ€” read content (selector-based, requires in-browser)
261
- // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
262
-
263
- router.post('/read', requireSession, (req, res) => {
264
- try {
265
- const { selector, id } = req.body;
266
- if (!selector) {
267
- return res.status(400).json(buildErrorResponse(id, 'invalid_argument', 'selector is required'));
268
- }
269
-
270
- const site = findSiteById.get(req.wabSession.siteId);
271
- if (!site) return res.status(404).json(buildErrorResponse(id, 'not_found', 'Site not found'));
272
-
273
- const config = parseSiteConfig(site);
274
- if (!config.agentPermissions?.readContent) {
275
- return res.status(403).json(buildErrorResponse(id, 'permission_denied', 'readContent not enabled'));
276
- }
277
-
278
- recordAnalytic({
279
- siteId: site.id,
280
- actionName: 'readContent',
281
- agentId: req.wabSession.agentMeta?.name || 'mcp-agent',
282
- triggerType: 'wab_api',
283
- success: true,
284
- metadata: { selector, transport: 'http' }
285
- });
286
-
287
- res.json(buildCommandResponse(id, {
288
- success: true,
289
- selector,
290
- note: 'Content reading via HTTP returns metadata only. Use the bridge script in-browser or the noscript bridge for rendered content.',
291
- bridge_page: `/api/noscript/bridge/${site.id}`,
292
- noscript_endpoints: {
293
- pixel: `/api/noscript/pixel/${site.id}`,
294
- css: `/api/noscript/css/${site.id}`,
295
- bridge: `/api/noscript/bridge/${site.id}`
296
- }
297
- }));
298
- } catch (err) {
299
- res.status(500).json(buildErrorResponse(null, 'internal', 'Read failed'));
300
- }
301
- });
302
-
303
- // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
304
- // GET /api/wab/page-info โ€” get page/site metadata
305
- // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
306
-
307
- router.get('/page-info', (req, res) => {
308
- try {
309
- const site = resolveSite(req);
310
- if (!site) return res.status(400).json(buildErrorResponse(null, 'invalid_argument', 'siteId required'));
311
-
312
- const config = parseSiteConfig(site);
313
- const neutralityScore = calculateNeutralityScore(site);
314
-
315
- res.json(buildCommandResponse(req.query.id || null, {
316
- title: site.name,
317
- domain: site.domain,
318
- url: `https://${site.domain}`,
319
- tier: site.tier,
320
- bridgeVersion: WAB_VERSION,
321
- protocol: PROTOCOL_VERSION,
322
- permissions: config.agentPermissions || {},
323
- restrictions: config.restrictions || {},
324
- security: {
325
- sandboxActive: true,
326
- sessionRequired: true,
327
- originValidation: true,
328
- rateLimit: config.restrictions?.rateLimit?.maxCallsPerMinute || 60
329
- },
330
- fairness: {
331
- neutralityScore,
332
- isIndependent: false
333
- },
334
- endpoints: {
335
- discover: `/api/wab/discover?siteId=${site.id}`,
336
- actions: `/api/wab/actions?siteId=${site.id}`,
337
- authenticate: '/api/wab/authenticate',
338
- bridge: `/api/noscript/bridge/${site.id}`,
339
- discovery: `/api/discovery/${site.id}`
340
- }
341
- }));
342
- } catch (err) {
343
- res.status(500).json(buildErrorResponse(null, 'internal', 'Failed to get page info'));
344
- }
345
- });
346
-
347
- // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
348
- // GET /api/wab/search โ€” fairness-weighted search (MCP adapter uses this)
349
- // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
350
-
351
- router.get('/search', searchLimiter, (req, res) => {
352
- try {
353
- const query = req.query.q || '';
354
- const category = req.query.category || null;
355
- const limit = Math.min(parseInt(req.query.limit) || 10, 100);
356
-
357
- let sql = `
358
- SELECT s.*, d.category, d.tags, d.is_independent, d.commission_rate,
359
- d.direct_benefit, d.neutrality_score, d.trust_signature
360
- FROM wab_directory d
361
- JOIN sites s ON d.site_id = s.id AND s.active = 1
362
- WHERE d.listed = 1
363
- `;
364
- const params = [];
365
-
366
- if (category) {
367
- sql += ' AND d.category = ?';
368
- params.push(category);
369
- }
370
-
371
- sql += ' ORDER BY d.neutrality_score DESC LIMIT ?';
372
- params.push(limit * 3);
373
-
374
- const candidates = db.prepare(sql).all(...params);
375
- const results = fairnessWeightedSearch(query, candidates).slice(0, limit);
376
-
377
- res.json(buildCommandResponse(req.query.id || null, {
378
- query,
379
- total: results.length,
380
- fairness_applied: true,
381
- results: results.map(r => ({
382
- siteId: r.id,
383
- name: r.name,
384
- domain: r.domain,
385
- description: r.description || '',
386
- category: r.category || 'general',
387
- tier: r.tier,
388
- neutrality_score: r._neutralityScore,
389
- is_independent: r._isIndependent,
390
- relevance_score: r._relevance,
391
- fairness_boost: r._fairnessBoost,
392
- final_score: r._finalScore,
393
- endpoints: {
394
- discover: `/api/wab/discover?siteId=${r.id}`,
395
- actions: `/api/wab/actions?siteId=${r.id}`,
396
- bridge: `/api/noscript/bridge/${r.id}`
397
- }
398
- }))
399
- }));
400
- } catch (err) {
401
- res.status(500).json(buildErrorResponse(null, 'internal', 'Search failed'));
402
- }
403
- });
404
-
405
- // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
406
- // GET /api/wab/ping โ€” health check
407
- // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
408
-
409
- router.get('/ping', (_req, res) => {
410
- res.json(buildCommandResponse(null, {
411
- pong: true,
412
- version: WAB_VERSION,
413
- protocol: PROTOCOL_VERSION,
414
- timestamp: Date.now(),
415
- status: 'healthy'
416
- }));
417
- });
418
-
419
- // โ”€โ”€โ”€ Discovery document builder โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
420
-
421
- function buildDiscovery(site) {
422
- const config = parseSiteConfig(site);
423
- const perms = config.agentPermissions || {};
424
- const features = config.features || {};
425
-
426
- const commands = Object.entries(perms)
427
- .filter(([, v]) => v)
428
- .map(([name]) => ({
429
- name,
430
- trigger: name === 'click' ? 'click' : name === 'fillForms' ? 'fill_and_submit' : name === 'scroll' ? 'scroll' : 'api',
431
- requiresAuth: ['apiAccess', 'automatedLogin', 'extractData'].includes(name)
432
- }));
433
-
434
- const featureList = ['auto_discovery', 'noscript_fallback', 'wab_protocol_api'];
435
- if (features.advancedAnalytics) featureList.push('advanced_analytics');
436
- if (features.realTimeUpdates) featureList.push('real_time_updates');
437
-
438
- const dirEntry = db.prepare('SELECT * FROM wab_directory WHERE site_id = ?').get(site.id);
439
-
440
- return {
441
- wab_version: WAB_VERSION,
442
- protocol: PROTOCOL_VERSION,
443
- generated_at: new Date().toISOString(),
444
- provider: {
445
- name: site.name,
446
- domain: site.domain,
447
- category: dirEntry?.category || 'general',
448
- description: site.description || ''
449
- },
450
- capabilities: {
451
- commands,
452
- permissions: perms,
453
- tier: site.tier,
454
- transport: ['js_global', 'http', 'websocket'],
455
- features: featureList
456
- },
457
- agent_access: {
458
- bridge_script: '/script/ai-agent-bridge.js',
459
- api_base: '/api/wab',
460
- websocket: '/ws/analytics',
461
- noscript: `/api/noscript/bridge/${site.id}`,
462
- discovery: `/api/discovery/${site.id}`
463
- },
464
- fairness: {
465
- is_independent: dirEntry ? !!dirEntry.is_independent : false,
466
- commission_rate: dirEntry ? dirEntry.commission_rate : 0,
467
- direct_benefit: dirEntry ? (dirEntry.direct_benefit || '') : '',
468
- neutrality_score: calculateNeutralityScore(site)
469
- },
470
- security: {
471
- session_required: true,
472
- origin_validation: true,
473
- rate_limit: config.restrictions?.rateLimit?.maxCallsPerMinute || 60,
474
- sandbox: true
475
- },
476
- endpoints: {
477
- authenticate: '/api/wab/authenticate',
478
- discover: `/api/wab/discover?siteId=${site.id}`,
479
- actions: `/api/wab/actions?siteId=${site.id}`,
480
- execute: '/api/wab/actions/{actionName}',
481
- read: '/api/wab/read',
482
- page_info: `/api/wab/page-info?siteId=${site.id}`,
483
- search: '/api/wab/search',
484
- ping: '/api/wab/ping',
485
- token_exchange: '/api/license/token',
486
- bridge_page: `/api/noscript/bridge/${site.id}`
487
- }
488
- };
489
- }
490
-
491
- 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;