web-agent-bridge 1.1.2 → 2.0.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.
- package/LICENSE +21 -21
- package/README.ar.md +446 -446
- package/README.md +780 -844
- package/bin/cli.js +80 -80
- package/bin/wab.js +80 -80
- package/examples/bidi-agent.js +119 -119
- package/examples/mcp-agent.js +94 -94
- package/examples/next-app-router/README.md +44 -0
- package/examples/puppeteer-agent.js +108 -108
- package/examples/saas-dashboard/README.md +55 -0
- package/examples/shopify-hydrogen/README.md +74 -0
- package/examples/vision-agent.js +171 -171
- package/examples/wordpress-elementor/README.md +77 -0
- package/package.json +69 -78
- package/public/.well-known/ai-assets.json +59 -0
- package/public/admin/login.html +84 -84
- package/public/ai.html +196 -0
- package/public/cookies.html +208 -208
- package/public/css/premium.css +317 -0
- package/public/css/styles.css +1235 -1235
- package/public/dashboard.html +704 -704
- package/public/demo.html +259 -0
- package/public/docs.html +585 -585
- package/public/feed.xml +89 -0
- package/public/index.html +495 -332
- package/public/js/auth-nav.js +31 -31
- package/public/js/auth-redirect.js +12 -12
- package/public/js/cookie-consent.js +56 -56
- package/public/js/wab-demo-page.js +721 -0
- package/public/js/ws-client.js +74 -74
- package/public/llms-full.txt +309 -0
- package/public/llms.txt +85 -0
- package/public/login.html +83 -83
- package/public/openapi.json +580 -0
- package/public/premium-dashboard.html +2487 -0
- package/public/premium.html +791 -0
- package/public/privacy.html +295 -295
- package/public/register.html +103 -103
- package/public/robots.txt +87 -0
- package/public/script/wab-consent.d.ts +36 -0
- package/public/script/wab-consent.js +104 -0
- package/public/script/wab-schema.js +131 -0
- package/public/script/wab.d.ts +108 -0
- package/public/script/wab.min.js +234 -0
- package/public/sitemap.xml +93 -0
- package/public/terms.html +254 -254
- package/public/video/tutorial.mp4 +0 -0
- package/script/ai-agent-bridge.js +1558 -1513
- package/sdk/README.md +55 -55
- package/sdk/index.d.ts +118 -0
- package/sdk/index.js +257 -203
- package/sdk/package.json +14 -14
- package/sdk/schema-discovery.js +83 -0
- package/server/config/secrets.js +94 -92
- package/server/index.js +0 -9
- package/server/middleware/adminAuth.js +30 -30
- package/server/middleware/auth.js +41 -41
- package/server/middleware/rateLimits.js +24 -24
- package/server/migrations/001_add_analytics_indexes.sql +7 -7
- package/server/migrations/002_premium_features.sql +418 -0
- package/server/models/adapters/index.js +33 -33
- package/server/models/adapters/mysql.js +183 -183
- package/server/models/adapters/postgresql.js +172 -172
- package/server/models/adapters/sqlite.js +7 -7
- package/server/models/db.js +561 -561
- package/server/routes/admin-premium.js +671 -0
- package/server/routes/admin.js +247 -247
- package/server/routes/api.js +131 -138
- package/server/routes/auth.js +51 -51
- package/server/routes/billing.js +45 -45
- package/server/routes/discovery.js +406 -329
- package/server/routes/license.js +240 -240
- package/server/routes/noscript.js +543 -543
- package/server/routes/premium-v2.js +686 -0
- package/server/routes/premium.js +724 -0
- package/server/routes/wab-api.js +476 -476
- package/server/services/agent-memory.js +625 -0
- package/server/services/email.js +204 -204
- package/server/services/fairness.js +420 -420
- package/server/services/plugins.js +747 -0
- package/server/services/premium.js +1883 -0
- package/server/services/self-healing.js +843 -0
- package/server/services/stripe.js +192 -192
- package/server/services/swarm.js +788 -0
- package/server/services/vision.js +871 -0
- package/server/utils/cache.js +125 -125
- package/server/utils/migrate.js +81 -81
- package/server/utils/secureFields.js +50 -50
- package/server/ws.js +101 -101
- package/docs/DEPLOY.md +0 -118
- package/docs/SPEC.md +0 -1540
- package/wab-mcp-adapter/README.md +0 -136
- package/wab-mcp-adapter/index.js +0 -555
- package/wab-mcp-adapter/package.json +0 -17
package/server/models/db.js
CHANGED
|
@@ -1,561 +1,561 @@
|
|
|
1
|
-
const Database = require('better-sqlite3');
|
|
2
|
-
const path = require('path');
|
|
3
|
-
const fs = require('fs');
|
|
4
|
-
const crypto = require('crypto');
|
|
5
|
-
const bcrypt = require('bcryptjs');
|
|
6
|
-
const { v4: uuidv4 } = require('uuid');
|
|
7
|
-
const { encryptOptional, decryptOptional } = require('../utils/secureFields');
|
|
8
|
-
|
|
9
|
-
const isTest = process.env.NODE_ENV === 'test';
|
|
10
|
-
const DATA_DIR = isTest
|
|
11
|
-
? path.join(__dirname, '..', '..', 'data-test')
|
|
12
|
-
: path.join(__dirname, '..', '..', 'data');
|
|
13
|
-
if (!fs.existsSync(DATA_DIR)) fs.mkdirSync(DATA_DIR, { recursive: true });
|
|
14
|
-
|
|
15
|
-
const dbFile = isTest ? 'wab-test.db' : 'wab.db';
|
|
16
|
-
const db = new Database(path.join(DATA_DIR, dbFile));
|
|
17
|
-
|
|
18
|
-
db.pragma('journal_mode = WAL');
|
|
19
|
-
db.pragma('foreign_keys = ON');
|
|
20
|
-
|
|
21
|
-
db.exec(`
|
|
22
|
-
CREATE TABLE IF NOT EXISTS users (
|
|
23
|
-
id TEXT PRIMARY KEY,
|
|
24
|
-
email TEXT UNIQUE NOT NULL,
|
|
25
|
-
password TEXT NOT NULL,
|
|
26
|
-
name TEXT NOT NULL,
|
|
27
|
-
company TEXT,
|
|
28
|
-
created_at TEXT DEFAULT (datetime('now')),
|
|
29
|
-
updated_at TEXT DEFAULT (datetime('now'))
|
|
30
|
-
);
|
|
31
|
-
|
|
32
|
-
CREATE TABLE IF NOT EXISTS sites (
|
|
33
|
-
id TEXT PRIMARY KEY,
|
|
34
|
-
user_id TEXT NOT NULL,
|
|
35
|
-
domain TEXT NOT NULL,
|
|
36
|
-
name TEXT NOT NULL,
|
|
37
|
-
description TEXT,
|
|
38
|
-
tier TEXT DEFAULT 'free' CHECK(tier IN ('free','starter','pro','enterprise')),
|
|
39
|
-
license_key TEXT UNIQUE NOT NULL,
|
|
40
|
-
api_key TEXT UNIQUE,
|
|
41
|
-
config TEXT DEFAULT '{}',
|
|
42
|
-
active INTEGER DEFAULT 1,
|
|
43
|
-
created_at TEXT DEFAULT (datetime('now')),
|
|
44
|
-
updated_at TEXT DEFAULT (datetime('now')),
|
|
45
|
-
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
|
46
|
-
);
|
|
47
|
-
|
|
48
|
-
CREATE TABLE IF NOT EXISTS analytics (
|
|
49
|
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
50
|
-
site_id TEXT NOT NULL,
|
|
51
|
-
action_name TEXT NOT NULL,
|
|
52
|
-
agent_id TEXT,
|
|
53
|
-
trigger_type TEXT,
|
|
54
|
-
success INTEGER,
|
|
55
|
-
metadata TEXT DEFAULT '{}',
|
|
56
|
-
created_at TEXT DEFAULT (datetime('now')),
|
|
57
|
-
FOREIGN KEY (site_id) REFERENCES sites(id) ON DELETE CASCADE
|
|
58
|
-
);
|
|
59
|
-
|
|
60
|
-
CREATE TABLE IF NOT EXISTS subscriptions (
|
|
61
|
-
id TEXT PRIMARY KEY,
|
|
62
|
-
user_id TEXT NOT NULL,
|
|
63
|
-
site_id TEXT NOT NULL,
|
|
64
|
-
tier TEXT NOT NULL CHECK(tier IN ('free','starter','pro','enterprise')),
|
|
65
|
-
status TEXT DEFAULT 'active' CHECK(status IN ('active','cancelled','expired','trial')),
|
|
66
|
-
started_at TEXT DEFAULT (datetime('now')),
|
|
67
|
-
expires_at TEXT,
|
|
68
|
-
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
|
|
69
|
-
FOREIGN KEY (site_id) REFERENCES sites(id) ON DELETE CASCADE
|
|
70
|
-
);
|
|
71
|
-
|
|
72
|
-
CREATE INDEX IF NOT EXISTS idx_sites_domain ON sites(domain);
|
|
73
|
-
CREATE INDEX IF NOT EXISTS idx_sites_license ON sites(license_key);
|
|
74
|
-
CREATE INDEX IF NOT EXISTS idx_analytics_site ON analytics(site_id);
|
|
75
|
-
CREATE INDEX IF NOT EXISTS idx_analytics_created ON analytics(created_at);
|
|
76
|
-
|
|
77
|
-
CREATE TABLE IF NOT EXISTS admins (
|
|
78
|
-
id TEXT PRIMARY KEY,
|
|
79
|
-
email TEXT UNIQUE NOT NULL,
|
|
80
|
-
password TEXT NOT NULL,
|
|
81
|
-
name TEXT NOT NULL,
|
|
82
|
-
role TEXT DEFAULT 'admin' CHECK(role IN ('admin','superadmin')),
|
|
83
|
-
created_at TEXT DEFAULT (datetime('now'))
|
|
84
|
-
);
|
|
85
|
-
|
|
86
|
-
CREATE TABLE IF NOT EXISTS free_grants (
|
|
87
|
-
id TEXT PRIMARY KEY,
|
|
88
|
-
user_id TEXT NOT NULL,
|
|
89
|
-
site_id TEXT,
|
|
90
|
-
granted_tier TEXT NOT NULL CHECK(granted_tier IN ('starter','pro','enterprise')),
|
|
91
|
-
reason TEXT,
|
|
92
|
-
granted_by TEXT NOT NULL,
|
|
93
|
-
granted_at TEXT DEFAULT (datetime('now')),
|
|
94
|
-
expires_at TEXT,
|
|
95
|
-
active INTEGER DEFAULT 1,
|
|
96
|
-
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
|
|
97
|
-
FOREIGN KEY (granted_by) REFERENCES admins(id)
|
|
98
|
-
);
|
|
99
|
-
|
|
100
|
-
CREATE TABLE IF NOT EXISTS stripe_customers (
|
|
101
|
-
id TEXT PRIMARY KEY,
|
|
102
|
-
user_id TEXT UNIQUE NOT NULL,
|
|
103
|
-
stripe_customer_id TEXT UNIQUE,
|
|
104
|
-
created_at TEXT DEFAULT (datetime('now')),
|
|
105
|
-
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
|
106
|
-
);
|
|
107
|
-
|
|
108
|
-
CREATE TABLE IF NOT EXISTS stripe_subscriptions (
|
|
109
|
-
id TEXT PRIMARY KEY,
|
|
110
|
-
user_id TEXT NOT NULL,
|
|
111
|
-
site_id TEXT NOT NULL,
|
|
112
|
-
stripe_subscription_id TEXT UNIQUE,
|
|
113
|
-
stripe_price_id TEXT,
|
|
114
|
-
tier TEXT NOT NULL CHECK(tier IN ('starter','pro','enterprise')),
|
|
115
|
-
status TEXT DEFAULT 'active' CHECK(status IN ('active','cancelled','past_due','trialing','incomplete')),
|
|
116
|
-
current_period_start TEXT,
|
|
117
|
-
current_period_end TEXT,
|
|
118
|
-
created_at TEXT DEFAULT (datetime('now')),
|
|
119
|
-
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
|
|
120
|
-
FOREIGN KEY (site_id) REFERENCES sites(id) ON DELETE CASCADE
|
|
121
|
-
);
|
|
122
|
-
|
|
123
|
-
CREATE TABLE IF NOT EXISTS payments (
|
|
124
|
-
id TEXT PRIMARY KEY,
|
|
125
|
-
user_id TEXT NOT NULL,
|
|
126
|
-
stripe_payment_id TEXT UNIQUE,
|
|
127
|
-
amount INTEGER NOT NULL,
|
|
128
|
-
currency TEXT DEFAULT 'usd',
|
|
129
|
-
status TEXT DEFAULT 'succeeded',
|
|
130
|
-
description TEXT,
|
|
131
|
-
created_at TEXT DEFAULT (datetime('now')),
|
|
132
|
-
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
|
133
|
-
);
|
|
134
|
-
|
|
135
|
-
CREATE TABLE IF NOT EXISTS notifications_log (
|
|
136
|
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
137
|
-
user_id TEXT,
|
|
138
|
-
email_to TEXT NOT NULL,
|
|
139
|
-
template TEXT NOT NULL,
|
|
140
|
-
subject TEXT NOT NULL,
|
|
141
|
-
status TEXT DEFAULT 'sent' CHECK(status IN ('sent','failed','queued')),
|
|
142
|
-
error_message TEXT,
|
|
143
|
-
created_at TEXT DEFAULT (datetime('now'))
|
|
144
|
-
);
|
|
145
|
-
|
|
146
|
-
CREATE TABLE IF NOT EXISTS smtp_settings (
|
|
147
|
-
id INTEGER PRIMARY KEY CHECK(id = 1),
|
|
148
|
-
host TEXT,
|
|
149
|
-
port INTEGER DEFAULT 587,
|
|
150
|
-
secure INTEGER DEFAULT 0,
|
|
151
|
-
username TEXT,
|
|
152
|
-
password TEXT,
|
|
153
|
-
from_name TEXT DEFAULT 'Web Agent Bridge',
|
|
154
|
-
from_email TEXT,
|
|
155
|
-
enabled INTEGER DEFAULT 0,
|
|
156
|
-
updated_at TEXT DEFAULT (datetime('now'))
|
|
157
|
-
);
|
|
158
|
-
|
|
159
|
-
INSERT OR IGNORE INTO smtp_settings (id) VALUES (1);
|
|
160
|
-
|
|
161
|
-
CREATE TABLE IF NOT EXISTS platform_settings (
|
|
162
|
-
key TEXT PRIMARY KEY,
|
|
163
|
-
value TEXT,
|
|
164
|
-
updated_at TEXT DEFAULT (datetime('now'))
|
|
165
|
-
);
|
|
166
|
-
|
|
167
|
-
CREATE INDEX IF NOT EXISTS idx_free_grants_user ON free_grants(user_id);
|
|
168
|
-
CREATE INDEX IF NOT EXISTS idx_stripe_subs_user ON stripe_subscriptions(user_id);
|
|
169
|
-
CREATE INDEX IF NOT EXISTS idx_payments_user ON payments(user_id);
|
|
170
|
-
CREATE INDEX IF NOT EXISTS idx_notifications_user ON notifications_log(user_id);
|
|
171
|
-
`);
|
|
172
|
-
|
|
173
|
-
function generateLicenseKey() {
|
|
174
|
-
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
|
|
175
|
-
const segments = [];
|
|
176
|
-
for (let s = 0; s < 4; s++) {
|
|
177
|
-
let seg = '';
|
|
178
|
-
const bytes = crypto.randomBytes(5);
|
|
179
|
-
for (let i = 0; i < 5; i++) seg += chars[bytes[i] % chars.length];
|
|
180
|
-
segments.push(seg);
|
|
181
|
-
}
|
|
182
|
-
return `WAB-${segments.join('-')}`;
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
function generateApiKey() {
|
|
186
|
-
return `wab_${uuidv4().replace(/-/g, '')}`;
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
// ─── User Operations ──────────────────────────────────────────────────
|
|
190
|
-
const createUser = db.prepare(`
|
|
191
|
-
INSERT INTO users (id, email, password, name, company) VALUES (?, ?, ?, ?, ?)
|
|
192
|
-
`);
|
|
193
|
-
|
|
194
|
-
const findUserByEmail = db.prepare(`SELECT * FROM users WHERE email = ?`);
|
|
195
|
-
const findUserById = db.prepare(`SELECT id, email, name, company, created_at FROM users WHERE id = ?`);
|
|
196
|
-
|
|
197
|
-
function registerUser({ email, password, name, company }) {
|
|
198
|
-
const id = uuidv4();
|
|
199
|
-
const hashed = bcrypt.hashSync(password, 12);
|
|
200
|
-
createUser.run(id, email, hashed, name, company || null);
|
|
201
|
-
return { id, email, name, company };
|
|
202
|
-
}
|
|
203
|
-
|
|
204
|
-
function loginUser({ email, password }) {
|
|
205
|
-
const user = findUserByEmail.get(email);
|
|
206
|
-
if (!user) return null;
|
|
207
|
-
if (!bcrypt.compareSync(password, user.password)) return null;
|
|
208
|
-
return { id: user.id, email: user.email, name: user.name, company: user.company };
|
|
209
|
-
}
|
|
210
|
-
|
|
211
|
-
// ─── Site Operations ──────────────────────────────────────────────────
|
|
212
|
-
const createSite = db.prepare(`
|
|
213
|
-
INSERT INTO sites (id, user_id, domain, name, description, tier, license_key, api_key, config)
|
|
214
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
215
|
-
`);
|
|
216
|
-
|
|
217
|
-
const findSitesByUser = db.prepare(`SELECT * FROM sites WHERE user_id = ? ORDER BY created_at DESC`);
|
|
218
|
-
const findSiteById = db.prepare(`SELECT * FROM sites WHERE id = ?`);
|
|
219
|
-
const findSiteByLicense = db.prepare(`SELECT * FROM sites WHERE license_key = ? AND active = 1`);
|
|
220
|
-
const findSiteByDomainAndLicense = db.prepare(`SELECT * FROM sites WHERE domain = ? AND license_key = ? AND active = 1`);
|
|
221
|
-
const updateSiteConfig = db.prepare(`UPDATE sites SET config = ?, updated_at = datetime('now') WHERE id = ? AND user_id = ?`);
|
|
222
|
-
const updateSiteTier = db.prepare(`UPDATE sites SET tier = ?, updated_at = datetime('now') WHERE id = ? AND user_id = ?`);
|
|
223
|
-
const deleteSite = db.prepare(`UPDATE sites SET active = 0, updated_at = datetime('now') WHERE id = ? AND user_id = ?`);
|
|
224
|
-
|
|
225
|
-
function addSite({ userId, domain, name, description, tier }) {
|
|
226
|
-
const id = uuidv4();
|
|
227
|
-
const licenseKey = generateLicenseKey();
|
|
228
|
-
const apiKey = generateApiKey();
|
|
229
|
-
const config = JSON.stringify({
|
|
230
|
-
agentPermissions: { readContent: true, click: true, fillForms: false, scroll: true, navigate: false, apiAccess: false, automatedLogin: false, extractData: false },
|
|
231
|
-
features: { advancedAnalytics: false, realTimeUpdates: false },
|
|
232
|
-
restrictions: { allowedSelectors: [], blockedSelectors: ['.private', '[data-private]'], rateLimit: { maxCallsPerMinute: 60 } },
|
|
233
|
-
logging: { enabled: false, level: 'basic' }
|
|
234
|
-
});
|
|
235
|
-
createSite.run(id, userId, domain, name, description || '', tier || 'free', licenseKey, apiKey, config);
|
|
236
|
-
return { id, domain, name, licenseKey, apiKey, tier: tier || 'free' };
|
|
237
|
-
}
|
|
238
|
-
|
|
239
|
-
// ─── Analytics ────────────────────────────────────────────────────────
|
|
240
|
-
const insertAnalytic = db.prepare(`
|
|
241
|
-
INSERT INTO analytics (site_id, action_name, agent_id, trigger_type, success, metadata)
|
|
242
|
-
VALUES (?, ?, ?, ?, ?, ?)
|
|
243
|
-
`);
|
|
244
|
-
|
|
245
|
-
const getAnalyticsBySite = db.prepare(`
|
|
246
|
-
SELECT action_name, trigger_type, COUNT(*) as count, SUM(success) as successes
|
|
247
|
-
FROM analytics WHERE site_id = ? AND created_at >= ? GROUP BY action_name, trigger_type
|
|
248
|
-
ORDER BY count DESC
|
|
249
|
-
`);
|
|
250
|
-
|
|
251
|
-
const getAnalyticsTimeline = db.prepare(`
|
|
252
|
-
SELECT date(created_at) as day, COUNT(*) as count
|
|
253
|
-
FROM analytics WHERE site_id = ? AND created_at >= ?
|
|
254
|
-
GROUP BY day ORDER BY day
|
|
255
|
-
`);
|
|
256
|
-
|
|
257
|
-
function recordAnalytic({ siteId, actionName, agentId, triggerType, success, metadata }) {
|
|
258
|
-
insertAnalytic.run(siteId, actionName, agentId || null, triggerType || null, success ? 1 : 0, JSON.stringify(metadata || {}));
|
|
259
|
-
}
|
|
260
|
-
|
|
261
|
-
// ─── License Verification ─────────────────────────────────────────────
|
|
262
|
-
function verifyLicense(domain, licenseKey) {
|
|
263
|
-
const site = findSiteByDomainAndLicense.get(domain, licenseKey);
|
|
264
|
-
if (!site) {
|
|
265
|
-
const siteByKey = findSiteByLicense.get(licenseKey);
|
|
266
|
-
if (siteByKey) return { valid: false, error: 'Domain mismatch', tier: 'free' };
|
|
267
|
-
return { valid: false, error: 'Invalid license key', tier: 'free' };
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
// Check for free grant override
|
|
271
|
-
const grant = db.prepare(`SELECT * FROM free_grants WHERE user_id = ? AND (site_id = ? OR site_id IS NULL) AND active = 1 AND (expires_at IS NULL OR expires_at > datetime('now')) ORDER BY granted_at DESC LIMIT 1`).get(site.user_id, site.id);
|
|
272
|
-
const effectiveTier = grant ? grant.granted_tier : site.tier;
|
|
273
|
-
|
|
274
|
-
const tierPermissions = {
|
|
275
|
-
free: { apiAccess: false, automatedLogin: false, extractData: false, advancedAnalytics: false },
|
|
276
|
-
starter: { apiAccess: false, automatedLogin: true, extractData: false, advancedAnalytics: true },
|
|
277
|
-
pro: { apiAccess: true, automatedLogin: true, extractData: true, advancedAnalytics: true },
|
|
278
|
-
enterprise: { apiAccess: true, automatedLogin: true, extractData: true, advancedAnalytics: true }
|
|
279
|
-
};
|
|
280
|
-
|
|
281
|
-
return {
|
|
282
|
-
valid: true,
|
|
283
|
-
tier: effectiveTier,
|
|
284
|
-
domain: site.domain,
|
|
285
|
-
allowedPermissions: tierPermissions[effectiveTier] || tierPermissions.free
|
|
286
|
-
};
|
|
287
|
-
}
|
|
288
|
-
|
|
289
|
-
// ─── Admin Operations ─────────────────────────────────────────────────
|
|
290
|
-
function createAdmin({ email, password, name, role }) {
|
|
291
|
-
const id = uuidv4();
|
|
292
|
-
const hashed = bcrypt.hashSync(password, 12);
|
|
293
|
-
db.prepare(`INSERT INTO admins (id, email, password, name, role) VALUES (?, ?, ?, ?, ?)`).run(id, email, hashed, name, role || 'admin');
|
|
294
|
-
return { id, email, name, role: role || 'admin' };
|
|
295
|
-
}
|
|
296
|
-
|
|
297
|
-
function loginAdmin({ email, password }) {
|
|
298
|
-
const admin = db.prepare(`SELECT * FROM admins WHERE email = ?`).get(email);
|
|
299
|
-
if (!admin) return null;
|
|
300
|
-
if (!bcrypt.compareSync(password, admin.password)) return null;
|
|
301
|
-
return { id: admin.id, email: admin.email, name: admin.name, role: admin.role };
|
|
302
|
-
}
|
|
303
|
-
|
|
304
|
-
function findAdminById(id) {
|
|
305
|
-
return db.prepare(`SELECT id, email, name, role, created_at FROM admins WHERE id = ?`).get(id);
|
|
306
|
-
}
|
|
307
|
-
|
|
308
|
-
/**
|
|
309
|
-
* First-run admin creation from env only (no hardcoded password).
|
|
310
|
-
* Alternatively use: node scripts/create-admin.js <email> <password>
|
|
311
|
-
*/
|
|
312
|
-
function maybeBootstrapAdmin() {
|
|
313
|
-
if (isTest) return;
|
|
314
|
-
const count = db.prepare(`SELECT COUNT(*) as c FROM admins`).get().c;
|
|
315
|
-
if (count > 0) return;
|
|
316
|
-
const email = process.env.BOOTSTRAP_ADMIN_EMAIL;
|
|
317
|
-
const password = process.env.BOOTSTRAP_ADMIN_PASSWORD;
|
|
318
|
-
if (!email || !password) {
|
|
319
|
-
console.warn('[WAB] No admin accounts. Set BOOTSTRAP_ADMIN_EMAIL and BOOTSTRAP_ADMIN_PASSWORD for first boot, or run: node scripts/create-admin.js <email> <password>');
|
|
320
|
-
return;
|
|
321
|
-
}
|
|
322
|
-
createAdmin({ email, password, name: 'Bootstrap Admin', role: 'superadmin' });
|
|
323
|
-
console.log('[WAB] Bootstrap admin created from BOOTSTRAP_ADMIN_* environment variables.');
|
|
324
|
-
}
|
|
325
|
-
|
|
326
|
-
// ─── Admin Queries ────────────────────────────────────────────────────
|
|
327
|
-
function getAllUsers() {
|
|
328
|
-
return db.prepare(`SELECT id, email, name, company, created_at FROM users ORDER BY created_at DESC`).all();
|
|
329
|
-
}
|
|
330
|
-
|
|
331
|
-
function getAllSites() {
|
|
332
|
-
return db.prepare(`SELECT s.*, u.email as user_email, u.name as user_name FROM sites s LEFT JOIN users u ON s.user_id = u.id ORDER BY s.created_at DESC`).all();
|
|
333
|
-
}
|
|
334
|
-
|
|
335
|
-
function getAdminStats() {
|
|
336
|
-
const totalUsers = db.prepare(`SELECT COUNT(*) as c FROM users`).get().c;
|
|
337
|
-
const totalSites = db.prepare(`SELECT COUNT(*) as c FROM sites WHERE active = 1`).get().c;
|
|
338
|
-
const totalAnalytics = db.prepare(`SELECT COUNT(*) as c FROM analytics`).get().c;
|
|
339
|
-
const todayAnalytics = db.prepare(`SELECT COUNT(*) as c FROM analytics WHERE created_at >= date('now')`).get().c;
|
|
340
|
-
const tierBreakdown = db.prepare(`SELECT tier, COUNT(*) as count FROM sites WHERE active = 1 GROUP BY tier`).all();
|
|
341
|
-
const recentUsers = db.prepare(`SELECT id, email, name, company, created_at FROM users ORDER BY created_at DESC LIMIT 10`).all();
|
|
342
|
-
const totalRevenue = db.prepare(`SELECT COALESCE(SUM(amount), 0) as total FROM payments WHERE status = 'succeeded'`).get().total;
|
|
343
|
-
const activeGrants = db.prepare(`SELECT COUNT(*) as c FROM free_grants WHERE active = 1 AND (expires_at IS NULL OR expires_at > datetime('now'))`).get().c;
|
|
344
|
-
const monthlySignups = db.prepare(`SELECT COUNT(*) as c FROM users WHERE created_at >= date('now', '-30 days')`).get().c;
|
|
345
|
-
return { totalUsers, totalSites, totalAnalytics, todayAnalytics, tierBreakdown, recentUsers, totalRevenue, activeGrants, monthlySignups };
|
|
346
|
-
}
|
|
347
|
-
|
|
348
|
-
function getPlatformAnalytics(days) {
|
|
349
|
-
const since = new Date(Date.now() - days * 86400000).toISOString();
|
|
350
|
-
const timeline = db.prepare(`SELECT date(created_at) as day, COUNT(*) as count FROM analytics WHERE created_at >= ? GROUP BY day ORDER BY day`).all(since);
|
|
351
|
-
const topActions = db.prepare(`SELECT action_name, COUNT(*) as count FROM analytics WHERE created_at >= ? GROUP BY action_name ORDER BY count DESC LIMIT 20`).all(since);
|
|
352
|
-
const signups = db.prepare(`SELECT date(created_at) as day, COUNT(*) as count FROM users WHERE created_at >= ? GROUP BY day ORDER BY day`).all(since);
|
|
353
|
-
return { timeline, topActions, signups };
|
|
354
|
-
}
|
|
355
|
-
|
|
356
|
-
// ─── Free Grant Operations ────────────────────────────────────────────
|
|
357
|
-
function grantFreeTier({ userId, siteId, tier, reason, grantedBy, expiresAt }) {
|
|
358
|
-
const id = uuidv4();
|
|
359
|
-
db.prepare(`INSERT INTO free_grants (id, user_id, site_id, granted_tier, reason, granted_by, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?)`).run(id, userId, siteId || null, tier, reason || null, grantedBy, expiresAt || null);
|
|
360
|
-
if (siteId) {
|
|
361
|
-
db.prepare(`UPDATE sites SET tier = ?, updated_at = datetime('now') WHERE id = ?`).run(tier, siteId);
|
|
362
|
-
} else {
|
|
363
|
-
db.prepare(`UPDATE sites SET tier = ?, updated_at = datetime('now') WHERE user_id = ? AND active = 1`).run(tier, userId);
|
|
364
|
-
}
|
|
365
|
-
return { id, userId, siteId, tier, reason };
|
|
366
|
-
}
|
|
367
|
-
|
|
368
|
-
function revokeGrant(grantId) {
|
|
369
|
-
const grant = db.prepare(`SELECT * FROM free_grants WHERE id = ?`).get(grantId);
|
|
370
|
-
if (!grant) return false;
|
|
371
|
-
db.prepare(`UPDATE free_grants SET active = 0 WHERE id = ?`).run(grantId);
|
|
372
|
-
if (grant.site_id) {
|
|
373
|
-
db.prepare(`UPDATE sites SET tier = 'free', updated_at = datetime('now') WHERE id = ?`).run(grant.site_id);
|
|
374
|
-
} else {
|
|
375
|
-
db.prepare(`UPDATE sites SET tier = 'free', updated_at = datetime('now') WHERE user_id = ? AND active = 1`).run(grant.user_id);
|
|
376
|
-
}
|
|
377
|
-
return true;
|
|
378
|
-
}
|
|
379
|
-
|
|
380
|
-
function getActiveGrants() {
|
|
381
|
-
return db.prepare(`SELECT g.*, u.email as user_email, u.name as user_name, a.name as admin_name FROM free_grants g LEFT JOIN users u ON g.user_id = u.id LEFT JOIN admins a ON g.granted_by = a.id WHERE g.active = 1 ORDER BY g.granted_at DESC`).all();
|
|
382
|
-
}
|
|
383
|
-
|
|
384
|
-
// ─── Stripe DB Operations ─────────────────────────────────────────────
|
|
385
|
-
function saveStripeCustomer(userId, stripeCustomerId) {
|
|
386
|
-
const id = uuidv4();
|
|
387
|
-
db.prepare(`INSERT OR REPLACE INTO stripe_customers (id, user_id, stripe_customer_id) VALUES (?, ?, ?)`).run(id, userId, stripeCustomerId);
|
|
388
|
-
}
|
|
389
|
-
|
|
390
|
-
function getStripeCustomer(userId) {
|
|
391
|
-
return db.prepare(`SELECT * FROM stripe_customers WHERE user_id = ?`).get(userId);
|
|
392
|
-
}
|
|
393
|
-
|
|
394
|
-
function saveStripeSubscription({ userId, siteId, stripeSubId, stripePriceId, tier, status, periodStart, periodEnd }) {
|
|
395
|
-
const id = uuidv4();
|
|
396
|
-
db.prepare(`INSERT INTO stripe_subscriptions (id, user_id, site_id, stripe_subscription_id, stripe_price_id, tier, status, current_period_start, current_period_end) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(id, userId, siteId, stripeSubId, stripePriceId, tier, status || 'active', periodStart, periodEnd);
|
|
397
|
-
}
|
|
398
|
-
|
|
399
|
-
function updateStripeSubscription(stripeSubId, { status, periodStart, periodEnd, tier }) {
|
|
400
|
-
const updates = [];
|
|
401
|
-
const params = [];
|
|
402
|
-
if (status) { updates.push('status = ?'); params.push(status); }
|
|
403
|
-
if (periodStart) { updates.push('current_period_start = ?'); params.push(periodStart); }
|
|
404
|
-
if (periodEnd) { updates.push('current_period_end = ?'); params.push(periodEnd); }
|
|
405
|
-
if (tier) { updates.push('tier = ?'); params.push(tier); }
|
|
406
|
-
if (updates.length === 0) return;
|
|
407
|
-
params.push(stripeSubId);
|
|
408
|
-
db.prepare(`UPDATE stripe_subscriptions SET ${updates.join(', ')} WHERE stripe_subscription_id = ?`).run(...params);
|
|
409
|
-
}
|
|
410
|
-
|
|
411
|
-
function getStripeSubscriptionBySubId(stripeSubId) {
|
|
412
|
-
return db.prepare(`SELECT * FROM stripe_subscriptions WHERE stripe_subscription_id = ?`).get(stripeSubId);
|
|
413
|
-
}
|
|
414
|
-
|
|
415
|
-
function savePayment({ userId, stripePaymentId, amount, currency, status, description }) {
|
|
416
|
-
const id = uuidv4();
|
|
417
|
-
db.prepare(`INSERT INTO payments (id, user_id, stripe_payment_id, amount, currency, status, description) VALUES (?, ?, ?, ?, ?, ?, ?)`).run(id, userId, stripePaymentId, amount, currency || 'usd', status || 'succeeded', description || null);
|
|
418
|
-
}
|
|
419
|
-
|
|
420
|
-
function getPayments(limit) {
|
|
421
|
-
return db.prepare(`SELECT p.*, u.email as user_email, u.name as user_name FROM payments p LEFT JOIN users u ON p.user_id = u.id ORDER BY p.created_at DESC LIMIT ?`).all(limit || 50);
|
|
422
|
-
}
|
|
423
|
-
|
|
424
|
-
// ─── SMTP Settings ────────────────────────────────────────────────────
|
|
425
|
-
function getSmtpSettings() {
|
|
426
|
-
const row = db.prepare(`SELECT * FROM smtp_settings WHERE id = 1`).get();
|
|
427
|
-
if (!row) return null;
|
|
428
|
-
if (row.password) {
|
|
429
|
-
const dec = decryptOptional(row.password);
|
|
430
|
-
return { ...row, password: dec != null ? dec : row.password };
|
|
431
|
-
}
|
|
432
|
-
return row;
|
|
433
|
-
}
|
|
434
|
-
|
|
435
|
-
function updateSmtpSettings({ host, port, secure, username, password, fromName, fromEmail, enabled }) {
|
|
436
|
-
const current = db.prepare(`SELECT password FROM smtp_settings WHERE id = 1`).get();
|
|
437
|
-
let nextPassword = current && current.password;
|
|
438
|
-
if (password !== undefined) {
|
|
439
|
-
nextPassword = encryptOptional(password);
|
|
440
|
-
}
|
|
441
|
-
db.prepare(`UPDATE smtp_settings SET host = ?, port = ?, secure = ?, username = ?, password = ?, from_name = ?, from_email = ?, enabled = ?, updated_at = datetime('now') WHERE id = 1`).run(host, port || 587, secure ? 1 : 0, username, nextPassword, fromName || 'Web Agent Bridge', fromEmail, enabled ? 1 : 0);
|
|
442
|
-
}
|
|
443
|
-
|
|
444
|
-
function logNotification({ userId, emailTo, template, subject, status, errorMessage }) {
|
|
445
|
-
db.prepare(`INSERT INTO notifications_log (user_id, email_to, template, subject, status, error_message) VALUES (?, ?, ?, ?, ?, ?)`).run(userId || null, emailTo, template, subject, status || 'sent', errorMessage || null);
|
|
446
|
-
}
|
|
447
|
-
|
|
448
|
-
function getNotificationLogs(limit) {
|
|
449
|
-
return db.prepare(`SELECT * FROM notifications_log ORDER BY created_at DESC LIMIT ?`).all(limit || 100);
|
|
450
|
-
}
|
|
451
|
-
|
|
452
|
-
// ─── Admin User Management ───────────────────────────────────────────
|
|
453
|
-
function adminUpdateUserTier(userId, siteId, tier) {
|
|
454
|
-
if (siteId) {
|
|
455
|
-
db.prepare(`UPDATE sites SET tier = ?, updated_at = datetime('now') WHERE id = ? AND user_id = ?`).run(tier, siteId, userId);
|
|
456
|
-
} else {
|
|
457
|
-
db.prepare(`UPDATE sites SET tier = ?, updated_at = datetime('now') WHERE user_id = ? AND active = 1`).run(tier, userId);
|
|
458
|
-
}
|
|
459
|
-
}
|
|
460
|
-
|
|
461
|
-
/**
|
|
462
|
-
* Admin: update any site by id (tier and/or active).
|
|
463
|
-
*
|
|
464
|
-
* @param {string} siteId Site UUID.
|
|
465
|
-
* @param {{ tier?: string, active?: boolean }} updates Partial updates.
|
|
466
|
-
* @returns {boolean}
|
|
467
|
-
*/
|
|
468
|
-
function adminUpdateSite(siteId, updates) {
|
|
469
|
-
const site = findSiteById.get(siteId);
|
|
470
|
-
if (!site) return false;
|
|
471
|
-
let tier = site.tier;
|
|
472
|
-
let active = site.active;
|
|
473
|
-
if (updates.tier !== undefined) {
|
|
474
|
-
if (!['free', 'starter', 'pro', 'enterprise'].includes(updates.tier)) return false;
|
|
475
|
-
tier = updates.tier;
|
|
476
|
-
}
|
|
477
|
-
if (updates.active !== undefined) {
|
|
478
|
-
active = updates.active ? 1 : 0;
|
|
479
|
-
}
|
|
480
|
-
db.prepare(`UPDATE sites SET tier = ?, active = ?, updated_at = datetime('now') WHERE id = ?`).run(tier, active, siteId);
|
|
481
|
-
return true;
|
|
482
|
-
}
|
|
483
|
-
|
|
484
|
-
function adminDeleteUser(userId) {
|
|
485
|
-
db.prepare(`UPDATE sites SET active = 0 WHERE user_id = ?`).run(userId);
|
|
486
|
-
db.prepare(`DELETE FROM users WHERE id = ?`).run(userId);
|
|
487
|
-
}
|
|
488
|
-
|
|
489
|
-
function getUserFullDetails(userId) {
|
|
490
|
-
const user = db.prepare(`SELECT id, email, name, company, created_at FROM users WHERE id = ?`).get(userId);
|
|
491
|
-
if (!user) return null;
|
|
492
|
-
const sites = db.prepare(`SELECT * FROM sites WHERE user_id = ? ORDER BY created_at DESC`).all(userId);
|
|
493
|
-
const grants = db.prepare(`SELECT * FROM free_grants WHERE user_id = ? AND active = 1`).all(userId);
|
|
494
|
-
const payments = db.prepare(`SELECT * FROM payments WHERE user_id = ? ORDER BY created_at DESC`).all(userId);
|
|
495
|
-
const stripeCustomer = db.prepare(`SELECT * FROM stripe_customers WHERE user_id = ?`).get(userId);
|
|
496
|
-
return { ...user, sites, grants, payments, stripeCustomer };
|
|
497
|
-
}
|
|
498
|
-
|
|
499
|
-
// ─── Platform Settings ───────────────────────────────────────────────
|
|
500
|
-
function getPlatformSetting(key) {
|
|
501
|
-
const row = db.prepare(`SELECT value FROM platform_settings WHERE key = ?`).get(key);
|
|
502
|
-
return row ? row.value : null;
|
|
503
|
-
}
|
|
504
|
-
|
|
505
|
-
function setPlatformSetting(key, value) {
|
|
506
|
-
db.prepare(`INSERT OR REPLACE INTO platform_settings (key, value, updated_at) VALUES (?, ?, datetime('now'))`).run(key, value);
|
|
507
|
-
}
|
|
508
|
-
|
|
509
|
-
module.exports = {
|
|
510
|
-
db,
|
|
511
|
-
registerUser,
|
|
512
|
-
loginUser,
|
|
513
|
-
findUserById,
|
|
514
|
-
findUserByEmail,
|
|
515
|
-
addSite,
|
|
516
|
-
findSitesByUser,
|
|
517
|
-
findSiteById,
|
|
518
|
-
findSiteByLicense,
|
|
519
|
-
updateSiteConfig,
|
|
520
|
-
updateSiteTier,
|
|
521
|
-
deleteSite,
|
|
522
|
-
recordAnalytic,
|
|
523
|
-
getAnalyticsBySite,
|
|
524
|
-
getAnalyticsTimeline,
|
|
525
|
-
verifyLicense,
|
|
526
|
-
generateLicenseKey,
|
|
527
|
-
generateApiKey,
|
|
528
|
-
// Admin
|
|
529
|
-
createAdmin,
|
|
530
|
-
loginAdmin,
|
|
531
|
-
findAdminById,
|
|
532
|
-
maybeBootstrapAdmin,
|
|
533
|
-
getAllUsers,
|
|
534
|
-
getAllSites,
|
|
535
|
-
getAdminStats,
|
|
536
|
-
getPlatformAnalytics,
|
|
537
|
-
adminUpdateUserTier,
|
|
538
|
-
adminUpdateSite,
|
|
539
|
-
adminDeleteUser,
|
|
540
|
-
getUserFullDetails,
|
|
541
|
-
// Free Grants
|
|
542
|
-
grantFreeTier,
|
|
543
|
-
revokeGrant,
|
|
544
|
-
getActiveGrants,
|
|
545
|
-
// Stripe
|
|
546
|
-
saveStripeCustomer,
|
|
547
|
-
getStripeCustomer,
|
|
548
|
-
saveStripeSubscription,
|
|
549
|
-
updateStripeSubscription,
|
|
550
|
-
getStripeSubscriptionBySubId,
|
|
551
|
-
savePayment,
|
|
552
|
-
getPayments,
|
|
553
|
-
// SMTP
|
|
554
|
-
getSmtpSettings,
|
|
555
|
-
updateSmtpSettings,
|
|
556
|
-
logNotification,
|
|
557
|
-
getNotificationLogs,
|
|
558
|
-
// Platform
|
|
559
|
-
getPlatformSetting,
|
|
560
|
-
setPlatformSetting
|
|
561
|
-
};
|
|
1
|
+
const Database = require('better-sqlite3');
|
|
2
|
+
const path = require('path');
|
|
3
|
+
const fs = require('fs');
|
|
4
|
+
const crypto = require('crypto');
|
|
5
|
+
const bcrypt = require('bcryptjs');
|
|
6
|
+
const { v4: uuidv4 } = require('uuid');
|
|
7
|
+
const { encryptOptional, decryptOptional } = require('../utils/secureFields');
|
|
8
|
+
|
|
9
|
+
const isTest = process.env.NODE_ENV === 'test';
|
|
10
|
+
const DATA_DIR = isTest
|
|
11
|
+
? path.join(__dirname, '..', '..', 'data-test')
|
|
12
|
+
: path.join(__dirname, '..', '..', 'data');
|
|
13
|
+
if (!fs.existsSync(DATA_DIR)) fs.mkdirSync(DATA_DIR, { recursive: true });
|
|
14
|
+
|
|
15
|
+
const dbFile = isTest ? 'wab-test.db' : 'wab.db';
|
|
16
|
+
const db = new Database(path.join(DATA_DIR, dbFile));
|
|
17
|
+
|
|
18
|
+
db.pragma('journal_mode = WAL');
|
|
19
|
+
db.pragma('foreign_keys = ON');
|
|
20
|
+
|
|
21
|
+
db.exec(`
|
|
22
|
+
CREATE TABLE IF NOT EXISTS users (
|
|
23
|
+
id TEXT PRIMARY KEY,
|
|
24
|
+
email TEXT UNIQUE NOT NULL,
|
|
25
|
+
password TEXT NOT NULL,
|
|
26
|
+
name TEXT NOT NULL,
|
|
27
|
+
company TEXT,
|
|
28
|
+
created_at TEXT DEFAULT (datetime('now')),
|
|
29
|
+
updated_at TEXT DEFAULT (datetime('now'))
|
|
30
|
+
);
|
|
31
|
+
|
|
32
|
+
CREATE TABLE IF NOT EXISTS sites (
|
|
33
|
+
id TEXT PRIMARY KEY,
|
|
34
|
+
user_id TEXT NOT NULL,
|
|
35
|
+
domain TEXT NOT NULL,
|
|
36
|
+
name TEXT NOT NULL,
|
|
37
|
+
description TEXT,
|
|
38
|
+
tier TEXT DEFAULT 'free' CHECK(tier IN ('free','starter','pro','enterprise')),
|
|
39
|
+
license_key TEXT UNIQUE NOT NULL,
|
|
40
|
+
api_key TEXT UNIQUE,
|
|
41
|
+
config TEXT DEFAULT '{}',
|
|
42
|
+
active INTEGER DEFAULT 1,
|
|
43
|
+
created_at TEXT DEFAULT (datetime('now')),
|
|
44
|
+
updated_at TEXT DEFAULT (datetime('now')),
|
|
45
|
+
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
|
46
|
+
);
|
|
47
|
+
|
|
48
|
+
CREATE TABLE IF NOT EXISTS analytics (
|
|
49
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
50
|
+
site_id TEXT NOT NULL,
|
|
51
|
+
action_name TEXT NOT NULL,
|
|
52
|
+
agent_id TEXT,
|
|
53
|
+
trigger_type TEXT,
|
|
54
|
+
success INTEGER,
|
|
55
|
+
metadata TEXT DEFAULT '{}',
|
|
56
|
+
created_at TEXT DEFAULT (datetime('now')),
|
|
57
|
+
FOREIGN KEY (site_id) REFERENCES sites(id) ON DELETE CASCADE
|
|
58
|
+
);
|
|
59
|
+
|
|
60
|
+
CREATE TABLE IF NOT EXISTS subscriptions (
|
|
61
|
+
id TEXT PRIMARY KEY,
|
|
62
|
+
user_id TEXT NOT NULL,
|
|
63
|
+
site_id TEXT NOT NULL,
|
|
64
|
+
tier TEXT NOT NULL CHECK(tier IN ('free','starter','pro','enterprise')),
|
|
65
|
+
status TEXT DEFAULT 'active' CHECK(status IN ('active','cancelled','expired','trial')),
|
|
66
|
+
started_at TEXT DEFAULT (datetime('now')),
|
|
67
|
+
expires_at TEXT,
|
|
68
|
+
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
|
|
69
|
+
FOREIGN KEY (site_id) REFERENCES sites(id) ON DELETE CASCADE
|
|
70
|
+
);
|
|
71
|
+
|
|
72
|
+
CREATE INDEX IF NOT EXISTS idx_sites_domain ON sites(domain);
|
|
73
|
+
CREATE INDEX IF NOT EXISTS idx_sites_license ON sites(license_key);
|
|
74
|
+
CREATE INDEX IF NOT EXISTS idx_analytics_site ON analytics(site_id);
|
|
75
|
+
CREATE INDEX IF NOT EXISTS idx_analytics_created ON analytics(created_at);
|
|
76
|
+
|
|
77
|
+
CREATE TABLE IF NOT EXISTS admins (
|
|
78
|
+
id TEXT PRIMARY KEY,
|
|
79
|
+
email TEXT UNIQUE NOT NULL,
|
|
80
|
+
password TEXT NOT NULL,
|
|
81
|
+
name TEXT NOT NULL,
|
|
82
|
+
role TEXT DEFAULT 'admin' CHECK(role IN ('admin','superadmin')),
|
|
83
|
+
created_at TEXT DEFAULT (datetime('now'))
|
|
84
|
+
);
|
|
85
|
+
|
|
86
|
+
CREATE TABLE IF NOT EXISTS free_grants (
|
|
87
|
+
id TEXT PRIMARY KEY,
|
|
88
|
+
user_id TEXT NOT NULL,
|
|
89
|
+
site_id TEXT,
|
|
90
|
+
granted_tier TEXT NOT NULL CHECK(granted_tier IN ('starter','pro','enterprise')),
|
|
91
|
+
reason TEXT,
|
|
92
|
+
granted_by TEXT NOT NULL,
|
|
93
|
+
granted_at TEXT DEFAULT (datetime('now')),
|
|
94
|
+
expires_at TEXT,
|
|
95
|
+
active INTEGER DEFAULT 1,
|
|
96
|
+
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
|
|
97
|
+
FOREIGN KEY (granted_by) REFERENCES admins(id)
|
|
98
|
+
);
|
|
99
|
+
|
|
100
|
+
CREATE TABLE IF NOT EXISTS stripe_customers (
|
|
101
|
+
id TEXT PRIMARY KEY,
|
|
102
|
+
user_id TEXT UNIQUE NOT NULL,
|
|
103
|
+
stripe_customer_id TEXT UNIQUE,
|
|
104
|
+
created_at TEXT DEFAULT (datetime('now')),
|
|
105
|
+
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
|
106
|
+
);
|
|
107
|
+
|
|
108
|
+
CREATE TABLE IF NOT EXISTS stripe_subscriptions (
|
|
109
|
+
id TEXT PRIMARY KEY,
|
|
110
|
+
user_id TEXT NOT NULL,
|
|
111
|
+
site_id TEXT NOT NULL,
|
|
112
|
+
stripe_subscription_id TEXT UNIQUE,
|
|
113
|
+
stripe_price_id TEXT,
|
|
114
|
+
tier TEXT NOT NULL CHECK(tier IN ('starter','pro','enterprise')),
|
|
115
|
+
status TEXT DEFAULT 'active' CHECK(status IN ('active','cancelled','past_due','trialing','incomplete')),
|
|
116
|
+
current_period_start TEXT,
|
|
117
|
+
current_period_end TEXT,
|
|
118
|
+
created_at TEXT DEFAULT (datetime('now')),
|
|
119
|
+
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
|
|
120
|
+
FOREIGN KEY (site_id) REFERENCES sites(id) ON DELETE CASCADE
|
|
121
|
+
);
|
|
122
|
+
|
|
123
|
+
CREATE TABLE IF NOT EXISTS payments (
|
|
124
|
+
id TEXT PRIMARY KEY,
|
|
125
|
+
user_id TEXT NOT NULL,
|
|
126
|
+
stripe_payment_id TEXT UNIQUE,
|
|
127
|
+
amount INTEGER NOT NULL,
|
|
128
|
+
currency TEXT DEFAULT 'usd',
|
|
129
|
+
status TEXT DEFAULT 'succeeded',
|
|
130
|
+
description TEXT,
|
|
131
|
+
created_at TEXT DEFAULT (datetime('now')),
|
|
132
|
+
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
|
133
|
+
);
|
|
134
|
+
|
|
135
|
+
CREATE TABLE IF NOT EXISTS notifications_log (
|
|
136
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
137
|
+
user_id TEXT,
|
|
138
|
+
email_to TEXT NOT NULL,
|
|
139
|
+
template TEXT NOT NULL,
|
|
140
|
+
subject TEXT NOT NULL,
|
|
141
|
+
status TEXT DEFAULT 'sent' CHECK(status IN ('sent','failed','queued')),
|
|
142
|
+
error_message TEXT,
|
|
143
|
+
created_at TEXT DEFAULT (datetime('now'))
|
|
144
|
+
);
|
|
145
|
+
|
|
146
|
+
CREATE TABLE IF NOT EXISTS smtp_settings (
|
|
147
|
+
id INTEGER PRIMARY KEY CHECK(id = 1),
|
|
148
|
+
host TEXT,
|
|
149
|
+
port INTEGER DEFAULT 587,
|
|
150
|
+
secure INTEGER DEFAULT 0,
|
|
151
|
+
username TEXT,
|
|
152
|
+
password TEXT,
|
|
153
|
+
from_name TEXT DEFAULT 'Web Agent Bridge',
|
|
154
|
+
from_email TEXT,
|
|
155
|
+
enabled INTEGER DEFAULT 0,
|
|
156
|
+
updated_at TEXT DEFAULT (datetime('now'))
|
|
157
|
+
);
|
|
158
|
+
|
|
159
|
+
INSERT OR IGNORE INTO smtp_settings (id) VALUES (1);
|
|
160
|
+
|
|
161
|
+
CREATE TABLE IF NOT EXISTS platform_settings (
|
|
162
|
+
key TEXT PRIMARY KEY,
|
|
163
|
+
value TEXT,
|
|
164
|
+
updated_at TEXT DEFAULT (datetime('now'))
|
|
165
|
+
);
|
|
166
|
+
|
|
167
|
+
CREATE INDEX IF NOT EXISTS idx_free_grants_user ON free_grants(user_id);
|
|
168
|
+
CREATE INDEX IF NOT EXISTS idx_stripe_subs_user ON stripe_subscriptions(user_id);
|
|
169
|
+
CREATE INDEX IF NOT EXISTS idx_payments_user ON payments(user_id);
|
|
170
|
+
CREATE INDEX IF NOT EXISTS idx_notifications_user ON notifications_log(user_id);
|
|
171
|
+
`);
|
|
172
|
+
|
|
173
|
+
function generateLicenseKey() {
|
|
174
|
+
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
|
|
175
|
+
const segments = [];
|
|
176
|
+
for (let s = 0; s < 4; s++) {
|
|
177
|
+
let seg = '';
|
|
178
|
+
const bytes = crypto.randomBytes(5);
|
|
179
|
+
for (let i = 0; i < 5; i++) seg += chars[bytes[i] % chars.length];
|
|
180
|
+
segments.push(seg);
|
|
181
|
+
}
|
|
182
|
+
return `WAB-${segments.join('-')}`;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function generateApiKey() {
|
|
186
|
+
return `wab_${uuidv4().replace(/-/g, '')}`;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// ─── User Operations ──────────────────────────────────────────────────
|
|
190
|
+
const createUser = db.prepare(`
|
|
191
|
+
INSERT INTO users (id, email, password, name, company) VALUES (?, ?, ?, ?, ?)
|
|
192
|
+
`);
|
|
193
|
+
|
|
194
|
+
const findUserByEmail = db.prepare(`SELECT * FROM users WHERE email = ?`);
|
|
195
|
+
const findUserById = db.prepare(`SELECT id, email, name, company, created_at FROM users WHERE id = ?`);
|
|
196
|
+
|
|
197
|
+
function registerUser({ email, password, name, company }) {
|
|
198
|
+
const id = uuidv4();
|
|
199
|
+
const hashed = bcrypt.hashSync(password, 12);
|
|
200
|
+
createUser.run(id, email, hashed, name, company || null);
|
|
201
|
+
return { id, email, name, company };
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
function loginUser({ email, password }) {
|
|
205
|
+
const user = findUserByEmail.get(email);
|
|
206
|
+
if (!user) return null;
|
|
207
|
+
if (!bcrypt.compareSync(password, user.password)) return null;
|
|
208
|
+
return { id: user.id, email: user.email, name: user.name, company: user.company };
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// ─── Site Operations ──────────────────────────────────────────────────
|
|
212
|
+
const createSite = db.prepare(`
|
|
213
|
+
INSERT INTO sites (id, user_id, domain, name, description, tier, license_key, api_key, config)
|
|
214
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
215
|
+
`);
|
|
216
|
+
|
|
217
|
+
const findSitesByUser = db.prepare(`SELECT * FROM sites WHERE user_id = ? ORDER BY created_at DESC`);
|
|
218
|
+
const findSiteById = db.prepare(`SELECT * FROM sites WHERE id = ?`);
|
|
219
|
+
const findSiteByLicense = db.prepare(`SELECT * FROM sites WHERE license_key = ? AND active = 1`);
|
|
220
|
+
const findSiteByDomainAndLicense = db.prepare(`SELECT * FROM sites WHERE domain = ? AND license_key = ? AND active = 1`);
|
|
221
|
+
const updateSiteConfig = db.prepare(`UPDATE sites SET config = ?, updated_at = datetime('now') WHERE id = ? AND user_id = ?`);
|
|
222
|
+
const updateSiteTier = db.prepare(`UPDATE sites SET tier = ?, updated_at = datetime('now') WHERE id = ? AND user_id = ?`);
|
|
223
|
+
const deleteSite = db.prepare(`UPDATE sites SET active = 0, updated_at = datetime('now') WHERE id = ? AND user_id = ?`);
|
|
224
|
+
|
|
225
|
+
function addSite({ userId, domain, name, description, tier }) {
|
|
226
|
+
const id = uuidv4();
|
|
227
|
+
const licenseKey = generateLicenseKey();
|
|
228
|
+
const apiKey = generateApiKey();
|
|
229
|
+
const config = JSON.stringify({
|
|
230
|
+
agentPermissions: { readContent: true, click: true, fillForms: false, scroll: true, navigate: false, apiAccess: false, automatedLogin: false, extractData: false },
|
|
231
|
+
features: { advancedAnalytics: false, realTimeUpdates: false },
|
|
232
|
+
restrictions: { allowedSelectors: [], blockedSelectors: ['.private', '[data-private]'], rateLimit: { maxCallsPerMinute: 60 } },
|
|
233
|
+
logging: { enabled: false, level: 'basic' }
|
|
234
|
+
});
|
|
235
|
+
createSite.run(id, userId, domain, name, description || '', tier || 'free', licenseKey, apiKey, config);
|
|
236
|
+
return { id, domain, name, licenseKey, apiKey, tier: tier || 'free' };
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// ─── Analytics ────────────────────────────────────────────────────────
|
|
240
|
+
const insertAnalytic = db.prepare(`
|
|
241
|
+
INSERT INTO analytics (site_id, action_name, agent_id, trigger_type, success, metadata)
|
|
242
|
+
VALUES (?, ?, ?, ?, ?, ?)
|
|
243
|
+
`);
|
|
244
|
+
|
|
245
|
+
const getAnalyticsBySite = db.prepare(`
|
|
246
|
+
SELECT action_name, trigger_type, COUNT(*) as count, SUM(success) as successes
|
|
247
|
+
FROM analytics WHERE site_id = ? AND created_at >= ? GROUP BY action_name, trigger_type
|
|
248
|
+
ORDER BY count DESC
|
|
249
|
+
`);
|
|
250
|
+
|
|
251
|
+
const getAnalyticsTimeline = db.prepare(`
|
|
252
|
+
SELECT date(created_at) as day, COUNT(*) as count
|
|
253
|
+
FROM analytics WHERE site_id = ? AND created_at >= ?
|
|
254
|
+
GROUP BY day ORDER BY day
|
|
255
|
+
`);
|
|
256
|
+
|
|
257
|
+
function recordAnalytic({ siteId, actionName, agentId, triggerType, success, metadata }) {
|
|
258
|
+
insertAnalytic.run(siteId, actionName, agentId || null, triggerType || null, success ? 1 : 0, JSON.stringify(metadata || {}));
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// ─── License Verification ─────────────────────────────────────────────
|
|
262
|
+
function verifyLicense(domain, licenseKey) {
|
|
263
|
+
const site = findSiteByDomainAndLicense.get(domain, licenseKey);
|
|
264
|
+
if (!site) {
|
|
265
|
+
const siteByKey = findSiteByLicense.get(licenseKey);
|
|
266
|
+
if (siteByKey) return { valid: false, error: 'Domain mismatch', tier: 'free' };
|
|
267
|
+
return { valid: false, error: 'Invalid license key', tier: 'free' };
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
// Check for free grant override
|
|
271
|
+
const grant = db.prepare(`SELECT * FROM free_grants WHERE user_id = ? AND (site_id = ? OR site_id IS NULL) AND active = 1 AND (expires_at IS NULL OR expires_at > datetime('now')) ORDER BY granted_at DESC LIMIT 1`).get(site.user_id, site.id);
|
|
272
|
+
const effectiveTier = grant ? grant.granted_tier : site.tier;
|
|
273
|
+
|
|
274
|
+
const tierPermissions = {
|
|
275
|
+
free: { apiAccess: false, automatedLogin: false, extractData: false, advancedAnalytics: false },
|
|
276
|
+
starter: { apiAccess: false, automatedLogin: true, extractData: false, advancedAnalytics: true },
|
|
277
|
+
pro: { apiAccess: true, automatedLogin: true, extractData: true, advancedAnalytics: true },
|
|
278
|
+
enterprise: { apiAccess: true, automatedLogin: true, extractData: true, advancedAnalytics: true }
|
|
279
|
+
};
|
|
280
|
+
|
|
281
|
+
return {
|
|
282
|
+
valid: true,
|
|
283
|
+
tier: effectiveTier,
|
|
284
|
+
domain: site.domain,
|
|
285
|
+
allowedPermissions: tierPermissions[effectiveTier] || tierPermissions.free
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
// ─── Admin Operations ─────────────────────────────────────────────────
|
|
290
|
+
function createAdmin({ email, password, name, role }) {
|
|
291
|
+
const id = uuidv4();
|
|
292
|
+
const hashed = bcrypt.hashSync(password, 12);
|
|
293
|
+
db.prepare(`INSERT INTO admins (id, email, password, name, role) VALUES (?, ?, ?, ?, ?)`).run(id, email, hashed, name, role || 'admin');
|
|
294
|
+
return { id, email, name, role: role || 'admin' };
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
function loginAdmin({ email, password }) {
|
|
298
|
+
const admin = db.prepare(`SELECT * FROM admins WHERE email = ?`).get(email);
|
|
299
|
+
if (!admin) return null;
|
|
300
|
+
if (!bcrypt.compareSync(password, admin.password)) return null;
|
|
301
|
+
return { id: admin.id, email: admin.email, name: admin.name, role: admin.role };
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
function findAdminById(id) {
|
|
305
|
+
return db.prepare(`SELECT id, email, name, role, created_at FROM admins WHERE id = ?`).get(id);
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* First-run admin creation from env only (no hardcoded password).
|
|
310
|
+
* Alternatively use: node scripts/create-admin.js <email> <password>
|
|
311
|
+
*/
|
|
312
|
+
function maybeBootstrapAdmin() {
|
|
313
|
+
if (isTest) return;
|
|
314
|
+
const count = db.prepare(`SELECT COUNT(*) as c FROM admins`).get().c;
|
|
315
|
+
if (count > 0) return;
|
|
316
|
+
const email = process.env.BOOTSTRAP_ADMIN_EMAIL;
|
|
317
|
+
const password = process.env.BOOTSTRAP_ADMIN_PASSWORD;
|
|
318
|
+
if (!email || !password) {
|
|
319
|
+
console.warn('[WAB] No admin accounts. Set BOOTSTRAP_ADMIN_EMAIL and BOOTSTRAP_ADMIN_PASSWORD for first boot, or run: node scripts/create-admin.js <email> <password>');
|
|
320
|
+
return;
|
|
321
|
+
}
|
|
322
|
+
createAdmin({ email, password, name: 'Bootstrap Admin', role: 'superadmin' });
|
|
323
|
+
console.log('[WAB] Bootstrap admin created from BOOTSTRAP_ADMIN_* environment variables.');
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
// ─── Admin Queries ────────────────────────────────────────────────────
|
|
327
|
+
function getAllUsers() {
|
|
328
|
+
return db.prepare(`SELECT id, email, name, company, created_at FROM users ORDER BY created_at DESC`).all();
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
function getAllSites() {
|
|
332
|
+
return db.prepare(`SELECT s.*, u.email as user_email, u.name as user_name FROM sites s LEFT JOIN users u ON s.user_id = u.id ORDER BY s.created_at DESC`).all();
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
function getAdminStats() {
|
|
336
|
+
const totalUsers = db.prepare(`SELECT COUNT(*) as c FROM users`).get().c;
|
|
337
|
+
const totalSites = db.prepare(`SELECT COUNT(*) as c FROM sites WHERE active = 1`).get().c;
|
|
338
|
+
const totalAnalytics = db.prepare(`SELECT COUNT(*) as c FROM analytics`).get().c;
|
|
339
|
+
const todayAnalytics = db.prepare(`SELECT COUNT(*) as c FROM analytics WHERE created_at >= date('now')`).get().c;
|
|
340
|
+
const tierBreakdown = db.prepare(`SELECT tier, COUNT(*) as count FROM sites WHERE active = 1 GROUP BY tier`).all();
|
|
341
|
+
const recentUsers = db.prepare(`SELECT id, email, name, company, created_at FROM users ORDER BY created_at DESC LIMIT 10`).all();
|
|
342
|
+
const totalRevenue = db.prepare(`SELECT COALESCE(SUM(amount), 0) as total FROM payments WHERE status = 'succeeded'`).get().total;
|
|
343
|
+
const activeGrants = db.prepare(`SELECT COUNT(*) as c FROM free_grants WHERE active = 1 AND (expires_at IS NULL OR expires_at > datetime('now'))`).get().c;
|
|
344
|
+
const monthlySignups = db.prepare(`SELECT COUNT(*) as c FROM users WHERE created_at >= date('now', '-30 days')`).get().c;
|
|
345
|
+
return { totalUsers, totalSites, totalAnalytics, todayAnalytics, tierBreakdown, recentUsers, totalRevenue, activeGrants, monthlySignups };
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
function getPlatformAnalytics(days) {
|
|
349
|
+
const since = new Date(Date.now() - days * 86400000).toISOString();
|
|
350
|
+
const timeline = db.prepare(`SELECT date(created_at) as day, COUNT(*) as count FROM analytics WHERE created_at >= ? GROUP BY day ORDER BY day`).all(since);
|
|
351
|
+
const topActions = db.prepare(`SELECT action_name, COUNT(*) as count FROM analytics WHERE created_at >= ? GROUP BY action_name ORDER BY count DESC LIMIT 20`).all(since);
|
|
352
|
+
const signups = db.prepare(`SELECT date(created_at) as day, COUNT(*) as count FROM users WHERE created_at >= ? GROUP BY day ORDER BY day`).all(since);
|
|
353
|
+
return { timeline, topActions, signups };
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
// ─── Free Grant Operations ────────────────────────────────────────────
|
|
357
|
+
function grantFreeTier({ userId, siteId, tier, reason, grantedBy, expiresAt }) {
|
|
358
|
+
const id = uuidv4();
|
|
359
|
+
db.prepare(`INSERT INTO free_grants (id, user_id, site_id, granted_tier, reason, granted_by, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?)`).run(id, userId, siteId || null, tier, reason || null, grantedBy, expiresAt || null);
|
|
360
|
+
if (siteId) {
|
|
361
|
+
db.prepare(`UPDATE sites SET tier = ?, updated_at = datetime('now') WHERE id = ?`).run(tier, siteId);
|
|
362
|
+
} else {
|
|
363
|
+
db.prepare(`UPDATE sites SET tier = ?, updated_at = datetime('now') WHERE user_id = ? AND active = 1`).run(tier, userId);
|
|
364
|
+
}
|
|
365
|
+
return { id, userId, siteId, tier, reason };
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
function revokeGrant(grantId) {
|
|
369
|
+
const grant = db.prepare(`SELECT * FROM free_grants WHERE id = ?`).get(grantId);
|
|
370
|
+
if (!grant) return false;
|
|
371
|
+
db.prepare(`UPDATE free_grants SET active = 0 WHERE id = ?`).run(grantId);
|
|
372
|
+
if (grant.site_id) {
|
|
373
|
+
db.prepare(`UPDATE sites SET tier = 'free', updated_at = datetime('now') WHERE id = ?`).run(grant.site_id);
|
|
374
|
+
} else {
|
|
375
|
+
db.prepare(`UPDATE sites SET tier = 'free', updated_at = datetime('now') WHERE user_id = ? AND active = 1`).run(grant.user_id);
|
|
376
|
+
}
|
|
377
|
+
return true;
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
function getActiveGrants() {
|
|
381
|
+
return db.prepare(`SELECT g.*, u.email as user_email, u.name as user_name, a.name as admin_name FROM free_grants g LEFT JOIN users u ON g.user_id = u.id LEFT JOIN admins a ON g.granted_by = a.id WHERE g.active = 1 ORDER BY g.granted_at DESC`).all();
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
// ─── Stripe DB Operations ─────────────────────────────────────────────
|
|
385
|
+
function saveStripeCustomer(userId, stripeCustomerId) {
|
|
386
|
+
const id = uuidv4();
|
|
387
|
+
db.prepare(`INSERT OR REPLACE INTO stripe_customers (id, user_id, stripe_customer_id) VALUES (?, ?, ?)`).run(id, userId, stripeCustomerId);
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
function getStripeCustomer(userId) {
|
|
391
|
+
return db.prepare(`SELECT * FROM stripe_customers WHERE user_id = ?`).get(userId);
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
function saveStripeSubscription({ userId, siteId, stripeSubId, stripePriceId, tier, status, periodStart, periodEnd }) {
|
|
395
|
+
const id = uuidv4();
|
|
396
|
+
db.prepare(`INSERT INTO stripe_subscriptions (id, user_id, site_id, stripe_subscription_id, stripe_price_id, tier, status, current_period_start, current_period_end) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(id, userId, siteId, stripeSubId, stripePriceId, tier, status || 'active', periodStart, periodEnd);
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
function updateStripeSubscription(stripeSubId, { status, periodStart, periodEnd, tier }) {
|
|
400
|
+
const updates = [];
|
|
401
|
+
const params = [];
|
|
402
|
+
if (status) { updates.push('status = ?'); params.push(status); }
|
|
403
|
+
if (periodStart) { updates.push('current_period_start = ?'); params.push(periodStart); }
|
|
404
|
+
if (periodEnd) { updates.push('current_period_end = ?'); params.push(periodEnd); }
|
|
405
|
+
if (tier) { updates.push('tier = ?'); params.push(tier); }
|
|
406
|
+
if (updates.length === 0) return;
|
|
407
|
+
params.push(stripeSubId);
|
|
408
|
+
db.prepare(`UPDATE stripe_subscriptions SET ${updates.join(', ')} WHERE stripe_subscription_id = ?`).run(...params);
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
function getStripeSubscriptionBySubId(stripeSubId) {
|
|
412
|
+
return db.prepare(`SELECT * FROM stripe_subscriptions WHERE stripe_subscription_id = ?`).get(stripeSubId);
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
function savePayment({ userId, stripePaymentId, amount, currency, status, description }) {
|
|
416
|
+
const id = uuidv4();
|
|
417
|
+
db.prepare(`INSERT INTO payments (id, user_id, stripe_payment_id, amount, currency, status, description) VALUES (?, ?, ?, ?, ?, ?, ?)`).run(id, userId, stripePaymentId, amount, currency || 'usd', status || 'succeeded', description || null);
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
function getPayments(limit) {
|
|
421
|
+
return db.prepare(`SELECT p.*, u.email as user_email, u.name as user_name FROM payments p LEFT JOIN users u ON p.user_id = u.id ORDER BY p.created_at DESC LIMIT ?`).all(limit || 50);
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
// ─── SMTP Settings ────────────────────────────────────────────────────
|
|
425
|
+
function getSmtpSettings() {
|
|
426
|
+
const row = db.prepare(`SELECT * FROM smtp_settings WHERE id = 1`).get();
|
|
427
|
+
if (!row) return null;
|
|
428
|
+
if (row.password) {
|
|
429
|
+
const dec = decryptOptional(row.password);
|
|
430
|
+
return { ...row, password: dec != null ? dec : row.password };
|
|
431
|
+
}
|
|
432
|
+
return row;
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
function updateSmtpSettings({ host, port, secure, username, password, fromName, fromEmail, enabled }) {
|
|
436
|
+
const current = db.prepare(`SELECT password FROM smtp_settings WHERE id = 1`).get();
|
|
437
|
+
let nextPassword = current && current.password;
|
|
438
|
+
if (password !== undefined) {
|
|
439
|
+
nextPassword = encryptOptional(password);
|
|
440
|
+
}
|
|
441
|
+
db.prepare(`UPDATE smtp_settings SET host = ?, port = ?, secure = ?, username = ?, password = ?, from_name = ?, from_email = ?, enabled = ?, updated_at = datetime('now') WHERE id = 1`).run(host, port || 587, secure ? 1 : 0, username, nextPassword, fromName || 'Web Agent Bridge', fromEmail, enabled ? 1 : 0);
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
function logNotification({ userId, emailTo, template, subject, status, errorMessage }) {
|
|
445
|
+
db.prepare(`INSERT INTO notifications_log (user_id, email_to, template, subject, status, error_message) VALUES (?, ?, ?, ?, ?, ?)`).run(userId || null, emailTo, template, subject, status || 'sent', errorMessage || null);
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
function getNotificationLogs(limit) {
|
|
449
|
+
return db.prepare(`SELECT * FROM notifications_log ORDER BY created_at DESC LIMIT ?`).all(limit || 100);
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
// ─── Admin User Management ───────────────────────────────────────────
|
|
453
|
+
function adminUpdateUserTier(userId, siteId, tier) {
|
|
454
|
+
if (siteId) {
|
|
455
|
+
db.prepare(`UPDATE sites SET tier = ?, updated_at = datetime('now') WHERE id = ? AND user_id = ?`).run(tier, siteId, userId);
|
|
456
|
+
} else {
|
|
457
|
+
db.prepare(`UPDATE sites SET tier = ?, updated_at = datetime('now') WHERE user_id = ? AND active = 1`).run(tier, userId);
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/**
|
|
462
|
+
* Admin: update any site by id (tier and/or active).
|
|
463
|
+
*
|
|
464
|
+
* @param {string} siteId Site UUID.
|
|
465
|
+
* @param {{ tier?: string, active?: boolean }} updates Partial updates.
|
|
466
|
+
* @returns {boolean}
|
|
467
|
+
*/
|
|
468
|
+
function adminUpdateSite(siteId, updates) {
|
|
469
|
+
const site = findSiteById.get(siteId);
|
|
470
|
+
if (!site) return false;
|
|
471
|
+
let tier = site.tier;
|
|
472
|
+
let active = site.active;
|
|
473
|
+
if (updates.tier !== undefined) {
|
|
474
|
+
if (!['free', 'starter', 'pro', 'enterprise'].includes(updates.tier)) return false;
|
|
475
|
+
tier = updates.tier;
|
|
476
|
+
}
|
|
477
|
+
if (updates.active !== undefined) {
|
|
478
|
+
active = updates.active ? 1 : 0;
|
|
479
|
+
}
|
|
480
|
+
db.prepare(`UPDATE sites SET tier = ?, active = ?, updated_at = datetime('now') WHERE id = ?`).run(tier, active, siteId);
|
|
481
|
+
return true;
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
function adminDeleteUser(userId) {
|
|
485
|
+
db.prepare(`UPDATE sites SET active = 0 WHERE user_id = ?`).run(userId);
|
|
486
|
+
db.prepare(`DELETE FROM users WHERE id = ?`).run(userId);
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
function getUserFullDetails(userId) {
|
|
490
|
+
const user = db.prepare(`SELECT id, email, name, company, created_at FROM users WHERE id = ?`).get(userId);
|
|
491
|
+
if (!user) return null;
|
|
492
|
+
const sites = db.prepare(`SELECT * FROM sites WHERE user_id = ? ORDER BY created_at DESC`).all(userId);
|
|
493
|
+
const grants = db.prepare(`SELECT * FROM free_grants WHERE user_id = ? AND active = 1`).all(userId);
|
|
494
|
+
const payments = db.prepare(`SELECT * FROM payments WHERE user_id = ? ORDER BY created_at DESC`).all(userId);
|
|
495
|
+
const stripeCustomer = db.prepare(`SELECT * FROM stripe_customers WHERE user_id = ?`).get(userId);
|
|
496
|
+
return { ...user, sites, grants, payments, stripeCustomer };
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
// ─── Platform Settings ───────────────────────────────────────────────
|
|
500
|
+
function getPlatformSetting(key) {
|
|
501
|
+
const row = db.prepare(`SELECT value FROM platform_settings WHERE key = ?`).get(key);
|
|
502
|
+
return row ? row.value : null;
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
function setPlatformSetting(key, value) {
|
|
506
|
+
db.prepare(`INSERT OR REPLACE INTO platform_settings (key, value, updated_at) VALUES (?, ?, datetime('now'))`).run(key, value);
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
module.exports = {
|
|
510
|
+
db,
|
|
511
|
+
registerUser,
|
|
512
|
+
loginUser,
|
|
513
|
+
findUserById,
|
|
514
|
+
findUserByEmail,
|
|
515
|
+
addSite,
|
|
516
|
+
findSitesByUser,
|
|
517
|
+
findSiteById,
|
|
518
|
+
findSiteByLicense,
|
|
519
|
+
updateSiteConfig,
|
|
520
|
+
updateSiteTier,
|
|
521
|
+
deleteSite,
|
|
522
|
+
recordAnalytic,
|
|
523
|
+
getAnalyticsBySite,
|
|
524
|
+
getAnalyticsTimeline,
|
|
525
|
+
verifyLicense,
|
|
526
|
+
generateLicenseKey,
|
|
527
|
+
generateApiKey,
|
|
528
|
+
// Admin
|
|
529
|
+
createAdmin,
|
|
530
|
+
loginAdmin,
|
|
531
|
+
findAdminById,
|
|
532
|
+
maybeBootstrapAdmin,
|
|
533
|
+
getAllUsers,
|
|
534
|
+
getAllSites,
|
|
535
|
+
getAdminStats,
|
|
536
|
+
getPlatformAnalytics,
|
|
537
|
+
adminUpdateUserTier,
|
|
538
|
+
adminUpdateSite,
|
|
539
|
+
adminDeleteUser,
|
|
540
|
+
getUserFullDetails,
|
|
541
|
+
// Free Grants
|
|
542
|
+
grantFreeTier,
|
|
543
|
+
revokeGrant,
|
|
544
|
+
getActiveGrants,
|
|
545
|
+
// Stripe
|
|
546
|
+
saveStripeCustomer,
|
|
547
|
+
getStripeCustomer,
|
|
548
|
+
saveStripeSubscription,
|
|
549
|
+
updateStripeSubscription,
|
|
550
|
+
getStripeSubscriptionBySubId,
|
|
551
|
+
savePayment,
|
|
552
|
+
getPayments,
|
|
553
|
+
// SMTP
|
|
554
|
+
getSmtpSettings,
|
|
555
|
+
updateSmtpSettings,
|
|
556
|
+
logNotification,
|
|
557
|
+
getNotificationLogs,
|
|
558
|
+
// Platform
|
|
559
|
+
getPlatformSetting,
|
|
560
|
+
setPlatformSetting
|
|
561
|
+
};
|