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,771 +1,771 @@
1
- 'use strict';
2
-
3
- const crypto = require('crypto');
4
- const { db } = require('../models/db');
5
-
6
- // ─── Schema Creation ──────────────────────────────────────────────────
7
-
8
- db.exec(`
9
- CREATE TABLE IF NOT EXISTS plugin_registry (
10
- id TEXT PRIMARY KEY,
11
- name TEXT UNIQUE NOT NULL,
12
- version TEXT,
13
- author TEXT,
14
- description TEXT,
15
- category TEXT,
16
- entry_point TEXT,
17
- hooks TEXT DEFAULT '[]',
18
- config_schema TEXT DEFAULT '{}',
19
- icon TEXT,
20
- downloads INTEGER DEFAULT 0,
21
- rating REAL DEFAULT 0,
22
- rating_count INTEGER DEFAULT 0,
23
- enabled INTEGER DEFAULT 1,
24
- is_official INTEGER DEFAULT 0,
25
- created_at TEXT DEFAULT (datetime('now')),
26
- updated_at TEXT DEFAULT (datetime('now'))
27
- );
28
-
29
- CREATE TABLE IF NOT EXISTS plugin_installations (
30
- id TEXT PRIMARY KEY,
31
- plugin_id TEXT NOT NULL,
32
- site_id TEXT NOT NULL,
33
- user_id TEXT,
34
- config TEXT DEFAULT '{}',
35
- enabled INTEGER DEFAULT 1,
36
- installed_at TEXT DEFAULT (datetime('now')),
37
- updated_at TEXT DEFAULT (datetime('now')),
38
- UNIQUE(plugin_id, site_id)
39
- );
40
-
41
- CREATE TABLE IF NOT EXISTS plugin_hooks (
42
- id TEXT PRIMARY KEY,
43
- plugin_id TEXT NOT NULL,
44
- hook_name TEXT NOT NULL,
45
- handler TEXT NOT NULL,
46
- priority INTEGER DEFAULT 10,
47
- created_at TEXT DEFAULT (datetime('now'))
48
- );
49
-
50
- CREATE TABLE IF NOT EXISTS hook_executions (
51
- id TEXT PRIMARY KEY,
52
- hook_name TEXT NOT NULL,
53
- plugin_id TEXT,
54
- site_id TEXT,
55
- input TEXT DEFAULT '{}',
56
- output TEXT DEFAULT '{}',
57
- duration_ms INTEGER,
58
- success INTEGER,
59
- error TEXT,
60
- executed_at TEXT DEFAULT (datetime('now'))
61
- );
62
-
63
- CREATE INDEX IF NOT EXISTS idx_plugin_registry_category ON plugin_registry(category);
64
- CREATE INDEX IF NOT EXISTS idx_plugin_registry_name ON plugin_registry(name);
65
- CREATE INDEX IF NOT EXISTS idx_plugin_installations_site ON plugin_installations(site_id);
66
- CREATE INDEX IF NOT EXISTS idx_plugin_installations_plugin ON plugin_installations(plugin_id);
67
- CREATE INDEX IF NOT EXISTS idx_plugin_hooks_plugin ON plugin_hooks(plugin_id);
68
- CREATE INDEX IF NOT EXISTS idx_plugin_hooks_hook_name ON plugin_hooks(hook_name);
69
- CREATE INDEX IF NOT EXISTS idx_hook_executions_site ON hook_executions(site_id);
70
- CREATE INDEX IF NOT EXISTS idx_hook_executions_hook ON hook_executions(hook_name);
71
- CREATE INDEX IF NOT EXISTS idx_hook_executions_executed ON hook_executions(executed_at);
72
- `);
73
-
74
- // ─── Prepared Statements ──────────────────────────────────────────────
75
-
76
- const stmts = {
77
- insertPlugin: db.prepare(`
78
- INSERT INTO plugin_registry (id, name, version, author, description, category, entry_point, hooks, config_schema, icon, is_official, created_at, updated_at)
79
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'), datetime('now'))
80
- `),
81
- getPlugin: db.prepare(`SELECT * FROM plugin_registry WHERE id = ?`),
82
- getPluginByName: db.prepare(`SELECT * FROM plugin_registry WHERE name = ?`),
83
- insertInstallation: db.prepare(`
84
- INSERT INTO plugin_installations (id, plugin_id, site_id, user_id, config, enabled, installed_at, updated_at)
85
- VALUES (?, ?, ?, ?, ?, 1, datetime('now'), datetime('now'))
86
- ON CONFLICT(plugin_id, site_id) DO UPDATE SET
87
- user_id = excluded.user_id,
88
- config = excluded.config,
89
- enabled = 1,
90
- updated_at = datetime('now')
91
- `),
92
- deleteInstallation: db.prepare(`DELETE FROM plugin_installations WHERE plugin_id = ? AND site_id = ?`),
93
- getInstallation: db.prepare(`SELECT * FROM plugin_installations WHERE id = ?`),
94
- updateInstallationConfig: db.prepare(`UPDATE plugin_installations SET config = ?, updated_at = datetime('now') WHERE id = ?`),
95
- getInstalledPlugins: db.prepare(`
96
- SELECT pi.*, pr.name, pr.version, pr.author, pr.description, pr.category, pr.icon, pr.hooks as plugin_hooks, pr.config_schema, pr.rating, pr.rating_count, pr.downloads, pr.is_official
97
- FROM plugin_installations pi
98
- JOIN plugin_registry pr ON pi.plugin_id = pr.id
99
- WHERE pi.site_id = ? AND pi.enabled = 1 AND pr.enabled = 1
100
- ORDER BY pr.name
101
- `),
102
- insertHook: db.prepare(`
103
- INSERT INTO plugin_hooks (id, plugin_id, hook_name, handler, priority, created_at)
104
- VALUES (?, ?, ?, ?, ?, datetime('now'))
105
- `),
106
- getHooksForName: db.prepare(`
107
- SELECT ph.*, pr.name as plugin_name
108
- FROM plugin_hooks ph
109
- JOIN plugin_registry pr ON ph.plugin_id = pr.id
110
- WHERE ph.hook_name = ?
111
- ORDER BY ph.priority ASC
112
- `),
113
- getHooksForPlugin: db.prepare(`SELECT * FROM plugin_hooks WHERE plugin_id = ?`),
114
- deleteHooksForPlugin: db.prepare(`DELETE FROM plugin_hooks WHERE plugin_id = ?`),
115
- insertExecution: db.prepare(`
116
- INSERT INTO hook_executions (id, hook_name, plugin_id, site_id, input, output, duration_ms, success, error, executed_at)
117
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'))
118
- `),
119
- incrementDownloads: db.prepare(`UPDATE plugin_registry SET downloads = downloads + 1, updated_at = datetime('now') WHERE id = ?`),
120
- updateRating: db.prepare(`UPDATE plugin_registry SET rating = ?, rating_count = rating_count + 1, updated_at = datetime('now') WHERE id = ?`),
121
- installationCount: db.prepare(`SELECT COUNT(*) as count FROM plugin_installations WHERE plugin_id = ?`),
122
- executionStats: db.prepare(`
123
- SELECT COUNT(*) as total,
124
- SUM(CASE WHEN success = 1 THEN 1 ELSE 0 END) as successes
125
- FROM hook_executions WHERE plugin_id = ?
126
- `),
127
- };
128
-
129
- // ─── Helpers ──────────────────────────────────────────────────────────
130
-
131
- function parseJSON(str, fallback) {
132
- if (!str) return fallback;
133
- try { return JSON.parse(str); } catch { return fallback; }
134
- }
135
-
136
- function enrichPlugin(row) {
137
- if (!row) return null;
138
- return {
139
- ...row,
140
- hooks: parseJSON(row.hooks, []),
141
- config_schema: parseJSON(row.config_schema, {}),
142
- enabled: !!row.enabled,
143
- is_official: !!row.is_official,
144
- };
145
- }
146
-
147
- // ─── validateConfig ───────────────────────────────────────────────────
148
-
149
- function validateConfig(config, schema) {
150
- if (!schema || typeof schema !== 'object') return { valid: true, errors: [] };
151
- const errors = [];
152
-
153
- if (schema.required && Array.isArray(schema.required)) {
154
- for (const field of schema.required) {
155
- if (config[field] === undefined || config[field] === null) {
156
- errors.push(`Missing required field: ${field}`);
157
- }
158
- }
159
- }
160
-
161
- if (schema.properties && typeof schema.properties === 'object') {
162
- for (const [key, rule] of Object.entries(schema.properties)) {
163
- const val = config[key];
164
- if (val === undefined || val === null) continue;
165
-
166
- if (rule.type) {
167
- const typeMap = {
168
- string: 'string',
169
- number: 'number',
170
- boolean: 'boolean',
171
- array: 'array',
172
- object: 'object',
173
- };
174
- const expected = typeMap[rule.type];
175
- if (expected) {
176
- const actual = Array.isArray(val) ? 'array' : typeof val;
177
- if (actual !== expected) {
178
- errors.push(`Field "${key}" must be of type ${rule.type}, got ${actual}`);
179
- }
180
- }
181
- }
182
-
183
- if (rule.enum && Array.isArray(rule.enum)) {
184
- if (!rule.enum.includes(val)) {
185
- errors.push(`Field "${key}" must be one of: ${rule.enum.join(', ')}`);
186
- }
187
- }
188
-
189
- if (rule.type === 'number' && typeof val === 'number') {
190
- if (rule.min !== undefined && val < rule.min) {
191
- errors.push(`Field "${key}" must be >= ${rule.min}`);
192
- }
193
- if (rule.max !== undefined && val > rule.max) {
194
- errors.push(`Field "${key}" must be <= ${rule.max}`);
195
- }
196
- }
197
-
198
- if (rule.type === 'string' && typeof val === 'string') {
199
- if (rule.minLength !== undefined && val.length < rule.minLength) {
200
- errors.push(`Field "${key}" must have length >= ${rule.minLength}`);
201
- }
202
- if (rule.maxLength !== undefined && val.length > rule.maxLength) {
203
- errors.push(`Field "${key}" must have length <= ${rule.maxLength}`);
204
- }
205
- }
206
- }
207
- }
208
-
209
- return { valid: errors.length === 0, errors };
210
- }
211
-
212
- // ─── Core Functions ───────────────────────────────────────────────────
213
-
214
- function registerPlugin({ name, version, author, description, category, entryPoint, hooks, configSchema, icon, isOfficial }) {
215
- const id = crypto.randomUUID();
216
- const hooksJSON = JSON.stringify(hooks || []);
217
- const schemaJSON = JSON.stringify(configSchema || {});
218
-
219
- stmts.insertPlugin.run(
220
- id, name, version || '1.0.0', author || 'Unknown', description || '',
221
- category || 'general', entryPoint || '', hooksJSON, schemaJSON,
222
- icon || '', isOfficial ? 1 : 0
223
- );
224
-
225
- if (Array.isArray(hooks)) {
226
- for (const hook of hooks) {
227
- if (hook.name && hook.handler) {
228
- registerHook(id, hook.name, hook.handler, hook.priority || 10);
229
- }
230
- }
231
- }
232
-
233
- return enrichPlugin(stmts.getPlugin.get(id));
234
- }
235
-
236
- function getPlugin(pluginId) {
237
- return enrichPlugin(stmts.getPlugin.get(pluginId));
238
- }
239
-
240
- function getPluginByName(name) {
241
- return enrichPlugin(stmts.getPluginByName.get(name));
242
- }
243
-
244
- function listPlugins({ category, search, sort, limit, offset } = {}) {
245
- let sql = 'SELECT * FROM plugin_registry WHERE enabled = 1';
246
- const params = [];
247
-
248
- if (category) {
249
- sql += ' AND category = ?';
250
- params.push(category);
251
- }
252
-
253
- if (search) {
254
- sql += ' AND (name LIKE ? OR description LIKE ?)';
255
- const term = `%${search}%`;
256
- params.push(term, term);
257
- }
258
-
259
- const sortMap = {
260
- downloads: 'downloads DESC',
261
- rating: 'rating DESC',
262
- created_at: 'created_at DESC',
263
- name: 'name ASC',
264
- };
265
- sql += ` ORDER BY ${sortMap[sort] || 'created_at DESC'}`;
266
-
267
- sql += ' LIMIT ? OFFSET ?';
268
- params.push(limit || 50, offset || 0);
269
-
270
- const rows = db.prepare(sql).all(...params);
271
- return rows.map(enrichPlugin);
272
- }
273
-
274
- function installPlugin(pluginId, siteId, userId, config) {
275
- const plugin = stmts.getPlugin.get(pluginId);
276
- if (!plugin) throw new Error(`Plugin not found: ${pluginId}`);
277
-
278
- const schema = parseJSON(plugin.config_schema, {});
279
- const finalConfig = config || {};
280
-
281
- if (schema && schema.properties) {
282
- const validation = validateConfig(finalConfig, schema);
283
- if (!validation.valid) {
284
- throw new Error(`Invalid config: ${validation.errors.join('; ')}`);
285
- }
286
- }
287
-
288
- const id = crypto.randomUUID();
289
- stmts.insertInstallation.run(id, pluginId, siteId, userId || null, JSON.stringify(finalConfig));
290
- stmts.incrementDownloads.run(pluginId);
291
-
292
- return {
293
- id,
294
- plugin_id: pluginId,
295
- site_id: siteId,
296
- user_id: userId,
297
- config: finalConfig,
298
- enabled: true,
299
- };
300
- }
301
-
302
- function uninstallPlugin(pluginId, siteId) {
303
- const changes = stmts.deleteInstallation.run(pluginId, siteId).changes;
304
- return changes > 0;
305
- }
306
-
307
- function configurePlugin(installationId, config) {
308
- const installation = stmts.getInstallation.get(installationId);
309
- if (!installation) throw new Error(`Installation not found: ${installationId}`);
310
-
311
- const plugin = stmts.getPlugin.get(installation.plugin_id);
312
- if (!plugin) throw new Error(`Plugin not found: ${installation.plugin_id}`);
313
-
314
- const schema = parseJSON(plugin.config_schema, {});
315
- if (schema && schema.properties) {
316
- const validation = validateConfig(config, schema);
317
- if (!validation.valid) {
318
- throw new Error(`Invalid config: ${validation.errors.join('; ')}`);
319
- }
320
- }
321
-
322
- stmts.updateInstallationConfig.run(JSON.stringify(config), installationId);
323
- return { id: installationId, config };
324
- }
325
-
326
- function getInstalledPlugins(siteId) {
327
- const rows = stmts.getInstalledPlugins.all(siteId);
328
- return rows.map(row => ({
329
- ...row,
330
- config: parseJSON(row.config, {}),
331
- plugin_hooks: parseJSON(row.plugin_hooks, []),
332
- config_schema: parseJSON(row.config_schema, {}),
333
- enabled: !!row.enabled,
334
- is_official: !!row.is_official,
335
- }));
336
- }
337
-
338
- // ─── Hook Management ──────────────────────────────────────────────────
339
-
340
- function registerHook(pluginId, hookName, handlerCode, priority) {
341
- const id = crypto.randomUUID();
342
- stmts.insertHook.run(id, pluginId, hookName, handlerCode, priority || 10);
343
- return { id, plugin_id: pluginId, hook_name: hookName, priority: priority || 10 };
344
- }
345
-
346
- function executeHook(hookName, siteId, input) {
347
- const installed = stmts.getInstalledPlugins.all(siteId);
348
- const installedPluginIds = new Set(installed.map(i => i.plugin_id));
349
-
350
- const allHooks = stmts.getHooksForName.all(hookName);
351
- const relevantHooks = allHooks.filter(h => installedPluginIds.has(h.plugin_id));
352
-
353
- const results = [];
354
-
355
- for (const hook of relevantHooks) {
356
- const execId = crypto.randomUUID();
357
- const start = Date.now();
358
- let output = null;
359
- let success = true;
360
- let error = null;
361
-
362
- try {
363
- const vm = require('vm');
364
- const sandbox = {
365
- input: JSON.parse(JSON.stringify(input || {})),
366
- config: {},
367
- result: null,
368
- JSON,
369
- Math,
370
- Date,
371
- Array,
372
- Object,
373
- String,
374
- Number,
375
- Boolean,
376
- parseInt,
377
- parseFloat,
378
- isNaN,
379
- isFinite,
380
- encodeURIComponent,
381
- decodeURIComponent,
382
- };
383
- const inst = installed.find(i => i.plugin_id === hook.plugin_id);
384
- sandbox.config = inst ? JSON.parse(JSON.stringify(parseJSON(inst.config, {}))) : {};
385
-
386
- const wrappedCode = `'use strict'; result = (function(input, config) { ${hook.handler} })(input, config);`;
387
- const script = new vm.Script(wrappedCode, { timeout: 1000, filename: `plugin-${hook.plugin_id}.vm` });
388
- const context = vm.createContext(sandbox, { codeGeneration: { strings: false, wasm: false } });
389
- script.runInContext(context, { timeout: 1000 });
390
- output = sandbox.result;
391
- } catch (err) {
392
- success = false;
393
- error = err.message || String(err);
394
- }
395
-
396
- const duration = Date.now() - start;
397
-
398
- stmts.insertExecution.run(
399
- execId, hookName, hook.plugin_id, siteId,
400
- JSON.stringify(input || {}), JSON.stringify(output || {}),
401
- duration, success ? 1 : 0, error
402
- );
403
-
404
- results.push({
405
- plugin_id: hook.plugin_id,
406
- plugin_name: hook.plugin_name,
407
- hook_name: hookName,
408
- output,
409
- success,
410
- error,
411
- duration_ms: duration,
412
- });
413
- }
414
-
415
- return results;
416
- }
417
-
418
- function getAvailableHooks() {
419
- return [
420
- { name: 'before_action', description: 'Triggered before any agent action is executed' },
421
- { name: 'after_action', description: 'Triggered after an agent action completes' },
422
- { name: 'on_discover', description: 'Triggered when agent discovers new page elements' },
423
- { name: 'on_authenticate', description: 'Triggered during authentication flow' },
424
- { name: 'on_error', description: 'Triggered when an error occurs during agent execution' },
425
- { name: 'on_memory_store', description: 'Triggered when data is stored in agent memory' },
426
- { name: 'on_memory_recall', description: 'Triggered when data is recalled from agent memory' },
427
- { name: 'on_heal_selector', description: 'Triggered when a CSS selector self-heals' },
428
- { name: 'on_vision_analyze', description: 'Triggered when vision analysis is performed on a page' },
429
- { name: 'on_swarm_start', description: 'Triggered when a swarm task begins' },
430
- { name: 'on_swarm_complete', description: 'Triggered when a swarm task completes' },
431
- { name: 'on_fairness_search', description: 'Triggered during fairness-aware search ranking' },
432
- { name: 'on_page_load', description: 'Triggered when a monitored page is loaded' },
433
- { name: 'on_agent_connect', description: 'Triggered when an agent connects to a site' },
434
- { name: 'on_agent_disconnect', description: 'Triggered when an agent disconnects from a site' },
435
- { name: 'custom', description: 'Generic hook for user-defined plugin events' },
436
- ];
437
- }
438
-
439
- // ─── Stats & Rating ───────────────────────────────────────────────────
440
-
441
- function getPluginStats(pluginId) {
442
- const plugin = stmts.getPlugin.get(pluginId);
443
- if (!plugin) return null;
444
-
445
- const instCount = stmts.installationCount.get(pluginId).count;
446
- const execStats = stmts.executionStats.get(pluginId);
447
- const total = execStats.total || 0;
448
- const successes = execStats.successes || 0;
449
-
450
- return {
451
- plugin_id: pluginId,
452
- name: plugin.name,
453
- installations: instCount,
454
- downloads: plugin.downloads,
455
- avg_rating: plugin.rating,
456
- rating_count: plugin.rating_count,
457
- total_executions: total,
458
- successful_executions: successes,
459
- success_rate: total > 0 ? Math.round((successes / total) * 10000) / 100 : 0,
460
- };
461
- }
462
-
463
- function ratePlugin(pluginId, userId, rating) {
464
- if (rating < 1 || rating > 5) throw new Error('Rating must be between 1 and 5');
465
-
466
- const plugin = stmts.getPlugin.get(pluginId);
467
- if (!plugin) throw new Error(`Plugin not found: ${pluginId}`);
468
-
469
- const oldAvg = plugin.rating || 0;
470
- const oldCount = plugin.rating_count || 0;
471
- const newAvg = ((oldAvg * oldCount) + rating) / (oldCount + 1);
472
- const rounded = Math.round(newAvg * 100) / 100;
473
-
474
- stmts.updateRating.run(rounded, pluginId);
475
-
476
- return { plugin_id: pluginId, new_rating: rounded, rating_count: oldCount + 1 };
477
- }
478
-
479
- // ─── Execution Log ────────────────────────────────────────────────────
480
-
481
- function getHookExecutionLog(siteId, { hookName, pluginId, limit } = {}) {
482
- let sql = 'SELECT he.*, pr.name as plugin_name FROM hook_executions he LEFT JOIN plugin_registry pr ON he.plugin_id = pr.id WHERE he.site_id = ?';
483
- const params = [siteId];
484
-
485
- if (hookName) {
486
- sql += ' AND he.hook_name = ?';
487
- params.push(hookName);
488
- }
489
- if (pluginId) {
490
- sql += ' AND he.plugin_id = ?';
491
- params.push(pluginId);
492
- }
493
-
494
- sql += ' ORDER BY he.executed_at DESC LIMIT ?';
495
- params.push(limit || 100);
496
-
497
- const rows = db.prepare(sql).all(...params);
498
- return rows.map(row => ({
499
- ...row,
500
- input: parseJSON(row.input, {}),
501
- output: parseJSON(row.output, {}),
502
- success: !!row.success,
503
- }));
504
- }
505
-
506
- // ─── Seed Official Plugins ────────────────────────────────────────────
507
-
508
- function seedOfficialPlugins() {
509
- const existing = stmts.getPluginByName.get('fairness-boost');
510
- if (existing) return;
511
-
512
- const plugins = [
513
- {
514
- name: 'fairness-boost',
515
- version: '1.0.0',
516
- author: 'WAB Team',
517
- description: 'Boosts indie and small-business sites in search results by 15% to promote a fairer web ecosystem.',
518
- category: 'fairness',
519
- entryPoint: 'fairness-boost/index.js',
520
- icon: '⚖️',
521
- isOfficial: true,
522
- configSchema: {
523
- properties: {
524
- boost_percentage: { type: 'number', min: 1, max: 50 },
525
- target_categories: { type: 'array' },
526
- },
527
- required: [],
528
- },
529
- hooks: [
530
- {
531
- name: 'on_fairness_search',
532
- priority: 5,
533
- handler: [
534
- 'var results = input.results || [];',
535
- 'var boost = (config && config.boost_percentage) || 15;',
536
- 'var boosted = results.map(function(r) {',
537
- ' if (r.is_indie || r.is_small_business) {',
538
- ' return Object.assign({}, r, { score: (r.score || 0) * (1 + boost / 100), boosted: true });',
539
- ' }',
540
- ' return r;',
541
- '});',
542
- 'return { results: boosted, boost_applied: boost };',
543
- ].join('\n'),
544
- },
545
- ],
546
- },
547
- {
548
- name: 'security-monitor',
549
- version: '1.0.0',
550
- author: 'WAB Team',
551
- description: 'Monitors agent actions for suspicious patterns like credential harvesting, XSS payloads, and unauthorized data access.',
552
- category: 'security',
553
- entryPoint: 'security-monitor/index.js',
554
- icon: '🛡️',
555
- isOfficial: true,
556
- configSchema: {
557
- properties: {
558
- alert_threshold: { type: 'number', min: 1, max: 10 },
559
- blocked_patterns: { type: 'array' },
560
- },
561
- required: [],
562
- },
563
- hooks: [
564
- {
565
- name: 'after_action',
566
- priority: 1,
567
- handler: [
568
- 'var action = input.action || "";',
569
- 'var data = input.data || "";',
570
- 'var dataStr = typeof data === "string" ? data : JSON.stringify(data);',
571
- 'var suspicious = [];',
572
- 'var patterns = [',
573
- ' { re: /password|passwd|secret|token/i, label: "credential_access" },',
574
- ' { re: /<script|javascript:|on\\w+\\s*=/i, label: "xss_attempt" },',
575
- ' { re: /eval\\(|Function\\(|setTimeout\\(.*,/i, label: "code_injection" },',
576
- ' { re: /\\.env|credentials|private_key/i, label: "sensitive_file_access" }',
577
- '];',
578
- 'for (var i = 0; i < patterns.length; i++) {',
579
- ' if (patterns[i].re.test(action) || patterns[i].re.test(dataStr)) {',
580
- ' suspicious.push(patterns[i].label);',
581
- ' }',
582
- '}',
583
- 'return { flagged: suspicious.length > 0, threats: suspicious, action: action, timestamp: new Date().toISOString() };',
584
- ].join('\n'),
585
- },
586
- ],
587
- },
588
- {
589
- name: 'analytics-enhanced',
590
- version: '1.0.0',
591
- author: 'WAB Team',
592
- description: 'Provides detailed page-load analytics including timing metrics, resource counts, and performance scoring.',
593
- category: 'analytics',
594
- entryPoint: 'analytics-enhanced/index.js',
595
- icon: '📊',
596
- isOfficial: true,
597
- configSchema: {
598
- properties: {
599
- track_resources: { type: 'boolean' },
600
- track_timing: { type: 'boolean' },
601
- sampling_rate: { type: 'number', min: 0, max: 100 },
602
- },
603
- required: [],
604
- },
605
- hooks: [
606
- {
607
- name: 'on_page_load',
608
- priority: 10,
609
- handler: [
610
- 'var url = input.url || "unknown";',
611
- 'var timing = input.timing || {};',
612
- 'var loadTime = timing.loadComplete || 0;',
613
- 'var domReady = timing.domReady || 0;',
614
- 'var resources = input.resources || [];',
615
- 'var scripts = resources.filter(function(r) { return r.type === "script"; }).length;',
616
- 'var styles = resources.filter(function(r) { return r.type === "stylesheet"; }).length;',
617
- 'var images = resources.filter(function(r) { return r.type === "image"; }).length;',
618
- 'var perfScore = 100;',
619
- 'if (loadTime > 3000) perfScore -= 20;',
620
- 'if (loadTime > 5000) perfScore -= 20;',
621
- 'if (scripts > 20) perfScore -= 15;',
622
- 'if (images > 50) perfScore -= 10;',
623
- 'if (perfScore < 0) perfScore = 0;',
624
- 'return {',
625
- ' url: url,',
626
- ' load_time_ms: loadTime,',
627
- ' dom_ready_ms: domReady,',
628
- ' resource_counts: { scripts: scripts, styles: styles, images: images, total: resources.length },',
629
- ' performance_score: perfScore,',
630
- ' tracked_at: new Date().toISOString()',
631
- '};',
632
- ].join('\n'),
633
- },
634
- ],
635
- },
636
- {
637
- name: 'auto-healer',
638
- version: '1.0.0',
639
- author: 'WAB Team',
640
- description: 'Automatically logs errors and suggests self-healing strategies such as selector updates, retry logic, and fallback actions.',
641
- category: 'reliability',
642
- entryPoint: 'auto-healer/index.js',
643
- icon: '🩹',
644
- isOfficial: true,
645
- configSchema: {
646
- properties: {
647
- max_retries: { type: 'number', min: 0, max: 10 },
648
- auto_retry: { type: 'boolean' },
649
- },
650
- required: [],
651
- },
652
- hooks: [
653
- {
654
- name: 'on_error',
655
- priority: 3,
656
- handler: [
657
- 'var errorMsg = input.error || input.message || "Unknown error";',
658
- 'var selector = input.selector || null;',
659
- 'var action = input.action || "unknown";',
660
- 'var strategies = [];',
661
- 'if (selector) {',
662
- ' strategies.push({ type: "selector_update", suggestion: "Try broader selector or data-testid attribute" });',
663
- ' strategies.push({ type: "wait_and_retry", suggestion: "Element may not be loaded yet, add wait before action" });',
664
- '}',
665
- 'if (/timeout|ETIMEDOUT/i.test(errorMsg)) {',
666
- ' strategies.push({ type: "increase_timeout", suggestion: "Network may be slow, increase timeout threshold" });',
667
- ' strategies.push({ type: "retry", suggestion: "Transient failure, retry with exponential backoff" });',
668
- '}',
669
- 'if (/not found|404/i.test(errorMsg)) {',
670
- ' strategies.push({ type: "fallback_url", suggestion: "Page may have moved, check for redirects" });',
671
- '}',
672
- 'if (/permission|forbidden|403/i.test(errorMsg)) {',
673
- ' strategies.push({ type: "re_authenticate", suggestion: "Session may have expired, re-authenticate" });',
674
- '}',
675
- 'if (strategies.length === 0) {',
676
- ' strategies.push({ type: "log_and_skip", suggestion: "Unknown error pattern, log and continue" });',
677
- '}',
678
- 'return { error: errorMsg, action: action, selector: selector, strategies: strategies, analyzed_at: new Date().toISOString() };',
679
- ].join('\n'),
680
- },
681
- ],
682
- },
683
- {
684
- name: 'memory-optimizer',
685
- version: '1.0.0',
686
- author: 'WAB Team',
687
- description: 'Checks for duplicate entries before storing new data in agent memory, reducing storage waste and improving recall accuracy.',
688
- category: 'performance',
689
- entryPoint: 'memory-optimizer/index.js',
690
- icon: '🧠',
691
- isOfficial: true,
692
- configSchema: {
693
- properties: {
694
- similarity_threshold: { type: 'number', min: 0, max: 1 },
695
- max_memory_entries: { type: 'number', min: 10, max: 100000 },
696
- },
697
- required: [],
698
- },
699
- hooks: [
700
- {
701
- name: 'on_memory_store',
702
- priority: 5,
703
- handler: [
704
- 'var key = input.key || "";',
705
- 'var value = input.value || "";',
706
- 'var existingKeys = input.existing_keys || [];',
707
- 'var valueStr = typeof value === "string" ? value : JSON.stringify(value);',
708
- 'var dominated = false;',
709
- 'var duplicateOf = null;',
710
- 'for (var i = 0; i < existingKeys.length; i++) {',
711
- ' if (existingKeys[i] === key) {',
712
- ' dominated = true;',
713
- ' duplicateOf = key;',
714
- ' break;',
715
- ' }',
716
- ' var normalizedExisting = existingKeys[i].toLowerCase().replace(/[^a-z0-9]/g, "");',
717
- ' var normalizedNew = key.toLowerCase().replace(/[^a-z0-9]/g, "");',
718
- ' if (normalizedExisting === normalizedNew) {',
719
- ' dominated = true;',
720
- ' duplicateOf = existingKeys[i];',
721
- ' break;',
722
- ' }',
723
- '}',
724
- 'return {',
725
- ' allow_store: !dominated,',
726
- ' is_duplicate: dominated,',
727
- ' duplicate_of: duplicateOf,',
728
- ' key: key,',
729
- ' value_length: valueStr.length,',
730
- ' checked_at: new Date().toISOString()',
731
- '};',
732
- ].join('\n'),
733
- },
734
- ],
735
- },
736
- ];
737
-
738
- const doSeed = db.transaction(() => {
739
- for (const p of plugins) {
740
- try {
741
- registerPlugin(p);
742
- } catch (_) {
743
- // already exists
744
- }
745
- }
746
- });
747
- doSeed();
748
- }
749
-
750
- seedOfficialPlugins();
751
-
752
- // ─── Exports ──────────────────────────────────────────────────────────
753
-
754
- module.exports = {
755
- registerPlugin,
756
- getPlugin,
757
- getPluginByName,
758
- listPlugins,
759
- installPlugin,
760
- uninstallPlugin,
761
- configurePlugin,
762
- getInstalledPlugins,
763
- registerHook,
764
- executeHook,
765
- getAvailableHooks,
766
- validateConfig,
767
- getPluginStats,
768
- ratePlugin,
769
- getHookExecutionLog,
770
- seedOfficialPlugins,
771
- };
1
+ 'use strict';
2
+
3
+ const crypto = require('crypto');
4
+ const { db } = require('../models/db');
5
+
6
+ // ─── Schema Creation ──────────────────────────────────────────────────
7
+
8
+ db.exec(`
9
+ CREATE TABLE IF NOT EXISTS plugin_registry (
10
+ id TEXT PRIMARY KEY,
11
+ name TEXT UNIQUE NOT NULL,
12
+ version TEXT,
13
+ author TEXT,
14
+ description TEXT,
15
+ category TEXT,
16
+ entry_point TEXT,
17
+ hooks TEXT DEFAULT '[]',
18
+ config_schema TEXT DEFAULT '{}',
19
+ icon TEXT,
20
+ downloads INTEGER DEFAULT 0,
21
+ rating REAL DEFAULT 0,
22
+ rating_count INTEGER DEFAULT 0,
23
+ enabled INTEGER DEFAULT 1,
24
+ is_official INTEGER DEFAULT 0,
25
+ created_at TEXT DEFAULT (datetime('now')),
26
+ updated_at TEXT DEFAULT (datetime('now'))
27
+ );
28
+
29
+ CREATE TABLE IF NOT EXISTS plugin_installations (
30
+ id TEXT PRIMARY KEY,
31
+ plugin_id TEXT NOT NULL,
32
+ site_id TEXT NOT NULL,
33
+ user_id TEXT,
34
+ config TEXT DEFAULT '{}',
35
+ enabled INTEGER DEFAULT 1,
36
+ installed_at TEXT DEFAULT (datetime('now')),
37
+ updated_at TEXT DEFAULT (datetime('now')),
38
+ UNIQUE(plugin_id, site_id)
39
+ );
40
+
41
+ CREATE TABLE IF NOT EXISTS plugin_hooks (
42
+ id TEXT PRIMARY KEY,
43
+ plugin_id TEXT NOT NULL,
44
+ hook_name TEXT NOT NULL,
45
+ handler TEXT NOT NULL,
46
+ priority INTEGER DEFAULT 10,
47
+ created_at TEXT DEFAULT (datetime('now'))
48
+ );
49
+
50
+ CREATE TABLE IF NOT EXISTS hook_executions (
51
+ id TEXT PRIMARY KEY,
52
+ hook_name TEXT NOT NULL,
53
+ plugin_id TEXT,
54
+ site_id TEXT,
55
+ input TEXT DEFAULT '{}',
56
+ output TEXT DEFAULT '{}',
57
+ duration_ms INTEGER,
58
+ success INTEGER,
59
+ error TEXT,
60
+ executed_at TEXT DEFAULT (datetime('now'))
61
+ );
62
+
63
+ CREATE INDEX IF NOT EXISTS idx_plugin_registry_category ON plugin_registry(category);
64
+ CREATE INDEX IF NOT EXISTS idx_plugin_registry_name ON plugin_registry(name);
65
+ CREATE INDEX IF NOT EXISTS idx_plugin_installations_site ON plugin_installations(site_id);
66
+ CREATE INDEX IF NOT EXISTS idx_plugin_installations_plugin ON plugin_installations(plugin_id);
67
+ CREATE INDEX IF NOT EXISTS idx_plugin_hooks_plugin ON plugin_hooks(plugin_id);
68
+ CREATE INDEX IF NOT EXISTS idx_plugin_hooks_hook_name ON plugin_hooks(hook_name);
69
+ CREATE INDEX IF NOT EXISTS idx_hook_executions_site ON hook_executions(site_id);
70
+ CREATE INDEX IF NOT EXISTS idx_hook_executions_hook ON hook_executions(hook_name);
71
+ CREATE INDEX IF NOT EXISTS idx_hook_executions_executed ON hook_executions(executed_at);
72
+ `);
73
+
74
+ // ─── Prepared Statements ──────────────────────────────────────────────
75
+
76
+ const stmts = {
77
+ insertPlugin: db.prepare(`
78
+ INSERT INTO plugin_registry (id, name, version, author, description, category, entry_point, hooks, config_schema, icon, is_official, created_at, updated_at)
79
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'), datetime('now'))
80
+ `),
81
+ getPlugin: db.prepare(`SELECT * FROM plugin_registry WHERE id = ?`),
82
+ getPluginByName: db.prepare(`SELECT * FROM plugin_registry WHERE name = ?`),
83
+ insertInstallation: db.prepare(`
84
+ INSERT INTO plugin_installations (id, plugin_id, site_id, user_id, config, enabled, installed_at, updated_at)
85
+ VALUES (?, ?, ?, ?, ?, 1, datetime('now'), datetime('now'))
86
+ ON CONFLICT(plugin_id, site_id) DO UPDATE SET
87
+ user_id = excluded.user_id,
88
+ config = excluded.config,
89
+ enabled = 1,
90
+ updated_at = datetime('now')
91
+ `),
92
+ deleteInstallation: db.prepare(`DELETE FROM plugin_installations WHERE plugin_id = ? AND site_id = ?`),
93
+ getInstallation: db.prepare(`SELECT * FROM plugin_installations WHERE id = ?`),
94
+ updateInstallationConfig: db.prepare(`UPDATE plugin_installations SET config = ?, updated_at = datetime('now') WHERE id = ?`),
95
+ getInstalledPlugins: db.prepare(`
96
+ SELECT pi.*, pr.name, pr.version, pr.author, pr.description, pr.category, pr.icon, pr.hooks as plugin_hooks, pr.config_schema, pr.rating, pr.rating_count, pr.downloads, pr.is_official
97
+ FROM plugin_installations pi
98
+ JOIN plugin_registry pr ON pi.plugin_id = pr.id
99
+ WHERE pi.site_id = ? AND pi.enabled = 1 AND pr.enabled = 1
100
+ ORDER BY pr.name
101
+ `),
102
+ insertHook: db.prepare(`
103
+ INSERT INTO plugin_hooks (id, plugin_id, hook_name, handler, priority, created_at)
104
+ VALUES (?, ?, ?, ?, ?, datetime('now'))
105
+ `),
106
+ getHooksForName: db.prepare(`
107
+ SELECT ph.*, pr.name as plugin_name
108
+ FROM plugin_hooks ph
109
+ JOIN plugin_registry pr ON ph.plugin_id = pr.id
110
+ WHERE ph.hook_name = ?
111
+ ORDER BY ph.priority ASC
112
+ `),
113
+ getHooksForPlugin: db.prepare(`SELECT * FROM plugin_hooks WHERE plugin_id = ?`),
114
+ deleteHooksForPlugin: db.prepare(`DELETE FROM plugin_hooks WHERE plugin_id = ?`),
115
+ insertExecution: db.prepare(`
116
+ INSERT INTO hook_executions (id, hook_name, plugin_id, site_id, input, output, duration_ms, success, error, executed_at)
117
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'))
118
+ `),
119
+ incrementDownloads: db.prepare(`UPDATE plugin_registry SET downloads = downloads + 1, updated_at = datetime('now') WHERE id = ?`),
120
+ updateRating: db.prepare(`UPDATE plugin_registry SET rating = ?, rating_count = rating_count + 1, updated_at = datetime('now') WHERE id = ?`),
121
+ installationCount: db.prepare(`SELECT COUNT(*) as count FROM plugin_installations WHERE plugin_id = ?`),
122
+ executionStats: db.prepare(`
123
+ SELECT COUNT(*) as total,
124
+ SUM(CASE WHEN success = 1 THEN 1 ELSE 0 END) as successes
125
+ FROM hook_executions WHERE plugin_id = ?
126
+ `),
127
+ };
128
+
129
+ // ─── Helpers ──────────────────────────────────────────────────────────
130
+
131
+ function parseJSON(str, fallback) {
132
+ if (!str) return fallback;
133
+ try { return JSON.parse(str); } catch { return fallback; }
134
+ }
135
+
136
+ function enrichPlugin(row) {
137
+ if (!row) return null;
138
+ return {
139
+ ...row,
140
+ hooks: parseJSON(row.hooks, []),
141
+ config_schema: parseJSON(row.config_schema, {}),
142
+ enabled: !!row.enabled,
143
+ is_official: !!row.is_official,
144
+ };
145
+ }
146
+
147
+ // ─── validateConfig ───────────────────────────────────────────────────
148
+
149
+ function validateConfig(config, schema) {
150
+ if (!schema || typeof schema !== 'object') return { valid: true, errors: [] };
151
+ const errors = [];
152
+
153
+ if (schema.required && Array.isArray(schema.required)) {
154
+ for (const field of schema.required) {
155
+ if (config[field] === undefined || config[field] === null) {
156
+ errors.push(`Missing required field: ${field}`);
157
+ }
158
+ }
159
+ }
160
+
161
+ if (schema.properties && typeof schema.properties === 'object') {
162
+ for (const [key, rule] of Object.entries(schema.properties)) {
163
+ const val = config[key];
164
+ if (val === undefined || val === null) continue;
165
+
166
+ if (rule.type) {
167
+ const typeMap = {
168
+ string: 'string',
169
+ number: 'number',
170
+ boolean: 'boolean',
171
+ array: 'array',
172
+ object: 'object',
173
+ };
174
+ const expected = typeMap[rule.type];
175
+ if (expected) {
176
+ const actual = Array.isArray(val) ? 'array' : typeof val;
177
+ if (actual !== expected) {
178
+ errors.push(`Field "${key}" must be of type ${rule.type}, got ${actual}`);
179
+ }
180
+ }
181
+ }
182
+
183
+ if (rule.enum && Array.isArray(rule.enum)) {
184
+ if (!rule.enum.includes(val)) {
185
+ errors.push(`Field "${key}" must be one of: ${rule.enum.join(', ')}`);
186
+ }
187
+ }
188
+
189
+ if (rule.type === 'number' && typeof val === 'number') {
190
+ if (rule.min !== undefined && val < rule.min) {
191
+ errors.push(`Field "${key}" must be >= ${rule.min}`);
192
+ }
193
+ if (rule.max !== undefined && val > rule.max) {
194
+ errors.push(`Field "${key}" must be <= ${rule.max}`);
195
+ }
196
+ }
197
+
198
+ if (rule.type === 'string' && typeof val === 'string') {
199
+ if (rule.minLength !== undefined && val.length < rule.minLength) {
200
+ errors.push(`Field "${key}" must have length >= ${rule.minLength}`);
201
+ }
202
+ if (rule.maxLength !== undefined && val.length > rule.maxLength) {
203
+ errors.push(`Field "${key}" must have length <= ${rule.maxLength}`);
204
+ }
205
+ }
206
+ }
207
+ }
208
+
209
+ return { valid: errors.length === 0, errors };
210
+ }
211
+
212
+ // ─── Core Functions ───────────────────────────────────────────────────
213
+
214
+ function registerPlugin({ name, version, author, description, category, entryPoint, hooks, configSchema, icon, isOfficial }) {
215
+ const id = crypto.randomUUID();
216
+ const hooksJSON = JSON.stringify(hooks || []);
217
+ const schemaJSON = JSON.stringify(configSchema || {});
218
+
219
+ stmts.insertPlugin.run(
220
+ id, name, version || '1.0.0', author || 'Unknown', description || '',
221
+ category || 'general', entryPoint || '', hooksJSON, schemaJSON,
222
+ icon || '', isOfficial ? 1 : 0
223
+ );
224
+
225
+ if (Array.isArray(hooks)) {
226
+ for (const hook of hooks) {
227
+ if (hook.name && hook.handler) {
228
+ registerHook(id, hook.name, hook.handler, hook.priority || 10);
229
+ }
230
+ }
231
+ }
232
+
233
+ return enrichPlugin(stmts.getPlugin.get(id));
234
+ }
235
+
236
+ function getPlugin(pluginId) {
237
+ return enrichPlugin(stmts.getPlugin.get(pluginId));
238
+ }
239
+
240
+ function getPluginByName(name) {
241
+ return enrichPlugin(stmts.getPluginByName.get(name));
242
+ }
243
+
244
+ function listPlugins({ category, search, sort, limit, offset } = {}) {
245
+ let sql = 'SELECT * FROM plugin_registry WHERE enabled = 1';
246
+ const params = [];
247
+
248
+ if (category) {
249
+ sql += ' AND category = ?';
250
+ params.push(category);
251
+ }
252
+
253
+ if (search) {
254
+ sql += ' AND (name LIKE ? OR description LIKE ?)';
255
+ const term = `%${search}%`;
256
+ params.push(term, term);
257
+ }
258
+
259
+ const sortMap = {
260
+ downloads: 'downloads DESC',
261
+ rating: 'rating DESC',
262
+ created_at: 'created_at DESC',
263
+ name: 'name ASC',
264
+ };
265
+ sql += ` ORDER BY ${sortMap[sort] || 'created_at DESC'}`;
266
+
267
+ sql += ' LIMIT ? OFFSET ?';
268
+ params.push(limit || 50, offset || 0);
269
+
270
+ const rows = db.prepare(sql).all(...params);
271
+ return rows.map(enrichPlugin);
272
+ }
273
+
274
+ function installPlugin(pluginId, siteId, userId, config) {
275
+ const plugin = stmts.getPlugin.get(pluginId);
276
+ if (!plugin) throw new Error(`Plugin not found: ${pluginId}`);
277
+
278
+ const schema = parseJSON(plugin.config_schema, {});
279
+ const finalConfig = config || {};
280
+
281
+ if (schema && schema.properties) {
282
+ const validation = validateConfig(finalConfig, schema);
283
+ if (!validation.valid) {
284
+ throw new Error(`Invalid config: ${validation.errors.join('; ')}`);
285
+ }
286
+ }
287
+
288
+ const id = crypto.randomUUID();
289
+ stmts.insertInstallation.run(id, pluginId, siteId, userId || null, JSON.stringify(finalConfig));
290
+ stmts.incrementDownloads.run(pluginId);
291
+
292
+ return {
293
+ id,
294
+ plugin_id: pluginId,
295
+ site_id: siteId,
296
+ user_id: userId,
297
+ config: finalConfig,
298
+ enabled: true,
299
+ };
300
+ }
301
+
302
+ function uninstallPlugin(pluginId, siteId) {
303
+ const changes = stmts.deleteInstallation.run(pluginId, siteId).changes;
304
+ return changes > 0;
305
+ }
306
+
307
+ function configurePlugin(installationId, config) {
308
+ const installation = stmts.getInstallation.get(installationId);
309
+ if (!installation) throw new Error(`Installation not found: ${installationId}`);
310
+
311
+ const plugin = stmts.getPlugin.get(installation.plugin_id);
312
+ if (!plugin) throw new Error(`Plugin not found: ${installation.plugin_id}`);
313
+
314
+ const schema = parseJSON(plugin.config_schema, {});
315
+ if (schema && schema.properties) {
316
+ const validation = validateConfig(config, schema);
317
+ if (!validation.valid) {
318
+ throw new Error(`Invalid config: ${validation.errors.join('; ')}`);
319
+ }
320
+ }
321
+
322
+ stmts.updateInstallationConfig.run(JSON.stringify(config), installationId);
323
+ return { id: installationId, config };
324
+ }
325
+
326
+ function getInstalledPlugins(siteId) {
327
+ const rows = stmts.getInstalledPlugins.all(siteId);
328
+ return rows.map(row => ({
329
+ ...row,
330
+ config: parseJSON(row.config, {}),
331
+ plugin_hooks: parseJSON(row.plugin_hooks, []),
332
+ config_schema: parseJSON(row.config_schema, {}),
333
+ enabled: !!row.enabled,
334
+ is_official: !!row.is_official,
335
+ }));
336
+ }
337
+
338
+ // ─── Hook Management ──────────────────────────────────────────────────
339
+
340
+ function registerHook(pluginId, hookName, handlerCode, priority) {
341
+ const id = crypto.randomUUID();
342
+ stmts.insertHook.run(id, pluginId, hookName, handlerCode, priority || 10);
343
+ return { id, plugin_id: pluginId, hook_name: hookName, priority: priority || 10 };
344
+ }
345
+
346
+ function executeHook(hookName, siteId, input) {
347
+ const installed = stmts.getInstalledPlugins.all(siteId);
348
+ const installedPluginIds = new Set(installed.map(i => i.plugin_id));
349
+
350
+ const allHooks = stmts.getHooksForName.all(hookName);
351
+ const relevantHooks = allHooks.filter(h => installedPluginIds.has(h.plugin_id));
352
+
353
+ const results = [];
354
+
355
+ for (const hook of relevantHooks) {
356
+ const execId = crypto.randomUUID();
357
+ const start = Date.now();
358
+ let output = null;
359
+ let success = true;
360
+ let error = null;
361
+
362
+ try {
363
+ const vm = require('vm');
364
+ const sandbox = {
365
+ input: JSON.parse(JSON.stringify(input || {})),
366
+ config: {},
367
+ result: null,
368
+ JSON,
369
+ Math,
370
+ Date,
371
+ Array,
372
+ Object,
373
+ String,
374
+ Number,
375
+ Boolean,
376
+ parseInt,
377
+ parseFloat,
378
+ isNaN,
379
+ isFinite,
380
+ encodeURIComponent,
381
+ decodeURIComponent,
382
+ };
383
+ const inst = installed.find(i => i.plugin_id === hook.plugin_id);
384
+ sandbox.config = inst ? JSON.parse(JSON.stringify(parseJSON(inst.config, {}))) : {};
385
+
386
+ const wrappedCode = `'use strict'; result = (function(input, config) { ${hook.handler} })(input, config);`;
387
+ const script = new vm.Script(wrappedCode, { timeout: 1000, filename: `plugin-${hook.plugin_id}.vm` });
388
+ const context = vm.createContext(sandbox, { codeGeneration: { strings: false, wasm: false } });
389
+ script.runInContext(context, { timeout: 1000 });
390
+ output = sandbox.result;
391
+ } catch (err) {
392
+ success = false;
393
+ error = err.message || String(err);
394
+ }
395
+
396
+ const duration = Date.now() - start;
397
+
398
+ stmts.insertExecution.run(
399
+ execId, hookName, hook.plugin_id, siteId,
400
+ JSON.stringify(input || {}), JSON.stringify(output || {}),
401
+ duration, success ? 1 : 0, error
402
+ );
403
+
404
+ results.push({
405
+ plugin_id: hook.plugin_id,
406
+ plugin_name: hook.plugin_name,
407
+ hook_name: hookName,
408
+ output,
409
+ success,
410
+ error,
411
+ duration_ms: duration,
412
+ });
413
+ }
414
+
415
+ return results;
416
+ }
417
+
418
+ function getAvailableHooks() {
419
+ return [
420
+ { name: 'before_action', description: 'Triggered before any agent action is executed' },
421
+ { name: 'after_action', description: 'Triggered after an agent action completes' },
422
+ { name: 'on_discover', description: 'Triggered when agent discovers new page elements' },
423
+ { name: 'on_authenticate', description: 'Triggered during authentication flow' },
424
+ { name: 'on_error', description: 'Triggered when an error occurs during agent execution' },
425
+ { name: 'on_memory_store', description: 'Triggered when data is stored in agent memory' },
426
+ { name: 'on_memory_recall', description: 'Triggered when data is recalled from agent memory' },
427
+ { name: 'on_heal_selector', description: 'Triggered when a CSS selector self-heals' },
428
+ { name: 'on_vision_analyze', description: 'Triggered when vision analysis is performed on a page' },
429
+ { name: 'on_swarm_start', description: 'Triggered when a swarm task begins' },
430
+ { name: 'on_swarm_complete', description: 'Triggered when a swarm task completes' },
431
+ { name: 'on_fairness_search', description: 'Triggered during fairness-aware search ranking' },
432
+ { name: 'on_page_load', description: 'Triggered when a monitored page is loaded' },
433
+ { name: 'on_agent_connect', description: 'Triggered when an agent connects to a site' },
434
+ { name: 'on_agent_disconnect', description: 'Triggered when an agent disconnects from a site' },
435
+ { name: 'custom', description: 'Generic hook for user-defined plugin events' },
436
+ ];
437
+ }
438
+
439
+ // ─── Stats & Rating ───────────────────────────────────────────────────
440
+
441
+ function getPluginStats(pluginId) {
442
+ const plugin = stmts.getPlugin.get(pluginId);
443
+ if (!plugin) return null;
444
+
445
+ const instCount = stmts.installationCount.get(pluginId).count;
446
+ const execStats = stmts.executionStats.get(pluginId);
447
+ const total = execStats.total || 0;
448
+ const successes = execStats.successes || 0;
449
+
450
+ return {
451
+ plugin_id: pluginId,
452
+ name: plugin.name,
453
+ installations: instCount,
454
+ downloads: plugin.downloads,
455
+ avg_rating: plugin.rating,
456
+ rating_count: plugin.rating_count,
457
+ total_executions: total,
458
+ successful_executions: successes,
459
+ success_rate: total > 0 ? Math.round((successes / total) * 10000) / 100 : 0,
460
+ };
461
+ }
462
+
463
+ function ratePlugin(pluginId, userId, rating) {
464
+ if (rating < 1 || rating > 5) throw new Error('Rating must be between 1 and 5');
465
+
466
+ const plugin = stmts.getPlugin.get(pluginId);
467
+ if (!plugin) throw new Error(`Plugin not found: ${pluginId}`);
468
+
469
+ const oldAvg = plugin.rating || 0;
470
+ const oldCount = plugin.rating_count || 0;
471
+ const newAvg = ((oldAvg * oldCount) + rating) / (oldCount + 1);
472
+ const rounded = Math.round(newAvg * 100) / 100;
473
+
474
+ stmts.updateRating.run(rounded, pluginId);
475
+
476
+ return { plugin_id: pluginId, new_rating: rounded, rating_count: oldCount + 1 };
477
+ }
478
+
479
+ // ─── Execution Log ────────────────────────────────────────────────────
480
+
481
+ function getHookExecutionLog(siteId, { hookName, pluginId, limit } = {}) {
482
+ let sql = 'SELECT he.*, pr.name as plugin_name FROM hook_executions he LEFT JOIN plugin_registry pr ON he.plugin_id = pr.id WHERE he.site_id = ?';
483
+ const params = [siteId];
484
+
485
+ if (hookName) {
486
+ sql += ' AND he.hook_name = ?';
487
+ params.push(hookName);
488
+ }
489
+ if (pluginId) {
490
+ sql += ' AND he.plugin_id = ?';
491
+ params.push(pluginId);
492
+ }
493
+
494
+ sql += ' ORDER BY he.executed_at DESC LIMIT ?';
495
+ params.push(limit || 100);
496
+
497
+ const rows = db.prepare(sql).all(...params);
498
+ return rows.map(row => ({
499
+ ...row,
500
+ input: parseJSON(row.input, {}),
501
+ output: parseJSON(row.output, {}),
502
+ success: !!row.success,
503
+ }));
504
+ }
505
+
506
+ // ─── Seed Official Plugins ────────────────────────────────────────────
507
+
508
+ function seedOfficialPlugins() {
509
+ const existing = stmts.getPluginByName.get('fairness-boost');
510
+ if (existing) return;
511
+
512
+ const plugins = [
513
+ {
514
+ name: 'fairness-boost',
515
+ version: '1.0.0',
516
+ author: 'WAB Team',
517
+ description: 'Boosts indie and small-business sites in search results by 15% to promote a fairer web ecosystem.',
518
+ category: 'fairness',
519
+ entryPoint: 'fairness-boost/index.js',
520
+ icon: '⚖️',
521
+ isOfficial: true,
522
+ configSchema: {
523
+ properties: {
524
+ boost_percentage: { type: 'number', min: 1, max: 50 },
525
+ target_categories: { type: 'array' },
526
+ },
527
+ required: [],
528
+ },
529
+ hooks: [
530
+ {
531
+ name: 'on_fairness_search',
532
+ priority: 5,
533
+ handler: [
534
+ 'var results = input.results || [];',
535
+ 'var boost = (config && config.boost_percentage) || 15;',
536
+ 'var boosted = results.map(function(r) {',
537
+ ' if (r.is_indie || r.is_small_business) {',
538
+ ' return Object.assign({}, r, { score: (r.score || 0) * (1 + boost / 100), boosted: true });',
539
+ ' }',
540
+ ' return r;',
541
+ '});',
542
+ 'return { results: boosted, boost_applied: boost };',
543
+ ].join('\n'),
544
+ },
545
+ ],
546
+ },
547
+ {
548
+ name: 'security-monitor',
549
+ version: '1.0.0',
550
+ author: 'WAB Team',
551
+ description: 'Monitors agent actions for suspicious patterns like credential harvesting, XSS payloads, and unauthorized data access.',
552
+ category: 'security',
553
+ entryPoint: 'security-monitor/index.js',
554
+ icon: '🛡️',
555
+ isOfficial: true,
556
+ configSchema: {
557
+ properties: {
558
+ alert_threshold: { type: 'number', min: 1, max: 10 },
559
+ blocked_patterns: { type: 'array' },
560
+ },
561
+ required: [],
562
+ },
563
+ hooks: [
564
+ {
565
+ name: 'after_action',
566
+ priority: 1,
567
+ handler: [
568
+ 'var action = input.action || "";',
569
+ 'var data = input.data || "";',
570
+ 'var dataStr = typeof data === "string" ? data : JSON.stringify(data);',
571
+ 'var suspicious = [];',
572
+ 'var patterns = [',
573
+ ' { re: /password|passwd|secret|token/i, label: "credential_access" },',
574
+ ' { re: /<script|javascript:|on\\w+\\s*=/i, label: "xss_attempt" },',
575
+ ' { re: /eval\\(|Function\\(|setTimeout\\(.*,/i, label: "code_injection" },',
576
+ ' { re: /\\.env|credentials|private_key/i, label: "sensitive_file_access" }',
577
+ '];',
578
+ 'for (var i = 0; i < patterns.length; i++) {',
579
+ ' if (patterns[i].re.test(action) || patterns[i].re.test(dataStr)) {',
580
+ ' suspicious.push(patterns[i].label);',
581
+ ' }',
582
+ '}',
583
+ 'return { flagged: suspicious.length > 0, threats: suspicious, action: action, timestamp: new Date().toISOString() };',
584
+ ].join('\n'),
585
+ },
586
+ ],
587
+ },
588
+ {
589
+ name: 'analytics-enhanced',
590
+ version: '1.0.0',
591
+ author: 'WAB Team',
592
+ description: 'Provides detailed page-load analytics including timing metrics, resource counts, and performance scoring.',
593
+ category: 'analytics',
594
+ entryPoint: 'analytics-enhanced/index.js',
595
+ icon: '📊',
596
+ isOfficial: true,
597
+ configSchema: {
598
+ properties: {
599
+ track_resources: { type: 'boolean' },
600
+ track_timing: { type: 'boolean' },
601
+ sampling_rate: { type: 'number', min: 0, max: 100 },
602
+ },
603
+ required: [],
604
+ },
605
+ hooks: [
606
+ {
607
+ name: 'on_page_load',
608
+ priority: 10,
609
+ handler: [
610
+ 'var url = input.url || "unknown";',
611
+ 'var timing = input.timing || {};',
612
+ 'var loadTime = timing.loadComplete || 0;',
613
+ 'var domReady = timing.domReady || 0;',
614
+ 'var resources = input.resources || [];',
615
+ 'var scripts = resources.filter(function(r) { return r.type === "script"; }).length;',
616
+ 'var styles = resources.filter(function(r) { return r.type === "stylesheet"; }).length;',
617
+ 'var images = resources.filter(function(r) { return r.type === "image"; }).length;',
618
+ 'var perfScore = 100;',
619
+ 'if (loadTime > 3000) perfScore -= 20;',
620
+ 'if (loadTime > 5000) perfScore -= 20;',
621
+ 'if (scripts > 20) perfScore -= 15;',
622
+ 'if (images > 50) perfScore -= 10;',
623
+ 'if (perfScore < 0) perfScore = 0;',
624
+ 'return {',
625
+ ' url: url,',
626
+ ' load_time_ms: loadTime,',
627
+ ' dom_ready_ms: domReady,',
628
+ ' resource_counts: { scripts: scripts, styles: styles, images: images, total: resources.length },',
629
+ ' performance_score: perfScore,',
630
+ ' tracked_at: new Date().toISOString()',
631
+ '};',
632
+ ].join('\n'),
633
+ },
634
+ ],
635
+ },
636
+ {
637
+ name: 'auto-healer',
638
+ version: '1.0.0',
639
+ author: 'WAB Team',
640
+ description: 'Automatically logs errors and suggests self-healing strategies such as selector updates, retry logic, and fallback actions.',
641
+ category: 'reliability',
642
+ entryPoint: 'auto-healer/index.js',
643
+ icon: '🩹',
644
+ isOfficial: true,
645
+ configSchema: {
646
+ properties: {
647
+ max_retries: { type: 'number', min: 0, max: 10 },
648
+ auto_retry: { type: 'boolean' },
649
+ },
650
+ required: [],
651
+ },
652
+ hooks: [
653
+ {
654
+ name: 'on_error',
655
+ priority: 3,
656
+ handler: [
657
+ 'var errorMsg = input.error || input.message || "Unknown error";',
658
+ 'var selector = input.selector || null;',
659
+ 'var action = input.action || "unknown";',
660
+ 'var strategies = [];',
661
+ 'if (selector) {',
662
+ ' strategies.push({ type: "selector_update", suggestion: "Try broader selector or data-testid attribute" });',
663
+ ' strategies.push({ type: "wait_and_retry", suggestion: "Element may not be loaded yet, add wait before action" });',
664
+ '}',
665
+ 'if (/timeout|ETIMEDOUT/i.test(errorMsg)) {',
666
+ ' strategies.push({ type: "increase_timeout", suggestion: "Network may be slow, increase timeout threshold" });',
667
+ ' strategies.push({ type: "retry", suggestion: "Transient failure, retry with exponential backoff" });',
668
+ '}',
669
+ 'if (/not found|404/i.test(errorMsg)) {',
670
+ ' strategies.push({ type: "fallback_url", suggestion: "Page may have moved, check for redirects" });',
671
+ '}',
672
+ 'if (/permission|forbidden|403/i.test(errorMsg)) {',
673
+ ' strategies.push({ type: "re_authenticate", suggestion: "Session may have expired, re-authenticate" });',
674
+ '}',
675
+ 'if (strategies.length === 0) {',
676
+ ' strategies.push({ type: "log_and_skip", suggestion: "Unknown error pattern, log and continue" });',
677
+ '}',
678
+ 'return { error: errorMsg, action: action, selector: selector, strategies: strategies, analyzed_at: new Date().toISOString() };',
679
+ ].join('\n'),
680
+ },
681
+ ],
682
+ },
683
+ {
684
+ name: 'memory-optimizer',
685
+ version: '1.0.0',
686
+ author: 'WAB Team',
687
+ description: 'Checks for duplicate entries before storing new data in agent memory, reducing storage waste and improving recall accuracy.',
688
+ category: 'performance',
689
+ entryPoint: 'memory-optimizer/index.js',
690
+ icon: '🧠',
691
+ isOfficial: true,
692
+ configSchema: {
693
+ properties: {
694
+ similarity_threshold: { type: 'number', min: 0, max: 1 },
695
+ max_memory_entries: { type: 'number', min: 10, max: 100000 },
696
+ },
697
+ required: [],
698
+ },
699
+ hooks: [
700
+ {
701
+ name: 'on_memory_store',
702
+ priority: 5,
703
+ handler: [
704
+ 'var key = input.key || "";',
705
+ 'var value = input.value || "";',
706
+ 'var existingKeys = input.existing_keys || [];',
707
+ 'var valueStr = typeof value === "string" ? value : JSON.stringify(value);',
708
+ 'var dominated = false;',
709
+ 'var duplicateOf = null;',
710
+ 'for (var i = 0; i < existingKeys.length; i++) {',
711
+ ' if (existingKeys[i] === key) {',
712
+ ' dominated = true;',
713
+ ' duplicateOf = key;',
714
+ ' break;',
715
+ ' }',
716
+ ' var normalizedExisting = existingKeys[i].toLowerCase().replace(/[^a-z0-9]/g, "");',
717
+ ' var normalizedNew = key.toLowerCase().replace(/[^a-z0-9]/g, "");',
718
+ ' if (normalizedExisting === normalizedNew) {',
719
+ ' dominated = true;',
720
+ ' duplicateOf = existingKeys[i];',
721
+ ' break;',
722
+ ' }',
723
+ '}',
724
+ 'return {',
725
+ ' allow_store: !dominated,',
726
+ ' is_duplicate: dominated,',
727
+ ' duplicate_of: duplicateOf,',
728
+ ' key: key,',
729
+ ' value_length: valueStr.length,',
730
+ ' checked_at: new Date().toISOString()',
731
+ '};',
732
+ ].join('\n'),
733
+ },
734
+ ],
735
+ },
736
+ ];
737
+
738
+ const doSeed = db.transaction(() => {
739
+ for (const p of plugins) {
740
+ try {
741
+ registerPlugin(p);
742
+ } catch (_) {
743
+ // already exists
744
+ }
745
+ }
746
+ });
747
+ doSeed();
748
+ }
749
+
750
+ seedOfficialPlugins();
751
+
752
+ // ─── Exports ──────────────────────────────────────────────────────────
753
+
754
+ module.exports = {
755
+ registerPlugin,
756
+ getPlugin,
757
+ getPluginByName,
758
+ listPlugins,
759
+ installPlugin,
760
+ uninstallPlugin,
761
+ configurePlugin,
762
+ getInstalledPlugins,
763
+ registerHook,
764
+ executeHook,
765
+ getAvailableHooks,
766
+ validateConfig,
767
+ getPluginStats,
768
+ ratePlugin,
769
+ getHookExecutionLog,
770
+ seedOfficialPlugins,
771
+ };